text
stringlengths 8
6.88M
|
|---|
#include "Logging.h"
#include <iostream>
static void Info_Fallback(const char* text)
{
std::cout << "INFO: " << text << std::endl;
}
static void Warning_Fallback(const char* text)
{
std::cout << "WARNING: " << text << std::endl;
}
static void Error_Fallback(const char* text)
{
std::cout << "ERROR: " << text << std::endl;
}
static WhatIBuild::LoggingCallbacks g_LogCallbacks =
{
&Info_Fallback,
&Warning_Fallback,
&Error_Fallback
};
void WhatIBuild::LogManager::Inititalize(const LoggingCallbacks& callbacks)
{
g_LogCallbacks = callbacks;
}
void WhatIBuild::LogManager::Info(const char* text)
{
(*g_LogCallbacks.logInfo)(text);
}
void WhatIBuild::LogManager::Warning(const char* text)
{
(*g_LogCallbacks.logWarning)(text);
}
void WhatIBuild::LogManager::Error(const char* text)
{
(*g_LogCallbacks.logError)(text);
}
|
#ifndef __INC_GRAPH_HPP
#define __INC_GRAPH_HPP
#pragma once
#include <list>
#include <vector>
#include <stack>
#include <iostream>
#include <utility>
#include <limits>
#include <functional>
#pragma once
#ifndef _BEGIN_ZHF_LIB
#define _BEGIN_ZHF_LIB namespace zhf_lib{
#endif // !_BEGIN_ZHF_LIB
#ifndef _END_ZHF_LIB
#define _END_ZHF_LIB }
#endif // !_END_ZHF_LIB
#ifndef _ZHF
#define _ZHF zhf_lib::
#endif // !_ZHF
_BEGIN_ZHF_LIB
using std::list;
using std::vector;
using std::stack;
using std::pair;
/*The basic class for a vertex of a graph*/
template <class _Data>
class _NodeBase
{
public:
inline explicit _NodeBase(const unsigned id)
:id(id)
{
data = nullptr;
}
inline explicit _NodeBase(const _Data &data, unsigned id)
:id(id)
{
this->data = new _Data(data);
}
inline explicit _NodeBase(const _NodeBase &n)
{
data = new _Data(*n.data);
id = n.id;
}
virtual ~_NodeBase()
{
std::cout << "delete node " << id << std::endl;
delete data;
}
virtual _NodeBase& operator=(const _NodeBase& rhs)
{
if (&rhs != this)
{
delete data;
data = new _Data(*rhs.data);
id = rhs.id;
}
return *this;
}
_Data *data;
inline unsigned get_id()
{
return id;
}
protected:
unsigned id;
};
/*The basic class for represent a graph
*type name 'Data' and 'Node' can be set by given that 'Node' is
*inherited from class '_NodeBase'
*/
template <class _Data,
class _Node = _NodeBase<_Data>>
class _Graph_Base
{
public:
inline _Graph_Base(const size_t size, const vector<_Data> &nodes_data) :s(size)
{
nodes.resize(size);
initial_nodes(nodes_data);
}
~_Graph_Base()
{
for (unsigned i = 0; i < nodes.size(); i++)
{
delete nodes[i];
}
}
inline virtual _Node *get_node(unsigned index)
{
return nodes.at(index);
}
inline virtual size_t size()
{
return s;
}
private:
void initial_nodes(const vector<_Data> &nodes_data)
{
for (unsigned i = 0; i < nodes.size(); i++)
{
nodes[i] = new _Node(_Data(nodes_data[i]), i);
}
}
protected:
vector<_Node*> nodes;
size_t s;
};
/*Weight can only be C++ numeric data like int, unsigned, ...*/
template <class _Weight>
class WeightedEdge
{
public:
WeightedEdge()
{
weight = _Weight(0);
}
WeightedEdge(const _Weight &w)
{
weight = w;
}
_Weight weight;
const static WeightedEdge MaxWeight;
};
template <class _Weight>
bool operator<(const _Weight &lhs, const _Weight &rhs)
{
return lhs.weight > rhs.weight;
}
template <class _Weight>
bool operator>(const _Weight &lhs, const _Weight &rhs)
{
return lhs.weight > rhs.weight;
}
template <class _Weight>
const WeightedEdge<_Weight> WeightedEdge<_Weight>::MaxWeight(std::numeric_limits<_Weight>::max());
/*class 'GraphMatrix' represent a graph in a matrix*/
template <class _Data,
class _Node = _NodeBase<_Data>>
class GraphMatrix
: public _Graph_Base<_Data, _Node>
{
public:
GraphMatrix(const size_t size, const vector<_Data> &nodes_data, const vector<vector<bool>> &adjMatrix)
: _Graph_Base<_Data, _Node>(size, nodes_data)
{
adj_matrix.resize(size);
for (auto iter = adj_matrix.begin(); iter != adj_matrix.end(); iter++)
{
iter->resize(size, false);
}
initial_adj_matrix(adjMatrix);
}
private:
void initial_adj_matrix(const vector<vector<bool>> &adjMatrix)
{
for (unsigned i = 0; i < adj_matrix.size(); i++)
{
for (unsigned j = 0; j < adj_matrix[i].size(); j++)
{
adj_matrix[i][j] = adjMatrix[i][j];
}
}
}
vector<vector<bool>> adj_matrix;
};
/*class 'GraphList' represent a graph in the form of adj-list*/
template <class _Data,
class _Node = _NodeBase<_Data>>
class GraphList
:public _Graph_Base<_Data, _Node>
{
public:
GraphList(const size_t size, const vector<_Data> &nodes_data)
:_Graph_Base<_Data, _Node>(size, nodes_data)
{
for (auto iter = this->nodes.begin(); iter != this->nodes.end(); iter++)
{
adj_list[*iter] = list<_NodeBase<_Data>*>();
}
}
GraphList(const size_t size, const vector<_Data> &nodes_data, const vector<vector<bool>> &adj_matrix)
:_Graph_Base<_Data, _Node>(size, nodes_data)
{
for (unsigned i = 0; i < this->nodes.size(); i++)
{
adj_list[nodes[i].id] = list<_Node*>();
for (unsigned j = 0; j < nodes.size(); j++)
{
if (adj_matrix[i][j]) // connected
{
adj_list[nodes[i].id].push_back(nodes[j]);
}
}
}
}
private:
vector<list<_Node*>> adj_list;
};
/*interface of weighted graph*/
template <class _Data,
class _Node = _NodeBase<_Data>,
class _Weight = WeightedEdge<unsigned>>
class _WeightedGraph_Base
: public _Graph_Base<_Data, _Node>
{
public:
inline _WeightedGraph_Base(const size_t size, const vector<_Data> &nodes_data)
:_Graph_Base<_Data, _Node>(size, nodes_data) { }
inline virtual _Weight get_edge_weight(_Node *, _Node *) = 0;
};
/*class 'WeightedGraphMatrix' add weighted edges of a graph, Weight can only inherited from 'WeightedEdge'*/
template <class _Data,
class _Node = _NodeBase<_Data>,
class _Weight = WeightedEdge<unsigned>>
class WeightedGraphMatrix
: public _WeightedGraph_Base<_Data, _Node, _Weight>
{
public:
WeightedGraphMatrix(const size_t size, const vector<_Data> &nodes_data,
const vector<vector<bool>> &adjMatrix, const vector<vector<_Weight>> &edgeWeight)
: _WeightedGraph_Base<_Data, _Node, _Weight>(size, nodes_data)
{
edge_weight.resize(size);
for (auto iter = edge_weight.begin(); iter != edge_weight.end(); iter++)
{
iter->resize(size, _Weight());
}
initial_edge_weight(edgeWeight);
adj_matrix.resize(size);
for (auto iter = adj_matrix.begin(); iter != adj_matrix.end(); iter++)
{
iter->resize(size, false);
}
initial_adj_matrix(adjMatrix);
}
inline virtual _Weight get_edge_weight(_Node *u, _Node *v)
{
return edge_weight[u->get_id()][v->get_id()];
}
const vector<bool> &get_adj_vertices(unsigned id)
{
return adj_matrix.at(id);
}
private:
void initial_edge_weight(const vector<vector<_Weight>> &edgeWeight)
{
for (unsigned i = 0; i < edge_weight.size(); i++)
{
for (unsigned j = 0; j < edge_weight[i].size(); j++)
{
edge_weight[i][j] = edgeWeight[i][j];
}
}
}
void initial_adj_matrix(const vector<vector<bool>> &adjMatrix)
{
for (unsigned i = 0; i < adj_matrix.size(); i++)
{
for (unsigned j = 0; j < adj_matrix[i].size(); j++)
{
adj_matrix[i][j] = adjMatrix[i][j];
}
}
}
vector<vector<_Weight>> edge_weight;
vector<vector<bool>> adj_matrix;
};
template <class _Data,
class _Node = _NodeBase<_Data>,
class _Weight = WeightedEdge<unsigned>>
class WeightedGraphList
:public _WeightedGraph_Base<_Data, _Node, _Weight>
{
public:
using _WeightedEdge = pair<_Node*, _Weight>;
WeightedGraphList(const size_t size, const vector<_Data> &nodes_data,
const vector<vector<bool>> &adj_matrix, const vector<vector<_Weight>> &edgeWeight)
:_WeightedGraph_Base<_Data, _Node, _Weight>(size, nodes_data)
{
adj_list.resize(size);
for (unsigned i = 0; i < this->nodes.size(); i++)
{
adj_list[this->nodes[i]->get_id()] = list<_WeightedEdge>();
for (unsigned j = 0; j < this->nodes.size(); j++)
{
if (adj_matrix[i][j]) // connected
{
adj_list[this->nodes[i]->get_id()].push_back(_WeightedEdge(this->nodes[j], edgeWeight[i][j]));
}
}
}
}
inline virtual _Weight get_edge_weight(_Node *u, _Node *v)
{
for (auto iter = adj_list[u->get_id()].begin(); iter != adj_list[u->get_id()].end(); iter++)
{
if (iter->first == v) // find edge (u, v)
{
return iter->second;
}
}
return _Weight::MaxWeight;
}
const list<_WeightedEdge> &get_adj_get_adj_vertices(unsigned id)
{
return adj_list.at(id);
}
private:
vector<list<_WeightedEdge>> adj_list;
};
_END_ZHF_LIB
#endif // !__INC_GRAPH_HPP
|
// Created on: 1992-09-28
// Created by: Remi GILET
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GC_MakeRotation_HeaderFile
#define _GC_MakeRotation_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Real.hxx>
class Geom_Transformation;
class gp_Lin;
class gp_Ax1;
class gp_Pnt;
class gp_Dir;
//! This class implements elementary construction algorithms for a
//! rotation in 3D space. The result is a
//! Geom_Transformation transformation.
//! A MakeRotation object provides a framework for:
//! - defining the construction of the transformation,
//! - implementing the construction algorithm, and
//! - consulting the result.
class GC_MakeRotation
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs a rotation through angle Angle about the axis defined by the line Line.
Standard_EXPORT GC_MakeRotation(const gp_Lin& Line, const Standard_Real Angle);
//! Constructs a rotation through angle Angle about the axis defined by the axis Axis.
Standard_EXPORT GC_MakeRotation(const gp_Ax1& Axis, const Standard_Real Angle);
//! Constructs a rotation through angle Angle about the axis
//! defined by the point Point and the unit vector Direc.
Standard_EXPORT GC_MakeRotation(const gp_Pnt& Point, const gp_Dir& Direc, const Standard_Real Angle);
//! Returns the constructed transformation.
Standard_EXPORT const Handle(Geom_Transformation)& Value() const;
operator const Handle(Geom_Transformation)& () const { return Value(); }
protected:
private:
Handle(Geom_Transformation) TheRotation;
};
#endif // _GC_MakeRotation_HeaderFile
|
class Solution {
public:
int binaryGap(int N) {
int c = 0, p = -1, i = 0;
while(N != 0) {
if(N&1) {
if(p!=-1) c = max(c, i-p);
p = i;
}
N = N>>1;
i++;
}
return c;
}
};
|
#include <iostream>
#include "time.h"
#include "testApp.h"
#include "City.h"
#include "GeoInfo.h"
#include "Utility.h"
#include "glc.h"
//--------------------------------------------------------------
void testApp::setup()
{
ofSetFrameRate(60);
ofBackground(0, 0, 0);
//ofEnableAlphaBlending();
ofEnableSmoothing();
//glBlendFunc(GL_SRC_ALPHA, GL_ONE);
//glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
//glClearDepth(1.0f); // Depth buffer setup
//glDepthFunc(GL_LESS);
//glEnable(GL_DEPTH_TEST);
//glShadeModel(GL_SMOOTH); // Enable smooth shading
//glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really nice perspective calculations
setupQuesoGlc();
// load font with extended parameters:
// font name, size, anti-aliased, full character set
//inputFont.loadFont("verdana.ttf", 60, true, true);
//displayFont.loadFont("Osaka.ttf", 15, true, true);
input = "";
earth = new Earth(200.0f);
earth->init();
earth->initQuadric();
rotX = 0.0f;
rotY = 0.0f;
rotZ = 0.0f;
speedX = 0.0f;
speedY = 0.0f;
speedZ = 0.0f;
eyeX = 0.0f;
eyeY = 0.0f;
eyeZ = -1.0f;
showXYZ = false;
current = 0;
error = "Error!";
for (int j = 0; j < maxLongitude; ++j) {
for (int i = 0; i < maxLatitude; ++i) {
points[maxLatitude * j + i] = new MyPoint(double(i) * maxLatitude - 180.0,
double(j) * (360.0 / maxLongitude),
*earth);
}
}
string _cities[] = {"tokyo"};
for (int i = 0; i < 1; ++i) {
cities.push_back(City(_cities[i], *earth));
}
}
// Set up and initialize GLC
void testApp::setupQuesoGlc()
{
ofSetVerticalSync(true);
//ofSetFrameRate(60);
//ofEnableAlphaBlending();
//ofEnableSmoothing();
//ofBackground(0, 0, 0);
ctx = glcGenContext();
glcContext(ctx);
// glcAppendCatalog(ofToDataPath("font").c_str());
glcAppendCatalog("/System/Library/Fonts");
font = glcGenFontID();
glcNewFontFromFamily(font, "Hiragino Mincho ProN");
glcFontFace(font, "W6");
glcFont(font);
glcRenderStyle(GLC_TEXTURE);
glcEnable(GLC_GL_OBJECTS);
glcEnable(GLC_MIPMAP);
glcEnable(GLC_HINTING_QSO);
glcStringType(GLC_UTF8_QSO);
}
//--------------------------------------------------------------
void testApp::update()
{
//ofBackground(0, 0, 0);
speedX = (cities[current].lat - rotX)/50;
speedY = (cities[current].lng - rotY)/50;
rotX += speedX;
rotY += speedY;
rotZ += speedZ;
//if (rotX == cities[cities.size()-1].lat) speedX = 0;
//if (rotY == cities[cities.size()-1].lng) speedY = 0;
if (rotZ >= 360.0f) rotZ = 0.0f;
}
//--------------------------------------------------------------
void testApp::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef((GLfloat)(ofGetWidth() / 2), (GLfloat)(ofGetHeight() / 2), 0.0f);
gluLookAt(eyeX*100, eyeY*100, eyeZ*100, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
//glRotatef(cities[cities.size()-1].lat, 1.0f, 0.0f, 0.0f); // Rotate On The X Axis
//glRotatef(-cities[cities.size()-1].lng, 0.0f, 1.0f, 0.0f); // Rotate On The Y Axis
glRotatef(rotX, 1.0f, 0.0f, 0.0f); // Rotate On The X Axis
glRotatef(-rotY, 0.0f, 1.0f, 0.0f); // Rotate On The Y Axis
glRotatef(180.0f, 0.0f, 1.0f, 0.0f); // Rotate On The X Axis
//glRotatef(rotX, 1.0f, 0.0f, 0.0f); // Rotate On The X Axis
//glRotatef(rotY, 0.0f, 1.0f, 0.0f); // Rotate On The Y Axis
earth->draw();
for (int j = 0; j < maxLongitude; ++j) {
for (int i = 0; i < maxLatitude; ++i) {
points[j * maxLatitude + i]->draw();
}
}
for (int i = 0; i < cities.size(); ++i) {
cities[i].draw();
}
if (showXYZ) drawXYZ();
glPopMatrix();
drawString();
displayFPS();
}
void testApp::drawString()
{
glEnable(GL_TEXTURE_2D);
glPushMatrix(); {
glTranslatef(ofGetWidth()/2, ofGetHeight()/2 + 10, 0);
//glRotatef(60, 1, 0, 0);
static float rot = 0;
glRotatef(-rot, 0, 1, 0);
if (rot > 360) rot = 0;
rot += 0.2;
ofPushStyle(); {
ofEnableAlphaBlending();
ofSetColor(255, 255, 255, 127);
glPushMatrix(); {
glTranslatef(30, -50, 0);
glScalef(32, -32, 1);
char *c;
sprintf(c, "#%02d", current+1);
glcRenderString(c);
} glPopMatrix();
glPushMatrix(); {
glTranslatef(30, 0, 0);
glScalef(32, -32, 1);
glcRenderString(cities[current].address.c_str());
} glPopMatrix();
glPushMatrix(); {
glTranslatef(30, 50, 0);
glScalef(32, -32, 1);
time_t rawtime;
time(&rawtime);
tm *ptm = gmtime(&rawtime);
time_t localtime = mktime(ptm);
localtime += cities[current].offset * 3600;
char *str = ctime(&localtime);
glcRenderString(str);
} glPopMatrix();
ofDisableAlphaBlending();
} ofPopStyle();
// draw input string
glPushMatrix();
glTranslatef(30, 100, 0);
glScalef(32, -32, 1);
//glColor3f(0.f, 1.f, 0.f);
ofPushStyle();
ofSetColor(0, 255, 0);
if (showError) {
glcRenderString(error.c_str());
} else {
glcRenderString(input.c_str());
}
ofPopStyle();
glPopMatrix();
} glPopMatrix();
}
//--------------------------------------------------------------
void testApp::keyPressed(int key)
{
int len = input.length();
switch(key) {
/* case ' ':
input += "%20";
break;
case 'x':
showXYZ = (showXYZ) ? false : true;
break;
case 'q':
eyeZ += 0.005f;
break;
case 'w':
eyeZ -= 0.005f;
break;
*/
case OF_KEY_LEFT:
if (--current < 0) current = cities.size() - 1;
break;
case OF_KEY_RIGHT:
if (++current >= cities.size()) current = 0;
break;
case OF_KEY_UP:
eyeZ -= 0.001f;
break;
case OF_KEY_DOWN:
eyeZ += 0.001f;
break;
case OF_KEY_PAGE_UP:
//eyeY += 0.005f;
break;
case OF_KEY_PAGE_DOWN:
//eyeY -= 0.005f;
break;
case OF_KEY_BACKSPACE:
if (len) input.erase(len-1);
break;
case OF_KEY_RETURN:
input = replace_all(input, " ", "%20");
try {
cities.push_back(City(input, *earth));
input.erase(0);
current = cities.size() - 1;
} catch (runtime_error e) {
cout << e.what() << endl;
input.erase(0);
showError = true;
}
break;
default:
showError = false;
input += key;
break;
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key)
{
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y)
{
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button)
{
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button)
{
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button)
{
}
//--------------------------------------------------------------
void testApp::resized(int w, int h)
{
/* if (h == 0) h = 1; // prevent a divide by zero by
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)w / (GLfloat)h, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();*/
}
GLvoid testApp::displayFPS()
{
static long lastTime = glutGet(GLUT_ELAPSED_TIME);
static long loops = 0;
static GLfloat fps = 0;
int newTime = glutGet(GLUT_ELAPSED_TIME);
if ((newTime - lastTime) > 100)
{
float newFPS = (float)loops / float(newTime - lastTime) * 1000.0f;
fps = (fps + newFPS) / 2.0f;
char title[80];
sprintf(title, "GLUT Demo - %.2f", fps);
glutSetWindowTitle(title);
lastTime = newTime;
loops = 0;
}
loops++;
}
void testApp::drawXYZ()
{
glBegin(GL_LINES);
glColor3d(0, 1, 0); // x
glVertex2d(-300, 0);
glVertex2d(300, 0);
glColor3d(1, 0, 0); // y
glVertex2d(0, 0);
glVertex2d(0, 300);
glColor3d(0, 0, 1); // z
glVertex3d(0, 0, -300);
glVertex3d(0, 0, 300);
glEnd();
}
|
/******************************************
* AUTHOR : Abhishek Naidu *
* NICK : abhisheknaiidu *
******************************************/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
#define CPS CLOCKS_PER_SEC
#define all(n) n.begin(),n.end()
#define pii pair<int,int>
#define vi vector<int>
#define mii map<int,int>
#define ps(x,y) fixed<<setprecision(y)<<x
#define mk(arr,n,type) type *arr=new type[n];
#define w(x) int x; cin>>x; while(x--)
#define pqb priority_queue<int>
#define pqs priority_queue<int,vi,greater<int> >
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define f first
#define s second
#define ll long long int
#define pb push_back
#define mp make_pair
#define inf 1e18
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
//Initializing Boolean Globally because
// It initializes with 0 values then
// rather than storing Garbage values
// Also bool takes 1 bit and whereas int
// takes 4 bits, Ss taking bool in order to
// Avoid TLE!!!
bool a[90000001];
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int32_t main()
{
abhisheknaiidu();
vi primes;
// Assumption by hit and Trial Method
int b = 90000000;
a[0] = a[1] = true;
for (int i = 2; i * i <= b ; i++) {
if (!a[i]) {
for (int j = i * i; j <= b; j += i)
a[j] = true;
}
}
for (int i = 2; i <= b; i++)
{
if (!a[i]) {
primes.pb(i);
}
}
w(x) {
int k;
cin >> k;
cout << k << " ";
cout << primes[k - 1] << endl;
}
return 0;
}
|
#include<iostream>
#include<vector>
#include<iterator>
#include<string>
#include<list>
#include<random>
#include<sstream>
#include<time.h>
#include<Windows.h>
#include<stdlib.h>
using namespace std;
struct card
{
friend bool compare(card& c1, card& c2);
public:
const int readnum();
const int readcol();
int lorCard();
int funCard();
const string id();
card() = default;
card(int x, int y) :color(x), num(y) {};
void redef();
void redel();
void changeNum(const int d);
void changeCol(const int d);
int lorColor = 0;
private:
int color;
int num;
};
void card::changeNum(const int d)
{
num = d;
}
void card::changeCol(const int d)
{
color = d;
}
const int card::readnum()
{
return num;
}
const int card::readcol()
{
return color;
}
//判定是否为神牌,非神牌则返回0
int card::lorCard()
{//6:+4
if (color == 6)return 2;
//5 选定颜色
else if (color == 5)return 1;
//普通牌
else return 0;
}
int card::funCard()
{
if (color < 5 && num>9 && num != 13 && num != 14)
{
switch (num)
{
case 10:return 1; break;//停
case 11:return 2; break;//反转
case 12:return 3; break;//+2
}
}
else return 0;
}
//一个表明身份的函数
const string card::id()
{
vector < string > colour{ "red", "yellow", "blue", "green","mistake","Wild","plus4" };
string s1, s2;
s1 = colour[color];
if (num < 10)//1-9为普通牌
{
s2 = std::to_string(num);
}
else
{
switch (num) {
case 10:s2 = "Skip"; break;
case 11:s2 = "Reverse"; break;
case 12:s2 = "+2(Draw Two)"; break;
case 13:s2 = "+4(Wild Draw Four)"; break;
case -1:s2 = "Wild"; break;
}
}
const string str = "[" + s1 + " " + s2 + "]";
return str;
}
bool compare(card& c1, card& c2)
{
//普通牌颜色或字数相同
if (c1.readnum() == c2.readnum() || c1.readcol() == c2.readcol())return 1;
//如果是神牌,则都可以出
else if (c2.lorCard() != 0)return 1;
//其余则不能出
else return 0;
}
struct CardData:public card
{
friend void readit(CardData c1);
friend void leftCards(CardData& all, CardData& rest, int i);
public:
void set();
void shuffle();
size_t getSize();
vector<card>& getVec();
private:
vector<card> cards;
};
vector<card>& CardData::getVec()
{
return cards;
}
size_t CardData::getSize()
{
return (cards.size());
}
void CardData::shuffle()
{
std::random_shuffle(cards.begin(), cards.end());
}
struct PLAY :public CardData
{
public:
void giveCards(const int i, CardData& numCard);
void showdown(card& c1, string& str);
void showdown(string& str);
void npcSearch(card& c1);
void plusCard(CardData& rest, int i);
void readit();
void input();
void input(card& c1);
void gamepro1(int j, string str);
void mainpro1();
int npcGetCol();
string showit();
bool gamer = 0;
int cir = 0, th;
auto sizeo() { return player.size(); }
private:
list<card> player;
};
//输出玩家所带卡牌信息
void PLAY::readit()//readit(players[0].player);
{
std::ostringstream cardinfo;
for (card& entry : player)
{
cardinfo << " " << entry.id();
}
cout << cardinfo.str() << endl;
}
//读出玩家所有牌的信息,返回string
string PLAY::showit()
{
std::ostringstream cardinfo;
for (card& entry : player)
{
cardinfo << " " << entry.id();
}
return cardinfo.str() + '\n';
}
//玩家环形链表
struct ListNode
{
PLAY val;
int order;
ListNode* next;
ListNode* prev;
};
void readit(card& c1);
void process(ListNode* ptr, int i, ListNode* main);
void ListClear(ListNode* head);
void rule();
ListNode*& game(vector<PLAY>& players, int i);
CardData allCard, restCard, usedCard;
vector<string> yanse{ "red", "yellow", "blue", "green" };
bool win = 0, role = 0, ex = 0;
int ver = 0;
int game();
int main()
{
int flag = 0;
while (1)
{
cout << "欢迎来到UNO小游戏" << endl;
cout << "输入1开始游戏" << endl;
cout << "输入2查看游戏规则" << endl;
string str;
cin >> str;
if (str == "1") { flag = 1; break; }
else if (str == "2") { cout << "游戏规则" << endl; flag = 2; break; }
else { cout << "无法识别,请重新输入" << endl; }
}
system("CLS");
if (flag == 2) {
while (1) {
rule(); cout << "按3返回";
int i; cin >> i;
if (i == 3)break;
}
}
system("CLS");
game();
return 0;
}
void rule()
{
cout << "UNO游戏规则" << endl;
cout << "游戏中有普通牌、万能牌、功能牌三种" << '\n' << "普通牌由(红、黄、绿、蓝)四种颜色和1-9的数字组成" << '\n'<<endl;
cout << "万能牌:" << '\n' << "【Wild牌】,可以你可以随意指定下家出牌的颜色(4色中选1)" << endl;
cout << "【+4(Draw Four)牌】,你可以随意指定下家出牌的颜色,同时下家需从牌堆中罚摸4张牌,且不能出牌" <<'\n'<< endl;
cout << "功能牌:" << '\n' << "【Skip牌】打出跳过后,你的下家不能出牌,轮到再下家出牌" << endl;
cout << "【Reverse牌】打出反转后,当前出牌时针顺序将反转。" << '\n' << "eg:原出牌顺序为A→B→C→D→A,在打出此牌之后,顺序变为D→C→B→A→D" << endl;
cout << "【+2(Draw Two)牌】打出+2后,下家将被罚摸2张牌,并且不能出牌" << '\n'<<endl;
cout << "每次出牌需与上家出的牌数字【或】颜色一样" << endl;
cout << "功能牌有(红黄绿蓝)四种颜色,出牌时需与上家颜色一样" << '\n' << "万能牌为黑色,都可以出" << '\n'<<endl;
cout << "UNO的获胜条件是:先将自己手上的牌全部打完(类似于斗地主)。" << '\n' << endl;
cout << "接下来将由您开始出牌" << '\n' << "******出牌格式请务必与显示的牌格式一致 eg: [red 3]******" << endl;
}
int game()
{
srand(time(NULL));
//初始化所有牌
allCard.set();
//随机数函数洗牌
allCard.shuffle();
//创建玩家,生成players[0]~[i-1]
int i;
while (1) {
cout << "请输入玩家个数,按回车结束";
cin >> i;
if (i > 9 || i < 2)cout << "请输入2-9的整数" << endl;
else break;
}
system("CLS");
vector<PLAY> players(i);//初始化i个PLAY对象
players[0].gamer = 1;
//发牌
for (int j = 0; j < i; ++j)
{
players[j].giveCards(j, allCard);
players[j].th = j;
}
//统计剩余的牌
leftCards(allCard, restCard, i);
//显示本人的牌
players[0].readit();
//出牌
cout << "请玩家出牌" << endl;
getchar();//吸掉上一个'\n'
//开始搭建循环链表
ListNode*& main = game(players, i);//值传递:主角位置//记得最后要free
process(main, i, main);
ListClear(main);
return 0;
}
//游戏进程
void process(ListNode* ptr, int i, ListNode* main)
{
ListNode* p = nullptr;
while (!win) {
cout << endl;
Sleep(1000);
if (restCard.getSize() == 0) { cout << "没有人获胜!" << endl; break; }
if (ptr->val.gamer && ptr->val.cir == 0)//主角第一次
{
ptr->val.input();
ptr->val.readit();
++ptr->val.cir;
p = ptr->next;
ptr = p;
p = nullptr;
}
else {
if (ver % 2 == 0)//没有反转
{
if (ex)
{
p = ptr->next->next;
ptr = p;
p = nullptr;
ex = 0;
}
else;
if (ptr->val.gamer)//如果是主角
{
ptr->val.mainpro1();
}
else //如果不是主角
{
ptr->val.gamepro1(ptr->order, main->val.showit());
if (ptr == main->prev)cout << main->val.showit();
}
//指向下一个指针
if (ptr->val.sizeo() == 0)
{
win = 1;
cout << "The player" << ptr->val.th << "has winned!" << endl;
}
else {
p = ptr->next;
ptr = p;
p = nullptr;
}
}
else//有反转:该第j-2个玩家出牌
{
if (ex)
{
p = ptr->prev->prev;
ptr = p;
p = nullptr;
ex = 0;
}
else;
if (ptr->val.gamer)//如果是主角
{
if (ptr->val.cir == 0)//主角第一次
{
ptr->val.input();
ptr->val.readit();
++ptr->val.cir;
}
else {
ptr->val.mainpro1();
}
}
else //如果不是主角
{
ptr->val.gamepro1(ptr->order, main->val.showit());
if (ptr == main->next)cout << main->val.showit();
}
if (ptr->val.sizeo() == 0)
{
win = 1;
cout << "The player" << ptr->val.th << "has winned!" << endl;
}
else {
p = ptr->prev;
ptr = p;
p = nullptr;
}
}
}
}
}
void ListClear(ListNode* head)
{
ListNode* q;
ListNode* p = head;
while (p->next) {
q = p;
p = q->next;
free(q);
}
free(p);
head = NULL;
}
//构造循环链表
ListNode*& game(vector<PLAY>& players, int i)
{
ListNode* cir = new ListNode;
cir->val = players[0];
cir->order = 0;
cir->next = nullptr;
cir->prev = nullptr;
ListNode* p = cir;
for (int j = 1; j < i; ++j)
{
ListNode* pN = new ListNode;
pN->val = players[j];
pN->order = j;
pN->next = nullptr;
cir->next = pN;
pN->prev = cir;
cir = pN;
}
cir->next = p;
p->prev = cir;//成环
return p;
}
void PLAY::gamepro1(int j, string str)//npc出牌
{
npcSearch(usedCard.getVec().back());
}
void PLAY::mainpro1()//玩家非首次出牌
{
input(usedCard.getVec().back());
readit();
}
//输入牌函数
void PLAY::input()
{
string s1;
getline(cin, s1);
showdown(s1);
}
void PLAY::input(card& c1)//接收上一个牌
{
int flag = 0;
if (c1.lorCard() != 0)//神牌
{
switch (c1.lorCard())
{
case 2:
{cout << "玩家" << th << "增加四张牌" << endl;
plusCard(restCard, 4);
c1.redel();
flag = 1;
break; }//+4
case 1://换颜色
{c1.redel();
cout << "是否出牌 yes or no" << endl;
string s;
cin >> s;
//增加了“过”的选项
switch (s[0])
{
case 'n': cout << "玩家" << th << "选择不出牌,过" << endl; plusCard(restCard, 1); flag = 1; break;
case 'y':flag = 0; break;
}
getchar();
if (flag == 0) {
string s2;
getline(cin, s2);
showdown(usedCard.getVec().back(), s2);
flag = 1;
}break;
}//换颜色
}
}
//功能牌
else if (c1.funCard() != 0)
{
switch (c1.funCard())//1停2反转3+2
{
case 1: cout << "该玩家" << th << "被禁止出牌,过" << endl; c1.redef(); break;
case 2: cout << "出牌顺序调换" << endl; break;//反转
case 3:plusCard(restCard, 2);//+2
c1.redef();
cout << "该玩家" << th << "增加两张牌" << endl;
break;
}
}
else {//普通牌
cout << "是否出牌 yes or no" << endl;
string s;
cin >> s;
getchar();
//增加了“过”的选项
switch (s[0])
{
case 'n': cout << "玩家" << th << "选择不出牌,过" << endl; plusCard(restCard, 1); flag = 1; break;
case 'y':flag = 0; break;
}
if (flag == 0)
{
if (c1.lorCard() == 0 && c1.funCard() == 0)
{
string s2;
getline(cin, s2);
showdown(usedCard.getVec().back(), s2);
}
}
}
}
//npc选色用函数:生成0~3的随机数
int PLAY::npcGetCol()
{
list<card>::iterator b = player.begin(), e = player.end();
int red = 0, yellow = 0, blue = 0, green = 0;
for (b; b != e; ++b)
{
card& c2 = *b;
switch (c2.readcol())
{
case 0:++red; break;
case 1:++yellow; break;
case 2:++blue; break;
case 3:++green; break;
}
}
int flag = 0;
if ((red >= yellow ? red : yellow) >= (blue >= green ? blue : green))flag = 1; else flag = 2;
if (flag == 1) { if (red >= yellow)return 0; else return 1; }
else { if (blue >= green)return 2; else return 3; }
}
//出牌功能判定
//npc寻找可以出的牌
void PLAY::npcSearch(card& c1)
{
//c1是普通数字牌的情况
if (c1.funCard() == 0 && c1.lorCard() == 0)
{
int flag = 0;
card c2;
list<card>::iterator b = player.begin(), e = player.end();
//有神牌优先出神牌
for (b; b != e; ++b)
{
if (b->lorCard() != 0)
{
role = 0;
c2 = *b;
player.erase(b);
cout << "玩家" << th << "出牌" << c2.id() << endl;
const int f = 5;
srand(time(NULL));
int i;
int j = (rand() % 2);//选取0-1
if (j == 0)
{
srand(time(NULL));
i = (rand() % 4);//选取0~3的数
c2.lorColor = i;
}
else { i = npcGetCol(); c2.lorColor = i; }
cout << "下一张出牌颜色必须为" << yanse[i] << endl;
usedCard.getVec().push_back(c2);
flag = 1;
break;
}
}
if (flag == 0)
{
b = player.begin(), e = player.end();
for (b; b != e; ++b)
{
if (compare(c1, *b))
{
flag = 1;
c2 = *b;
player.erase(b);
usedCard.getVec().push_back(c2);
cout << "玩家" << th << "出牌" << c2.id() << endl;
if (c2.funCard() == 2) { ++ver; ex = 1; c2.redef(); }
break;
}
}
if (flag == 0)
{
cout << "该玩家" << th << "没有可出的牌,过" << endl;
plusCard(restCard, 1);
}
}
}
else if (c1.funCard() != 0)//功能牌的情况
{
switch (c1.funCard())//1停2反转3+2
{
case 1:
cout << "该玩家" << th << "被禁止出牌,过" << endl;
c1.redef();
break;
case 2:
cout << "出牌顺序调换" << endl;
break; //反转
case 3:
plusCard(restCard, 2);//+2
c1.redef();
cout << "该玩家" << th << "增加两张牌" << endl;
break;
}
}
else//神牌的情况
{
if (role) {
int flag = 1;
const int f = 5;
cout << "请选择颜色 red yellow blue green" << endl;
string s1;
cin >> s1;
switch (s1[0])
{
case'r':c1.lorColor = 0; break;
case'y':c1.lorColor = 1; break;
case'b':c1.lorColor = 2; break;
case'g':c1.lorColor = 3; break;
//
}
}
else;
if (c1.lorCard() == 2)
{
cout << "该玩家" << th << "增加四张牌" << endl;
plusCard(restCard, 4);
c1.redel();
}
else
{
c1.redel();
npcSearch(usedCard.getVec().back());
}
}
}
void card::redef()
{
if (num == 11)cout << "出牌顺序调换" << endl;
else if (num == 12)cout << "下一玩家增加两张牌" << endl;
this->changeNum(14);
usedCard.getVec().push_back(*this);
}
void card::redel()
{
if (num == 13)cout << "下一玩家增加四张牌" << endl;
this->changeCol(lorColor);
usedCard.getVec().push_back(*this);
}
void PLAY::plusCard(CardData& rest, int i)
{
vector<card>::iterator b = rest.getVec().begin(), e = rest.getVec().end();
if (b + i >= e)
{
for (b; b != rest.getVec().end(); ++b)
{
player.push_back(*b);
}
rest.getVec().clear();
}
else
{
for (int j = 0; j < i; ++j)
{
player.push_back(*b); ++b;
}
rest.getVec().erase(b - i, b);
}
}
//读出单个卡牌信息
void readit(card& c1)
{
cout << c1.id() << endl;
}
//读出一套卡牌信息
void readit(CardData c1)
{
for (card& entry : c1.cards)
cout << " " << entry.id();
}
void leftCards(CardData& all, CardData& rest, int i)
{//现在已经发出i*7张牌,all[i*7]
for (int j = 0; j < (108 - i * 7); ++j)
rest.cards.push_back(all.cards[i * 7 + j]);
}
//首次出牌的判定
void PLAY::showdown(string& str)
{//验证是否有这个牌
int flag = 0;
card c2;
list<card>::iterator b = player.begin(), e = player.end();
for (b; b != e; ++b)
{
if (b->id() == str) {
flag = 1;
if (b->lorCard() != 0 || b->funCard() != 0) {
flag = 2; break;
}
else
{
c2 = *b;
player.erase(b);
break;
}
}
else;
}
if (flag == 0) { cout << "不符规则,请重新出牌" << endl; input(); }
else if (flag == 2) {
cout << "首局最好不要出功能/万能牌" << '\n'; input();
}
else {
cout << "玩家" << th << "出牌 " << c2.id() << endl;
usedCard.getVec().push_back(c2);
}
}
//非首次出牌的判定
void PLAY::showdown(card& c1, string& str)
{//验证是否有这个牌
int flag = 0;
card c2;
list<card>::iterator b = player.begin(), e = player.end();
for (b; b != e; ++b)
{
if (b->id() == str) {
flag = 1;
c2 = *b;
player.erase(b);
break;
}
else;
}
if (flag == 0) {
cout << "不符规则,请重新出牌" << endl; input(usedCard.getVec().back());
}
else
{
//验证与上一个牌是否匹配
if (!compare(c1, c2)) {
cout << "不符规则,请重新出牌" << endl; input(usedCard.getVec().back());
}
else//以下肯定都是匹配的牌
{
if (c2.funCard() == 2) {
++ver; ex = 1;
c2.redef();
cout << "玩家0出牌 " << c2.id() << endl;
}
else {
if (c2.lorCard() != 0)role = 1;
else;
cout << "玩家0出牌 " << c2.id() << endl;
usedCard.getVec().push_back(c2);
}
}
}
}
void PLAY::giveCards(const int i, CardData& numCard)
{
for (int j = 0; j < 7; ++j)
player.push_back(numCard.getVec()[i * 7 + j]);
}
void setPlayers(vector<list<card>>& player, int i)
{
for (int j = 0; j < i; ++j)
{
list<card> p1;
player.push_back(p1);
}
}
void CardData::set()
{//初始化普通数字牌
//0红1黄2蓝3绿
for (int j = 0; j < 4; ++j)
{
card num(j, 0);
this->cards.push_back(num);
}
for (int j = 0; j < 4; ++j)
for (int i = 1; i < 10; )
{
card num(j, i);
this->cards.push_back(num);
this->cards.push_back(num);
++i;
}
//numCard[j*4+i]i:0~19
//初始化功能牌
//10禁止11反转12加2
for (int j = 0; j < 4; ++j)
for (int z = 10; z < 13; ++z)
for (int i = 0; i < 2; ++i)
{
card num(j, z);
this->cards.push_back(num);
}
//funCard[j][z][i]z:0~2,i:0~2
//初始化万能牌
//5变色6+4
for (int j = 0; j < 4; ++j)
{
card num(5, -1);
this->cards.push_back(num);
card num2(6, 13);
this->cards.push_back(num);
}
}
|
// Copyright (C) 2012-2017 Hartmut Kaiser
// (C) Copyright 2008-10 Anthony Williams
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under 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)
#include <pika/config.hpp>
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <pika/thread.hpp>
#include <array>
#include <chrono>
#include <string>
#include <thread>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
int make_int_slowly()
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return 42;
}
void test_wait_for_either_of_two_futures_list()
{
std::array<pika::future<int>, 2> futures;
pika::lcos::local::packaged_task<int()> pt1(make_int_slowly);
futures[0] = pt1.get_future();
pika::lcos::local::packaged_task<int()> pt2(make_int_slowly);
futures[1] = pt2.get_future();
pt1();
pika::future<pika::when_some_result<std::array<pika::future<int>, 2>>> r =
pika::when_some(1u, futures);
pika::when_some_result<std::array<pika::future<int>, 2>> raw = r.get();
PIKA_TEST_EQ(raw.indices.size(), 1u);
PIKA_TEST_EQ(raw.indices[0], 0u);
std::array<pika::future<int>, 2> t = std::move(raw.futures);
PIKA_TEST(!futures.front().valid());
PIKA_TEST(!futures.back().valid());
PIKA_TEST(t.front().is_ready());
PIKA_TEST_EQ(t.front().get(), 42);
}
///////////////////////////////////////////////////////////////////////////////
using pika::program_options::options_description;
using pika::program_options::variables_map;
using pika::future;
int pika_main(variables_map&)
{
test_wait_for_either_of_two_futures_list();
pika::finalize();
return 0;
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
// Configure application-specific options
options_description cmdline("Usage: " PIKA_APPLICATION_STRING " [options]");
// We force this test to use several threads by default.
std::vector<std::string> const cfg = {"pika.os_threads=all"};
// Initialize and run pika
pika::init_params init_args;
init_args.desc_cmdline = cmdline;
init_args.cfg = cfg;
return pika::init(pika_main, argc, argv, init_args);
}
|
#include "precompiled.h"
#include "component/meshcomponent.h"
#include "component/jscomponent.h"
#include "entity/entitymanager.h"
#include "scene/scene.h"
#include "render/render.h"
#include "render/shapes.h"
#include "render/rendergroup.h"
#include "mesh/meshcache.h"
using namespace component;
REGISTER_COMPONENT_TYPE(MeshComponent, MESHCOMPONENT);
#pragma warning(disable: 4355) // disable warning for using 'this' as an initializer
MeshComponent::MeshComponent(entity::Entity* entity, const string& name, const desc_type& desc)
: Component(entity, name, desc), m_meshName(desc.mesh), transform(this), m_mesh(NULL)
{
transform = desc.transformComponent;
}
MeshComponent::~MeshComponent()
{
if(m_acquired)
release();
if(m_scriptObject)
destroyScriptObject();
}
void MeshComponent::acquire()
{
if(m_acquired)
return;
ASSERT(m_mesh == NULL);
m_mesh = mesh::getMesh(m_meshName);
if(!m_mesh)
{
INFO("WARNING: unable to acquire mesh \"%s\" on component \"%s.%s\"", m_meshName.c_str(),
m_entity->getName().c_str(), m_name.c_str());
return;
}
if(!transform)
{
INFO("WARNING: unable to acquire transform for \"%s.%s\"",
m_entity->getName().c_str(), m_name.c_str());
m_mesh = NULL;
return;
}
m_mesh->acquire();
m_entity->getManager()->getScene()->addRenderable(this);
Component::acquire();
}
void MeshComponent::release()
{
Component::release();
transform.release();
m_mesh = NULL;
m_entity->getManager()->getScene()->removeRenderable(this);
}
D3DXVECTOR3 MeshComponent::getRenderOrigin() const
{
ASSERT(transform);
D3DXMATRIX m = m_mesh->mesh_offset * transform->getTransform();
D3DXVECTOR3 scale, pos;
D3DXQUATERNION rot;
D3DXMatrixDecompose(&scale, &rot, &pos, &m);
return pos;
}
void MeshComponent::render(texture::Material* lighting)
{
ASSERT(m_acquired);
ASSERT(transform);
render::RenderGroup* rg = m_mesh->rendergroup;
rg->material = lighting;
D3DXMATRIX m = m_mesh->mesh_offset * transform->getTransform();
render::drawGroup(rg, &m);
if(render::visualizeFlags & render::VIS_AXIS)
render::drawAxis(transform->getPos(), transform->getRot());
}
JSObject* MeshComponent::createScriptObject()
{
return jscomponent::createComponentScriptObject(this);
}
void MeshComponent::destroyScriptObject()
{
jscomponent::destroyComponentScriptObject(this);
m_scriptObject = NULL;
}
|
#ifndef CRequestHelpInfoMessage_H
#define CRequestHelpInfoMessage_H
#include "CMessage.h"
#include <QObject>
//ÇëÇóXMLÏûÏ¢
class CRequestHelpInfoMessage : public CMessage
{
Q_OBJECT
public:
CRequestHelpInfoMessage(CMessageEventMediator* pMessageEventMediator, QObject *parent = 0);
~CRequestHelpInfoMessage();
virtual void packedSendMessage(NetMessage& netMessage);
virtual bool treatMessage(const NetMessage& netMessage, CMessageFactory* pFactory, SocketContext* clientSocket);
};
#endif //CRequestHelpInfoMessage_H
|
#include "EntitiesModule.h"
namespace Game
{
EntitiesModule::EntitiesModule() : mEntities()
{
}
EntitiesModule::~EntitiesModule()
{
cleanup();
}
Entity* EntitiesModule::get(uint32_t id)
{
return mEntities.find(id)->second;
}
Entity* EntitiesModule::add()
{
auto entity = new Entity();
mEntities.insert(std::pair<uint32_t, Entity*>(++mInternalId, entity));
entity->setId(mInternalId);
return entity;
}
void EntitiesModule::start()
{
for (auto element : mEntities) {
element.second->start();
}
}
void EntitiesModule::stop()
{
for (auto element : mEntities) {
element.second->stop();
}
}
void EntitiesModule::update()
{
for (auto element : mEntities) {
element.second->update();
}
}
void EntitiesModule::draw()
{
for (auto element : mEntities) {
element.second->draw();
}
}
void EntitiesModule::configure()
{
for (auto element : mEntities) {
element.second->configure();
}
}
void EntitiesModule::cleanup()
{
while (!mEntities.empty()) {
auto it = mEntities.begin();
if (it->second != NULL) {
it->second->cleanup();
delete it->second;
}
mEntities.erase(it);
}
}
}
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
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.
====================================================================*/
// Local includes
#include "pch.h"
#include "Common.h"
#include "Debug.h"
#include "Icons.h"
#include "Log.h"
#include "NetworkSystem.h"
#include "StepTimer.h"
// System includes
#include "NotificationSystem.h"
// IGT includes
#include <IGTCommon.h>
#include <igtlMessageBase.h>
#include <igtlStatusMessage.h>
// STL includes
#include <sstream>
using namespace Concurrency;
using namespace Windows::Data::Xml::Dom;
using namespace Windows::Media::SpeechRecognition;
using namespace Windows::Networking::Connectivity;
using namespace Windows::Networking;
using namespace Windows::Storage;
namespace HoloIntervention
{
namespace System
{
const float NetworkSystem::NETWORK_BLINK_TIME_SEC = 0.75;
const double NetworkSystem::CONNECT_TIMEOUT_SEC = 3.0;
const uint32_t NetworkSystem::RECONNECT_RETRY_DELAY_MSEC = 100;
const uint32_t NetworkSystem::RECONNECT_RETRY_COUNT = 10;
const uint32 NetworkSystem::DICTATION_TIMEOUT_DELAY_MSEC = 8000;
const uint32 NetworkSystem::KEEP_ALIVE_INTERVAL_MSEC = 1000;
//----------------------------------------------------------------------------
task<bool> NetworkSystem::WriteConfigurationAsync(XmlDocument^ document)
{
return create_task([this, document]()
{
auto xpath = ref new Platform::String(L"/HoloIntervention");
if (document->SelectNodes(xpath)->Length != 1)
{
return false;
}
auto rootNode = document->SelectNodes(xpath)->Item(0);
auto connectionsElem = document->CreateElement(L"IGTConnections");
for (auto connector : m_connectors)
{
auto connectionElem = document->CreateElement(L"Connection");
connectionElem->SetAttribute(L"Name", ref new Platform::String(connector->Name.c_str()));
if (connector->Connector->ServerHost != nullptr)
{
connectionElem->SetAttribute(L"Host", connector->Connector->ServerHost->DisplayName);
}
if (connector->Connector->ServerPort != nullptr)
{
connectionElem->SetAttribute(L"Port", connector->Connector->ServerPort);
}
if (connector->Connector->EmbeddedImageTransformName != nullptr)
{
connectionElem->SetAttribute(L"EmbeddedImageTransformName", connector->Connector->EmbeddedImageTransformName->GetTransformName());
}
connectionsElem->AppendChild(connectionElem);
}
rootNode->AppendChild(connectionsElem);
return true;
});
}
//----------------------------------------------------------------------------
task<bool> NetworkSystem::ReadConfigurationAsync(XmlDocument^ document)
{
return create_task([this, document]()
{
auto xpath = ref new Platform::String(L"/HoloIntervention/IGTConnections/Connection");
if (document->SelectNodes(xpath)->Length == 0)
{
return task_from_result(false);
}
std::vector<task<std::shared_ptr<UI::Icon>>> modelLoadingTasks;
for (auto node : document->SelectNodes(xpath))
{
if (!HasAttribute(L"Name", node))
{
return task_from_result(false);
}
if (!HasAttribute(L"Host", node))
{
return task_from_result(false);
}
if (!HasAttribute(L"Port", node))
{
return task_from_result(false);
}
Platform::String^ name = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Name")->NodeValue);
Platform::String^ host = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Host")->NodeValue);
Platform::String^ port = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Port")->NodeValue);
if (name->IsEmpty() || host->IsEmpty() || port->IsEmpty())
{
return task_from_result(false);
}
std::shared_ptr<ConnectorEntry> entry = std::make_shared<ConnectorEntry>();
entry->Name = std::wstring(name->Data());
entry->HashedName = HashString(name->Data());
entry->Connector = ref new UWPOpenIGTLink::IGTClient();
entry->Connector->ServerHost = ref new HostName(host);
entry->ErrorMessageToken = entry->Connector->ErrorMessage += ref new UWPOpenIGTLink::ErrorMessageEventHandler(std::bind(&NetworkSystem::ErrorMessageHandler, this, std::placeholders::_1, std::placeholders::_2));
entry->ErrorMessageToken = entry->Connector->WarningMessage += ref new UWPOpenIGTLink::WarningMessageEventHandler(std::bind(&NetworkSystem::WarningMessageHandler, this, std::placeholders::_1, std::placeholders::_2));
try
{
std::stoi(port->Data());
entry->Connector->ServerPort = port;
}
catch (const std::exception&) {}
if (HasAttribute(L"EmbeddedImageTransformName", node))
{
Platform::String^ embeddedImageTransformName = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"EmbeddedImageTransformName")->NodeValue);
if (!embeddedImageTransformName->IsEmpty())
{
try
{
auto transformName = ref new UWPOpenIGTLink::TransformName(embeddedImageTransformName);
entry->Connector->EmbeddedImageTransformName = transformName;
}
catch (Platform::Exception^) {}
}
}
// Create icon
modelLoadingTasks.push_back(m_icons.AddEntryAsync(L"Assets/Models/network_icon.cmo", entry->HashedName).then([this, entry](std::shared_ptr<UI::Icon> iconEntry)
{
entry->Icon.m_iconEntry = iconEntry;
return iconEntry;
}));
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
m_connectors.push_back(entry);
}
return when_all(begin(modelLoadingTasks), end(modelLoadingTasks)).then([this](std::vector<std::shared_ptr<UI::Icon>> entries)
{
m_componentReady = true;
return true;
});
});
}
//----------------------------------------------------------------------------
NetworkSystem::NetworkSystem(HoloInterventionCore& core, System::NotificationSystem& notificationSystem, Input::VoiceInput& voiceInput, UI::Icons& icons, Debug& debug)
: IConfigurable(core)
, m_notificationSystem(notificationSystem)
, m_voiceInput(voiceInput)
, m_icons(icons)
, m_debug(debug)
{
/*
disabled, currently crashes
FindServersAsync().then([this](task<std::vector<std::wstring>> findServerTask)
{
std::vector<std::wstring> servers;
try
{
servers = findServerTask.get();
}
catch (const std::exception& e)
{
LOG(LogLevelType::LOG_LEVEL_ERROR, std::string("IGTConnector failed to find servers: ") + e.what());
}
});
*/
}
//----------------------------------------------------------------------------
NetworkSystem::~NetworkSystem()
{
}
//----------------------------------------------------------------------------
task<bool> NetworkSystem::ConnectAsync(uint64 hashedConnectionName, double timeoutSec /*= CONNECT_TIMEOUT_SEC*/, task_options& options /*= Concurrency::task_options()*/)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
assert((*iter)->Connector != nullptr);
(*iter)->State = CONNECTION_STATE_CONNECTING;
return create_task((*iter)->Connector->ConnectAsync(timeoutSec), options).then([this, hashedConnectionName](task<bool> connectTask)
{
bool result(false);
try
{
result = connectTask.get();
}
catch (const std::exception& e)
{
LOG(LogLevelType::LOG_LEVEL_ERROR, std::string("IGTConnector failed to connect: ") + e.what());
return false;
}
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (result)
{
(*iter)->State = CONNECTION_STATE_CONNECTED;
}
else
{
(*iter)->State = CONNECTION_STATE_DISCONNECTED;
}
return result;
});
}
return task_from_result(false);
}
//----------------------------------------------------------------------------
task<std::vector<bool>> NetworkSystem::ConnectAsync(double timeoutSec /*= CONNECT_TIMEOUT_SEC*/, task_options& options /*= Concurrency::task_options()*/)
{
// Connect all connectors
auto tasks = std::vector<task<bool>>();
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
for (auto entry : m_connectors)
{
auto task = this->ConnectAsync(entry->HashedName, 4.0);
tasks.push_back(task);
}
return when_all(begin(tasks), end(tasks));
}
//----------------------------------------------------------------------------
bool NetworkSystem::IsConnected(uint64 hashedConnectionName) const
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
return iter == end(m_connectors) ? false : (*iter)->Connector->Connected;
}
//----------------------------------------------------------------------------
HoloIntervention::System::NetworkSystem::ConnectorList NetworkSystem::GetConnectors()
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
return m_connectors;
}
//----------------------------------------------------------------------------
Concurrency::task<UWPOpenIGTLink::CommandData> NetworkSystem::SendCommandAsync(uint64 hashedConnectionName, const std::wstring& commandName, const std::map<std::wstring, std::wstring>& attributes)
{
UWPOpenIGTLink::CommandData cmdData = {0, false};
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter == end(m_connectors))
{
LOG_ERROR("Unable to locate connector.");
return task_from_result(cmdData);
}
auto map = ref new Platform::Collections::Map<Platform::String^, Platform::String^>();
for (auto& pair : attributes)
{
map->Insert(ref new Platform::String(pair.first.c_str()),
ref new Platform::String(pair.second.c_str()));
}
return create_task((*iter)->Connector->SendCommandAsync(ref new Platform::String(commandName.c_str()), map));
}
//----------------------------------------------------------------------------
bool NetworkSystem::IsCommandComplete(uint64 hashedConnectionName, uint32 commandId)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter == end(m_connectors))
{
LOG_ERROR("Unable to locate connector.");
return false;
}
return (*iter)->Connector->IsCommandComplete(commandId);
}
//----------------------------------------------------------------------------
void NetworkSystem::ProcessNetworkLogic(DX::StepTimer& timer)
{
for (auto& connector : m_connectors)
{
if (!connector->Icon.m_iconEntry->GetModel()->IsLoaded())
{
continue;
}
switch (connector->State)
{
case System::NetworkSystem::CONNECTION_STATE_CONNECTING:
case System::NetworkSystem::CONNECTION_STATE_DISCONNECTING:
if (connector->Icon.m_networkPreviousState != connector->State)
{
connector->Icon.m_networkBlinkTimer = 0.f;
}
else
{
connector->Icon.m_networkBlinkTimer += static_cast<float>(timer.GetElapsedSeconds());
if (connector->Icon.m_networkBlinkTimer >= NETWORK_BLINK_TIME_SEC)
{
connector->Icon.m_networkBlinkTimer = 0.f;
connector->Icon.m_iconEntry->GetModel()->ToggleVisible();
}
}
connector->Icon.m_networkIsBlinking = true;
break;
case System::NetworkSystem::CONNECTION_STATE_UNKNOWN:
case System::NetworkSystem::CONNECTION_STATE_DISCONNECTED:
case System::NetworkSystem::CONNECTION_STATE_CONNECTION_LOST:
connector->Icon.m_iconEntry->GetModel()->SetVisible(true);
connector->Icon.m_networkIsBlinking = false;
if (connector->Icon.m_wasNetworkConnected)
{
connector->Icon.m_iconEntry->GetModel()->SetRenderingState(Rendering::RENDERING_GREYSCALE);
connector->Icon.m_wasNetworkConnected = false;
}
break;
case System::NetworkSystem::CONNECTION_STATE_CONNECTED:
connector->Icon.m_iconEntry->GetModel()->SetVisible(true);
connector->Icon.m_networkIsBlinking = false;
if (!connector->Icon.m_wasNetworkConnected)
{
connector->Icon.m_wasNetworkConnected = true;
connector->Icon.m_iconEntry->GetModel()->SetRenderingState(Rendering::RENDERING_DEFAULT);
}
break;
}
connector->Icon.m_networkPreviousState = connector->State;
}
}
//----------------------------------------------------------------------------
void NetworkSystem::RegisterVoiceCallbacks(Input::VoiceInputCallbackMap& callbackMap)
{
callbackMap[L"connect"] = [this](SpeechRecognitionResult ^ result)
{
uint64 connectMessageId = m_notificationSystem.QueueMessage(L"Connecting...");
auto task = this->ConnectAsync(4.0);
};
callbackMap[L"set IP"] = [this](SpeechRecognitionResult ^ result)
{
// TODO : dictation
/*
// Which connector?
m_dictationMatcherToken = m_voiceInput.RegisterDictationMatcher([this](const std::wstring & text)
{
bool matchedText(false);
m_accumulatedDictationResult += text;
OutputDebugStringW((m_accumulatedDictationResult + L"\n").c_str());
if (matchedText)
{
m_voiceInput.RemoveDictationMatcher(m_dictationMatcherToken);
m_voiceInput.SwitchToCommandRecognitionAsync();
return true;
}
else
{
return false;
}
});
m_voiceInput.SwitchToDictationRecognitionAsync();
call_after([this]()
{
m_voiceInput.RemoveDictationMatcher(m_dictationMatcherToken);
m_dictationMatcherToken = INVALID_TOKEN;
m_voiceInput.SwitchToCommandRecognitionAsync();
m_accumulatedDictationResult.clear();
}, DICTATION_TIMEOUT_DELAY_MSEC);
*/
};
callbackMap[L"disconnect"] = [this](SpeechRecognitionResult ^ result)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
for (auto entry : m_connectors)
{
entry->Connector->Disconnect();
entry->State = CONNECTION_STATE_DISCONNECTED;
}
m_notificationSystem.QueueMessage(L"Disconnected.");
};
}
//----------------------------------------------------------------------------
UWPOpenIGTLink::TransformName^ NetworkSystem::GetEmbeddedImageTransformName(uint64 hashedConnectionName) const
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
return iter == end(m_connectors) ? nullptr : (*iter)->Connector->EmbeddedImageTransformName;
}
//----------------------------------------------------------------------------
void NetworkSystem::SetEmbeddedImageTransformName(uint64 hashedConnectionName, UWPOpenIGTLink::TransformName^ name)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
(*iter)->Connector->EmbeddedImageTransformName = name;
}
}
//----------------------------------------------------------------------------
void NetworkSystem::Disconnect(uint64 hashedConnectionName)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
(*iter)->Connector->Disconnect();
(*iter)->State = CONNECTION_STATE_DISCONNECTED;
}
}
//----------------------------------------------------------------------------
bool NetworkSystem::GetConnectionState(uint64 hashedConnectionName, ConnectionState& state) const
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
state = (*iter)->State;
return true;
}
return false;
}
//----------------------------------------------------------------------------
void NetworkSystem::SetHostname(uint64 hashedConnectionName, const std::wstring& hostname)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
(*iter)->Connector->ServerHost = ref new HostName(ref new Platform::String(hostname.c_str()));
}
}
//----------------------------------------------------------------------------
bool NetworkSystem::GetHostname(uint64 hashedConnectionName, std::wstring& hostName) const
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
hostName = (*iter)->Connector->ServerHost->DisplayName->Data();
return true;
}
return false;
}
//----------------------------------------------------------------------------
void NetworkSystem::SetPort(uint64 hashedConnectionName, int32 port)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
(*iter)->Connector->ServerPort = port.ToString();
}
}
//----------------------------------------------------------------------------
bool NetworkSystem::GetPort(uint64 hashedConnectionName, int32& port) const
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
port = std::stoi((*iter)->Connector->ServerPort->Data());
return true;
}
return false;
}
//----------------------------------------------------------------------------
UWPOpenIGTLink::TrackedFrame^ NetworkSystem::GetTrackedFrame(uint64 hashedConnectionName, double& latestTimestamp)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
auto latestFrame = (*iter)->Connector->GetTrackedFrame(latestTimestamp);
if (latestFrame == nullptr)
{
return nullptr;
}
try
{
latestTimestamp = latestFrame->Timestamp;
}
catch (Platform::ObjectDisposedException^) { return nullptr; }
return latestFrame;
}
return nullptr;
}
//----------------------------------------------------------------------------
UWPOpenIGTLink::TransformListABI^ NetworkSystem::GetTDataFrame(uint64 hashedConnectionName, double& latestTimestamp)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
auto latestFrame = (*iter)->Connector->GetTDataFrame(latestTimestamp);
if (latestFrame == nullptr)
{
return nullptr;
}
try
{
if (latestFrame->Size > 0)
{
latestTimestamp = latestFrame->GetAt(0)->Timestamp;
}
else
{
return nullptr;
}
}
catch (Platform::ObjectDisposedException^) { return nullptr; }
return latestFrame;
}
return nullptr;
}
//----------------------------------------------------------------------------
UWPOpenIGTLink::Transform^ NetworkSystem::GetTransform(uint64 hashedConnectionName, UWPOpenIGTLink::TransformName^ transformName, double& latestTimestamp)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
auto latestFrame = (*iter)->Connector->GetTransform(transformName, latestTimestamp);
if (latestFrame == nullptr)
{
return nullptr;
}
try
{
latestTimestamp = latestFrame->Timestamp;
}
catch (Platform::ObjectDisposedException^) { return nullptr; }
return latestFrame;
}
return nullptr;
}
//----------------------------------------------------------------------------
UWPOpenIGTLink::Polydata^ NetworkSystem::GetPolydata(uint64 hashedConnectionName, Platform::String^ name)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
auto polydata = (*iter)->Connector->GetPolydata(name);
return polydata;
}
return nullptr;
}
//----------------------------------------------------------------------------
UWPOpenIGTLink::VideoFrame^ NetworkSystem::GetImage(uint64 hashedConnectionName, double& latestTimestamp)
{
std::lock_guard<std::recursive_mutex> guard(m_connectorsMutex);
auto iter = std::find_if(begin(m_connectors), end(m_connectors), [hashedConnectionName](std::shared_ptr<ConnectorEntry> entry)
{
return hashedConnectionName == entry->HashedName;
});
if (iter != end(m_connectors))
{
auto image = (*iter)->Connector->GetImage(latestTimestamp);
return image;
}
return nullptr;
}
//-----------------------------------------------------------------------------
void NetworkSystem::Update(DX::StepTimer& timer)
{
if (!m_componentReady)
{
return;
}
ProcessNetworkLogic(timer);
for (auto connector : m_connectors)
{
if (connector->State == CONNECTION_STATE_CONNECTED && !connector->Connector->Connected)
{
// Other end has likely dropped us, update the state (and thus the UI), and reconnect
LOG_INFO("Connection dropped by server. Reconnecting.");
connector->State = CONNECTION_STATE_DISCONNECTED;
ConnectAsync(connector->HashedName, 4.0);
}
}
}
//----------------------------------------------------------------------------
task<std::vector<std::wstring>> NetworkSystem::FindServersAsync()
{
return create_task([this]()
{
std::vector<std::wstring> results;
auto hostNames = NetworkInformation::GetHostNames();
for (auto host : hostNames)
{
if (host->Type == HostNameType::Ipv4)
{
std::wstring hostIP(host->ToString()->Data());
std::wstring machineIP = hostIP.substr(hostIP.find_last_of(L'.') + 1);
std::wstring prefix = hostIP.substr(0, hostIP.find_last_of(L'.'));
// Given a subnet, ping all other IPs
for (int i = 0; i < 256; ++i)
{
std::wstringstream ss;
ss << i;
if (ss.str() == machineIP)
{
continue;
}
UWPOpenIGTLink::IGTClient^ client = ref new UWPOpenIGTLink::IGTClient();
client->ServerHost = ref new HostName(ref new Platform::String((prefix + L"." + ss.str()).c_str()));
client->ServerPort = L"18944";
task<bool> connectTask = create_task(client->ConnectAsync(0.5));
bool result(false);
try
{
result = connectTask.get();
}
catch (const std::exception&)
{
continue;
}
if (result)
{
client->Disconnect();
results.push_back(prefix + L"." + ss.str());
}
}
}
}
return results;
});
}
//----------------------------------------------------------------------------
void NetworkSystem::ErrorMessageHandler(UWPOpenIGTLink::IGTClient^ mc, Platform::String^ msg)
{
for (auto& connector : m_connectors)
{
if (connector->Connector == mc)
{
WLOG_ERROR(ref new Platform::String(connector->Name.c_str()) + L" error: " + msg);
return;
}
}
WLOG_ERROR(L"Unknown connector error: " + msg);
}
//----------------------------------------------------------------------------
void NetworkSystem::WarningMessageHandler(UWPOpenIGTLink::IGTClient^ mc, Platform::String^ msg)
{
for (auto& connector : m_connectors)
{
if (connector->Connector == mc)
{
WLOG_WARNING(ref new Platform::String(connector->Name.c_str()) + L" warning: " + msg);
return;
}
}
WLOG_WARNING(L"Unknown connector warning: " + msg);
}
}
}
|
#include <bits/stdc++.h>
#define REP(i, a, b) for(int i = (int)a; i < (int)b; i++)
#define fastio ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define pb push_back
#define mp make_pair
#define st first
#define nd second
#define vi vector<int>
#define ii pair<int, int>
#define ll long long int
#define MAX 200010
#define MOD 1000000007
#define oo 0x7fffffff
#define endl '\n'
using namespace std;
int main()
{
fastio;
int a, b, c, pre=0;
cin >> a >> b >> c;
if((a+b == c) || (a==b)){
pre++;
}
if((a+c == b) || (a==c)){
pre++;
}
if((b+c == a) || (b==c)){
pre++;
}
if(pre > 0){
cout << "S\n";
}else{
cout << "N\n";
}
return 0;
}
|
#include <iostream>
//i is a const int
//j is an int (top level const dropped)
//k is a const int
//p is a const int* (pointer to const int) but p is not const
//j2 is a const int
//k2 is a reference to const int
int main()
{
const int i = 42;
auto j = i; const auto &k = i; auto *p =&i;
const auto j2 = i, &k2 = i;
// this should be ok, and j should be '12'
j = 12.2;
std::cout << "j: " << j << std::endl;
//this should fail, because &k is const
//k = 12; //error: assignment of read-only reference ‘k’
//this should fail, because p points to a const int
//*p = 12; // error: assignment of read-only location ‘* p’
//however, this should be ok, because p is not a top-level const
p = &j;
//and this will print '12'
std::cout << "*p: " << *p << std::endl;
//this will print '42'
std::cout << "j2: " << j2 << std::endl;
//this will fail, because j2 is a const int:
//j2 = 12; //error: assignment of read-only variable ‘j2’
//this will print '42'
std::cout << "k2: " << k2 << std::endl;
// but this will fail, because k2 references a const int
//k2 = 12; //error: assignment of read-only reference ‘k2’
}
|
/*
* Copyright 2019 Nagoya University
*
* 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.
*/
/****************************************
* hdmi_static_converter.cpp
* データベース形式ダイナミックマップを読み込み、
* ベクタマップに変換して配信するメインプログラム
****************************************/
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
#include "dmp_file.h"
#include "adas_file.h"
#include "dmp_to_adas.h"
/************************************************************
* グローバル変数定義
************************************************************/
bool bDebugFlg = false; // デバッグログ出力フラグ
std::ofstream ofsdbg; // デバッグログ出力ストリーム
/************************************************************
* ローカル定数定義
************************************************************/
#define HOST_DEFAULT "127.0.0.1" // DBシステム/PostgreSQLサーバ ホスト名
#ifdef USE_DMLIB
#define PORT_DEFAULT 9001 // DBシステム ポート番号
#else
#define PORT_DEFAULT 5432 // PostgreSQLサーバ ポート番号
#endif
#define USER_DEFAULT "dm2" // PostgreSQLサーバ ユーザ名
#define PASS_DEFAULT "dm2" // PostgreSQLサーバ パスワード
#define DTBS_DEFAULT "dm2_db" // PostgreSQLデータベース名
#define ADAS_DEFAULT "ADAS" // ADAS-MAPを出力するディレクトリのパス
#define SYNO_DEFAULT 7 // 平面直角座標系指定 (n=1-19)
//#define ENABLE_TIME_MEASURE 1 // 実行時間測定用
/***********************************************************
*
* データベース形式ダイナミックマップ 静的マップデータ変換プログラム メイン関数 ver 1.1
* データベース形式ダイナミックマップの静的マップデータを読み込み、
* ベクタマップ(ADAS-MAP)へと変換して、Autowareに配信する
*
* input: args - コマンドライン引数
*#ifdef USE_DMLIB
* ・"-hn hostname" = DBシステム ホスト名指定 (default:localhost)
* ・"-pn portno" = DBシステム ポート番号指定 (default:9001)
*#else
* ・"-hn hostname" = PostgreSQLホスト名指定 (default:localhost)
* ・"-pn portno" = PostgreSQLポート番号指定 (default:5432)
* ・"-un username" = PostgreSQLユーザ名指定 (default:dm2)
* ・"-pw password" = PostgreSQLパスワード指定 (default:dm2)
* ・"-db database" = PostgreSQLデータベース名指定 (default:dm2_db)
*#endif
* ・"-sn" = 平面直角座標系指定 (n=1-19, default:7)
* ・"-pb" = 変換後Vectormap配信 (default:false)
* ・"-d" = デバッグログ出力 (debug.log, default:false)
* ・"-e" = エラーログ出力 (error.log, default:screen)
* ・"-h" = ヘルプ表示
* output: ADASディレクトリ - 変換したADAS-MAPファイルの出力ディレクトリ
* return: リターンコード
*
* author: N.Iwasaki @AXE corp.
* date written: 2018/Mar/22
* last modified: 2018/Mar/30
* Copyright 2018 AXE corp. All rights reserved.
***********************************************************/
int main(int argc, char *argv[])
{
bool bErrorFlg = false; // エラーログ出力フラグ
std::ofstream ofserr; // エラーログ出力ストリーム
std::streambuf *cerrSave;
std::string sHostName = HOST_DEFAULT; // DBシステム/PostgreSQL ホスト名
int iPortNo = PORT_DEFAULT; // DBシステム/PostgreSQL ポート番号
std::string sUserName = USER_DEFAULT; // PostgreSQL ユーザ名
std::string sPassword = PASS_DEFAULT; // PostgreSQL パスワード
std::string sDatabase = DTBS_DEFAULT; // PostgreSQL データベース名
int iSysNo = SYNO_DEFAULT; // 平面直角座標系
bool bPublishFlg = false; // ベクタマップ配信フラグ
const char *sKillCmd = "killall vector_map_loader > /dev/null 2>&1"; // ベクタマップ配信ROSノード停止コマンド
std::cout << "Harmoware-DMI static-dynamicmap converter ver 1.1: START" << std::endl;
#ifdef ENABLE_TIME_MEASURE
time_t timeStart = time(NULL);
#endif
// コマンド引数の解析
for(int i=1; i<argc; i++)
{
std::string option = argv[i];
if((option == "-HN") || (option == "-hn"))
{
// DBシステム/PostgreSQLホスト名指定
if(++i < argc)
sHostName = argv[i];
else
std::cerr << "WARNING:[main-01] missing host name" << std::endl;
}
else if((option == "-PN") || (option == "-pn"))
{
// DBシステム/PostgreSQLポート番号指定
if(++i < argc)
{
int ip = atoi(argv[i]);
if((ip >= 1024) && (ip <= 65535))
iPortNo = ip;
else
std::cerr << "WARNING:[main-02] illegal port number=" << std::string(argv[i]) << std::endl;
}
else
std::cerr << "WARNING:[main-03] missing port number" << std::endl;
}
else if((option == "-UN") || (option == "-un"))
{
// PostgreSQLユーザ名指定
if(++i < argc)
sUserName = argv[i];
else
std::cerr << "WARNING:[main-04] missing user name" << std::endl;
}
else if((option == "-PW") || (option == "-pw"))
{
// PostgreSQLパスワード指定
if(++i < argc)
sPassword = argv[i];
else
std::cerr << "WARNING:[main-05] missing password" << std::endl;
}
else if((option == "-DB") || (option == "-db"))
{
// PostgreSQLデータベース名指定
if(++i < argc)
sDatabase = argv[i];
else
std::cerr << "WARNING:[main-05] missing database" << std::endl;
}
else if(((option.substr(0, 2) == "-S") || (option.substr(0, 2) == "-s")) &&
(option.size() >= 3) && (option.size() <= 4))
{
// 平面直角座標系指定
int sn = atoi(option.c_str() + 2);
if((sn >= 1) && (sn <= 19))
{
iSysNo = sn;
std::cout << "DEBUG:[main] Plane rectangular coordinate system=" << sn << std::endl;
}
else
{
iSysNo = 1000;
std::cerr << "WARNING:[main-06] illegal coordinate system=" << sn << std::endl;
}
}
else if((option == "-PB") || (option == "-pb"))
{
// 変換後Vectormap配信
bPublishFlg = true;
std::cout << "DEBUG:[main] Publish vectormap" << std::endl;
}
else if((option == "-D") || (option == "-d"))
{
// デバッグログ出力
bDebugFlg = true;
std::cout << "DEBUG:[main] Debug log output to <debug.log>" << std::endl;
}
else if((option == "-E") || (option == "-e"))
{
// エラーログ出力
bErrorFlg = true;
std::cout << "DEBUG:[main] Error log output to <error.log>" << std::endl;
}
else if((option == "-H") || (option == "-h"))
{
// ヘルプメッセージ出力
std::cout
<< std::endl
<< "NAME" << std::endl
<< " hdmi_static_converter - translate from static dynamic-map to vectormap." << std::endl
<< std::endl
<< "SYNOPSIS" << std::endl
#ifdef USE_DMLIB
<< " hdmi_static_converter [-hn name] [-pn nnnn] [-sn] [pb] [-d] [-e] [-h]" << std::endl
#else
<< " hdmi_static_converter [-hn name] [-pn nnnn] [-un name] [-pw pass] [-db name] [-sn] [pb] [-d] [-e] [-h]" << std::endl
#endif
<< std::endl
<< "DESCRIPTION"
<< " translate from static dynamic-map to vectormap(ADAS-MAP)." << std::endl
<< std::endl
#ifdef USE_DMLIB
<< " -hn name set DBsystem hostname (default=localhost)" << std::endl
<< " -pn nnnn set DBsystem portnumber (default=9001)" << std::endl
#else
<< " -hn name set PostgreSQL hostname (default=localhost)" << std::endl
<< " -pn nnnn set PostgreSQL portnumber (default=5432)" << std::endl
<< " -un name set PostgreSQL username (default=dm2)" << std::endl
<< " -pw pass set PostgreSQL password (default=dm2)" << std::endl
<< " -db name set PostgreSQL database (default=dm2_db)" << std::endl
#endif
<< " -sn set Plane rectangular coordinate system (n=1-19, default=7)" << std::endl
<< " -pb publish vector map (default:false)" << std::endl
<< " -d output debug log to 'debug.log'. (default=none)" << std::endl
<< " -e output error log to 'error.log'. (default=console)" << std::endl
<< " -h display help(this) message." << std::endl
<< std::endl;
return 0;
}
else
{
std::cerr << "ERROR:[main-07] illegal option=" << option << std::endl;
return 1;
}
}
if(bDebugFlg)
{
// デバッグログ出力ストリームのオープン
ofsdbg.open("debug.log");
time_t timer = time(NULL);
ofsdbg << "DEBUG:[main] DEBUG LOG START at " << ctime(&timer) << std::endl;
}
if(bErrorFlg)
{
// エラーログ出力ストリームのオープン(エラー出力をコンソールからファイルに切り替え)
ofserr.open("error.log");
cerrSave = std::cerr.rdbuf();
std::cerr.rdbuf(ofserr.rdbuf());
time_t timer = time(NULL);
std::cerr << "DEBUG:[main] ERROR LOG START at " << ctime(&timer) << std::endl;
}
if(bPublishFlg)
{
// もしROSノードが起動していれば、ノードを停止
system(sKillCmd);
}
// 静的ダイナミックマップの読み込み
if(!readDmpData(sHostName, iPortNo, sUserName, sPassword, sDatabase, iSysNo))
{
std::cerr << "ERROR:[main-08] readDmpData()" << std::endl;
return -1;
}
// 地物データの再構築
if(!rebuildFeatureData())
{
std::cerr << "ERROR:[main-09] rebuildFeatureData()" << std::endl;
return -1;
}
// 関連データの再構築
if(!rebuildRelationshipData())
{
std::cerr << "ERROR:[main-10] rebuildRelationshipData()" << std::endl;
return -1;
}
#ifdef ENABLE_TIME_MEASURE
time_t timeRead = time(NULL);
#endif
// 静的ダイナミックマップの読み込みデータの確認表示
checkDmpData();
// 静的ダイナミックマップのデータをADAS-MAPのデータに変換
if(!tranDmpToAdas())
{
std::cerr << "ERROR:[main-11] tranDmpToAdas()" << std::endl;
return -1;
}
#ifdef ENABLE_TIME_MEASURE
time_t timeTrans = time(NULL);
#endif
// 変換したADAS-MAPの書き込み
if(!writeAdasMapFiles("ADAS"))
{
std::cerr << "ERROR:[main-12] writeAdasMapFiles()" << std::endl;
return -1;
}
#ifdef ENABLE_TIME_MEASURE
time_t timeWrite = time(NULL);
#endif
if(bPublishFlg)
{
// ベクタマップ配信ROSノード起動コマンドの作成
std::string sStartCmd; // 起動コマンド
std::string sCwd; // カレントディレクトリのパス
char sBuff[256];
getcwd(sBuff, sizeof(sBuff));
sCwd = std::string(sBuff);
sStartCmd = "rosrun map_file vector_map_loader";
if(!g_MpAdArea.empty())
sStartCmd += " '" + sCwd + "/ADAS/area.csv'";
if(!g_MpAdCrosswalk.empty())
sStartCmd += " '" + sCwd + "/ADAS/crosswalk.csv'";
if(!g_MpAdDtlane.empty())
sStartCmd += " '" + sCwd + "/ADAS/dtlane.csv'";
sStartCmd += " '" + sCwd + "/ADAS/idx.csv'";
if(!g_MpAdIntersection.empty())
sStartCmd += " '" + sCwd + "/ADAS/intersection.csv'";
if(!g_MpAdLane.empty())
sStartCmd += " '" + sCwd + "/ADAS/lane.csv'";
if(!g_MpAdLine.empty())
sStartCmd += " '" + sCwd + "/ADAS/line.csv'";
if(!g_MpAdNode.empty())
sStartCmd += " '" + sCwd + "/ADAS/node.csv'";
if(!g_MpAdPoint.empty())
sStartCmd += " '" + sCwd + "/ADAS/point.csv'";
if(!g_MpAdPole.empty())
sStartCmd += " '" + sCwd + "/ADAS/pole.csv'";
if(!g_MpAdPoledata.empty())
sStartCmd += " '" + sCwd + "/ADAS/poledata.csv'";
if(!g_MpAdRoadmark.empty())
sStartCmd += " '" + sCwd + "/ADAS/road_surface_mark.csv'";
if(!g_MpAdRoadedge.empty())
sStartCmd += " '" + sCwd + "/ADAS/roadedge.csv'";
if(!g_MpAdRoadsign.empty())
sStartCmd += " '" + sCwd + "/ADAS/roadsign.csv'";
if(!g_MpAdSidewalk.empty())
sStartCmd += " '" + sCwd + "/ADAS/sidewalk.csv'";
if(!g_MpAdSignaldata.empty())
sStartCmd += " '" + sCwd + "/ADAS/signaldata.csv'";
if(!g_MpAdStopline.empty())
sStartCmd += " '" + sCwd + "/ADAS/stopline.csv'";
if(!g_MpAdStreetlight.empty())
sStartCmd += " '" + sCwd + "/ADAS/streetlight.csv'";
if(!g_MpAdUtilitypole.empty())
sStartCmd += " '" + sCwd + "/ADAS/utilitypole.csv'";
if(!g_MpAdVector.empty())
sStartCmd += " '" + sCwd + "/ADAS/vector.csv'";
if(!g_MpAdWhiteline.empty())
sStartCmd += " '" + sCwd + "/ADAS/whiteline.csv'";
sStartCmd += " > /dev/null 2>&1 &";
//std::cerr << "DEBUG:[main] sStartCmd=" << sStartCmd << std::endl;
// 変換したADAS-MAPの配信
int iret;
if((iret = system(sStartCmd.c_str())))
std::cerr << "WARNING:[main-13] system(sStartCmd), iret=" << iret << std::endl;
}
#ifdef ENABLE_TIME_MEASURE
time_t timePblsh = time(NULL);
#endif
if(bErrorFlg)
{
// エラーログ出力ストリームのクローズ
std::cerr.rdbuf(cerrSave);
ofserr.close();
}
if(bDebugFlg)
{
// デバッグログ出力ストリームのクローズ
ofsdbg.close();
}
#if ENABLE_TIME_MEASURE
std::cout << "DEBUG:[main] timeRead=" << timeRead - timeStart
<< ", timeTrans=" << timeTrans - timeRead
<< ", timeWrite=" << timeWrite - timeTrans
<< ", timePblsh=" << timePblsh - timeWrite
<< ", timeTotal=" << timePblsh - timeStart << std::endl;
#endif
std::cout << std::endl << "Harmoware-DMI static-dynamicmap converter: END" << std::endl;
return 0;
}
|
#include "TTree.h"
#include "TSystem.h"
#include "TFile.h"
#include "TLorentzVector.h"
#include "math.h"
#include "iostream"
#include "FWCore/FWLite/interface/AutoLibraryLoader.h"
#include "DataFormats/FWLite/interface/Handle.h"
#include "DataFormats/FWLite/interface/Event.h"
#include "DataFormats/Common/interface/EDProductGetter.h"
#include "SimDataFormats/GeneratorProducts/interface/LHEEventProduct.h"
void read_lhe_WZ()
{
clock_t begin = clock();
gSystem->Load("libFWCoreFWLite.so");
AutoLibraryLoader::enable();
gSystem->Load("libDataFormatsFWLite.so");
TFile file("Input/lhe_WZ.root");
fwlite::Event ev(&file);
TFile * outfile = TFile::Open("Input/WZatgc_tree.root","RECREATE");
TTree * tree = new TTree("tree","tree");
double MWW_tree, DPhi_MET_tree, DPhi_Wlep_tree, zhadpt_tree, wleppt_tree, deltaR_tree,mfatjet;
int channel_tree;
std::vector<double> atgc_weights_tree;
tree->Branch("MWW",&MWW_tree);
tree->Branch("weight",&atgc_weights_tree);
tree->Branch("deltaPhi_WjetMet",&DPhi_MET_tree);
tree->Branch("jet_pt",&zhadpt_tree);
tree->Branch("W_pt",&wleppt_tree);
tree->Branch("deltaR_LeptonWJet",&deltaR_tree);
tree->Branch("deltaPhi_WJetWlep",&DPhi_Wlep_tree);
tree->Branch("channel",&channel_tree);
tree->Branch("mfatjet",&mfatjet);
int n_events = 0, n_used = 0, n_el = 0, n_mu = 0, corr_ev = 0, twolep = 0;
int n_tot = tree->GetEntries();
for( ev.toBegin(); ! ev.atEnd(); ++ev)
{
bool keep_Event = true;
fwlite::Handle<LHEEventProduct> lhe;
//now can access data
lhe.getByLabel(ev,"source");
TLorentzVector wz, wlep, elvector, muvector, nelvector, nmuvector;
int nzhad = 0, nlep = 0, nv = 0, zhadID = -1000, channel = -1;
double delphi_met = 0, delphi_lep, delR = 0;
if(lhe.product()->weights().size()!=150)
{
//std::cout<<"only "<<weights.size()<<" weights!"<<std::endl;
corr_ev++;
keep_Event = false;
continue;
}
n_events++;
for(int i = 0; i < lhe->hepeup().NUP; i++)
{
//W+-,Z
if(abs(lhe->hepeup().IDUP[i]) == 24 or abs(lhe->hepeup().IDUP[i]) == 23)
{
nv++;
TLorentzVector wvector( lhe->hepeup().PUP[i][0],
lhe->hepeup().PUP[i][1],
lhe->hepeup().PUP[i][2],
lhe->hepeup().PUP[i][3]);
wz += wvector;
}
//el+-
if(abs(lhe->hepeup().IDUP[i])==11)
{
nlep++;
channel = 1;
int motherID = lhe->hepeup().MOTHUP[i].first -1;
if(abs(lhe->hepeup().IDUP[motherID])!=24)
keep_Event = false;
TLorentzVector elvector_tmp(lhe->hepeup().PUP[i][0],
lhe->hepeup().PUP[i][1],
lhe->hepeup().PUP[i][2],
lhe->hepeup().PUP[i][3]);
elvector += elvector_tmp;
if(abs(elvector.PseudoRapidity()) > 2.5 or elvector.Pt() < 50)
keep_Event = false;
wlep += elvector;
}
//mu+-
if(abs(lhe->hepeup().IDUP[i])==13)
{
nlep++;
channel = 2;
int motherID = lhe->hepeup().MOTHUP[i].first -1;
if(abs(lhe->hepeup().IDUP[motherID])!=24)
keep_Event = false;
TLorentzVector muvector_tmp(lhe->hepeup().PUP[i][0],
lhe->hepeup().PUP[i][1],
lhe->hepeup().PUP[i][2],
lhe->hepeup().PUP[i][3]);
muvector += muvector_tmp;
if(abs(muvector.PseudoRapidity()) > 2.1 or muvector.Pt() < 50)
keep_Event = false;
wlep += muvector;
}
//tau+-
if(abs(lhe->hepeup().IDUP[i])==15)
{
nlep++;
keep_Event = false;
}
//n_el
if(abs(lhe->hepeup().IDUP[i])==12)
{
TLorentzVector nelvector_tmp(lhe->hepeup().PUP[i][0],
lhe->hepeup().PUP[i][1],
lhe->hepeup().PUP[i][2],
lhe->hepeup().PUP[i][3]);
nelvector += nelvector_tmp;
if(nelvector.Pt() < 80)
keep_Event = false;
wlep += nelvector;
}
//n_mu
if(abs(lhe->hepeup().IDUP[i])==14)
{
TLorentzVector nmuvector_tmp(lhe->hepeup().PUP[i][0],
lhe->hepeup().PUP[i][1],
lhe->hepeup().PUP[i][2],
lhe->hepeup().PUP[i][3]);
nmuvector += nmuvector_tmp;
if(nmuvector.Pt() < 40)
keep_Event = false;
wlep = wlep + nmuvector;
}
//z_had
if(abs(lhe->hepeup().IDUP[i]) < 7)
{
int motherID = lhe->hepeup().MOTHUP[i].first - 1;
if(abs(lhe->hepeup().IDUP[motherID])==23 and motherID!=zhadID)
{
nzhad++;
zhadID = motherID;
}
}
}
TLorentzVector zhad(lhe->hepeup().PUP[zhadID][0],
lhe->hepeup().PUP[zhadID][1],
lhe->hepeup().PUP[zhadID][2],
lhe->hepeup().PUP[zhadID][3]);
if(nv != 2) //or nlep != 1 or nzhad != 1)
std::cout << "something went wrong! (-> nv,nlep,zwhad)" << "(" << nv << " , " << nlep << " , " << nzhad << ")" << std::endl;
if(nlep != 1)
{
twolep++;
keep_Event = false;
}
if(wz.M() < 600. or wz.M() > 3500.)
keep_Event = false;
if(keep_Event)
{
if(channel == 1)
{
delphi_met = nelvector.DeltaPhi(zhad);
delR = elvector.DeltaR(zhad);
}
if(channel == 2)
{
delphi_met = nmuvector.DeltaPhi(zhad);
delR = muvector.DeltaR(zhad);
}
delphi_lep = wlep.DeltaPhi(zhad);
if(wlep.Pt() > 200. and zhad.Pt() > 200. and abs(zhad.PseudoRapidity()) < 2.4 and delR > M_PI/2. and abs(delphi_lep) > 2. and abs(delphi_met) > 2.)
{
n_used++;
std::vector <double> weights;
int n_weights = lhe.product()->weights().size();
for(int i = 0; i < n_weights; i++)
{
double weight = lhe->weights()[i].wgt;
weights.push_back(weight);
}
atgc_weights_tree = weights;
MWW_tree = wz.M();
DPhi_MET_tree = delphi_met;
DPhi_Wlep_tree = delphi_lep;
zhadpt_tree = zhad.Pt();
wleppt_tree = wlep.Pt();
deltaR_tree = delR;
channel_tree = channel;
mfatjet = zhad.M();
tree->Fill();
}
}
if(n_events%50000==0)
std::cout << n_used << " / " << n_events << " , corrupted events: " << corr_ev << std::endl;
if(n_events==2000000)
break;
}
tree->Write();
std::cout << n_used << " events used "<< std::endl;
std::cout<<twolep<<" events with 2 leptons"<<std::endl;
exit(0);
}
|
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
/*
vector<int> vec;
if(nums.empty()) {
return vec;
}
sort(nums.begin(), nums.end());
for(int i = 1; i < nums[0]; i++) {
vec.push_back(i);
}
for(int i = 0; i < nums.size() - 1; i++) {
if((nums[i+1] - nums[i]) <= 1) {
continue;
}
for(int dif = 1; dif < (nums[i+1] - nums[i]); dif++) {
vec.push_back(nums[i] + dif);
}
}
for(int num = nums[nums.size() - 1] + 1; num <= nums.size(); num++) {
vec.push_back(num);
}
return vec;
*/
for(int i = 0; i < nums.size(); i++) {
int index = abs(nums[i]) - 1;
nums[index] = 0 - abs(nums[index]);
}
vector<int> vec;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] > 0) {
vec.push_back(i+1);
}
}
return vec;
}
};
|
#include <iostream>
using namespace std;
void merge(int arr[], int left, int middel, int right)
{
int i = left; //starting index for left subarray
int j = middel + 1; //starting index for right subarray
int k = left; //starting index for temp array
int temp[5]; //tempArray
while (i <= middel && j <= right)
{
if (arr[i] <= arr[j])
{
temp[k] = arr[i];
i++;
k++;
}
else
{
temp[k] = arr[j];
j++;
k++;
}
}
while (i <= middel)
{
temp[k] = arr[i];
i++;
k++;
}
while (j <= right)
{
temp[k] = arr[j];
j++;
k++;
}
for (int s = left; s <= right; s++)
{
arr[s] = temp[s];
}
}
void mergeSort(int arr[], int left, int right)
{
if (left < right)
{
int middel = (left + right) / 2;
mergeSort(arr, left, middel);
mergeSort(arr, middel + 1, right);
merge(arr, left, middel, right);
}
}
int main()
{
int myArray[5];
cout << "Enter the 5 Elements" << endl;
for (int i = 0; i < 5; i++)
{
cin >> myArray[i];
}
cout << "Before Sorting" << endl;
for (int j = 0; j < 5; j++)
{
cout << myArray[j] << " ";
}
mergeSort(myArray, 0, 4);
cout << endl;
cout << "After Sorting Sorting" << endl;
for (int j = 0; j < 5; j++)
{
cout << myArray[j] << " ";
}
return 0;
}
|
//
// Created by aleksey on 18.04.2019.
//
#pragma once
#include <G4VModel.hh>
#include <G4VGraphicsScene.hh>
#include <G4TransportationManager.hh>
#include <G4Field.hh>
#include <G4FieldManager.hh>
#include <G4Colour.hh>
#include <G4VisAttributes.hh>
#include <G4Polyline.hh>
#include <G4ArrowModel.hh>
class MyElectricFieldModel : public G4VModel {
public:
enum Representation {fullArrow, lightArrow};
MyElectricFieldModel(G4int fNDataPointsPerMaxHalfScene = 5,
const Representation &fRepresentation = Representation::fullArrow,
G4int fArrow3DLineSegmentsPerCircle = 6);
virtual ~MyElectricFieldModel();
void DescribeYourselfTo(G4VGraphicsScene &scene) override;
private:
MyElectricFieldModel (const MyElectricFieldModel&);
MyElectricFieldModel& operator = (const MyElectricFieldModel&);
G4int fNDataPointsPerMaxHalfScene;
Representation fRepresentation;
G4int fArrow3DLineSegmentsPerCircle;
};
|
//
// Fish.cpp
// GetFish
//
// Created by zs on 14-12-8.
//
//
#include "Fish.h"
#include "Common.h"
#include "Tools.h"
#include "AudioController.h"
//#include "FishingPlayLayer.h"
Fish* Fish::create(int type,float speed , int dir ,const char* name)
{
Fish* fish = new Fish();
if(fish && fish->init(type,speed , dir, name)) {
fish->autorelease();
return fish;
}
CC_SAFE_DELETE(fish);
return NULL;
}
Fish::Fish():_deadType(EXIT_MAP_DEAD),_volume(1),_aY(0),_isDead(false),_exitDead(EXIT_DEAD_NORMAL),_startX(0),_startY(0),_stayTime(0),_tortoiseC(0),_deadTime(0),_changeTime(0),_shipID(-1),_score(1)
{
}
Fish::~Fish()
{
}
bool Fish::init(int type,float speed , int dir ,const char* name)
{
if(Actor::init(name)) {
_screenSize = CCDirector::sharedDirector()->getWinSize();
_id = type;
setSpeed(speed,0);
_dir = dir;
this->initData();
setState(ACT_STATE_WALK);
return true;
}
return false;
}
void Fish::initData()
{
if (_dir==DIR_RIGHT) {
playWithIndex(ANIM_RIGHT);
_x =-getBodyRect().size.width/2+1;
} else {
playWithIndex(ANIM_LEFT);
_x =_screenSize.width+getBodyRect().size.width/2-1;
}
this->_y = Tools::randomFloatInRange( _screenSize.height-this->FISH_Y_MIN-50,this->FISH_Y_MAX);
this->setPosition(ccp(_x, _y));
if (getBone("data_1")) {
setScore(getBone("data_1")->getWorldInfo()->x) ;
}
}
void Fish::cycle(float delta)
{
if (_state == STATE_DEAD) {
return;
}
switch (_exitDead) {
case EXIT_DEAD_NORMAL:
if (isExitMap()) {
setDead(true);
}
break;
case EXIT_DEAD_LEFT:
if (isExitMapLeft()) {
setDead(true);
}
break;
case EXIT_DEAD_RIGHT:
if (isExitMapRight()) {
setDead(true);
}
break;
default:
if (isExitMap()) {
setDead(true);
}
break;
}
switch (_state) {
case ACT_STATE_GO:
case ACT_STATE_DOLPHIN_ATK:
case ACT_STATE_WALK:
if (getType() == SWORDFISH) {
_changeTime--;
if (_changeTime==0) {
_speedx=2*_speedx;
}
}
if(_dir == DIR_RIGHT){
_x +=_speedx;
}else{
_x -=_speedx;
}
setSharkAnim();
break;
case ACT_STATE_TURN:
_speedy-=2;
_x -= 6.0f;
_y += _speedy;
// if (_speedy <0 && _y <= _screenSize.height - FishingPlayLayer::_kegY) {
// _y = _screenSize.height - FishingPlayLayer::_kegY;
// setDead(true);
// }
break;
case ACT_STATE_DOLPHIN_READY:
if (!getAnimation()->getIsPlaying()) {
setState(ACT_STATE_DOLPHIN_ATK);
setSpeedX(20);
this->setAnim(ANIM_ATK);
AUDIO->playSfx("music/da");
}
break;
case ACT_STATE_LIGHT_READY:
if (!getAnimation()->getIsPlaying()) {
setState(ACT_STATE_LIGHT);
this->setAnim(6);
}
break;
case ACT_STATE_LIGHT:
if (!getAnimation()->getIsPlaying()) {
this->setAnim(0);
setGo();
}
break;
case ACT_STATE_TORTOISE_READY:
if (!getAnimation()->getIsPlaying()) {
setState(ACT_STATE_TORTOISE);
this->setAnim(6);
setTortoiseC(3);
int r = Tools::randomIntInRange(0, 3);
if (r==0) {
setSpeed(15, -10);
}else if(r == 1){
setSpeed(-15, 10);
}else if(r == 2){
setSpeed(15, 10);
}else{
setSpeed(-15, -10);
}
}
break;
case ACT_STATE_TORTOISE:
_x +=_speedx;
_y +=_speedy;
if (_x > _screenSize.width-getBodyRect().size.width/2 && _tortoiseC > 0) {
_tortoiseC--;
AUDIO->playSfx("music/tortoiseattack");
_x = _screenSize.width-getBodyRect().size.width/2;
_speedx = -_speedx;
}
if (_x < getBodyRect().size.width/2 && _tortoiseC > 0) {
_tortoiseC--;
AUDIO->playSfx("music/tortoiseattack");
_x = getBodyRect().size.width/2;
_speedx = -_speedx;
}
if (_y < 50) {
_tortoiseC--;
AUDIO->playSfx("music/tortoiseattack");
_y = 50;
_speedy = -_speedy;
}
if (_y > _screenSize.height-this->FISH_Y_MIN) {
_tortoiseC--;
AUDIO->playSfx("music/tortoiseattack");
_y = _screenSize.height-this->FISH_Y_MIN;
_speedy = -_speedy;
}
setTortoiseR();
break;
case ACT_STATE_GOTOSHIP:
_x = getPositionX();
_y = getPositionY();
if (this->numberOfRunningActions()==0) {
setState(ACT_STATE_ZHUANG_STAY);
_stayTime = 40;
setAnim(Fish::ANIM_ATK_READY);
}
break;
case ACT_STATE_ZHUANG_STAY:
// _stayTime--;
// if (_stayTime<=0) {
if (getAnimation()->getIsComplete()) {
setDes(_startX,_startY,2);
setState(ACT_STATE_ZHUANG_END);
setAnim(Fish::ANIM_RIGHT);
}
break;
case ACT_STATE_ZHUANG_END:
_x = getPositionX();
_y = getPositionY();
if (this->numberOfRunningActions()==0) {
setState(ACT_STATE_WALK);
// CCLOG("end???");
}
break;
case ACT_STATE_ZHUANG_ATK:
if (getAnimation()->getIsComplete()) {
setDes(_startX,_startY,2);
setState(ACT_STATE_ZHUANG_END);
setAnim(0);
}
break;
case ACT_STATE_HAN_UP:
if (getDir() == DIR_LEFT) {
_x -= 7;
} else {
_x += 7;
}
_speedy -= _aY;
_y += _speedy;
if (getDir() == DIR_LEFT) {
if (getRotation() == 90 && _speedy<0) {
setRotation(-90);
AUDIO->playSfx("music/pb");
}
}else{
if (getRotation() == -90 && _speedy<0) {
setRotation(90);
AUDIO->playSfx("music/pb");
}
}
if (_y <= _oldy) {
_y = _oldy;
setSpeedY(0);
setRotation(0);
setAnim(ANIM_RIGHT);
setState(ACT_STATE_WALK);
}
break;
case ACT_STATE_HAN_ATK:
_deadTime--;
if (_deadTime<=0) {
setDead(true);
}
break;
case ACT_STATE_DEN:
if(_dir == DIR_RIGHT){
_x +=15;
}else{
_x -=15;
}
break;
case ACT_STATE_SHOCK:
_stayTime--;
if (_stayTime<0) {
setGo();
setAnim(ANIM_RIGHT);
}
break;
case ACT_STATE_FALL:
_y -=15;
if (_y<_screenSize.height-this->FISH_Y_MIN-30) {
setGo();
}
break;
default:
break;
}
this->setPosition(ccp(_x, _y));
}
void Fish::setSpeed(float spdx, float spdy)
{
setSpeedX(spdx);
setSpeedY(spdy);
}
bool Fish::isExitMap()
{
float dx = 0;
if (isStrong()) {
dx = 100;
}
return ((this->getPositionX() + getBodyRect().size.width/2) < -dx || this->getPositionX()- getBodyRect().size.width/2> _screenSize.width+dx);
}
bool Fish::isExitMapLeft()
{
float dx = 0;
if (isStrong()) {
dx = 100;
}
return ((this->getPositionX() + getBodyRect().size.width/2) < -dx);
}
bool Fish::isExitMapRight()
{
float dx = 0;
if (isStrong()) {
dx = 100;
}
return (this->getPositionX()- getBodyRect().size.width/2> _screenSize.width+dx);
}
//void Fish::draw()
//{
//// ccDrawColor4B(0xff, 0xff, 0xff, 0);
//// glLineWidth(1.0f);
////
//// CCRect*rect =_anim->bodyRectInWorld();
////
//// ccDrawRect(ccp(rect->origin.x, rect->origin.y), ccp(rect->origin.x+rect->size.width, rect->origin.y+rect->size.height));
////
////// ccDrawColor4B(0x00, 0x00, 0x00, 0);
////// glLineWidth(1.0f);
//// rect =_anim->attackRectInWorld();
////
//// ccDrawRect(ccp(rect->origin.x, rect->origin.y), ccp(rect->origin.x+rect->size.width, rect->origin.y+rect->size.height));
//
//}
bool Fish::isFishDead()
{
return _isDead||_state == STATE_DEAD;
}
bool Fish::isState(int state)
{
return _state == state;
}
void Fish::setState(int state)
{
_state = state;
}
void Fish::setShipID(int id)
{
_shipID = id;
}
bool Fish::isCanHooked() {
// return _state == ACT_STATE_NORMAL || _state == ACT_STATE_WALK || _state == ACT_STATE_GO || _state == ACT_STATE_GO_TIME || _state == ACT_STATE_GO_TIME_DOWN;
return _state != ACT_STATE_HOOKED&&_state != ACT_STATE_FALL&&_state != ACT_STATE_FALLRUN&&_state != ACT_STATE_DEAD&&_state !=ACT_STATE_HAN_UP&&_state !=ACT_STATE_HAN_ATK;
}
bool Fish::isHooked() {
if (isCanHooked()) {
playWithIndex(ANIM_HOOK);
_state = ACT_STATE_HOOKED;
return true;
}
return false;
}
bool Fish::issetXY() {
return _state == ACT_STATE_HOOKED || _state == ACT_STATE_ESCAPE;
}
int Fish::getShipID()
{
return _shipID;
}
void Fish::setDead(bool isdead)
{
_isDead = isdead;
if (_isDead) {
setState(STATE_DEAD);
}
}
void Fish::setSpeedX(float sx)
{
_speedx = sx;
}
void Fish::setSpeedY(float sy)
{
_speedy = sy;
}
int Fish::getVolume()
{
return _volume;
}
void Fish::setXY(float x,float y)
{
_x = x;
_y = y;
setPosition(ccp(_x, _y));
}
void Fish::setTurn()
{
}
bool Fish::isNormalFish()
{
return _id<=NORMAL_E;
}
bool Fish::isDolphin()
{
return _id == DOLPHIN;
}
bool Fish::isLightFish()
{
return _id == LIGHTFISH;
}
bool Fish::isTortoise()
{
return _id == TORTOISE;
}
void Fish::setAnim(int anim)
{
if (anim != ANIM_HOOK && anim != ANIM_TURN && _dir == DIR_LEFT) {
anim++;
}
playWithIndex(anim);
}
int Fish::getID()
{
return _id;
}
bool Fish::isUseFish()
{
return isDolphin() || isLightFish() || isTortoise();
}
bool Fish::isHook()
{
return _state == ACT_STATE_HOOKED || _state == ACT_STATE_ESCAPE;
}
bool Fish::isShark()
{
return _id == SHARK;
}
bool Fish::isSword()
{
return _id == SWORDFISH;
}
bool Fish::isStrong()
{
return _id == STRONGFISH;
}
bool Fish::isEle()
{
return _id == ELEFISH;
}
void Fish::setGo()
{
_exitDead = EXIT_DEAD_NORMAL;
if (_y>_screenSize.height-this->FISH_Y_MIN) {
setState(ACT_STATE_FALL);
}else{
_state = ACT_STATE_GO;
setSpeedX(20);
setAnim(ANIM_RIGHT);
getAnimation()->setSpeedScale(1.5);
}
}
void Fish::setTortoiseC(int c)
{
_tortoiseC = c;
}
void Fish::setTortoiseR()
{
if (_speedx < 0) {
if (getCurrentMovementID()!="Animation8") {
playWithIndex(7);
}
if (_speedy < 0) {
setRotation(-30);
} else {
setRotation(30);
}
} else {
if (getCurrentMovementID()!="Animation7") {
playWithIndex(6);
}
if (_speedy < 0) {
setRotation(30);
} else {
setRotation(-30);
}
}
}
bool Fish::isWhale()
{
return _id == WHALE;
}
bool Fish::isEat()
{
return _id == EATFISH;
}
int Fish::getDir()
{
return _dir;
}
float Fish::getX()
{
return _x;
}
float Fish::getY()
{
return _y;
}
void Fish::setStartPos(float x,float y)
{
_startX = x;
_startY = y;
}
void Fish::setDes(float desX,float desY, float time)
{
// if (_dir == DIR_RIGHT) {
// if (_x > desX) {
// _dir = DIR_LEFT;
//
// setAnim(_anim->getCurAnimationIndex());
//
// }
// } else {
// if (_x < desX) {
// _dir = DIR_RIGHT;
//
// setAnim(_anim->getCurAnimationIndex());
// }
// }
CCMoveTo* move = CCMoveTo::create(time, ccp(desX, desY));
this->runAction(move);
}
void Fish::setOLDY(float y)
{
_oldy = y;
}
void Fish::setAY(float a)
{
_aY = a;
}
float Fish::getSpeedY() const
{
return _speedy;
}
void Fish::setDeadTime(float time)
{
_deadTime = time;
}
int Fish::getType() const
{
return _id;
}
void Fish::setDeadType(int type)
{
_deadType = type;
}
void Fish::setSharkAnim()
{
if (_id == SHARK&&(getCurrentMovementID()=="Animation8"||getCurrentMovementID()=="Animation7")&&getAnimation()->getIsComplete()) {
setAnim(ANIM_RIGHT);
}
}
void Fish::setChangeTime(float time)
{
_changeTime = time;
}
void Fish::setStayTime(float time)
{
_stayTime = time;
}
int Fish::getDeadType() const
{
return _deadType;
}
void Fish::setExitDeadType(int type)
{
_exitDead = type;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;
#define MAX_NA 53
#define MAX_NB 53
class FoxPlayingGame {
public:
double
theMax(int nA, int nB, int paramA, int paramB)
{
double mx[MAX_NB][MAX_NA],mn[MAX_NB][MAX_NA];
memset(mx, 0, MAX_NA*MAX_NB);
memset(mn, 0, MAX_NA*MAX_NB);
double sa = paramA/1000.0;
double sb = paramB/1000.0;
for (int a=1; a<=nA; ++a) {
mx[0][a] = mx[0][a-1] + sa;
mn[0][a] = mn[0][a-1] + sa;
}
for (int a=1; a<=nA; ++a) {
for (int b=1; b<=nB; ++b) {
mx[b][a] = max(max(mx[b-1][a]*sb,mx[b][a-1]+sa),max(mn[b-1][a]*sb, mn[b][a-1]+sa));
mn[b][a] = min(min(mx[b-1][a]*sb,mx[b][a-1]+sa),min(mn[b-1][a]*sb, mn[b][a-1]+sa));
}
}
return mx[nB][nA];
}
};
|
/* This Simulator cited from Prof. Demko's Simulator.h
* I have changed the class Halton, HaltonGBM, EulerMarayama
* This file generates random number and simulates stochastic process
*/
#ifndef __SIMULATOR_H_
#define __SIMULATOR_H_
#include <cmath>
#include <ctime>
#include <string>
#include "mt19937ar.h"
#include "BoxMuller.h"
#include "./tnt/tnt.h"
//#include "./jama125/jama_cholesky.h"
//using namespace JAMA;
//using namespace TNT;
class Simulator{
public:
virtual double operator()(void)= 0; // argument gives step size
virtual void Seed(unsigned long int) = 0; // initializes RNG
virtual void Seed() = 0;
virtual void Skip(int) = 0; // goes through several simulations;
};
class Mersenne:public Simulator{
public:
Mersenne(){Seed();}
Mersenne(unsigned long s){Seed(s);}
void Seed(unsigned long s){ init_genrand(s);}
void Seed(){ init_genrand(0x13579bdf);}
void Skip(int n){ for(int i =0; i< n; ++i) genrand_real3();}
double operator()(){return genrand_real3();}
};
class Box_Muller:public Mersenne{
public:
Box_Muller():Mersenne(){}
Box_Muller(unsigned long s):Mersenne(s){}
double operator()(){return genrand_std_normal();}
};
class Milstein:public Box_Muller
{
double spot; // initial price
double spot2; // the second initial price
double drift; // drift
double drift2;
double sigma; // initial diffusion
double sigma2;
double dT; // delta t
double lamda;
double theta;
double theta2;
double yita;
int NumSteps;
double det; // dt*drift
double det2;
// constant term for milstein methods
double cons_yita;
double cons_theta;
double cons_theta2;
double cons_lamda;
public:
Milstein(double sp, double d, double s, double dt, double lmd, double thet, double yta, int N):Box_Muller(), spot(sp), drift(d), sigma(s), dT(dt), lamda(lmd), theta(thet), yita(yta), NumSteps(N)
{
det = dT * drift;
cons_yita = yita / 2.0 * sqrt(dT);
cons_lamda = lamda * dT;
cons_theta = lamda * theta * dT - yita * yita / 4.0 * dT;
}
Milstein(double sp, double ru, double d, double d2, double s, double s2, double dt, double lmd, double thet, double thet2, double yta, int N):Box_Muller(), spot(sp), spot2(ru), drift(d), drift2(d2), sigma(s), sigma2(s2), dT(dt), lamda(lmd), theta(thet), theta2(thet2), yita(yta), NumSteps(N)
{
det = dT * drift; // for S&P 500
det2 = dT * drift2; // for Russel 2000
cons_yita = yita / 2.0 * sqrt(dT);
cons_lamda = lamda * dT;
cons_theta = lamda * theta * dT - yita * yita / 4.0 * dT; // for S&P 500
cons_theta2 = lamda * theta2 * dT - yita * yita / 4.0 * dT; // for Russel 2000
}
double operator ()()
{
double x = spot;
double vol = sigma;
for(int i = 0; i < NumSteps; i++)
{
double z1 = genrand_std_normal();
x *= 1 + det + sqrt(vol*dT) * z1;
double z2 = genrand_std_normal();
double temp = sqrt(vol) + cons_yita * z2;
vol = temp * temp - cons_lamda * vol + cons_theta;
}
return x;
}
double operator()(TNT::Array2D<double> C)
{
double x1 = spot; // S&P 500 initial spot price
double x2 = spot2; // Russel 2000 initial spot price
double vol1 = sigma; // S&P 500 initial variance
double vol2 = sigma2; // Russel 2000 initial variance
int dim = C.dim1();
for(int i = 0; i < NumSteps; i++)
{
double *NormPhi = new double [dim];
double *NormRand = new double [dim];
for(int i = 0; i < dim; i++)
{
NormRand[i] = genrand_std_normal();
NormPhi[i] = 0.0;
}
for(int i = 0; i < dim; i++)
{
for(int j = 0; j < dim; j++)
{
NormPhi[i] += C[i][j] * NormRand[j];
}
}
x1 *= 1 + det +sqrt(vol1 * dT) * NormPhi[0];
x2 *= 1 + det2 + sqrt(vol2 * dT) * NormPhi[1];
double temp1 = sqrt(vol1) + cons_yita * NormPhi[2];
vol1 = temp1 * temp1 - cons_lamda * vol1 + cons_theta;
double temp2 = sqrt(vol2) + cons_yita * NormPhi[3];
vol2 = temp2 * temp2 - cons_lamda * vol2 + cons_theta2;
delete [] NormPhi;
delete [] NormRand;
}
return (x1 + x2) / 2.0;
}
};
#endif
|
#include<iostream>
using namespace std;
struct Date{
int d,m,y;
};
const int monthDays[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int leapYearCount(Date d){
int years = d.y;
if(d.m<=2)
years--;
return (years/4) - (years/100) + (years/400);
}
int getDifference(Date d1,Date d2){
int n1=0,n2=0;
n1=d1.y*365+d1.d;
for(int i=0;i<d1.m;i++){
n1+=monthDays[i];
}
n1+=leapYearCount(d1);
n2=d2.y*365+d2.d;
for(int i=0;i<d2.m;i++){
n2+=monthDays[i];
}
n2+=leapYearCount(d2);
return n2-n1;
}
int main(){
Date d1= {10, 2, 2014};
Date d2= {10, 3, 2015};
cout << "Difference between two dates is " << getDifference(d1, d2)<<endl;
return 0;
}
|
#include "string.h"
#include <cstring>
String::String()
{
data = new char[1];
*data='\0';
size=0;
}
String::String(int n,char c)
{
data=new char[n+1];
size=n;
char *tmp=data;
while(n--)
{
*tmp++=c;
}
*tmp='\0';
}
String::String(const char *source)
{
if(source==NULL)
{
data=new char[1];
*data='\0';
size=0;
}
else
{
size=strlen(source);
data=new char[size+1];
strcpy(data,source);
}
}
String::String(const String &obj)
{
data=new char[obj.size+1];
strcpy(data,obj.data);
size=obj.size;
}
String & String::operator = (char *s)
{
if(data!=NULL)
{
delete [] data;
}
size=strlen(s);
data=new char[strlen(s)+1];
strcpy(data,s);
return *this;
}
String & String::operator=(const String &s)
{
if(this==&s)
{
return *this;
}
if(data!=NULL)
{
delete [] data;
}
size=s.size;
data=new char[s.size+1];
strcpy(data,s.data);
return *this;
}
String::~String()
{
if(data!=NULL)
{
delete [] data;
data=NULL;
size=0;
}
}
char &String::operator [] (int i)
{
return data[i];
}
const char &String::operator [] (int i) const
{
return data[i];
}
String &String::operator+=(const String& s)
{
int len=size+s.size+1;
char *tmp=data;
data=new char[len];
strcpy(data,tmp);
strcat(data,s.data);
size=len-1;
delete [] tmp;
return *this;
}
String & String::operator+=(const char *s)
{
if(s==NULL)
{
return *this;
}
char *tmp=data;
int len =size+strlen(s)+1;
data=new char[len];
size=len-1;
strcpy(data,tmp);
strcat(data,s);
delete [] tmp;
return *this;
}
ostream &operator<<(ostream &out,String &s)
{
for(int i=0;i<s.size;i++)
{
out<<s[i]<<" ";
}
return out;
}
|
/*********************************************************************
** Author: Chris Matian
** Date: 07/20/2017
** Description: This is the class specification file for Box which contains all of the early declarations used in Box.cpp
*********************************************************************/
// Class specification file.
#ifndef BOX_HPP
#define BOX_HPP
//Box class declaration
class Box {
private:
// Variable Declarations
double height;
double width;
double length;
public:
// Constructor Prototypes
Box();
Box(double, double, double);
// Function Prototypes
double setHeight(double);
double setWidth(double);
double setLength(double);
double calcVolume();
double calcSurfaceArea();
};
#endif
|
#pragma once
#include <iostream>
#include "Vector3.h"
#include "Results.h"
using namespace std;
class AABB
{
private:
Vector3D<float> Min;
Vector3D<float> Max;
public:
AABB(const Vector3D<float>&, const Vector3D<float>&);
Vector3D<float> GetMin() const noexcept;
Vector3D<float> GetMax() const noexcept;
Result Intersect(const AABB&) noexcept;
};
|
#include "InputParserForTraining.h"
namespace Train {
InputParserForTraining::~InputParserForTraining() {
cout << "destructor of InputParserForTraining called" << endl;
int length = AM->length();
for (int i=0; i<length; i++) {
map<UID, FriendsMap*> curRow = AM->getRow(i);
for (map<UID, FriendsMap*>::iterator j=curRow.begin(); j!=curRow.end(); j++) {
FriendsMap* curElement = j->second;
delete curElement;
}
}
delete AM;
while (freeTuples != NULL) {
ActionLogTuple* temp = freeTuples;
freeTuples = freeTuples->next;
delete temp;
}
cout << "memory in AM released, mem: " << getCurrentMemoryUsage() << endl;
}
InputParserForTraining::InputParserForTraining(AnyOption* opt1) {
opt = opt1;
phase = strToInt(opt->getValue("phase"));
int computeUserInf = strToInt(opt->getValue("computeUserInf"));
if (computeUserInf == 0) {
graphFile = opt->getValue("graphFile");
cout << "graphFile = " << graphFile << endl;
}
actionsFile = opt->getValue("actionsFile");
dynamicFG = 1;
// actions_file_schema = (const char*) opt->getValue("actions_file_schema");
cout << "actionsFile = " << actionsFile << endl;
// cout << "actions_file_schema: " << actions_file_schema << endl;
edges = 0;
// initialize AM HashTree
// AM = NULL;
AM = new HashTreeCube(89041); // i.e. hashtable of size 1024
// AM = new HashTreeCube(181081); // i.e. hashtable of size 1024
// cout << "AM of length " << AM->length() << " created" << endl;
freeTuples = NULL;
freeTuplesSize = 0;
cout << "Done initializing InputParserForTraining" << endl;
}
// its not building a matrix but keeps info for connected nodes only
void InputParserForTraining::buildAdjacencyMatFromFile() {
cout << "In buildAdjacencyMatFromFile from file " << graphFile << endl;
ifstream myfile (graphFile, ios::in);
if (myfile.is_open()) {
while (! myfile.eof() ) {
std::string line;
getline (myfile,line);
if (line.empty()) continue;
std::string::size_type pos = line.find_first_of(" \t:");
int prevpos = 0;
// get the first node
string str = line.substr(prevpos, pos-prevpos);
UID u1 = strToInt(str);
// get the second node
prevpos = line.find_first_not_of(" \t:", pos);
pos = line.find_first_of(" \t:", prevpos);
str = line.substr(prevpos, pos-prevpos);
UID u2 = strToInt(str);
// get the timestamp
prevpos = line.find_first_not_of(" \t:", pos);
pos = line.find_first_of(" \t:", prevpos);
if (pos == std::string::npos)
str = line.substr(prevpos);
else
str = line.substr(prevpos, pos-prevpos);
TS ts = strToInt(str);
//TS ts = 0;
if (edges % 50000 == 0) {
cout << "(node1, node2, ts, AM size till now, edges till now, mem) = " << u1 << ", " << u2 << ", " << ts << ", " << AM->size() << ", " << edges << ", " << getCurrentMemoryUsage() << endl;
}
if (u1 == u2) {
cout << "WARNING: Self edge detected for user " << u1 << ". Ignoring!" << endl;
} else if (u1 > u2) {
UID temp = u1;
u1 = u2;
u2 = temp;
}
FriendsMap* neighbors = AM->find(u1);
if (neighbors == NULL) {
neighbors = new FriendsMap();
neighbors->insert(pair<UID, Edge*>(u2, new Edge(ts)));
AM->insert(u1, neighbors);
edges++;
} else {
FriendsMap::iterator it = neighbors->find(u2);
if (it == neighbors->end()) {
neighbors->insert(pair<UID, Edge*>(u2, new Edge(ts)));
edges++;
} else {
// cout << "WARNING: Edge redundant between users " << u1 << " and " << u2 << endl;
}
}
// also add the edges u2->u1 but done allocate Edge class to them
// .. it is just to find friends efficiently
neighbors = AM->find(u2);
if (neighbors == NULL) {
neighbors = new FriendsMap();
neighbors->insert(pair<UID, Edge*>(u1, NULL));
AM->insert(u2, neighbors);
} else {
FriendsMap::iterator it = neighbors->find(u1);
if (it == neighbors->end()) {
neighbors->insert(pair<UID, Edge*>(u1, NULL));
} else {
// cout << "WARNING: Edge redundant between users " << u1 << " and " << u2 << endl;
}
}
}
myfile.close();
} else {
cout << "Can't open friendship graph file " << graphFile << endl;
}
users = AM->size();
cout << "BuildAdjacencyMatFromFile done" << endl;
cout << "Size of friendship graph hashtree is : " << AM->size() << endl;
cout << "Number of edges in the friendship graph are: " << edges << endl;
}
void InputParserForTraining::printAdjacencyMatrix() {
/*
for (Matrix::iterator i=AM.begin(); i!=AM.end(); i++) {
UID u1 = i->first;
UserList& edgeList = i->second;
for (UserList::iterator j=edgeList.begin(); j!=edgeList.end(); j++) {
UID u2 = *j;
cout << u1 << " " << u2 << endl;
}
}*/
}
void InputParserForTraining::openActionsLog() {
pActionsLog.open(actionsFile, ios::in);
if (!pActionsLog.is_open()) {
cout << "cant open actions file:" << actionsFile << endl;
exit(0);
}
}
void InputParserForTraining::closeActionsLog() {
pActionsLog.close();
}
HashTreeCube* InputParserForTraining::getAM() {
return AM;
}
// its not building a matrix but keeps info for connected nodes only
// for Type 4 models
void InputParserForTraining::readTrainingData() {
cout << "in readTrainingData" << endl;
unsigned int myedges = 0;
string basedir = opt->getValue("training_dir") ;
// now read edgesCounts file
string edgesCountsFileName = basedir + "/edgesCounts.txt";
unsigned int edges = 0;
cout << "Reading edgesCounts file " << edgesCountsFileName << endl;
ifstream myfile (edgesCountsFileName.c_str(), ios::in);
string delim = " \t";
if (myfile.is_open()) {
while (! myfile.eof() ) {
std::string line;
getline (myfile,line);
if (line.empty()) continue;
std::string::size_type pos = line.find_first_of(delim);
int prevpos = 0;
// get first user
string str = line.substr(prevpos, pos-prevpos);
UID u1 = strToInt(str);
// get the second user
prevpos = line.find_first_not_of(delim, pos);
pos = line.find_first_of(delim, prevpos);
UID u2 = strToInt(line.substr(prevpos, pos-prevpos));
if (u1 > u2) {
cout << "something wrong. u > v" << u1 << " " << u2 << endl;
exit(1);
}
++edges;
Edge* e = new Edge(line, pos, dynamicFG);
FriendsMap* neighbors = AM->find(u1);
if (neighbors == NULL) {
neighbors = new FriendsMap();
neighbors->insert(pair<UID, Edge*>(u2, e));
AM->insert(u1, neighbors);
} else {
FriendsMap::iterator it = neighbors->find(u2);
if (it == neighbors->end()) {
neighbors->insert(pair<UID, Edge*>(u2, e));
} else {
// cout << "WARNING: Edge redundant between users " << u1 << " and " << u2 << endl;
}
}
// also add the edges u2->u1 but done allocate Edge class to them
// .. it is just to find friends efficiently
neighbors = AM->find(u2);
if (neighbors == NULL) {
neighbors = new FriendsMap();
neighbors->insert(pair<UID, Edge*>(u1, NULL));
AM->insert(u2, neighbors);
} else {
FriendsMap::iterator it = neighbors->find(u1);
if (it == neighbors->end()) {
neighbors->insert(pair<UID, Edge*>(u1, NULL));
} else {
// cout << "WARNING: Edge redundant between users " << u1 << " and " << u2 << endl;
}
}
// cout << "(node1, node2, AM size till now, edges till now) = " << u << ", " << v << ", " << AM->size() << ", " << edges << endl;
if (edges % 50000 == 0) {
cout << "(node1, node2, AM size till now, edges till now, mem) = " << u1 << ", " << u2 << ", " << AM->size() << ", " << edges << ", " << getCurrentMemoryUsage() << endl;
}
}
myfile.close();
} else {
cout << "Can't open edgesCounts file " << edgesCountsFileName << endl;
}
u_counts.clear();
users = AM->size();
cout << "readTrainingData done" << endl;
cout << "Size of friendship graph hashtree is : " << AM->size() << endl;
cout << "Number of edges in the friendship graph are: " << edges << "; myedges: " << myedges/2 << endl << endl;
}
int InputParserForTraining::getUserCounts(UID u) {
return u_counts[u];
}
UsersCounts& InputParserForTraining::getUsersCounts() {
return u_counts;
}
}
|
#include "bsconnect.hh"
#include "Eigen/LU"
using namespace Geometry;
static Vector3D surfaceNormal(const BSSurface &s, double u, double v) {
VectorMatrix der;
s.eval(u, v, 1, der);
return (der[1][0] ^ der[0][1]).normalize();
}
// `p` (supposedly in the `(u,v)` plane) is written as a combination of `u` and `v`.
// Returns `{ a, b }` s.t. `u * a + v * b = p`.
static std::pair<double, double> inSystem(const Vector3D &u, const Vector3D &v, const Vector3D &p) {
return { p * u / u.normSqr(), p * v / v.normSqr() };
}
static double normalCurvature(const BSSurface &s, double u, double v, const Vector3D &dir) {
VectorMatrix der;
s.eval(u, v, 2, der);
auto n = (der[1][0] ^ der[0][1]).normalize();
double E = der[1][0] * der[1][0];
double F = der[1][0] * der[0][1];
double G = der[0][1] * der[0][1];
double L = n * der[2][0];
double M = n * der[1][1];
double N = n * der[0][2];
auto [du, dv] = inSystem(der[1][0], der[0][1], dir);
double du2 = du * du, dudv = du * dv, dv2 = dv * dv;
return (L * du2 + 2 * M * dudv + N * dv2) / (E * du2 + 2 * F * dudv + G * dv2);
}
static void connectC0(const BSSurface &master, BSSurface &slave, size_t fixed) {
size_t m = slave.numControlPoints()[1];
for (size_t j = fixed; j < m - fixed; ++j)
slave.controlPoint(0, j) = master.controlPoint(0, j);
}
static void connectG1(const BSSurface &master, BSSurface &slave, size_t fixed, size_t resolution) {
size_t m = slave.numControlPoints()[1];
size_t p = slave.basisV().degree();
DoubleMatrix der_u;
slave.basisU().basisFunctionDerivatives(slave.basisU().findSpan(0.0), 0.0, 1, der_u);
double dbase = der_u[1][1];
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(resolution, m - fixed * 2);
Eigen::MatrixXd b(resolution, 3);
using VecMap = Eigen::Map<const Eigen::Vector3d>;
for (size_t k = 0; k < resolution; ++k) {
double v = (double)k / (resolution - 1);
auto n = surfaceNormal(master, 0, v);
DoubleVector coeff_v;
size_t span = slave.basisV().findSpan(v);
slave.basisV().basisFunctions(span, v, coeff_v);
for (size_t j = 0; j <= p; ++j)
if (span - p + j >= fixed && span - p + j < m - fixed)
A(k, span - p + j - fixed) = dbase * coeff_v[j];
VectorMatrix der;
slave.eval(0, v, 1, der);
b.block<1,3>(k, 0) = VecMap((n * -(der[1][0] * n)).data());
}
Eigen::MatrixXd x = A.fullPivLu().solve(b);
for (size_t j = 0; j < m - fixed * 2; ++j)
slave.controlPoint(1, fixed + j) += { x(j, 0), x(j, 1), x(j, 2) };
}
static void connectG2(const BSSurface &master, BSSurface &slave, size_t fixed, size_t resolution) {
size_t m = slave.numControlPoints()[1];
size_t p = slave.basisV().degree();
size_t q = slave.basisU().degree();
const auto &knots = slave.basisU().knots();
double base = (knots[q+1] - knots[2]) * (knots[q+2] - knots[2]) / (q * (q - 1));
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(resolution, m - fixed * 2);
Eigen::MatrixXd b(resolution, 3);
using VecMap = Eigen::Map<const Eigen::Vector3d>;
for (size_t k = 0; k < resolution; ++k) {
double v = (double)k / (resolution - 1);
VectorMatrix der;
slave.eval(0, v, 1, der);
auto d1 = der[1][0];
double k_master = -normalCurvature(master, 0, v, d1);
double k_slave = normalCurvature(slave, 0, v, d1);
auto n = surfaceNormal(slave, 0, v);
DoubleVector coeff_v;
size_t span = slave.basisV().findSpan(v);
slave.basisV().basisFunctions(span, v, coeff_v);
for (size_t j = 0; j <= p; ++j)
if (span - p + j >= fixed && span - p + j < m - fixed)
A(k, span - p + j - fixed) = coeff_v[j];
b.block<1,3>(k, 0) = VecMap((n * (k_master - k_slave) * d1.normSqr() * base).data());
}
Eigen::MatrixXd x = A.fullPivLu().solve(b);
for (size_t j = 0; j < m - fixed * 2; ++j)
slave.controlPoint(2, fixed + j) += { x(j, 0), x(j, 1), x(j, 2) };
}
void connectBSplineSurfaces(const BSSurface &master, BSSurface &slave,
bool fix_c0, bool fix_g1, bool fix_g2,
const std::array<size_t,3> &fixed, size_t resolution) {
if (fix_c0)
connectC0(master, slave, fixed[0]);
if (fix_g1)
connectG1(master, slave, fixed[1], resolution);
if (fix_g2)
connectG2(master, slave, fixed[2], resolution);
}
|
//Phoenix_RK
/*
https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
*/
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string s="";
if(strs.size()==0)
return s;
string str=strs[0];
int flag=1;
for(int x=0;x<str.length() && flag ;x++)
{
for(int i=1;i<strs.size();i++)
{
if(str[x]!=strs[i][x])
{
flag=0;
break;
}
}
if(flag)
s=s+str[x];
}
return s;
}
};
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string s="";
if(strs.size()==0)
return s;
string str=strs[0];
int flag=1;
for(int i=1;i<strs.size();i++)
{
while(strs[i].find(str)!=0)
{
str=str.substr(0,str.length()-1);
}
}
return str;
}
};
|
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long t, n, m, k, r, c, ans;
map<pair<int, int>, int> grid;
cin >> t;
for(int i = 0; i < t; i++)
{
cin >> n >> m >> k;
ans = 0;
grid.clear();
for(int j = 0; j < k; j++)
{
cin >> r >> c;
if(r != 1 && grid[{r-1, c}])
{
ans--;
}
else{
grid[{r, c}] = true;
ans++;
}
if(c != m && grid[{r, c + 1}])
{
ans--;
}
else
{
grid[{r,c}] = true;
ans++;
}
if(r != n && grid[{r + 1, c}])
{
ans--;
}
else
{
grid[{r,c}] = true;
ans++;
}
if(c != 1 && grid[{r , c - 1}])
{
ans--;
}
else
{
grid[{r,c}] = true;
ans++;
}
}
cout << ans << endl;
}
}
|
#include "..\h\backBuffer.h"
CBackBuffer::CBackBuffer() :
m_hwnd(0),
m_BFDC(0),
m_hBFBitmap(0),
m_hOldBitmap(0),
m_iWidth(0),
m_iHeight(0)
{}
CBackBuffer::~CBackBuffer() {
SelectObject(m_BFDC, m_hOldBitmap);
DeleteObject(m_hBFBitmap);
DeleteObject(m_BFDC);
}
bool CBackBuffer::Initialize(HWND _hwnd, int _iWidth, int _iHeight) {
m_hwnd = _hwnd;
m_iWidth = _iWidth;
m_iHeight = _iHeight;
HDC hWindowDC = GetDC(m_hwnd);
m_BFDC = CreateCompatibleDC(hWindowDC);
m_hBFBitmap = CreateCompatibleBitmap(hWindowDC, m_iWidth, m_iHeight);
ReleaseDC(m_hwnd, hWindowDC);
m_hOldBitmap = static_cast<HBITMAP>(SelectObject(m_BFDC, m_hBFBitmap));
HBRUSH brush_white = static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));
HBRUSH brush_old = static_cast<HBRUSH>(SelectObject(m_BFDC, brush_white));
Rectangle(m_BFDC, 0, 0, m_iWidth, m_iHeight);
SelectObject(m_BFDC, brush_old);
return true;
}
void CBackBuffer::Clear() {
HBRUSH brush_old = static_cast<HBRUSH>(SelectObject(GetBFDC(), GetStockObject(WHITE_BRUSH)));
HPEN pen = CreatePen(PS_SOLID, 0, RGB(44, 44, 44));
SelectObject(m_BFDC, pen);
Rectangle(GetBFDC(), -1, 0, GetWidth(), GetHeight());
SelectObject(GetBFDC(), brush_old);
DeleteObject(pen);
}
void CBackBuffer::Present() {
HDC hWindowDC = ::GetDC(m_hwnd);
BitBlt(hWindowDC, 0, 0, GetWidth(), GetHeight(), GetBFDC(), 0, 0, SRCCOPY);
ReleaseDC(m_hwnd, hWindowDC);
}
HDC CBackBuffer::GetBFDC() const {
return m_BFDC;
}
void CBackBuffer::SetBFBitmap(HBITMAP _bitmap) {
m_hBFBitmap = _bitmap;
}
HBITMAP CBackBuffer::GetBFBitmap() const {
return m_hBFBitmap;
}
HWND CBackBuffer::GetHWND() const {
return m_hwnd;
}
int CBackBuffer::GetHeight() const {
return m_iHeight;
}
int CBackBuffer::GetWidth() const {
return m_iWidth;
}
|
// sensorLightClass.h
#ifndef _SENSORLIGHTCLASS_h
#define _SENSORLIGHTCLASS_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#include <ArduinoJson.h>
#include <FS.h>
#include <SPIFFS.h>
#else
#include "WProgram.h"
#endif
class sensorLightClass
{
public:
String name;
int light = 0;
int valueToNight = 1800;
uint8_t pin = NULL;
void setName(String x = "undefinedName") {
this->name = x;
this->readConf();
}
bool isNight(){
if (this->pin != NULL) {
this->light = analogRead(this->pin);
}
if (this->light >= this->valueToNight){
return true;
}
else {
return false;
}
}
String get() {
return (String(this->name) + " value: " + String(this->light) + " valueN: " + String(this->valueToNight));
}
void saveConf() {
if (SPIFFS.begin()) {
String fileName = ("/config_" + this->name);
if (SPIFFS.exists(fileName)) {
SPIFFS.remove(fileName);
}
File config_file = SPIFFS.open(fileName, FILE_WRITE);
if (config_file) {
DynamicJsonDocument conf(64);
conf["valueToNight"] = this->valueToNight;
conf["pin"] = this->pin;
serializeJson(conf, config_file);
config_file.close();
}
else {
Serial.println("Failed to save json");
}
}
}
void readConf() {
if (SPIFFS.begin()) {
String fileName = ("/config_" + this->name);
if (SPIFFS.exists(fileName)) {
File config_file = SPIFFS.open(fileName);
if (config_file) {
DynamicJsonDocument conf(64);
deserializeJson(conf, config_file);
config_file.close();
this->valueToNight = conf["valueToNight"];
this->pin = conf["pin"];
}
else {
Serial.println("Failed to load json config_light[x]. Set default - 1800");
}
}
}
}
};
extern sensorLightClass sensorLight;
#endif
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = 5e3 + 10;
int a[maxn],t[maxn],n;
int lowbit(int k) {
return k&(-k);
}
int query(int k) {
int ans = 0;
while (k > 0) {
ans += t[k];
k -= lowbit(k);
}
return ans;
}
void updata(int k,int d) {
while (k <= n) {
t[k] += d;
k += lowbit(k);
}
}
int main() {
while (scanf("%d",&n) != EOF) {
memset(t,0,sizeof(t));
int rec = 0;
for (int i = 1;i <= n; i++) {
scanf("%d",&a[i]);
rec += query(n) - query(a[i]);
updata(a[i]+1,1);
}
int ans = rec;
for (int i = 1;i < n; i++) {
rec = rec - a[i] + (n-1-a[i]);
ans = min(ans,rec);
}
printf("%d\n",ans);
}
return 0;
}
|
// Created on: 1997-07-28
// Created by: Pierre CHALAMET
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Graphic3d_Texture2Dplane_HeaderFile
#define _Graphic3d_Texture2Dplane_HeaderFile
#include <Standard.hxx>
#include <Graphic3d_NameOfTexturePlane.hxx>
#include <Graphic3d_Texture2D.hxx>
#include <Graphic3d_NameOfTexture2D.hxx>
class TCollection_AsciiString;
class Graphic3d_Texture2Dplane;
DEFINE_STANDARD_HANDLE(Graphic3d_Texture2Dplane, Graphic3d_Texture2D)
//! This class allows the management of a 2D texture defined from a plane equation
//! Use the SetXXX() methods for positioning the texture as you want.
class Graphic3d_Texture2Dplane : public Graphic3d_Texture2D
{
public:
//! Creates a texture from a file
Standard_EXPORT Graphic3d_Texture2Dplane(const TCollection_AsciiString& theFileName);
//! Creates a texture from a predefined texture name set.
Standard_EXPORT Graphic3d_Texture2Dplane(const Graphic3d_NameOfTexture2D theNOT);
//! Creates a texture from the pixmap.
Standard_EXPORT Graphic3d_Texture2Dplane(const Handle(Image_PixMap)& thePixMap);
//! Defines the texture projection plane for texture coordinate S
//! default is <1.0, 0.0, 0.0, 0.0>
Standard_EXPORT void SetPlaneS (const Standard_ShortReal A, const Standard_ShortReal B, const Standard_ShortReal C, const Standard_ShortReal D);
//! Defines the texture projection plane for texture coordinate T
//! default is <0.0, 1.0, 0.0, 0.0>
Standard_EXPORT void SetPlaneT (const Standard_ShortReal A, const Standard_ShortReal B, const Standard_ShortReal C, const Standard_ShortReal D);
//! Defines the texture projection plane for both S and T texture coordinate
//! default is NOTP_XY meaning:
//! <1.0, 0.0, 0.0, 0.0> for S
//! and <0.0, 1.0, 0.0, 0.0> for T
Standard_EXPORT void SetPlane (const Graphic3d_NameOfTexturePlane thePlane);
//! Defines the texture scale for the S texture coordinate
//! much easier than recomputing the S plane equation
//! but the result is the same
//! default to 1.0
Standard_EXPORT void SetScaleS (const Standard_ShortReal theVal);
//! Defines the texture scale for the T texture coordinate
//! much easier than recompution the T plane equation
//! but the result is the same
//! default to 1.0
Standard_EXPORT void SetScaleT (const Standard_ShortReal theVal);
//! Defines the texture translation for the S texture coordinate
//! you can obtain the same effect by modifying the S plane
//! equation but its not easier.
//! default to 0.0
Standard_EXPORT void SetTranslateS (const Standard_ShortReal theVal);
//! Defines the texture translation for the T texture coordinate
//! you can obtain the same effect by modifying the T plane
//! equation but its not easier.
//! default to 0.0
Standard_EXPORT void SetTranslateT (const Standard_ShortReal theVal);
//! Sets the rotation angle of the whole texture.
//! the same result might be achieved by recomputing the
//! S and T plane equation but it's not the easiest way...
//! the angle is expressed in degrees
//! default is 0.0
Standard_EXPORT void SetRotation (const Standard_ShortReal theVal);
//! Returns the current texture plane name or NOTP_UNKNOWN
//! when the plane is user defined.
Standard_EXPORT Graphic3d_NameOfTexturePlane Plane() const;
//! Returns the current texture plane S equation
Standard_EXPORT void PlaneS (Standard_ShortReal& A, Standard_ShortReal& B, Standard_ShortReal& C, Standard_ShortReal& D) const;
//! Returns the current texture plane T equation
Standard_EXPORT void PlaneT (Standard_ShortReal& A, Standard_ShortReal& B, Standard_ShortReal& C, Standard_ShortReal& D) const;
//! Returns the current texture S translation value
Standard_EXPORT void TranslateS (Standard_ShortReal& theVal) const;
//! Returns the current texture T translation value
Standard_EXPORT void TranslateT (Standard_ShortReal& theVal) const;
//! Returns the current texture S scale value
Standard_EXPORT void ScaleS (Standard_ShortReal& theVal) const;
//! Returns the current texture T scale value
Standard_EXPORT void ScaleT (Standard_ShortReal& theVal) const;
//! Returns the current texture rotation angle
Standard_EXPORT void Rotation (Standard_ShortReal& theVal) const;
DEFINE_STANDARD_RTTIEXT(Graphic3d_Texture2Dplane,Graphic3d_Texture2D)
protected:
private:
Graphic3d_NameOfTexturePlane myPlaneName;
};
#endif // _Graphic3d_Texture2Dplane_HeaderFile
|
#include "./platform/UnitTestSupport.hpp"
#include <Dot++/Parser.hpp>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
namespace {
struct GraphMock
{
GraphMock()
: finalized(false)
{
}
void createGraph(const std::string& name) { graphName = name.empty() ? "<empty>" : name; }
void createDigraph(const std::string& name) { digraphName = name.empty() ? "<empty>" : name; }
void createVertex(const std::string& name) { vertices.insert(name); }
void createEdge(const std::string& vertex1, const std::string& vertex2)
{
edges.insert(std::make_pair(vertex1, vertex2));
}
void applyGraphAttribute(const std::string& attributeName, const std::string& value)
{
graphAttributes.insert(std::make_pair(attributeName, value));
}
void applyDefaultVertexAttribute(const std::string& attributeName, const std::string& value)
{
defaultVertexAttributes.insert(std::make_pair(attributeName, value));
}
void applyVertexAttribute(const std::string& vertex, const std::string& attributeName, const std::string& value)
{
vertexAttributes.insert(std::make_pair(std::make_pair(vertex, attributeName), value));
}
void applyDefaultEdgeAttribute(const std::string& attributeName, const std::string& value)
{
defaultEdgeAttributes.insert(std::make_pair(attributeName, value));
}
void applyEdgeAttribute(const std::string& vertex1, const std::string& vertex2, const std::string& attributeName, const std::string& value)
{
edgeAttributes.insert(std::make_pair(std::make_pair(std::make_pair(vertex1, vertex2), attributeName), value));
}
void finalize()
{
finalized = true;
}
std::string graphName;
std::string digraphName;
std::set<std::string> vertices;
std::set<std::pair<std::string, std::string>> edges;
std::map<std::string, std::string> graphAttributes;
// key: attributeName
std::map<std::string, std::string> defaultVertexAttributes;
// key: (vertex, attribute)
std::map<std::pair<std::string, std::string>, std::string> vertexAttributes;
// key: attributeName
std::map<std::string, std::string> defaultEdgeAttributes;
// key: ((v1, v2), attribute)
std::map<std::pair<std::pair<std::string, std::string>, std::string>, std::string> edgeAttributes;
bool finalized;
};
struct ParserFixture
{
ParserFixture()
: parser(graph)
, filename("test.dot")
{
}
void assertGraphEmpty()
{
CHECK(graph.graphName.empty());
CHECK(graph.digraphName.empty());
CHECK(graph.vertices.empty());
CHECK(graph.edges.empty());
CHECK(graph.graphAttributes.empty());
CHECK(graph.defaultVertexAttributes.empty());
CHECK(graph.vertexAttributes.empty());
CHECK(graph.defaultEdgeAttributes.empty());
CHECK(graph.edgeAttributes.empty());
}
bool hasVertex(const std::string& key)
{
return graph.vertices.find(key) != graph.vertices.end();
}
bool hasEdge(const std::string& v1, const std::string& v2)
{
return graph.edges.find(std::make_pair(v1, v2)) != graph.edges.end();
}
std::string graphAttribute(const std::string& attribute)
{
const auto iter = graph.graphAttributes.find(attribute);
if(iter != graph.graphAttributes.cend())
{
return iter->second;
}
throw std::runtime_error("Graph Attribute Key Not Found");
}
std::string defaultVertexAttribute(const std::string& attribute)
{
const auto iter = graph.defaultVertexAttributes.find(attribute);
if(iter != graph.defaultVertexAttributes.end())
{
return iter->second;
}
throw std::runtime_error("Default Vertex Attribute Key Not Found");
}
std::string vertexAttribute(const std::string& vertex, const std::string& attribute)
{
const auto iter = graph.vertexAttributes.find(std::make_pair(vertex, attribute));
if(iter != graph.vertexAttributes.cend())
{
return iter->second;
}
throw std::runtime_error("Vertex Attribute Key Not Found");
}
std::string defaultEdgeAttribute(const std::string& attribute)
{
const auto iter = graph.defaultEdgeAttributes.find(attribute);
if(iter != graph.defaultEdgeAttributes.end())
{
return iter->second;
}
throw std::runtime_error("Default Edge Attribute Key Not Found");
}
std::string edgeAttribute(const std::string& v1, const std::string& v2, const std::string attribute)
{
const auto iter = graph.edgeAttributes.find(std::make_pair(std::make_pair(v1, v2), attribute));
if(iter != graph.edgeAttributes.cend())
{
return iter->second;
}
throw std::runtime_error("Edge Attribute Key Not Found");
}
GraphMock graph;
dot_pp::Parser<GraphMock> parser;
const std::string filename;
};
TEST_FIXTURE(ParserFixture, verifyInstantiation)
{
}
TEST_FIXTURE(ParserFixture, verifyIgnoresWhitespace)
{
assertGraphEmpty();
std::istringstream ss(" \t\n");
parser.parse(ss, filename, graph);
assertGraphEmpty();
}
TEST_FIXTURE(ParserFixture, verifyConstructsEmptyGraph)
{
assertGraphEmpty();
std::istringstream ss("graph {}");
parser.parse(ss, filename, graph);
CHECK_EQUAL("<empty>", graph.graphName);
CHECK(graph.vertices.empty());
CHECK(graph.edges.empty());
}
TEST_FIXTURE(ParserFixture, verifyConstructsEmptyDigraph)
{
assertGraphEmpty();
std::istringstream ss("digraph {}");
parser.parse(ss, filename, graph);
CHECK_EQUAL("<empty>", graph.digraphName);
CHECK(graph.vertices.empty());
CHECK(graph.edges.empty());
}
TEST_FIXTURE(ParserFixture, verifyConstructsGraph)
{
assertGraphEmpty();
std::istringstream ss(
"/* This graph contains some\r\n"
" some information. \r\n"
"*/ \n\n"
"digraph stages {" "\n"
"\n"
"// define graph attribuetes \n"
"\t" "size = \"100,100\"; \n"
"\t" "position= center ; " "\n"
"\t" "// define default attributes \n"
"\t" "node [ color=black fontsize=10];" "\n"
"\t" "edge [ color=blue fontsize=8 ];" "\n"
"\n"
"// define vertices with attributes \n"
"\t" "a [ color=red];"
"\t" "b [ color = \"blue\" weight=3.2] ;\n"
"\n"
"// define some edges...\n"
"\t" "a -> b -> c -> d -> e [ weight = \"1.0\" color=red ]; \t \r \n"
"\t" "a -> c -> e [ weight = 2 ];"
"\t" "b -> f;" "\n"
"\t" "{ rank = same; A; B; C; }\n"
"}\r\n");
parser.parse(ss, filename, graph);
CHECK_EQUAL("stages", graph.digraphName);
REQUIRE CHECK_EQUAL(6U, graph.vertices.size());
CHECK(hasVertex("a"));
CHECK(hasVertex("b"));
CHECK(hasVertex("c"));
CHECK(hasVertex("d"));
CHECK(hasVertex("e"));
CHECK(hasVertex("f"));
CHECK_EQUAL(7U, graph.edges.size());
CHECK(hasEdge("a", "b"));
CHECK(hasEdge("b", "c"));
CHECK(hasEdge("c", "d"));
CHECK(hasEdge("d", "e"));
CHECK(hasEdge("a", "c"));
CHECK(hasEdge("c", "e"));
CHECK(hasEdge("b", "f"));
CHECK_EQUAL(2U, graph.graphAttributes.size());
CHECK_EQUAL("100,100", graphAttribute("size"));
CHECK_EQUAL("center", graphAttribute("position"));
CHECK_EQUAL(2U, graph.defaultVertexAttributes.size());
CHECK_EQUAL("black", defaultVertexAttribute("color"));
CHECK_EQUAL("10", defaultVertexAttribute("fontsize"));
CHECK_EQUAL(3U, graph.vertexAttributes.size());
CHECK_EQUAL("red", vertexAttribute("a", "color"));
CHECK_EQUAL("blue", vertexAttribute("b", "color"));
CHECK_EQUAL("3.2", vertexAttribute("b", "weight"));
CHECK_EQUAL(2U, graph.defaultEdgeAttributes.size());
CHECK_EQUAL("blue", defaultEdgeAttribute("color"));
CHECK_EQUAL("8", defaultEdgeAttribute("fontsize"));
CHECK_EQUAL(10U, graph.edgeAttributes.size());
CHECK_EQUAL("1.0", edgeAttribute("a", "b", "weight"));
CHECK_EQUAL("1.0", edgeAttribute("b", "c", "weight"));
CHECK_EQUAL("1.0", edgeAttribute("c", "d", "weight"));
CHECK_EQUAL("1.0", edgeAttribute("d", "e", "weight"));
CHECK_EQUAL("red", edgeAttribute("a", "b", "color"));
CHECK_EQUAL("red", edgeAttribute("b", "c", "color"));
CHECK_EQUAL("red", edgeAttribute("c", "d", "color"));
CHECK_EQUAL("red", edgeAttribute("d", "e", "color"));
CHECK_EQUAL("2", edgeAttribute("a", "c", "weight"));
CHECK_EQUAL("2", edgeAttribute("c", "e", "weight"));
}
}
|
#include "ClnUtils.h"
namespace PticaGovorun
{
// Divdes [min;max] interval into 'numPoints' points. If numPoints=2 the result is two points [min,max].
// The routine is similar to Matlab 'linspace' function.
void linearSpace(float min, float max, int numPoints, wv::slice<float> points)
{
PG_Assert(numPoints >= 2);
PG_Assert(points.size() >= numPoints && "Space for points must be allocated");
// to prevent float round offs, set the first and the last points to expected min and max vlues
points[0] = min;
points[numPoints - 1] = max;
// assign internal points
for (int i = 1; i < numPoints - 1; ++i)
{
points[i] = min + (max - min) * i / (numPoints - 1);
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef QUICK_BINDER_ENABLED_H
#define QUICK_BINDER_ENABLED_H
#include "adjunct/quick_toolkit/bindings/QuickBinder.h"
/**
* A unidirectional binding for the "enabled" state of a QuickWidget.
*
* The "enabled" state of a QuickWidget is bound to a boolean OpProperty.
*
* @author Wojciech Dzierzanowski (wdzierzanowski)
*/
class QuickBinder::EnabledBinding : public QuickBinder::Binding
{
public:
EnabledBinding();
virtual ~EnabledBinding();
OP_STATUS Init(QuickWidget& widget, OpProperty<bool>& property);
void OnPropertyChanged(bool new_value);
// Binding
virtual const QuickWidget* GetBoundWidget() const { return m_widget; }
private:
QuickWidget* m_widget;
OpProperty<bool>* m_property;
};
#endif // QUICK_BINDER_ENABLED_H
|
#include <cstdlib>
#include <stdio.h>
#include <vector>
#include <omp.h>
int main(int argc, char *argv[]) {
int N = atoi(argv[1]);
std::vector<std::vector<int> > a(N, std::vector<int>(N, 2));
std::vector<std::vector<int> > b(N, std::vector<int>(N, 2));
std::vector<std::vector<int> > prod(N, std::vector<int>(N, 0));
double start_time, end_time, one_threaded_run_time;
int num, count;
for (int threads = 1; threads <= 17; threads++){
omp_set_num_threads(threads);
start_time = omp_get_wtime();
#pragma omp parallel private (num)
{
count = omp_get_num_threads();
num = omp_get_thread_num();
if (num == 0)
printf("Всего нитей: %d\n", count);
#pragma omp for
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
prod[i][j] += a[i][k] * b[k][j];
}
}
}
}
/*
printf("\n");
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
printf(" %d ", prod[i][j]);
}
printf("\n");
} */
end_time = omp_get_wtime();
if (threads == 1) {
one_threaded_run_time = end_time - start_time;
}
double time = end_time - start_time;
printf("Время вычисления %d потоков: %lf\n", threads, time);
printf("Эффективность: %lf%%\n\n", threads, one_threaded_run_time/time*100);
}
for (int threads = 1; threads <= 17; threads++){
omp_set_num_threads(threads);
start_time = omp_get_wtime();
#pragma omp parallel private (num)
{
count = omp_get_num_threads();
num = omp_get_thread_num();
if (num == 0)
printf("Всего нитей: %d\n", count);
#pragma omp for
for (int j = 0; j < N; ++j) {
for (int i = 0; i < N; ++i) {
for (int k = 0; k < N; ++k) {
prod[i][j] += a[i][k] * b[k][j];
}
}
}
}
/*
printf("\n");
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
printf(" %d ", prod[i][j]);
}
printf("\n");
} */
end_time = omp_get_wtime();
if (threads == 1) {
one_threaded_run_time = end_time - start_time;
}
double time = end_time - start_time;
printf("Время вычисления %d потоков (поменяны строки и столбцы): %lf\n", threads, time);
printf("Эффективность: %lf%%\n\n", threads, one_threaded_run_time/time*100);
}
for (int threads = 1; threads <= 17; threads++){
omp_set_num_threads(threads);
start_time = omp_get_wtime();
#pragma omp parallel private (num)
{
count = omp_get_num_threads();
num = omp_get_thread_num();
if (num == 0)
printf("Всего нитей: %d\n", count);
#pragma omp for
for (int k = 0; k < N; ++k) {
for (int j = 0; j < N; ++j) {
for (int i = 0; i < N; ++i) {
prod[i][j] += a[i][k] * b[k][j];
}
}
}
}
/*
printf("\n");
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
printf(" %d ", prod[i][j]);
}
printf("\n");
} */
end_time = omp_get_wtime();
if (threads == 1) {
one_threaded_run_time = end_time - start_time;
}
double time = end_time - start_time;
printf("Время вычисления %d потоков (поменяны циклы): %lf\n", threads, time);
printf("Эффективность: %lf%%\n\n", threads, one_threaded_run_time/time*100);
}
}
|
//inputpasser.hpp
//Turns SDL input into actions.
//Created by Lewis Hosie
//17-11-11
#include <SDL.h>
#include "world.hpp"
#ifndef E_INPUTPASSER
#define E_INPUTPASSER
class inputpasser{
bool keys[SDLK_LAST];
//entity &theentity;
public:
inputpasser(world& theworld){
for(int i=0; i<SDLK_LAST; i++)
keys[i]=false;
}
void on_keydown(SDL_keysym e){
keys[e.sym]=true;
}
void tick(){
/*if(iskeydown('w')) theentity.move(fvec3(0.0f,0.0f,-0.5f));
if(iskeydown('s')) theentity.move(fvec3(0.0f,0.0f,0.5f));
if(iskeydown('a')) theentity.move(fvec3(-0.5f,0.0f,0.0f));
if(iskeydown('d')) theentity.move(fvec3(0.5f,0.0f,0.0f));*/
}
void on_keyup(SDL_keysym e){
keys[e.sym]=false;
}
bool iskeydown(int thekey){
if(thekey >= 0 && thekey < SDLK_LAST)
return keys[thekey];
else{
//FIXME: Throw some "key doesn't exist" exception here.
return false;
}
}
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright 2002-2009 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Karlsson
*/
#include "core/pch.h"
#ifdef PREFS_HAVE_DESKTOP_UI
#include "adjunct/desktop_util/prefs/PrefsCollectionDesktopUI.h"
#include "modules/prefs/prefsmanager/prefstypes.h"
#include "modules/prefsfile/prefssection.h"
#include "modules/prefsfile/prefsentry.h"
#include "modules/prefsfile/impl/backend/prefssectioninternal.h" // Yeah, it's ugly
#include "modules/prefsfile/impl/backend/prefsentryinternal.h" // This, too
#include "modules/prefsfile/prefsfile.h"
#include "modules/util/gen_str.h"
#include "modules/prefs/prefsmanager/collections/prefs_macros.h"
#include "adjunct/desktop_util/prefs/PrefsCollectionDesktopUI_c.inl"
#include "adjunct/quick/managers/SpeedDialManager.h"
PrefsCollectionUI *PrefsCollectionUI::CreateL(PrefsFile *reader)
{
if (g_opera->prefs_module.m_pcui)
LEAVE(OpStatus::ERR);
g_opera->prefs_module.m_pcui = OP_NEW_L(PrefsCollectionUI, (reader));
return g_opera->prefs_module.m_pcui;
}
PrefsCollectionUI::~PrefsCollectionUI()
{
#ifdef PREFS_COVERAGE
CoverageReport(
m_stringprefdefault, PCUI_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCUI_NUMBEROFINTEGERPREFS);
#endif
OP_DELETE(m_windowsizeprefs);
OP_DELETE(m_treeview_columns);
OP_DELETE(m_treeview_matches);
g_opera->prefs_module.m_pcui = NULL;
}
void PrefsCollectionUI::ReadAllPrefsL(PrefsModule::PrefsInitInfo *)
{
// Read everything
OpPrefsCollection::ReadAllPrefsL(
m_stringprefdefault, PCUI_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCUI_NUMBEROFINTEGERPREFS);
ReadCachedQuickSectionsL();
}
#ifdef PREFS_VALIDATE
void PrefsCollectionUI::CheckConditionsL(int which, int *value, const uni_char *host)
{
// Check any post-read/pre-write conditions and adjust value accordingly
switch (static_cast<integerpref>(which))
{
case ShowTrayIcon:
break;
case SecondsBeforeAutoHome:
if (*value < 30)
*value = 30;
else if (*value > 6000)
*value = 6000;
break;
case StartupType:
if (*value <= _STARTUP_FIRST_ENUM || *value >= _STARTUP_LAST_ENUM)
*value = STARTUP_CONTINUE;
break;
#ifdef SUPPORT_SPEED_DIAL
case NumberOfSpeedDialColumns:
if (*value < 0) // non-positive integers will be interpreted as "auto"
*value = 0;
break;
#endif
#ifdef PREFS_HAVE_DISABLE_OPEN_SAVE
case NoSave:
case NoOpen:
#endif
case ShowProblemDlg:
case ShowGestureUI:
#ifdef _INTERNAL_BUTTONSET_SUPPORT_
case UseExternalButtonSet:
#endif
#ifdef LINK_BAR
case LinkBarPosition:
#endif
break;
case ShowExitDialog:
if (*value < _CONFIRM_EXIT_STRATEGY_FIRST_ENUM || *value >= _CONFIRM_EXIT_STRATEGY_LAST_ENUM)
*value = ExitStrategyExit;
break;
case OperaUniteExitPolicy:
case WarnAboutActiveTransfersOnExit:
if (*value < _CONFIRM_EXIT_STRATEGY_FIRST_ENUM || *value >= _CONFIRM_EXIT_STRATEGY_LAST_ENUM)
*value = ExitStrategyConfirm;
break;
case ShowDefaultBrowserDialog:
case ShowStartupDialog:
#ifndef _NO_MENU_TOGGLE_MENU_
case ShowMenu:
#endif
case MaximizeNewWindowsWhenAppropriate:
case SDI:
case AllowEmptyWorkspace:
case ShowWindowMenu:
case ShowCloseButtons:
case ClickToMinimize:
case WindowCycleType:
case ShowLanguageFileWarning:
case PersonalbarAlignment:
case PersonalbarInlineAlignment:
case MainbarAlignment:
case PagebarAlignment:
case AddressbarAlignment:
case AddressbarInlineAutocompletion:
case TreeViewDropDownMaxLines:
case StatusbarAlignment:
#ifdef SUPPORT_GENERATE_THUMBNAILS
case UseThumbnailsInWindowCycle:
case UseThumbnailsInTabTooltips:
#endif // SUPPORT_GENERATE_THUMBNAILS
#ifdef _VALIDATION_SUPPORT_
case ShowValidationDialog:
#endif // _VALIDATION_SUPPORT_
case ProgressPopup:
case PopupButtonHelp:
case WindowRecoveryStrategy:
case ShowProgressDlg:
#ifndef TARGETED_BANNER_SUPPORT
case ShowSetupdialogOnStart:
#endif
#ifdef M2_SUPPORT
case LimitAttentionToPersonalChatMessages:
case ShowNotificationForNewMessages:
case ShowNotificationForNoNewMessages:
#endif
case ShowNotificationForBlockedPopups:
case ShowNotificationForFinishedTransfers:
case ShowNotificationsForWidgets:
case PagebarAutoAlignment:
case PagebarOpenURLOnMiddleClick:
case ShowHiddenToolbarsWhileCustomizing:
case ShowPanelToggle:
case ColorListRowMode:
case Running:
case HotlistVisible:
case HotlistSingleClick:
case HotlistSplitter:
case HotlistSortBy:
case HotlistSortAsc:
#ifdef M2_SUPPORT
case HotlistShowAccountInfoDetails:
#endif
case HotlistBookmarksManagerSplitter:
case HotlistBookmarksManagerStyle:
case HotlistBookmarksSplitter:
case HotlistBookmarksStyle:
case HotlistContactsManagerSplitter:
case HotlistContactsManagerStyle:
case HotlistContactsSplitter:
case HotlistContactsStyle:
case HotlistNotesSplitter:
// case TransWinShowTransferWindow:
case TransWinLogEntryDaysToLive:
case TransWinActivateOnNewTransfer:
case TransWinShowDetails:
#if defined BRANDED_BANNER_WITHOUT_REGISTRATION || defined TARGETED_BANNER_SUPPORT
case UseBrandedBanner:
case BrandedBannerWidth:
case BrandedBannerHeight:
#endif
case ClearPrivateDataDialog_CheckFlags:
case NavigationbarAlignment:
case NavigationbarAutoAlignment:
case HotlistAlignment:
#ifdef M2_SUPPORT
case MailHandler:
#endif
case WebmailService:
case UseIntegratedSearch:
case CenterMouseButtonAction:
#ifdef PREFS_HAVE_MIDDLE_MOUSEBUTTON_EXT
case ExtendedCenterMouseButtonAction:
#endif
case HasShownCenterClickInfo:
case OpenPageNextToCurrent:
case ConfirmOpenBookmarkLimit:
case EllipsisInCenter:
case EnableDrag:
case ShowCloseAllDialog:
case ShowCloseAllButActiveDialog:
case AlternativePageCycleMode:
case ShowAddressInCaption:
case CheckForNewOpera:
case ShowNewOperaDialog:
case TransferItemsAddedOnTop:
case ImportedCustomBookmarks:
case FirstRunTimestamp:
case MaxWidthForBookmarksInMenu:
case AllowContextMenus:
case SourceViewerMode:
case HistoryViewStyle:
case AskAboutFlashDownload:
#ifdef PERMANENT_HOMEPAGE_SUPPORT
case PermanentHomepage:
#endif
#ifdef ENABLE_USAGE_REPORT
case EnableUsageStatistics:
case ReportTimeoutForUsageStatistics:
case AskForUsageStatsPercentage:
#endif
case DisableBookmarkImport:
case ShowMailErrorDialog:
#ifdef SUPPORT_SPEED_DIAL
case SpeedDialState:
case ShowAddSpeedDialButton:
#endif
#ifdef FEATURE_SCROLL_MARKER
case EnableScrollMarker:
#endif
case ExtendedKeyboardShortcuts:
case ShowDisableJSCheckbox:
case ActivateTabOnClose:
#ifdef WEBSERVER_SUPPORT
case EnableUnite:
case RestartUniteServicesAfterCrash:
#ifdef SHOW_DISCOVERED_DEVICES_SUPPORT
case EnableServiceDiscoveryNotifications:
#endif // SHOW_DISCOVERED_DEVICES_SUPPORT
#endif // WEBSERVER_SUPPORT
#ifdef INTEGRATED_DEVTOOLS_SUPPORT
case DevToolsSplitter:
case DevToolsIsAttached:
#endif // INTEGRATED_DEVTOOLS_SUPPORT
#ifdef AUTO_UPDATE_SUPPORT
case TimeOfLastUpdateCheck:
case LevelOfUpdateAutomation:
case AutoUpdateState:
case AutoUpdateResponded:
case BrowserJSTime:
case SpoofTime:
case SaveAutoUpdateXML:
case DownloadAllSnapshots:
case DictionaryTime:
case HardwareBlocklistTime:
case HandlersIgnoreTime:
case CountryCheck:
#if defined INTERNAL_SPELLCHECK_SUPPORT
case AskAboutMissingDictionary:
#endif
#endif // AUTO_UPDATE_SUPPORT
case ShowSearchesInAddressfieldAutocompletion:
case VirtualKeyboardType:
case OpenDraggedLinkInBackground:
case DoubleclickToClose:
case AcceptLicense:
case AddressSearchDropDownWeightedWidth:
case DimSearchOpacity:
case ChromeIntegrationDragArea:
case ChromeIntegrationDragAreaMaximized:
case EnableAddressbarFavicons:
case AddressDropdownMixSuggestions:
break; // Nothing to do.
#ifdef SUPPORT_SPEED_DIAL
case SpeedDialZoomLevel:
{
if (*value == 0) // automatic zoom
break;
if (*value < static_cast<int>(SpeedDialManager::MinimumZoomLevel * 100) ||
*value > static_cast<int>(SpeedDialManager::MaximumZoomLevel * 100))
{
*value = static_cast<int>(SpeedDialManager::DefaultZoomLevel * 100);
}
break;
}
#endif // SUPPORT_SPEED_DIAL
#ifdef AUTO_UPDATE_SUPPORT
case UpdateCheckInterval:
{
if(*value < 300)
{
*value = 300;
}
break;
}
case DelayedUpdateCheckInterval:
{
if (*value < 0)
{
*value = 0;
}
break;
}
case ThrottleLevel:
if (*value < 0)
*value = 0;
else if(*value > 9)
*value = 9;
break;
case ThrottlePeriod:
if (*value < 1)
*value = 1;
else if(*value > 10000)
*value = 10000;
break;
case UpdateCheckIntervalGadgets:
#endif
#ifdef PAGEBAR_THUMBNAILS_SUPPORT
case PagebarHeight:
#ifdef TAB_THUMBNAILS_ON_SIDES
case PagebarWidth:
#endif // TAB_THUMBNAILS_ON_SIDES
case EnableUIAnimations:
case UseThumbnailsInsideTabs:
break;
#endif // PAGEBAR_THUMBNAILS_SUPPORT
#ifdef WEB_TURBO_MODE
case ShowNetworkSpeedNotification:
case ShowOperaTurboInfo:
case TurboSNNotificationLeft:
break;
case OperaTurboMode:
if (*value < 0)
*value = 0;
else if (*value > 2)
*value = 2;
break;
#endif // WEB_TURBO_MODE
#ifdef SKIN_SUPPORT
case DebugSkin:
break;
#endif // SKIN_SUPPORT
case GoogleTLDDownloaded:
case ShowCrashLogUploadDlg:
case UpgradeCount:
case ShowPrivateIntroPage:
case UseExternalDownloadManager:
case ShowDownloadManagerSelectionDialog:
case UIPropertyExaminer:
case DisableOperaPackageAutoUpdate:
case HideURLParameter:
case ShowFullURL:
case TotalUptime:
case StartupTimestamp:
case UseHTTPProxyForAllProtocols:
break;
#ifdef MSWIN
case UseWindows7TaskbarThumbnails:
break;
#endif
#ifdef WIDGET_RUNTIME_SUPPORT
case DisableWidgetRuntime:
#ifdef _MACINTOSH_
*value = TRUE;
#endif // _MACINTOSH_
case ShowWidgetDebugInfoDialog:
break;
#endif // WIDGET_RUNTIME_SUPPORT
#ifdef DOM_GEOLOCATION_SUPPORT
case ShowGeolocationLicenseDialog:
break;
#endif // DOM_GEOLOCATION_SUPPORT
case StrategyOnApplicationCache:
if (*value < 0)
*value = 0;
else if(*value > 2)
*value = 2;
break;
#ifdef PLUGIN_AUTO_INSTALL
case PluginAutoInstallMaxItems:
case PluginAutoInstallEnabled:
break;
#endif // PLUGIN_AUTO_INSTALL
case CollectionStyle:
case CollectionSortType:
if (*value < 0)
*value = 0;
else if(*value > 1)
*value = 1;
break;
case ShowDropdownButtonInAddressfield:
case SoundsEnabled:
case CollectionZoomLevel:
case CollectionSplitter:
case ShowFullscreenExitInformation:
break;
default:
// Unhandled preference! For clarity, all preferenes not needing to
// be checked should be put in an empty case something: break; clause
// above.
OP_ASSERT(!"Unhandled preference");
break;
}
}
BOOL PrefsCollectionUI::CheckConditionsL(int which, const OpStringC &invalue,
OpString **outvalue, const uni_char *host)
{
// Check any post-read/pre-write conditions and adjust value accordingly
switch (static_cast<stringpref>(which))
{
case HotlistActiveTab:
case LanguageCodesFileName:
case ValidationURL:
case ValidationForm:
case NewestSeenVersion:
case AuCountryCode:
case MaxVersionRun:
case FirstVersionRun:
case UserEmail:
#if defined BRANDED_BANNER_WITHOUT_REGISTRATION || defined TARGETED_BANNER_SUPPORT
case BrandedBannerURL:
#endif
case OneTimePage:
case CustomBookmarkImportFilename:
case HotlistBookmarksYSplitter:
case HotlistContactsYSplitter:
#ifdef OPERA_CONSOLE
case ErrorConsoleFilter:
#endif
case IntranetHosts:
#ifdef AUTO_UPDATE_SUPPORT
case AutoUpdateServer:
case AutoUpdateGeoServer:
#endif // AUTO_UPDATE_SUPPORT
case GoogleTLDDefault:
case GoogleTLDServer:
case CrashFeedbackPage:
case UpgradeFromVersion:
case DownloadManager:
case ExtensionSetParent:
case IdOfHardcodedDefaultSearch:
case HashOfDefaultSearch:
case IdOfHardcodedSpeedDialSearch:
case HashOfSpeedDialSearch:
case TipsConfigMetaFile:
case TipsConfigFile:
case CountryCode:
case DetectedCountryCode:
case ActiveCountryCode:
case ActiveRegion:
case ActiveDefaultLanguage:
case ClickedSound:
case EndSound:
case FailureSound:
case LoadedSound:
case StartSound:
case TransferDoneSound:
case ProgramTitle:
case NewestUsedBetaName:
break; // Nothing to do.
default:
// Unhandled preference! For clarity, all preferenes not needing to
// be checked should be put in an empty case something: break; clause
// above.
OP_ASSERT(!"Unhandled preference");
}
// When FALSE is returned, no OpString is created for outvalue
return FALSE;
}
#endif // PREFS_VALIDATE
BOOL PrefsCollectionUI::GetWindowInfo(const OpStringC &which, OpRect &size, WinSizeState &state)
{
PrefsEntry *entry = m_windowsizeprefs->FindEntry(which);
if (entry)
{
// A valid entry was found in the cache; retrieve the data from it
const uni_char *values = entry->Get();
if (values && *values)
{
int x, y, w, h, read_state;
switch (uni_sscanf(values, UNI_L("%d,%d,%d,%d,%d"),
&x, &y, &w, &h, &read_state))
{
case 5:
// Valid window size state and rectangle
state = WinSizeState(read_state);
size.Set(x, y, w, h);
return TRUE;
case 4:
// Valid rectangle
state = INVALID_WINSIZESTATE;
size.Set(x, y, w, h);
return TRUE;
}
}
}
return FALSE;
}
#ifdef PREFS_WRITE
OP_STATUS PrefsCollectionUI::WriteWindowInfoL(const OpStringC &which, const OpRect &size, WinSizeState state)
{
if (which.IsEmpty())
{
OP_ASSERT(!"Must call WriteWindowInfoL with a named window");
LEAVE(OpStatus::ERR_NULL_POINTER);
}
uni_char inival[64]; /* ARRAY OK 2009-02-26 adame */
uni_snprintf(inival, ARRAY_SIZE(inival), UNI_L("%d,%d,%d,%d,%d"),
static_cast<int>(size.x), static_cast<int>(size.y),
static_cast<int>(size.width), static_cast<int>(size.height),
static_cast<int>(state));
#ifdef PREFS_READ
OP_STATUS rc = m_reader->WriteStringL(UNI_L("Windows"), which, inival);
#else
const OP_STATUS rc = OpStatus::OK;
#endif
if (OpStatus::IsSuccess(rc))
{
// Store in cache
m_windowsizeprefs->SetL(which, inival);
}
return rc;
}
#endif // !PREFS_WRITE
void PrefsCollectionUI::ReadCachedQuickSectionsL()
{
// Cache the window size preferences section, since we do not know
// what is inside it :-(
OP_ASSERT(NULL == m_treeview_columns); // Make sure we are not called twice
OP_ASSERT(NULL == m_windowsizeprefs);
OP_ASSERT(NULL == m_treeview_matches);
#ifdef PREFS_READ
m_treeview_columns = m_reader->ReadSectionInternalL(UNI_L("Columns"));
/*DOC
*section=Columns
*name=m_treeview_columns
*key=name of treeview
*type=string
*value=-
*description=List of columns for treeview
*/
m_windowsizeprefs = m_reader->ReadSectionInternalL(UNI_L("Windows"));
/*DOC
*section=Windows
*name=m_windowsizeprefs
*key=name of window
*type=string
*value=x,y,width,height,state
*description=Saved size and state of window
*/
m_treeview_matches = m_reader->ReadSectionInternalL(UNI_L("Matches"));
/*DOC
*section=Matches
*name=m_treeview_matches
*key=name of treeview
*type=string
*value="list", "of", "search", "words"
*description=Remembered search words for quick search
*/
#else
m_treeview_columns = OP_NEW_L(PrefsSectionInternal, ());
m_treeview_columns->ConstructL(NULL);
m_windowsizeprefs = OP_NEW_L(PrefsSectionInternal, ());
m_windowsizeprefs->ConstructL(NULL);
m_treeview_matches = OP_NEW_L(PrefsSectionInternal, ());
m_treeview_matches->ConstructL(NULL);
#endif
}
#ifdef PREFS_HOSTOVERRIDE
void PrefsCollectionUI::ReadOverridesL(const uni_char *host, PrefsSection *section, BOOL active, BOOL from_user)
{
ReadOverridesInternalL(host, section, active, from_user,
m_integerprefdefault, m_stringprefdefault);
}
#endif // PREFS_HOSTOVERRIDE
const uni_char *PrefsCollectionUI::GetColumnSettings(const OpStringC &which)
{
return m_treeview_columns->Get(which);
}
#ifdef PREFS_WRITE
void PrefsCollectionUI::WriteColumnSettingsL(const OpStringC &which, const uni_char *column_string)
{
# ifdef PREFS_READ
m_reader->WriteStringL(UNI_L("Columns"), which, column_string);
# endif
m_treeview_columns->SetL(which, column_string);
}
#endif // PREFS_WRITE
const uni_char *PrefsCollectionUI::GetMatchSettings(const OpStringC &which)
{
return m_treeview_matches->Get(which);
}
#ifdef PREFS_WRITE
void PrefsCollectionUI::WriteMatchSettingsL(const OpStringC &which, const uni_char *match_string)
{
# ifdef PREFS_READ
m_reader->WriteStringL(UNI_L("Matches"), which, match_string);
# endif
m_treeview_matches->SetL(which, match_string);
}
#endif // PREFS_WRITE
void PrefsCollectionUI::ClearMatchSettingsL()
{
#ifdef PREFS_READ
# ifdef PREFS_WRITE
m_reader->ClearSectionL(UNI_L("Matches"));
# endif
// We might still have global or forced values, so re-read
PrefsSectionInternal *new_treeview_matches =
m_reader->ReadSectionInternalL(UNI_L("Matches"));
OP_DELETE(m_treeview_matches); m_treeview_matches = new_treeview_matches;
#endif
}
#endif
|
/*
* Copyright 2019 LogMeIn
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <memory>
#include <queue>
#include <thread>
#include <utility>
#include "asyncly/executor/IStrand.h"
#include "asyncly/executor/Strand.h"
#include "asyncly/task/detail/PeriodicTask.h"
#include "asyncly/executor/ExceptionShield.h"
namespace asyncly {
namespace {
auto createTaskExceptionHandler(
Task&& task, std::function<void(std::exception_ptr)> exceptionHandler)
{
return [task{ std::move(task) }, exceptionHandler{ std::move(exceptionHandler) }] {
try {
task();
} catch (...) {
exceptionHandler(std::current_exception());
}
};
}
}
template <typename Base>
class ExceptionShield final : public Base,
public std::enable_shared_from_this<ExceptionShield<Base>> {
public:
ExceptionShield(
const std::shared_ptr<IExecutor>& executor,
std::function<void(std::exception_ptr)> exceptionHandler);
clock_type::time_point now() const override;
void post(Task&& f) override;
std::shared_ptr<Cancelable> post_at(const clock_type::time_point& t, Task&& f) override;
std::shared_ptr<Cancelable> post_after(const clock_type::duration& t, Task&& f) override;
std::shared_ptr<Cancelable>
post_periodically(const clock_type::duration& t, CopyableTask task) override;
ISchedulerPtr get_scheduler() const override;
private:
const std::shared_ptr<IExecutor> executor_;
const std::function<void(std::exception_ptr)> exceptionHandler_;
};
template <typename Base>
ExceptionShield<Base>::ExceptionShield(
const std::shared_ptr<IExecutor>& executor,
std::function<void(std::exception_ptr)> exceptionHandler)
: executor_{ executor }
, exceptionHandler_{ exceptionHandler }
{
if (!executor_) {
throw std::runtime_error("must pass in non-null executor");
}
if (!exceptionHandler_) {
throw std::runtime_error("must pass in non-null exception handler");
}
}
template <typename Base> clock_type::time_point ExceptionShield<Base>::now() const
{
return executor_->now();
}
template <typename Base> void ExceptionShield<Base>::post(Task&& closure)
{
closure.maybe_set_executor(this->shared_from_this());
executor_->post(createTaskExceptionHandler(std::move(closure), exceptionHandler_));
}
template <typename Base>
std::shared_ptr<Cancelable>
ExceptionShield<Base>::post_at(const clock_type::time_point& t, Task&& closure)
{
closure.maybe_set_executor(this->shared_from_this());
return executor_->post_at(t, createTaskExceptionHandler(std::move(closure), exceptionHandler_));
}
template <typename Base>
std::shared_ptr<Cancelable>
ExceptionShield<Base>::post_after(const clock_type::duration& t, Task&& closure)
{
closure.maybe_set_executor(this->shared_from_this());
return executor_->post_after(
t, createTaskExceptionHandler(std::move(closure), exceptionHandler_));
}
template <typename Base>
std::shared_ptr<Cancelable>
ExceptionShield<Base>::post_periodically(const clock_type::duration& period, CopyableTask task)
{
return detail::PeriodicTask::create(period, std::move(task), this->shared_from_this());
}
template <typename Base>
std::shared_ptr<asyncly::IScheduler> ExceptionShield<Base>::get_scheduler() const
{
return executor_->get_scheduler();
}
IExecutorPtr create_exception_shield(
const IExecutorPtr& executor, std::function<void(std::exception_ptr)> exceptionHandler)
{
if (!executor) {
throw std::runtime_error("must pass in non-null executor");
}
if (is_serializing(executor)) {
return std::make_shared<ExceptionShield<IStrand>>(executor, exceptionHandler);
} else {
return std::make_shared<ExceptionShield<IExecutor>>(executor, exceptionHandler);
}
}
}
|
#include <iostream>
using namespace std;
//s(n)=1+1*2+1*2*3+....+ ...*n
int dequi(int n)
{
if(n==1)
{
return 1;
}
int giaithua=1;
for(int i=2;i<=n;i++)
{
giaithua*=i;
}
return giaithua+dequi(n-1);
}
int giaithua(int n)
{
int gt=1;
for(int i=2;i<=n;i++)
{
gt*=i;
}
return gt;
}
int khudequi(int n)
{
int tong=0;
int gt=1;
for(int i=1;i<=n;i++)
{
tong+=giaithua(i);
// gt*=i;
// tong+=gt;
}
return tong;
}
int dequiduoi(int n,int x=1)
{
if(n==1)
{
return x;
}
int gt=1;
for(int i=2;i<=n;i++)
{
gt*=i;
}
return dequiduoi(n-1,x+gt);
}
int main()
{
int n=5;
cout<<"\n de qui ="<<dequi(n);
cout<<"\n Khu de qui ="<<khudequi(n);
cout<<"\n de qui duoi ="<<dequiduoi(n);
return 0;
}
|
#include <avr/io.h>
#include "IR_library.h"
#include "robotlib.h"
#include "motors.h"
void setup() {
//setupServo();
//setupUltraSonic();
setupMotors();
setupIR();
}
void loop() {
handleIRinput();
}
|
/*In this program we will be seeing about LOOPS CONTROL STATEMENTS in C++ Program*/
/*In C++ break , continue and goto are called as LOOP CONTROL STATEMENT, which is been used for controling the flow of loop in a c++ program.*/
/*In this Example lets see how break works in a program.*/
/*break is a type of loop control statement which is used to terminate a loop, and execute remaining part of a programming statement after loop .*/
/*Syntax of break
break;
*/
/*including preprocessor / header file in the program*/
#include <iostream>
/*using namespace*/
using namespace std ;
/*creating a main() function of the program*/
int main()
{
for ( int i = 1 ; i <= 10 ; i++)
{
cout<<"\nValue of i = " << i << endl ;
if ( i == 7)
{
cout<<"\nBreak has been applied . Thus the loop is terminated when i becomes 7 " << endl ;
break ;
}
}
cout<<"\nBreak Statement has executed SUCCESSFULLY....." << endl ;
}
|
#include "QFileSearch.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFileSearch w;
w.show();
a.installNativeEventFilter(w.filter);
return a.exec();
}
|
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
string k = "##############################################";
cout << " ================================================"<< endl;
cout << " Selamat Datang di Program Pointer "<< endl;
cout << " Mengetahui Nilai Mata Kuliah " << endl;
const int ukuran_array = 5;
int nilai_maksimal = 0;
string namap;
string array[ukuran_array][2];
string kategori;
for(int i = 0; i <= ukuran_array - 1; i++){
cout << k << endl;
cout << "nilai ke-" << i + 1 << endl;
cout << "masukan nama : ";
cin >> *(*(array+i)+0);
cout << "masukan nilai : ";
cin >> *(*(array+i)+1);
cout<<endl;
}
cout << endl << "Kategorisasi Nilai" << endl << k << endl << endl;
for(int p = 0; p <= ukuran_array-1; p++){
string nama = *(*(array+p)+0);
istringstream ss(*(*(array+p)+1));
int nilai;
ss >> nilai;
if(nilai >= 90 && nilai <= 100){
kategori = "A";
}
else if(nilai >= 80 && nilai < 90){
kategori = "B";
}
else if(nilai >= 70 && nilai < 80){
kategori = "C";
}
else if(nilai >= 60 && nilai < 70){
kategori = "D";
}
else if(nilai >= 50 && nilai < 60){
kategori = "E";
}
else if(nilai < 50){
kategori = "Tidak Lulus";
}
cout <<endl<<endl<< k << endl<< "Nama : " << nama << endl << "Nilai : " << nilai << endl << "Kategori Nilai : " << kategori<< endl;
if(nilai > nilai_maksimal){
nilai_maksimal = nilai;
namap = nama;
}
}
cout << endl << k << endl << "Nilai Maksimum : " << nilai_maksimal << endl << "Oleh : " << namap << endl << k << endl;
cout << " Terima Kasih telah Berkunjung" << endl;
return 0;
}
|
//quick select algo to find the kth smallest element
//worst case o(n^2)
#include <iostream>
//#include"lamuto.h"
using namespace std;
void swap(int arr[],int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
int lamuto(int arr[],int l,int h){
int p=arr[h]; //to handle cases when pivot is not the last element
// swap(arr,index,h);// make pivot last element and proceed normally
int j=0;
for(int i=0;i<=h;i++){
if( arr[i]<=p){
swap(arr,i,j);
j++;
}
}
return j-1;
}
int quickSelect(int arr[],int n,int k){
int l=0;
int r=n-1;
while(l<=r){
int p=lamuto(arr,l,r);
if(p==k-1){
return p;
}
if(p>k-1){
r=p-1;
}
else{
l=p+1;
}
}
return -1;
}
int main(int argc, char const *argv[]) {
int arr[]={10,5,11,8,6,26};
int n=sizeof(arr)/sizeof(arr[0]);
int k=3;
printf("Element is %d\n",arr[quickSelect(arr,n,k)] );
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef OP_SOCKET_H
#define OP_SOCKET_H
#ifdef _EXTERNAL_SSL_SUPPORT_
#ifndef _STRUCT_CIPHERENTRY_
#define _STRUCT_CIPHERENTRY_
// convenience structure used to transfer selected ciphers to an external SSL handler
struct cipherentry_st
{
uint8 id[2];
};
#endif // !_STRUCT_CIPHERENTRY_
#endif // _EXTERNAL_SSL_SUPPORT_
class OpSocketAddress;
class OpSocketListener;
#ifdef _EXTERNAL_SSL_SUPPORT_
#include "modules/util/adt/opvector.h"
class OpCertificate;
#endif
class SocketWrapper;
/** @short A socket, an endpoint for [network] communication.
*
* A socket is either a listening socket that accepts incoming remote
* connections, or (more common) a client socket that connects to a
* remote listening socket. Listening sockets will call Listen(),
* while client sockets call Connect(). A socket is never both a
* listening socket and a client socket, so calling Listen() and
* Connect() on the same socket is not allowed.
*
* Socket connect/read/write operations are always non-blocking. Write
* and connect operations are in addition asynchronous.
*
* This means that when attempting to receive data over the socket,
* the implementation will only provide the caller with data already
* in the operating system's network buffer, even if the caller
* requested more data than what's currently available. Likewise, when
* sending data over a socket, the implementation will just fill the
* OS network buffer and return. If not all data could fit in the OS
* network buffer, it will be sent later, when the OS has signalled
* that it can accept more data for sending. Connecting to a remote
* host is also handled asynchronously, meaning that the result of the
* connection attempt is signalled to core via the listener.
*
* A socket object has a listener, which the platform code uses to
* notify core about events (errors, connection established, data
* ready for reading, data sent, etc.). Which listener method calls
* are allowed from a given method in this class is documented
* explicitly for each individual method. If nothing is mentioned
* about allowed listener method calls in the documentation of a
* method, it means that no listener method calls are allowed from
* that method.
*
* When an out-of-memory condition has been reported by an OpSocket
* object, it is in an undefined state, meaning that any further
* operation, except for deleting it, is pointless.
*/
class OpSocket
{
public:
/** Enumeration of possible socket errors. */
enum Error
{
/** No error */
NETWORK_NO_ERROR,
/** Secure socket error handled */
ERROR_HANDLED,
/** Network link error */
NETWORK_ERROR,
/** The requested operation caused the socket to block */
SOCKET_BLOCKING,
/** Connection attempt failed because the remote host actively
* refused to accept the connection */
CONNECTION_REFUSED,
/** Connection attempt to remote host failed */
CONNECTION_FAILED,
/** Operation failed because socket is not connected. */
CONNECTION_CLOSED,
/** Timed out while attempting to connect to remote host */
CONNECT_TIMED_OUT,
/** Timed out while attempting to send data to remote host */
SEND_TIMED_OUT,
/** Timed out while attempting to receive data from remote host */
RECV_TIMED_OUT,
/** While attempting set up a listening socket, the specified
* listening address+port was found to already be in use. */
ADDRESS_IN_USE,
/** Permission to perform the requested operation was denied. */
ACCESS_DENIED,
/** Secure socket connection attempt failed */
SECURE_CONNECTION_FAILED,
/** Network went down */
INTERNET_CONNECTION_CLOSED,
/** The system is temporarily without network access */
OUT_OF_COVERAGE,
/** Unused */
NO_SOCKETS,
/** The remote host name could not be resolved to an address.
*
* While most systems will report this as an error from
* OpHostResolver, some systems can only resolve addresses as
* part of the socket connect stage.
*/
HOST_ADDRESS_NOT_FOUND,
/** Out of memory.
*
* Should only be used when an asynchronous operation runs out
* of memory. In other cases, return OpStatus::ERR_NO_MEMORY
* from the method that ran out of memory is the right thing
* to do.
*/
OUT_OF_MEMORY
};
#ifdef _EXTERNAL_SSL_SUPPORT_
/* Enumeration of possible SSL connection errors returned by OpSocket::GetSSLConnectErrors() */
enum SSLError
{
SSL_NO_ERROR = 0,
CERT_BAD_CERTIFICATE = 1,
CERT_DIFFERENT_CERTIFICATE = 2,
CERT_INCOMPLETE_CHAIN = 4,
CERT_EXPIRED = 8,
CERT_NO_CHAIN = 16
};
#endif // _EXTERNAL_SSL_SUPPORT_
private:
/** Create and return an OpSocket object.
*
* @param socket (output) Set to the socket created
* @param listener The listener of the socket (see
* OpSocketListener)
* @param secure TRUE if the socket is to be secure, meaning that an
* SSL connection is to be established when Connect() is called.
* Note: This parameter will always be FALSE when using Opera's internal SSL
* support. If this is to be a listening socket, blank sockets passed as a
* parameter to Accept() will inherit the secureness of this
* socket. If this is to be such a blank socket, specified secureness
* is in other words overridden by the secureness of the listening
* socket. If the platform implementation cannot honor the requested
* secureness, OpStatus::ERR_NOT_SUPPORTED must be returned. If secure is
* TRUE and the secure connection failes,
* OpSocketListener::OnSocketConnectError(SECURE_CONNECTION_FAILED) must
* be called. Core will then call GetSSLConnectErrors() for more
* detailed errors. Depending on the certificate errors
* core will call the platform callback OpSSLListener::OnCertificateBrowsingNeeded()
* which should trigger a dialog for the user to Accept/Deny access to
* the server.
*
* NOTE: this method should only be called by SocketWrapper::CreateTCPSocket.
* All core code should use SocketWrapper::CreateTCPSocket instead of calling
* this directly.
*
* @return ERR_NO_MEMORY, ERR_NOT_SUPPORTED, ERR or OK
*/
static OP_STATUS Create(OpSocket** socket, OpSocketListener* listener, BOOL secure=FALSE);
// This is the only class that should call OpSocket::Create
friend class SocketWrapper;
public:
/** Destructor.
*
* If there is an active connection, attempt to close it
* gracefully, unless SetAbortiveClose() has been called.
*/
virtual ~OpSocket() {}
/** Connect a socket to a given address.
*
* The listener (OpSocketListener) is to be called to provide
* feedback (connection established, connection failed) to the
* caller.
*
* A connection attempt is initiated by calling this method. It is
* concluded when OnSocketConnected() or OnSocketConnectError() is
* called, or when this method returns an error value.
*
* OnSocketConnected() is called as soon as the connection attempt
* succeeds. Then the socket is connected, and core should expect
* the listener methods OnSocketDataReady() and OnSocketClosed()
* to be called any time.
*
* Opera sockets are non-blocking, meaning that if the platform
* side cannot succeed or fail connecting immediately,
* OpStatus::OK is returned, and then core will be notified later
* via the listener how the connection attempt went. Otherwise,
* OnSocketConnectError() will be called with an error code.
*
* If the connection attempt succeeded, from now on the
* implementation will automatically call the listener method
* OnSocketDataReady() when data arrives and OnSocketClosed() when
* the remote end closes the connection.
*
* A socket is never both a listening socket and a client socket,
* so calling Listen() and Connect() on the same socket is not
* allowed.
*
* Allowed error codes to pass via the listener triggered by
* calling this method: NETWORK_ERROR, CONNECTION_REFUSED,
* CONNECTION_FAILED, CONNECT_TIMED_OUT,
* INTERNET_CONNECTION_CLOSED, OUT_OF_COVERAGE,
* HOST_ADDRESS_NOT_FOUND and SECURE_CONNECTION_FAILED (when
* an external ssl library is used. In case of secure
* socket, OnSocketConnected() can only be called when the socket
* is connected and the ssl connection has been established).
*
* Allowed listener methods to call triggered by calling this
* method: OnSocketConnected(), OnSocketConnectError(). The
* listener methods may be called after this method has returned,
* but only if it returned OpStatus::OK.
*
* @param socket_address A socket address. The address must be
* valid - i.e. socket_address->IsAddressValid() must return TRUE
* if called. Port number may not be 0. The implementation must
* not use this socket address object after this method has
* returned.
*
* @return OK if no immediate error. OK does not mean that the
* connection attempt was successful, unless OnSocketConnected() of
* the listener has already been called (it may just mean "nothing
* wrong so far"). ERR is returned when the connection attempt failed
* instantly - hopefully preceded by a call to OnSocketConnectError()
* of the listener (or core will not be able to tell why it
* failed). ERR_NO_MEMORY is returned on OOM.
*/
virtual OP_STATUS Connect(OpSocketAddress* socket_address) = 0;
/** Send data over the socket.
*
* The listener (OpSocketListener) is to be called to provide
* feedback to the caller. Feedback includes progress information
* and errors.
*
* Opera sockets are non-blocking, meaning that if not all data
* could be sent immediately, an implementation shall keep unsent
* data, return, and attempt to send it later, when the OS is
* ready to accept more data. Listener methods may be called any
* time here. OnSocketDataSent() is to be called every time some
* data could be sent to the OS successfully.
*
* Call OnSocketSendError() when errors related to sending
* occur. One common error may be that Send() is called too soon
* after a previous call, so that the implementation hasn't been
* able to deliver all data to the OS yet. In that case, call
* OnSocketSendError() with SOCKET_BLOCKING, and return
* OpStatus::ERR, so that the caller may try again later. The
* caller should wait for another call to OnSocketDataSent()
* before retrying.
*
* Allowed error codes to pass via the listener triggered by
* calling this method: NETWORK_ERROR, SEND_TIMED_OUT,
* INTERNET_CONNECTION_CLOSED, OUT_OF_COVERAGE.
*
* Allowed listener method to call triggered by calling this method:
* OnSocketSendError(). The listener method may be called after this
* method has returned, but only if it returned OpStatus::OK.
*
* This method must be re-entrancy safe. However, when it is
* re-entered, the implementation has to signal a SOCKET_BLOCKING
* error when reaching some recursion level (so that the we don't run
* out of stack). Doing this already at the first re-entry is
* recommended, but not required if the platform handles deep
* recursions well.
*
* This method may not be called on a closed socket, i.e. when
* OnSocketClosed() has already been called, or before OnSocketConnected()
* has been called.
*
* @param data The data to send. The caller is free to re-use the data
* buffer for other purposes as soon as this method returns. In other
* words: If not all data can be sent immediately, the platform must
* make a copy of the unsent data, since the buffer passed in this
* parameter may have been overwritten with other data before the
* platform is ready to send the remaining data.
* @param length The length of the data
*
* @return OK if no error (meaning: "data is (or will be) sent").
* Return ERR_NO_MEMORY on OOM. Return ERR on serious errors that
* cannot be expressed via OnSocketSendError() of
* OpSocketListener. Returning ERR means that the data passed was
* not accepted, so that the caller needs to resend (it if it
* doesn't just want to give up).
*/
virtual OP_STATUS Send(const void* data, UINT length) = 0;
/** Receive data over the socket.
*
* The listener (OpSocketListener) is to be called to provide
* feedback (read errors, connection closed) to the caller.
*
* This is a non-blocking call, meaning that the implementation may not
* wait for additional data to arrive over the network before it returns;
* it will simply fill the buffer with what is already in the operating
* system's input buffer (which may well be empty, which is not an error
* condition).
*
* Allowed error codes to pass via the listener when calling this
* method: NETWORK_ERROR, SOCKET_BLOCKING, RECV_TIMED_OUT,
* INTERNET_CONNECTION_CLOSED, OUT_OF_COVERAGE.
*
* Allowed listener method to calls triggered by calling this method:
* OnSocketReceiveError() and OnSocketClosed(). Only to be called
* synchronously (before this method returns). OpStatus::ERR is always
* returned from this method if OnSocketReceiveError() was called. Calling
* OnSocketClosed() does not signify an error; it just means that the
* connection was closed by the remote endpoint while the local endpoint
* tried to read data. *bytes_received is set to 0 and OpStatus::OK is
* returned in this case.
*
* This method may not be called on a closed socket, i.e. when
* OnSocketClosed() has already been called, or before OnSocketConnected()
* has been called.
*
* @param buffer (output) A buffer - the buffer to write received data
* into. Must be ignored by the caller unless OpStatus::OK is returned.
* @param length Maximum number of bytes to read
* @param bytes_received (output) Set to the number of bytes actually
* read. Must be ignored by the caller unless OpStatus::OK is returned.
*
* @return OK, ERR or ERR_NO_MEMORY.
*/
virtual OP_STATUS Recv(void* buffer, UINT length, UINT* bytes_received) = 0;
/** Close the socket.
*
* Allowed listener method to call triggered by calling this method:
* OnSocketCloseError(). Only to be called synchronously (before this
* method returns).
*/
virtual void Close() = 0;
/** Get the address of the remote end of the socket connection.
*
* @param socket_address a socket address to be filled in
*/
virtual OP_STATUS GetSocketAddress(OpSocketAddress* socket_address) = 0;
#ifdef OPSOCKET_GETLOCALSOCKETADDR
/** Get the address of the local end of the socket connection.
*
* @param socket_address a socket address to be filled in
*/
virtual OP_STATUS GetLocalSocketAddress(OpSocketAddress* socket_address) = 0;
#endif // OPSOCKET_GETLOCALSOCKETADDR
/** Set or change the listener for this socket.
*
* @param listener New listener to set.
*/
virtual void SetListener(OpSocketListener* listener) = 0;
#ifdef SOCKET_LISTEN_SUPPORT
# ifndef DOXYGEN_DOCUMENTATION
/** @deprecated Use Listen(OpSocketAddress*, int) instead. */
DEPRECATED(virtual OP_STATUS Bind(OpSocketAddress* socket_address)); // inlined below
/** @deprecated Use Listen(OpSocketAddress*, int) instead. */
DEPRECATED(virtual OP_STATUS SetLocalPort(UINT port)); // inlined below
/** @deprecated Use Listen(OpSocketAddress*, int) instead. */
DEPRECATED(virtual OP_STATUS Listen(UINT queue_size)); // inlined below
# endif // !DOXYGEN_DOCUMENTATION
/** Set the socket to listen for incoming connections on a given address+port.
*
* Binds the socket to a local address+port and creates a queue to hold
* incoming connections, which can be married with blank sockets using
* Accept(). Once a listen queue has been created, clients' connection
* requests will be appended until the queue is full, at which point it
* will reject any incoming connection requests.
*
* A socket is never both a listening socket and a client socket,
* so calling Listen() and Connect() on the same socket is not
* allowed.
*
* Allowed error codes to pass via the listener when calling this
* method: NETWORK_ERROR, ADDRESS_IN_USE, ACCESS_DENIED
*
* Allowed listener method to call triggered by calling this method:
* OnSocketListenError() and OnSocketConnectionRequest().
*
* OnSocketListenError() is only to be called synchronously (before this
* method returns). OpStatus::ERR is always returned from this method if
* OnSocketListenError() was called. The error code ADDRESS_IN_USE is used
* when attempting to use an address+port to which another listening socket
* has already been bound. ACCESS_DENIED is used when attempting to use an
* address+port to which the user doesn't have permission (e.g. port
* numbers less than 1024 on UNIX systems). NETWORK_ERROR may be used in
* other, network related, error situations. For other error situations, no
* listener method will be called.
*
* OnSocketConnectionRequest() is only to be called asynchronously (after
* this method has returned), whenever there are pending connection
* requests in the queue.
*
* @param socket_address A local socket address. The actual address part
* may specify on which network interface (loopback, ethernet interface 1,
* ethernet interface 2, etc.) to bind the socket, if the system provides
* multiple network interfaces. If no address is set (i.e. if
* socket_address->IsAddressValid() would return FALSE if called), the
* default network interface on the system will be used. The port number
* must always be set. The implementation must not use this socket address
* object after this method has returned.
* @param queue_size Maximum number of incoming connection requests in the
* queue
*
* @return OK if successful, ERR_NO_MEMORY on OOM, ERR for other errors (a
* listener method may or may not have been called if ERR is returned).
*/
virtual OP_STATUS Listen(OpSocketAddress* socket_address, int queue_size) = 0;
/** Accept a pending socket connection request to the listening socket.
*
* Prior to this call, a successful call to Listen() must have taken place.
*
* This method extracts the first pending connection request from the queue
* created by Listen() and connects it to the parameter-specified socket.
*
* Allowed error codes to pass via the listener triggered by calling this
* method: SOCKET_BLOCKING, NETWORK_ERROR, CONNECT_TIMED_OUT,
* INTERNET_CONNECTION_CLOSED, OUT_OF_COVERAGE.
*
* Allowed listener method to call triggered by calling this method:
* OnSocketConnectError(). Only to be called synchronously (before this
* method returns). OpStatus::ERR is always returned from this method if
* OnSocketConnectError() was called. The error code SOCKET_BLOCKING is
* used if there were no pending connection requests in the queue. The
* parameter-specified socket may be re-used in a future call to Accept()
* if this happened.
*
* @param socket (out) A socket to represent the accepted connection.
*
* @return OK if successful, ERR_NO_MEMORY on OOM, ERR for other errors (a
* listener method may or may not have been called if ERR is returned). If
* OK is returned, the parameter-specified socket is ready for use (Recv(),
* Send(), Close(), ...).
*/
virtual OP_STATUS Accept(OpSocket* socket) = 0;
#endif // SOCKET_LISTEN_SUPPORT
#ifdef _EXTERNAL_SSL_SUPPORT_
/** Upgrade the TCP connection to a secure connection.
*
* This function is only called by core when an SSL connection is
* established over a HTTP proxy connection.
*
* Keep the TCP connection open, and start establishing SSL on the
* connection. Call OpSocketListener::OnSocketConnected() or
* OpSocketListener::OnSocketConnectError(SECURE_CONNECTION_FAILED) when
* done.
*
* @return OK if successful, ERR_NO_MEMORY on OOM
*/
virtual OP_STATUS UpgradeToSecure() = 0;
/** Initialize the ciphers and protocol version of a secure socket.
*
* Note: this only works for SSL v3 and newer
*
* @param ciphers An array of structures holding the two element array with
* the cipher specification selected for this socket
* @param cipher_count The number of elements in the cipher array protocol
* support
*
* Note that this call can be ignored if it is not possible to set the
* ciphers used by the external SSL library.
*
* @return OK if successful, ERR_NO_MEMORY on OOM
*/
virtual OP_STATUS SetSecureCiphers(const cipherentry_st* ciphers, UINT cipher_count) = 0;
/** Accept insecure certificate.
*
* When OpSocketListener::OnSocketConnectError() has been called, core will
* call GetSSLConnectErrors(). If GetSSLConnectErrors() reports a
* certificate error, core will call ExtractCertificate() and ask user to
* accept/deny. If the certificate is accepted, this function will be
* called.
*
* @param certificate The certificate to be accepted. It must be checked
* that this is the same certificate as given by ExtractCertificate on this
* socket.
*
* @return OK if successful, ERR_NO_MEMORY on OOM, ERR if certificate is
* not the same as current certificate.
*/
virtual OP_STATUS AcceptInsecureCertificate(OpCertificate *certificate) = 0;
/** Get the current cipher, TLS protocol version and Public Key length in bits.
*
* @param used_cipher Return the current SSL/TLS cipher ID in this
* structure
* @param tls_v1_used Return a SSL/TLS version indicator here
* (TRUE if it is TLS v1, FALSE if SSL v3)
* @param pk_keysize Return the Public Key cipher's key length (in
* bits) here. If the cipher length is unavailable return 0.
*
* @return OK if the cipher was successfully retrieved, ERR_NO_MEMORY on OOM.
*/
virtual OP_STATUS GetCurrentCipher(cipherentry_st* used_cipher, BOOL* tls_v1_used, UINT32* pk_keysize) = 0;
/** Set the host name.
*
* This is used to test the validity of a certificate
*
* @param server_name The name of the server.
*
* @return OpStatus::OK if servername was successfully set,
* OpStatus::ERR_NO_MEMORY if memory allocation error occurred
*/
virtual OP_STATUS SetServerName(const uni_char* server_name) = 0;
/** Get the server certificate used for secure socket.
*
* @return The SSL/TLS server certificate wrapper. The certificate is owned
* and must be deleted by caller. Returns NULL if memory error.
*/
virtual OpCertificate *ExtractCertificate() = 0;
/** Get the server full certificate chain used for secure socket.
*
* @return The SSL/TLS server certificate wrapper. The certificate chain is
* owned and must be deleted by caller. The chain starts with the server
* certificate and ends with the top CA certificate. Returns NULL if memory
* error.
*/
virtual OpAutoVector<OpCertificate> *ExtractCertificateChain() = 0;
/** Get SSL connection errors.
*
* Returns the SSL errors that caused the call to OnSocketConnectError()
* with error SECURE_CONNECTION_FAILED.
*
* @return The errors - Bit array of ORed errors as enumerated in
* OpSocket::SSLError
*/
virtual int GetSSLConnectErrors() = 0;
#endif // _EXTERNAL_SSL_SUPPORT_
#ifdef SOCKET_NEED_ABORTIVE_CLOSE
/** Inform the socket layer that an abortive close is required.
*
* To avoid unwanted re-transmissions in the TCP layer after closing a
* socket for e.g. a timed out HTTP connection, it is necessary to signal
* that the socket close should happen abortively. If this is signalled to
* the socket implementation the platform layer should do its best to shut
* down the socket immediately, resetting the socket connection if
* necessary.
*/
virtual void SetAbortiveClose() = 0;
#endif // SOCKET_NEED_ABORTIVE_CLOSE
#ifdef SOCKET_SUPPORTS_TIMER
/** Change the socket idle timeout.
*
* Initial state of a socket is the default timeout value.
*
* Using an idle timer, after a certain time of socket inactivity, the
* socket may disconnect (or, if not yet connected, cancel the connection
* attempt), and report this situation using OpSocketListener. If the idle
* timer expires while the socket is attempting to connect to the remote
* host, OnSocketConnectError(CONNECT_TIMED_OUT) is called.
*
* @param seconds Number of seconds of socket inactivity to allow before
* disconnecting the socket. If this value is 0, there will be no idle
* timeout. This parameter is ignored if the 'restore_default' parameter is
* TRUE.
* @param restore_default If TRUE, ignore the 'seconds' parameter and use
* system default timeout interval. This is the initial state of a socket.
*/
virtual void SetTimeOutInterval(unsigned int seconds, BOOL restore_default = FALSE) = 0;
#endif // SOCKET_SUPPORTS_TIMER
#ifdef OPSOCKET_PAUSE_DOWNLOAD
/** Pause data reception.
*
* Temporarily stop receiving data from the socket. While loading is
* paused, an OpSocket will attempt to stop receiving data, and, more
* importantly, not notify its listener even if there's more data available
* for reading. No data must be lost because of a pause. A user of this
* feature should be aware that pausing for too long may cause the remote
* end to time out and close the connection.
*
* @return OK if no error
*
* @see ContinueRecv()
*/
virtual OP_STATUS PauseRecv() = 0;
/** Resume data reception.
*
* The counterpart to the PauseRecv() method. It resumes data
* reception after a pause.
*
* @return OK if no error
*
* @see PauseRecv()
*/
virtual OP_STATUS ContinueRecv() = 0;
#endif // OPSOCKET_PAUSE_DOWNLOAD
#ifdef OPSOCKET_OPTIONS
/**
* Enumeration of socket options that can be enabled/disabled using OpSocket::SetSocketOption().
*/
enum OpSocketBoolOption
{
/**
* Disables Nagle's algorithm for TCP sockets.
*
* If a program writes a single byte to a socket it would be
* incredibly inefficient to attach a full IP + TCP header to
* that and send it a cross the network immediately. To avoid
* this OS network stacks will typically buffer the written
* data until either A) more data to be sent has arrived, or
* B) some amount of time has passed at which point the OS has
* no choice but to send the inefficient packet anyway.
* For protocols that rely on roundtriping very small packages
* over TCP at very low latency this behavior can incur a
* performance penalty and then this socket option can be
* used to force the OS the always send the data over the
* wire immediate when it arrives to the network stack.
*
* When this socket option is enabled it's a good idea to
* try and send() full packets in one go if possible.
*
* This option applies only to TCP sockets and cannot / must
* not be enabled or disabled for UDP sockets.
*
* See also: http://en.wikipedia.org/wiki/Nagle's_algorithm
*/
SO_TCP_NODELAY
};
/**
* Configure socket behavior.
*
* Allows the user to opt into non-standard socket behavior,
* see OpSocketOption for information on specific options.
* Options may exists at various protocol levels, e.g. IP, TCP etc.
*
* NOTE: This method may only be called while the socket is connected,
* i.e. during or after OnConnected() is called on the listener
* and not after the socket is closed.
*
*
* @param option See @ref OpSocketOption.
* @param value indicates whether this socket option is to be turned on or off.
* @return OK if the socket option was applied without errors
* @return ERR_OUT_OF_RANGE if invalid parameters were passed via "value" or "value_len"
* @return ERR for all other errors, including network errors etc.
* @return ERR_BAD_FILE_NUMBER if the socket object or subsystem is invalid,
* this error should be considered a bug in the calling code or
* in the socket platform implementation.
*/
virtual OP_STATUS SetSocketOption(OpSocketBoolOption option, BOOL value) = 0;
/**
* Get socket configuration.
*
* Allows the user to see if a certain socket option is currently activated or not.
* See OpSocketOption for information on specific options.
* Options may exists at various protocol levels, e.g. IP, TCP etc.
*
* NOTE: This method may only be called while the socket is connected,
* i.e. during or after OnConnected() is called on the listener
* and not after the socket is closed.
*
* @param option See @ref OpSocketOption.
* @param out_value out parameter where a boolean value is stored indicating
* whether this socket option is currently turned on or off.
* @return OK if the socket option was read without errors.
* @return ERR_OUT_OF_RANGE if invalid parameters were passed via "value" or "value_len".
* @return ERR for all other errors, including network errors etc.
* @return ERR_BAD_FILE_NUMBER if the socket object or subsystem is invalid,
* this error should be considered a bug in the calling code or
* in the socket platform implementation.
*/
virtual OP_STATUS GetSocketOption(OpSocketBoolOption option, BOOL& out_value) = 0;
#endif // OPSOCKET_OPTIONS
};
#ifdef SOCKET_LISTEN_SUPPORT
# ifndef DOXYGEN_DOCUMENTATION
inline OP_STATUS OpSocket::Bind(OpSocketAddress* socket_address) { return OpStatus::ERR; }
inline OP_STATUS OpSocket::SetLocalPort(UINT port) { return OpStatus::ERR; }
inline OP_STATUS OpSocket::Listen(UINT queue_size) { return OpStatus::ERR; }
# endif // DOXYGEN_DOCUMENTATION
#endif // SOCKET_LISTEN_SUPPORT
/** Socket listener - implemented in core code, called from platform code.
*
* An object of this class is notified about any state changes or events that
* occur on the socket to which it subscribes.
*
* Note: Unless explicitly mentioned, any method call on an object of
* this class may cause the calling socket to be deleted. Therefore,
* make sure that there is nothing on the call stack referencing the
* socket after the listener method has returned.
*
* As an object could conceivably observe more than one socket at a
* time, sockets calling these methods pass a pointer to the
* signalling socket.
*/
class OpSocketListener
{
public:
virtual ~OpSocketListener() {}
/** The socket has connected to a remote host successfully.
*
* @param socket The socket which has connected
*/
virtual void OnSocketConnected(OpSocket* socket) = 0;
/** There is data ready to be received on the socket.
*
* This listener method is called (typically from the event loop on
* the platform side) as long as there is any data at all waiting to
* be read. There doesn't necessarily have to be any new data since
* the previous call. This means that core should read some (as much
* as possible) data (OpSocket::Recv()) when this method is called, to
* prevent it from throttling.
*
* @param socket The socket that is ready for reading
*/
virtual void OnSocketDataReady(OpSocket* socket) = 0;
/** Data has been sent on the socket.
*
* As a response, core may want to send (OpSocket::Send()) more data,
* if there is any left to send. It is legal to do this
* immediately. The platform is responsible for avoiding infinite
* recursion.
*
* @param socket The socket that has sent data
* @param bytes_sent The number of bytes sent
*/
virtual void OnSocketDataSent(OpSocket* socket, UINT bytes_sent) = 0;
/** The socket has closed.
*
* This informs core that there is no more data to be read. Core should not
* try to read or write on a closed socket. Platform code needs to make
* sure that all data has been received (with Recv()) before calling this
* listener method.
*
* @param socket The socket that was closed.
*/
virtual void OnSocketClosed(OpSocket* socket) = 0;
#ifdef SOCKET_LISTEN_SUPPORT
/** A listening socket has received an incoming connection request.
*
* A typical response to this method call is to call socket->Accept().
*
* This listener method is called (typically from the event loop on the
* platform side) as long as there are any pending connection requests at
* all in the queue. There doesn't necessarily have to be any new
* connection requests since the previous call. This means that core should
* attempt to accept as many connections as possible (at least one) when
* this method is called, to prevent it from throttling.
*
* @param socket listening socket from which the request is coming
*/
virtual void OnSocketConnectionRequest(OpSocket* socket) = 0;
/** An error has occured on the socket whilst setting it up for listening.
*
* @param socket The socket on which the error has occurred
* @param error The error - as enumerated in OpSocket.
*/
virtual void OnSocketListenError(OpSocket* socket, OpSocket::Error error) = 0;
#endif // SOCKET_LISTEN_SUPPORT
/** An error has occured on the socket whilst connecting.
*
* This method is also called when accepting a new incoming connection on a
* listening socket fails.
*
* @param socket The socket on which the error has occurred
* @param error The error - as enumerated in OpSocket.
*/
virtual void OnSocketConnectError(OpSocket* socket, OpSocket::Error error) = 0;
/** An error has occured on the socket whilst receiving.
*
* @param socket The socket on which the error has occurred
* @param error The error - as enumerated in OpSocket.
*/
virtual void OnSocketReceiveError(OpSocket* socket, OpSocket::Error error) = 0;
/** An error has occured on the socket whilst sending.
*
* @param socket The socket on which the error has occurred
* @param error The error - as enumerated in OpSocket.
*/
virtual void OnSocketSendError(OpSocket* socket, OpSocket::Error error) = 0;
/** An error has occured on the socket whilst closing.
*
* @param socket The socket on which the error has occurred
* @param error The error - as enumerated in OpSocket.
*/
virtual void OnSocketCloseError(OpSocket* socket, OpSocket::Error error) = 0;
#ifndef URL_CAP_TRUST_ONSOCKETDATASENT
/** Data has been sent.
*
* This method is soon to be removed.
*
* @param socket The socket on which the data has been sent
* @param bytes_sent Number of bytes sent
*/
virtual void OnSocketDataSendProgressUpdate(OpSocket* socket, UINT bytes_sent) { }
#endif // !URL_CAP_TRUST_ONSOCKETDATASENT
};
#ifdef PI_INTERNET_CONNECTION
# include "modules/url/url_socket_wrapper.h"
#endif // PI_INTERNET_CONNECTION
#endif // !OP_SOCKET_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 2009-2011
*
* WebGL GLSL compiler -- AST representation.
*
*/
#ifndef WGL_AST_H
#define WGL_AST_H
#include "modules/webgl/src/wgl_base.h"
#include "modules/webgl/src/wgl_glsl.h"
#include "modules/util/simset.h"
#include "modules/webgl/src/wgl_symbol.h"
class WGL_PrettyPrinter;
class WGL_ExprVisitor;
class WGL_Expr;
class WGL_ExprList;
class WGL_LiteralExpr;
class WGL_VarExpr;
class WGL_TypeConstructorExpr;
class WGL_UnaryExpr;
class WGL_PostExpr;
class WGL_SeqExpr;
class WGL_BinaryExpr;
class WGL_CallExpr;
class WGL_CondExpr;
class WGL_IndexExpr;
class WGL_SelectExpr;
class WGL_AssignExpr;
class WGL_Type;
class WGL_ExprVisitor
{
public:
virtual WGL_Expr *VisitExpr(WGL_LiteralExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_VarExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_TypeConstructorExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_UnaryExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_PostExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_SeqExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_BinaryExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_CondExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_CallExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_IndexExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_SelectExpr *e) = 0;
virtual WGL_Expr *VisitExpr(WGL_AssignExpr *e) = 0;
virtual WGL_ExprList *VisitExprList(WGL_ExprList *ls);
};
class WGL_Expr
: public ListElement<WGL_Expr>
{
public:
enum Type
{
None = 0,
Lit,
Var,
TypeConstructor,
Unary,
PostOp,
Seq,
Binary,
Cond,
Call,
Index,
Select,
Assign
};
WGL_Expr()
: cached_type(NULL)
{
}
virtual ~WGL_Expr()
{
}
WGL_Type *GetExprType() { return cached_type; }
/**< Return the recorded type for this expression. The
static analyser / validator will annotate expressions
with types, hence this will return NULL prior to (or during)
it. */
virtual WGL_Expr::Type GetType()
{
return None;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v) = 0;
enum Precedence
{
/* Section 5.1 table */
PrecLowest = 0,
PrecComma = 1,
PrecAssign = 2, // right assoc + all of them
PrecCond = 3,
PrecLogOr = 4,
PrecLogXor = 5,
PrecLogAnd = 6,
PrecEq = 7,
PrecRel = 8,
PrecAdd = 9,
PrecMul = 10,
PrecPrefix = 11, // right-associative.
PrecPostfix = 12,
PrecCall = 13,
PrecFieldSel = 14,
PrecHighest = 15
};
enum Associativity
{
AssocNone = 0,
AssocLeft = 1,
AssocRight = 2
};
/* Associativity in LSB, precedence above that. */
typedef unsigned PrecAssoc;
/* Expression operators, infix and postfix. */
enum Operator
{
OpBase,
OpCond,
OpComma,
OpAssign,
OpOr,
OpXor,
OpAnd,
OpFieldSel,
OpEq,
OpNEq,
OpLt,
OpGt,
OpLe,
OpGe,
OpAdd,
OpSub,
OpMul,
OpDiv,
OpPreInc,
OpPreDec,
OpNot,
OpNegate,
OpPostInc,
OpPostDec,
OpCall,
OpIndex,
OpNop
};
static WGL_Expr *Clone(WGL_Context *context, WGL_Expr *e);
/**< Clone the given expression into the environment (and allocator)
associated with 'context'. OOM is signalled via the context
if encountered and NULL returned. NULL may also be returned
if the expression is not cloneable. */
WGL_Type *cached_type;
/**< If non-NULL, the computed type for this expression. */
};
class WGL_Literal
{
public:
enum Type
{
Double = 1,
Int,
UInt,
Bool,
Vector,
Matrix,
Array,
Struct,
String
};
struct DoubleValue
{
double value;
const uni_char *value_string;
};
union Value
{
DoubleValue d;
int i;
unsigned u_int;
bool b;
const uni_char *s;
};
Type type;
Value value;
WGL_Literal(Type t)
: type(t)
{
// Initializing the largest element in the union to zero.
value.d.value = 0;
value.d.value_string = NULL;
}
WGL_Literal(double d, const uni_char *lit_str)
: type(Double)
{
value.d.value = d;
value.d.value_string = lit_str;
}
WGL_Literal(int i)
: type(Int)
{
value.i = i;
}
WGL_Literal(unsigned ui)
: type(UInt)
{
value.u_int = ui;
}
WGL_Literal(const uni_char *s)
: type(String)
{
value.s = s; // no copying.
}
WGL_Literal(WGL_Literal *l);
virtual void Show(WGL_PrettyPrinter *p);
static Value ToDouble(Type t, Value v);
static Value ToUnsignedInt(Type t, Value v);
static Value ToInt(Type t, Value v);
static Value ToBool(Type t, Value v);
};
class WGL_TypeQualifier;
class WGL_TypeVisitor;
class WGL_Type
: public ListElement<WGL_Type>
{
public:
enum Type
{
NoType = 0,
Basic,
Vector,
Matrix,
Sampler,
Name,
Struct,
Array
};
/** GLSL precision attributes on types. */
enum Precision
{
NoPrecision = 0,
Low,
Medium,
High
};
WGL_Type(BOOL is_heap_allocated)
: type_qualifier(NULL)
, precision(NoPrecision)
, implicit_precision(FALSE)
, is_heap_allocated(is_heap_allocated)
{
}
virtual ~WGL_Type();
WGL_Type *AddPrecision(WGL_Type::Precision p);
WGL_Type *AddTypeQualifier(WGL_TypeQualifier *tq);
virtual Type GetType()
{
return NoType;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v) = 0;
WGL_TypeQualifier *type_qualifier;
Precision precision;
BOOL implicit_precision;
/**< TRUE if the validator inserted the precision by resolving it. */
BOOL is_heap_allocated;
/**< If TRUE, delete type components upon free. */
void Show(WGL_PrettyPrinter *printer);
static void Show(WGL_PrettyPrinter *p, Precision op);
static BOOL IsVectorType(WGL_Type *t, unsigned basic_type_mask = 0);
static BOOL IsMatrixType(WGL_Type *t, unsigned basic_type_mask = 0);
static BOOL HasBasicType(WGL_Type *t, unsigned basic_type_mask = 0);
static WGL_Type *CopyL(WGL_Type *t);
static unsigned GetTypeSize(WGL_Type *t);
};
class WGL_ArrayType;
class WGL_VectorType;
class WGL_MatrixType;
class WGL_SamplerType;
class WGL_NameType;
class WGL_StructType;
class WGL_BasicType;
class WGL_TypeVisitor
{
public:
virtual WGL_Type *VisitType(WGL_BasicType *t) = 0;
virtual WGL_Type *VisitType(WGL_ArrayType *t) = 0;
virtual WGL_Type *VisitType(WGL_VectorType *t) = 0;
virtual WGL_Type *VisitType(WGL_MatrixType *t) = 0;
virtual WGL_Type *VisitType(WGL_SamplerType *t) = 0;
virtual WGL_Type *VisitType(WGL_NameType *t) = 0;
virtual WGL_Type *VisitType(WGL_StructType *t) = 0;
};
class WGL_BasicType
: public WGL_Type
{
public:
/** Builtin base types for GLSL. Along with these, there are also
* the vector, matrix and sampler types. */
enum Type
{
Void = 0,
Float = 1,
Int = 2,
UInt = 4,
Bool = 8
};
WGL_BasicType(Type ty, BOOL is_heap_allocated)
: WGL_Type(is_heap_allocated)
, type(ty)
{
}
virtual ~WGL_BasicType();
virtual WGL_Type::Type GetType()
{
return WGL_Type::Basic;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v)
{
return v->VisitType(this);
}
static WGL_BasicType::Type GetBasicType(WGL_Type *t);
static WGL_Literal::Type ToLiteralType(WGL_BasicType::Type t);
Type type;
};
/** WGL_LiteralVector is constructed internally to hold vector constants;
i.e., not directly generated by the frontend. */
class WGL_LiteralVector
: public WGL_Literal
{
public:
WGL_LiteralVector(WGL_BasicType::Type element_type)
: WGL_Literal(WGL_Literal::Vector)
, element_type(element_type)
{
}
union Value
{
double *doubles;
int *ints;
unsigned *u_ints;
bool *bools;
};
virtual void Show(WGL_PrettyPrinter *p);
WGL_BasicType::Type element_type;
Value value;
unsigned size;
};
/** WGL_LiteralVector is constructed internally to hold array constants;
not supported by the source language. */
class WGL_LiteralArray
: public WGL_Literal
{
public:
WGL_LiteralArray(WGL_BasicType::Type element_type)
: WGL_Literal(WGL_Literal::Array)
, element_type(element_type)
, size(0)
{
}
union Value
{
double *doubles;
int *ints;
unsigned *u_ints;
bool *bools;
};
virtual void Show(WGL_PrettyPrinter *p);
WGL_BasicType::Type element_type;
Value value;
unsigned size;
};
class WGL_LiteralExpr
: public WGL_Expr
{
public:
WGL_LiteralExpr(WGL_Literal *l)
: literal(l)
{
}
virtual ~WGL_LiteralExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return Lit;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
static WGL_BasicType::Type GetBasicType(WGL_LiteralExpr *e);
WGL_Literal *literal;
};
class WGL_VarExpr
: public WGL_Expr
{
public:
WGL_VarExpr(WGL_VarName *n)
: name(n)
, const_name(NULL)
, intrinsic(WGL_GLSL::NotAnIntrinsic)
{
}
WGL_VarExpr(const uni_char *nm)
: name(NULL)
, const_name(nm)
, intrinsic(WGL_GLSL::NotAnIntrinsic)
{
}
virtual ~WGL_VarExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return Var;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_VarName *name;
const uni_char *const_name;
WGL_GLSL::Intrinsic intrinsic;
/**< If > 0, the variable is a known GLSL intrinsic. The static analyzer
will decorate the variables (in function application position) with
this info. */
};
class WGL_TypeConstructorExpr
: public WGL_Expr
{
public:
WGL_TypeConstructorExpr(WGL_Type *t)
: constructor(t)
{
}
virtual ~WGL_TypeConstructorExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::TypeConstructor;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Type *constructor;
};
class WGL_UnaryExpr
: public WGL_Expr
{
public:
WGL_UnaryExpr(WGL_Expr::Operator o, WGL_Expr *e)
: op(o)
, arg(e)
{
}
virtual ~WGL_UnaryExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Unary;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr::Operator op;
WGL_Expr *arg;
};
class WGL_PostExpr
: public WGL_Expr
{
public:
WGL_PostExpr(WGL_Expr::Operator o, WGL_Expr *e)
: arg(e)
, op(o)
{
}
virtual ~WGL_PostExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::PostOp;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr *arg;
WGL_Expr::Operator op;
};
class WGL_SeqExpr
: public WGL_Expr
{
public:
WGL_SeqExpr(WGL_Expr *e1, WGL_Expr *e2)
: arg1(e1)
, arg2(e2)
{
}
virtual ~WGL_SeqExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Seq;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr *arg1;
WGL_Expr *arg2;
};
class WGL_BinaryExpr
: public WGL_Expr
{
public:
WGL_BinaryExpr(WGL_Expr::Operator o, WGL_Expr *e1, WGL_Expr *e2)
: op(o)
, arg1(e1)
, arg2(e2)
{
}
virtual ~WGL_BinaryExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Binary;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr::Operator op;
WGL_Expr *arg1;
WGL_Expr *arg2;
};
class WGL_CondExpr
: public WGL_Expr
{
public:
WGL_CondExpr(WGL_Expr *e1, WGL_Expr *e2, WGL_Expr *e3)
: arg1(e1)
, arg2(e2)
, arg3(e3)
{
}
virtual ~WGL_CondExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Cond;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr *arg1;
WGL_Expr *arg2;
WGL_Expr *arg3;
};
class WGL_ExprList
: public ListElement<WGL_ExprList>
{
public:
WGL_ExprList()
{
}
WGL_ExprList *Add(WGL_Expr *e1)
{
e1->Into(&list);
return this;
}
virtual WGL_ExprList *VisitExprList(WGL_ExprVisitor *s)
{
return s->VisitExprList(this);
}
static unsigned ComputeWidth(WGL_ExprList *list);
List<WGL_Expr> list;
};
class WGL_CallExpr
: public WGL_Expr
{
public:
WGL_CallExpr(WGL_Expr *f, WGL_ExprList *a)
: fun(f)
, args(a)
{
}
virtual ~WGL_CallExpr()
{
Out();
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Call;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr *fun;
WGL_ExprList *args;
};
class WGL_IndexExpr
: public WGL_Expr
{
public:
WGL_IndexExpr(WGL_Expr *e1, WGL_Expr *e2)
: array(e1)
, index(e2)
{
}
virtual ~WGL_IndexExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Index;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr *array;
WGL_Expr *index;
};
class WGL_SelectExpr
: public WGL_Expr
{
public:
WGL_SelectExpr(WGL_Expr *rec, WGL_VarName *f)
: value(rec)
, field(f)
{
}
virtual ~WGL_SelectExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Select;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr *value;
WGL_VarName *field;
};
class WGL_AssignExpr
: public WGL_Expr
{
public:
WGL_AssignExpr(WGL_Expr::Operator o, WGL_Expr *e1, WGL_Expr *e2)
: op(o)
, lhs(e1)
, rhs(e2)
{
}
virtual ~WGL_AssignExpr()
{
}
virtual WGL_Expr::Type GetType()
{
return WGL_Expr::Assign;
}
virtual WGL_Expr *VisitExpr(WGL_ExprVisitor *v)
{
return v->VisitExpr(this);
}
WGL_Expr::Operator op;
WGL_Expr *lhs;
WGL_Expr *rhs;
};
class WGL_Stmt;
class WGL_StmtList;
class WGL_SwitchStmt;
class WGL_SimpleStmt;
class WGL_WhileStmt;
class WGL_BodyStmt;
class WGL_DoStmt;
class WGL_IfStmt;
class WGL_ForStmt;
class WGL_ReturnStmt;
class WGL_ExprStmt;
class WGL_DeclStmt;
class WGL_CaseLabel;
class WGL_StmtVisitor
{
public:
virtual WGL_Stmt *VisitStmt(WGL_SwitchStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_SimpleStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_BodyStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_WhileStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_DoStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_IfStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_ForStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_ReturnStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_ExprStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_DeclStmt *s) = 0;
virtual WGL_Stmt *VisitStmt(WGL_CaseLabel *s) = 0;
virtual WGL_StmtList *VisitStmtList(WGL_StmtList *ls);
};
class WGL_StmtList;
class WGL_Stmt
: public ListElement<WGL_Stmt>
{
public:
enum Type
{
StmtNone = 0,
Switch,
Simple,
Body,
While,
Do,
StmtDecl,
StmtLabel,
For,
Return,
StmtExpr,
StmtIf
};
WGL_Stmt()
: line_number(0)
{
}
virtual Type GetType()
{
return StmtNone;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v) = 0;
unsigned line_number;
};
class WGL_StmtList
: public ListElement<WGL_StmtList>
{
public:
WGL_StmtList()
{
}
WGL_StmtList *Add(WGL_Stmt *s1 )
{
s1->Into(&list);
return this;
}
virtual WGL_StmtList *VisitStmtList(WGL_StmtVisitor *s)
{
return s->VisitStmtList(this);
}
List<WGL_Stmt> list;
};
class WGL_SwitchStmt
: public WGL_Stmt
{
public:
WGL_SwitchStmt(WGL_Expr *e1, WGL_StmtList *ss)
: scrutinee(e1)
, cases(ss)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::Switch;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Expr *scrutinee;
WGL_StmtList *cases;
};
class WGL_SimpleStmt
: public WGL_Stmt
{
public:
enum Type
{
Empty = 1,
Default,
Continue,
Break,
Discard
};
WGL_SimpleStmt(Type k)
: type(k)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::Simple;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
Type type;
};
class WGL_BodyStmt
: public WGL_Stmt
{
public:
WGL_BodyStmt(WGL_StmtList *ss)
: body(ss)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::Body;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_StmtList *body;
};
class WGL_WhileStmt
: public WGL_Stmt
{
public:
WGL_WhileStmt(WGL_Expr *e1, WGL_Stmt *b)
: condition(e1)
, body(b)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::While;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Expr *condition;
WGL_Stmt *body;
};
class WGL_DoStmt
: public WGL_Stmt
{
public:
WGL_DoStmt(WGL_Stmt *s, WGL_Expr *e1)
: body(s)
, condition(e1)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::Do;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Stmt *body;
WGL_Expr *condition;
};
class WGL_Decl;
class WGL_DeclList;
class WGL_FunctionPrototype;
class WGL_PrecisionDefn;
class WGL_ArrayDecl;
class WGL_VarDecl;
class WGL_TypeDecl;
class WGL_InvariantDecl;
class WGL_FunctionDefn;
class WGL_DeclVisitor
{
public:
virtual WGL_Decl *VisitDecl(WGL_FunctionPrototype *d) = 0;
virtual WGL_Decl *VisitDecl(WGL_PrecisionDefn *d) = 0;
virtual WGL_Decl *VisitDecl(WGL_ArrayDecl *d) = 0;
virtual WGL_Decl *VisitDecl(WGL_VarDecl *d) = 0;
virtual WGL_Decl *VisitDecl(WGL_TypeDecl *d) = 0;
virtual WGL_Decl *VisitDecl(WGL_InvariantDecl *d) = 0;
virtual WGL_Decl *VisitDecl(WGL_FunctionDefn *d) = 0;
virtual WGL_DeclList *VisitDeclList(WGL_DeclList *ls);
};
class WGL_CaseLabel
: public WGL_Stmt
{
public:
WGL_CaseLabel(WGL_Expr *e1)
: condition(e1)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::StmtLabel;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Expr *condition;
/**< The 'case' expression; NULL being used to represent 'default'. */
};
class WGL_Decl
: public ListElement<WGL_Decl>
{
public:
enum Type
{
DeclNone = 0,
Invariant,
TypeDecl,
Var,
Array,
Function,
PrecisionDecl,
Proto
};
WGL_Decl()
: line_number(0)
{
}
unsigned line_number;
virtual Type GetType()
{
return DeclNone;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *d) = 0;
static WGL_FunctionDefn *GetFunction(WGL_Decl *d, const uni_char *name);
/**< If 'd' is a function definition with the given name, return it.
Otherwise NULL. */
};
class WGL_DeclStmt
: public WGL_Stmt
{
public:
WGL_DeclStmt()
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::StmtDecl;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
void Add(WGL_Decl *d);
List<WGL_Decl> decls;
};
class WGL_ForStmt
: public WGL_Stmt
{
public:
WGL_ForStmt(WGL_Stmt *d, WGL_Expr *e1, WGL_Expr *e2, WGL_Stmt *s)
: head(d)
, predicate(e1)
, update(e2)
, body(s)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::For;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Stmt *head;
WGL_Expr *predicate;
WGL_Expr *update;
WGL_Stmt *body;
};
class WGL_ReturnStmt
: public WGL_Stmt
{
public:
WGL_ReturnStmt(WGL_Expr *e1)
: value(e1)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::Return;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Expr *value;
};
class WGL_ExprStmt
: public WGL_Stmt
{
public:
WGL_ExprStmt(WGL_Expr *e1)
: expr(e1)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::StmtExpr;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Expr *expr;
};
class WGL_VectorType
: public WGL_Type
{
public:
enum Type
{
/* Note: the relative ordering of these tags MUST mirror
those defined for tokens (e.g., TYPE_xxx). We must also have
Vec<m> + <n> = Vec<m + n> and similarly for BVec, etc. (See
WGL_ValidationState::GetTypeForSwizzle().) */
Vec2 = 1,
Vec3,
Vec4,
BVec2,
BVec3,
BVec4,
IVec2,
IVec3,
IVec4,
UVec2,
UVec3,
UVec4
};
WGL_VectorType(Type ty, BOOL is_heap_allocated)
: WGL_Type(is_heap_allocated)
, type(ty)
{
}
virtual ~WGL_VectorType();
virtual WGL_Type::Type GetType()
{
return Vector;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v)
{
return v->VisitType(this);
}
static WGL_BasicType::Type GetElementType(WGL_VectorType *vec);
static BOOL SameElementType(WGL_VectorType *t1, WGL_VectorType *t2);
static BOOL HasElementType(WGL_VectorType *vec, WGL_BasicType::Type t);
static unsigned GetMagnitude(WGL_VectorType *vec);
static WGL_VectorType::Type ToVectorType(WGL_BasicType::Type t, unsigned size);
Type type;
};
class WGL_MatrixType
: public WGL_Type
{
public:
enum Type
{
/* Note: the relative ordering of these tags MUST mirror
those defined for tokens (e.g., TYPE_xxx) */
Mat2 = 1,
Mat3,
Mat4,
Mat2x2,
Mat2x3,
Mat2x4,
Mat3x2,
Mat3x3,
Mat3x4,
Mat4x2,
Mat4x3,
Mat4x4
};
WGL_MatrixType(Type ty, BOOL is_heap_allocated)
: WGL_Type(is_heap_allocated)
, type(ty)
{
}
virtual ~WGL_MatrixType();
virtual WGL_Type::Type GetType()
{
return Matrix;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v)
{
return v->VisitType(this);
}
static WGL_BasicType::Type GetElementType(WGL_MatrixType *mat);
static BOOL SameElementType(WGL_MatrixType *m1, WGL_MatrixType *m2);
static BOOL HasElementType(WGL_MatrixType *mat, WGL_BasicType::Type t);
static unsigned GetColumns(WGL_MatrixType *mat);
static unsigned GetRows(WGL_MatrixType *mat);
Type type;
};
class WGL_SamplerType
: public WGL_Type
{
public:
enum Type
{
/* Same comment as above applies here. */
Sampler1D = 1,
Sampler2D,
Sampler3D,
SamplerCube,
Sampler1DShadow,
Sampler2DShadow,
SamplerCubeShadow,
Sampler1DArray,
Sampler2DArray,
Sampler1DArrayShadow,
Sampler2DArrayShadow,
SamplerBuffer,
Sampler2DMS,
Sampler2DMSArray,
Sampler2DRect,
Sampler2DRectShadow,
ISampler1D,
ISampler2D,
ISampler3D,
ISamplerCube,
ISampler1DArray,
ISampler2DArray,
ISampler2DRect,
ISamplerBuffer,
ISampler2DMS,
ISampler2DMSArray,
USampler1D,
USampler2D,
USampler3D,
USamplerCube,
USampler1DArray,
USampler2DArray,
USampler2DRect,
USamplerBuffer,
USampler2DMS,
USampler2DMSArray
};
WGL_SamplerType(Type ty, BOOL is_heap_allocated)
: WGL_Type(is_heap_allocated)
, type(ty)
{
}
virtual ~WGL_SamplerType();
virtual WGL_Type::Type GetType()
{
return Sampler;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v)
{
return v->VisitType(this);
}
Type type;
};
class WGL_NameType
: public WGL_Type
{
public:
WGL_NameType(WGL_VarName *n, BOOL is_heap_allocated)
: WGL_Type(is_heap_allocated)
, name(n)
{
}
virtual ~WGL_NameType();
virtual WGL_Type::Type GetType()
{
return WGL_Type::Name;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v)
{
return v->VisitType(this);
}
WGL_VarName *name;
};
class WGL_IfStmt
: public WGL_Stmt
{
public:
WGL_IfStmt(WGL_Expr *e1, WGL_Stmt *s1, WGL_Stmt *s2)
: predicate(e1)
, then_part(s1)
, else_part(s2)
{
}
virtual WGL_Stmt::Type GetType()
{
return WGL_Stmt::StmtIf;
}
virtual WGL_Stmt *VisitStmt(WGL_StmtVisitor *v)
{
return v->VisitStmt(this);
}
WGL_Expr *predicate;
WGL_Stmt *then_part;
WGL_Stmt *else_part;
};
class WGL_Field;
class WGL_FieldList;
class WGL_FieldVisitor
{
public:
virtual WGL_Field *VisitField(WGL_Field *d) { return d; }
virtual WGL_FieldList *VisitFieldList(WGL_FieldList *ls);
};
class WGL_Field
: public ListElement<WGL_Field>
{
public:
WGL_Field(WGL_VarName *v, WGL_Type *t, BOOL is_heap_allocated)
: name(v)
, type(t)
, is_heap_allocated(is_heap_allocated)
{
}
~WGL_Field();
virtual WGL_Field *VisitField(WGL_FieldVisitor *f)
{
return f->VisitField(this);
}
WGL_VarName *name;
WGL_Type *type;
BOOL is_heap_allocated;
/**< If TRUE, delete type components upon free. */
};
class WGL_FieldList
: public ListElement<WGL_FieldList>
{
public:
WGL_FieldList(BOOL is_heap_allocated)
: is_heap_allocated(is_heap_allocated)
{
}
~WGL_FieldList()
{
if (is_heap_allocated)
list.Clear();
}
WGL_FieldList *Add(WGL_Context *context, WGL_Type *t, WGL_VarName *i);
virtual WGL_FieldList *VisitFieldList(WGL_FieldVisitor *s)
{
return s->VisitFieldList(this);
}
List<WGL_Field> list;
BOOL is_heap_allocated;
/**< If TRUE, delete type components upon free. */
};
class WGL_StructType
: public WGL_Type
{
public:
WGL_StructType(WGL_VarName *tag, WGL_FieldList *f, BOOL is_heap_allocated)
: WGL_Type(is_heap_allocated)
, tag(tag)
, fields(f)
{
}
virtual ~WGL_StructType();
virtual WGL_Type::Type GetType()
{
return WGL_Type::Struct;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v)
{
return v->VisitType(this);
}
WGL_VarName *tag;
WGL_FieldList *fields;
};
class WGL_ArrayType
: public WGL_Type
{
public:
WGL_ArrayType(WGL_Type *t, WGL_Expr *e, BOOL is_heap_allocated)
: WGL_Type(is_heap_allocated)
, element_type(t)
, length(e)
, is_constant_value(FALSE)
, length_value(0)
{
}
virtual ~WGL_ArrayType();
virtual WGL_Type::Type GetType()
{
return WGL_Type::Array;
}
virtual WGL_Type *VisitType(WGL_TypeVisitor *v)
{
return v->VisitType(this);
}
static void ShowSizes(WGL_PrettyPrinter *printer, WGL_ArrayType *t);
WGL_Type *element_type;
WGL_Expr *length;
BOOL is_constant_value;
/**< TRUE => length_value has the constant (folded) array length. */
unsigned length_value;
/**< If is_constant_value is TRUE, holds the number of elements in the
array. */
};
class WGL_InvariantDecl
: public WGL_Decl
{
public:
WGL_InvariantDecl(WGL_VarName *i)
: var_name(i)
, next(NULL)
{
}
virtual WGL_Decl::Type GetType()
{
return WGL_Decl::Invariant;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *v)
{
return v->VisitDecl(this);
}
WGL_VarName *var_name;
WGL_InvariantDecl *next;
};
class WGL_TypeDecl
: public WGL_Decl
{
public:
WGL_TypeDecl(WGL_Type *t, WGL_VarName *i)
: type(t)
, var_name(i)
{
}
virtual WGL_Decl::Type GetType()
{
return WGL_Decl::TypeDecl;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *v)
{
return v->VisitDecl(this);
}
WGL_Type *type;
WGL_VarName *var_name;
};
class WGL_VarDecl
: public WGL_Decl
{
public:
WGL_VarDecl(WGL_Type *t, WGL_VarName *i, WGL_Expr *e)
: type(t)
, identifier(i)
, initialiser(e)
{
}
virtual WGL_Decl::Type GetType()
{
return WGL_Decl::Var;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *v)
{
return v->VisitDecl(this);
}
void Show(WGL_PrettyPrinter *printer, BOOL with_no_precision);
WGL_Type *type;
WGL_VarName *identifier;
WGL_Expr *initialiser;
};
class WGL_ArrayDecl
: public WGL_Decl
{
public:
WGL_ArrayDecl(WGL_Type *t, WGL_VarName *i, WGL_Expr *e1, WGL_Expr *e2)
: type(t)
, identifier(i)
, size(e1)
, initialiser(e2)
{
}
virtual WGL_Decl::Type GetType()
{
return WGL_Decl::Array;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *v)
{
return v->VisitDecl(this);
}
WGL_Type *type;
WGL_VarName *identifier;
WGL_Expr *size;
WGL_Expr *initialiser;
};
class WGL_LayoutPair;
class WGL_LayoutList;
class WGL_LayoutVisitor
{
public:
virtual WGL_LayoutPair *VisitLayout(WGL_LayoutPair *d)
{
return d;
}
virtual WGL_LayoutList *VisitLayoutList(WGL_LayoutList *ls) = 0;
};
class WGL_LayoutPair
: public ListElement<WGL_LayoutPair>
{
public:
WGL_LayoutPair(WGL_VarName *i, int v)
: identifier(i)
, value(v)
{
}
virtual WGL_LayoutPair *VisitLayout(WGL_LayoutVisitor *v)
{
return v->VisitLayout(this);
}
WGL_VarName *identifier;
int value;
};
/** Layout qualifiers are not part of the shader language in GLES2.0 (part of OpenGL GLSL 1.50.)
* Keep the class and representation in this AST. */
class WGL_LayoutList
: public ListElement<WGL_LayoutList>
{
public:
WGL_LayoutList(BOOL is_heap_allocated)
: is_heap_allocated(is_heap_allocated)
{
}
~WGL_LayoutList();
WGL_LayoutList *Add(WGL_LayoutPair *l1)
{
l1->Into(&list);
return this;
}
virtual WGL_LayoutList *VisitLayoutList(WGL_LayoutVisitor *l)
{
return l->VisitLayoutList(this);
}
List<WGL_LayoutPair> list;
BOOL is_heap_allocated;
/**< If TRUE, delete type components upon free. */
};
class WGL_TypeQualifier
{
public:
enum Storage
{
NoStorage = 0,
Const,
Attribute,
Varying,
Uniform,
In,
Out,
InOut
};
enum InvariantKind
{
NoInvariant = 0,
Invariant
};
WGL_TypeQualifier(BOOL is_heap_allocated)
: storage(NoStorage)
, layouts(NULL)
, invariant(NoInvariant)
, is_heap_allocated(is_heap_allocated)
{
}
WGL_TypeQualifier(const WGL_TypeQualifier &ty, BOOL is_heap_allocated)
: storage(ty.storage)
, layouts(NULL)
, invariant(ty.invariant)
, is_heap_allocated(is_heap_allocated)
{
}
~WGL_TypeQualifier();
WGL_TypeQualifier *AddInvariant(InvariantKind i);
WGL_TypeQualifier *AddStorage(Storage s);
WGL_TypeQualifier *AddLayout(WGL_LayoutList *l);
void Show(WGL_PrettyPrinter *printer);
Storage storage;
WGL_LayoutList *layouts;
InvariantKind invariant;
BOOL is_heap_allocated;
/**< If TRUE, delete type components upon free. */
};
class WGL_FunctionDefn
: public WGL_Decl
{
public:
WGL_FunctionDefn(WGL_Decl *d, WGL_Stmt *s)
: head(d)
, body(s)
{
}
virtual WGL_Decl::Type GetType()
{
return WGL_Decl::Function;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *v)
{
return v->VisitDecl(this);
}
WGL_Decl *head;
WGL_Stmt *body;
};
class WGL_PrecisionDefn
: public WGL_Decl
{
public:
WGL_PrecisionDefn(WGL_Type::Precision p, WGL_Type *t)
: precision(p)
, type(t)
{
}
virtual WGL_Decl::Type GetType()
{
return WGL_Decl::PrecisionDecl;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *v)
{
return v->VisitDecl(this);
}
WGL_Type::Precision precision;
WGL_Type *type;
};
class WGL_Param;
class WGL_ParamList;
class WGL_ParamVisitor
{
public:
virtual WGL_Param *VisitParam(WGL_Param *d)
{
return d;
}
virtual WGL_ParamList *VisitParamList(WGL_ParamList *ls);
};
class WGL_Param
: public ListElement<WGL_Param>
{
public:
enum Direction
{
None = 0,
In,
Out,
InOut
};
WGL_Param(WGL_Type *t, WGL_VarName *i1, Direction d)
: type(t)
, name(i1)
, direction(d)
{
}
virtual WGL_Param *VisitParam(WGL_ParamVisitor *d)
{
return d->VisitParam(this);
}
static void Show(WGL_PrettyPrinter *p, Direction d);
WGL_Type *type;
WGL_VarName *name;
Direction direction;
};
class WGL_ParamList
: public ListElement<WGL_ParamList>
{
public:
WGL_ParamList()
{
}
WGL_ParamList *Add(WGL_Context *context, WGL_Type *t, WGL_VarName *i);
WGL_ParamList *Add(WGL_Param *p1)
{
p1->Into(&list);
return this;
}
virtual WGL_ParamList *VisitParamList(WGL_ParamVisitor *d)
{
return d->VisitParamList(this);
}
static WGL_Param *FindParam(WGL_ParamList *list, WGL_VarName *i);
List<WGL_Param> list;
};
class WGL_FunctionPrototype
: public WGL_Decl
{
public:
WGL_FunctionPrototype(WGL_Type *t, WGL_VarName *i, WGL_ParamList *ps)
: return_type(t)
, name(i)
, parameters(ps)
{
}
virtual WGL_Decl::Type GetType()
{
return WGL_Decl::Proto;
}
virtual WGL_Decl *VisitDecl(WGL_DeclVisitor *v)
{
return v->VisitDecl(this);
}
void Show(WGL_PrettyPrinter *printer, BOOL as_proto);
WGL_Type *return_type;
WGL_VarName *name;
WGL_ParamList *parameters;
};
class WGL_DeclList
: public ListElement<WGL_DeclList>
{
public:
WGL_DeclList()
{
}
WGL_DeclList *Add(WGL_Decl *d1)
{
d1->Into(&list);
return this;
}
virtual WGL_DeclList *VisitDeclList(WGL_DeclVisitor *s)
{
return s->VisitDeclList(this);
}
List<WGL_Decl> list;
};
class WGL_Op
{
public:
static void Show(WGL_PrettyPrinter *p, WGL_Expr::Operator op);
static void Show(WGL_PrettyPrinter *p, WGL_TypeQualifier::Storage s);
static void Show(WGL_PrettyPrinter *p, WGL_TypeQualifier::InvariantKind i);
static WGL_Expr::Precedence GetPrecedence(WGL_Expr::Operator op);
static WGL_Expr::Associativity GetAssociativity(WGL_Expr::Operator op);
static WGL_Expr::PrecAssoc ToPrecAssoc(WGL_Expr::Precedence p, WGL_Expr::Associativity a) { return ( (static_cast<unsigned>(a) & 0xff) | (static_cast<unsigned>(p) << 0x8)); }
static WGL_Expr::Precedence GetPrecAssocP(WGL_Expr::PrecAssoc pa) { return ((WGL_Expr::Precedence)(pa >> 0x8)); }
static WGL_Expr::Associativity GetPrecAssocA(WGL_Expr::PrecAssoc pa) { return ((WGL_Expr::Associativity)(pa & 0xff)); }
};
#endif // WGL_AST_H
|
#pragma once
#include "DxLib.h"
class StageSelect
{
private:
int key_graphic[2];
int buck_graphic[5];
int number;
int pos_x[2];//0->A/1->D
int pos_y[2];
int buckground_x[5];
int buckground_y[5];
public:
StageSelect();
~StageSelect() {};
void update(char A, char D);
void draw();
int getnumber()
{
return number;
}
};
|
#include<iostream>
using namespace std;
int main()
{
int i,n,num1=0,num2=1,next;
cout<<"Enter no. of terms:";
cin>>n;
cout<<"\nFibonacci series:\n";
for(i=1;i!=n;i++)
{
cout<<num1<<" ";
next=num1+num2;
num1=num2;
num2=next;
}
return 0;
}
|
#include "MoveCalibration.h"
#include "simplex.h"
#include "IniFile.h"
using namespace std;
namespace Move
{
MoveCalibration::MoveCalibration(int moveId, MoveOrientation* orientation)
:orientation(orientation)
{
this->id=moveId;
char fileName[]="settings.cfg";
MoveDevice::TMoveBluetooth bt;
MoveDevice::ReadMoveBluetoothSettings(id,&bt);
//device name
sprintf_s(deviceName,"Move_%s",bt.MoveBtMacString);
state=NotCalibrated;
try
{
data.gyroGain=IniFile::GetMat3("gyroGain", deviceName, fileName);
data.accBias=IniFile::GetVec3("accBias", deviceName, fileName);
data.accGain=IniFile::GetMat3("accGain", deviceName, fileName);
state=InitialCalibrationDone;
data.magBias=IniFile::GetVec3("magBias", deviceName, fileName);
data.magGain=IniFile::GetMat3("magGain", deviceName, fileName);
state=Calibrated;
}
catch(MoveConfigFileRecordNotFoundException)
{}
if (state==InitialCalibrationDone)
{
MoveManager::getInstance()->notify(moveId, M_InitialCalibratingDone);
MoveManager::getInstance()->notify(moveId, M_DoesntUseMagnetometers);
}
else if (state==Calibrated)
{
MoveManager::getInstance()->notify(moveId, M_Calibrated);
MoveManager::getInstance()->notify(moveId, M_UseMagnetometers);
}
timer=5.0f;
orientation->useHighGain(true);
rawData=0;
magPosition=-1;
}
MoveCalibration::~MoveCalibration(void)
{
}
void MoveCalibration::Update(Vec3 mag, Quat ref, float deltat)
{
if (timer>0.0f)
{
timer-=deltat;
if (timer<=2.0f)
orientation->useHighGain(false);
return;
}
if (state==MagnetometerSphereCalibration || state==MagnetometerRefCalibration)
{
if (mag.x==0 && mag.y==0 && mag.z==0)
return;
if (timer>0.0f)
{
timer-=deltat;
if (timer<=2.0f)
orientation->useHighGain(false);
return;
}
if (magPosition==-1)
{
MoveManager::getInstance()->notify(id, M_RotateMove);
orientation->UseMagnetometer(false);
magBuf[++magPosition]=mag;
magRef[magPosition]=ref;
return;
}
ref.Normalize();
// calculate relative vector between previous measure point and the current orientation
if ((ref|magRef[magPosition])<0)
ref=Quat(-ref.w,-1.0f*ref.v);
Vec3 axis=(!ref*magRef[magPosition]).v;
// if there is enough turn between 2 measure points
if (axis.length()>.3f)
{
magBuf[++magPosition]=mag;
magRef[magPosition]=ref;
}
}
if (magPosition>=MAG_ITERATIONS-1)
{
if (state==MagnetometerSphereCalibration)
{
MoveManager::getInstance()->notify(id, M_CalibrationProcessing);
//initialize the algorithm
Vec3 min, max, bias, gain;
min=magBuf[0];
max=magBuf[0];
for (int i=1; i<MAG_ITERATIONS; i++)
{
SWAP_MIN(min.x,magBuf[i].x);
SWAP_MIN(min.y,magBuf[i].y);
SWAP_MIN(min.z,magBuf[i].z);
SWAP_MAX(max.x,magBuf[i].x);
SWAP_MAX(max.y,magBuf[i].y);
SWAP_MAX(max.z,magBuf[i].z);
}
bias=(max+min)*0.5f;
gain=2.0f/(max-min);
std::vector<double> init;
std::vector<double> result;
init.push_back(gain.x);
init.push_back(0.00001);
init.push_back(0.00001);
init.push_back(0.00001);
init.push_back(gain.y);
init.push_back(0.00001);
init.push_back(0.00001);
init.push_back(0.00001);
init.push_back(gain.z);
init.push_back(bias.x);
init.push_back(bias.y);
init.push_back(bias.z);
result.clear();
SpecVectorFunctor<double,MoveCalibration> ft(this, &MoveCalibration::integrateMagSphereError);
result=BT::Simplex(ft, init, 2000);
data.magGain=Mat3(result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8]);
data.magBias=Vec3(result[9],result[10],result[11]);
magPosition=-1;
orientation->useHighGain(true);
orientation->UseMagnetometer(true);
timer=5.0f;
state=MagnetometerRefCalibration;
}
else if (state==MagnetometerRefCalibration)
{
MoveManager::getInstance()->notify(id, M_CalibrationProcessing);
// calculate North vector
North=Vec3::ZERO;
for (int i=1; i<MAG_ITERATIONS; i++)
{
Vec3 point=(magBuf[i]-data.magBias)*data.magGain;
//integrate the error
Vec3 north=point*!magRef[i];
North+=north;
}
North/=float(MAG_ITERATIONS);
North.y=0;
std::vector<double> init;
std::vector<double> result;
init.push_back(data.magGain.m00);
init.push_back(data.magGain.m01);
init.push_back(data.magGain.m02);
init.push_back(data.magGain.m10);
init.push_back(data.magGain.m11);
init.push_back(data.magGain.m12);
init.push_back(data.magGain.m20);
init.push_back(data.magGain.m21);
init.push_back(data.magGain.m22);
init.push_back(data.magBias.x);
init.push_back(data.magBias.y);
init.push_back(data.magBias.z);
result.clear();
SpecVectorFunctor<double,MoveCalibration> ft(this, &MoveCalibration::integrateMagRefError);
result=BT::Simplex(ft, init, 5000);
data.magGain=Mat3(result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8]);
data.magBias=Vec3(result[9],result[10],result[11]);
IniFile::SetValue("magBias", data.magBias, deviceName, "settings.cfg");
IniFile::SetValue("magGain", data.magGain, deviceName, "settings.cfg");
orientation->UseMagnetometer(true);
orientation->useHighGain(true);
timer=5.0f;
state=Calibrated;
MoveManager::getInstance()->notify(id, M_Calibrated);
}
}
}
MoveCalibrationData MoveCalibration::getCalibrationData()
{
return data;
}
double MoveCalibration::integrateGyroError(std::vector<double> x)
{
double error=0.0;
Vec3 point;
Vec3 objective[3];
objective[0]=Vec3( 2*PI, 0, 0);
objective[1]=Vec3( 0, 2*PI, 0 );
objective[2]=Vec3( 0, 0, 2*PI );
Mat3 gain=Mat3(x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8]);
for (int i=0; i<3; i++)
{
//remove bias
point=(rawData->GyroVectors[i]-(rawData->GyroBiasVectors[1]*rawData->UnknownVectors[1]));
//convert from 80 rpm to 1 rotate per second
point*=0.75f;
//calculate error vector
point=point*gain-objective[i];
//integrate the error
error+=abs((double)point.length2());
}
return error;
}
double MoveCalibration::integrateMagSphereError(std::vector<double> x)
{
double error=0.0;
Vec3 point;
Mat3 gain=Mat3(x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8]);
Vec3 bias=Vec3(x[9],x[10],x[11]);
for (int i=1; i<MAG_ITERATIONS; i++)
{
//calculate calibrated point
point=(magBuf[i]-bias)*gain;
//calculate error
float diff=point.length()-1.0f;
error+=diff*diff;
}
return error/(double)MAG_ITERATIONS;
}
double MoveCalibration::integrateMagRefError(std::vector<double> x)
{
double error=0.0;
Vec3 point;
Mat3 gain=Mat3(x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8]);
Vec3 bias=Vec3(x[9],x[10],x[11]);
for (int i=1; i<MAG_ITERATIONS; i++)
{
//calculate calibrated point
point=(magBuf[i]-bias)*gain;
//integrate the error
Vec3 calculated=point*!magRef[i];
error+=(calculated-North).length2();
}
return error/(double)MAG_ITERATIONS;
}
double MoveCalibration::integrateAccError(std::vector<double> x)
{
double error=0.0;
Vec3 point;
Vec3 objective[6];
objective[0]=Vec3( -9.81f, 0, 0 );
objective[1]=Vec3( 9.81f, 0, 0 );
objective[2]=Vec3( 0, -9.81f, 0 );
objective[3]=Vec3( 0, 9.81f, 0 );
objective[4]=Vec3( 0, 0, -9.81f );
objective[5]=Vec3( 0, 0, 9.81f);
Mat3 gain=Mat3(x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8]);
Vec3 bias=Vec3(x[9],x[10],x[11]);
for (int i=0; i<6; i++)
{
//calculate error vector
point=(rawData->AccVectors[i]-bias)*gain-objective[i];
//integrate the error
error+=abs((double)point.length2());
}
return error;
}
//move calibration
void MoveCalibration::initialCalibration()
{
MoveDevice::TMoveCalib calib;
if (!MoveDevice::ReadMoveCalibration(id,&calib))
{
MoveManager::getInstance()->notify(id, M_CantReadCalibration);
return;
}
MoveManager::getInstance()->notify(id, M_CalibrationProcessing);
rawData=new MoveRawCalibration(calib);
std::vector<double> init;
std::vector<double> result;
data.magBias=Vec3::ZERO;
data.magGain=Mat3();
//ACCELEROMETER
init.clear();
init.push_back(0.0022);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0022);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0022);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0001);
result.clear();
SpecVectorFunctor<double,MoveCalibration> ft2(this, &MoveCalibration::integrateAccError);
result=BT::Simplex(ft2, init);
data.accGain=Mat3(result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8]);
data.accBias=Vec3(result[9],result[10],result[11]);
//GYROSCOPE
init.clear();
init.push_back(0.0016);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0016);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0001);
init.push_back(0.0016);
result.clear();
SpecVectorFunctor<double,MoveCalibration> ft3(this, &MoveCalibration::integrateGyroError);
result=BT::Simplex(ft3, init);
data.gyroGain=Mat3(result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8]);
////save calibration
IniFile::SetValue("gyroGain", data.gyroGain, deviceName, "settings.cfg");
IniFile::SetValue("accBias", data.accBias, deviceName, "settings.cfg");
IniFile::SetValue("accGain", data.accGain, deviceName, "settings.cfg");
delete rawData;
state=InitialCalibrationDone;
MoveManager::getInstance()->notify(id, M_InitialCalibratingDone);
}
void MoveCalibration::calibrateMagnetometer()
{
state=MagnetometerSphereCalibration;
magPosition=-1;
timer=0.0f;
}
}
|
#include "editcomputer.h"
#include "ui_editcomputer.h"
#include "utilities/constants.h"
#include "data_types/computer.h"
editComputer::editComputer(QWidget *parent) :
QDialog(parent),
ui(new Ui::editComputer){
ui->setupUi(this);
// type dropdown list
ui->edit_dropdown_type->addItem("");
ui->edit_dropdown_type->addItem("Mechanical");
ui->edit_dropdown_type->addItem("Electronic");
ui->edit_dropdown_type->addItem("Transistor");
ui->edit_dropdown_type->addItem("Other");
// was it built dropdown list
ui->edit_dropdown_was_it_built->addItem("");
ui->edit_dropdown_was_it_built->addItem("Yes");
ui->edit_dropdown_was_it_built->addItem("No");
}
editComputer::~editComputer(){
delete ui;
}
void editComputer::setComputer(Computer comp){
string type;
string wasBuilt;
compID = comp.getId();
if(comp.getComputerType() == constants::MECHANICAL){
type = "Mechanical";
}
else if(comp.getComputerType() == constants::ELECTRONIC){
type = "Electronic";
}
else if(comp.getComputerType() == constants::TRANSISTOR){
type = "Transistor";
}
else{
type = "Other";
}
if(comp.getWasItBuilt() == constants::DB_TRUE){
wasBuilt = "Yes";
}
else{
wasBuilt = "No";
}
ui->button_remove_image->setEnabled(false);
// Printing info
ui->edit_name->setText(QString::fromStdString(comp.getComputerName()));
ui->edit_dropdown_type->setCurrentText(QString::fromStdString(type));
ui->edit_dropdown_was_it_built->setCurrentText(QString::fromStdString(wasBuilt));
if(comp.getBuildYear() == 0){
ui->edit_buildyear->setText(QString::fromStdString(""));
}
else{
ui->edit_buildyear->setText(QString::number(comp.getBuildYear()));
}
ui->edit_description->setText(QString::fromStdString(comp.getComputerDescription()));
if(!comp.getImageByteArray().isEmpty()){
currentImage = comp.getImageByteArray();
ui->button_remove_image->setEnabled(true);
ui->lineEdit_image->setText(QString::fromStdString("There is an image selected to " + comp.getComputerName()));
}
vector<Relation> allRelations = relService.displayRelations();
vector<Pioneer> allPioneers = pioService.getList();
for(unsigned int i = 0; i < allRelations.size(); i++){
Relation relInstance = allRelations[i];
for(unsigned int j = 0; j < allPioneers.size(); j++){
Pioneer pioInstance = allPioneers[j];
if(relInstance.getCompName() == comp.getComputerName() && relInstance.getPioName() == pioInstance.getName()){
relatedPioneers.push_back(pioInstance);
}
}
}
bool relatedPioneer = false;
for(unsigned int i = 0; i < allPioneers.size(); i++){
Pioneer unrelated = allPioneers[i];
relatedPioneer = false;
for(unsigned int j = 0; j < relatedPioneers.size(); j++){
Pioneer related = relatedPioneers[j];
if(related.getName() != unrelated.getName()){
relatedPioneer = false;
}
else{
relatedPioneer = true;
}
}
if(relatedPioneer == false){
unrelatedPioneers.push_back(unrelated);
}
}
displayRelatedPioneers();
displayUnrelatedPioneers();
ui->button_add_relation->setEnabled(false);
ui->button_remove_relation->setEnabled(false);
}
void editComputer::on_pushButton_editcomputer_clicked(){
// Clear error messages
emptyLines();
string name = ui->edit_name->text().toStdString();
string built = getCurrentWasItBuilt();
string type = getCurrentType();
string buildYear = ui->edit_buildyear->text().toStdString();
string description = ui->edit_description->toPlainText().toStdString();
bool error = errorCheck(name, built, buildYear, type, description);
if(error){
return;
}
if(buildYear.empty()){
buildYear = "0";
}
int bYear = atoi(buildYear.c_str());
if(image.isEmpty() && !currentImage.isEmpty()){
image = currentImage;
}
Computer comp(compID, name, bYear, type, built, description, image);
int answer = QMessageBox::question(this, "Save Changes", "Are you sure you want to save changes?");
if(answer == QMessageBox::No){
return;
}
else{
compService.editComputer(comp);
this->done(1);
}
}
void editComputer::emptyLines(){
ui->label_name_error->setText("");
ui->label_type_error->setText("");
ui->label_wasbuilt_error->setText("");
ui->label_description_error->setText("");
ui->label_build_year_error->setText("");
}
bool editComputer::errorCheck(string name, string wasBuilt, string buildYear, string type, string description){
bool error = false;
if(name.empty()){
ui->label_name_error->setText("<span style ='color: #ff0000'>Input Name!</span>");
error = true;
}
if(type.empty()){
ui->label_type_error->setText("<span style ='color: #ff0000'>Choose Type!</span>");
error = true;
}
if(wasBuilt.empty()){
ui->label_wasbuilt_error->setText("<span style ='color: #ff0000'>Choose Yes/No!</span>");
error = true;
qDebug() << QString::fromStdString(wasBuilt);
}
if((wasBuilt == "" || wasBuilt == "No") && buildYear.empty()){
// do nothing
}
if((wasBuilt == "false") && !buildYear.empty()){
ui->label_build_year_error->setText("<span style ='color: #ff0000'>Computer Wasn't Built!</span>");
error = true;
}
else if(wasBuilt == "true" && buildYear.empty()){
ui->label_build_year_error->setText("<span style ='color: #ff0000'>Input Build Year!</span>");
error = true;
}
else if(wasBuilt == "true" && !is_number(buildYear)){
ui->label_build_year_error->setText("<span style ='color: #ff0000'>Input a Number!</span>");
error = true;
}
if((wasBuilt == "" || wasBuilt == "No") && buildYear.empty()){
// do nothing
}
if((wasBuilt == "false") && !buildYear.empty()){
ui->label_build_year_error->setText("<span style ='color: #ff0000'>Computer Wasn't Built!</span>");
error = true;
}
else if(wasBuilt == "true" && buildYear.empty()){
ui->label_build_year_error->setText("<span style ='color: #ff0000'>Input Build Year!</span>");
error = true;
}
else if(wasBuilt == "true" && !is_number(buildYear)){
ui->label_build_year_error->setText("<span style ='color: #ff0000'>Input a Number!</span>");
error = true;
}
if(description.empty()){
ui->label_description_error->setText("<span style ='color: #ff0000'>Input Description!</span>");
error = true;
}
int bYear = atoi(buildYear.c_str());
if(bYear > constants::CURRENT_YEAR){
ui->label_build_year_error->setText("<span style ='color: #ff0000'>Computers from the future are not allowed!</span>");
error = true;
}
if(error == true){
return true;
}
return false;
}
bool editComputer::is_number(string& s){
string::const_iterator it = s.begin();
while (it != s.end() && isdigit(*it)){
++it;
}
return !s.empty() && it == s.end();
}
void editComputer::on_button_cancel_clicked(){
this->done(0);
}
void editComputer::displayRelatedPioneers(){
ui->list_related_pioneers->clear();
for(unsigned int i = 0; i < relatedPioneers.size(); i++){
Pioneer instance = relatedPioneers[i];
ui->list_related_pioneers->addItem(QString::fromStdString(instance.getName()));
}
}
void editComputer::displayUnrelatedPioneers(){
ui->list_unrelated_pioneers->clear();
for(unsigned int i = 0; i < unrelatedPioneers.size(); i++){
Pioneer instance = unrelatedPioneers[i];
ui->list_unrelated_pioneers->addItem(QString::fromStdString(instance.getName()));
}
}
void editComputer::on_list_unrelated_pioneers_clicked(const QModelIndex &/* unused */){
ui->button_add_relation->setEnabled(true);
}
void editComputer::on_list_related_pioneers_clicked(const QModelIndex &/* unused */){
ui->button_remove_relation->setEnabled(true);
}
void editComputer::on_button_remove_relation_clicked(){
int currentlySelectedPioneerIndex = ui->list_related_pioneers->currentIndex().row();
Pioneer selectedPioneer = relatedPioneers[currentlySelectedPioneerIndex];
unrelatedPioneers.push_back(selectedPioneer);
relatedPioneers.erase(relatedPioneers.begin() + currentlySelectedPioneerIndex);
displayRelatedPioneers();
displayUnrelatedPioneers();
int pioID = selectedPioneer.getId();
relService.removeRelation(pioID, compID);
ui->button_remove_relation->setEnabled(false);
}
void editComputer::on_button_add_relation_clicked(){
int currentlySelectedPioneerIndex = ui->list_unrelated_pioneers->currentIndex().row();
Pioneer selectedPioneer = unrelatedPioneers[currentlySelectedPioneerIndex];
relatedPioneers.push_back(selectedPioneer);
unrelatedPioneers.erase(unrelatedPioneers.begin() + currentlySelectedPioneerIndex);
displayUnrelatedPioneers();
displayRelatedPioneers();
int pioID = selectedPioneer.getId();
relService.addRelations(pioID, compID);
ui->button_add_relation->setEnabled(false);
}
void editComputer::on_pushButton_image_clicked(){
QString filePath = QFileDialog::getOpenFileName(
this,
"Search for images",
"/home",
"Image files (*.jpg)"
);
if (filePath.length()){ // File selected
QPixmap pixmap(filePath);
ui->lineEdit_image->setText(filePath);
QBuffer inBuffer( &image );
inBuffer.open( QIODevice::WriteOnly );
pixmap.save( &inBuffer, "JPG" );
}
else{
//didn't open file
}
}
string editComputer::getCurrentType(){
string type = ui->edit_dropdown_type->currentText().toStdString();
if(type == ""){
return "";
}
else if(type == "Mechanical"){
return constants::MECHANICAL;
}
else if(type == "Electronic"){
return constants::ELECTRONIC;
}
else if(type == "Transistor"){
return constants::TRANSISTOR;
}
else if(type == "Other"){
return "other";
}
else{
return "";
}
}
string editComputer::getCurrentWasItBuilt(){
string wasBuilt = ui->edit_dropdown_was_it_built->currentText().toStdString();
if(wasBuilt == ""){
return "";
}
else if(wasBuilt == "Yes"){
return constants::DB_TRUE;
}
else if(wasBuilt == "No"){
return constants::DB_FALSE;
}
else{
return "";
}
}
void editComputer::on_button_remove_image_clicked(){
currentImage.clear();
ui->lineEdit_image->setText(QString::fromStdString("Current Image has been deleted!"));
ui->button_remove_image->setEnabled(false);
}
|
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "Containers/CircularQueue.h"
#include "TouchControls.generated.h"
DECLARE_LOG_CATEGORY_EXTERN(LogTouchControls, Log, All);
class UBorder;
class UButton;
class UCanvasPanelSlot;
class UImage;
struct SpeedStatistics
{
static const uint32 MaxAvailableCount = 10;
SpeedStatistics() : MoveStatisticsCache(MaxAvailableCount + 1), OffsetNum(0.0f), ThresholdValue(10.0f), MaxAccelerateRatio(0.4f) { ClearData(); }
void ClearData()
{
OffsetNum = 0.0f;
}
float RequestDynamicScale(float Offset)
{
if (MoveStatisticsCache.IsFull())
{
float OldestOffset;
check(MoveStatisticsCache.Dequeue(OldestOffset));
OffsetNum -= OldestOffset;
}
MoveStatisticsCache.Enqueue(Offset);
OffsetNum += Offset;
const float PositiveOffsetNum = FMath::Abs(OffsetNum);
return PositiveOffsetNum < ThresholdValue ? 0.1f : FMath::Min(PositiveOffsetNum * 0.1f / ThresholdValue, MaxAccelerateRatio);
}
TCircularQueue<float> MoveStatisticsCache;
float OffsetNum;
const float ThresholdValue;
const float MaxAccelerateRatio;
};
UCLASS()
class GDKSHOOTER_API UTouchControls : public UUserWidget
{
GENERATED_BODY()
public:
UTouchControls(const FObjectInitializer& ObjectInitializer);
void NativeConstruct() override;
void BindControls();
protected:
virtual FReply NativeOnTouchStarted(const FGeometry& InGeometry, const FPointerEvent& InGestureEvent) override;
virtual FReply NativeOnTouchMoved(const FGeometry& InGeometry, const FPointerEvent& InGestureEvent) override;
virtual FReply NativeOnTouchEnded(const FGeometry& InGeometry, const FPointerEvent& InGestureEvent) override;
virtual void NativeTick(const FGeometry& AllottedGeometry, float InDeltaTime) override;
UFUNCTION(BlueprintCallable)
void ShowAllActionButtons(bool Enable) const;
private:
UFUNCTION()
FEventReply HandleJumpPressed(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleJumpReleased(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleCrouchPressed(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleCrouchReleased(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleTriggerPressed(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleTriggerReleased(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleScopePressed(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleScopeReleased(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleSprintPressed(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
FEventReply HandleSprintReleased(FGeometry Geometry, const FPointerEvent& MouseEvent);
UFUNCTION()
void OnDeath(const FString& VictimName, int32 VictimId);
void HandleTouchMoveOnLeftController(const FVector2D& TouchPosition);
void HandleTouchEndOnLeftController();
void HandleTouchMoveOnRightController(const FVector2D& TouchPosition);
void HandleTouchEndOnRightController(const FVector2D& TouchPosition);
protected:
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UBorder* SprintButton;
// Crouch or slide (moving or not moving)
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UBorder* CrouchSlideButton;
// Jump and vault
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UBorder* JumpButton;
// Shoot weapon (right)
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UBorder* RightShootButton;
// Aim down sight with weapon
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UBorder* SiteScopeButton;
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UImage* LeftControllerForeImage;
UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
UImage* LeftControllerBackImage;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta = (DisplayName = XLinearScaling, ClampMin = "0.1"), Category = Responsiveness)
float XLinearScaling = 0.1f;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta = (DisplayName = YLinearScaling, ClampMin = "0.1"), Category = Responsiveness)
float YLinearScaling = 0.1f;
private:
struct FLeftControllerInfo
{
FVector2D LeftControllerCenter;
FVector2D LeftTouchStartPosition;
FVector2D MoveVelocity;
bool bLeftControllerActive = false;
float DistanceToEdge = 0;
float DistanceToEdgeSquare = 0;
int32 TouchIndex = -1;
};
// This is the data used to manage the camera movement.
struct FreeTouch
{
FVector2D LastPos;
int32 FingerIndex = -1;
bool bActive = false;
} CameraTouch;
bool bControlsBound;
bool bScopePressed;
bool bSprintPressed;
bool bCrouchPressed;
SpeedStatistics SpeedStatisticsX;
SpeedStatistics SpeedStatisticsY;
FLeftControllerInfo LeftControllerInfo;
UCanvasPanelSlot* LeftForeImageCanvasSlot = nullptr;
};
|
/* BEGIN LICENSE */
/*****************************************************************************
* SKCore : the SK core library
* Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr>
* $Id: file.cpp,v 1.8.2.3 2005/02/17 15:29:21 krys Exp $
*
* Authors: W.P. Dauchy
* Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr>
* Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Alternatively you can contact IDM <skcontact @at@ idm> for other license
* contracts concerning parts of the code owned by IDM.
*
*****************************************************************************/
/* END LICENSE */
#include <nspr/nspr.h>
#include <nspr/plstr.h>
#include "../skcoreconfig.h"
#include "../machine.h"
#include "../error.h"
#include "../refcount.h"
#include "../skptr.h"
#include "../envir/envir.h"
#include "skfopen.h"
#include "file.h"
#include "textfile.h"
#include "inifile.h"
SK_REFCOUNT_IMPL(SKFile)
// --------------------------------------------------------------------------
//
// SKFile
//
// --------------------------------------------------------------------------
SKFile::SKFile()
{
m_pszFileName = NULL;
}
SKFile::~SKFile()
{
if(m_pszFileName)
PL_strfree(m_pszFileName);
}
// --------------------------------------------------------------------------
//
// SetFileName
//
// --------------------------------------------------------------------------
SKERR SKFile::SetFileName(const char *pszFileName,
const char *pszDefaultFileName)
{
if (!pszFileName || !pszFileName[0])
return err_invalid;
if(m_pszFileName)
{
PR_Free(m_pszFileName);
m_pszFileName = NULL;
}
// FIXME : this code will conflict with delayed and transient modes
SKERR err = FindFileInEnvirPath(pszFileName, &m_pszFileName);
if (err != noErr)
return err_notfound;
PRFileInfo info;
PRStatus status = PR_GetFileInfo(m_pszFileName, &info);
if(status != PR_SUCCESS)
return err_failure;
if(info.type == PR_FILE_DIRECTORY)
{
if(!pszDefaultFileName)
return err_invalid;
PRUint32 iLen1 = PL_strlen(m_pszFileName);
PRUint32 iLen2 = PL_strlen(pszDefaultFileName);
char *pszNew = (char *)PR_Malloc((iLen1 + iLen2 + 2) * sizeof(char));
if(!pszNew)
return err_memory;
PL_strcpy(pszNew, m_pszFileName);
pszNew[iLen1] = '/';
PL_strcpy(pszNew + iLen1 + 1, pszDefaultFileName);
PR_Free(m_pszFileName);
m_pszFileName = pszNew;
}
return noErr;
}
void SKFile::PushEnvir()
{
SKEnvir *pEnvir = NULL;
SKEnvir::GetEnvir(&pEnvir);
SK_ASSERT(pEnvir);
pEnvir->Push();
char * p = m_pszFileName + PL_strlen(m_pszFileName) - 1;
while(p >= m_pszFileName && !IS_SEPARATOR(p))
p--;
if(p >= m_pszFileName)
{
char c1 = *p;
char c2 = *(p + 1);
*p = ';';
*(p + 1) = '\0';
pEnvir->PrependToValue("PATH", m_pszFileName);
*p = c1;
*(p + 1) = c2;
}
}
void SKFile::PopEnvir()
{
SKEnvir *pEnvir = NULL;
SKEnvir::GetEnvir(&pEnvir);
SK_ASSERT(pEnvir);
pEnvir->Pop();
}
SKERR SKFile::GetFileName(const char*& psz)
{
psz = PL_strdup(m_pszFileName);
return (psz == NULL);
}
SKERR SKFile::ConfigureItem(char *pszSection, char *pszName, char *pszValue)
{
// file path
if(!PL_strcmp(pszName, "PATH"))
return SetFileName(pszValue);
// nobody knows about this configuration option
return SKError(err_cnf_invalid, "[SKFile::Configure] "
"Invalid configuration option [%s] %s=%s",
pszSection, pszName, pszValue);
}
// --------------------------------------------------------------------------
//
// SetDescription
//
// --------------------------------------------------------------------------
/*
void SKFile::SetDescription (const char* szDescription)
{
strncpy (m_szDescription, szDescription, sizeof(m_szDescription) - 1);
m_szDescription[sizeof(m_szDescription)-1] = 0;
}
*/
// --------------------------------------------------------------------------
//
// Check
//
// --------------------------------------------------------------------------
SKERR SKFile::Check (void)
{
return noErr;
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n, a[200000];
vector<int> v1, v2;
bool failed;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
sort(a, a + n);
failed = false;
v1.push_back(a[0]);
if (n != 1)
{
v2.push_back(a[1]);
}
for (int i = 2; i < n; i++)
{
if (a[i] == v1.back())
{
if (a[i] == v2.back())
{
failed = true;
break;
}
v2.push_back(a[i]);
}
else
v1.push_back(a[i]);
}
if (failed)
cout << "NO" << endl;
else
{
cout << "YES" << endl;
cout << v1.size() << endl;
for (int ele : v1)
cout << ele << " ";
cout << endl;
cout << v2.size() << endl;
for (auto itr = v2.rbegin(); itr != v2.rend(); itr++)
cout << *itr << " ";
cout << endl;
}
}
|
#ifndef Chequera_h
#define Chequera_h
#include "CtaBanc.h"
using namespace std;
class Chequera:public CtaBanc{
public:
Chequera();
Chequera(int);
int getCom();
void setCom(int);
void muestra();
private:
int comision;
};
Chequera():CtaBanc(){
comision=0;
}
Chequera::Chequera(int n, int s,int c):CtaBanc(n,s){
comision=c;
}
int Chequera::getCom(){
return comision;
}
void Chequera::setCom(int c){
comision=c;
}
void Chequera::muestra(){
cout<<"Numero de Cuenta: "<<n<<endl;
cout<<"Saldo: "<<s<<endl;
cout<<"Comision: "<<c<<endl;
}
#endif /* Chequera_h */
|
/*
* MacCommandLineArgumentHandler.cpp
* Opera
*
* Created by Adam Minchinton on 6/19/07.
* Copyright 2007 Opera All rights reserved.
*
*/
#include "core/pch.h"
#include "modules/util/opfile/opfile.h"
#include "adjunct/desktop_util/boot/DesktopBootstrap.h"
#include "platforms/mac/subclasses/MacCommandLineArgumentHandler.h"
#include "platforms/mac/File/FileUtils_Mac.h"
// Suffix to add to the end of the Opera Preferences folders when -pd option is used
OpString g_pref_folder_suffix;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
OP_STATUS CommandLineArgumentHandler::Create(CommandLineArgumentHandler** handler)
{
*handler = new MacCommandLineArgumentHandler();
return *handler ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
OP_STATUS MacCommandLineArgumentHandler::CheckArgPlatform(CommandLineManager::CLArgument arg_name, const char* arg)
{
// Check the param if needed
return OpStatus::OK;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
OP_STATUS MacCommandLineArgumentHandler::HandlePlatform(CommandLineManager::CLArgument arg_name, CommandLineArgument *arg_value)
{
// Only add the arguments that need to be handled in a specific way for this patform here
switch (arg_name)
{
case CommandLineManager::PrefsSuffix:
g_pref_folder_suffix.Set(CommandLineManager::GetInstance()->GetArgument(CommandLineManager::PrefsSuffix)->m_string_value);
break;
// Now supported on Mac as well. See DSK-339862
case CommandLineManager::PersonalDirectory:
break;
case CommandLineManager::ScreenHeight:
case CommandLineManager::ScreenWidth:
{
CommandLineArgument *cl_height, *cl_width;
// If both of these have be gotten then we can change resolution
if ((cl_height = CommandLineManager::GetInstance()->GetArgument(CommandLineManager::ScreenHeight)) != NULL &&
(cl_width = CommandLineManager::GetInstance()->GetArgument(CommandLineManager::ScreenWidth)) != NULL)
{
// This code needs to be refined so that it doesn't mess up the desktop, tests if it can chage to the mode
// and most likely only change the main display? Should also use the same colour depth as it was using
//CGDirectDisplayID dspy;
CGDirectDisplayID display[5];
CGDisplayCount numDisplays;
CGDisplayCount i;
CGDisplayErr err;
boolean_t exactMatch;
err = CGGetActiveDisplayList(5, display, &numDisplays);
if ( err == CGDisplayNoErr )
{
for ( i = 0; i < numDisplays; ++i )
{
CFDictionaryRef mode;
// Perhaps this should change to other resolutions?
mode = CGDisplayBestModeForParameters(display[i],
24,
800,
600,
&exactMatch);
if ((err = CGDisplaySwitchToMode(display[i], mode)) != CGDisplayNoErr)
return OpStatus::ERR;
}
}
else
return OpStatus::ERR;
}
}
break;
case CommandLineManager::CrashLog:
// Crash recovery requires disabling HW acceleration
g_desktop_bootstrap->DisableHWAcceleration();
break;
default:
// Not handled
return OpStatus::ERR;
}
return OpStatus::OK;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL MacCommandLineArgumentHandler::HideHelp(CommandLineManager::CLArgument arg_name)
{
switch (arg_name)
{
case CommandLineManager::DisableCoreAnimation:
case CommandLineManager::DisableInvalidatingCoreAnimation:
case CommandLineManager::WatirTest:
case CommandLineManager::DebugProxy:
return TRUE;
default:
return FALSE;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
int MacCommandLineArgumentHandler::OutputText(const char *format, ...)
{
char buf[256] = {0};
va_list args;
va_start(args, format);
int ret_val = vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
// Dont output unknown argument -psn message, the psn argument is added by the system
if(!strstr(buf, "Unknown argument: -psn"))
{
printf("%s", buf);
}
return ret_val;
}
|
//你们考了多少分
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxn 200 + 5
typedef struct tree
{ //结构体,l,r存左右端点,num存分数
int r;
int l;
int num;
};
int num[maxn];
tree t[maxn];
inline void pu(int k)
{ //没搞明白
t[k].num = max(t[k << 1].num, t[k << 1 | 1].num);
return;
}
void build(int now, int l, int r)
{ //建树过程
t[now].l = l;
t[now].r = r;
if (l == r)
{
t[now].num = num[l];
return;
} //真正存分数的只有叶子节点,其他节点只是表示区间,方便查找
int mid = (l + r) >> 1;
build(now << 1, l, mid); //开始建左右孩子节点
build(now << 1 | 1, mid + 1, r);
pu(now); //没搞明白
}
int query_poin(int k, int l, int r)
{ //查询函数,区间内的最大值
int res = 0;
if (l <= t[k].l && r >= t[k].r)
return t[k].num; //刚好在区间内,输出数据,有点没明白
int mid = (t[k].r + t[k].l) >> 1;
if (l <= mid)
res = max(res, query_poin(k << 1, l, r)); //有点迷
if (r > mid)
res = max(res, query_poin(k << 1 | 1, l, r));
return res;
}
void update(int now, int x, int y)
{
if(t[now].l==t[now].r){
t[now].num=y;
return ;
}
int mid=(t[now].l+t[now].r)>>1;
if(x<=mid)update(now<<1,x,y);
else update(now<<1|1,x,y);
pu(now);
}
int main()
{
int n, m;
while (scanf("%d%d", &n, &m) != EOF)
{
for (int i = 1; i <= n; i++)
{
scanf("%d", &num[i]);
}
build(1, 1, n);
while (m--)
{
char c;
int i, j;
cin >> c;
scanf("%d%d", &i, &j);
if (c == 'Q')
{
printf("%d\n", query_poin(1, i, j));
}
if (c == 'U')
{
update(1, i, j);
}
}
}
return 0;
}
|
#ifndef NETWORK_H_
#define NETWORK_H_
#include <iostream>
#include <vector>
#include <Eigen/Core>
#include "Instance.hpp"
#include "layers/Linear_layer.h"
#include "layers/Logistic_layer.h"
#include "layers/Quadratic_loss.h"
using namespace Eigen;
class Network
{
public:
Network(int input_size, int output_size = 1);
virtual ~Network();
void install_layer(Layer* target_layer);
void install_loss_function(Loss_function* target_layer);
double train_bp(Instance* data_set, int data_size, double l_rate);
MatrixXd forward(Instance input); //put the input_data into the network
protected:
int input_size, output_size;
std::vector<Layer*> layers;
std::vector<MatrixXd> weights;
Loss_function *loss;
void install_layer(Layer* target_layer, MatrixXd target_weight);
void print();
private:
double train_bp(Instance data, double l_rate); //train a single instance, returnvalue of loss function
};
#endif
|
// written by Michael - originally written Fall, 2000
// updated Fall, 2005
// updated Fall, 2006 - new texture manager, improvements for behaviors
// simple example behaviors - something to learn from
#include "../GrTown_PCH.H"
#include "../DrawUtils.H"
#include "Utilities/Texture.H"
#include "../MMatrix.H"
#include "../GrObject.H"
#include "../Examples/plane.cpp"
#include "../Examples/fireworks.h"
#include "SimpleBehaviors.H"
#include <math.h>
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////
// a trick - since we don't care much about what the rotation is (only
// the rate), we can tie the rotation to the absolute time
Spin::Spin(GrObject* o, float v) : Behavior(o), vel(v)
{
}
void Spin::simulateUntil(unsigned long t)
{
// remember position
float x = owner->transform[3][0];
float y = owner->transform[3][1];
float z = owner->transform[3][2];
// set rotation based on time
rotMatrix(owner->transform, 'y', vel * static_cast<float>(t));
// put the position back
owner->transform[3][0] = x;
owner->transform[3][1] = y;
owner->transform[3][2] = z;
lastV = t;
}
////////////////////////////////////////////////////////////////////////
ForwardAlways::ForwardAlways(GrObject* o, float v)
: Behavior(o), vel(v)
{
}
void ForwardAlways::simulateUntil(unsigned long t)
{
unsigned long dt = t - lastV; // how long since last update
float secs = ((float) dt) / 1000; // convert ms to sec
lastV = t;
owner->transform[3][0] += owner->transform[2][0] * secs * vel;
owner->transform[3][1] += owner->transform[2][1] * secs * vel;
owner->transform[3][2] += owner->transform[2][2] * secs * vel;
lastV = t;
}
////////////////////////////////////////////////////////////////////////
TurnAlways::TurnAlways(GrObject* o, float v)
: Behavior(o), vel(v)
{
}
void TurnAlways::simulateUntil(unsigned long t)
{
unsigned long dt = t - lastV; // how long since last update
float secs = ((float) dt) / 1000; // convert ms to sec
lastV = t;
Matrix delta, newT;
rotMatrix(delta,'Y',secs * vel);
multMatrix(delta,owner->transform,newT);
copyMatrix(newT,owner->transform);
lastV = t;
}
//////////////////////////////////////////////////////////////////////////////
TakeOff::TakeOff(GrObject* owner) :Behavior(owner)
{
plane *p = static_cast<plane*>(owner);
p->fbr = 0;
p->pox = 370.0;
p->poy = 2.0;
p->poz = -300.0;
p->v = 0;
}
Land::Land(GrObject* owner) :Behavior(owner)
{
plane *p = static_cast<plane*>(owner);
p->fbr = -10;
p->pox = -800.0;
p->poy = 200;
p->poz = -300;
p->v = 0.1;
}
void TakeOff::simulateUntil(unsigned long t)
{
unsigned long dt = t - lastV; // how long since last update
float secs = ((float)dt) / 1000; // convert ms to sec
lastV = t;
if (dt > 1000) return;
unsigned long tp = t/1000;
plane *p=static_cast<plane*>(owner);
if (p->v <= 0.15)
{
p->v += secs * 0.03; //accleration of plane
}
else if (p->fbr<=20.0)
{
p->fbr += dt*0.005;
}
float tmp = p->fbr * 2 * pi / 360;
p->poy += dt*p->v*sin(tmp);
p->pox += dt*p->v*cos(tmp);
}
void Land::simulateUntil(unsigned long t)
{
unsigned long dt = t - lastV; // how long since last update
float secs = ((float)dt) / 1000; // convert ms to sec
lastV = t;
if (dt > 1000) return;
plane *p = static_cast<plane*>(owner);
float tmp = -10 * 2 * pi / 360;
if (p->poy <= 6)
{
tmp = 0;
if (p->v > 0.0) p->v -= 0.01*secs;
else p->v = 0;
if (p->fbr > 0.0) p->fbr -= 20.0 * secs;
else p->fbr = 0;
if (p->poy > 2.0) p->poy -= 8.0 * secs;
else p->poy = 2;
}
else if (p->poy < 10)
{
p->fbr = 10.0;
tmp = -(p->poy - 6)*0.41667;
}
else if (p->poy < 30)
{
p->fbr = 20-p->poy;
tmp = -(p->poy - 2)*0.35714;
tmp = tmp * 2 * pi / 360;
}
else
{
tmp = -10 * 2 * pi / 360;
}
p->poy += dt*p->v*sin(tmp);
p->pox += dt*p->v*cos(tmp);
if (p->v == 0) p->over = true;
}
Fly::Fly(GrObject* owner) :Behavior(owner)
{
plane *p;
p=static_cast<plane*>(owner);
p->dir = rand()%361;
p->pox = rand() % 4001 - 2000;
p->poz = rand() % 4001 - 2000;
p->poy = rand() % 100 + 50;
p->v = 0.2;
p->fbr = 0;
p->over = false;
p->lrr = 0;
}
void Fly::simulateUntil(unsigned long t)
{
unsigned long dt = t - lastV; // how long since last update
float secs = ((float)dt) / 1000; // convert ms to sec
lastV = t;
plane *p = static_cast<plane*>(owner);
if (dt > 1000) return;
float tmp = p->dir * 2 * pi / 360;
p->pox += dt*p->v*-sin(tmp);
p->poz += dt*p->v*-cos(tmp);
}
AirControl::AirControl(GrObject* owner, plane **pList) :Behavior(owner), pl(pList), air(false), ld(NULL), tk(NULL)
{
for (int i = 0; i < 10; i++) fl[i]=NULL;
}
void AirControl::simulateUntil(unsigned long t)
{
lastV = t;
if (tk==NULL && ld==NULL)
{
if (rand() % 2 == 0)
{
ld = new Land(pl[0]);
pl[0]->over = false;
}
else
{
tk = new TakeOff(pl[0]);
pl[0]->over = false;
}
}
else if (tk != NULL)
{
if (pl[0]->over)
{
delete tk;
tk = NULL;
}
}
else if (ld != NULL)
{
if (pl[0]->over)
{
delete ld;
ld = NULL;
}
}
for (int i = 0; i < 10; i++)
{
if (fl[i] == NULL)
{
fl[i] = new Fly(pl[i + 1]);
pl[i + 1]->over = false;
}
else
{
if (pl[i + 1]->over)
{
delete fl[i];
fl[i] = new Fly(pl[i + 1]);
pl[i + 1]->over = false;
}
}
}
}
FireControl::FireControl(GrObject *owner):Behavior(owner)
{
}
void FireControl::simulateUntil(unsigned long t)
{
unsigned long dt = t - lastV; // how long since last update
float secs = ((float)dt) / 1000; // convert ms to sec
lastV = t;
Fireworks *f = static_cast<Fireworks*>(owner);
if (dt > 1000) return;
printf("%f %f %f %f\n", f->pt[1]->pox, f->pt[1]->poy, f->pt[1]->poz, f->pt[1]->time);
if (!f->sta)
{
f->sta = true;
f->pox = rand() % 200;
f->poz = rand() % 200;
f->poy = 0;
f->vx = (float)(rand() % 100) / 10;
if (rand() % 2 == 0) f->vx = -f->vx;
f->vz = (float)(rand() % 100) / 10;
if (rand() % 2 == 0)f->vz = -f->vz;
f->vy = (float)(rand() % 50)+50;
f->time = rand() % 2000 + 2000;
}
else if (f->time > 0)
{
f->vy -= 25*secs;
f->pox += f->vx*secs;
f->poy += f->vy*secs;
f->poz += f->vz*secs;
f->time -= dt;
}
else if (!f->peng)
{
f->peng = true;
for (int i = 0; i < 100; i++)
{
f->pt[i]->sta = true;
f->pt[i]->pox = f->pox;
f->pt[i]->poy = f->poy;
f->pt[i]->poz = f->poz;
f->pt[i]->vx = (float)(rand() % 20)-10;
f->pt[i]->vy = (float)(rand() % 20) - 10;
f->pt[i]->vz = (float)(rand() % 20) - 10;
f->pt[i]->time = rand() % 2000+2000;
}
}
else
{
bool survive = false;
for (int i = 0; i < 100; i++)
{
if (f->pt[i]->sta)
{
survive = true;
f->pt[i]->vy -= 5*secs;
f->pt[i]->pox += f->pt[i]->vx*secs;
f->pt[i]->poy += f->pt[i]->vy*secs;
f->pt[i]->poz += f->pt[i]->vz*secs;
f->pt[i]->time -= dt;
if (f->pt[i]->time <= 0) f->pt[i]->sta = false;
}
}
if (!survive)
{
f->sta = false;
f->peng = false;
}
}
}
|
#include "room.h"
#include "ui_mainwindow.h"
#include "mainwindow.h"
Room::Room(string description, string roomSetting) {
this->description = description;
this->roomSetting = roomSetting;
this->itemDescription = itemDescription;
}
void Room::setExits(Room *forward, Room *backward, Room *right, Room *left) {
if (forward != nullptr)
exits["forward"] = forward;
if (backward != nullptr)
exits["backward"] = backward;
if (right != nullptr)
exits["right"] = right;
if (left != nullptr)
exits["left"] = left;
}
string Room::shortDescription() {
return description;
}
string Room::getRoomSetting(){
return roomSetting;
}
string Room::longDescription() {
return description + "\n" + displayItem() + exitString();
}
string Room::exitString() {
string returnString = "\nexits =";
for (map<string, Room*>::iterator i = exits.begin(); i != exits.end(); i++)
// Loop through map
returnString += " " + i->first; // access the "first" element of the pair (direction as a string)
return returnString;
}
Room* Room::nextRoom(string direction) {
map<string, Room*>::iterator next = exits.find(direction); //returns an iterator for the "pair"
if (next == exits.end())
return nullptr; // if exits.end() was returned, there's no room in that direction.
return next->second; // If there is a room, remove the "second" (Room*)
// part of the "pair" (<string, Room*>) and return it.
}
void Room::addItem(Item *inItem) {
itemsInRoom.push_back(*inItem);
}
string Room::displayItem() {
string tempString = "Items in room: ";
if (itemsInRoom.size() < 1) {
tempString = "No item in room";
}
else {
tempString += itemsInRoom.front().getShortDescription();
for (std::size_t n = 1; n < itemsInRoom.size(); ++n) {
tempString += ", " + itemsInRoom[n].getShortDescription();
}
}
return tempString;
}
string Room::showItemInInventory(){
string tempString;
if (itemsInRoom.size() < 1) {
tempString = " ";
}
else {
tempString = itemsInRoom.front().getShortDescription();
}
return tempString;
}
void Room::deleteItem(int index) {
itemsInRoom.erase(itemsInRoom.begin() + index);
}
int Room::numberOfItems() {
return itemsInRoom.size();
}
int Room::isItemInRoom(string inString)
{
int sizeItems = (itemsInRoom.size());
if (itemsInRoom.size() < 1) {
return false;
}
else if (itemsInRoom.size() > 0) {
int x = (0);
for (int n = sizeItems; n > 0; n--) {
// compare inString with short description
int tempFlag = inString.compare( itemsInRoom[x].getShortDescription());
if (tempFlag == 0) {
itemsInRoom.erase(itemsInRoom.begin()+x);
return x;
}
x++;
}
}
return -1;
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Варианты доступа к элементам перечислений enum по выбору пользователя
// V 1.1
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include <iostream>
enum Colors {
YELLOW,
WHITE,
ORANGE,
GREEN,
};
int main() {
using namespace std;
cout << "Choose a color:\n yellow\t - 0,\n white\t - 1,\n orange\t - 2,\n green\t - 3\n";
cout << "Enter num: " << endl;
int userNum;
cin >> userNum;
Colors color(static_cast<Colors>(userNum));
if (color == YELLOW) {
cout << "White" << endl;
}
else if (color == WHITE) {
cout << "Yellow" << endl;
}
else if (color == ORANGE) {
cout << "Orange" << endl;
}
else if (color == GREEN) {
cout << "Green" << endl;
}
else {
cout << "Unknown!" << endl;
}
return 0;
}
/* Output:
Choose a color:
yellow - 0,
white - 1,
orange - 2,
green - 3
Enter num:
1
Yellow
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "623"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 3000
struct BigNum {
int num[MAXN+5];
BigNum(){
memset(num, 0, sizeof(num));
};
friend ostream &operator<<(ostream &out, const BigNum &rhs){
bool start = false;
string ans = "";
for(int i = MAXN+5-1 ; i >= 0 ; i-- ){
char tmp = (rhs.num[i]+'0');
if( rhs.num[i] != 0 )
start = true;
if( start )
ans += tmp;
}
out << ans;
return out;
}
BigNum operator*(int &rhs){
BigNum ans;
for(int i = 0 ; i < MAXN+5 ; i++ )
ans.num[i] = num[i]*rhs;
int carry = 0;
for(int i = 0 ; i < MAXN+5 ; i++ ){
ans.num[i] += carry;
carry = ans.num[i]/10;
ans.num[i] %= 10;
}
return ans;
}
}table[1005];
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
table[0].num[0] = 1;
for(int i = 1 ; i < 1005 ; i++ )
table[i] = table[i-1]*i;
int N;
while( ~scanf("%d",&N) ){
cout << N << "!\n" << table[N] << endl;
}
return 0;
}
|
/*
* Pen.hpp
*
* Created on: Jun 14, 2016
* Author: tgil
*/
#ifndef SGFX_PEN_HPP_
#define SGFX_PEN_HPP_
#include <sgfx/sg_types.h>
#include "../var/Item.hpp"
namespace sgfx {
class Pen : public var::Item<sg_pen_t> {
public:
enum mode {
SET /*! Set pixels to color */ = SG_PEN_FLAG_SET,
CLR /*! Clear pixels to zero */ = SG_PEN_FLAG_CLR,
INVERT /*! Invert pixels */ = SG_PEN_FLAG_INVERT,
BLEND /*! Blend pixels */ = SG_PEN_FLAG_BLEND,
};
Pen();
Pen(u32 color, u8 thickness = 1, bool fill = false, enum mode mode = SET);
u8 thickness() const { return item().thickness; }
bool is_set() const { return (item().o_flags & SG_PEN_FLAG_SET) != 0; }
bool is_clr() const { return (item().o_flags & SG_PEN_FLAG_CLR) != 0; }
bool is_invert() const { return (item().o_flags & SG_PEN_FLAG_INVERT) != 0; }
bool is_blend() const { return (item().o_flags & SG_PEN_FLAG_BLEND) != 0; }
bool is_fill() const { return (item().o_flags & SG_PEN_FLAG_FILL) != 0; }
u32 color() const { return item().color; }
u8 red() const { return item().rgba[0]; }
u8 green() const { return item().rgba[1]; }
u8 blue() const { return item().rgba[2]; }
u8 alpha() const { return item().rgba[3]; }
void set_color(u32 v){ data()->color = v; }
void set_thickness(u8 v){ data()->thickness = v; }
void set_mode(enum mode v){
u16 flags = data()->o_flags;
data()->o_flags = (flags & SG_PEN_FLAG_FILL) | v;
}
void set_fill(bool v = true){
if( v ){
data()->o_flags |= SG_PEN_FLAG_FILL;
} else {
data()->o_flags &= ~SG_PEN_FLAG_FILL;
}
}
};
} /* namespace sgfx */
#endif /* SGFX_PEN_HPP_ */
|
//
// Builder.hpp
// ItsyForth
//
// Created by Dad on 4/17/21.
//
#ifndef Builder_hpp
#define Builder_hpp
/*
#include <string>
#include "Types.hpp"
class Runtime;
class DictionaryWord;
class OpCode;
class Builder {
public:
Builder(Runtime* runtime);
std::string getNextInputWord(char delim);
DictionaryWord* findWord(const OpCode& opcode);
DictionaryWord* findWord(const std::string& name);
DictionaryWord* createWord(OpCode opcode, Num flags = 0);
DictionaryWord* createWord(const std::string& name, OpCode opcode, Num flags = 0);
void compileOpCode(const OpCode& opcode);
void compileConstant(const std::string& name, long value);
void compileLiteral(long value);
void compileStartWord(const std::string& name, Num flags = 0);
void compileReference(DictionaryWord* word);
void compileReference(const std::string& name);
void compileEndWord();
void compileBegin();
void compileIf();
void compileElse();
void compileEndif();
void compileAgain();
void rebuildDictionary();
private:
XData* append(const XData& data);
void pushMarkDP();
void pushMark(XData* m);
XData* popMark();
Runtime* runtime;
XData* marks[16];
int marksIdx;
};
*/
#endif /* Builder_hpp */
|
//
// Created by fab on 11/05/2020.
//
#ifndef DUMBERENGINE_RIGIDBODY_HPP
#define DUMBERENGINE_RIGIDBODY_HPP
#include <bullet/btBulletDynamicsCommon.h>
#include "../IComponent.hpp"
#include "../../systems/physics/Physics.hpp"
#include "ICollisionCallbacks.hpp"
class RigidBody : public IComponent
{
private:
float mass;
btVector3 localInertia;
btTransform physicsTransform;
btCollisionShape* shape;
btRigidBody* body;
btDefaultMotionState* motionState;
bool isDynamic;
public:
void drawInspector() override;
void start() override;
void update() override;
void draw() override;
~RigidBody()
{
Physics::physicEngine->removeRigidBody(body);
delete shape;
delete body;
}
};
#endif //DUMBERENGINE_RIGIDBODY_HPP
|
#include "mpi.h"
#include <vector>
#include <iostream>
using namespace std;
void max(void *a, void *b, int *l, MPI_Datatype *type) {
for (auto i = 0; i < *l; i++) {
((int*)b)[i] = max(((int*)a)[i], ((int*)b)[i]);
}
}
int main(int argc, char **argv) {
int rank, size;
int myres, mpires;
MPI_Init(&argc, &argv);
MPI_Op maxop;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Op_create(&max, 1, &maxop);
int a = rank;
MPI_Reduce(&a, &myres, 1, MPI_INT, maxop, 0, MPI_COMM_WORLD);
MPI_Reduce(&a, &mpires, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
MPI_Op_free(&maxop);
if(rank == 0) {
cout << "my:" << myres << endl;
cout << "mpi:" << mpires << endl;
}
MPI_Finalize();
return EXIT_SUCCESS;
}
|
#include <ncurses.h>
#include <iostream>
#include <sys/time.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
WINDOW *create_newwin(int height, int width, int starty, int startx);
void remove_win(WINDOW *cur_win);
int game_win_height = 20;
int game_win_width = 25;
int next_win_height = 10;
int next_win_width = 14;
WINDOW *game_win, *next_win, *score_win;
//REMEMBER TO COME BACK
int key;
int get_rand(int min, int max) {
return (min + rand() % (max - min + 1));
}
WINDOW *create_newwin(int height, int width, int starty, int startx) {
WINDOW *cur_win;
cur_win = newwin(height, width, starty, startx);
box(cur_win, 0, 0);
wrefresh(cur_win);
//return the pointer
return cur_win;
}
void remove_win(WINDOW *cur_win) {
wborder(cur_win, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
wrefresh(cur_win);
delwin(cur_win);
}
class Piece {
public:
int score;
int x;
int y;
int width;
int height;
int shape;
int box_shape[4][4];
int next_width;
int next_height;
int next_shape;
int next_box_shape[4][4];
int box_map[30][45];
int is_over;
//int game_status;
public:
void initialize();
void set_shape(int &cshape, int box_shape[4][4], int &width, int &height);
void score_next();
void judge();
void move();
void rotate();
//void switch_status();
bool is_overlap();
bool is_row_occupied(int row);
};
void Piece::initialize() {
score = 0;
is_over = false;
for (int i = 0; i < game_win_height; i++)
for (int j = 0; j < game_win_width; j++) {
if(i == 0 || i == game_win_height - 1 || j == 0 || j == game_win_width - 1)
box_map[i][j] = 1;
else
box_map[i][j] = 0;
}
//Initialize shapes
srand((unsigned)time(0));
shape = get_rand(0, 6);
set_shape(shape, box_shape, width, height);
//Print shapes
next_shape = get_rand(0, 6);
set_shape(next_shape, next_box_shape, next_width, next_height);
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if(next_box_shape[i][j] == 1)
mvwaddch(next_win, (next_win_height - next_height)/2+i, (next_win_width - next_width)/2+j, '#');
wrefresh(next_win);
mvwprintw(score_win, next_win_height, next_win_width, "%d", score);
wrefresh(score_win);
}
//update score_win and next_win
void Piece::score_next() {
score++;
judge();
mvwprintw(score_win, next_win_height/2, next_win_width/2, "%d", score);
wrefresh(score_win);
//Update next shape
set_shape(next_shape, box_shape, width, height);
next_shape = get_rand(0, 6);
set_shape(next_shape, next_box_shape, next_width, next_height);
//clean up score window
for (int i = 1; i < next_win_height - 1; i++)
for (int j = 1; j < next_win_width - 1; j++) {
mvwaddch(next_win, i, j, ' ');
wrefresh(next_win);
}
//print next shape
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if(next_box_shape[i][j] == 1) {
mvwaddch(next_win, (next_win_height - next_height)/2+i, (next_win_width - next_width)/2+j, '#');
wrefresh(next_win);
}
}
//set box_shape and width height according to shape
void Piece::set_shape(int &pshape, int box_shape[4][4], int &width, int &height) {
int i,j;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
box_shape[i][j] = 0;
switch(pshape) {
case 0:
height = 1;
width = 4;
box_shape[0][0] = 1;
box_shape[0][1] = 1;
box_shape[0][2] = 1;
box_shape[0][3] = 1;
break;
case 1:
height = 2;
width = 3;
box_shape[0][0] = 1;
box_shape[1][0] = 1;
box_shape[1][1] = 1;
box_shape[1][2] = 1;
break;
case 2:
height = 2;
width = 3;
box_shape[0][2] = 1;
box_shape[1][0] = 1;
box_shape[1][1] = 1;
box_shape[1][2] = 1;
break;
case 3:
height = 2;
width = 3;
box_shape[0][1] = 1;
box_shape[0][2] = 1;
box_shape[1][0] = 1;
box_shape[1][1] = 1;
break;
case 4:
height = 2;
width = 3;
box_shape[0][0] = 1;
box_shape[0][1] = 1;
box_shape[1][1] = 1;
box_shape[1][2] = 1;
break;
case 5:
height = 2;
width = 2;
box_shape[0][0] = 1;
box_shape[0][1] = 1;
box_shape[1][0] = 1;
box_shape[1][1] = 1;
break;
case 6:
height = 2;
width = 3;
box_shape[0][1] = 1;
box_shape[1][0] = 1;
box_shape[1][1] = 1;
box_shape[1][2] = 1;
break;
}
x = game_win_width / 2;
y = 1;
if (is_overlap())
is_over = true;
}
void Piece::rotate() {
int temp[4][4] = {0};
int original_piece[4][4] = {0};
int temp_height, temp_width;
int original_height = height;
int original_width = width;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
original_piece[i][j] = box_shape[i][j];
//Transpose
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
temp[j][i] = box_shape[i][j];
int t = height;
height = width;
width = t;
//Refresh
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
box_shape[i][j] = 0;
//Flip horizontally
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
box_shape[i][width - j - 1] = temp[i][j];
//Rotation is not a valid move -> get back to original
if(is_overlap()) {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
box_shape[i][j] = original_piece[i][j];
height = original_height;
width = original_width;
}
//Rotation is valid
else {
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++) {
if(original_piece[i][j] == 1) {
mvwaddch(game_win, y+i, x+j, ' ');
wrefresh(game_win);
}
}
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++) {
if(box_shape[i][j] == 1) {
mvwaddch(game_win, y+i, x+j, '#');
wrefresh(game_win);
}
}
}
}
/**
Piece::switch_status() {
"stub"
}
**/
//keyboard
void Piece::move() {
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 400000; //.4 sec
//select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptionfds, struct timeval *timeout)
if(select(1, &fds, NULL, NULL, &timeout) == 0) {
y++;
if(is_overlap()) {
y--;
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
if(box_shape[i][j] == 1)
box_map[y+i][x+j] = 1;
score_next();
}
else {
for (int i = height - 1; i >= 0; i--)
for (int j = 0; j < width; j++) {
if (box_shape[i][j] == 1) {
mvwaddch(game_win, y-1+i, x+j, ' ');
mvwaddch(game_win, y+i, x+j, '#');
}
}
wrefresh(game_win);
}
}
//check if fd 0 is in fds
//aka if a signal is received
if(FD_ISSET(0, &fds)) {
key = getch();
while (key == -1);
if (key == KEY_LEFT) {
x--;
if (is_overlap())
x++;
else {
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++) {
if (box_shape[i][j] == 1) {
mvwaddch(game_win, y+i, x+j+1, ' ');
mvwaddch(game_win, y+i, x+j, '#');
}
}
wrefresh(game_win);
}
}
if (key == KEY_RIGHT) {
x++;
if (is_overlap())
x--;
else {
//MIND THE ORDER OF ERASING
for (int i = 0; i < height; i++)
for (int j = width - 1; j >= 0; j--) {
if (box_shape[i][j] == 1) {
mvwaddch(game_win, y+i, x+j-1, ' ');
mvwaddch(game_win, y+i, x+j, '#');
}
}
wrefresh(game_win);
}
}
if(key == KEY_DOWN) {
y++;
if (is_overlap()) {
y--;
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
box_map[y+i][x+j] = 1;
}
else {
//MIND THE ORDER OF ERASING
for (int i = height - 1; i >= 0; i--)
for (int j = 0; j < width; j++) {
if(box_shape[i][j] == 1) {
mvwaddch(game_win, y+i-1, x+j, ' ');
mvwaddch(game_win, y+i, x+j, '#');
}
}
wrefresh(game_win);
}
}
if(key == KEY_UP) {
rotate();
}
}
}
bool Piece::is_overlap() {
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++) {
if (box_shape[i][j] == 1) {
if (y + i > game_win_height - 2)
return true;
if (x + j > game_win_width - 2 || x + j < 1)
return true;
if (box_map[y+i][x+j] == 1)
return true;
}
}
return false;
}
bool Piece::is_row_occupied(int row) {
for (int j = 1; j < game_win_width - 1; j++)
if(box_map[row][j] == 1)
return true;
return false;
}
void Piece::judge() {
int filled_line = 0;
bool is_full;
for (int i = 1; i < game_win_height - 1; i++) {
is_full = true;
for (int j = 1; j < game_win_width - 1; j++) {
if (box_map[i][j] == 0)
is_full = false;
}
//Empty the row first, and get rid of empty rows
if (is_full) {
score += 5;
filled_line++;
for (int j = 1; j < game_win_width - 1; j++)
box_map[i][j] = 0;
}
}
if (filled_line != 0) {
for (int i = game_win_height - 2; i > 1; i--) {
int temp = i;
if (!is_row_occupied(i)) {
while(temp > 1 && (!is_row_occupied(--temp)));
//Until a row that has something
for(int j = 1; j < game_win_width - 1; j++) {
box_map[i][j] = box_map[temp][j];
box_map[temp][j] = 0;
}
}
}
for (int i = 1; i < game_win_height - 1; i++)
for (int j = 1; j < game_win_width - 1; j++) {
if(box_map[i][j] == 1)
mvwaddch(game_win, i, j, '#');
else
mvwaddch(game_win, i, j, ' ');
}
wrefresh(game_win);
}
}
//Game loop
int main() {
initscr();
cbreak();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
refresh();
//Windows
game_win = create_newwin(game_win_height, game_win_width, 0, 0);
wborder(game_win, '|', '|', '-', '-', '+', '+', '+', '+');
wrefresh(game_win);
score_win = create_newwin(next_win_height, next_win_width, 10, game_win_width+5);
mvprintw(10, game_win_width+5, "%s", "Score");
refresh();
next_win = create_newwin(next_win_height, next_win_width, 0, game_win_width+5);
mvprintw(0, game_win_width+5, "%s", "Next");
refresh();
Piece *p = new Piece;
p -> initialize();
while(!p -> is_over)
p -> move();
// Clean up
remove_win(game_win);
remove_win(next_win);
remove_win(score_win);
delete p;
system("clear");
int terminal_height, terminal_width;
getmaxyx(stdscr, terminal_height, terminal_width);
mvprintw(terminal_height/2, terminal_width/2, "%s", "GAME OVER!\n");
refresh();
sleep(2);
endwin();
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e8
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
// 昇順sort
#define sorti(x) sort(x.begin(), x.end())
// 降順sort
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
int main() {
int n;
while (cin >> n && n) {
vector<vector<int> > stage(n, vector<int>(n+1, 0));
rep(i,n)rep(j,n+1) cin >> stage[i][j];
vector<int> dp(1 << n, INF);
dp[0] = 0;
// 1 ~ n
for (int bit = 0; bit < (1 << n); ++bit) {
rep(i,n) {
if ( (bit & (1 << i)) != 0) continue;
int cost = stage[i][0];
rep(j,n) {
if ( (bit & (1 << j)) == 0) continue;
cost = min(stage[i][j+1], cost);
}
int now = (bit | (1 << i));
dp[now] = min(dp[now], dp[bit] + cost);
}
}
cout << dp[(1 << n) - 1] << endl;
}
}
|
// Created on: 2015-02-18
// Created by: Nikolai BUKHALOV
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2015 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntPatch_PointLine_HeaderFile
#define _IntPatch_PointLine_HeaderFile
#include <Adaptor3d_Surface.hxx>
#include <IntPatch_Line.hxx>
class gp_Pnt;
class gp_Pnt2d;
class IntSurf_PntOn2S;
class IntSurf_LineOn2S;
class IntPatch_Point;
DEFINE_STANDARD_HANDLE(IntPatch_PointLine, IntPatch_Line)
//! Definition of an intersection line between two
//! surfaces.
//! A line defined by a set of points
//! (e.g. coming from a walking algorithm) as
//! defined in the class WLine or RLine (Restriction line).
class IntPatch_PointLine : public IntPatch_Line
{
public:
//! Adds a vertex in the list. If theIsPrepend == TRUE the new
//! vertex will be added before the first element of vertices sequence.
//! Otherwise, to the end of the sequence
Standard_EXPORT virtual
void AddVertex (const IntPatch_Point& Pnt,
const Standard_Boolean theIsPrepend = Standard_False) = 0;
//! Returns the number of intersection points.
Standard_EXPORT virtual Standard_Integer NbPnts() const = 0;
//! Returns number of vertices (IntPatch_Point) of the line
Standard_EXPORT virtual Standard_Integer NbVertex() const = 0;
//! Returns the intersection point of range Index.
Standard_EXPORT virtual const IntSurf_PntOn2S& Point (const Standard_Integer Index) const = 0;
//! Returns the vertex of range Index on the line.
Standard_EXPORT virtual const IntPatch_Point& Vertex (const Standard_Integer Index) const = 0;
//! Returns the vertex of range Index on the line.
virtual IntPatch_Point& ChangeVertex (const Standard_Integer Index) = 0;
//! Removes vertices from the line
Standard_EXPORT virtual void ClearVertexes() = 0;
//! Removes single vertex from the line
Standard_EXPORT virtual void RemoveVertex (const Standard_Integer theIndex) = 0;
//! Returns set of intersection points
Standard_EXPORT virtual Handle(IntSurf_LineOn2S) Curve() const = 0;
//! Returns TRUE if P1 is out of the box built from
//! the points on 1st surface
Standard_EXPORT virtual Standard_Boolean IsOutSurf1Box(const gp_Pnt2d& P1) const = 0;
//! Returns TRUE if P2 is out of the box built from
//! the points on 2nd surface
Standard_EXPORT virtual Standard_Boolean IsOutSurf2Box(const gp_Pnt2d& P2) const = 0;
//! Returns TRUE if P is out of the box built from 3D-points.
Standard_EXPORT virtual Standard_Boolean IsOutBox(const gp_Pnt& P) const = 0;
//! Returns the radius of curvature of
//! the intersection line in given point.
//! Returns negative value if computation is not possible.
Standard_EXPORT static Standard_Real
CurvatureRadiusOfIntersLine(const Handle(Adaptor3d_Surface)& theS1,
const Handle(Adaptor3d_Surface)& theS2,
const IntSurf_PntOn2S& theUVPoint);
DEFINE_STANDARD_RTTIEXT(IntPatch_PointLine,IntPatch_Line)
protected:
//! To initialize the fields, when the transitions
//! are In or Out.
Standard_EXPORT IntPatch_PointLine(const Standard_Boolean Tang, const IntSurf_TypeTrans Trans1, const IntSurf_TypeTrans Trans2);
//! To initialize the fields, when the transitions
//! are Touch.
Standard_EXPORT IntPatch_PointLine(const Standard_Boolean Tang, const IntSurf_Situation Situ1, const IntSurf_Situation Situ2);
//! To initialize the fields, when the transitions
//! are Undecided.
Standard_EXPORT IntPatch_PointLine(const Standard_Boolean Tang);
private:
};
#endif // _IntPatch_PointLine_HeaderFile
|
//UVA 515-King
/*
題目大意:
給定一個序列的長度,然後給定若干關係:這個關係是子序列各個元素之和與某個給定整數的大小關係。要求是否存在這樣一個序列滿足所有給定的若干關係。
本題主要就是需要想到利用前n個元素的和為替代,即設s[i] = a[1] + a[2] + …a[i]。
則a[si] + a[si+1] + … + a[si + ni] = s[si + ni] - s[si - 1];所以如果a[si] + a[si+1] + … + a[si + ni] < k 則 s[si + ni] - s[si - 1] < k <= k - 1;如果a[si] + a[si+1] + … + a[si + ni] > k 則 s[si - 1] - s[si + ni] < -k <= -k - 1;
*/
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <queue>
using namespace std;
const int MAX_N = 200 + 10;
int head[MAX_N],d[MAX_N],cnt[MAX_N],vis[MAX_N];
const int INF = (1 << 30);
struct Edge
{
int v, w, next;
};
Edge edge[MAX_N];
int n, m, _count;
void addEdge(int u, int v, int w)
{
edge[_count].v = v;
edge[_count].w = w;
edge[_count].next = head[u];
head[u] = _count++;
}
bool SPFA()
{
memset(vis,0,sizeof(vis));
memset(cnt,0,sizeof(cnt));
for(int i = 0;i <= n;i++)
d[i] = INF;
d[n + 1] = 0;
queue<int> Q;
Q.push(n + 1);
cnt[n + 1]++;
while(!Q.empty())
{
int u = Q.front();
Q.pop();
vis[u] = false;
for(int e = head[u]; e != -1; e = edge[e].next)
{
if(d[edge[e].v] > d[u] + edge[e].w)
{
d[edge[e].v] = d[u] + edge[e].w;
if(!vis[edge[e].v])
{
Q.push(edge[e].v);
vis[edge[e].v] = true;
cnt[edge[e].v]++;
if(cnt[edge[e].v] >= n + 2)// 0 ~ n + 1 共有n + 2個點
return false;
}
}
}
}
return true;
}
int main()
{
while(scanf("%d", &n), n)
{
scanf("%d", &m);
int s, len, k;
char str[10];
_count = 0;
memset(head, -1, sizeof(head));
for(int i = 0; i <= n; i++)
addEdge(n + 1, i, 0);//添加從n + 1 到所有點的路徑,設置邊權為0
for(int i = 1; i <= m; i++)
{
scanf("%d%d%s%d", &s, &len, str, &k);
if(str[0] == 'g')//將大於轉換為小於等於
addEdge(s + len, s - 1, -k - 1);
else//將小於轉化為小於等於
addEdge(s - 1, s + len, k - 1);
}
if(!SPFA())
printf("successful conspiracy\n");
else
printf("lamentable kingdom\n");
}
return 0;
}
|
#ifndef INTERFACE_H
#define INTERFACE_H
#include "data_types/pioneer.h"
#include "data_types/computer.h"
#include "services/pioneerservice.h"
#include "services/computerservice.h"
#include "services/relationservice.h"
#include "services/relationservice.h"
#include "ui/menuscreen.h"
#include <iostream>
#include <vector>
#include <string>
#include <limits>
using namespace std;
class Interface{
public:
Interface();
// Default Constructor
void userInput();
// Decides what the program should do, based on the input from user
// -----------------------------------------------------------
// MENU SCREENS & MESSAGES
// -----------------------------------------------------------
void searchPioneer(bool &goToMainMenu);
// Function that allows user to search for pioneer
void searchComputer(bool &goToMainMenu);
// Function that allows user to search for computer
void searchRelation(bool& goToMainMenu);
// Function that allows user to search for relations
void errorMessage();
// General error message
bool continueMessage();
// Asks if user wants to continue
int menuErrorCheck(int min, int max);
// Checks if input is correct. If not, displays an error message
void searchResults(string str);
// Display of search result
void notFound();
// Prints out a message that says "No search results were found"
// -----------------------------------------------------------
// PRINT FUNCTIONS
// -----------------------------------------------------------
void printListOfPioneers(vector<Pioneer>& list);
// Prints list of pioneers
void printListOfComputers(vector<Computer>& list);
// Prints list of computers
void printListOfRelations(vector<Relation>& list);
// Prints list of relations
void print();
// Sends user to correct print function
void pioneerPrintChoice();
// Gets input from user how to print list of pioneers and prints it out
void computerPrintChoice();
// Gets input from user how to print list of computers and prints it out
void printRelations();
// Prints relations between pioneer and computer
void getPioFilterInput(char& f, char& m, char& d, char& a, int input);
// Gets input from user from filter menu and sets parameters as 'X' or ' ' depending on what was chosen
void getCompFilterInput(char& b, char& n, char& m, char& e, char& t, int input);
// Gets input from user from filter menu and sets parameters as 'X' or ' ' depending on what was chosen
void twoFilterCheck(char& input, char& other);
// Checks and makes sure that input and other are never chosen at same time and toggles values if already chosen
void threeFilterCheck(char& input, char& filterTwo, char& filterThree);
// Checks and makes sure that input, filterTwo and filterThree are never chosen at same time and toggles values if already chosen
void getSortSqlCommand(string &orderBy, int input, string type);
// Returns correct string to be used in SQL command in Connection class based on user input
void getPioFilterSqlCommand(char& f, char& m, char& d, char& a, string& sex, string& dead);
// Returns correct string to be used in SQL command in Connection class based on user input
void getCompFilterSqlCommand(char& b, char& n, char& m, char& e, char& t, string& built, string& type);
// Returns correct string to be used in SQL command in Connection class based on user input
void getDirectionSqlCommand(string& direction, int input);
// Returns correct string to be used in SQL command in Connection class based on user input
// -----------------------------------------------------------
// SEARCH FUNCTIONS
// -----------------------------------------------------------
void search();
// Function that starts search
// -----------------------------------------------------------
// ADD FUNCTIONS
// -----------------------------------------------------------
void addCompOrPio();
// Add a pioneer or a computer to the list ?
void addPioneer();
// Gets input from user about a new pioneer to add to database
void addComputer();
// Gets input from user about a new computer to add to database
// -----------------------------------------------------------
// DELETE FUNCTIONS
// -----------------------------------------------------------
void deleteThings();
// Delete menu, chooses where to delete from
void deletePio();
// Deletes either a single pioneer or all pioneers
void deleteComp();
// Deletes either a single computer or all computers
// -----------------------------------------------------------
// GET FUNCTIONS
// -----------------------------------------------------------
string getSex(string sex);
// Gets input from user with error check and returns result
int getYear();
// Gets input from user with error check and returns result
void getRelation(char numb);
// ...
string getDescription(string desc);
// Gets description from user and returns the result
string wasBuilt(int buildYear);
// Gets if the computer was built or not
void printList();
// Prints list from SQL database
void linkCtoP();
// Links computer to pioneer
void linkPioCheck(vector<Pioneer>& result, Pioneer& relationPio);
// Checks size of vector and lets user pick Pioneer if vector is > 1
void linkCompCheck(vector<Computer>& result, Computer& relationComp, Pioneer relationPio);
// Checks size of vector and lets user pick Computer if vector is > 1
private:
PioneerService pioService;
ComputerService compService;
RelationService relService;
Pioneer pioTemp;
Computer compTemp;
MenuScreen menu;
};
#endif // INTERFACE_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include <core/pch.h>
#ifdef EXTENSION_SUPPORT
#include "modules/dom/src/extensions/domextensionuibadge.h"
#include "modules/dom/src/extensions/domextensionuiitem.h"
#include "modules/dom/src/canvas/domcontext2d.h"
#include "modules/stdlib/include/double_format.h"
/* static */ OP_STATUS
DOM_ExtensionUIBadge::Make(DOM_Object *this_object, DOM_ExtensionUIBadge *&new_obj, ES_Object *properties, DOM_ExtensionUIItem *owner, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
RETURN_IF_ERROR(DOMSetObjectRuntime(new_obj = OP_NEW(DOM_ExtensionUIBadge, ()), origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::EXTENSION_UIBADGE_PROTOTYPE), "Badge"));
return new_obj->Initialize(this_object, properties, owner, return_value, origining_runtime);
}
static OP_STATUS
ConstructUIColor(DOM_Object *this_object, UINT32 &color_val, ES_Value &value, ES_Value *return_value, ES_Runtime *origining_runtime)
{
if (value.type == VALUE_STRING)
{
const uni_char *col_string = value.value.string;
COLORREF col;
if (!ParseColor(col_string, uni_strlen(col_string), col))
{
this_object->CallDOMException(DOM_Object::NOT_SUPPORTED_ERR, return_value);
return OpStatus::ERR;
}
else
{
color_val = col;
return OpStatus::OK;
}
}
else if (value.type == VALUE_OBJECT)
{
ES_Object *color_array = value.value.object;
unsigned char rgba[4]; /* ARRAY OK 2010-09-08 sof */
ES_Value color_value;
for (unsigned i = 0; i < 4; i++)
{
OP_BOOLEAN result;
if (OpBoolean::IsError(result = origining_runtime->GetIndex(color_array, i, &color_value)))
{
if (i == 3)
{
rgba[3] = 0xff;
break;
}
else
return result;
}
else if (result == OpBoolean::IS_FALSE || color_value.type != VALUE_NUMBER || !op_isfinite(value.value.number))
{
this_object->CallDOMException(DOM_Object::NOT_SUPPORTED_ERR, return_value);
return OpStatus::ERR;
}
else
{
double d = color_value.value.number;
if (d < 0 || d > 255)
{
this_object->CallDOMException(DOM_Object::NOT_SUPPORTED_ERR, return_value);
return OpStatus::ERR;
}
else
rgba[i] = static_cast<unsigned char>(op_truncate(d));
}
}
color_val = OP_RGBA(rgba[0], rgba[1], rgba[2], rgba[3]);
return OpStatus::OK;
}
else
{
this_object->CallDOMException(DOM_Object::NOT_SUPPORTED_ERR, return_value);
return OpStatus::ERR;
}
}
/* static */ int
DOM_ExtensionUIBadge::update(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT(badge, DOM_TYPE_EXTENSION_UIBADGE, DOM_ExtensionUIBadge);
if (argc < 0)
{
badge->m_owner->SetBlockedThread(NULL);
badge->m_owner->GetThreadListener()->Remove();
OpExtensionUIListener::ItemAddedStatus call_status = badge->m_owner->GetAddedCallStatus();
badge->m_owner->ResetCallStatus();
return DOM_ExtensionUIItem::HandleItemAddedStatus(this_object, call_status, return_value);
}
DOM_CHECK_ARGUMENTS("o");
ES_Object *properties = argv[0].value.object;
DOM_Runtime *runtime = badge->GetRuntime();
BOOL has_changed = FALSE;
OP_STATUS status;
OP_BOOLEAN result;
ES_Value value;
CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("backgroundColor"), &value));
if (result == OpBoolean::IS_TRUE)
{
has_changed = TRUE;
UINT32 new_color;
if (OpStatus::IsSuccess(status = ConstructUIColor(this_object, new_color, value, return_value, origining_runtime)))
badge->m_background_color = new_color;
else
return (OpStatus::IsMemoryError(status) ? ES_NO_MEMORY : ES_EXCEPTION);
}
CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("color"), &value));
if (result == OpBoolean::IS_TRUE)
{
has_changed = TRUE;
UINT32 new_color;
if (OpStatus::IsSuccess(status = ConstructUIColor(this_object, new_color, value, return_value, origining_runtime)))
badge->m_color = new_color;
else
return (OpStatus::IsMemoryError(status) ? ES_NO_MEMORY : ES_EXCEPTION);
}
CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("display"), &value));
if (result == OpBoolean::IS_TRUE && value.type == VALUE_STRING)
{
const uni_char *disp = value.value.string;
BOOL is_none = FALSE;
if ((is_none = uni_str_eq("none", disp)) || uni_str_eq("block", disp))
{
if (badge->m_displayed == is_none)
has_changed = TRUE;
badge->m_displayed = !is_none;
}
else
has_changed = FALSE;
}
CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("textContent"), &value));
if (result == OpBoolean::IS_TRUE && value.type == VALUE_STRING)
{
has_changed = TRUE;
RETURN_IF_ERROR(UniSetConstStr(badge->m_text_content, value.value.string));
}
if (has_changed)
{
CALL_INVALID_IF_ERROR(badge->m_owner->NotifyItemUpdate(origining_runtime, badge->m_owner));
return (ES_SUSPEND | ES_RESTART);
}
else
return ES_FAILED;
}
OP_STATUS
DOM_ExtensionUIBadge::Initialize(DOM_Object *this_object, ES_Object *properties, DOM_ExtensionUIItem *owner, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
m_owner = owner;
m_background_color = DEFAULT_BADGE_BACKGROUND_COLOR_VALUE;
m_color = DEFAULT_BADGE_COLOR_VALUE;
m_displayed = DEFAULT_BADGE_DISPLAYED;
m_text_content = NULL;
OP_BOOLEAN result;
ES_Value value;
RETURN_IF_ERROR(result = origining_runtime->GetName(properties, UNI_L("backgroundColor"), &value));
if (result == OpBoolean::IS_TRUE)
{
UINT32 new_color;
RETURN_IF_ERROR(ConstructUIColor(this_object, new_color, value, return_value, origining_runtime));
m_background_color = new_color;
}
RETURN_IF_ERROR(result = origining_runtime->GetName(properties, UNI_L("color"), &value));
if (result == OpBoolean::IS_TRUE)
{
UINT32 new_color;
RETURN_IF_ERROR(ConstructUIColor(this_object, new_color, value, return_value, origining_runtime));
m_color = new_color;
}
RETURN_IF_ERROR(result = origining_runtime->GetName(properties, UNI_L("display"), &value));
if (result == OpBoolean::IS_TRUE && value.type == VALUE_STRING)
{
const uni_char *disp = value.value.string;
BOOL is_none = FALSE;
if ((is_none = uni_str_eq("none", disp)) || uni_str_eq("block", disp))
m_displayed = !is_none;
}
RETURN_IF_ERROR(result = origining_runtime->GetName(properties, UNI_L("textContent"), &value));
if (result == OpBoolean::IS_TRUE)
{
if (value.type == VALUE_STRING)
RETURN_IF_ERROR(UniSetConstStr(m_text_content, value.value.string));
else if (value.type == VALUE_NUMBER)
{
char num_str_buf[32]; /* ARRAY OK 2010-11-09 sof */
OpDoubleFormat::ToString(num_str_buf, value.value.number);
RETURN_IF_ERROR(SetStr(const_cast<uni_char *&>(m_text_content), const_cast<const char *>(num_str_buf)));
}
else if (value.type == VALUE_BOOLEAN)
RETURN_IF_ERROR(SetStr(const_cast<uni_char *&>(m_text_content), value.value.boolean ? "true" : "false"));
}
return OpStatus::OK;
}
DOM_ExtensionUIBadge::DOM_ExtensionUIBadge()
: m_owner(NULL)
, m_text_content(NULL)
, m_displayed(DEFAULT_BADGE_DISPLAYED)
, m_background_color(0)
, m_color(0)
{
}
DOM_ExtensionUIBadge::~DOM_ExtensionUIBadge()
{
OP_NEW_DBG("DOM_ExtensionUIBadge::~DOM_ExtensionUIBadge()", "extensions.dom");
OP_DBG(("this: %p text_content: %s", this, m_text_content));
OP_DELETEA(m_text_content);
}
/* virtual */ ES_GetState
DOM_ExtensionUIBadge::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch(property_name)
{
case OP_ATOM_display:
DOMSetString(value, m_displayed ? UNI_L("block") : UNI_L("none"));
return GET_SUCCESS;
case OP_ATOM_textContent:
DOMSetString(value, m_text_content ? m_text_content : DEFAULT_BADGE_TEXTCONTENT);
return GET_SUCCESS;
case OP_ATOM_backgroundColor:
return DOMCanvasColorUtil::DOMSetCanvasColor(value, m_background_color);
case OP_ATOM_color:
return DOMCanvasColorUtil::DOMSetCanvasColor(value, m_color);
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ExtensionUIBadge::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch(property_name)
{
case OP_ATOM_display:
if (value->type == VALUE_BOOLEAN && m_displayed != static_cast<BOOL>(value->value.boolean))
{
m_displayed = value->value.boolean;
PUT_FAILED_IF_ERROR_EXCEPTION(m_owner->NotifyItemUpdate(origining_runtime, m_owner), INVALID_STATE_ERR);
DOMSetNull(value);
return PUT_SUSPEND;
}
else if (value->type != VALUE_STRING)
return PUT_NEEDS_STRING;
else if (uni_str_eq(value->value.string, "block") || uni_str_eq(value->value.string, "none"))
{
m_displayed = uni_str_eq("block", value->value.string);
PUT_FAILED_IF_ERROR_EXCEPTION(m_owner->NotifyItemUpdate(origining_runtime, m_owner), INVALID_STATE_ERR);
DOMSetNull(value);
return PUT_SUSPEND;
}
else
return PUT_SUCCESS;
case OP_ATOM_textContent:
if (value->type != VALUE_STRING)
return PUT_NEEDS_STRING;
else if (!m_text_content || !uni_str_eq(value->value.string, m_text_content))
{
PUT_FAILED_IF_ERROR(UniSetConstStr(m_text_content, value->value.string));
PUT_FAILED_IF_ERROR_EXCEPTION(m_owner->NotifyItemUpdate(origining_runtime, m_owner), INVALID_STATE_ERR);
DOMSetNull(value);
return PUT_SUSPEND;
}
else
return PUT_SUCCESS;
case OP_ATOM_backgroundColor:
if (value->type == VALUE_STRING || value->type == VALUE_OBJECT)
{
UINT32 new_color;
OP_STATUS status;
ES_Value return_value;
if (OpStatus::IsSuccess(status = ConstructUIColor(this, new_color, *value, &return_value, origining_runtime)))
{
m_background_color = new_color;
PUT_FAILED_IF_ERROR_EXCEPTION(m_owner->NotifyItemUpdate(origining_runtime, m_owner), INVALID_STATE_ERR);
DOMSetNull(value);
return PUT_SUSPEND;
}
else
return (OpStatus::IsMemoryError(status) ? PUT_NO_MEMORY : PUT_EXCEPTION);
}
else
return PUT_NEEDS_STRING;
case OP_ATOM_color:
if (value->type == VALUE_STRING || value->type == VALUE_OBJECT)
{
UINT32 new_color;
OP_STATUS status;
ES_Value return_value;
if (OpStatus::IsSuccess(status = ConstructUIColor(this, new_color, *value, &return_value, origining_runtime)))
{
m_color = new_color;
PUT_FAILED_IF_ERROR_EXCEPTION(m_owner->NotifyItemUpdate(origining_runtime, m_owner), INVALID_STATE_ERR);
DOMSetNull(value);
return PUT_SUSPEND;
}
else
return (OpStatus::IsMemoryError(status) ? PUT_NO_MEMORY : PUT_EXCEPTION);
}
else
return PUT_NEEDS_STRING;
default:
return DOM_Object::PutName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_ExtensionUIBadge::PutNameRestart(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime, ES_Object *restart_object)
{
switch (property_name)
{
case OP_ATOM_display:
case OP_ATOM_textContent:
case OP_ATOM_backgroundColor:
case OP_ATOM_color:
{
m_owner->SetBlockedThread(NULL);
m_owner->GetThreadListener()->Remove();
OpExtensionUIListener::ItemAddedStatus call_status = m_owner->GetAddedCallStatus();
m_owner->ResetCallStatus();
return ConvertCallToPutName(DOM_ExtensionUIItem::HandleItemAddedStatus(this, call_status, value), value);
}
default:
return DOM_Object::PutNameRestart(property_name, value, origining_runtime, restart_object);
}
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_ExtensionUIBadge)
DOM_FUNCTIONS_FUNCTION(DOM_ExtensionUIBadge, DOM_ExtensionUIBadge::update, "update", "o-")
DOM_FUNCTIONS_END(DOM_ExtensionUIBadge)
#endif // EXTENSION_SUPPORT
|
/**
Este codigo esta basado en el ejemplo/data/data/Andres/Repos/command_source/Geant4/Ejemplos10x3/Geant4-10.3.0/extended/electromagnetic/TestEm0/DirectAccess.cc
*/
#include "MyAnalysisManager.hh"
#include "G4Material.hh"
#include "G4PEEffectFluoModel.hh" //Fotoelectrico
#include "G4KleinNishinaCompton.hh" //Compton
#include "G4BetheHeitlerModel.hh" //Conversion interna
#include "G4eeToTwoGammaModel.hh"
#include "G4MollerBhabhaModel.hh"
#include "G4SeltzerBergerModel.hh"
#include "G4BetheBlochModel.hh"
#include "G4BraggModel.hh"
#include "G4MuBetheBlochModel.hh"
#include "G4MuBremsstrahlungModel.hh"
#include "G4MuPairProductionModel.hh"
#include "globals.hh"
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
#include "G4Gamma.hh"
#include "G4Positron.hh"
#include "G4Electron.hh"
#include "G4Proton.hh"
#include "G4MuonPlus.hh"
#include "G4DataVector.hh"
#include "G4NistManager.hh"
#include "G4ParticleTable.hh"
int main() {
double minx, maxx;
int nbins = pow(10,8);
minx= pow(10,-4); maxx= pow(10, 4);
double dx= (maxx-minx) / nbins;
auto AM= MyAnalysisManager::Instance();
AM->CreateTGraph(1, AM->Color(1) ); //Fotoelectrico
AM->CreateTGraph(1, AM->Color(2) ); //Compton
AM->CreateTGraph(1, AM->Color(3) ); //Pares
AM->CreateTGraph(1, AM->Color(0) ); //Total
G4UnitDefinition::BuildUnitsTable();
G4ParticleDefinition* gamma = G4Gamma::Gamma();
G4DataVector cuts;
cuts.push_back(1*keV);
G4Material* material = G4NistManager::Instance()->FindOrBuildMaterial("G4_Fe");
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
G4MaterialCutsCouple* couple = new G4MaterialCutsCouple(material);
couple->SetIndex(0);
// work only for simple materials
G4double Z = material->GetZ();
//G4double A = material->GetA(); //umas
G4VEmModel* phot = new G4PEEffectFluoModel();
G4VEmModel* comp = new G4KleinNishinaCompton();
G4VEmModel* conv = new G4BetheHeitlerModel();
phot->Initialise(gamma, cuts);
comp->Initialise(gamma, cuts);
conv->Initialise(gamma, cuts);
// valid pointer to a couple is needed for this model
phot->SetCurrentCouple(couple);
// compute CrossSection per atom and MeanFreePath
G4double Emin = minx*MeV, Emax = maxx*MeV, dz = dx*MeV;
G4double E; G4double CrossPhoto; G4double CrossCompt; G4double CrossConv;
double z0= log10(Emin) ; double z;
int i=1;
for (E = Emin, z=z0 ; E <= Emax; z+=dz, i+=1, E = pow(10, z) )
{
CrossPhoto = phot->ComputeCrossSectionPerAtom(gamma,E,Z);
CrossCompt = comp->ComputeCrossSectionPerAtom(gamma,E,Z);
CrossConv = conv->ComputeCrossSectionPerAtom(gamma,E,Z);
AM->SetPointTGraph(0, i , E/MeV, CrossPhoto/millibarn);
AM->SetPointTGraph(1, i , E/MeV, CrossCompt/millibarn);
AM->SetPointTGraph(2, i , E/MeV, CrossConv/millibarn);
AM->SetPointTGraph(3, i , E/MeV, (CrossConv + CrossCompt + CrossPhoto )/millibarn );
}
//G4BestUnit (conv->ComputeCrossSectionPerAtom(gamma,Energy,Z),"Surface")
//G4BestUnit (phot->ComputeMeanFreePath(gamma,Energy,material),"Length")
AM->SetFrame( minx, 1, maxx, pow(10,10) );
AM->GetTGraph(0)->Draw("PLSAME");
AM->GetTGraph(1)->Draw("PLSAME");
AM->GetTGraph(2)->Draw("PLSAME");
AM->GetTGraph(3)->Draw("PLSAME");
AM->Print();
return 0;
}
|
#include <iostream>
int main(void){
std::cout<<"helloworld"<<std::endl;
return 0;
}
|
#include <NaryTree.h>
#include <Wrapper.h>
#include <PrePostVisitor.h>
#include <PuttingVisitor.h>
#include <iostream>
int main(void)
{
using namespace std;
Int *ip = new Int(0);
Int *ip1 = new Int(1);
Int *ip2 = new Int(2);
Int *ip3 = new Int(3);
Int *ip11 = new Int(11);
Int *ip12 = new Int(12);
Int *ip13 = new Int(13);
Int *ip21 = new Int(21);
Int *ip22 = new Int(22);
Int *ip31 = new Int(31);
NaryTree *nt = new NaryTree(3, *ip);
NaryTree *nt1 = new NaryTree(3, *ip1);
NaryTree *nt2 = new NaryTree(3, *ip2);
NaryTree *nt3 = new NaryTree(3, *ip3);
NaryTree *nt11 = new NaryTree(3, *ip11);
NaryTree *nt12 = new NaryTree(3, *ip12);
NaryTree *nt13 = new NaryTree(3, *ip13);
NaryTree *nt21= new NaryTree(3, *ip21);
NaryTree *nt22= new NaryTree(3, *ip22);
NaryTree *nt31= new NaryTree(3, *ip31);
nt1->AttachSubtree(0, *nt11);
nt1->AttachSubtree(1, *nt12);
nt1->AttachSubtree(2, *nt13);
nt2->AttachSubtree(0,*nt21);
nt2->AttachSubtree(1, *nt22);
nt3->AttachSubtree(0, *nt31);
nt->AttachSubtree(0, *nt1);
nt->AttachSubtree(1, *nt2);
nt->AttachSubtree(2, *nt3);
cout << "is empty?:" << nt->IsEmpty()<< endl;
cout<<" degree:" << nt->Degree() <<endl;
cout << "root tree key : " << nt->Key()<< endl;
cout << "is leaf?:"<< nt->IsLeaf()<<endl;
cout << "height:"<< nt->Height() << endl;
PuttingVisitor pv(cout);
PreOrder ppv(pv);
Tree & t = dynamic_cast<Tree &> (*nt);
cout <<endl<<"breadth first travel as following:" <<endl;
t.BreadthFirstTraversal(pv);
cout << endl;
cout <<"Depth first travel as following:" <<endl;
t.DepthFirstTraversal(ppv);
cout << endl;
cout << " visit the General Tree as Iterator:"<< endl;
Iterator &i = t.NewIterator();
while(!i.IsDone()){
Int &g = dynamic_cast<Int &>(*i);
cout << " ";
g.Put(cout) ;
++i;
}
cout << endl;
cout << " after detatch sub tree do BreadthFirstTraversal : "<< endl;
NaryTree &nt3r = nt->DetachSubtree(2);
delete &nt3r;
t.BreadthFirstTraversal(pv);
cout <<endl;
}
|
#include "stdafx.h"
#include "txtData.h"
txtData::txtData(){}
txtData::~txtData(){}
HRESULT txtData::init(){ return S_OK; }
void txtData::release(){}
//save
void txtData::txtSave(const char * saveFileName, vector<string> vStr)
{
HANDLE file;
char str[128];
DWORD write;
strncpy_s(str, 128, vectorArrayCombine(vStr), 126);
file = CreateFile(
saveFileName, //파일이름
GENERIC_WRITE, //쓰기 권환
FALSE, //공유 모드
NULL, //상속자에게 값을 넘길거 있는가
CREATE_ALWAYS, //항상 새로운파일 만든다.
FILE_ATTRIBUTE_NORMAL, //모든 속성(읽기 전용, 숨긴, 운영제제 전용파일)을 지정하지 않는다.
NULL //생성된 템플릿 파일의 유효한 핸들에 속성을 넣는 BOOL값
);
//strlen 등 문자열 길이 함수를 쓰면 먹통된다
WriteFile(
file, //대상 파일으 핸들
str, //데이터가 들어있는 버퍼
128, //쓰고자 하는 바이트 수
&write, //쓰고자 하는 바이트 수를 리턴하기 위한 DWORD변수의 포인터
NULL); //비동기입출력을 할 때 사용 BOOL값
CloseHandle(file);
/*
열려진 핸들을 닫는다.(버퍼, 프로세스, 파일)
WIN32에서 핸들로 표현되는 모든 것을 말한다.
그러나 아이콘 , 팬, 브러쉬 GDI오브젝튼 닫을 수 없다.
*/
}
char * txtData::vectorArrayCombine(vector<string> vArray)
{
char str[128];
ZeroMemory(str, sizeof(str));
//X Axis, Y Axis, CurrentHP, MaxHP
//100, 100, 100, 100
for (int i = 0; i < vArray.size(); i++)
{
strncat_s(str, 128, vArray[i].c_str(), 126);
if (i + 1 < vArray.size()) strcat(str, ",");
}
return str;
}
vector<string> txtData::txtLoad(const char * loadFileName)
{
HANDLE file;
char str[128];
DWORD read;
file = CreateFile(
loadFileName,
GENERIC_READ, //쓰기
FALSE,
NULL,
OPEN_EXISTING, //파일이 존재할 경우에만 파일을 연다.
FILE_ATTRIBUTE_NORMAL,
NULL
);
ReadFile(file, str, 128, &read, NULL);
CloseHandle(file);
return charArraySeparation(str);
}
vector<string> txtData::charArraySeparation(char charArray[])
{
vector<string> vArray;
char* temp;
const char* separator = ",";
char* token;
token = strtok(charArray, separator);
vArray.push_back(token);
while (NULL != (token = strtok(NULL, separator)))
{
vArray.push_back(token);
}
return vArray;
}
|
// -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
// opera:config strings
#ifdef OPERACONFIG_URL
DI_IDHELP
SI_SAVE_BUTTON_TEXT
S_CONFIG_DEFAULT
S_CONFIG_SHOW_ALL
S_DOC_NEED_JS
SI_IDFORM_RESET
S_NO_MATCHES_FOUND
S_QUICK_FIND
S_SETTINGS_SAVED
S_NO_SETTINGS_SAVED
S_CONFIG_RESTART
S_CONFIG_TITLE
#endif
#ifndef USE_MINIMAL_OPERA_CONFIG
S_CONFIG_NO_INFORMATION
S_CONFIG_LOADING
#endif // !USE_MINIMAL_OPERA_CONFIG
|
#include <sys/ipc.h>
#include <semaphore.h>
#include <sys/sem.h>
#include <fcntl.h>
#include <iostream>
#define RWRR (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
using namespace std;
sem_t call_sem_init( );
sem_t call_sem_open( );
int main() {
sem_t sem = call_sem_open();
cout << "sem=" << (void *) &sem << endl;
return( 0 );
}
// generate a
key_t getIpcKey() {
return ftok( "/home/tomabot/local/ipc/ipc.key", 'a' );
}
// create a named POSIX Semaphore
sem_t call_sem_open( ) {
sem_t *psem = (sem_t *) 0;
psem = sem_open(
"/tmp", // the name of the semaphore
O_CREAT, //|O_EXCL, // create a new named semaphore if it doesn't exist yet
// if it already exists, return an error
RWRR, // owner rw, group r, other r
1 // initial value of the semaphore
);
cout << "sem_t=" << (void *) psem << endl;
return *psem;
}
// create an unnamed POSIX Semaphore to be used between related processes
sem_t call_sem_init( ) {
sem_t sem;
int rtnValue = sem_init(
&sem, // address of semabore variable
1, // using semaphore with multiple processes, use nonzero
1 // initial value of the semaphore
);
cout << "sem_init() returned " << rtnValue << endl;
return sem;
}
|
/*
Author: Matt Pinner @mpinenr
Intent :
Smooth Sound and Motion Reactivity for Wearable LEDs
Wearing LEDs can be dumb. mostly they're not respectful of the surrounding environment.
This code uses LOTS of data to infer the energy of the wearer and environment to turn down and slow the reactivity of LEDs.
Libraries were used from the following sources:
- I2Cdev for MPU9150 originally by Jeff Rowberg <jeff@rowberg.net>
at https://github.com/jrowberg/i2cdevlib (modified by Aaron Weiss <aaron@sparkfun.com>)
- Adafruit's neopixel library : https://github.com/adafruit/Adafruit_NeoPixel
- Msgeq7 for determining frequency bands and accelerometer readings : https://github.com/justinb26/MSGEQ7-library
- EWMA for smoothing : https://github.com/CBMalloch/Arduino/tree/master/libraries/EWMA
*/
#undef int()
#include <stdio.h>
#include <math.h>
#include <EWMA.h>
// number of sound frequency bands supported
#define BANDS 7
// we'll be tracking an Exponentially Weighted Moving Average (EWMA) for each band of sound
EWMA myEwmaBand[BANDS];
// we'll also track an EWMA for our accelleration and gryo
EWMA myEwmaAccel, myEwmaGyro;
// defines how many measurements the ewma for each sensor is calculated over.
// more measures will increase the smoothing.
//fewer will make the impact of the most recent measurement greater and therefore more immediate
#define EWMA_SOUND_BUCKETS 10 // 10 - very reactive
#define EWMA_ACCEL_BUCKETS 400 // 400 - very slow to react
#define EWMA_GRYO_BUCKETS 100 // 100 - slow affect
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#include "Wire.h"
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "MPU6050.h"
#include <MSGEQ7.h>
#include <Adafruit_NeoPixel.h>
#define LED_PIN 13
#define STRIP_PIN 2
#define NECK_PIN 2
// define MSGEQ7 : Output, Strobe, and Reset Pins
#define MSGEQ7_OUTPUT_PIN A3
#define MSGEQ7_STROBE_PIN 22
#define MSGEQ7_RESET_PIN 23
// define geometry of the jacket
#define SPINE_LEDS 24
#define NECK_LEDS 8
// create objects for our leds
Adafruit_NeoPixel strip = Adafruit_NeoPixel(SPINE_LEDS, STRIP_PIN, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel neck = Adafruit_NeoPixel(NECK_LEDS, NECK_PIN, NEO_GRB + NEO_KHZ800);
// create an object for our sound sensor's hardware FFT
MSGEQ7 msgeq7;
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 accelgyro;
// lots of data from our motion sensor can be stored here for caching and globe access
// stores raw accel/gyro/mag measurements from device
int16_t ax, ay, az;
int16_t gx, gy, gz;
int16_t mx, my, mz;
// stores previous and max accelleration values for delta calculation and self tuning
int16_t lastax, lastay, lastaz;
int16_t ewmaAccelX, ewmaAccelY, ewmaAccelZ;
// stores previous and max gyro values for delta calculation and self tuning
int16_t lastgx, lastgy, lastgz;
int16_t ewmaGyroX, ewmaGyroY, ewmaGyroZ;
// stores previous and max sound values for delta calculation and self tuning
int16_t lastBand[BANDS];
int16_t emBand[BANDS];
bool blinkState = false;
void setup() {
delay(100);
strip.begin();
strip.show(); // Initialize all pixels to 'off'
neck.begin();
neck.show(); // Initialize all pixels to 'off'
// Initialize Output, Strobe, and Reset Pins
msgeq7.init(MSGEQ7_OUTPUT_PIN, MSGEQ7_STROBE_PIN, MSGEQ7_RESET_PIN);
// join I2C bus (I2Cdev library doesn't do this automatically)
Wire.begin();
// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);
// initialize device
Serial.println("Initializing I2C devices...");
accelgyro.initialize();
// verify connection
Serial.println("Testing device connections...");
Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
// configure Arduino LED for
pinMode(LED_PIN, OUTPUT);
// initialize our sensor averages
myEwmaAccel.init(myEwmaAccel.periods(EWMA_ACCEL_BUCKETS));
myEwmaGyro.init(myEwmaGyro.periods(EWMA_GRYO_BUCKETS));
for (int i = 0; i < BANDS; i++) {
myEwmaBand[i].init(myEwmaBand[i].periods(EWMA_SOUND_BUCKETS));
}
return; // done with setup
}
// this happens as fast as posssible over and over
// NO DELAYS
//
// standard senor loop:
// 0. read sensors
// 1. derive meaning
// 2. update outputs
void loop() {
// read sound bands
// - results are stored for globe access)
readEq();
// read motion sensors
// - results are stored for globe access)
readMotion();
// calculate a brightness from our Averages and scale to 1-255 for led display use
// our Y direction is the most impactfull as it is alligned with the human body up and down
// the Y accelleration implies up and down motion -> walking?dancing
// the Y gryo is a rotation (or more accurately a change in rotation) as in turning around or rotation at the hips or shoulders
int brightness = map (ewmaAccelY + ewmaGyroY, 0, 200000, 1, 255);
// update our leds
// our color/birghtness math is kind of sad here
// i choose very specific/simple colors for each band and to always match each other.
for (int i = 0; i < SPINE_LEDS; i++ ) {
strip.setPixelColor(i, 0, 0, 0);
neck.setPixelColor(i, 0, 0, 0);
// we only care about the 4 lower bands
// the highs are always full of noise.
// the mid are great for human voice detection
// the lows imply some music
// purple for a middle band
// starts could go to the top
if (emBand[3]/40 > (i-15)) {
strip.setPixelColor(SPINE_LEDS-i, brightness/2, 0, brightness);
neck.setPixelColor(8-i/3, brightness/2, 0, brightness);
}
// blue for a lower middle band
// starts nearish the bottom
if (emBand[2]/50 > (i-12)) {
strip.setPixelColor(SPINE_LEDS-i, 0, 0, brightness);
neck.setPixelColor(8-i/3, 0, 0, brightness);
}
// pink for the lower band
// starts near the bottom
if (emBand[1]/60 > (i-6)) {
strip.setPixelColor(SPINE_LEDS-i, brightness, 0, brightness);
neck.setPixelColor(8-i/3, brightness, 0, brightness);
}
// tourquise for the lowest band
// starts from the bottom
if (emBand[0]/70 > i) {
strip.setPixelColor(SPINE_LEDS-i, 0, brightness, brightness);
neck.setPixelColor(8-i/3, 0, brightness, brightness);
}
// end for each led loop
}
// push new led colors to the hardware
strip.show();
neck.show();
// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
return; // done with main loop (do it again)
}
// reads sound data
// stores results in global variables
// updates EWMAs
void readEq() {
msgeq7.poll(); // Update values from MSGEQ7
showEqValues(); // Print the current EQ values to Serial
for (int i = 0; i < BANDS; i++) {
// record the difference in readings from last reading, so lots of zeros
emBand[i] = msgeq7.getValue(i);
myEwmaBand[i].record(abs(lastBand[i] - emBand[i]));
lastBand[i] = emBand[i];
}
return;
}
// reads motion data
// stores results in global variables
// updates EWMAs
void readMotion() {
// read raw accel/gyro measurements from device
accelgyro.getMotion9(&ax, &ay, &az, &gx, &gy, &gz, &mx, &my, &mz);
ewmaAccelY = myEwmaAccel.record(abs(lastay - ay));
lastay = abs(ay);
ewmaGyroY = myEwmaGyro.record(abs(lastgy - gy));
lastgy = abs(gy);
showMotionValues();
return;
}
// prints sound bands to serial out
// for debugging
void showEqValues()
{
Serial.print("Current values - ");
Serial.print("63HZ: ");
Serial.print(msgeq7.getValue(0));
Serial.print(" 160HZ: ");
Serial.print(msgeq7.getValue(1));
Serial.print(" 400HZ: ");
Serial.print(msgeq7.getValue(2));
Serial.print(" 1000HZ: ");
Serial.print(msgeq7.getValue(3));
Serial.print(" 4500HZ: ");
Serial.print(msgeq7.getValue(4));
Serial.print(" 6250HZ: ");
Serial.print(msgeq7.getValue(5));
Serial.print(" 16000HZ: ");
Serial.print(msgeq7.getValue(6));
Serial.println();
return;
}
// prints motion data to serial out
// for debugging
void showMotionValues() {
// display tab-separated raw accel/gyro/mag values
Serial.print("a/g/m:\t");
Serial.print(ax);
Serial.print("\t");
Serial.print(ay);
Serial.print("\t");
Serial.print(az);
Serial.print("\t");
Serial.print(gx);
Serial.print("\t");
Serial.print(gy);
Serial.print("\t");
Serial.print(gz);
Serial.print("\t");
Serial.print(mx);
Serial.print("\t");
Serial.print(my);
Serial.print("\t");
Serial.print(mz);
// display calculated ewma values
Serial.print("\tew: ");
Serial.print(ewmaAccelY);
Serial.print("\t");
Serial.print(ewmaGyroY);
Serial.print("\t");
Serial.println("\t");
return;
}
|
// Created on: 2008-05-26
// Created by: Ekaterina SMIRNOVA
// Copyright (c) 2008-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef BRepMesh_CircleInspector_HeaderFile
#define BRepMesh_CircleInspector_HeaderFile
#include <IMeshData_Types.hxx>
#include <BRepMesh_Circle.hxx>
#include <gp_XY.hxx>
#include <NCollection_CellFilter.hxx>
//! Auxiliary class to find circles shot by the given point.
class BRepMesh_CircleInspector : public NCollection_CellFilter_InspectorXY
{
public:
typedef Standard_Integer Target;
//! Constructor.
//! @param theTolerance tolerance to be used for identification of shot circles.
//! @param theReservedSize size to be reserved for vector of circles.
//! @param theAllocator memory allocator to be used by internal collections.
BRepMesh_CircleInspector(
const Standard_Real theTolerance,
const Standard_Integer theReservedSize,
const Handle(NCollection_IncAllocator)& theAllocator)
: mySqTolerance(theTolerance*theTolerance),
myResIndices(theAllocator),
myCircles(theReservedSize, theAllocator)
{
}
//! Adds the circle to vector of circles at the given position.
//! @param theIndex position of circle in the vector.
//! @param theCircle circle to be added.
void Bind(const Standard_Integer theIndex,
const BRepMesh_Circle& theCircle)
{
myCircles.SetValue(theIndex, theCircle);
}
//! Resutns vector of registered circles.
const IMeshData::VectorOfCircle& Circles() const
{
return myCircles;
}
//! Returns circle with the given index.
//! @param theIndex index of circle.
//! @return circle with the given index.
BRepMesh_Circle& Circle(const Standard_Integer theIndex)
{
return myCircles(theIndex);
}
//! Set reference point to be checked.
//! @param thePoint bullet point.
void SetPoint(const gp_XY& thePoint)
{
myResIndices.Clear();
myPoint = thePoint;
}
//! Returns list of circles shot by the reference point.
IMeshData::ListOfInteger& GetShotCircles()
{
return myResIndices;
}
//! Performs inspection of a circle with the given index.
//! @param theTargetIndex index of a circle to be checked.
//! @return status of the check.
NCollection_CellFilter_Action Inspect(
const Standard_Integer theTargetIndex)
{
BRepMesh_Circle& aCircle = myCircles(theTargetIndex);
const Standard_Real& aRadius = aCircle.Radius();
if (aRadius < 0.)
return CellFilter_Purge;
gp_XY& aLoc = const_cast<gp_XY&>(aCircle.Location());
const Standard_Real aDX = myPoint.ChangeCoord(1) - aLoc.ChangeCoord(1);
const Standard_Real aDY = myPoint.ChangeCoord(2) - aLoc.ChangeCoord(2);
//This check is wrong. It is better to use
//
// const Standard_Real aR = aRadius + aToler;
// if ((aDX * aDX + aDY * aDY) <= aR * aR)
// {
// ...
// }
//where aToler = sqrt(mySqTolerance). Taking into account the fact
//that the input parameter of the class (see constructor) is linear
//(not quadratic) tolerance there is no point in square root computation.
//Simply, we do not need to compute square of the input tolerance and to
//assign it to mySqTolerance. The input linear tolerance is needed to be used.
//However, this change leads to hangs the test case "perf mesh bug27119".
//So, this correction is better to be implemented in the future.
if ((aDX * aDX + aDY * aDY) - (aRadius * aRadius) <= mySqTolerance)
myResIndices.Append(theTargetIndex);
return CellFilter_Keep;
}
//! Checks indices for equlity.
static Standard_Boolean IsEqual(
const Standard_Integer theIndex,
const Standard_Integer theTargetIndex)
{
return (theIndex == theTargetIndex);
}
private:
Standard_Real mySqTolerance;
IMeshData::ListOfInteger myResIndices;
IMeshData::VectorOfCircle myCircles;
gp_XY myPoint;
};
#endif
|
#include <iostream>
#include "FDHeatMethod.hpp"
template<typename X>
FDHeatMethod<X>::FDHeatMethod(Option<X> *__option, X _S_min, X _S_max, int _N, int _M) : FDMethod<X>(__option, _N, _M) {
if (_S_min <= 0) {
std::cout << " S_min musi byc większe niż zero ";
}
this->x_min = transform_to_X(_S_min);
this->x_max = transform_to_X(_S_max);
X t0(0.0);
this->dtau = this->transform_to_tau(t0) / this->N;
this->dx = (this->x_max - this->x_min) / this->M;
this->alpha = this->dtau / (this->dx * this->dx);
X k = this->option->r / (0.5 * pow(this->option->sigma, 2));
this->a = -0.5 * (k - 1.);
this->b = -0.25 * pow(k + 1., 2);
// this->a = (this->option->r - 0.5 * pow(this->option->sigma, 2)) / pow(this->option->sigma, 2);
// this->b = (2 * this->option->r) / pow(this->option->sigma, 2) + pow(this->a, 2);
}
template<typename X>
X FDHeatMethod<X>::transform_to_X(const X &S) {
return log(S / this->option->E);
}
template<typename X>
X FDHeatMethod<X>::transform_to_tau(const X &t) {
return 0.5 * pow(this->option->sigma, 2) * (this->option->T - t);
}
template<typename X>
X FDHeatMethod<X>::transform_to_S(const X &x) {
return this->option->E * exp(x);
}
template<typename X>
X FDHeatMethod<X>::transform_to_t(const X &tau) {
// return this->option->T - tau / (0.5 * pow(this->option->sigma, 2));
return this->option->T - 2 * tau / pow(this->option->sigma, 2);
}
template<typename X>
X FDHeatMethod<X>::t_val(const int &i) {
return this->dtau * i;
}
template<typename X>
X FDHeatMethod<X>::s_val(const int &j) {
return this->x_min + this->dx * j;
}
template<typename X>
X FDHeatMethod<X>::payoff(const int &i_tau, const int &j_x) {
X tau = this->t_val(i_tau);
X x = this->s_val(j_x);
// X v = this->option->payoff(this->transform_to_S(x));
// return (v / this->option->E) * exp(this->a * x + this->b * tau);
return fmax(exp(0.5 * (this->k - 1) * x) - exp(0.5 * (this->k + 1) * x), 0);
}
template<typename X>
X FDHeatMethod<X>::upper_bd_cond(const int &i_tau, const int &j_x) {
// X x = this->s_val(j_x);
// X tau = this->t_val(i_tau);
// X v = this->option->upper_bd_cond(this->transform_to_t(tau), this->transform_to_S(x));
// return (v / this->option->E) * exp(this->a * x + this->b * tau);
return 0.0;
}
template<typename X>
X FDHeatMethod<X>::lower_bd_cond(const int &i_tau, const int &j_x) {
X x = this->s_val(j_x);
X tau = this->t_val(i_tau);
// X v = this->option->lower_bd_cond(this->transform_to_t(tau), this->transform_to_S(x));
// return (v / this->option->E) * exp(this->a * x + this->b * tau);
return fmax(exp(0.5 * (k - 1) * x) - exp(0.5 * (k + 1) * x), 0);
}
template<typename X>
X FDHeatMethod<X>::average_approximation() {
X x = this->transform_to_X(this->option->S0);
X t0(0.0);
X tau = this->transform_to_tau(t0);
int j = static_cast<int>((x - this->x_min) / this->dx);
X alpha1(0.0);
X alpha0(1.0);
X w1 = (x - this->s_val(j)) / this->dx;
X w0 = 1.0 - w1;
X u = alpha1 * w1 * (*this->vOld)[j + 1] + alpha1 * w0 * (*this->vOld)[j]
+ alpha0 * w1 * (*this->vNew)[j + 1] + alpha0 * w0 * (*this->vNew)[j];
return (u * this->option->E) / (exp(this->a * x + this->b * tau));
}
|
#include <atomic>
#include <condition_variable>
#include <deque>
#include <map>
#include <mutex>
#include <unordered_set>
#include <stdlib.h>
#include "chunk_registry.hpp"
#include "chunk_allocator.hpp"
struct freelist : public std::vector<void*>
{
};
class alloc {
public:
alloc (void** stack_bottom, bool free_memory = true);
~alloc ();
void*
allocate (std::size_t size);
void
free (void* ptr);
private:
void
mark(void *ptr);
void
mark_stack();
void
sweep();
void
collect();
private:
void **stack_bottom;
private:
void*
allocate_from_list (std::size_t size, freelist &list);
std::map<std::size_t, freelist> freelists;
private:
const std::size_t list_objects_max_size;
private:
void
add_to_freelist (std::size_t size, freelist &list);
chunk*
chunk_allocate (std::size_t size);
chunk_registry ch_reg;
chunk_allocator ch_alloc;
std::unordered_set <chunk*> allocated_chunks;
private:
struct barrier
{
barrier():
remaining_threads (0),
gc_required (false)
{
}
bool
trigger()
{
std::unique_lock<std::mutex> lock (mutex);
if (gc_required)
{
join_inner(lock);
return false;
}
else
{
gc_required = true;
remaining_threads--;
cv.wait (lock, [&]() { return remaining_threads == 0; });
return true;
}
}
void
join_if_required()
{
if (gc_required)
{
std::unique_lock<std::mutex> lock (mutex);
join_inner (lock);
}
}
void
finish()
{
std::unique_lock<std::mutex> lock (mutex);
cv.notify_all();
remaining_threads++;
gc_required = false;
}
void add_thread ()
{
std::unique_lock<std::mutex> lock (mutex);
if (gc_required)
{
cv.wait (lock, [&](){ return !gc_required; });
}
remaining_threads++;
}
void remove_thread ()
{
std::unique_lock<std::mutex> lock (mutex);
remaining_threads--;
cv.notify_all();
}
int remaining_threads;
std::atomic<bool> gc_required;
private:
void
join_inner (std::unique_lock <std::mutex> &lock)
{
remaining_threads--;
cv.notify_all ();
cv.wait (lock, [&](){ return !gc_required; });
remaining_threads++;
}
std::mutex mutex;
std::condition_variable cv;
};
public:
barrier gc_barrier;
private:
bool free_memory;
};
|
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
class CMainFrame :
public CFrameWindowImpl<CMainFrame>,
public CUpdateUI<CMainFrame>,
public CMessageFilter,
public CIdleHandler,
public CAppWindow<CMainFrame>
{
public:
DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME)
virtual BOOL PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_KEYDOWN )
{
UINT nRepCnt = pMsg->lParam & 0xFFFF;
UINT nFlags = ((pMsg->lParam & 0xFFFF0000) >> 16);
switch(pMsg->wParam)
{
case VK_RETURN :
if(m_view.m_controller->OnReturnKey(nRepCnt, nFlags))
return TRUE;
break;
case VK_UP :
if(m_view.m_controller->OnUpKey(nRepCnt, nFlags))
return TRUE;
break;
case VK_DOWN :
if(m_view.m_controller->OnDownKey(nRepCnt, nFlags))
return TRUE;
break;
case VK_LEFT :
if(m_view.m_controller->OnLeftKey(nRepCnt, nFlags))
return TRUE;
break;
case VK_RIGHT :
if(m_view.m_controller->OnRightKey(nRepCnt, nFlags))
return TRUE;
break;
}
}
if(CFrameWindowImpl<CMainFrame>::PreTranslateMessage(pMsg))
return TRUE;
return m_view.PreTranslateMessage(pMsg);
}
virtual BOOL OnIdle()
{
return FALSE;
}
BEGIN_UPDATE_UI_MAP(CMainFrame)
END_UPDATE_UI_MAP()
BEGIN_MSG_MAP(CMainFrame)
MSG_WM_CREATE ( OnCreate )
// MSG_WM_DESTROY ( OnDestroy )
MSG_WM_KEYDOWN ( OnKeyDown )
MSG_WM_COPYDATA ( m_view.m_controller->OnCopyData )
// MSG_WM_ACTIVATE ( m_view.m_controller->OnActivate )
COMMAND_ID_HANDLER(ID_ACTION, m_view.m_controller->OnAction)
COMMAND_ID_HANDLER(ID_APP_EXIT, OnFileExit)
COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
COMMAND_ID_HANDLER(ID_BACK_LAST_APP,m_view.m_controller->OnBackLastApplication)
COMMAND_ID_HANDLER(ID_SAVE_CURRENT_CONTENT,
m_view.m_controller->OnSaveContentHtml)
COMMAND_ID_HANDLER(ID_MENU_SAVECONTENTTABXML,
m_view.m_controller->OnSaveContentXml)
CHAIN_MSG_MAP(CAppWindow<CMainFrame>)
CHAIN_MSG_MAP(CUpdateUI<CMainFrame>)
CHAIN_MSG_MAP(CFrameWindowImpl<CMainFrame>)
END_MSG_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
int OnCreate(LPCREATESTRUCT lpCreateStruct)
{
m_setting.Load();
m_pickWordKey = m_setting.LoadIntValue("MYSK_PICK_BUTTON_APP_KEY", 0);
if(0 != m_pickWordKey)
{
m_pickWordKey += 0xC0; // VK_APP1 = 0xC1;
SHSetAppKeyWndAssoc(m_pickWordKey, *this);
}
// initial controller
m_view.setController(m_controllerFactory.create("Cald2"));
m_view.m_controller->Init(this);
CreateSimpleCEMenuBar();
m_hWndClient = m_view.Create(m_hWnd);
m_wndPick.MyCreate(m_setting);
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
m_mainMenu = (HMENU)SendMessage(m_hWndCECommandBar, SHCMBM_GETSUBMENU, (WPARAM)0, (LPARAM)ID_MENU);
return 0;
}
LRESULT OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PostMessage(WM_CLOSE);
return 0;
}
LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CAboutDlg dlg;
dlg.DoModal();
return 0;
}
bool AppHibernate(bool bHibernate)
{
SK_TRACE(SK_LOG_DEBUG, "AppHibernate(%d)", bHibernate);
return false;
}
bool AppNewInstance(LPCTSTR lpstrCmdLine)
{
SK_TRACE(SK_LOG_DEBUG, _T("AppNewInstance(%s)"), lpstrCmdLine);
return false;
}
void AppSave()
{
SK_TRACE(SK_LOG_DEBUG, "AppSave()");
}
/*
void OnDestroy()
{
m_view.m_controller->Fini();
SetMsgHandled(TRUE);
// first remove all pages for avoiding exception.
// m_wndContentTabView.RemoveAllPages();
// ::PostQuitMessage(0);
}
LRESULT OnActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
UINT nState = (UINT)LOWORD(wParam);
BOOL bMinimized = (BOOL)HIWORD(wParam);
HWND wndOther = (HWND)lParam;
switch(nState)
{
case WA_ACTIVE :
case WA_CLICKACTIVE :
installAppKey();
break;
case WA_INACTIVE :
uninstallAppKey();
break;
}
return CAppWindow<CMainFrame>::OnActivate(uMsg, wParam, lParam, bHandled);
}
*/
void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if(0 != m_pickWordKey && nChar == m_pickWordKey)
{
m_wndPick.DoPickWord();
return;
}
}
/*
void installAppKey()
{
SHSetAppKeyWndAssoc(VK_APP1, *this);
SHSetAppKeyWndAssoc(VK_APP2, *this);
SHSetAppKeyWndAssoc(VK_APP3, *this);
SHSetAppKeyWndAssoc(VK_APP4, *this);
}
void uninstallAppKey()
{
SHSetAppKeyWndAssoc(VK_APP1, NULL);
SHSetAppKeyWndAssoc(VK_APP2, NULL);
SHSetAppKeyWndAssoc(VK_APP3, NULL);
SHSetAppKeyWndAssoc(VK_APP4, NULL);
}
*/
Setting m_setting;
UINT m_pickWordKey;
HMENU m_mainMenu;
CSKMobileView m_view;
CPickButton m_wndPick;
ControllerFactory m_controllerFactory;
};
|
http://www.geeksforgeeks.org/shuffle-a-given-array/
|
#pragma once
template <typename T>
void containerSwap(T &a, T &b)
{
T tmp = a;
a = b;
b = tmp;
}
template <typename C>
void SelectionSort(C &container, long containerSize)
{
if (containerSize == 0)
return;
for (int i = 0; i < containerSize; i++)
{
long position = i;
long minimumPos = i;
for (int j = position; j < containerSize; j++)
{
if (container[minimumPos] == container[j] || container[minimumPos] < container[j])
continue;
else
minimumPos = j;
}
if (minimumPos != position)
containerSwap(container[position], container[minimumPos]);
}
}
|
#include "source.h"
#include <math.h>
double heatSource(double x, double y) {
double dx = x - 0.9;
double dy = y - 0.9;
return 2000.0 * exp(-20.0 * (dx * dx + dy * dy));
}
|
#ifndef SERIAL_H
#define SERIAL_H
#include "port.h"
#include <QMutex>
#include <QObject>
class Serial : public QObject, public IPort
{
Q_OBJECT
public:
// Serial();
virtual ~Serial();
public:
static const int DATABITS_FIVE = 5;
static const int DATABITS_SIX = 6;
static const int DATABITS_SEVEN = 7;
static const int DATABITS_EIGHT = 8;
static const int PARITY_NO = 0;
static const int PARITY_ODD = 1;
static const int PARITY_EVENT = 2;
static const int PARITY_MARK = 3;
static const int PARITY_SPACE = 4;
static const int STOPBITS_ONE = 1;
static const int STOPBITS_TWO = 2;
static const int BAUD_9600 = 9600;
static const int BAUD_115200 = 115200;
static const int FLUSH_RX = 1;
static const int FLUSH_TX = 2;
static const int BUFFER_LENGTH = 1024;
public:
int openPort(void);
int closePort(void);
int readData(char* rxBuffer, int bytes);
int writeData(char* txBuffer, int bytes);
int flush(int flag);
//++++++++++++++++++++++++
void setSpecifiedBaudrate(int baudrate);
public slots:
virtual void run()=0;
protected:
virtual void initSerialPort(int dataBits, int parity, int stopBits, int baud)=0;
void initFD();
void setDataBits(int dataBits);
void setParity(int parity);
void setStopBits(int stopBits);
void setBaudrate(int baudrate);
void setDevName(char* name);
void printBuf(char *buf, int len);
private:
int termiosInit(struct termios *tios); // int parity, int data_bits, int stop_bits);
private:
int fd;
int dataBits;
int parity;
int stopBits;
int baudrate;
char* devName; //[30] = {'\0'}; //char devName[30]={'\0'}
QMutex rxMutex;
QMutex txMutex;
};
#endif // SERIAL_H
#if 0
#ifndef SERIAL_H
#define SERIAL_H
#include <QObject>
#include <QMutex>
#include <QLabel>
#include <termios.h>
#include <unistd.h>
/*
* ------------------------------good
*
#define ELECTRIC_TABLE_PORTNUMBER 6//1 // com1: ttl->rs485
#define ELECTRIC_TABLE_PORTFILENAME ("/dev/ttySAC6")
#define GPS_PORTNUMBER 3 // com3: rs232
#define GPS_PORTFILENAME ("/dev/ttySAC3")
#define INCLINOMETER_PORTNUMBER 1//6 // com6: ttl
#define INCLINOMETER_PORTFILENAME ("/dev/ttySAC1")
#define SERIAL4_BCK_PORTNUMBER 4 // com4
#define SERIAL7_BCK_PORTNUMBER 7 // com7
*/
// com1: 485, com3: rs232, com4: rs232, com6: ttl
#define TESTPORT_PORTNUMBER 6 // com6: ttl, 9600, used for test INCLINOMETER port
#define TESTPORT_PORTFILENAME ("/dev/ttySAC6")
//#define GPS_PORTNUMBER 3 // com3: rs232
//#define GPS_PORTFILENAME ("/dev/ttySAC3")
#define GPS_PORTNUMBER 3 // com3: rs232
#define GPS_PORTFILENAME ("/dev/ttySAC3")
#if 0
#define INCLINOMETER_PORTNUMBER 1 // com1: 485
#define INCLINOMETER_PORTFILENAME ("/dev/ttySAC1")
#define ELECTRIC_TABLE_PORTNUMBER 4 // com1: 485 // com4: 232
#define ELECTRIC_TABLE_PORTFILENAME ("/dev/ttySAC4")
#else
#define INCLINOMETER_PORTNUMBER 4 // com1: 485
#define INCLINOMETER_PORTFILENAME ("/dev/ttySAC4")
#define ELECTRIC_TABLE_PORTNUMBER 1 // com1: 485 // com4: 232
#define ELECTRIC_TABLE_PORTFILENAME ("/dev/ttySAC1")
#endif
#define SERIAL7_BCK_PORTNUMBER 7 // com7:ttl
#define BUFFER_LENGTH 1024
#define DEFAULT_BAUDRATE 115200 // gps
#define INCLINOMETER_BAUDRATE 9600 // 485
#define TESTPORT_BAUDRATE 9600 // 485
#define ELECTRICTABLE_BAUDRATE 115200 //57600 // 9600
typedef struct serial_info
{
int portNumber; // 当前串口号
char sendBuf[BUFFER_LENGTH];
char recvBuf[BUFFER_LENGTH];
int sendLength; // 实际发送字节数
int recvLength; // 实际接收字节数
bool sendDataIsReady; // 发送数据准备好,可以发数据
bool recvReady; // 接收数据ok
QMutex sendBufMutex; // 发送数据的锁
QMutex recvBufMutex; // 接收数据的锁
bool stop; // 退出标志
}serial_info_t;
class Serial : public QObject
{
Q_OBJECT
public:
Serial();
Serial(int number, int baud);
~Serial();
public:
void set_portNumber(int number);
int serial_open(int parity,int data_bits,int stop_bits); //,int timeout);
int serial_close(void);
int serial_flush(int flag);
int serial_write(void);
int serial_read(void);
int serial_poll(int timeout);
signals:
public slots:
//void doOperation(void);
private:
char* get_serial_dev_name(void);
int termios_init(struct termios *tios, int parity,int data_bits,int stop_bits);
void serial_print_buf(char *buf, int len);
protected:
int fd;
int baudrate;
serial_info_t *si;
private:
struct termios old_tios;
};
void serial_exit_enable(int number);
void fill_serialSendBuf(int number, char *buf, int length);
int get_serialReceivedData(int number, char *buf);
void display_serialReceivedData(int number, QLabel *label);
void get_serialNBytes(int number, char *buf, int length);
int get_InclinometersData(float *x, float *y);
#endif // SERIAL_H
#endif
|
#include <iostream>
#include <string>
#include <vector>
#include "../rapidxml/rapidxml.hpp"
#include "../rapidxml/rapidxml_utils.hpp"
#include "../rapidxml/rapidxml_print.hpp"
#include "Container.h"
#include "gameObjects.h"
#include "Creature.h"
#include "Trigger.h"
#include "Item.h"
#include "Room.h"
#include "utils.h"
#include <cstring>
using namespace std;
using namespace rapidxml;
int main(){
// Initialize and parse xml file
rapidxml::file<>xmlFile("../map1.xml");
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
// Initialize root xml node
xml_node<> *map = doc.first_node();
// Initialize Object Vectors
vector<Item> gameItems;
int item_count = 0;
vector<Container> gameContainers;
int container_count = 0;
vector<Creature> gameCreatures;
int creature_count = 0;
// Create all game objects
xml_node<> *mapElement = NULL;
for(mapElement = map->first_node(); mapElement; mapElement = mapElement->next_sibling()){
//cout << mapElement->name() << endl;
if(strcmp(mapElement->name(),"item") == 0){
Item newItem = Item(mapElement);
gameItems.push_back(newItem);
//cout << "hi" << endl;
}
if(strcmp(mapElement->name(),"creature") == 0){
Creature newCreature = Creature(mapElement);
gameCreatures.push_back(newCreature);
}
}
for(mapElement = map->first_node(); mapElement; mapElement = mapElement->next_sibling()){
if(strcmp(mapElement->name(),"container") == 0){
Container newContainer = Container(mapElement, gameItems);
gameContainers.push_back(newContainer);
}
}
// Initialize Room Vector
vector<Room> gameRooms;
int room_count = 0;
// Create all game rooms
for(mapElement = map->first_node(); mapElement; mapElement = mapElement->next_sibling()){
if(strcmp(mapElement->name(),"room") == 0){
Room newRoom = Room(mapElement, gameItems, gameCreatures, gameContainers);
gameRooms.push_back(newRoom);
}
}
// Initialize Player Inventory
vector<Item> Inventory;
// Initialize Game Object Iterators
vector<Room>::iterator roomIt = gameRooms.begin();
vector<Item>::iterator itemIt = gameItems.begin();
vector<Container>::iterator ContainerIt = gameContainers.begin();
vector<Creature>::iterator CreatureIt = gameCreatures.begin();
// Initialize Game Loop
string gameStatus = "";
// Set initial room to be the first room
string roomName = gameRooms[0].getName();
int roomFind = 0;
int roomCount = 0;
while(roomName != "Game Over"){
roomCount = 0;
for(roomIt = gameRooms.begin(); roomIt != gameRooms.end(); roomIt++){
if((roomIt)->getName() == roomName){
roomFind = roomCount;
}
roomCount++;
}
roomName = loadRoom(&(gameRooms[roomFind]), &gameItems, &gameContainers, &gameCreatures, &Inventory);
}
}
|
// Originally Written by Luke Simmons and Megan Sword
// Edited by Alfred Ledgin
// 11/4/2015
// CS 303
// Project 2
#pragma once
#include <string>
#include <stack>
#include "Operator.h"
using namespace std;
class Evaluator {
public:
Evaluator(string line);
Evaluator();
const double evaluate(string equation);
const double evaluate() { return evaluate(eqString); }
private:
string eqString;
};
|
//
// Created by micky on 15. 5. 20.
//
#include <iostream>
#include "JudgeServer.h"
JudgeServer *JudgeServer::instance = NULL;
void JudgeServer::createNewConnection()
{
InetSocket *clnt = nullptr;
clnt = _serv.accept();
if(_conn.size() < (size_t)clnt->getFileDescriptor()) {
_conn.resize(clnt->getFileDescriptor()+1);
}
_conn[clnt->getFileDescriptor()] = clnt;
_pm.addEvent(clnt->getFileDescriptor(), EPOLLIN);
InformMessage("new connection from %s", clnt->getIpAddress().c_str());
}
void JudgeServer::removeConnection(InetSocket *sock)
{
InformMessage("disconnect with %s", sock->getIpAddress().c_str());
sock->close();
_pm.removeEvent(sock->getFileDescriptor());
delete sock;
}
void JudgeServer::receiveData(int fd)
{
InetSocket &sock = *_conn[fd];
InformMessage("receive data from %s", sock.getIpAddress().c_str());
struct packet p;
if(!sock.recvPacket(p)) {
removeConnection(&sock);
return ;
}
//Json parsing
Json::Reader reader;
Json::Value root;
reader.parse(p.buf, root);
InformMessage("%d message type %s, buf %s", fd, root.get("type", "notype").asCString(), p.buf.c_str());
process(root, sock);
}
void JudgeServer::onRead(int fd)
{
InformMessage("read!");
if(fd == _serv.getFileDescriptor()) {
createNewConnection();
}
else {
receiveData(fd);
}
}
void JudgeServer::run()
{
InformMessage("server start");
_judgeManager.start();
_pm.addEvent(_serv.getFileDescriptor(), EPOLLIN);
_pm.polling(-1);
}
void JudgeServer::process(Json::Value &value, InetSocket &socket) {
std::string str = value.get("type", "notype").asString();
if(str=="login") {
loginProcess(value.get("id", "null").asString()
, value.get("pw", "null").asString(), socket);
}
else if(str=="submit") {
submitProcess(value, socket);
}
else {
}
}
void JudgeServer::loginProcess(std::string id, std::string pw, InetSocket &sock) {
Json::StyledWriter writer;
DataBase::DBConnection dbc("mongodb://192.168.0.38");
auto collection = dbc.getCollection("judge_user", "judge_user");
bsoncxx::builder::stream::document filter;
filter << "id" << id;
filter << "pw" << pw;
InformMessage("login id : %s pw : %s", id.c_str(), pw.c_str());
for(auto &&doc : collection.find(filter)) {
loginSuccess(sock, dbc, doc);
return ;
}
loginFailed(sock);
}
void JudgeServer::loginFailed(InetSocket &sock) {
Json::StyledWriter writer;
packet p;
Json::Value val;
val["result"] = "false";
p.buf = writer.write(val);
p.len = static_cast<int>(p.buf.size());
sock.sendPacket(p);
val.clear();
InformMessage("login failed");
}
void JudgeServer::loginSuccess(InetSocket &sock, DataBase::DBConnection &dbc,
bsoncxx::document::view doc) {
Json::StyledWriter writer;
std::string tmp;
packet p;
Json::Value val;
InformMessage("login success");
tmp = bsoncxx::to_json(doc["name"].get_value());
tmp = tmp.substr(1, tmp.size()-2);
InformMessage("name %s", tmp.c_str());
val["result"] = "true";
val["id"] = tmp;
val["problems"] = getProblemList(dbc);
val["languages"] = getLanguageList(dbc);
p.buf = writer.write(val);
p.len = static_cast<int>(p.buf.size());
sock.sendPacket(p);
val.clear();
}
Json::Value JudgeServer::getProblemList(DataBase::DBConnection &dbc) {
Json::Reader reader;
Json::Value tempValue;
mongocxx::options::find optProj;
bsoncxx::builder::basic::document proj;
Json::Value questionObj;
Json::Value questionList;
std::string tmp;
auto collection = dbc.getCollection("judge_question", "judge_question");
proj.append(std::tuple<std::string, std::string>("_id","true")); //proj["_id"] = "true";
proj.append(std::tuple<std::string, std::string>("title", "true")); //proj["title"] = "true";
optProj.projection(proj.view());
for(auto &&doc : collection.find({}, optProj)) {
reader.parse(bsoncxx::to_json(doc), tempValue);
questionObj["title"]=tempValue["title"];
questionObj["qno"]=tempValue["_id"]["$oid"];
questionList.append(questionObj);
questionObj.clear();
}
return questionList;
}
Json::Value JudgeServer::getLanguageList(DataBase::DBConnection &dbc) {
Json::Reader reader;
Json::Value tempValue;
mongocxx::options::find optProj;
bsoncxx::builder::basic::document proj;
Json::Value languageObj;
Json::Value languageList;
std::string tmp;
auto collection = dbc.getCollection("judge_language", "judge_language");
proj.append(std::tuple<std::string, std::string>("_id","true")); //proj["_id"] = "true";
proj.append(std::tuple<std::string, std::string>("name", "true")); //proj["title"] = "true";
optProj.projection(proj.view());
for(auto &&doc : collection.find({}, optProj)) {
reader.parse(bsoncxx::to_json(doc), tempValue);
languageObj["lang"]=tempValue["name"];
InformMessage("qno : %s", tmp.c_str());
languageObj["langno"]=tempValue["_id"]["$oid"];
languageList.append(languageObj);
languageObj.clear();
}
return languageList;
}
void JudgeServer::submitProcess(Json::Value &value, InetSocket &socket) {
question q;
Json::Reader reader;
Json::Value temp;
DataBase::DBConnection dbc;
bsoncxx::builder::stream::document d;
q.code = value.get("code", "").asString();
q.extends = value.get("lang", "").asString();
q.qno = value.get("qno", "0").asString();
q.title = value.get("title", "").asString();
q.lang = value.get("lang", "cpp").asString();
q.examinee_id = value.get("id", "").asString();
// session
q.examinee = &socket;
// from db
getQuestionData(reader, dbc, d, q, temp);
getCompilerData(q, reader, temp, dbc, d);
InformMessage("code %s, extends %s, qno %s, q.limit %d, q.title %s"
, q.code.c_str(), q.extends.c_str(), q.qno.c_str(), q.limit, q.title.c_str());
_judgeManager.submit(q);
}
question &JudgeServer::getCompilerData(question &q, Json::Reader &reader, Json::Value &temp,
DataBase::DBConnection &dbc, bsoncxx::builder::stream::document &d) {
mongocxx::collection collection = dbc.getCollection("judge_language", "judge_language");
d << "name" << q.lang;
for(auto&& doc : collection.find(d)) {
InformMessage("language doc %s",bsoncxx::to_json(doc).c_str());
reader.parse(bsoncxx::to_json(doc), temp);
q.compiler = temp.get("compiler", "").asString();
q.compileOption= temp.get("compile_option", "").asString();
q.extends = temp.get("extend", "").asString();
break;
}
return q;
}
void JudgeServer::getQuestionData(Json::Reader &reader, DataBase::DBConnection &dbc,
bsoncxx::builder::stream::document &d, question &q, Json::Value &temp) {
mongocxx::collection collection = dbc.getCollection("judge_question", "judge_question");
d << "title" << q.title;
for(auto&& doc : collection.find(d)) {
InformMessage("question doc %s",bsoncxx::to_json(doc).c_str());
reader.parse(bsoncxx::to_json(doc), temp);
q.limit = temp.get("limit", 1).asInt();
for(auto inputIt = temp["input"].begin(), ansIt=temp["output"].begin();
inputIt!=temp["input"].end() && ansIt!=temp["output"].end();) {
InformMessage("input %s ans %s", inputIt->asString().c_str(), ansIt->asString().c_str());
std::string in = inputIt->asString();
in.push_back('\n');
q.testcases.push_back(std::make_pair(in, ansIt->asString()));
inputIt++;
ansIt++;
}
break;
}
d.clear();
}
|
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
int T, __it = 0;
cin >> T;
while (T--) {
__it++;
cout << "Case #" << __it << ": ";
int x, r, c;
cin >> x >> r >> c;
if (r > c) swap(r, c);
if ( (r * c) % x != 0) {
cout << "RICHARD\n";
} else
if (x == 1) {
cout << "GABRIEL\n";
} else
if (x == 2) {
cout << "GABRIEL\n";
} else
if (x == 3) {
if (r == 1 && c == 3) {
cout << "RICHARD\n";
} else {
cout << "GABRIEL\n";
}
} else
if (x == 4) {
if ((r == 1 && c == 4) ||
(r == 2 && c == 4) ||
(r == 2 && c == 2))
{
cout << "RICHARD\n";
} else {
cout << "GABRIEL\n";
}
} else
if (x == 5) {
if (r <= 3) {
cout << "RICHARD\n";
} else {
cout << "GABRIEL\n";
}
} else
if (x == 6) {
if (r <= 3) {
cout << "RICHARD\n";
} else {
cout << "GABRIEL\n";
}
} else
if (x >= 7) {
cout << "RICHARD\n";
}
}
return 0;
}
|
//
// serial.h
// serialowabaza
//
// Created by Julia on 06.11.2018.
// Copyright © 2018 Julia. All rights reserved.
//
#ifndef serial_h
#define serial_h
#include"ogladadlo.h"
#include <fstream>
class serial:public ogladadlo{
public:
virtual void prezentujsie();
virtual void save(std::fstream &plik);
};
#endif /* serial_h */
|
#include <stdio.h>
#include <FlexLexer.h>
#include "util.h"
#include "errormsg.h"
#include "tokens.h"
//int yylex(void); [> prototype for the lexing function <]
std::string toknames[] = {
"ID", "STRING", "INT", "COMMA", "COLON", "SEMICOLON", "LPAREN",
"RPAREN", "LBRACK", "RBRACK", "LBRACE", "RBRACE", "DOT", "PLUS",
"MINUS", "TIMES", "DIVIDE", "EQ", "NEQ", "LT", "LE", "GT", "GE",
"AND", "OR", "ASSIGN", "ARRAY", "IF", "THEN", "ELSE", "WHILE", "FOR",
"TO", "DO", "LET", "IN", "END", "OF", "BREAK", "NIL", "FUNCTION",
"VAR", "TYPE"
};
std::string tokname(int tok) {
return tok<257 || tok>299 ? "BAD_TOKEN" : toknames[tok-257];
}
vlex::YYSTYPE vlex::yylval;
yyFlexLexer* vlex::lexer = nullptr;
int main(int argc, char **argv) {
if (argc!= 2) {
fprintf(stderr,"usage: lextest inputfile < inputfile\n");
exit(1);
}
using vlex::errormsg;
std::string fname=argv[1];
errormsg::reset(fname);
vlex::lexer = new yyFlexLexer;
for(;;) {
int tok = vlex::lexer->yylex();
if (0 == tok) break;
switch(tok) {
case vlex::ID:
case vlex::STRING:
printf("%10s %4d %s\n",tokname(tok).data(),errormsg::tokpos, vlex::yylval.sval.data());
break;
case vlex::INT:
printf("%10s %4d %d\n",tokname(tok).data(),errormsg::tokpos, vlex::yylval.ival);
break;
default:
printf("%10s %4d\n",tokname(tok).data(), errormsg::tokpos);
}
}
delete vlex::lexer;
return 0;
}
|
/*In this program we will be seeing about STRING in C++ Program*/
/*C++ provide 2 types of String representations:
1) C- Style Character string - which is as similar in C Program.
2) The string Class type which is specially introduced with Standard C++.
*/
/*Strings in C++ Programming is also know as a One Dimensional Array of characters. Thus string contains a character Array which is terminated by a NULL character "\0"*/
/*By Default C++ compiler initialize a Null character at the end of every String . Therefore no woriies about the null character . Just have a note on it.*/
/*In this program lets see some string functons used in C++ Programming*/
/*In this lets see the standard string in c++, which is more powerfull and many more functionality in this standard string library*/
/*including preprocessor / headerfile in the program*/
#include <iostream>
/*string is a Standard c++ library for strings in C++ Program*/
#include <string>
/*using namespace*/
using namespace std ;
/*creating a main() function of the program*/
int main()
{
string str1 = "String";
string str2 = "Program";
string str3 ;
string str4 = "Strings";
/*strlen() in Standard C++ string library is by using size() */
/*Synatx for finding a string length is
string.size();
*/
cout<<"\nThe length of the String 1 " << str1 << " is ::: " << str1.size() << endl ;
cout<<"\nThe length of the String 2 " << str2 << " is ::: " << str2.size() << endl ;
cout<<"\nThe length of the String 4 " << str4 << " is ::: " << str4.size() << endl ;
/*strcpy() can be simply done by assigning it to other string*/
/*Synatx for assigning a string is
string2 = string1;
*/
str3 = str1;
cout<<"\nThe value which is copied to str3 from str1 is ::: " << str3 << endl ;
/*strcat() can be done easy like how we add 2 numbers .*/
/*Synatx Adding string is
str3 = str1 + str2 ;
*/
str1 = str1 + str2 ;
cout<<"\nThe concatenates the two strings is ::: " << str1 << endl ;
}
|
#include <stdlib.h>
#include "Mesh.h"
void mesh_read(const char* filename, Mesh& out);
int main(int argc, char **argv) {
Mesh mesh;
mesh_read("box.m", mesh);
system("pause");
return 0;
}
|
// Created on: 1993-06-07
// Created by: Jacques GOUSSARD
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntPatch_ArcFunction_HeaderFile
#define _IntPatch_ArcFunction_HeaderFile
#include <Adaptor2d_Curve2d.hxx>
#include <Adaptor3d_Surface.hxx>
#include <IntSurf_Quadric.hxx>
#include <TColgp_SequenceOfPnt.hxx>
#include <math_FunctionWithDerivative.hxx>
class IntPatch_ArcFunction : public math_FunctionWithDerivative
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT IntPatch_ArcFunction();
void SetQuadric (const IntSurf_Quadric& Q);
void Set (const Handle(Adaptor2d_Curve2d)& A);
void Set (const Handle(Adaptor3d_Surface)& S);
Standard_EXPORT Standard_Boolean Value (const Standard_Real X, Standard_Real& F) Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean Derivative (const Standard_Real X, Standard_Real& D) Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean Values (const Standard_Real X, Standard_Real& F, Standard_Real& D) Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbSamples() const;
Standard_EXPORT virtual Standard_Integer GetStateNumber() Standard_OVERRIDE;
const gp_Pnt& Valpoint (const Standard_Integer Index) const;
const IntSurf_Quadric& Quadric() const;
const Handle(Adaptor2d_Curve2d)& Arc() const;
const Handle(Adaptor3d_Surface)& Surface() const;
//! Returns the point, which has been computed
//! while the last calling Value() method
const gp_Pnt& LastComputedPoint() const;
protected:
private:
Handle(Adaptor2d_Curve2d) myArc;
Handle(Adaptor3d_Surface) mySurf;
IntSurf_Quadric myQuad;
gp_Pnt ptsol;
TColgp_SequenceOfPnt seqpt;
};
#include <IntPatch_ArcFunction.lxx>
#endif // _IntPatch_ArcFunction_HeaderFile
|
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#ifndef DRAW_ANIMATION_HPP_
#define DRAW_ANIMATION_HPP_
#include "Drawing.hpp"
namespace draw {
class AnimationAttr {
public:
AnimationAttr();
enum {
PUSH_LEFT = SG_ANIMATION_TYPE_PUSH_LEFT,
PUSH_RIGHT = SG_ANIMATION_TYPE_PUSH_RIGHT,
PUSH_UP = SG_ANIMATION_TYPE_PUSH_UP,
PUSH_DOWN = SG_ANIMATION_TYPE_PUSH_DOWN,
SLIDE_LEFT = SG_ANIMATION_TYPE_SLIDE_LEFT,
UNDO_SLIDE_LEFT = SG_ANIMATION_TYPE_UNDO_SLIDE_LEFT,
SLIDE_UP = SG_ANIMATION_TYPE_SLIDE_UP,
UNDO_SLIDE_UP = SG_ANIMATION_TYPE_UNDO_SLIDE_UP,
SLIDE_RIGHT = SG_ANIMATION_TYPE_SLIDE_RIGHT,
UNDO_SLIDE_RIGHT = SG_ANIMATION_TYPE_UNDO_SLIDE_RIGHT,
SLIDE_DOWN = SG_ANIMATION_TYPE_SLIDE_DOWN,
UNDO_SLIDE_DOWN = SG_ANIMATION_TYPE_UNDO_SLIDE_DOWN,
NONE = SG_ANIMATION_TYPE_NONE,
BOUNCE_UP = SG_ANIMATION_TYPE_BOUNCE_UP,
BOUNCE_DOWN = SG_ANIMATION_TYPE_BOUNCE_DOWN,
BOUNCE_LEFT = SG_ANIMATION_TYPE_BOUNCE_LEFT,
BOUNCE_RIGHT = SG_ANIMATION_TYPE_BOUNCE_RIGHT
};
enum {
LINEAR = SG_ANIMATION_PATH_LINEAR,
SQUARED = SG_ANIMATION_PATH_SQUARED,
SQUARED_UNDO = SG_ANIMATION_PATH_SQUARED_UNDO
};
sg_animation_t & attr(){ return m_attr; }
void set_type(u8 v){ m_attr.type = v; }
void set_path(u8 v){ m_attr.path.type = v; }
void set_step_total(u8 v){ m_attr.path.step_total = v; }
void set_motion_total(sg_size_t v){ m_attr.path.motion_total = v; }
//void set_drawing_start(drawing_point_t v){ m_drawing_attr.start = v; }
//void set_drawing_start(drawing_int_t x, drawing_int_t y){ m_drawing_attr.start.x = x; m_drawing_attr.start.y = y; }
//void set_drawing_dim(drawing_dim_t v){ m_drawing_attr.dim = v; }
//void set_drawing_dim(drawing_size_t w, drawing_size_t h){ m_drawing_attr.dim.w = w; m_drawing_attr.dim.h = h; }
void set_drawing_motion_total(drawing_size_t v){ m_drawing_motion_total = v; }
u8 type() const { return m_attr.type; }
u8 path() const { return m_attr.path.type; }
u16 step_total() const { return m_attr.path.step_total; }
sg_point_t start() const { return m_attr.start; }
sg_dim_t dim() const { return m_attr.dim; }
sg_size_t motion_total() const { return m_attr.path.motion_total; }
drawing_size_t drawing_motion_total() const { return m_drawing_motion_total; }
sg_animation_t * data(){ return &m_attr; }
private:
sg_animation_t m_attr;
drawing_size_t m_drawing_motion_total;
};
class Animation : public AnimationAttr {
public:
Animation();
void init(Drawing * current,
Drawing * target,
const DrawingAttr & attr);
bool exec(void (*draw)(void*,int,int) = 0, void * obj = 0);
void update_motion_total();
private:
int animate_frame(void (*draw)(void*,int,int), void * obj);
sg_animation_t * pattr(){ return data(); }
const DrawingAttr * m_drawing_attr;
};
};
#endif /* DRAW_ANIMATION_HPP_ */
|
#include <bits/stdc++.h>
using namespace std;
long long int mino=INT_MAX,maxo=INT_MIN,dife,n,i;
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
for(i=0;i<10;i++){
cin >> n;
if(n < mino) mino = n;
if(n > maxo) maxo = n;
}
cout << mino << " " << maxo << " " << (maxo-mino) ;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.