blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29a0fb9dd1720d1408475c2424e5a543a1e31a2a | acc0041a2b576f7aef5ff563d55c2ada95209820 | /Sources/WellLog/WellLogSlider.h | ec3578d5e1b9eaa1c0ae2bcca46cc4285b57d4c1 | [] | no_license | pvemavarapu/FingerRange_ComfortArea | d9416bcfb3e47902400d0a562a1273fb0607ce15 | 2219044a8ecc64bd63f93df9823709baeeae6e6f | refs/heads/master | 2021-09-22T19:54:07.404118 | 2018-09-14T17:53:26 | 2018-09-14T17:53:26 | 148,823,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | h | WellLogSlider.h | //|___________________________________________________________________
//!
//! \file WellLogSlider.h
//!
//! \brief Well-log slider class.
//!
//! Author: Phillip & Nathan (modified by Mark).
//|___________________________________________________________________
#pragma once
//|___________________
//|
//| Local Includes
//|___________________
#include <osg/Group>
#include <osgText/Text>
#include <osg/MatrixTransform>
//|___________________________________________________________________
//|
//! Well-log slider class.
//|___________________________________________________________________
class WellLogSlider : public osg::Group
{
public:
WellLogSlider(void);
~WellLogSlider(void);
void changeDepth(float delta);
float getDepthInMeters();
private:
void update(void);
void updateTextNode(void);
float _depthInMeters;
osg::ref_ptr<osg::MatrixTransform> _transform;
osg::ref_ptr<osgText::Text> _depthText;
};
|
615d75e6fb4e6f34e747e93fd05385a26509fc59 | a2065378a84ab5c3fbec8afa8b1464057175c2d5 | /elimDups.cpp | c5ccb36839e1e7ae093cd05bf940bf07d72a49e8 | [] | no_license | oursuccess/cplusplus_primer_practices | 377da4a3bfff0df34c97263a4bf9d0401bbc1aac | 9b975639eafc49d158992600cdd862282898e805 | refs/heads/master | 2020-04-05T04:22:37.428200 | 2018-11-14T12:09:31 | 2018-11-14T12:09:31 | 149,558,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197 | cpp | elimDups.cpp | #include<vector>
#include<string>
#include<algorithm>
void elimDups(std::vector<std::string> &vs)
{
sort(vs.begin(),vs.end());
auto end = unique(vs.begin(),vs.end());
vs.erase(end,vs.end());
}
|
4d6ce5f94268aa2f96d4af6c037dec22691f4865 | f291a7671d98bb529f74bf2aafbcc0f75c15018b | /source/annotator/source/geomObject/annotationgraphicsitem.cpp | 586ddcb54bb44aa24c0240b916081fbe8b26f1f4 | [
"Apache-2.0"
] | permissive | reger-men/annotator | c01c6e0341918c03f269fb3174874b98529cdbf8 | 7b040613a9197e0c13d904b19485d3bf28f94733 | refs/heads/master | 2021-01-15T14:53:27.086364 | 2016-07-08T23:00:42 | 2016-07-08T23:00:42 | 62,969,625 | 0 | 0 | null | 2016-07-09T21:20:01 | 2016-07-09T21:20:00 | null | UTF-8 | C++ | false | false | 10,926 | cpp | annotationgraphicsitem.cpp | #include <AnnotatorLib/Commands/NewAnnotation.h>
#include <AnnotatorLib/Commands/UpdateAnnotation.h>
#include "annotationgraphicsitem.h"
#include "plugins/pluginloader.h"
AnnotatorLib::Annotation *AnnotationGraphicsItem::getAnnotation()
{
return annotation;
}
AnnotationGraphicsItem::AnnotationGraphicsItem(AnnotatorLib::Annotation *annotation):
QGraphicsItem::QGraphicsItem(nullptr)
{
this->annotation = annotation;
if(annotation->getObject() == nullptr)
borderColor = idToColor(annotation->getId());
else
borderColor = idToColor(annotation->getObject()->getId());
setPos(annotation->getX() - annotation->getHRadius(), annotation->getY() - annotation->getVRadius());
initCorners();
initIdText();
rectX = 0;
rectY = 0;
width = annotation->getHRadius()*2;
height = annotation->getVRadius()*2;
cornerXPos = 0;
cornerYPos = 0;
cornerWidth = width,
cornerHeight = height,
originColor = borderColor;
}
AnnotationGraphicsItem::~AnnotationGraphicsItem()
{
for(int i = 0; i < 4; ++i){
delete corners[i];
}
}
static double r_ = (1 + sqrt(5)) / 2;
static double g_ = (3 + sqrt(7)) / 2;
static double b_ = (11 + sqrt(13)) / 2;
QColor AnnotationGraphicsItem::idToColor(long id)
{
double r = id * r_ - floor(id * r_);
double g = id * g_ - floor(id * g_);
double b = id * b_ - floor(id * b_);
return QColor(r * 255, g * 255, b* 255);
}
void AnnotationGraphicsItem::setPlayer(Player *player)
{
this->player = player;
}
void AnnotationGraphicsItem::initCorners()
{
for(int i = 0; i < 4; ++i){
corners[i] = new Corner(this,i);
corners[i]->hide();
//corners[i]->installSceneEventFilter(this);
}
setCornerPositions();
}
void AnnotationGraphicsItem::initIdText()
{
idText.setParentItem(this);
idText.setDefaultTextColor(borderColor);
idText.setPlainText(QString::number(annotation->getId()));
idText.setPos(rectX,rectY-20);
idText.hide();
}
void AnnotationGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mouseDoubleClickEvent(event);
if(this->player != nullptr && this->annotation != nullptr && this->annotation->getObject() != nullptr)
{
this->player->selectObject(annotation->getObject());
}
}
/*
void AnnotationGraphicsItem::changeAnnotationPosition(int x, int y)
{
annotation->setPosition(x, y);
}*/
/////////////////////////////////////////////////////////////
/**
* change item setting: if mouse on hover
*/
void AnnotationGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *){
corners[0] = new Corner(this,0);
corners[1] = new Corner(this,1);
corners[2] = new Corner(this,2);
corners[3] = new Corner(this,3);
corners[0]->installSceneEventFilter(this);
corners[1]->installSceneEventFilter(this);
corners[2]->installSceneEventFilter(this);
corners[3]->installSceneEventFilter(this);
setCornerPositions();
borderColor = Qt::green;
QLinearGradient gradient;
gradient.setStart(cornerXPos,cornerYPos);
gradient.setFinalStop( cornerWidth ,cornerYPos);
QColor grey1(150,150,150,125);
QColor grey2(225,225,225,125);
gradient.setColorAt((qreal)0, grey1 );
gradient.setColorAt((qreal)1, grey2 );
brush = gradient;
idText.show();
update();
}
/**
* set corner position
*/
void AnnotationGraphicsItem::setCornerPositions()
{
corners[0]->setPos(cornerXPos, cornerYPos);
corners[1]->setPos(cornerXPos+cornerWidth-corners[0]->getWidth(), cornerYPos);
corners[2]->setPos(cornerXPos+cornerWidth-corners[0]->getWidth() , cornerYPos+cornerHeight-corners[0]->getHeight());
corners[3]->setPos(cornerXPos, cornerYPos+cornerHeight-corners[0]->getHeight());
}
/**
* reset item setting: if mouse leave hover
*/
void AnnotationGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *){
corners[0]->setParentItem(NULL);
corners[1]->setParentItem(NULL);
corners[2]->setParentItem(NULL);
corners[3]->setParentItem(NULL);
delete corners[0];
delete corners[1];
delete corners[2];
delete corners[3];
borderColor = originColor;
brush = Qt::NoBrush;
idText.hide();
update();
}
/**
* set new size to the item
*/
void AnnotationGraphicsItem::setSize(int x, int y)
{
width += x;
height += y;
cornerWidth = width;
cornerHeight= height;
}
/**
* filter event: to get mpouse press, move and release from parent graphicsScene
*/
bool AnnotationGraphicsItem::sceneEventFilter(QGraphicsItem * watched, QEvent * event )
{
Corner * corner = dynamic_cast<Corner *>(watched);
if ( corner == NULL) return false;
QGraphicsSceneMouseEvent * own_event = dynamic_cast<QGraphicsSceneMouseEvent*>(event);
if ( own_event == NULL)
{
return false;
}
switch (event->type() )
{
// if the mouse pressed, save the (x,y) coordinates inside the corner object
case QEvent::GraphicsSceneMousePress:
{
corner->setMouseState(Corner::MouseDown);
corner->mouseDownX = own_event->pos().x();
corner->mouseDownY = own_event->pos().y();
this->setSelected(true);
}
break;
case QEvent::GraphicsSceneMouseRelease:
{
corner->setMouseState(Corner::MouseReleased);
changeAnnotationSize((int)this->x(), (int)this->y(), (int)this->width, (int)this->height);
}
break;
case QEvent::GraphicsSceneMouseMove:
{
corner->setMouseState(Corner::MouseMoving );
}
break;
default:
return false;
break;
}
if ( corner->getMouseState() == Corner::MouseMoving )
{
qreal x = own_event->pos().x();
qreal y = own_event->pos().y();
//XSign and YSign to add add or substract size of Item
int XSign = 0;
int YSign = 0;
switch( corner->getCorner() )
{
case 0:
{
XSign = +1;
YSign = +1;
}
break;
case 1:
{
XSign = -1;
YSign = +1;
}
break;
case 2:
{
XSign = -1;
YSign = -1;
}
break;
case 3:
{
XSign = +1;
YSign = -1;
}
break;
}
//Set the new size of Item, whene the the corner position is changed.
int XPos = corner->mouseDownX - x;
int YPos = corner->mouseDownY - y;
//set min width and min height to 10 px.
int newWidth = width + ( XSign * XPos);
if ( newWidth < 10 ) newWidth = 10;
int newHeight = height + (YSign * YPos) ;
if ( newHeight < 10 ) newHeight = 10;
int deltaWidth = newWidth - width ;
int deltaHeight = newHeight - height ;
//set the new size to item.
setSize(deltaWidth , deltaHeight);
deltaWidth *= (-1);
deltaHeight *= (-1);
switch( corner->getCorner() )
{
case 0:
{
int newXPos = this->pos().x() + deltaWidth;
int newYpos = this->pos().y() + deltaHeight;
this->setPos(newXPos, newYpos);
}
break;
case 1:
{
int newYpos = this->pos().y() + deltaHeight;
this->setPos(this->pos().x(), newYpos);
}
break;
case 2:
{
this->setPos(this->pos().x(), this->pos().y());
}
break;
case 3:
{
int newXPos = this->pos().x() + deltaWidth;
this->setPos(newXPos,this->pos().y());
}
break;
}
setCornerPositions();
this->update();
}
return true;
}
void AnnotationGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mousePressEvent(event);
deltax = this->x();
deltay = this->y();
}
void AnnotationGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mouseReleaseEvent(event);
deltax = this->x() - deltax;
deltay = this->y() - deltay;
changeAnnotationPosition(this->x(), this->y());
setCornerPositions();
this->update();
}
void AnnotationGraphicsItem::setAnnotationSize(int x, int y)
{
annotation->setPositionWH(annotation->getX(), annotation->getY(), x, y);
}
void AnnotationGraphicsItem::changeAnnotationPosition(int x, int y)
{
if(annotation->isInterpolated()){
annotation->setInterpolated(false);
AnnotatorLib::Commands::NewAnnotation * nA =
new AnnotatorLib::Commands::NewAnnotation(annotation->getObject(), annotation->getFrame(),
x + annotation->getHRadius(), y + annotation->getVRadius(),
annotation->getHRadius(), annotation->getVRadius(),
annotation->getNext(), annotation->getPrevious(), player->getSession(), true);
player->getSession()->execute(nA);
}else{
AnnotatorLib::Commands::UpdateAnnotation * uA = new AnnotatorLib::Commands::UpdateAnnotation(annotation,
x + annotation->getHRadius(), y + annotation->getVRadius(), annotation->getHRadius(), annotation->getVRadius());
player->getSession()->execute(uA);
}
// update position of last annotation in automation plugin
Annotator::Plugin * plugin = Annotator::PluginLoader::getInstance().getCurrent();
if(plugin){
plugin->setObject(annotation->getObject());
plugin->setLastAnnotation(annotation);
}
}
void AnnotationGraphicsItem::changeAnnotationSize(int x, int y, int w, int h)
{
if(annotation->isInterpolated()){
annotation->setInterpolated(false);
AnnotatorLib::Commands::NewAnnotation * nA =
new AnnotatorLib::Commands::NewAnnotation(annotation->getObject(), annotation->getFrame(),
x + w/2, y + h/2,
w/2, h/2,
annotation->getNext(), annotation->getPrevious(), player->getSession(), true);
player->getSession()->execute(nA);
}else{
AnnotatorLib::Commands::UpdateAnnotation * uA = new AnnotatorLib::Commands::UpdateAnnotation(annotation,
x + w/2, y + h/2, w/2, h/2);
player->getSession()->execute(uA);
}
// update position of last annotation in automation plugin
Annotator::Plugin * plugin = Annotator::PluginLoader::getInstance().getCurrent();
if(plugin){
plugin->setObject(annotation->getObject());
plugin->setLastAnnotation(annotation);
}
}
|
75f5bbb8037e5764d9e10b53fdc0f3bbce6ebb4b | f7333a3be3731449a99b8f1debf46da48d2f179b | /include/RandomContractionAlgorithm.h | 4e505036b4bfc747d9fd897787ce41473abc920a | [] | no_license | csrrmrvll/KargerMinCut | c7e5fd7d67fae0fd8f03d1f1d93b729fd1dcf2d6 | 7842beeab7322512d006f300cade1d124c131862 | refs/heads/master | 2021-01-23T08:04:10.462532 | 2017-02-18T08:06:00 | 2017-02-18T08:06:00 | 80,524,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | h | RandomContractionAlgorithm.h | #ifndef RANDOMCONTRACTIONALGORITHM_H
#define RANDOMCONTRACTIONALGORITHM_H
class Graph;
class RandomContractionAlgorithm
{
public:
static size_t run(const Graph & graph);
};
#endif // RANDOMCONTRACTIONALGORITHM_H
|
0d8215fe111ac8730d418cf8d7b9d06c1c4187bc | 326bc5a1d3a1834e895fe4c821d5f83dcb198717 | /Inventory.hpp | 9ef63f084f2ddb9569b79a0525b0cf17d13ad97f | [] | no_license | DavidNovak1521/School_OOP | da02ac004aa52796d5b9ba7d117a81425573463a | c6a6304dd55d8c3d3276e6f7aaac38fcf609ef06 | refs/heads/master | 2023-01-20T11:57:43.964265 | 2020-11-27T16:06:09 | 2020-11-27T16:06:09 | 309,932,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | hpp | Inventory.hpp | #ifndef INVENTORY_HPP
#define INVENTORY_HPP
#include <vector>
#include "Item.hpp"
class Inventory
{
public:
Inventory(double weightLimit);
~Inventory();
Inventory(const Inventory &) = delete;
Inventory &operator=(const Inventory &) = delete;
double getTotalWeight() const;
template <typename T>
double getWeight() const
{
double totalWeight = 0;
for (auto item : items)
{
T *pT = dynamic_cast<T *>(item);
if (pT != nullptr)
totalWeight += pT->getWeight();
}
return totalWeight;
}
int count() const;
const Item &get(int index) const;
bool put(Item *item);
Item *drop(int index);
void destroy(int index);
void clear();
private:
std::vector<Item *> items;
const double weightLimit;
};
#endif
|
1374b660521f77cca19dd246c7bb8f4e657b07cd | c651ea919f24fcf51cbe27d1c336b9324fda74e6 | /reverse/450-times-up-again/eval.cpp | 30f77a02dec8a4bb2dcd81b3beac323a6559c640 | [] | no_license | paiv/picoctf2019 | 31f611b21bcab0d1c84fd3cb246c7dd58f6949df | 90b1db56ac8c5b47ec6159d45c8decd6b90d06d5 | refs/heads/master | 2020-08-11T03:38:55.580861 | 2019-10-11T20:48:44 | 2019-10-11T20:48:44 | 214,483,178 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,227 | cpp | eval.cpp | // c++ -std=c++14 -O2 eval.cpp -o eval
#include <iostream>
#include <sstream>
typedef int32_t i32;
typedef int64_t i64;
using namespace std;
enum class NodeType {
Number,
OpAdd,
OpSub,
OpMul,
};
typedef struct Node {
NodeType type;
i64 value;
Node* left;
Node* right;
} Node;
static i64
parse_int(istringstream& si) {
i64 x;
si >> x;
return x;
}
static Node*
parse_node(istringstream& si) {
Node* node = new Node;
*node = {};
int x = si.peek();
while (si && isspace(x)) {
si.seekg(1, si.cur);
x = si.peek();
}
switch (x) {
case EOF:
break;
case '-': case '0': case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
node->type = NodeType::Number;
node->value = parse_int(si);
break;
case '(': {
char x, op = 0;
si >> x;
Node* left = parse_node(si);
si >> op;
switch (op) {
case '+':
node->type = NodeType::OpAdd; break;
case '-':
node->type = NodeType::OpSub; break;
case '*':
node->type = NodeType::OpMul; break;
case ')':
delete node;
return left;
default:
clog << "unhandled op: " << op << " " << (int)op << endl;
exit(1);
}
node->left = left;
node->right = parse_node(si);
}
break;
default:
clog << "unexpected char: " << (char)x << endl;
exit(1);
}
return node;
}
static i64
eval_node(Node* node) {
switch (node->type) {
case NodeType::OpAdd:
return eval_node(node->left) + eval_node(node->right);
case NodeType::OpSub:
return eval_node(node->left) - eval_node(node->right);
case NodeType::OpMul:
return eval_node(node->left) * eval_node(node->right);
case NodeType::Number:
return node->value;
}
}
int main(int argc, char const *argv[]) {
string s;
getline(cin, s);
istringstream si(s);
Node* root = parse_node(si);
i64 x = eval_node(root);
cout << x << endl;
return 0;
}
|
7b42156555b69597ebf13a1241618f82f896ff6d | 40d39150585c7e641f2f7d4d315eb52b2b38dbc2 | /Simulador/Principal/Principal.ino | 944ca8eb846db6ccdf2af4b4424cefa5970e14a2 | [] | no_license | LeaPepe/EmbebidosFinal | b3f9cdab4edc43bf291cf744eb71aadb921ce788 | 4f4b952ba23a28d33e4f4e10f24f8a6938f5ce26 | refs/heads/main | 2023-03-08T13:06:02.142186 | 2021-02-24T15:29:19 | 2021-02-24T15:29:19 | 336,659,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,225 | ino | Principal.ino | #include <Wire.h>
#include <Adafruit_MCP4725.h>
// Debug options
//#define DEBUG_TIME
//#define DEBUG_VALUES
#define DEBUG_CALCULATIONS
// ONE PHASE PARAMS
const float LINE_FREQ = 50;
const float LINE_FREQ_ANG_US_DEG = 2 * PI * LINE_FREQ / 1000000;
//Global variables
#ifdef DEBUG_TIME
unsigned long startTime, stopTime;
double t;
#endif //debug
int cyclesCount;
// DAC ADDR
Adafruit_MCP4725 DAC1;
Adafruit_MCP4725 DAC2;
// SETUP
void setup()
{
// Serial
Serial.begin(115200);
Serial.println("Begin ...");
// DAC
// 0x60 LOW, 0x61 HIGH
if (!DAC1.begin(0x60)) Serial.println("DAC 0x60 Not Found");
if (!DAC2.begin(0x61)) Serial.println("DAC 0x61 Not Found");
}
// LOOP
void loop()
{
// To display cycle time
#ifdef DEBUG_TIME
startTime = micros();
#endif //DEBUG_TIME
// Voltage
float sineV = sin(LINE_FREQ_ANG_US_DEG * micros()); // Sine(2pift)
int v = (int)(2048.0f + 2000.0f * sineV) ; // to logic value
DAC2.setVoltage(v, false);
// Current (analog reads)
int phaseOffset = 8 * (analogRead(A1) - 512); // A1 for time offset in ms
float sineA = sin(LINE_FREQ_ANG_US_DEG * (micros() - phaseOffset)); // Sine(2pif(t-offset))
int i = 2048 + (int)((2000.0f / 1024.0f) * analogRead(A0) * sineA); // A0 for amplitude
DAC1.setVoltage(i, false);
// To display cycle time
#ifdef DEBUG_TIME
stopTime = micros();
Serial.print("Cycle (ms): ");
Serial.println((stopTime - startTime) / 1000.0);
#endif //DEBUG_TIME
// To display real time samples
#ifdef DEBUG_VALUES
Serial.print(i);
Serial.print(',');
Serial.println(v);
#endif //DEBUG_VALUES
// To display teoric values Vrms,Irms,Phi
#ifdef DEBUG_CALCULATIONS
if (cyclesCount++ % 5000 == 0) {
float vrms = ((((float)(4048 - 2048)) * 318.4f) / 2048.0f) * 0.707f;
float irms = ((((float)((2048 +(2000.0f / 1024.0f) * analogRead(A0)) - 2048)) * 15.0f) / 2048.0f) * 0.707f;
Serial.print("Ve = ");
Serial.print(vrms);
Serial.print(", Ie = ");
Serial.print(irms);
Serial.print(", Phi = ");
float phi = (float)phaseOffset * 360.0f / 20000.0f;
Serial.println(phi);
}
#endif //DEBUG_CALCULATIONS
}
|
e07e976d6730901b9edac5522ee1aadcb8cafd2b | 41496fb1682c654d3aaad8bb2be7cacc3b1790fc | /Heap/index_heap.h | 6beb906837b8946bdf785f584c7f3664da421330 | [] | no_license | wisdomG/AlgorithmTemplate | ae6c64eb257abcfe8e8981f6bfffd33d2baf11eb | 14a0ad2b97b6a95178b594b475198c935d7ab895 | refs/heads/master | 2022-02-20T15:33:23.282880 | 2019-10-20T14:33:09 | 2019-10-20T14:33:09 | 113,799,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,119 | h | index_heap.h | #include <iostream>
#include <algorithm>
#include <cassert>
#include <utility>
using namespace std;
/* MaxHeap
* the index is from 1
* parent of i: i/2
* left child of i: i * 2;
* right child of i: i * 2 + 1
*/
template<typename T>
class IndexMaxHeap {
private:
T *data;
int *indexes;
int *reverse;
int cnt;
int capacity;
// Shife Up, comparing with the parent node
void shiftUp(int k) {
while (k > 1 && data[indexes[k/2]] < data[indexes[k]]) {
swap(indexes[k/2], indexes[k]);
reverse[indexes[k/2]] = k/2;
reverse[indexes[k]] = k;
k /= 2;
}
}
// Shift Down, comparing with the child node
void shiftDown(int k) {
while (k * 2 <= cnt) {
int j = k * 2; //record the position that may swap with k
if (j + 1 <= cnt && data[indexes[j+1]] > data[indexes[j]])
j += 1;
if (data[indexes[k]] >= data[indexes[j]])
break;
swap(indexes[k], indexes[j]);
reverse[indexes[k]] = k;
reverse[indexes[j]] = j;
k = j;
}
}
public:
IndexMaxHeap(int capacity) {
data = new T[capacity + 1];
indexes = new int[capacity + 1];
reverse = new int[capacity + 1];
for (int i = 0; i <= capacity; ++i)
reverse[i] = 0;
cnt = 0;
this->capacity = capacity;
}
~IndexMaxHeap() {
delete[] data;
delete[] indexes;
delete[] reverse;
}
int size() { return cnt; }
bool empty() { return cnt == 0; }
// idx >= 0
void insert(int idx, T item) {
assert(cnt + 1 <= this->capacity);
assert(idx + 1 >= 1 && idx + 1 <= this->capacity);
idx += 1;
data[idx] = item;
indexes[cnt+1] = idx;
reverse[idx] = cnt + 1;
++cnt;
shiftUp(cnt);
}
// return the maximal element, the use the last element as the top of heap and adjust it with shiftDown
T extractMax() {
assert(cnt > 0);
T ret = data[indexes[1]];
swap(indexes[1], indexes[cnt]);
reverse[indexes[1]] = 1;
reverse[indexes[cnt]] = 0;
--cnt;
shiftDown(1);
return ret;
}
int extractMaxIndex() {
assert(cnt > 0);
int ret = indexes[1] - 1;
swap(indexes[1], indexes[cnt]);
reverse[indexes[1]] = 1;
reverse[indexes[cnt]] = 0;
--cnt;
shiftDown(1);
return ret;
}
bool contain(int i) {
assert(i + 1 >= 1 && i + 1 <= capacity);
return reverse[i+1] != 0;
}
T getItem(int i) {
assert(contain(i));
return data[i+1];
}
void change(int i, T item) {
assert(contain(i));
i += 1;
data[i] = item;
int j = reverse[i];
shiftUp(j);
shiftDown(j);
/* O(n)
for (int j = 1; j <= cnt; ++j) {
if (indexes[j] == i) {
shiftUp(j);
shiftDown(j);
return ;
}
}*/
}
};
|
dc5a1d43f3e1ad6bc74ddf0470dda203ac3f97ac | 24715e7509aa21d97b96001b1cee789dd507fc20 | /GameFramework/Include/Object/Obj.cpp | 55df3b41c076d0ddac66707c0fddd02d5e168afa | [] | no_license | jhoryong/baba-is-you | 9c4da5336c857f8ef155d1aff073c0dcbeb8a812 | 4c011dc0dd8fdbf7c2a6c82e4fbf6956c5df020d | refs/heads/main | 2023-08-03T15:45:47.250413 | 2021-09-10T10:17:56 | 2021-09-10T10:17:56 | 365,950,244 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 9,591 | cpp | Obj.cpp | #include "Obj.h"
#include "../Resource/Texture.h"
#include "../Scene/Scene.h"
#include "../Scene/SceneResource.h"
#include "../Resource/ResourceManager.h"
#include "../Animation.h"
#include "../Resource/AnimationSequence.h"
#include "../Resource/AnimationSequence.h"
#include "../Scene/Camera.h"
#include "../Scene/SceneCollision.h"
#include "../Collider/Collider.h"
#include "../PathManager.h"
#include "../Input.h"
CObj::CObj() :
m_pScene(nullptr),
m_pTexture(nullptr),
m_pAnimation(nullptr),
m_bUI(false),
m_bEnvironment(false),
m_bStart(false),
m_bAlphaBlend(false),
m_cAlpha(255),
m_bDrawCollider(false)
{
}
CObj::CObj(const CObj& obj)
{
*this = obj;
m_iRefCount = 1;
if (m_pTexture)
m_pTexture->AddRef();
if (obj.m_pAnimation)
{
m_pAnimation = obj.m_pAnimation->Clone();
m_pAnimation->SetOwner(this);
m_pAnimation->SetScene(m_pScene);
}
m_ColliderList.clear();
auto iter = obj.m_ColliderList.begin();
auto iterEnd = obj.m_ColliderList.end();
for (; iter != iterEnd; ++iter)
{
CCollider* pCollider = (*iter)->Clone();
pCollider->m_pOwner = this;
m_ColliderList.push_back(pCollider);
}
}
CObj::~CObj()
{
SAFE_DELETE_VECLIST(m_ColliderList);
SAFE_DELETE(m_pAnimation);
SAFE_RELEASE(m_pTexture);
GET_SINGLE(CInput)->DeleteBindAction("Collider");
}
bool CObj::Init(const char* pFileName, const string& strPathName)
{
return true;
}
void CObj::Start()
{
///*static bool bKey = false;
//if (!bKey)
//{
// bKey = true;
//
//}
GET_SINGLE(CInput)->AddActionKey("Collider", VK_F2);
GET_SINGLE(CInput)->AddBindAction("Collider", KEY_TYPE::DOWN, this, &CObj::ColliderSwitch);
if (m_pAnimation)
{
SAFE_RELEASE(m_pTexture);
m_pTexture = m_pAnimation->m_pCurrent->pSequence->GetTexture();
}
}
void CObj::Update(float fTime)
{
if (m_pAnimation)
m_pAnimation->Update(fTime);
auto iter = m_ColliderList.begin();
auto iterEnd = m_ColliderList.end();
for (; iter != iterEnd; )
{
if (!(*iter)->IsEnable())
{
++iter;
continue;
}
(*iter)->Update(fTime);
++iter;
}
}
void CObj::PostUpdate(float fTime)
{
}
void CObj::Collision(float fTime)
{
auto iter = m_ColliderList.begin();
auto iterEnd = m_ColliderList.end();
Vector2 vRS = m_pScene->GetMainCamera()->GetResolution();
Vector2 vCameraPos = m_pScene->GetMainCamera()->GetPos();
Vector2 vExt = vRS / 4.f;
for (; iter != iterEnd; ++iter)
{
if (!(*iter)->IsEnable())
continue;
// 카메라로부터 너무 벗어나 있을 경우 포함을 안시킨다.
// 만약 이전에 충돌처리가 되고 있던 물체가 있을 경우
// 떨어지는 처리를 해주도록 한다.
if (!m_bUI)
{
if ((*iter)->GetSectionInfo().fL <= vCameraPos.x + vRS.x + vExt.x &&
(*iter)->GetSectionInfo().fR >= vCameraPos.x - vExt.x &&
(*iter)->GetSectionInfo().fT <= vCameraPos.y + vRS.y + vExt.y &&
(*iter)->GetSectionInfo().fB >= vCameraPos.y - vExt.y)
{
m_pScene->GetSceneCollision()->AddCollider(*iter);
}
// 이전 충돌체 있는지 판단하여 처리
else
{
}
}
else
m_pScene->GetSceneCollision()->AddCollider(*iter);
}
}
void CObj::PrevRender(float fTime)
{
if (!m_bUI)
m_vRenderPos = m_vPos - m_pScene->GetMainCamera()->GetPos();
else
m_vRenderPos = m_vPos;
}
void CObj::Render(HDC hDC, float fTime)
{
CCamera* pCamera = m_pScene->GetMainCamera();
Vector2 vLT = m_vRenderPos - m_vPivot * m_vSize;
if (m_pTexture)
{
if (m_bAlphaBlend)
{
if (m_pAnimation)
{
AnimationFrameInfo tCurrentFrame = m_pAnimation->GetCurrnetFrameInfo();
m_vSize = tCurrentFrame.vEnd - tCurrentFrame.vStart;
if (vLT.x + m_vSize.x <= 0.f)
return;
else if (vLT.x >= pCamera->GetResolution().x)
return;
else if (vLT.y + m_vSize.y <= 0.f)
return;
else if (vLT.y >= pCamera->GetResolution().y)
return;
int iFrame = 0;
if (m_pAnimation->m_pCurrent->pSequence->GetAnimType() == ANIM_TYPE::FRAME)
iFrame = m_pAnimation->m_pCurrent->iFrame;
m_pTexture->RenderAlphaBlend(m_cAlpha, hDC, vLT, tCurrentFrame.vStart, m_vSize, iFrame);
}
else
{
if (vLT.x + m_vSize.x <= 0.f)
return;
else if (vLT.x >= pCamera->GetResolution().x)
return;
else if (vLT.y + m_vSize.y <= 0.f)
return;
else if (vLT.y >= pCamera->GetResolution().y)
return;
m_pTexture->RenderAlphaBlend(m_cAlpha, hDC, vLT, Vector2::Zero, m_vSize);
}
}
else
{
if (m_pAnimation)
{
AnimationFrameInfo tCurrentFrame = m_pAnimation->GetCurrnetFrameInfo();
m_vSize = tCurrentFrame.vEnd - tCurrentFrame.vStart;
if (vLT.x + m_vSize.x <= 0.f)
return;
else if (vLT.x >= pCamera->GetResolution().x)
return;
else if (vLT.y + m_vSize.y <= 0.f)
return;
else if (vLT.y >= pCamera->GetResolution().y)
return;
int iFrame = 0;
if (m_pAnimation->m_pCurrent->pSequence->GetAnimType() == ANIM_TYPE::FRAME)
iFrame = m_pAnimation->m_pCurrent->iFrame;
m_pTexture->Render(hDC, vLT, tCurrentFrame.vStart, m_vSize, iFrame);
}
else
{
if (vLT.x + m_vSize.x <= 0.f)
return;
else if (vLT.x >= pCamera->GetResolution().x)
return;
else if (vLT.y + m_vSize.y <= 0.f)
return;
else if (vLT.y >= pCamera->GetResolution().y)
return;
m_pTexture->Render(hDC, vLT, Vector2::Zero, m_vSize);
}
}
}
else
{
Vector2 vRB = vLT + m_vSize;
//HBRUSH hPrevBrush = (HBRUSH)SelectObject(hDC, GetStockObject(NULL_BRUSH));
Rectangle(hDC, (int)vLT.x, (int)vLT.y, (int)vRB.x, (int)vRB.y);
//SelectObject(hDC, hPrevBrush);
}
if (m_bDrawCollider) // 디버깅 용으로 충돌체를 그려준다.
{
auto iter = m_ColliderList.begin();
auto iterEnd = m_ColliderList.end();
for (; iter != iterEnd; )
{
if (!(*iter)->IsEnable())
{
++iter;
continue;
}
(*iter)->Render(hDC, fTime);
++iter;
}
}
}
void CObj::PostRender(float fTime)
{
}
void CObj::SaveFile(const char* pFileName, const string& strPathName)
{
FILE* pFile = nullptr;
const char* pPath = GET_SINGLE(CPathManager)->FindPathMultibyte(strPathName);
char strFullPath[MAX_PATH] = {};
if (pPath)
strcpy_s(strFullPath, pPath);
strcat_s(strFullPath, pFileName);
fopen_s(&pFile, strFullPath, "wb");
if (!pFile)
return;
Save(pFile);
fclose(pFile);
}
void CObj::LoadFile(const char* pFileName, const string& strPathName)
{
FILE* pFile = nullptr;
const char* pPath = GET_SINGLE(CPathManager)->FindPathMultibyte(strPathName);
char strFullPath[MAX_PATH] = {};
if (pPath)
strcpy_s(strFullPath, pPath);
strcat_s(strFullPath, pFileName);
fopen_s(&pFile, strFullPath, "rb");
if (!pFile)
return;
Load(pFile);
fclose(pFile);
}
void CObj::Save(FILE* pFile)
{
}
void CObj::Load(FILE* pFile)
{
}
bool CObj::SetTexture(const string& strName)
{
SAFE_RELEASE(m_pTexture);
m_pTexture = m_pScene->GetSceneResource()->FindTexture(strName);
return true;
}
bool CObj::SetTexture(const string& strName, const TCHAR* pFileName, const string& strPathName)
{
SAFE_RELEASE(m_pTexture);
m_pScene->GetSceneResource()->LoadTexture(strName, pFileName, strPathName);
m_pTexture = m_pScene->GetSceneResource()->FindTexture(strName);
return true;
}
bool CObj::SetTexture(const string& strName,
const vector<const TCHAR*>& vecFileName, const string& strPathName)
{
SAFE_RELEASE(m_pTexture);
m_pScene->GetSceneResource()->LoadTexture(strName, vecFileName, strPathName);
m_pTexture = m_pScene->GetSceneResource()->FindTexture(strName);
return true;
}
bool CObj::SetTexture(const string& strName, const TCHAR* pFileName,
int iCount, const string& strPathName)
{
SAFE_RELEASE(m_pTexture);
m_pScene->GetSceneResource()->LoadTexture(strName, pFileName,
iCount, strPathName);
m_pTexture = m_pScene->GetSceneResource()->FindTexture(strName);
return true;
}
bool CObj::SetTexture(CTexture* pTexture)
{
SAFE_RELEASE(m_pTexture);
m_pTexture = pTexture;
if (m_pTexture)
m_pTexture->AddRef();
return true;
}
void CObj::CreateAnimation()
{
if (m_pAnimation)
return;
m_pAnimation = new CAnimation;
m_pAnimation->SetOwner(this);
m_pAnimation->SetScene(m_pScene);
m_pAnimation->Init();
}
void CObj::AddAnimationSequence(const string& strName)
{
m_pAnimation->AddSequence(strName);
}
void CObj::AddAnimationSequence(CAnimationSequence* pSequence)
{
m_pAnimation->AddSequence(pSequence);
}
void CObj::AddLoadedAnimationSequence(const string& strName)
{
CAnimationSequence* pSequence = GET_SINGLE(CResourceManager)->FindAnimationSequence(strName);
if (!pSequence)
return;
m_pAnimation->AddSequence(pSequence);
SAFE_RELEASE(pSequence);
}
void CObj::SetAnimationPlayRate(const string& strName, float fPlayRate)
{
m_pAnimation->SetPlayRate(strName, fPlayRate);
}
void CObj::AddAnimationPlayRate(const string& strName, float fPlayRate)
{
m_pAnimation->AddPlayRate(strName, fPlayRate);
}
void CObj::ChangeAnimation(const string& strName)
{
m_pAnimation->Change(strName);
}
void CObj::SetDefaultAnimation(const string& strName)
{
m_pAnimation->SetDefault(strName);
}
CCollider* CObj::FindCollider(const string& strName)
{
auto iter = m_ColliderList.begin();
auto iterEnd = m_ColliderList.end();
for (; iter != iterEnd; ++iter)
{
if ((*iter)->GetName() == strName)
return *iter;
}
return nullptr;
}
void CObj::DeleteCollider(const string& strName)
{
auto iter = m_ColliderList.begin();
auto iterEnd = m_ColliderList.end();
for (; iter != iterEnd; ++iter)
{
if ((*iter)->GetName() == strName)
{
SAFE_DELETE((*iter));
m_ColliderList.erase(iter);
break;
}
}
}
|
697f4df8f8498c000272d199c41b07a5b678364b | d1c5c2a116c14d3ab073a38782468969020fa035 | /src/a.cpp | a9f570ed054ba2a8feebfa30bb66e835eb88e49b | [] | no_license | letranconghung/purePursuit | 67efe61b9122deacbe9989e4f1a8aa53a6f9f23d | 2b68abeca2cdef7acb2f75b79968a79441da86ad | refs/heads/master | 2023-03-04T09:04:30.456038 | 2021-02-03T16:05:09 | 2021-02-03T16:05:09 | 335,615,511 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,219 | cpp | a.cpp | #include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
#include <algorithm>
using namespace std;
#define INF 1e10
#define INFsmall 1/INF
#define MAX_POW 100
ofstream pathTextFile;
ofstream kinematicsTextFile;
/**
* class Node
* */
class Node{
private:
double x, y;
public:
Node(): x{0}, y{0}
{}
Node(double p_x, double p_y): x{p_x}, y{p_y}
{}
friend Node operator+(const Node &n1, const Node &n2);
friend Node operator-(const Node &n1, const Node &n2);
friend Node operator*(const Node &n, double val);
friend Node operator/(const Node &n, double val);
pair<double, double> getXY(){
return make_pair(x, y);
}
double getX(){
return x;
}
double getY(){
return y;
}
void setXY(double x, double y){
this -> x = x;
this -> y = y;
}
void print(){
printf("X: %.2f Y: %.2f\n", x, y);
}
double mag(){
return sqrt(pow(this-> x, 2) + pow(this-> y, 2));
}
Node norm(){
double mag = this->mag();
return {(this->x)/mag, (this->y)/mag};
}
};
Node operator+(const Node &n1, const Node &n2){
return {n1.x + n2.x, n1.y + n2.y};
}
Node operator-(const Node &n1, const Node &n2){
return {n1.x - n2.x, n1.y - n2.y};
}
Node operator*(const Node &n, double val){
return {n.x*val, n.y*val};
}
Node operator/(const Node &n, double val){
return {n.x/val, n.y/val};
}
/**
* Math utility functions
* */
double distance(Node n1, Node n2){
Node diff = n2 - n1;
return diff.mag();
}
double circumRad(Node n1, Node n2, Node n3){
double a = distance(n1, n2);
double b = distance(n2, n3);
double c = distance(n3, n1);
double denom = sqrt((a+b+c)*(b+c-a)*(c+a-b)*(a+b-c));
if(denom <= INFsmall) return INF;
else return a*b*c/denom;
}
/**
* Debugging utility functions
* */
void printVector(vector<double> vd){
for(auto m : vd){
printf("%.2f ", m);
}
cout << endl;
}
/**
* class Path
* */
class Path{
private:
vector<Node> wps;
vector<Node> injWps;
double spacing;
vector<Node> smoWps;
double w_data, w_smooth, tolerance;
vector<double> dist;
vector<double> curv;
vector<double> maxV;
double maxVel;
public:
Path(): wps{}, dist{}, maxV{}
{}
Path(vector<Node> p_wps): wps{p_wps}, dist{}, maxV{}
{}
void inject(){
injWps.clear();
for(int i = 0;i<=wps.size()-2;++i){
Node start = wps[i];
Node end = wps[i+1];
Node diff = end - start;
Node step = diff.norm()*spacing;
int nFit = ceil(diff.mag()/spacing);
for(int j = 0;j<nFit;++j){
injWps.push_back(start + step*j);
}
}
injWps.push_back(wps[wps.size()-1]);
}
void smooth(){
smoWps = injWps;
double change = tolerance;
while(change >= tolerance){
change = 0;
for(int i = 1;i<injWps.size()-1;++i){
Node aux = smoWps[i];
smoWps[i] = aux + (injWps[i] - smoWps[i])*w_data + (smoWps[i-1] + smoWps[i+1] - smoWps[i]*2)*w_smooth;
Node diff = smoWps[i] - aux;
change += (fabs(diff.getX()) + fabs(diff.getY()));
}
printf("change = %.5f\n", change);
}
}
void calcDist(){
Node prevWp = smoWps[0];
double prevDist = 0;
for(auto smoWp : smoWps){
double deltaDist = distance(smoWp, prevWp);
double newDist = prevDist + deltaDist;
dist.push_back(newDist);
prevDist = newDist;
prevWp = smoWp;
}
printVector(dist);
}
void calcCurvature(){
curv.push_back(INFsmall); //starting point
for (int i = 1;i<=smoWps.size()-2;++i){
double r = circumRad(smoWps[i-1], smoWps[i], smoWps[i+1]);
curv.push_back(1/r);
}
curv.push_back(INFsmall); //final point
}
void calcMaxV(double maxVel, double k){
for(int i = 0;i<smoWps.size();++i){
maxV.push_back(min(maxVel, k/curv[i]));
}
printVector(maxV);
}
void setWps(vector<Node> p_wps, double p_spacing, double p_w_data, double p_w_smooth, double p_tolerance, double p_maxVel, double p_k){
//perform injection and smooth
wps = p_wps;
spacing = p_spacing;
w_data = p_w_data;
w_smooth = p_w_smooth;
tolerance = p_tolerance;
maxVel = p_maxVel;
this->inject();
this->smooth();
this->calcDist();
this->calcCurvature();
this->calcMaxV(p_maxVel, p_k);
}
void outputPathToText(){
pathTextFile << spacing << ' ' << w_data << ' ' << w_smooth << '\t' << tolerance << ' ' << smoWps.size() << ' ' << wps.size() << '\n';
for(auto smoWp : smoWps){
pathTextFile << smoWp.getX() << ' ' << smoWp.getY() << '\n';
}
for(auto wp : wps){
pathTextFile << wp.getX() << ' ' << wp.getY() << '\n';
}
}
void outputKinematicsToText(){
for(int i = 0;i<smoWps.size();++i){
kinematicsTextFile << dist[i] << ' ' << maxV[i] << '\n';
}
}
};
int main(){
Path path;
pathTextFile.open("../txt/path.txt", ios::out | ios::trunc);
kinematicsTextFile.open("../txt/kinematics.txt", ios::out | ios::trunc);
/**
* initialization code
* */
path.setWps({{0, 0}, {90, 0}, {135, -50}},6, .25, .75, .001, 100, 0.5);
path.outputPathToText();
path.outputKinematicsToText();
/**
* finalization code
* */
pathTextFile.close();
kinematicsTextFile.close();
return 0;
} |
d0650c78c32c403f218acb762bf3bb332b13c976 | 1e8014bb81256091c4b33533e3d298c5354e98b5 | /src/WriteFile.h | 500a85fc87011906a032aac0e44412605c00f632 | [] | no_license | cheneeheng/KINECT | 3689e0459ffb6f903f5d483eaf0cf4a16061ac81 | b6c4308668e72aabc3fd00542db24ea267ca8454 | refs/heads/master | 2021-01-19T10:25:34.064421 | 2017-07-19T13:11:09 | 2017-07-19T13:11:09 | 82,189,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,916 | h | WriteFile.h | /*
* WriteFile.h
*
* Created on: Apr 18, 2017
* Author: chen
* Detail: Writing data to file.
*/
#ifndef WRITEFILE_H_
#define WRITEFILE_H_
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
#include "CGraph.h"
#include "CKB.h"
#include "algo.h"
#include <Eigen/Eigen>
/**
* Writes data to file.
*/
class WriteFile
{
public:
/**
* Constructor for class WriteFile.
*/
WriteFile();
/**
* Destructor for class WriteFile.
*/
virtual ~WriteFile();
/**
* Rewrites the labels in the original dataset to fill up holes or gaps
* in the labeling.
*
* @param path_ Path to file.
* @param data_ List of data from original file.
* @param points_ List of points.
* @param contact_ List of contact.
* @param face_ Updates the label for face.
* @param label_ref_write_ Points in label reference
* @param label_ref_name_ Name of label reference
* @param label_list_ List of label for actions taken
*/
void RewriteDataFile(
std::string path_,
std::vector<std::vector<std::string> > data_,
std::vector<Eigen::Vector4d> points_,
std::vector<int> contact_,
Eigen::Vector4d face_,
std::vector<Eigen::Vector3d> label_ref_write_,
std::vector<std::string> label_ref_name_,
std::vector<std::string> label_list_);
void RewriteDataFileFilter(
int curr_,
int mem_,
int mem2_,
int mem3_,
std::string &mem_s_,
std::string &mem_s2_,
std::string &mem_s3_,
std::vector<std::string> &label_);
void WriteFileLA(
CGraph *Graph_,
CKB *kb_,
std::string path_);
// void WriteFileLA(
// std::vector<std::string> line_,
// std::vector<std::vector<std::string> > data_tmp,
// std::string path_);
void WriteFileGraph(
CGraph *Graph_,
std::string path_);
void WriteFileWindow(
CGraph *Graph_,
std::string path_);
void WriteFileSurface(
std::string path_,
std::vector<Eigen::Matrix3d> rotation_,
std::vector<Eigen::Vector4d> planeeq_,
std::vector<Eigen::Vector3d> boxmin_,
std::vector<Eigen::Vector3d> boxmid_,
std::vector<Eigen::Vector3d> boxmax_);
void WriteOSTransition(
std::string path_,
std::map<std::string, std::vector<std::vector<int> > > transition_);
void WriteFilePrediction(
CGraph *Graph_,
CKB *kb_,
std::string path_,
std::vector<std::string> labels_,
std::vector<std::map<std::string, double> > goals_,
std::vector<std::map<std::string, double> > windows_);
void WriteFilePrediction(
CGraph *Graph_,
CKB *kb_,
std::string path_,
std::vector<std::string> labels_,
std::vector<std::string> labels_predict_,
std::vector<std::map<std::string, double> > goals_,
std::vector<std::map<std::string, double> > windows_);
void WriteFile_(
std::string path_,
std::vector<std::vector<double> > data_);
};
#endif /* WRITEFILE_H_ */
|
1f09378f350366239b733b8ac832ac7fbbc7d3be | e0feac125fb92c3d1834f9c9c89baf4ab9428fc6 | /ipdf/public/ipdf/Simple/SimpleDetectorResponse.h | 872eb7aa9f8843141ab89668426d9973fdca1494 | [] | no_license | AlexHarn/bfrv1_icetray | e6b04d04694376488cec93bb4b2d649734ae8344 | 91f939afecf4a9297999b022cea807dea407abe9 | refs/heads/master | 2022-12-04T13:35:02.495569 | 2020-08-27T22:14:40 | 2020-08-27T22:14:40 | 275,841,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,794 | h | SimpleDetectorResponse.h | #ifndef IPDF_SimpleDetectorResponse_H
#define IPDF_SimpleDetectorResponse_H
/**
copyright (C) 2004
the icecube collaboration
$Id$
@file SimpleDetectorResponse.h
@version $Revision: 1.3 $
@date $Date$
@author S Robbins <robbins@physik.uni-wuppertal.de>
*/
#include <vector>
namespace IPDF {
class SimpleHitOm;
/**
* @brief Basic implementation of the detector response.
*
* Basically is a container for the hit oms.
*/
class SimpleDetectorResponse {
public:
typedef std::vector<SimpleHitOm*>::const_iterator const_iterator;
typedef SimpleHitOm HitOm;
typedef SimpleHitOm value_type; // conform to STL
/// @brief Ctor from ipdf vector of native HitOms
explicit SimpleDetectorResponse(const std::vector<SimpleHitOm*> hitoms)
: hitoms_(hitoms) { }
/// @brief Ctor from an ipdf native HitOm
explicit SimpleDetectorResponse(SimpleHitOm* hitom)
: hitoms_(1,hitom) { }
/// @brief Dtor: destroys all the contained PEHits
~SimpleDetectorResponse() {
for(SimpleDetectorResponse::iterator hiter = hitoms_.begin();
hiter != hitoms_.end(); ++hiter) {
delete *hiter;
}
}
/// @brief Access an HitOm via a simple integer key
const SimpleHitOm& operator[](int ihit) const {
return *hitoms_[ihit];
}
/// @brief STL compliant iterator
const_iterator begin() const { return hitoms_.begin(); }
/// @brief STL compliant iterator
const_iterator end() const { return hitoms_.end(); }
/// @brief STL compliance
size_t size() const { return hitoms_.size(); }
/// @brief STL compliance
bool empty() const { return hitoms_.empty(); }
private:
typedef std::vector<SimpleHitOm*>::iterator iterator;
std::vector<SimpleHitOm*> hitoms_;
};
} // namespace IPDF
#endif // IPDF_SimpleDetectorResponse_H
|
86032f461a812713fc9bbf4afbf7effd21e31b29 | d761e11c779aea4677ecf8b7cbf28e0a401f6525 | /src/include/interval.hpp | 8e65fdf10412b6d975fe7f33c49f63d0fd1e8cf5 | [] | no_license | derrick0714/infer | e5d717a878ff51fef6c9b55c444c2448d85f5477 | 7fabf5bfc34302eab2a6d2867cb4c22a6401ca73 | refs/heads/master | 2016-09-06T10:37:16.794445 | 2014-02-12T00:09:34 | 2014-02-12T00:09:34 | 7,787,601 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,333 | hpp | interval.hpp | #ifndef INCLUDE_INTERVAL_HPP
#define INCLUDE_INTERVAL_HPP
/// \class interval interval.hpp
/// \brief Represents a range of data.
///
/// This class is used to represent a range of blocks on a digital media
/// source. In addition, the class also implements a set of operators that
/// can be used to easily compare block ranges. The block ranges created
/// and represented by interval are forward-looking. For example, [0, 10]
/// and [4, 4] are correct forward-looking ranges whereas [5, 2] is not.
/// See BlockLayout for more information.
///
/// \remark We could have used Boost Intervals but that seems to be little
/// too much for our current needs.
///
template <typename T>
class interval {
public:
/// \typedef T value_type
/// A type definition for the bounds of block range.
typedef T value_type;
/// Constructor
/// Default Constructor
interval()
:_begin(0),
_end(0)
{}
/// \param (br) An instance of interval.
/// \brief Copy constructor for interval class.
interval(const interval &br)
:_begin(br._begin),
_end(br._end)
{}
/// \name Accessors
/// Getter and setter methods for interval.
//@{
///
/// \param (b) Beginning of a block range.
/// \param (e) End of the block range.
/// \return Returns true when the bounds are assigned to the block range; False otherwise.
/// \brief Sets a new range.
bool set(const value_type &b, const value_type &e) {
if (e < b) {
return false;
}
_begin = b;
_end = e;
return true;
}
/// \return Returns the Block Id of the beginning of the block range.
/// \brief Retruns the Block Id of the beginning of the block range.
value_type begin() const {
return _begin;
}
/// \param (b) A beginning for block range.
/// \return Returns true once a valid beginning is set; False when (b) is invalid.
/// \brief Sets a new beginning for a block range given a valid beginning.
bool begin(const value_type &b) {
if (_end < b) {
return false;
}
_begin = b;
return true;
}
/// \return Returns the Block Id of the end of the block range.
/// \brief Retruns the Block Id of the end of the block range.
value_type end() const {
return _end;
}
/// \param (e) An end for block range.
/// \return Returns true once a valid end is set; False when (e) is invalid.
/// \brief Sets a new end for a block range given a valid end.
bool end(const value_type &e) {
if (e < _begin) {
return false;
}
_end = e;
return true;
}
//@}
bool contains(const value_type &v) const {
return _begin <= v && v <= _end;
}
/// \name Overloaded Operators
/// Arithmetic operators overloaded for a pair of intervals
//@{
/// \param (b) Another interval to assign.
/// \return Returns a reference to a newly assigned interval
/// instance.
/// \brief Implements the assignment operator for interval.
/* // shallow copy is ok here...use default assignment op.
interval& operator= (const interval& b) {
_begin = b._begin;
_end = b._end;
return *this;
}
*/
/// \param (b) Another interval to compare with.
/// \return Returns true when the entire block range (b) is behind
/// this block range; False otherwise.
/// \brief Implements the less-than operator on a pair of intervals.
///
/// Given two block ranges \f$[I_i, I_j], [I_k, I_l]\f$ this
/// operator returns true if and only if \f$I_j < I_k\f$; false
/// otherwise. In other words, it returns true if and only if the
/// entire interval \f$[I_i, I_j]\f$ is in front of interval
/// \f$[I_k, I_l]\f$.
bool operator< (const interval& b) const {
return _end < b._begin;
}
/// \param (b) Another interval to compare with.
/// \return Returns true when the entire block range (b) is in
/// front of this block range; False otherwise.
/// \brief Implements the greater-than operator on a pair of intervals.
///
/// Given two block ranges \f$[I_i, I_j], [I_k, I_l]\f$ this
/// operator returns true if and only if \f$I_i > I_l\f$; false
/// otherwise. In other words, it returns true if and only if the
/// entire interval \f$[I_i, I_j]\f$ is behind the interval
/// \f$[I_k, I_l]\f$.
bool operator> (const interval& b) const {
return _begin > b._end;
}
/// \param (b) Another interval to compare with.
/// \return Returns true when the block range (b)is exactly on top
/// of this block; False otherwise.
/// \brief Implements the equals operator on a pair of intervals.
///
/// Given two block ranges \f$[I_i, I_j], [I_k, I_l]\f$ this
/// operator returns true if and only if
/// \f$\left(\left(I_i == I_k\right) {\bf and} \left(I_j == I_l\right)\right)\f$;
/// false otherwise.
bool operator== (const interval& b) const {
return _begin == b._begin && _end == b._end;
}
/// \param (b) Another interval to compare with.
/// \return Returns true when the block range (b) is not on top of
/// this block range; False otherwise.
/// \brief Implements the equals operator on a pair of intervals.
///
/// Given two block ranges \f$[I_i, I_j], [I_k, I_l]\f$ this
/// operator returns true if and only if
/// \f$\left(\left(I_i != I_k\right) {\bf or } \left(I_j != I_l\right)\right)\f$;
/// false otherwise.
bool operator!= (const interval& b) const {
return ! (*this == b);
}
private:
value_type _begin; /// Beginning of the block range.
value_type _end; /// End of the block range.
};
#endif
|
77b56dbe54dd19d4a900843f5c7a997f690940c0 | 78b176820108bb5f6782a082a36a2cd48da5ef18 | /Modules/OpenGL/Public/Toon/OpenGL/OpenGLConfig.hpp | 3cab4e506e266ceba298533000e1624c0642a8ee | [
"MIT"
] | permissive | benjinx/Toon | b73f20e920991768179ae49413252ec41824b7f7 | f21032b2f9ad5fbc9a3618a7719c33159257d954 | refs/heads/main | 2023-03-31T07:04:51.115717 | 2021-03-28T22:51:42 | 2021-03-28T22:51:42 | 333,629,196 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 340 | hpp | OpenGLConfig.hpp | #ifndef TOON_OPENGL_CONFIG_HPP
#define TOON_OPENGL_CONFIG_HPP
#include <Toon/Config.hpp>
#if defined(TOON_OPENGL_EXPORT)
#define TOON_OPENGL_API TOON_API_EXPORT
#else
#define TOON_OPENGL_API TOON_API_IMPORT
#endif
#include <glad/gl.h>
#include <Toon/SDL2/SDL2Config.hpp>
#include <SDL_opengl.h>
#endif // TOON_OPENGL_CONFIG_HPP |
f105d2cd1f0a34a63cdf874b4970503e43e5e6d4 | dd6ff658ccd73f7ef8febbe348fe08c5d1112607 | /Programming2/week3/bubblesortarrays/bubblesortarrays/main.cpp | 67493f4c3d57d2dcb69a13a6f31671aba7fd4e87 | [] | no_license | tapickell/C--CPPcode | 96a7e75d62e0aa8d91744020be71bf2b6db3e1d9 | c5462a178dd431b11e84db0e820f02da32de49dd | refs/heads/master | 2020-04-15T01:34:16.410345 | 2012-08-16T00:29:17 | 2012-08-16T00:29:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,182 | cpp | main.cpp | //
// main.cpp
// bubblesortarrays
//
// Created by Todd Pickell on 4/4/12.
// Copyright (c) 2012 Columbia College. All rights reserved.
//
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
void bubbleSort(vector<int>&);
int main (int argc, const char * argv[])
{
cout << "Creating array." << endl;
int myArray[] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
cout << "Printing array: " << endl;
vector<int> myVector;
for (int i = 0; i < 10; i++) {
cout << myArray[i] << endl;
myVector.push_back(myArray[i]);
}
cout << "Tansfereing to vector." << endl;
cout << "Sorting vector using buble sort algorythim" << endl;
bubbleSort(myVector);
cout << "Printing vecotr contents after bubble sort: " << endl;
for (int i = 0; i < myVector.size(); i++) {
cout << myVector[i] << endl;
}
return 0;
}
void bubbleSort(vector<int> &stack)
{
int i;
for (i = 0; i < stack.size(); i++)
{
if((i < stack.size() - 1) && (stack[i] > stack[i + 1]))
{
int tmp = stack[i];
stack[i] = stack[i + 1];
stack[i + 1] = tmp;
i = -1;
}
}
}
|
c6884e023a3520e11f4523f061621d2a057e0c90 | c58ff0678da1382b3f4dabf22da345e48526d2c4 | /Source/USemLog/Private/Monitors/SLPickAndPlaceListener.cpp | 9f692a1d8ffbfb4b60ea6e584cacc7f7fb120188 | [
"LGPL-3.0-only"
] | permissive | Sanic/USemLog | 770fae2f7d76e867c20543253513dc1b09bee6cf | edb154d5b053ea17d10f637c573d794a00dfa3b3 | refs/heads/master | 2021-07-18T13:24:03.718895 | 2020-06-22T15:50:57 | 2020-06-22T15:50:57 | 181,447,490 | 0 | 0 | BSD-3-Clause | 2019-05-02T08:50:42 | 2019-04-15T08:45:04 | C++ | UTF-8 | C++ | false | false | 17,570 | cpp | SLPickAndPlaceListener.cpp | // Copyright 2017-2020, Institute for Artificial Intelligence - University of Bremen
// Author: Andrei Haidu (http://haidu.eu)
#include "SLPickAndPlaceListener.h"
#include "SLManipulatorListener.h"
#include "Animation/SkeletalMeshActor.h"
#include "SLEntitiesManager.h"
#include "GameFramework/PlayerController.h"
// Sets default values for this component's properties
USLPickAndPlaceListener::USLPickAndPlaceListener()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
bIgnore = false;
// State flags
bIsInit = false;
bIsStarted = false;
bIsFinished = false;
CurrGraspedObj = nullptr;
EventCheck = ESLPaPStateCheck::NONE;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_NONE;
/* PickUp */
bLiftOffHappened = false;
/* PutDown */
RecentMovementBuffer.Reserve(RecentMovementBufferSize);
}
// Dtor
USLPickAndPlaceListener::~USLPickAndPlaceListener()
{
if (!bIsFinished)
{
Finish(true);
}
}
// Init listener
bool USLPickAndPlaceListener::Init()
{
if (bIgnore)
{
return false;
}
if (!bIsInit)
{
// Init the semantic entities manager
if (!FSLEntitiesManager::GetInstance()->IsInit())
{
FSLEntitiesManager::GetInstance()->Init(GetWorld());
}
// Check that the owner is part of the semantic entities
SemanticOwner = FSLEntitiesManager::GetInstance()->GetEntity(GetOwner());
if (!SemanticOwner.IsSet())
{
UE_LOG(LogTemp, Error, TEXT("%s::%d Owner is not semantically annotated.."), *FString(__func__), __LINE__);
return false;
}
// Init state
EventCheck = ESLPaPStateCheck::NONE;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_NONE;
bIsInit = true;
return true;
}
return false;
}
// Start listening to grasp events, update currently overlapping objects
void USLPickAndPlaceListener::Start()
{
if (!bIsStarted && bIsInit)
{
// Subscribe for grasp notifications from sibling component
if(SubscribeForGraspEvents())
{
// Start update callback (will directly be paused until a grasp is active)
GetWorld()->GetTimerManager().SetTimer(UpdateTimerHandle, this, &USLPickAndPlaceListener::Update, UpdateRate, true);
GetWorld()->GetTimerManager().PauseTimer(UpdateTimerHandle);
// Mark as started
bIsStarted = true;
}
}
}
// Stop publishing grasp events
void USLPickAndPlaceListener::Finish(float EndTime, bool bForced)
{
if (!bIsFinished && (bIsInit || bIsStarted))
{
// Finish any active event
FinishActiveEvent(EndTime);
// Mark as finished
bIsStarted = false;
bIsInit = false;
bIsFinished = true;
}
}
// Subscribe for grasp events from sibling component
bool USLPickAndPlaceListener::SubscribeForGraspEvents()
{
if(USLManipulatorListener* Sibling = CastChecked<USLManipulatorListener>(
GetOwner()->GetComponentByClass(USLManipulatorListener::StaticClass())))
{
Sibling->OnBeginManipulatorGrasp.AddUObject(this, &USLPickAndPlaceListener::OnSLGraspBegin);
Sibling->OnEndManipulatorGrasp.AddUObject(this, &USLPickAndPlaceListener::OnSLGraspEnd);
return true;
}
return false;
}
// Get grasped objects contact shape component
ISLContactShapeInterface* USLPickAndPlaceListener::GetContactShapeComponent(AActor* Actor) const
{
if(Actor)
{
for (const auto& C : Actor->GetComponents())
{
if(C->Implements<USLContactShapeInterface>())
{
if(ISLContactShapeInterface* CSI = Cast<ISLContactShapeInterface>(C))
{
return CSI;
}
}
}
}
return nullptr;
}
// Called when grasp starts
void USLPickAndPlaceListener::OnSLGraspBegin(const FSLEntity& Self, AActor* Other, float Time, const FString& GraspType)
{
if(CurrGraspedObj)
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] Cannot set %s as grasped object.. manipulator is already grasping %s;"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), *Other->GetName(), *CurrGraspedObj->GetName());
return;
}
// Take into account only objects that have a contact shape component
if(ISLContactShapeInterface* CSI = GetContactShapeComponent(Other))
{
CurrGraspedObj = Other;
GraspedObjectContactShape = CSI;
//UE_LOG(LogTemp, Warning, TEXT("%s::%d [%f] %s set as grasped object.."),
// *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), *Other->GetName());
PrevRelevantLocation = Other->GetActorLocation();
PrevRelevantTime = GetWorld()->GetTimeSeconds();
if(GraspedObjectContactShape->IsSupportedBySomething())
{
EventCheck = ESLPaPStateCheck::Slide;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_Slide;
}
else
{
//UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] %s should be in a SupportedBy state.. aborting interaction.."),
// *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), *Other->GetName());
CurrGraspedObj = nullptr;
GraspedObjectContactShape = nullptr;
EventCheck = ESLPaPStateCheck::NONE;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_NONE;
return;
}
if(GetWorld()->GetTimerManager().IsTimerPaused(UpdateTimerHandle))
{
GetWorld()->GetTimerManager().UnPauseTimer(UpdateTimerHandle);
}
else
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] This should not happen, timer should have been paused here.."),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
}
}
else
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] %s does not have a ContactShapeInterface required to query the SupportedBy state.. aborting interaction.."),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), *Other->GetName());
}
}
// Called when grasp ends
void USLPickAndPlaceListener::OnSLGraspEnd(const FSLEntity& Self, AActor* Other, float Time)
{
if(CurrGraspedObj == nullptr)
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] This should not happen.. currently grasped object is nullptr while ending grasp with %s"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), *Other->GetName());
return;
}
if(CurrGraspedObj == Other)
{
CurrGraspedObj = nullptr;
GraspedObjectContactShape = nullptr;
EventCheck = ESLPaPStateCheck::NONE;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_NONE;
// Terminate active event
FinishActiveEvent(Time);
//UE_LOG(LogTemp, Warning, TEXT("%s::%d [%f] %s removed as grasped object.."),
// *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), *Other->GetName());
if(!GetWorld()->GetTimerManager().IsTimerPaused(UpdateTimerHandle))
{
GetWorld()->GetTimerManager().PauseTimer(UpdateTimerHandle);
}
else
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] This should not happen, timer should have been running here.."),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
}
}
else
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] End grasp with %s while %s is still grasped.. ignoring event.."),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), *Other->GetName(), *CurrGraspedObj->GetName());
}
}
// Object released, terminate active even
void USLPickAndPlaceListener::FinishActiveEvent(float CurrTime)
{
if(EventCheck == ESLPaPStateCheck::Slide)
{
//UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## SLIDE ############## [%f <--> %f]"),
// *FString(__func__), __LINE__, CurrTime, PrevRelevantTime, CurrTime);
OnManipulatorSlideEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, CurrTime);
}
else if(EventCheck == ESLPaPStateCheck::PickUp)
{
if(bLiftOffHappened)
{
//UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## PICK UP ############## [%f <--> %f]"),
// *FString(__func__), __LINE__, CurrTime, PrevRelevantTime, CurrTime);
OnManipulatorSlideEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, CurrTime);
bLiftOffHappened = false;
}
}
else if(EventCheck == ESLPaPStateCheck::TransportOrPutDown)
{
//TODO
}
CurrGraspedObj = nullptr;
EventCheck = ESLPaPStateCheck::NONE;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_NONE;
}
// Backtrace and check if a put-down event happened
bool USLPickAndPlaceListener::HasPutDownEventHappened(const float CurrTime, const FVector& CurrObjLocation, uint32& OutPutDownEndIdx)
{
OutPutDownEndIdx = RecentMovementBuffer.Num() - 1;
while(OutPutDownEndIdx > 0 && CurrTime - RecentMovementBuffer[OutPutDownEndIdx].Key < PutDownMovementBacktrackDuration)
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t\t\t [%f] [%f/%f] MinPutDownHeight"),
*FString(__func__), __LINE__,
GetWorld()->GetTimeSeconds(),
RecentMovementBuffer[OutPutDownEndIdx].Key,
RecentMovementBuffer[OutPutDownEndIdx].Value.Z - CurrObjLocation.Z,
MinPutDownHeight);
if(RecentMovementBuffer[OutPutDownEndIdx].Value.Z - CurrObjLocation.Z > MinPutDownHeight)
{
UE_LOG(LogTemp, Warning, TEXT("%s::%d [%f] \t\t\t\t PUT DOWN HAPPENED"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
return true;
}
OutPutDownEndIdx--;
}
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t\t\t\t PUT DOWN HAS NOT HAPPENED"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
return false;
}
// Update callback
void USLPickAndPlaceListener::Update()
{
// Call the state update function
(this->*UpdateFunctionPtr)();
}
/* Update functions*/
// Default update function
void USLPickAndPlaceListener::Update_NONE()
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] This should not happen.."), *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
}
// Check for slide events
void USLPickAndPlaceListener::Update_Slide()
{
if(CurrGraspedObj == nullptr || GraspedObjectContactShape == nullptr)
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] This should not happen.."), *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
return;
}
const FVector CurrObjLocation = CurrGraspedObj->GetActorLocation();
const float CurrTime = GetWorld()->GetTimeSeconds();
const float CurrDistXY = FVector::DistXY(PrevRelevantLocation, CurrObjLocation);
// Sliding events can only end when the object is not supported by the surface anymore
if(!GraspedObjectContactShape->IsSupportedBySomething())
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t\t **** END SupportedBy ****"), *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
// Check if enough distance and time has passed for a sliding event
if(CurrDistXY > MinSlideDistXY && CurrTime - PrevRelevantTime > MinSlideDuration)
{
const float ExactSupportedByEndTime = GraspedObjectContactShape->GetLastSupportedByEndTime();
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## SLIDE ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PrevRelevantTime, ExactSupportedByEndTime);
// Broadcast event
OnManipulatorSlideEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, ExactSupportedByEndTime);
// Only update if they were part of the sliding event
PrevRelevantTime = ExactSupportedByEndTime;
PrevRelevantLocation = CurrObjLocation;
}
bLiftOffHappened = false;
EventCheck = ESLPaPStateCheck::PickUp;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_PickUp;
}
}
// Check for pick-up events
void USLPickAndPlaceListener::Update_PickUp()
{
const FVector CurrObjLocation = CurrGraspedObj->GetActorLocation();
const float CurrTime = GetWorld()->GetTimeSeconds();
if(!GraspedObjectContactShape->IsSupportedBySomething())
{
if(bLiftOffHappened)
{
if(CurrObjLocation.Z - LiftOffLocation.Z > MaxPickUpHeight ||
FVector::DistXY(LiftOffLocation, CurrObjLocation) > MaxPickUpDistXY)
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## PICK UP ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PrevRelevantTime, CurrTime);
// Broadcast event
OnManipulatorPickUpEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, CurrTime);
// Start checking for the next possible events
bLiftOffHappened = false;
PrevRelevantTime = CurrTime;
PrevRelevantLocation = CurrObjLocation;
EventCheck = ESLPaPStateCheck::TransportOrPutDown;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_TransportOrPutDown;
}
}
else if(CurrObjLocation.Z - PrevRelevantLocation.Z > MinPickUpHeight)
{
UE_LOG(LogTemp, Warning, TEXT("%s::%d [%f] \t **** LiftOFF **** \t\t\t\t\t\t\t\t LIFTOFF"), *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
// This is not going to be the start time of the PickUp event, we use the SupportedBy end time
// we save the LiftOffLocation to check against the ending of the PickUp event by comparing distances against
bLiftOffHappened = true;
LiftOffLocation = CurrObjLocation;
}
else if(FVector::DistXY(LiftOffLocation, PrevRelevantLocation) > MaxPickUpDistXY)
{
UE_LOG(LogTemp, Warning, TEXT("%s::%d [%f] \t **** Skip PickUp **** \t\t\t\t\t\t\t\t SKIP PICKUP"), *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
EventCheck = ESLPaPStateCheck::TransportOrPutDown;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_TransportOrPutDown;
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("%s::%d [%f] \t\t **** START SupportedBy ****"), *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
if(bLiftOffHappened)
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## PICK UP ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PrevRelevantTime, CurrTime);
OnManipulatorPickUpEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, CurrTime);
}
// Start checking for next event
PrevRelevantTime = CurrTime;
PrevRelevantLocation = CurrObjLocation;
EventCheck = ESLPaPStateCheck::Slide;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_Slide;
}
}
// Check for put-down or transport events
void USLPickAndPlaceListener::Update_TransportOrPutDown()
{
const float CurrTime = GetWorld()->GetTimeSeconds();
const FVector CurrObjLocation = CurrGraspedObj->GetActorLocation();
if(GraspedObjectContactShape->IsSupportedBySomething())
{
UE_LOG(LogTemp, Warning, TEXT("%s::%d [%f] \t\t **** START SupportedBy ****"), *FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
// Check for the PutDown movement start time
uint32 PutDownEndIdx = 0;
if(HasPutDownEventHappened(CurrTime, CurrObjLocation, PutDownEndIdx))
{
float PutDownStartTime = -1.f;
while(PutDownEndIdx > 0)
{
// Check when the
if(RecentMovementBuffer[PutDownEndIdx].Value.Z - CurrObjLocation.Z > MaxPutDownHeight
|| FVector::Distance(RecentMovementBuffer[PutDownEndIdx].Value, CurrObjLocation) > MaxPutDownDistXY)
{
PutDownStartTime = RecentMovementBuffer[PutDownEndIdx].Key;
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## TRANSPORT ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PrevRelevantTime, PutDownStartTime);
OnManipulatorTransportEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, PutDownStartTime);
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## PUT DOWN ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PutDownStartTime, CurrTime);
OnManipulatorPutDownEvent.Broadcast(SemanticOwner, CurrGraspedObj, PutDownStartTime, CurrTime);
break;
}
PutDownEndIdx--;
}
// If the limits are not crossed in the buffer the oldest available time is used (TODO, or should we ignore the action?)
if(PutDownStartTime < 0)
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] The limits were not crossed in the available data in the buffer, the oldest available time is used"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds());
PutDownStartTime = RecentMovementBuffer[0].Key;
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## TRANSPORT ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PrevRelevantTime, PutDownStartTime);
OnManipulatorPutDownEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, PutDownStartTime);
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## PUT DOWN ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PutDownStartTime, CurrTime);
OnManipulatorPutDownEvent.Broadcast(SemanticOwner, CurrGraspedObj, PutDownStartTime, CurrTime);
}
}
else
{
UE_LOG(LogTemp, Error, TEXT("%s::%d [%f] \t ############## TRANSPORT ############## [%f <--> %f]"),
*FString(__func__), __LINE__, GetWorld()->GetTimeSeconds(), PrevRelevantTime, CurrTime);
OnManipulatorTransportEvent.Broadcast(SemanticOwner, CurrGraspedObj, PrevRelevantTime, CurrTime);
}
RecentMovementBuffer.Reset(RecentMovementBufferSize);
PrevRelevantTime = CurrTime;
PrevRelevantLocation = CurrObjLocation;
EventCheck = ESLPaPStateCheck::Slide;
UpdateFunctionPtr = &USLPickAndPlaceListener::Update_Slide;
}
else
{
// Cache recent movements
if(RecentMovementBuffer.Num() > 1)
{
RecentMovementBuffer.Push(TPair<float, FVector>(CurrTime, CurrObjLocation));
// Remove values older than RecentMovementBufferDuration
int32 Count = 0;
while(RecentMovementBuffer.Last().Key - RecentMovementBuffer[Count].Key > RecentMovementBufferDuration)
{
Count++;
}
if(Count > 0)
{
RecentMovementBuffer.RemoveAt(0, Count, false);
}
}
else
{
RecentMovementBuffer.Push(TPair<float, FVector>(CurrTime, CurrObjLocation));
}
}
}
|
a7daadc453848a32ef2ce4cbfade54496af17ce2 | aff9e12bed9141a93662dd4cddb4aa2593bcbc32 | /common/mongoproxy/mongoproxy.cpp | 92f287c4db8b8c3e427a3f7e6e68628d4a08ed82 | [
"BSD-3-Clause"
] | permissive | flycloud123/darkforce | c92ac1837e05c7bc1f8bf82ec456c55b435963b7 | 4e76d659952d3a864eb0ef96bfb099004736923f | refs/heads/master | 2021-01-18T06:14:33.717779 | 2015-08-02T00:14:44 | 2015-08-02T00:14:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,494 | cpp | mongoproxy.cpp | /*
* mongoproxy.cpp
*
* Created on: 2015-3-31
* Author: qianqians
*/
#include "mongoproxy.h"
namespace Fossilizid{
namespace mongoproxy{
dbproxy::dbproxy(boost::shared_ptr<config::config> _config){
mongoc_init();
mongoc_uri_t * _uri = mongoc_uri_new_for_host_port(_config->get_value_string("ip").c_str(), _config->get_value_int("port"));
_client = mongoc_client_new(mongoc_uri_get_string(_uri));
mongoc_uri_destroy(_uri);
_db = mongoc_client_get_database(_client, _config->get_value_string("db").c_str());
}
dbproxy::~dbproxy(){
for(auto it : collectiondict){
mongoc_collection_destroy(it.second);
}
mongoc_database_destroy(_db);
mongoc_client_destroy(_client);
mongoc_cleanup();
}
mongoc_collection_t * dbproxy::get_collection(std::string collection_name){
auto it = collectiondict.find(collection_name);
if (it != collectiondict.end()){
return it->second;
}
return mongoc_database_get_collection(_db, collection_name.c_str());
}
bool dbproxy::create_index(std::string collection_name, const bson_t * keys, const mongoc_index_opt_t *opt, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection_name);
return mongoc_collection_create_index(_c, keys, opt, error);
}
bool dbproxy::drop_index (std::string collection, const std::string index_name, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_drop_index(_c, index_name.c_str(), error);
}
mongoc_cursor_t * dbproxy::find_indexes(std::string collection, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_find_indexes(_c, error);
}
int64_t dbproxy::count(std::string collection_name, mongoc_query_flags_t flags, const bson_t * query, int64_t skip, int64_t limit, const mongoc_read_prefs_t * read_prefs, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection_name);
return mongoc_collection_count(_c, flags, query, skip, limit, read_prefs, error);
}
bool dbproxy::insert(std::string collection, mongoc_insert_flags_t flags, const bson_t * document, const mongoc_write_concern_t * write_concern, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_insert(_c, flags, document, write_concern, error);
}
bool dbproxy::save(std::string collection, const bson_t * document, const mongoc_write_concern_t * write_concern, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_save(_c, document, write_concern, error);
}
bool dbproxy::update (std::string collection, mongoc_update_flags_t flags, const bson_t * selector, const bson_t * update, const mongoc_write_concern_t * write_concern, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_update(_c, flags, selector, update, write_concern, error);
}
bool dbproxy::remove(std::string collection, mongoc_remove_flags_t flags, const bson_t * selector, const mongoc_write_concern_t * write_concern, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_remove(_c, flags, selector, write_concern, error);
}
mongoc_cursor_t * dbproxy::find(std::string collection, mongoc_query_flags_t flags, uint32_t skip, uint32_t limit, uint32_t batch_size, const bson_t * query, const bson_t * fields, const mongoc_read_prefs_t * read_prefs){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_find(_c, flags, skip, limit, batch_size, query, fields, read_prefs);
}
bool dbproxy::find_and_modify(std::string collection, const bson_t * query, const bson_t * sort, const bson_t * update, const bson_t * fields, bool _remove, bool upsert, bool _new, bson_t * reply, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_find_and_modify(_c, query, sort, update, fields, _remove, upsert, _new, reply, error);
}
bool dbproxy::validate(std::string collection, const bson_t * options, bson_t * reply, bson_error_t * error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_validate(_c, options, reply, error);
}
bool dbproxy::stats(std::string collection, const bson_t *options, bson_t *reply, bson_error_t *error){
mongoc_collection_t * _c = get_collection(collection);
return mongoc_collection_stats(_c, options, reply, error);
}
} /* namespace mongoproxy */
} /* namespace Fossilizid */
|
ddf0e83d56082827f6d96a6c61a7b6b80fc520fa | ad257f133577d639e1e197d3909be3674d4a5c1d | /HashTable.cpp | 5825527eb9d3d03bca571b0ee19abf99062ab637 | [] | no_license | wyuhuang/data_structure_poker | e786136ad43e55ebbf87ad3281ebdfcbf03c5c51 | 751071c5b944f2f6da6d72a6552d5f32ac28c47f | refs/heads/main | 2023-01-20T20:00:26.703953 | 2020-12-04T08:33:13 | 2020-12-04T08:33:13 | 318,122,607 | 3 | 2 | null | 2020-12-04T08:33:15 | 2020-12-03T08:17:59 | C++ | GB18030 | C++ | false | false | 1,077 | cpp | HashTable.cpp | #include"HashTable.h"
#include<iostream>
using namespace std;
HashTable::HashTable()
{
for (int i = 0; i < MaxSize; i++)
{
ht[i] = nullptr;
}
}
HashTable :: ~HashTable( )
{
HashNode *p = nullptr, *q = nullptr;
for (int i = 0; i < MaxSize; i++)
{
p = q = ht[i];
while (p != nullptr)
{
p = p->next;
delete q;
q = p;
}
}
}
int HashTable :: H(int k)
{
return k % 22;
}
string HashTable :: SearchName(int k)
{
int j = H(k); //计算散列地址
string name = " ";
HashNode *p = ht[j]; //工作指针p初始化
if(p != nullptr){
while (p != nullptr)
{
// cout<<p->data<<endl;
name += p->data;
if(p->next != nullptr){
name += " & " ;
}
p = p->next;
}
return name;
}
else{
return "无名字";
}
}
void HashTable :: Insert(int k,string name)
{
int j = H(k); //计算散列地址
// cout<<j<<endl;
HashNode *p = ht[j]; //工作指针p初始化
p = new HashNode;
p->data = name;
// cout<<p->data<<endl;
p->next = ht[j];
ht[j] = p;
}
|
6edc52678ffcd86bfe63db48677ac4e126efa175 | 30150c1a4a99608aab496570e172bdce4c53449e | /077_OOP_class_across_files_multifile_comp/main.cpp | aa8e65cdfd3884e7deb63e4e55a1260bf8fcbe97 | [] | no_license | gergokutu/cplusplus-tutorials | 88334ba9b1aa8108109796d69ab5e8dd94da62c6 | 11e9c15f6c4e06b8e97ce77a732aec460d0251eb | refs/heads/master | 2020-09-04T17:46:03.954635 | 2020-01-14T11:44:15 | 2020-01-14T11:44:15 | 219,837,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 231 | cpp | main.cpp | #include <iostream>
// only main() statys here
#include "user.h"
int main()
{
User user1("Gergo", "Kovacs", "Platinum");
std::cout << user1 << std::endl;
User user2;
std::cin >> user2;
std::cout << user2 << std::endl;
} |
8ba6472df3f3d4a8ba16db818a159792c6c89aa1 | 018eac278e23bf4611b1b5d4aa0ac106dff8238b | /problem/poj 2253 Frogger(二分or最短路).cpp | 6dea3447bbf1a07263d3bb1b22f7e325e421b352 | [] | no_license | qian99/acm | 250294b153455913442d13bb5caed1a82cd0b9e3 | 4f88f34cbd6ee33476eceeeec47974c1fe2748d8 | refs/heads/master | 2021-01-11T17:38:56.835301 | 2017-01-23T15:00:46 | 2017-01-23T15:00:47 | 79,812,471 | 3 | 2 | null | null | null | null | GB18030 | C++ | false | false | 4,168 | cpp | poj 2253 Frogger(二分or最短路).cpp | //二分答案,bfs验证
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
#define eps 1e-9
#define pi acos(-1.0)
using namespace std;
typedef long long ll;
const int maxn=200+10;
const int maxm=maxn*maxn;
struct Point
{
int x,y;
};
struct Edge
{
int v,next;
double w;
};
Edge edges[maxm<<1];
int head[maxn],nEdge,n;
bool vis[maxn];
void AddEdge(int u,int v,double w)
{
nEdge++;
edges[nEdge].v=v;
edges[nEdge].w=w;
edges[nEdge].next=head[u];
head[u]=nEdge;
}
double Len(Point a,Point b)
{
return sqrt((double)(a.x-b.x)*(a.x-b.x)+(double)(a.y-b.y)*(a.y-b.y));
}
Point pt[maxn];
bool test(double maxl)
{
memset(vis,0,sizeof(vis));
vis[1]=true;
queue<int>q;
q.push(1);
while(!q.empty())
{
int u=q.front();q.pop();
for(int k=head[u];k!=-1;k=edges[k].next)
{
int v=edges[k].v;
if(vis[v]) continue;
if(edges[k].w<=maxl)
{
vis[v]=true;
q.push(v);
}
}
}
return vis[2];
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int tcase=0;
while(~scanf("%d",&n))
{
if(n==0) break;
tcase++;
memset(head,0xff,sizeof(head));
nEdge=-1;
for(int i=1;i<=n;++i)
scanf("%d%d",&pt[i].x,&pt[i].y);
for(int i=1;i<=n;++i)
for(int j=i+1;j<=n;++j)
{
double w=Len(pt[i],pt[j]);
AddEdge(i,j,w);
AddEdge(j,i,w);
}
double L=0,R=2000;
while(R-L>eps)
{
double m=(L+R)/2;
if(test(m))
R=m;
else
L=m;
}
printf("Scenario #%d\n",tcase);
printf("Frog Distance = %.3lf\n\n",L);
}
return 0;
}
//spfa,d[u]为到u点至少需要的弹跳距离
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
#define eps 1e-9
#define pi acos(-1.0)
using namespace std;
typedef long long ll;
const int maxn=200+10;
const int maxm=maxn*maxn;
struct Point
{
int x,y;
};
struct Edge
{
int v,next;
double w;
};
Edge edges[maxm<<1];
int head[maxn],nEdge,n;
bool inq[maxn];
double d[maxn];
void AddEdge(int u,int v,double w)
{
nEdge++;
edges[nEdge].v=v;
edges[nEdge].w=w;
edges[nEdge].next=head[u];
head[u]=nEdge;
}
double Len(Point a,Point b)
{
return sqrt((double)(a.x-b.x)*(a.x-b.x)+(double)(a.y-b.y)*(a.y-b.y));
}
Point pt[maxn];
double spfa()
{
memset(inq,0,sizeof(inq));
for(int i=1;i<=n;++i) d[i]=inf;
d[1]=0;
queue<int>q;
q.push(1);
while(!q.empty())
{
int u=q.front();q.pop();
inq[u]=false;
for(int k=head[u];k!=-1;k=edges[k].next)
{
int v=edges[k].v;
double tmp=max(d[u],edges[k].w);
if(d[v]>tmp)
{
d[v]=tmp;
if(!inq[v]){inq[v]=true;q.push(v);}
}
}
}
return d[2];
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int tcase=0;
while(~scanf("%d",&n))
{
if(n==0) break;
tcase++;
memset(head,0xff,sizeof(head));
nEdge=-1;
for(int i=1;i<=n;++i)
scanf("%d%d",&pt[i].x,&pt[i].y);
for(int i=1;i<=n;++i)
for(int j=i+1;j<=n;++j)
{
double w=Len(pt[i],pt[j]);
AddEdge(i,j,w);
AddEdge(j,i,w);
}
printf("Scenario #%d\n",tcase);
printf("Frog Distance = %.3lf\n\n",spfa());
}
return 0;
}
|
24202cec671837385d6f2fb31ce30d7d99de3df0 | a590cced3398b778443d8f830c7ea2dfc19e8523 | /Compilers/82014/targets/postfix_writer.h | a0bee1b441f0e4dfe6a290f4c6a9409776b00c51 | [] | no_license | meiraxx/bachelors-projects | ebe547bf1ca6e6b54354fe69914269ac4cb7419f | 79ca74aee565ecbfe0d69f54ee317b0867ffa51b | refs/heads/master | 2022-03-02T23:18:48.095678 | 2019-07-16T15:44:32 | 2019-07-16T15:44:32 | 197,222,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,081 | h | postfix_writer.h | #ifndef __XPL_SEMANTICS_PF_WRITER_H__
#define __XPL_SEMANTICS_PF_WRITER_H__
#include <string>
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <cdk/symbol_table.h>
#include <cdk/emitters/basic_postfix_emitter.h>
#include "targets/basic_ast_visitor.h"
#include "targets/body_args_size.h"
#include "targets/symbol.h"
namespace xpl {
//!
//! Traverse syntax tree and generate the corresponding assembly code.
//!
class postfix_writer: public basic_ast_visitor {
cdk::symbol_table<xpl::symbol> &_symtab;
cdk::basic_postfix_emitter &_pf;
int _lbl;
// functions/vardecls variables
std::string *_thisId; // the global id in which we are going to place the value of the variable
std::shared_ptr<symbol> _thisFunction; // the function where a variable or/and its value are being declared
int _thisFunctionEnd; // global variable so that 'return' knows where to jump back after being called
int _thisVarOffset = 0; // this represents the current offset of BOTH the FramePointer and InstructionPointer at multiple lines of postfix_writer.cpp in a function
// global sweep variables:
int _lbl_sweep_increment;
int _lbl_sweep_end;
// specialFunctionsVector
public:
std::vector<std::string> _specialFunctionsVector;
public:
postfix_writer(std::shared_ptr<cdk::compiler> compiler, cdk::symbol_table<xpl::symbol> &symtab,
cdk::basic_postfix_emitter &pf) :
basic_ast_visitor(compiler), _symtab(symtab), _pf(pf), _lbl(0) {
}
public:
~postfix_writer() {
os().flush();
}
private:
/** Method used to generate sequential labels. */
inline std::string mklbl(int lbl) {
std::ostringstream oss;
if (lbl < 0)
oss << ".L" << -lbl;
else
oss << "_L" << lbl;
return oss.str();
}
/*
inline int call_new_visitor(xpl::fundef_node * const node, int lvl){
int alloc_size = 0;
xpl::body_args_size * visitor = new xpl::body_args_size(_compiler); // new visitor that calculates total size of variables to declare within function body
node->accept(visitor, lvl);
alloc_size = visitor->allocSize();
delete visitor;
}*/
public:
void do_sequence_node(cdk::sequence_node * const node, int lvl);
public:
void do_integer_node(cdk::integer_node * const node, int lvl);
void do_double_node(cdk::double_node * const node, int lvl);
void do_string_node(cdk::string_node * const node, int lvl);
public:
void do_neg_node(cdk::neg_node * const node, int lvl);
public:
void do_add_node(cdk::add_node * const node, int lvl);
void do_sub_node(cdk::sub_node * const node, int lvl);
void do_mul_node(cdk::mul_node * const node, int lvl);
void do_div_node(cdk::div_node * const node, int lvl);
void do_mod_node(cdk::mod_node * const node, int lvl);
void do_lt_node(cdk::lt_node * const node, int lvl);
void do_le_node(cdk::le_node * const node, int lvl);
void do_ge_node(cdk::ge_node * const node, int lvl);
void do_gt_node(cdk::gt_node * const node, int lvl);
void do_ne_node(cdk::ne_node * const node, int lvl);
void do_eq_node(cdk::eq_node * const node, int lvl);
public:
void do_identifier_node(cdk::identifier_node * const node, int lvl);
void do_rvalue_node(cdk::rvalue_node * const node, int lvl);
void do_assignment_node(cdk::assignment_node * const node, int lvl);
public:
void do_evaluation_node(xpl::evaluation_node * const node, int lvl);
void do_print_node(xpl::print_node * const node, int lvl);
void do_read_node(xpl::read_node * const node, int lvl);
public:
void do_while_node(xpl::while_node * const node, int lvl);
void do_if_node(xpl::if_node * const node, int lvl);
void do_if_else_node(xpl::if_else_node * const node, int lvl);
// new methods
void do_sweep_node(xpl::sweep_node * const node, int lvl);
void do_stop_node(xpl::stop_node * const node, int lvl);
void do_next_node(xpl::next_node * const node, int lvl);
void do_return_node(xpl::return_node * const node, int lvl);
void do_block_node(xpl::block_node * const node, int lvl);
void do_indexer_node(xpl::indexer_node * const node, int lvl);
void do_vardecl_node(xpl::vardecl_node * const node, int lvl);
void do_body_node(xpl::body_node * const node, int lvl);
void do_fundecl_node(xpl::fundecl_node * const node, int lvl);
void do_fundef_node(xpl::fundef_node * const node, int lvl);
void do_funcall_node(xpl::funcall_node * const node, int lvl);
void do_memaddr_node(xpl::memaddr_node * const node, int lvl);
void do_memalloc_node(xpl::memalloc_node * const node, int lvl);
void do_identity_node(xpl::identity_node * const node, int lvl);
void do_and_node(cdk::and_node * const node, int lvl);
void do_or_node(cdk::or_node * const node, int lvl);
void do_not_node(cdk::not_node * const node, int lvl);
};
} // xpl
#endif |
53c09e494287962ee511bc4a297aef5a3af6f5be | 767276ba2e1ef439eaadcbe4b347f5f3187f68e9 | /CppFBPCore/Services/thzpush.cpp | 9a3793488f63b72b2aba061043742214953347dd | [
"Artistic-2.0"
] | permissive | jpaulm/cppfbp | 0274a34981e9f1489bacc4188320b4389c715ee3 | ba13fde16956296c767083e91ff820df9076ee7f | refs/heads/master | 2021-07-19T17:38:53.858865 | 2021-02-18T15:35:01 | 2021-02-18T15:35:01 | 23,405,424 | 66 | 16 | Artistic-2.0 | 2020-07-01T22:37:00 | 2014-08-27T21:05:32 | C | UTF-8 | C++ | false | false | 1,094 | cpp | thzpush.cpp | //#include <setjmp.h>
#include <stdio.h>
//#include <malloc.h>
#include <string.h>
#include "thzcbs.h"
#include "cppfbp.h"
int thzpush(Process *pptr, void **ptr)
{
IPh *IPptr;
//IPh *optr;
// IPh *qptr;
IP *tptr;
if (pptr -> trace) MSG1("%s Push start\n", pptr -> procname);
IPptr = (IPh *) *ptr - 1; /* back up size of header */
tptr = (IP *)IPptr;
if (tptr -> datapart[IPptr -> IP_size] != guard_value)
MSG1("Guard byte corrupted: '%s'\n", pptr->procname);
if (IPptr -> owner != pptr)
MSG1("IP header corrupted: '%s'\n", pptr->procname);
if (IPptr -> on_stack)
MSG1("IP on stack: '%s'\n", pptr->procname);
//optr = IPptr -> prev_IP;
//qptr = IPptr -> next_IP;
// if (optr != 0)
// optr -> next_IP = qptr;
// else
// pptr -> first_owned_IP = qptr;
// if (qptr != 0)
// qptr -> prev_IP = optr;
IPptr -> next_IP = pptr -> stack;
pptr -> stack = IPptr;
IPptr -> on_stack = TRUE;
if (pptr -> trace) MSG1("%s Push end\n",pptr -> procname);
*ptr = 0;
pptr -> owned_IPs--;
return(0);
}
|
8d80164f2a2c607eef9ac4a74bd4c8d3d4c31a76 | aea5a5cdf8ef4b7b62671e6fa237085568e06045 | /Lot.h | d276b2ceeb9f3e1a7acc3b17913db346309871fe | [] | no_license | whelanc5/Vehicle-detection | 9d11ba82e6f09d1aa1ec80a60533dc8b7029bcbe | 2192e4d726cbf7457660267c7c4f1d0866dd6a3f | refs/heads/master | 2021-07-24T19:12:22.802200 | 2017-10-31T03:46:59 | 2017-10-31T03:46:59 | 89,098,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | h | Lot.h | #pragma once
#ifndef MY_LOT
#define MY_LOT
#include<opencv2/core/core.hpp>
#include<iostream>
#include <fstream>
#include "Feed.h"
class Lot {
private:
//feed pointer vector, holds pointers to the Feed objects
std::vector<Feed *> feed_list;
//name of the lot
cv::String Lot_name;
//maximum capacity of the lot
cv::String capacity;
int lotCount = 0;
std::string id;
// function prototypes ////////////////////////////////////////////////////////////////////////////
public:
//constructor for Lot, takes string for the name and string for the capacity, and a string for the lotid
Lot(cv::String lotname, cv::String cap, cv::String lotid);
void addFeed(Feed feed); // allows you to add feeds
//allows to remove feeds
bool removeFeedAt(int index);
//returns the feeds within the lot
std::vector<Feed *> getFeeds();
void runFeeds();//makes the feeds run
//returns the name of the lot
cv::String getName();
//returns count for the lot
//int getCount();
std::string getCount();
//returns capacity
cv::String getCap();
//returns lot id
cv::String getId();
};
#endif
|
136279351ee944b3a23aa01b69b0c5713a011db4 | 4ed1029e771c426b8293d0f869c92c3e4070ccc7 | /bav_a10a_dis/config.cpp | 38afc7d7fa4e443606c417c15b45df32e1439472 | [] | no_license | Armaopterix/NTF-Modset | 59ffb7ec90f22c2cc484a063a206042c23f1dcac | 3aed27bbd569e81531de10eaa90c3b40548953bd | refs/heads/master | 2021-08-23T11:26:39.640870 | 2017-12-03T11:15:36 | 2017-12-03T11:15:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,479 | cpp | config.cpp | #define TEast 0
#define TWest 1
#define TGuerrila 2
#define TCivilian 3
#define TSideUnknown 4
#define TEnemy 5
#define TFriendly 6
#define TLogic 7
#define true 1
#define false 0
#define private 0
#define protected 1
#define public 2
class CfgPatches
{
class bav_A10A_dis
{
units[] = {"FIR_A10A","FIR_A10A_74fs","FIR_A10A_MD","FIR_A10A_47fs","FIR_A10A_Blank","FIR_A10A_Camo1","FIR_A10A_Camo2"};
weapons[] = {};
requiredVersion = 1.0;
requiredAddons[] = {"FIR_AirWeaponSystem_US","A3_Air_F_Beta","FIR_A10A_F"};
};
};
class CfgVehicles
{
class Logic;
class Module_F: Logic
{
class ArgumentsBaseUnits
{
class Units;
};
class ModuleDescription
{
class AnyBrain;
};
};
class thingX;
class Motorcycle;
class Air ;
class Plane : Air
{
class NewTurret ;
class ViewPilot ;
class HitPoints
{
class HitHull;
};
};
class Plane_Base_F : Plane
{
class AnimationSources;
class Components;
};
class Plane_CAS_01_base_F : Plane_Base_F{};
class FIR_A10A_Base : Plane_CAS_01_base_F
{
scope = 1;
};
class FIR_A10A : FIR_A10A_Base
{
scope = 1;
};
class FIR_A10A_Standard : FIR_A10A
{
scope = 1;
};
class FIR_A10A_74fs : FIR_A10A
{
scope = 1;
};
class FIR_A10A_47fs : FIR_A10A
{
scope = 1;
};
class FIR_A10A_MD : FIR_A10A
{
scope = 1;
};
class FIR_A10A_Blank : FIR_A10A
{
scope = 1;
};
class FIR_A10A_Camo1 : FIR_A10A
{
scope = 1;
};
class FIR_A10A_Camo2 : FIR_A10A
{
scope = 1;
};
};
|
8bee46b4565065989416ef4ae050a8007a833737 | 29a565527676d3ebb9200b11c95a188bde85ce94 | /PuzzleGame/main.cpp | 79b6591e4709082ec248d67cb1aaf4c3301e718f | [
"MIT"
] | permissive | CDHL/PuzzleGame | 3ed05357a64cf8f0ac8a57e301921c6a4b2acebe | eaf0378ad02643e18645d2b79814ca5b4c8d948c | refs/heads/master | 2023-06-08T01:08:01.844376 | 2023-05-28T14:17:45 | 2023-05-28T14:17:45 | 160,944,244 | 7 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,495 | cpp | main.cpp | #include "stdafx.h"
#include <cstdlib>
#include <ctime>
#include "draw.h"
#include "resource.h"
#include "window.h"
int WINAPI _tWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ PTSTR pCmdLine,
_In_ int nCmdShow
)
{
// 使用时间作为rand的种子
srand(static_cast<unsigned int>(time(NULL)));
// 初始化COM库
if (FAILED(CoInitialize(NULL)))
{
return 0;
}
// Register the window class.
const TCHAR CLASS_NAME[] = _T("PuzzleGame Window Class");
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
g_hWnd = CreateWindowEx(
0, // Optional window styles
CLASS_NAME, // Window class
_T("Puzzle Game"), // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (g_hWnd == NULL)
{
return 0;
}
ShowWindow(g_hWnd, nCmdShow);
UpdateWindow(g_hWnd);
// Run the message loop.
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 取消初始化COM库
CoUninitialize();
return (int)msg.wParam;
}
|
7dac0354c273b5b535d05e82fe5cc5f126f8c5e5 | ab784073a4924bad0b996234537625b4d3371191 | /src/nomadlda/sparse_matrix.h | 9f453e60faae542f6c6994e38b7ee932195de943 | [
"BSD-3-Clause"
] | permissive | francktcheng/LDA-Benchmark | 8ed257bd87eae25ae0221e3966b580c2b0e66033 | 9b387972c2ae48ef0c6eeb285c61f8ac82c10a94 | refs/heads/master | 2021-01-01T16:37:22.844545 | 2017-07-20T20:15:00 | 2017-07-20T20:15:00 | 97,874,046 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,493 | h | sparse_matrix.h | #ifndef SPARSE_MATRIX_H
#define SPARSE_MATRIX_H
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <assert.h>
#include <omp.h>
//#include "zlib_util.h"
#define MALLOC(type, size) (type*)malloc(sizeof(type)*(size))
#define smat_t sparse_matrix
template<typename val_type> class smat_t;
template<typename val_type> class entry_iterator_t; // iterator for files with (i,j,v) tuples
template<typename val_type> class smat_iterator_t; // iterator for nonzero entries in smat_t
template<typename val_type> class smat_subset_iterator_t; // iterator for nonzero entries in a subset
// H = X*W, (X: m*n, W: n*k row-major, H m*k row major)
template<typename val_type> void smat_x_dmat(const smat_t<val_type> &X, const val_type* W, const size_t k, val_type *H);
// H = a*X*W + H0, (X: m*n, W: n*k row-major, H m*k row major)
template<typename val_type> void smat_x_dmat(const val_type a, const smat_t<val_type> &X, const val_type* W, const size_t k, const val_type *H0, val_type *H);
// Sparse matrix format CSC & CSR
template<typename val_type>
class smat_t{
private:
bool mem_alloc_by_me;
bool read_from_binary;
unsigned char* binary_buf;
size_t binary_buf_len;
const static int HeaderSize =
sizeof(size_t)+sizeof(size_t)+sizeof(size_t)+sizeof(size_t);
void csr_to_csc();
void csc_to_csr();
public:
size_t rows, cols;
size_t nnz, max_row_nnz, max_col_nnz;
val_type *val, *val_t;
size_t *col_ptr, *row_ptr;
unsigned *row_idx, *col_idx;
// filetypes for loading smat_t
enum format_t {TXT=0, PETSc=1, BINARY=2, COMPRESSION=3};
// Constructor and Destructor
smat_t() : mem_alloc_by_me(false), read_from_binary(false), rows(0), cols(0), nnz(0){
val=val_t=NULL; col_ptr=row_ptr=NULL, row_idx=col_idx=NULL;}
smat_t(const smat_t& m){*this = m; mem_alloc_by_me = false; read_from_binary = false;}
~smat_t(){ clear_space();}
void clear_space();
smat_t transpose();
void apply_permutation(const std::vector<unsigned> &row_perm, const std::vector<unsigned> &col_perm);
void apply_permutation(const unsigned *row_perm=NULL, const unsigned *col_perm=NULL);
smat_subset_iterator_t<val_type> row_subset_it(const std::vector<unsigned> &subset);
smat_subset_iterator_t<val_type> row_subset_it(const unsigned *subset, int subset_size);
smat_subset_iterator_t<val_type> col_subset_it(const std::vector<unsigned> &subset);
smat_subset_iterator_t<val_type> col_subset_it(const unsigned *subset, int subset_size);
smat_t row_subset(const std::vector<unsigned> &subset);
smat_t row_subset(const unsigned *subset, int subset_size);
size_t nnz_of_row(unsigned i) const {return (row_ptr[i+1]-row_ptr[i]);}
size_t nnz_of_col(unsigned i) const {return (col_ptr[i+1]-col_ptr[i]);}
// smat-vector multiplication
void Xv(const val_type *v, val_type *Xv);
void XTu(const val_type *u, val_type *XTu);
// IO methods
void load_from_iterator(size_t _rows, size_t _cols, size_t _nnz, entry_iterator_t<val_type>* entry_it);
void load(size_t _rows, size_t _cols, size_t _nnz, const char *filename, format_t fmt);
void load_from_PETSc(const char *filename);
void save_PETSc_to_file(const char *filename);
void load_from_binary(const char *filename);
void save_binary_to_file(const char *filename);
// used for MPI verions
void from_mpi(){
mem_alloc_by_me = true;
max_col_nnz = 0;
for(size_t c = 0; c < cols; c++)
max_col_nnz = std::max(max_col_nnz, nnz_of_col(c));
}
val_type get_global_mean() const;
void remove_bias(val_type bias=0);
};
/*-------------- Iterators -------------------*/
template<typename val_type>
class rate_t{
public:
unsigned i, j; val_type v, weight;
rate_t(int ii=0, int jj=0, val_type vv=0, val_type ww=1.0): i(ii), j(jj), v(vv), weight(ww){}
};
template<typename val_type>
class entry_iterator_t {
public:
size_t nnz;
virtual rate_t<val_type> next() = 0;
};
#define MAXLINE 10240
// Iterator for files with (i,j,v) tuples
template<typename val_type>
class file_iterator_t: public entry_iterator_t<val_type>{
public:
file_iterator_t(size_t nnz_, const char* filename, size_t start_pos=0);
~file_iterator_t(){ if (fp) fclose(fp); }
rate_t<val_type> next();
private:
size_t nnz;
FILE *fp;
char line[MAXLINE];
};
// smat_t iterator
template<typename val_type>
class smat_iterator_t: public entry_iterator_t<val_type>{
public:
enum {ROWMAJOR, COLMAJOR};
// major: smat_iterator_t<val_type>::ROWMAJOR or smat_iterator_t<val_type>::COLMAJOR
smat_iterator_t(const smat_t<val_type>& M, int major = ROWMAJOR);
~smat_iterator_t() {}
rate_t<val_type> next();
private:
size_t nnz;
unsigned *col_idx;
size_t *row_ptr;
val_type *val_t;
size_t rows, cols, cur_idx;
size_t cur_row;
};
// smat_t subset iterator
template<typename val_type>
class smat_subset_iterator_t: public entry_iterator_t<val_type>{
public:
enum {ROWMAJOR, COLMAJOR};
// major: smat_iterator_t<val_type>::ROWMAJOR or smat_iterator_t<val_type>::COLMAJOR
smat_subset_iterator_t(const smat_t<val_type>& M, const unsigned *subset, size_t size, bool remapping=false, int major = ROWMAJOR);
~smat_subset_iterator_t() {}
size_t get_nnz() {return nnz;}
size_t get_rows() {return major==ROWMAJOR? remapping? subset.size(): rows: rows;}
size_t get_cols() {return major==ROWMAJOR? cols: remapping? subset.size():cols;}
rate_t<val_type> next();
private:
size_t nnz;
unsigned *col_idx;
size_t *row_ptr;
val_type *val_t;
size_t rows, cols, cur_idx;
size_t cur_row;
std::vector<unsigned>subset;
int major;
bool remapping;
};
// -------------- Implementation --------------
template<typename val_type>
void smat_t<val_type>::clear_space() {
if(mem_alloc_by_me) {
if(read_from_binary)
free(binary_buf);
else {
if(val)free(val); if(val_t)free(val_t);
if(row_ptr)free(row_ptr);if(row_idx)free(row_idx);
if(col_ptr)free(col_ptr);if(col_idx)free(col_idx);
}
}
read_from_binary = false;
mem_alloc_by_me = false;
}
template<typename val_type>
smat_t<val_type> smat_t<val_type>::transpose(){
smat_t<val_type> mt;
mt.cols = rows; mt.rows = cols; mt.nnz = nnz;
mt.val = val_t; mt.val_t = val;
mt.col_ptr = row_ptr; mt.row_ptr = col_ptr;
mt.col_idx = row_idx; mt.row_idx = col_idx;
mt.max_col_nnz=max_row_nnz; mt.max_row_nnz=max_col_nnz;
return mt;
}
template<typename val_type>
void smat_t<val_type>::apply_permutation(const std::vector<unsigned> &row_perm, const std::vector<unsigned> &col_perm) {
apply_permutation(row_perm.size()==rows? &row_perm[0]: NULL, col_perm.size()==cols? &col_perm[0]: NULL);
}
template<typename val_type>
void smat_t<val_type>::apply_permutation(const unsigned *row_perm, const unsigned *col_perm) {
if(row_perm!=NULL) {
for(size_t idx = 0; idx < nnz; idx++) row_idx[idx] = row_perm[row_idx[idx]];
csc_to_csr();
csr_to_csc();
}
if(col_perm!=NULL) {
for(size_t idx = 0; idx < nnz; idx++) col_idx[idx] = col_perm[col_idx[idx]];
csr_to_csc();
csc_to_csr();
}
}
template<typename val_type>
smat_subset_iterator_t<val_type> smat_t<val_type>::row_subset_it(const std::vector<unsigned> &subset) {
return row_subset_it(&subset[0], (int)subset.size());
}
template<typename val_type>
smat_subset_iterator_t<val_type> smat_t<val_type>::row_subset_it(const unsigned *subset, int subset_size) {
return smat_subset_iterator_t<val_type> (*this, subset, subset_size);
}
template<typename val_type>
smat_subset_iterator_t<val_type> smat_t<val_type>::col_subset_it(const std::vector<unsigned> &subset) {
return col_subset_it(&subset[0], (int)subset.size());
}
template<typename val_type>
smat_subset_iterator_t<val_type> smat_t<val_type>::col_subset_it(const unsigned *subset, int subset_size) {
bool remmapping = false; // no remapping by default
return smat_subset_iterator_t<val_type> (*this, subset, subset_size, remmapping, smat_subset_iterator_t<val_type>::COLMAJOR);
}
template<typename val_type>
smat_t<val_type> smat_t<val_type>::row_subset(const std::vector<unsigned> &subset) {
return row_subset(&subset[0], (int)subset.size());
}
template<typename val_type>
smat_t<val_type> smat_t<val_type>::row_subset(const unsigned *subset, int subset_size) {
smat_subset_iterator_t<val_type> it(*this, subset, subset_size);
smat_t<val_type> sub_smat;
sub_smat.load_from_iterator(subset_size, cols, it.get_nnz(), &it);
return sub_smat;
}
template<typename val_type>
val_type smat_t<val_type>::get_global_mean() const {
val_type sum=0;
for(size_t idx = 0; idx < nnz; idx++) sum += val[idx];
return sum/(val_type)nnz;
}
template<typename val_type>
void smat_t<val_type>::remove_bias(val_type bias){
if(bias) {
for(size_t idx = 0; idx < nnz; idx++) {
val[idx] -= bias;
val_t[idx] -= bias;
}
}
}
template<typename val_type>
void smat_t<val_type>::Xv(const val_type *v, val_type *Xv) {
for(size_t i = 0; i < rows; ++i) {
Xv[i] = 0;
for(size_t idx = row_ptr[i]; idx < row_ptr[i+1]; ++idx)
Xv[i] += val_t[idx] * v[col_idx[idx]];
}
}
template<typename val_type>
void smat_t<val_type>::XTu(const val_type *u, val_type *XTu) {
for(size_t i = 0; i < cols; ++i) {
XTu[i] = 0;
for(size_t idx = col_ptr[i]; idx < col_ptr[i+1]; ++idx)
XTu[i] += val[idx] * u[row_idx[idx]];
}
}
// Comparator for sorting rates into row/column comopression storage
template<typename val_type>
class SparseComp {
public:
const unsigned *row_idx;
const unsigned *col_idx;
SparseComp(const unsigned *row_idx_, const unsigned *col_idx_, bool isCSR=true) {
row_idx = (isCSR)? row_idx_: col_idx_;
col_idx = (isCSR)? col_idx_: row_idx_;
}
bool operator()(size_t x, size_t y) const {
return (row_idx[x] < row_idx[y]) || ((row_idx[x] == row_idx[y]) && (col_idx[x]< col_idx[y]));
}
};
template<typename val_type>
void smat_t<val_type>::load_from_iterator(size_t _rows, size_t _cols, size_t _nnz, entry_iterator_t<val_type> *entry_it){
clear_space(); // clear any pre-allocated space in case of memory leak
rows =_rows,cols=_cols,nnz=_nnz;
mem_alloc_by_me = true;
val = MALLOC(val_type, nnz); val_t = MALLOC(val_type, nnz);
row_idx = MALLOC(unsigned, nnz); col_idx = MALLOC(unsigned, nnz);
//row_idx = MALLOC(unsigned long, nnz); col_idx = MALLOC(unsigned long, nnz); // switch to this for matlab
row_ptr = MALLOC(size_t, rows+1); col_ptr = MALLOC(size_t, cols+1);
memset(row_ptr,0,sizeof(size_t)*(rows+1));
memset(col_ptr,0,sizeof(size_t)*(cols+1));
// a trick here to utilize the space the have been allocated
std::vector<size_t> perm(_nnz);
unsigned *tmp_row_idx = col_idx;
unsigned *tmp_col_idx = row_idx;
val_type *tmp_val = val;
for(size_t idx = 0; idx < _nnz; idx++){
rate_t<val_type> rate = entry_it->next();
row_ptr[rate.i+1]++;
col_ptr[rate.j+1]++;
tmp_row_idx[idx] = rate.i;
tmp_col_idx[idx] = rate.j;
tmp_val[idx] = rate.v;
perm[idx] = idx;
}
// sort entries into row-majored ordering
sort(perm.begin(), perm.end(), SparseComp<val_type>(tmp_row_idx, tmp_col_idx, true));
// Generate CSR format
for(size_t idx = 0; idx < _nnz; idx++) {
val_t[idx] = tmp_val[perm[idx]];
col_idx[idx] = tmp_col_idx[perm[idx]];
}
// Calculate nnz for each row and col
max_row_nnz = max_col_nnz = 0;
for(size_t r = 1; r <= rows; r++) {
max_row_nnz = std::max(max_row_nnz, row_ptr[r]);
row_ptr[r] += row_ptr[r-1];
}
for(size_t c = 1; c <= cols; c++) {
max_col_nnz = std::max(max_col_nnz, col_ptr[c]);
col_ptr[c] += col_ptr[c-1];
}
// Transpose CSR into CSC matrix
for(size_t r = 0; r < rows; ++r){
for(size_t idx = row_ptr[r]; idx < row_ptr[r+1]; idx++){
size_t c = (size_t) col_idx[idx];
row_idx[col_ptr[c]] = r;
val[col_ptr[c]++] = val_t[idx];
}
}
for(size_t c = cols; c > 0; --c) col_ptr[c] = col_ptr[c-1];
col_ptr[0] = 0;
}
template<typename val_type>
void smat_t<val_type>::load(size_t _rows, size_t _cols, size_t _nnz, const char* filename, smat_t<val_type>::format_t fmt){
if(fmt == smat_t<val_type>::TXT) {
file_iterator_t<val_type> entry_it(_nnz, filename);
load_from_iterator(_rows, _cols, _nnz, &entry_it);
} else if(fmt == smat_t<val_type>::PETSc) {
load_from_PETSc(filename);
} else {
fprintf(stderr, "Error: filetype %d not supported\n", fmt);
return ;
}
}
template<typename val_type>
void smat_t<val_type>::save_PETSc_to_file(const char *filename){
const int UNSIGNED_FILE = 1211216, LONG_FILE = 1015;
FILE *fp = fopen(filename, "wb");
if(fp == NULL) {
fprintf(stderr,"Error: can't open file %s\n", filename);
exit(1);
}
int32_t int_buf[3] = {(int32_t)LONG_FILE, (int32_t)rows, (int32_t)cols};
std::vector<int32_t> nnz_row(rows);
for(size_t r = 0; r < rows; r++)
nnz_row[r] = (int)nnz_of_row(r);
fwrite(&int_buf[0], sizeof(int32_t), 3, fp);
fwrite(&nnz, sizeof(size_t), 1, fp);
fwrite(&nnz_row[0], sizeof(int32_t), rows, fp);
fwrite(&col_idx[0], sizeof(unsigned), nnz, fp);
// the following part == fwrite(val_t, sizeof(double), nnz, fp);
const size_t chunksize = 1024;
double buf[chunksize];
size_t idx = 0;
while(idx + chunksize < nnz) {
for(size_t i = 0; i < chunksize; i++)
buf[i] = (double) val_t[idx+i];
fwrite(&buf[0], sizeof(double), chunksize, fp);
idx += chunksize;
}
size_t remaining = nnz - idx;
for(size_t i = 0; i < remaining; i++)
buf[i] = (double) val_t[idx+i];
fwrite(&buf[0], sizeof(double), remaining, fp);
fclose(fp);
}
template<typename val_type>
void smat_t<val_type>::load_from_PETSc(const char *filename) {
clear_space(); // clear any pre-allocated space in case of memory leak
const int UNSIGNED_FILE = 1211216, LONG_FILE = 1015;
int32_t int_buf[3];
size_t headersize = 0;
FILE *fp = fopen(filename, "rb");
if(fp == NULL) {
fprintf(stderr, "Error: can't read the file (%s)!!\n", filename);
return;
}
headersize += sizeof(int)*fread(int_buf, sizeof(int), 3, fp);
int filetype = int_buf[0];
rows = (size_t) int_buf[1];
cols = (size_t) int_buf[2];
if(filetype == UNSIGNED_FILE) {
headersize += sizeof(int)*fread(int_buf, sizeof(int32_t), 1, fp);
nnz = (size_t) int_buf[0];
} else if (filetype == LONG_FILE){
headersize += sizeof(size_t)*fread(&nnz, sizeof(int64_t), 1, fp);
} else {
fprintf(stderr, "Error: wrong PETSc format for %s\n", filename);
}
// Allocation of memory
mem_alloc_by_me = true;
val = MALLOC(val_type, nnz); val_t = MALLOC(val_type, nnz);
row_idx = MALLOC(unsigned, nnz); col_idx = MALLOC(unsigned, nnz);
row_ptr = MALLOC(size_t, rows+1); col_ptr = MALLOC(size_t, cols+1);
// load CSR from the binary PETSc format
{
// read row_ptr
std::vector<int32_t> nnz_row(rows);
headersize += sizeof(int32_t)*fread(&nnz_row[0], sizeof(int32_t), rows, fp);
row_ptr[0] = 0;
for(size_t r = 1; r <= rows; r++)
row_ptr[r] = row_ptr[r-1] + nnz_row[r-1];
// read col_idx
headersize += sizeof(int)*fread(&col_idx[0], sizeof(unsigned), nnz, fp);
// read val_t
const size_t chunksize = 1024;
double buf[chunksize];
size_t idx = 0;
while(idx + chunksize < nnz) {
headersize += sizeof(double)*fread(&buf[0], sizeof(double), chunksize, fp);
for(size_t i = 0; i < chunksize; i++)
val_t[idx+i] = (val_type) buf[i];
idx += chunksize;
}
size_t remaining = nnz - idx;
headersize += sizeof(double)*fread(&buf[0], sizeof(double), remaining, fp);
for(size_t i = 0; i < remaining; i++)
val_t[idx+i] = (val_type) buf[i];
}
fclose(fp);
csr_to_csc(); // Convert CSR to CSC
max_row_nnz = max_col_nnz = 0;
for(size_t c = 0; c < cols; c++) max_col_nnz = std::max(max_col_nnz, nnz_of_col(c));
for(size_t r = 0; r < rows; r++) max_row_nnz = std::max(max_row_nnz, nnz_of_row(r));
}
template<typename val_type>
void smat_t<val_type>::csr_to_csc() {
memset(col_ptr, 0, sizeof(size_t)*(cols+1));
for(size_t idx = 0; idx < nnz; idx++)
col_ptr[col_idx[idx]+1]++;
for(size_t c = 1; c <= cols; c++)
col_ptr[c] += col_ptr[c-1];
for(size_t r = 0; r < rows; r++) {
for(size_t idx = row_ptr[r]; idx != row_ptr[r+1]; idx++) {
size_t c = (size_t) col_idx[idx];
row_idx[col_ptr[c]] = r;
val[col_ptr[c]++] = val_t[idx];
}
}
for(size_t c = cols; c > 0; c--)
col_ptr[c] = col_ptr[c-1];
col_ptr[0] = 0;
}
template<typename val_type>
void smat_t<val_type>::csc_to_csr() {
memset(row_ptr, 0, sizeof(size_t)*(rows+1));
for(size_t idx = 0; idx < nnz; idx++)
row_ptr[row_idx[idx]+1]++;
for(size_t r = 1; r <= rows; r++)
row_ptr[r] += row_ptr[r-1];
for(size_t c = 0; c < cols; c++) {
for(size_t idx = col_ptr[c]; idx != col_ptr[c+1]; idx++) {
size_t r = (size_t) row_idx[idx];
col_idx[row_ptr[r]] = c;
val_t[row_ptr[r]++] = val[idx];
}
}
for(size_t r = rows; r > 0; r--)
row_ptr[r] = row_ptr[r-1];
row_ptr[0] = 0;
}
template<typename val_type>
file_iterator_t<val_type>::file_iterator_t(size_t nnz_, const char* filename, size_t start_pos){
nnz = nnz_;
fp = fopen(filename,"rb");
if(fp == NULL) {
fprintf(stderr, "Error: cannot read the file (%s)!!\n", filename);
return;
}
fseek(fp, start_pos, SEEK_SET);
}
template<typename val_type>
rate_t<val_type> file_iterator_t<val_type>::next() {
const int base10 = 10;
if(nnz > 0) {
--nnz;
if(fgets(&line[0], MAXLINE, fp)==NULL)
fprintf(stderr, "Error: reading error !!\n");
char *head_ptr = &line[0];
size_t i = strtol(head_ptr, &head_ptr, base10);
size_t j = strtol(head_ptr, &head_ptr, base10);
double v = strtod(head_ptr, &head_ptr);
return rate_t<val_type>(i-1, j-1, (val_type)v);
} else {
fprintf(stderr, "Error: no more entry to iterate !!\n");
return rate_t<val_type>(0,0,0);
}
}
/* Deprecated Implementation
template<typename val_type>
rate_t<val_type> file_iterator_t<val_type>::next() {
int i = 1, j = 1;
val_type v = 0;
if (nnz > 0) {
#ifdef _USE_FLOAT_
if(fscanf(fp, "%d %d %f", &i, &j, &v)!=3)
fprintf(stderr, "Error: reading smat_t\n");
#else
if(fscanf(fp, "%d %d %lf", &i, &j, &v)!=3)
fprintf(stderr, "Error: reading smat_t\n");
#endif
--nnz;
} else {
fprintf(stderr,"Error: no more entry to iterate !!\n");
}
return rate_t<val_type>(i-1,j-1,v);
}
*/
template<typename val_type>
smat_iterator_t<val_type>::smat_iterator_t(const smat_t<val_type>& M, int major) {
nnz = M.nnz;
col_idx = (major == ROWMAJOR)? M.col_idx: M.row_idx;
row_ptr = (major == ROWMAJOR)? M.row_ptr: M.col_ptr;
val_t = (major == ROWMAJOR)? M.val_t: M.val;
rows = (major==ROWMAJOR)? M.rows: M.cols;
cols = (major==ROWMAJOR)? M.cols: M.rows;
cur_idx = cur_row = 0;
}
template<typename val_type>
rate_t<val_type> smat_iterator_t<val_type>::next() {
while (cur_idx >= row_ptr[cur_row+1])
cur_row++;
if (nnz > 0)
nnz--;
else
fprintf(stderr,"Error: no more entry to iterate !!\n");
rate_t<val_type> ret(cur_row, col_idx[cur_idx], val_t[cur_idx]);
cur_idx++;
return ret;
}
template<typename val_type>
smat_subset_iterator_t<val_type>::smat_subset_iterator_t(const smat_t<val_type>& M, const unsigned *subset, size_t size, bool remapping_, int major_) {
major = major_; remapping = remapping_;
col_idx = (major == ROWMAJOR)? M.col_idx: M.row_idx;
row_ptr = (major == ROWMAJOR)? M.row_ptr: M.col_ptr;
val_t = (major == ROWMAJOR)? M.val_t: M.val;
rows = (major==ROWMAJOR)? (remapping?size:M.rows): (remapping?size:M.cols);
cols = (major==ROWMAJOR)? M.cols: M.rows;
this->subset.resize(size);
nnz = 0;
for(size_t i = 0; i < size; i++) {
unsigned idx = subset[i];
this->subset[i] = idx;
nnz += (major == ROWMAJOR)? M.nnz_of_row(idx): M.nnz_of_col(idx);
}
sort(this->subset.begin(), this->subset.end());
cur_row = 0;
cur_idx = row_ptr[this->subset[cur_row]];
}
template<typename val_type>
rate_t<val_type> smat_subset_iterator_t<val_type>::next() {
while (cur_idx >= row_ptr[subset[cur_row]+1]) {
cur_row++;
cur_idx = row_ptr[subset[cur_row]];
}
if (nnz > 0)
nnz--;
else
fprintf(stderr,"Error: no more entry to iterate !!\n");
rate_t<val_type> ret_rowwise(remapping?cur_row:subset[cur_row], col_idx[cur_idx], val_t[cur_idx]);
rate_t<val_type> ret_colwise(col_idx[cur_idx], remapping?cur_row:subset[cur_row], val_t[cur_idx]);
//printf("%d %d\n", cur_row, col_idx[cur_idx]);
cur_idx++;
return major==ROWMAJOR? ret_rowwise: ret_colwise;
}
/*
H = X*W
X is an m*n
W is an n*k, row-majored array
H is an m*k, row-majored array
*/
template<typename val_type>
void smat_x_dmat(const smat_t<val_type> &X, const val_type* W, const size_t k, val_type *H)
{
size_t m = X.rows;
#pragma omp parallel for schedule(dynamic,50) shared(X,H,W)
for(size_t i = 0; i < m; i++) {
val_type *Hi = &H[k*i];
memset(Hi,0,sizeof(val_type)*k);
for(size_t idx = X.row_ptr[i]; idx < X.row_ptr[i+1]; idx++) {
const val_type Xij = X.val_t[idx];
const val_type *Wj = &W[X.col_idx[idx]*k];
for(unsigned t = 0; t < k; t++)
Hi[t] += Xij*Wj[t];
}
}
}
/*
H = a*X*W + H0
X is an m*n
W is an n*k, row-majored array
H is an m*k, row-majored array
*/
template<typename val_type>
void smat_x_dmat(const val_type a, const smat_t<val_type> &X, const val_type* W, const size_t k, const val_type *H0, val_type *H)
{
size_t m = X.rows;
#pragma omp parallel for schedule(dynamic,50) shared(X,H,W)
for(size_t i = 0; i < m; i++) {
val_type *Hi = &H[k*i];
if(H != H0)
memcpy(Hi, &H0[k*i], sizeof(val_type)*k);
for(size_t idx = X.row_ptr[i]; idx < X.row_ptr[i+1]; idx++) {
const val_type Xij = X.val_t[idx];
const val_type *Wj = &W[X.col_idx[idx]*k];
for(unsigned t = 0; t < k; t++)
Hi[t] += a*Xij*Wj[t];
}
}
}
#undef smat_t
#endif // SPARSE_MATRIX_H
|
6e2ae4ebb77469f9b23ef145d60bbc67cac93a92 | d754ba23c8ff391ce9dcefcfae3b90cef16ecde0 | /CCC/ccc13s4.cpp | f587d63430a8a3045d99f257d717589fc1f6f375 | [] | no_license | TruVortex/Competitive-Programming | 3edc0838aef41128a27fdc7f47d704adbf2c3f38 | 3812ff630488d7589754ff25a3eefd8898226301 | refs/heads/master | 2023-05-10T01:48:00.996120 | 2021-06-02T03:36:35 | 2021-06-02T03:36:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | cpp | ccc13s4.cpp | #include <bits/stdc++.h>
using namespace std;
#define scan(x) do{while((x=getchar())<'0'); for(x-='0'; '0'<=(_=getchar()); x=(x<<3)+(x<<1)+_-'0');}while(0)
char _;
vector<vector<int>> adj(1000001);
bool bfs(int a, int b)
{
vector<bool> vis(1000001);
queue<int> buf;
buf.push(a);
vis[a] = true;
while (!buf.empty())
{
int u = buf.front();
buf.pop();
for (auto &x : adj[u])
if (!vis[x])
buf.push(x), vis[x] = true;
}
return vis[b];
}
int main()
{
int n, m, a, b;
scan(n); scan(m);
while(m--)
{
scan(a); scan(b);
adj[a].push_back(b);
}
scan(a); scan(b);
if (bfs(a,b))
printf("yes");
else if (bfs(b,a))
printf("no");
else
printf("unknown");
return 0;
}
|
bf7e9c6e74d24c624d53ad425f8053f25f67748b | 9d7c02f57514e770e430310215280c8ad01073ac | /OpenGL/IndexBuffer.cpp | 8171b7df43011c93ee3626ce1cc7e0cc4b62a55e | [] | no_license | elizabethadelaide/GPU_notes | 3bafef7e2b76e93cbcb5a742090af45f0ff7a3c3 | ad548db64b3fd03685c233519da6db8011123d95 | refs/heads/master | 2020-03-28T02:03:53.989699 | 2018-09-10T04:21:32 | 2018-09-10T04:21:32 | 147,544,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | cpp | IndexBuffer.cpp | #include "IndexBuffer.h"
#include "Renderer.h"
//Cosntructor
IndexBuffer::IndexBuffer(const unsigned int* data, unsigned int count)
:m_Count(count)
{
//Pass in pointer to unsigned to buffer
GLCall(glGenBuffers(1, &m_RendererID));
//Bind buffer array by ID
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_RendererID));
//Type, Size, data, usage
GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(unsigned int), data, GL_STATIC_DRAW));
}
//Desctrctor
IndexBuffer::~IndexBuffer() {
GLCall(glDeleteBuffers(1, &m_RendererID));
}
//Bind id
void IndexBuffer::Bind() const{
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_RendererID));
}
//Unbind (set ID to 0)
void IndexBuffer::Unbind() const{
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
} |
8a24428479e54024aa36bf705db8cfbf7347884f | 68a84d1f284c0f82e3625ec64d79bf21559c636f | /bank.cpp | 6d1718c41efe46a8d001f651010d40cd11e00ff6 | [] | no_license | schnej7/cryptoAtm | 5073aaa1b46eae368e7c3d0a017b009cd872ea54 | 217b870dc4ffd4e311b2cbbd22ee1052f6090c3a | refs/heads/master | 2020-03-29T11:03:03.471990 | 2013-12-03T08:55:34 | 2013-12-03T08:55:34 | 14,382,516 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,128 | cpp | bank.cpp | /**
@file bank.cpp
@brief Top level bank implementation file
*/
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <pthread.h>
#include <cstring>
#include <string>
using std::string;
#include <regex.h>
#include <crypt.h>
#include <vector>
using std::vector;
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include "acct.h"
#include "util.cpp"
void *client_thread(void *arg);
void *console_thread(void *arg);
//Used to store the accounts
std::vector <Acct> users;
std::string bankSecret = generateSecret( 40 );
std::vector<byte *> keys;
std::vector<bool> keysInUse;
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: bank listen-port\n");
return -1;
}
//Setup bank data first
users.push_back( Acct("Alice", "1234", 100, bankSecret) );
users.push_back( Acct("Bob", "6543", 50, bankSecret) );
users.push_back( Acct("Eve", "1122", 0, bankSecret) );
unsigned short ourport = atoi(argv[1]);
//socket setup
int lsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (!lsock) {
printf("fail to create socket\n");
return -1;
}
//listening address
sockaddr_in addr_l;
addr_l.sin_family = AF_INET;
addr_l.sin_port = htons(ourport);
unsigned char *ipaddr = reinterpret_cast<unsigned char *>(&addr_l.sin_addr);
ipaddr[0] = 127;
ipaddr[1] = 0;
ipaddr[2] = 0;
ipaddr[3] = 1;
if (0 != bind(lsock, reinterpret_cast<sockaddr *>(&addr_l), sizeof(addr_l))) {
printf("failed to bind socket\n");
return -1;
}
if (0 != listen(lsock, SOMAXCONN)) {
printf("failed to listen on socket\n");
return -1;
}
pthread_t cthread;
pthread_create(&cthread, NULL, console_thread, NULL);
//loop forever accepting new connections
while (1) {
sockaddr_in unused;
socklen_t size = sizeof(unused);
int csock = accept(lsock, reinterpret_cast<sockaddr *>(&unused), &size);
if (csock < 0) //bad client, skip it
continue;
pthread_t thread;
pthread_create(&thread, NULL, client_thread, (void *)(intptr_t)csock);
}
}
void *client_thread(void *arg) {
int length;
int atm;
char *charPacket = new char[1024];
std::vector<string> input;
std::string sessionKey;
int csock = *((int *)(&arg));
std::string packet;
recvPacket(csock, length, packet);
std::vector<std::string> results;
for (unsigned int i = 0; i < keys.size(); ++i) {
if (keysInUse[i]) {
continue;
}
std::string encoded;
CryptoPP::StringSource(keys[i], CryptoPP::AES::DEFAULT_KEYLENGTH, true,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(encoded)
) // HexEncoder
); // StringSource
results = openPacket(packet, encoded);
if (!results.empty() && results[1] == "handshake") {
sessionKey = encoded;
keysInUse[i] = true;
atm = i;
break;
}
}
if (results.empty()) {
keysInUse[atm] = false;
return NULL;
}
std::string bankNonce = makeNonce();
std::string message = "handshakeResponse";
length = 1024;
packet = createPacket(sessionKey, results[0], message, bankNonce);
sendPacket(csock, length, packet);
printf("[bank] client ID #%d connected\n", csock);
//input loop
string pinHash;
int current; //current user number
while (1) {
string message = "";
//read the packet from the ATM
if (!recvPacket(csock, length, packet)) {
keysInUse[atm] = false;
break;
}
vector<string> results = openPacket(packet, sessionKey);
if (results.empty()) {
keysInUse[atm] = false;
break;
}
/*for(int i = 0; i < results.size(); i++){
cout << results[i] << endl;
}*/
if (!(results[2] == bankNonce)) {
cout << "ATM " << atm << " SECURITY COMPROMISED!" << endl;
keysInUse[atm] = false;
break;
}
vector<string> command = parseCommand(results[1]);
if (command[0] == "login") {
//cout << "inside login" << endl;
string username = command[1];
pinHash = command[2];
bool validUser = false;
for ( int i = 0; i < users.size(); i++ ) {
if ( users[i].compareName(username, bankSecret) ) {
current = i;
validUser = true;
}
}
if (validUser) {
if (users[current].validatePin(pinHash, bankSecret)) {
if (!users[current].loggedIn) {
message = "success";
users[current].loggedIn = true;
} else {
message = "failure";
}
} else {
message = "failure";
}
} else {
message = "failure";
}
} else if (command[0] == "withdraw") {
int amount = stoi(command[1]);
int current_balance = users[current].getBalanceSecure(pinHash, bankSecret);
if (current_balance - amount < 0) {
message = "overdraft";
} else if (current_balance - amount >= 0 && current_balance - amount < 10) {
users[current].setBalanceSecure(current_balance - amount, pinHash, bankSecret);
message = "low";
} else {
users[current].setBalanceSecure(current_balance - amount, pinHash, bankSecret);
message = "success";
}
} else if (command[0] == "balance") {
message = std::to_string(users[current].getBalanceSecure(pinHash, bankSecret));
} else if (command[0] == "transfer") {
int amount = stoi(command[1]);
int userBalance = users[current].getBalanceSecure(pinHash, bankSecret);
string otherUser = command[2];
int other;
bool validUser = false;
for ( int i = 0; i < users.size(); i++ ) {
if ( users[i].compareName(otherUser, bankSecret) ) {
other = i;
validUser = true;
}
}
if (validUser) {
int otherBalance = users[other].getBalance();
if (userBalance - amount < 0) {
message = "overdraft";
} else if (userBalance - amount >= 0 && userBalance - amount < 10) {
users[current].setBalanceSecure(userBalance - amount, pinHash, bankSecret);
users[other].setBalanceSecure(otherBalance + amount, pinHash, bankSecret);
message = "low";
} else if (otherBalance + amount > 1000000000) {
message = "overflow";
} else {
users[current].setBalanceSecure(userBalance - amount, pinHash, bankSecret);
users[other].setBalance(otherBalance + amount);
message = "success";
}
} else {
message = "failure";
}
} else if (command[0] == "logout") {
keysInUse[atm] = false;
users[current].loggedIn = false;
break;
}
//TODO: process packet data
//TODO: put new data in packet
//send the new packet back to the client
bankNonce = makeNonce();
packet = createPacket(sessionKey, results[0], message, bankNonce);
if (!sendPacket(csock, length, packet)) {
keysInUse[atm] = false;
break;
}
}
printf("[bank] client ID #%d disconnected\n", csock);
close(csock);
return NULL;
}
void *deposit( char *msgbuf ) {
std::string messageString( msgbuf );
int begin = strlen( "deposit " );
int length = messageString.length();
int spaceLoc = 0;
for ( int i = begin; i < messageString.length(); i++ ) {
if ( messageString[i] == ' ' ) {
spaceLoc = i;
break;
}
}
std::string user = messageString.substr( begin, spaceLoc - begin );
std::string amount = messageString.substr( spaceLoc + 1, length - spaceLoc );
for ( int i = 0; i < users.size(); i++ ) {
if ( users[i].compareName(user, bankSecret) && users[i].getBalance() > 0 && atoi(amount.c_str()) > 0 ) {
users[i].setBalance( users[i].getBalance() + atoi(amount.c_str()) );
}
}
}
void *balance( char *msgbuf ) {
std::string messageString( msgbuf );
int begin = strlen( "balance " );
int length = messageString.length() - begin;
std::string user = messageString.substr( begin, length );
for ( int i = 0; i < users.size(); i++ ) {
if ( users[i].compareName(user, bankSecret) ) {
printf("%d\n", users[i].getBalance());
}
}
}
void *console_thread(void *arg) {
//Generate our keys
for (unsigned int i = 1; i <= 10; ++i) {
byte *key = new byte[CryptoPP::AES::DEFAULT_KEYLENGTH];
generateRandomKey(std::to_string((int)i), key, CryptoPP::AES::DEFAULT_KEYLENGTH);
keys.push_back(key);
keysInUse.push_back(false);
}
char buf[80];
// Compile regular expressions
regex_t depositregex;
regex_t balanceregex;
int reti;
reti = regcomp(&depositregex, "^deposit [a-zA-Z]+ [0-9]+$", REG_EXTENDED);
if ( reti ) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regcomp(&balanceregex, "^balance [a-zA-Z]+$", REG_EXTENDED);
if ( reti ) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
while (1) {
printf("bank> ");
fgets(buf, 79, stdin);
buf[strlen(buf) - 1] = '\0'; //trim off trailing newline
char msgbuf[100]; //msg buffer for regex errors
reti = regexec(&depositregex, buf, 0, NULL, 0);
if ( !reti ) {
//Deposit command
deposit( buf );
continue;
} else if ( reti == REG_NOMATCH ) {
//Not deposit
} else {
regerror(reti, &depositregex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
reti = regexec(&balanceregex, buf, 0, NULL, 0);
if ( !reti ) {
//Balance command
balance( buf );
continue;
} else if ( reti == REG_NOMATCH ) {
//Not balance
} else {
regerror(reti, &depositregex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
}
}
|
12da7d88239da010fdf446a845c1737076126a93 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /weblayer/renderer/content_renderer_client_impl.cc | 2eba35314768f41168df2da67dfc30f0718f9570 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 10,788 | cc | content_renderer_client_impl.cc | // Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/renderer/content_renderer_client_impl.h"
#include "base/feature_list.h"
#include "build/build_config.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/password_autofill_agent.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/content_capture/common/content_capture_features.h"
#include "components/content_capture/renderer/content_capture_sender.h"
#include "components/content_settings/renderer/content_settings_agent_impl.h"
#include "components/error_page/common/error.h"
#include "components/grit/components_scaled_resources.h"
#include "components/no_state_prefetch/common/prerender_url_loader_throttle.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_client.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_helper.h"
#include "components/no_state_prefetch/renderer/no_state_prefetch_utils.h"
#include "components/no_state_prefetch/renderer/prerender_render_frame_observer.h"
#include "components/page_load_metrics/renderer/metrics_render_frame_observer.h"
#include "components/subresource_filter/content/renderer/ad_resource_tracker.h"
#include "components/subresource_filter/content/renderer/subresource_filter_agent.h"
#include "components/subresource_filter/content/renderer/unverified_ruleset_dealer.h"
#include "components/subresource_filter/core/common/common_features.h"
#include "components/webapps/renderer/web_page_metadata_agent.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_runtime_features.h"
#include "ui/base/resource/resource_bundle.h"
#include "weblayer/common/features.h"
#include "weblayer/renderer/error_page_helper.h"
#include "weblayer/renderer/url_loader_throttle_provider.h"
#include "weblayer/renderer/weblayer_render_frame_observer.h"
#include "weblayer/renderer/weblayer_render_thread_observer.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/android_system_error_page/error_page_populator.h"
#include "components/cdm/renderer/android_key_systems.h"
#include "components/spellcheck/renderer/spellcheck.h" // nogncheck
#include "components/spellcheck/renderer/spellcheck_provider.h" // nogncheck
#include "content/public/common/url_constants.h"
#include "content/public/renderer/render_thread.h"
#include "services/service_manager/public/cpp/local_interface_provider.h"
#include "third_party/blink/public/platform/web_runtime_features.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_security_policy.h"
#endif
namespace weblayer {
namespace {
#if BUILDFLAG(IS_ANDROID)
class SpellcheckInterfaceProvider
: public service_manager::LocalInterfaceProvider {
public:
SpellcheckInterfaceProvider() = default;
SpellcheckInterfaceProvider(const SpellcheckInterfaceProvider&) = delete;
SpellcheckInterfaceProvider& operator=(const SpellcheckInterfaceProvider&) =
delete;
~SpellcheckInterfaceProvider() override = default;
// service_manager::LocalInterfaceProvider:
void GetInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) override {
// A dirty hack to make SpellCheckHost requests work on WebLayer.
// TODO(crbug.com/806394): Use a WebView-specific service for SpellCheckHost
// and SafeBrowsing, instead of |content_browser|.
content::RenderThread::Get()->BindHostReceiver(mojo::GenericPendingReceiver(
interface_name, std::move(interface_pipe)));
}
};
#endif // BUILDFLAG(IS_ANDROID)
} // namespace
ContentRendererClientImpl::ContentRendererClientImpl() = default;
ContentRendererClientImpl::~ContentRendererClientImpl() = default;
void ContentRendererClientImpl::RenderThreadStarted() {
#if BUILDFLAG(IS_ANDROID)
if (!spellcheck_) {
local_interface_provider_ = std::make_unique<SpellcheckInterfaceProvider>();
spellcheck_ = std::make_unique<SpellCheck>(local_interface_provider_.get());
}
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowedForReferrer(
blink::WebString::FromUTF8(content::kAndroidAppScheme));
#endif
content::RenderThread* thread = content::RenderThread::Get();
weblayer_observer_ = std::make_unique<WebLayerRenderThreadObserver>();
thread->AddObserver(weblayer_observer_.get());
browser_interface_broker_ =
blink::Platform::Current()->GetBrowserInterfaceBroker();
subresource_filter_ruleset_dealer_ =
std::make_unique<subresource_filter::UnverifiedRulesetDealer>();
thread->AddObserver(subresource_filter_ruleset_dealer_.get());
}
void ContentRendererClientImpl::RenderFrameCreated(
content::RenderFrame* render_frame) {
auto* render_frame_observer = new WebLayerRenderFrameObserver(render_frame);
new prerender::PrerenderRenderFrameObserver(render_frame);
ErrorPageHelper::Create(render_frame);
autofill::PasswordAutofillAgent* password_autofill_agent =
new autofill::PasswordAutofillAgent(
render_frame, render_frame_observer->associated_interfaces());
new autofill::AutofillAgent(render_frame, password_autofill_agent, nullptr,
render_frame_observer->associated_interfaces());
auto* agent = new content_settings::ContentSettingsAgentImpl(
render_frame, false /* should_whitelist */,
std::make_unique<content_settings::ContentSettingsAgentImpl::Delegate>());
if (weblayer_observer_) {
if (weblayer_observer_->content_settings_manager()) {
mojo::Remote<content_settings::mojom::ContentSettingsManager> manager;
weblayer_observer_->content_settings_manager()->Clone(
manager.BindNewPipeAndPassReceiver());
agent->SetContentSettingsManager(std::move(manager));
}
}
auto* metrics_render_frame_observer =
new page_load_metrics::MetricsRenderFrameObserver(render_frame);
auto ad_resource_tracker =
std::make_unique<subresource_filter::AdResourceTracker>();
metrics_render_frame_observer->SetAdResourceTracker(
ad_resource_tracker.get());
auto* subresource_filter_agent =
new subresource_filter::SubresourceFilterAgent(
render_frame, subresource_filter_ruleset_dealer_.get(),
std::move(ad_resource_tracker));
subresource_filter_agent->Initialize();
#if BUILDFLAG(IS_ANDROID)
// |SpellCheckProvider| manages its own lifetime (and destroys itself when the
// RenderFrame is destroyed).
new SpellCheckProvider(render_frame, spellcheck_.get(),
local_interface_provider_.get());
#endif
if (render_frame->IsMainFrame())
new webapps::WebPageMetadataAgent(render_frame);
if (content_capture::features::IsContentCaptureEnabledInWebLayer()) {
new content_capture::ContentCaptureSender(
render_frame, render_frame_observer->associated_interfaces());
}
if (!render_frame->IsMainFrame()) {
auto* main_frame_no_state_prefetch_helper =
prerender::NoStatePrefetchHelper::Get(
render_frame->GetMainRenderFrame());
if (main_frame_no_state_prefetch_helper) {
// Avoid any race conditions from having the browser tell subframes that
// they're no-state prefetching.
new prerender::NoStatePrefetchHelper(
render_frame,
main_frame_no_state_prefetch_helper->histogram_prefix());
}
}
}
void ContentRendererClientImpl::WebViewCreated(
blink::WebView* web_view,
bool was_created_by_renderer,
const url::Origin* outermost_origin) {
new prerender::NoStatePrefetchClient(web_view);
}
SkBitmap* ContentRendererClientImpl::GetSadPluginBitmap() {
return const_cast<SkBitmap*>(ui::ResourceBundle::GetSharedInstance()
.GetImageNamed(IDR_SAD_PLUGIN)
.ToSkBitmap());
}
SkBitmap* ContentRendererClientImpl::GetSadWebViewBitmap() {
return const_cast<SkBitmap*>(ui::ResourceBundle::GetSharedInstance()
.GetImageNamed(IDR_SAD_WEBVIEW)
.ToSkBitmap());
}
void ContentRendererClientImpl::PrepareErrorPage(
content::RenderFrame* render_frame,
const blink::WebURLError& error,
const std::string& http_method,
content::mojom::AlternativeErrorPageOverrideInfoPtr
alternative_error_page_info,
std::string* error_html) {
auto* error_page_helper = ErrorPageHelper::GetForFrame(render_frame);
if (error_page_helper)
error_page_helper->PrepareErrorPage();
#if BUILDFLAG(IS_ANDROID)
// This does nothing if |error_html| is non-null (which happens if the
// embedder injects an error page).
android_system_error_page::PopulateErrorPageHtml(error, error_html);
#endif
}
std::unique_ptr<blink::URLLoaderThrottleProvider>
ContentRendererClientImpl::CreateURLLoaderThrottleProvider(
blink::URLLoaderThrottleProviderType provider_type) {
return std::make_unique<URLLoaderThrottleProvider>(
browser_interface_broker_.get(), provider_type);
}
void ContentRendererClientImpl::GetSupportedKeySystems(
media::GetSupportedKeySystemsCB cb) {
media::KeySystemInfos key_systems;
#if BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(ENABLE_WIDEVINE)
cdm::AddAndroidWidevine(&key_systems);
#endif // BUILDFLAG(ENABLE_WIDEVINE)
cdm::AddAndroidPlatformKeySystems(&key_systems);
#endif // BUILDFLAG(IS_ANDROID)
std::move(cb).Run(std::move(key_systems));
}
void ContentRendererClientImpl::
SetRuntimeFeaturesDefaultsBeforeBlinkInitialization() {
blink::WebRuntimeFeatures::EnablePerformanceManagerInstrumentation(true);
#if BUILDFLAG(IS_ANDROID)
// Web Share is experimental by default, and explicitly enabled on Android
// (for both Chrome and WebLayer).
blink::WebRuntimeFeatures::EnableWebShare(true);
#endif
if (base::FeatureList::IsEnabled(subresource_filter::kAdTagging)) {
blink::WebRuntimeFeatures::EnableAdTagging(true);
}
if (base::FeatureList::IsEnabled(
autofill::features::kAutofillSharedAutofill)) {
blink::WebRuntimeFeatures::EnableSharedAutofill(true);
}
}
bool ContentRendererClientImpl::IsPrefetchOnly(
content::RenderFrame* render_frame) {
return prerender::NoStatePrefetchHelper::IsPrefetching(render_frame);
}
bool ContentRendererClientImpl::DeferMediaLoad(
content::RenderFrame* render_frame,
bool has_played_media_before,
base::OnceClosure closure) {
return prerender::DeferMediaLoad(render_frame, has_played_media_before,
std::move(closure));
}
} // namespace weblayer
|
be2b6a7ca63db08ce2d60b93df13abf080b3ed7e | a2be1270dc46ad89e9abafb1f41de97eaafe666b | /Reversi-Game/client/src/Game.h | 7e8074809c00cbb1b077352e2bf8a12e62dd28be | [] | no_license | SapKi/Reversi-Game | 5efd11e7284b3d5c1a25909cf8e81cac4fccfdfb | 32f01435675ed2fe96abe055809d839630893eeb | refs/heads/main | 2023-03-09T21:42:38.038737 | 2021-02-27T09:12:56 | 2021-02-27T09:12:56 | 342,815,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,204 | h | Game.h | //Sapir Kikoz 207071192
#ifndef EXAP1_GAME_H
#define EXAP1_GAME_H
#include "Board.h"
#include "GameLogic.h"
#include "Player.h"
#include "ConsolePrinting.h"
class Game {
public:
/*
* this function is the constructor of the class assing the current player of the game
*/
Game(int row, int cols,ConsolePrinting* con, const char* filename);
/*
* this function is running the mane game flow by getting the current
* player and call to the function of running a single turn
*/
void gameFlow(Player* player1, Player* player2,int typeOfGame, ConsolePrinting* con);
Player* manageTurn(Player* givenPlayer,Player* currPlayer, Player* otherPlayer);
~Game();
Board* GetBoard();
GameLogic* getGameLogic();
int** GetMoves();
Player* getFirstPlayer();
Player* getSecondPlayer();
private:
int rows,cols;
Board* gameBoard;
MajorGameLogic* gamelogic;
int** moves;
Player* player1;
Player* player2;
ConsolePrinting* con;
Cell* lastTurn;
int numofmoves;
int invalidmoves;
int typeOfGame;
int BlackDeafualtTurn;
int lasturnI;
int lasturnJ;
const char *filename;
};
#endif //EXAP1_GAME_H
|
2c152b1966f4ba851dcff9bb6160dd54141b9ca5 | 09934b3e1ece3f9ae1f58f29f76c9e4fe3c80c7d | /libraries/Catalex/Catalex.h | e17659eea322748af70b896167ad49e6a51473ef | [] | no_license | dgrubb/Corpsewood-Haunted-Forest | b92f7ae125185294cfdb9ab11f239ec141c8fcc4 | 51fb6199144ed71cb69ecf99b2bf31a600a1ab90 | refs/heads/master | 2021-08-08T05:22:03.229099 | 2017-11-09T16:51:04 | 2017-11-09T16:51:04 | 106,024,202 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,092 | h | Catalex.h |
#ifndef _CATALEX_H
#define _CATALEX_H
#include <Arduino.h>
#include <SoftwareSerial.h>
class Catalex
{
public:
const uint16_t max_volume = 0x0030; // 100%
const uint16_t min_volume = 0x0000; // 0%
const uint16_t sd_card_device = 0x02;
const uint16_t default_device = sd_card_device;
const uint16_t default_volume = max_volume; // This goes all the way to 11
class Cmd
{
public:
static const uint8_t cmd_next_song = 0x01;
static const uint8_t cmd_prev_song = 0x02;
static const uint8_t cmd_play_index = 0x03;
static const uint8_t cmd_volume_up = 0x04;
static const uint8_t cmd_volume_down = 0x05;
static const uint8_t cmd_set_volume = 0x06;
static const uint8_t cmd_single_cycle_play = 0x08;
static const uint8_t cmd_select_device = 0x09;
static const uint8_t cmd_sleep_mode = 0x0A;
static const uint8_t cmd_wake_up = 0x0B;
static const uint8_t cmd_reset = 0x0C;
static const uint8_t cmd_play = 0x0D;
static const uint8_t cmd_pause = 0x0E;
static const uint8_t cmd_play_folder = 0x0F;
static const uint8_t cmd_stop = 0x16;
static const uint8_t cmd_folder_cycle = 0x17;
static const uint8_t cmd_shuffle_play = 0x18;
static const uint8_t cmd_set_single_cycle = 0x19;
static const uint8_t cmd_play_with_volume = 0x22;
};
Catalex(uint16_t playlist_length, uint8_t rx, uint8_t tx);
Catalex();
~Catalex();
bool init(uint16_t playlist_length, uint8_t rx, uint8_t tx);
bool ready();
bool play(uint16_t index);
bool playRandom();
bool setVolume(uint16_t volume);
private:
bool m_isInited;
uint8_t m_rx;
uint8_t m_tx;
uint16_t m_volume;
uint16_t m_device;
uint16_t m_playlist_length;
SoftwareSerial *m_serial;
bool selectDevice(uint16_t device);
void sendCommand(const uint8_t command, uint16_t data);
};
#endif /* _CATALEX_H */
|
d50b7db1dcdab8d8b515f2097871bfd3d08f7467 | 2a35885833380c51048e54fbdc7d120fd6034f39 | /Competitions/ICPC/2018/Sub-Regionals/I (Interruptores)/I.cpp | f459489a9166d218e41d688e229070e3a8700393 | [] | no_license | NelsonGomesNeto/Competitive-Programming | 8152ab8aa6a40b311e0704b932fe37a8f770148b | 4d427ae6a06453d36cbf370a7ec3d33e68fdeb1d | refs/heads/master | 2022-05-24T07:06:25.540182 | 2022-04-07T01:35:08 | 2022-04-07T01:35:08 | 201,100,734 | 8 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | cpp | I.cpp | #include <bits/stdc++.h>
using namespace std;
set<pair<vector<int>, int> > visited;
int someOn(vector<int> lamp)
{
for (int i = 0; i < lamp.size(); i ++) if (lamp[i]) return(1);
return(0);
}
int main()
{
int n, m; scanf("%d %d", &n, &m);
vector<int> lamp; for (int i = 0; i < m; i ++) lamp.push_back(0);
int l; scanf("%d", &l);
for (int i = 0, j; i < l ; i ++)
{
scanf("%d", &j); lamp[j - 1] = 1;
}
vector<int> s[n]; int ki;
for (int i = 0; i < n; i ++)
{
scanf("%d", &ki);
for (int j = 0, k; j < ki; j ++)
{
scanf("%d", &k);
s[i].push_back(k - 1);
}
}
// for (int i = 0; i < lamp.size(); i ++) printf("%d", lamp[i]); printf("\n");
int i = 0;
while (someOn(lamp))
{
int pos = i % n;
if (visited.count({lamp, pos})) { i = -1; break; }
visited.insert({lamp, pos});
for (int j = 0; j < s[pos].size(); j ++)
lamp[s[pos][j]] = !lamp[s[pos][j]];
// for (int i = 0; i < lamp.size(); i ++) printf("%d", lamp[i]); printf("\n");
i ++;
}
printf("%d\n", i);
return(0);
} |
87ac4d6d87a67885eec5e8142862fae57c2d2993 | e86c8116ab0542a6b7f6a551344a86139e39f9de | /Framework/Graphics/Source/Private/Materials/Material.cpp | c6a0d785fa69fafa93f99b16f35dc6beac650f39 | [] | no_license | jazzboysc/RTGI | fb1b9eed9272ce48828e9a294529d70be3f61532 | 80290d4e1892948d81427569fb862267407e3c5a | refs/heads/master | 2020-04-14T05:23:38.219651 | 2015-07-17T07:12:48 | 2015-07-17T07:12:48 | 20,085,664 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,280 | cpp | Material.cpp | //----------------------------------------------------------------------------
// Graphics framework for real-time GI study.
// Che Sun at Worcester Polytechnic Institute, Fall 2013.
//----------------------------------------------------------------------------
#include "Material.h"
using namespace RTGI;
//----------------------------------------------------------------------------
Material::Material(MaterialTemplate* materialTemplate)
{
mRenderObject = 0;
mMaterialTemplate = materialTemplate;
}
//----------------------------------------------------------------------------
Material::~Material()
{
mMaterialTemplate = 0;
}
//----------------------------------------------------------------------------
void Material::Apply(int techniqueNum, int passNum)
{
Technique* tech = mMaterialTemplate->GetTechnique(techniqueNum);
RTGI_ASSERT( tech );
Pass* pass = (Pass*)tech->GetPass(passNum);
RTGI_ASSERT( pass );
PassInfo* passInfo = mTechniqueInfo[techniqueNum]->GetPassInfo(passNum);
RTGI_ASSERT( passInfo );
passInfo->Enable();
pass->Enable();
mRenderObject->OnEnableBuffers();
mRenderObject->OnUpdateShaderConstants(techniqueNum, passNum);
mRenderObject->OnRender(pass, passInfo);
mRenderObject->OnDisableBuffers();
pass->Disable();
passInfo->Disable();
}
//----------------------------------------------------------------------------
void Material::CreateDeviceResource(GPUDevice* device,
GeometryAttributes* geometryAttr)
{
mMaterialTemplate->CreateDeviceResource(device);
unsigned int tcount = mMaterialTemplate->GetTechniqueCount();
mTechniqueInfo.reserve(tcount);
for( unsigned int i = 0; i < tcount; ++i )
{
Technique* technique = mMaterialTemplate->GetTechnique((int)i);
TechniqueInfo* techInfo = new TechniqueInfo();
techInfo->CreatePassInfo(technique, geometryAttr);
mTechniqueInfo.push_back(techInfo);
}
}
//----------------------------------------------------------------------------
ShaderProgram* Material::GetProgram(int technique, int pass)
{
Technique* t = mMaterialTemplate->GetTechnique(technique);
Pass* p = (Pass*)t->GetPass(pass);
ShaderProgram* program = p->GetShaderProgram();
return program;
}
//---------------------------------------------------------------------------- |
2c2ec7d1c49ca21d429c70da484103b0684b638d | 0444507fd89d99c81e85498decdcd8b032896573 | /313B.cpp | ba3e1c5e445651c42e2fd45864b4953d4c91b2fa | [] | no_license | AkhilBandi/CF | f3c67dcfa664b136afa9bed832e7dc6f12254e37 | 6e422b5532de6815cd8506dd53e6d930bfbfb4a4 | refs/heads/master | 2020-12-03T08:09:06.395524 | 2017-06-28T11:47:26 | 2017-06-28T11:47:26 | 95,662,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | 313B.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
int d[s.length()-1],c[s.length()-1],e=0;
c[0]=0;
for(int i=0;i<s.length()-1;i++)
{
if(s[i]==s[i+1])
{
d[i]=1;
e++;
}
else
{
d[i]=0;
}
c[i+1]=e;
}
long long int m;
cin>>m;
long long int a[m],b[m];
for(int i=0;i<m;i++)
{
cin>>a[i]>>b[i];
cout<<c[b[i]-1]-c[a[i]-1]<<endl;
}
}
|
6981bbc47fcac4a7cc135eae8c5daa4644c03003 | aad3277bdecc191e8d7002ccbfb6b164b3a8f819 | /examples/Parola_Display/Parola_Display.ino | 05b055631fe0e2e2950628dba66198025273f6f9 | [
"MIT"
] | permissive | kscho8604/MD_Parola_for_RaspberryPi | 99a0864910a1451d85d8969e1dc3575803d32271 | 13c8df200e0c901a8744f8fc9d4b3478b4a36ae3 | refs/heads/master | 2023-08-26T07:26:20.911384 | 2021-10-24T13:22:43 | 2021-10-24T13:22:43 | 285,777,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,382 | ino | Parola_Display.ino | // Program to demonstrate the MD_Parola library
//
// For every string defined by pc[] iterate through all combinations
// of entry and exit effects.
//
// Animation speed can be controlled using a pot on pin SPEED_IN
//
// MD_MAX72XX library can be found at https://github.com/MajicDesigns/MD_MAX72XX
//
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 8
#define CLK_PIN 13
#define DATA_PIN 11
#define CS_PIN 10
// set to 1 if we are implementing the user interface pot
#define USE_UI_CONTROL 0
#if USE_UI_CONTROL
#define SPEED_IN A5
uint8_t frameDelay = 25; // default frame delay value
#endif // USE_UI_CONTROL
// Hardware SPI connection
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// Arbitrary output pins
// MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);
#define SPEED_TIME 25
#define PAUSE_TIME 1000
// Turn on debug statements to the serial output
#define DEBUG 0
#if DEBUG
#define PRINT(s, x) { Serial.print(F(s)); Serial.print(x); }
#define PRINTS(x) Serial.print(F(x))
#define PRINTX(x) Serial.println(x, HEX)
#else
#define PRINT(s, x)
#define PRINTS(x)
#define PRINTX(x)
#endif
// Global variables
uint8_t curText;
const char *pc[] =
{
"Parola for",
"Arduino",
};
uint8_t inFX, outFX;
textEffect_t effect[] =
{
PA_PRINT,
PA_SCAN_HORIZ,
PA_SCROLL_LEFT,
PA_WIPE,
PA_SCROLL_UP_LEFT,
PA_SCROLL_UP,
PA_OPENING_CURSOR,
PA_GROW_UP,
PA_MESH,
PA_SCROLL_UP_RIGHT,
PA_BLINDS,
PA_CLOSING,
PA_RANDOM,
PA_GROW_DOWN,
PA_SCAN_VERT,
PA_SCROLL_DOWN_LEFT,
PA_WIPE_CURSOR,
PA_DISSOLVE,
PA_OPENING,
PA_CLOSING_CURSOR,
PA_SCROLL_DOWN_RIGHT,
PA_SCROLL_RIGHT,
PA_SLICE,
PA_SCROLL_DOWN,
};
#if USE_UI_CONTROL
void doUI(void)
{
// set the speed if it has changed
{
int16_t speed = map(analogRead(SPEED_IN), 0, 1023, 0, 250);
if (speed != (int16_t)P.getSpeed())
{
P.setSpeed(speed);
P.setPause(speed);
frameDelay = speed;
PRINT("\nChanged speed to ", P.getSpeed());
}
}
}
#endif // USE_UI_CONTROL
void setup(void)
{
Serial.begin(57600);
PRINTS("[Parola Demo]");
#if USE_UI_CONTROL
pinMode(SPEED_IN, INPUT);
doUI();
#endif // USE_UI_CONTROL
P.begin();
P.setInvert(false);
P.displayText(pc[curText], PA_CENTER, SPEED_TIME, PAUSE_TIME, effect[inFX], effect[outFX]);
}
void loop(void)
{
#if USE_UI_CONTROL
doUI();
#endif // USE_UI_CONTROL
if (P.displayAnimate()) // animates and returns true when an animation is completed
{
// Set the display for the next string.
curText = (curText + 1) % ARRAY_SIZE(pc);
P.setTextBuffer(pc[curText]);
// When we have gone back to the first string, set a new exit effect
// and when we have done all those set a new entry effect.
if (curText == 0)
{
outFX = (outFX + 1) % ARRAY_SIZE(effect);
if (outFX == 0)
{
inFX = (inFX + 1) % ARRAY_SIZE(effect);
if (inFX == 0)
P.setInvert(!P.getInvert());
}
P.setTextEffect(effect[inFX], effect[outFX]);
}
// Tell Parola we have a new animation
P.displayReset();
}
}
|
ab3485cf0a44731b3454e50e221d95e5a3b1d73b | a14a08706912dc788690fb86808802687dc7908b | /matrix_stat.h | c5fdbd2d47724fb5065682cea34a49bc7a8e656f | [
"MIT"
] | permissive | Fitzclutchington/spt_mask_NOAA | a4c2d3e92fea9d89f76df86a29569096db8c88ae | 0f752b2c0730e75e8c04098cc75dcd3492addf77 | refs/heads/master | 2021-01-20T02:32:44.570167 | 2017-08-31T21:40:34 | 2017-08-31T21:40:34 | 101,324,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,221 | h | matrix_stat.h | #ifndef MATRIX_STAT_H_
#define MATRIX_STAT_H_
#include <vector>
#include <algorithm>
namespace acspo {
template <typename T>
double sum(const matrix<T> &mat)
{
unsigned int elem = mat.elem();
unsigned int count = 0;
double ret = 0;
#pragma omp parallel for reduction(+:ret,count)
for (unsigned int i = 0; i < elem; i++) {
if (!std::isnan(mat(i))) {
ret += mat(i);
count++;
}
}
if (count == 0) {
return NAN;
}
return ret;
}
template <typename T>
double mean(const matrix<T> &mat)
{
unsigned int elem = mat.elem();
unsigned int count = 0;
double ret = 0;
#pragma omp parallel for reduction(+:ret,count)
for (unsigned int i = 0; i < elem; i++) {
if (!std::isnan(mat(i))) {
ret += mat(i);
count++;
}
}
if (count == 0) {
return NAN;
}
ret /= count;
return ret;
}
template <typename T>
double var(const matrix<T> &mat, double avg)
{
unsigned int elem = mat.elem();
unsigned int count = 0;
double ret = 0;
#pragma omp parallel for reduction(+:ret,count)
for (unsigned int i = 0; i < elem; i++) {
if (!std::isnan(mat(i))) {
ret += (mat(i)-avg)*(mat(i)-avg);
count++;
}
}
if (count == 0) {
return NAN;
}
ret /= count;
return ret;
}
template <typename T>
double var(const matrix<T> &mat)
{
return var(mat, mean(mat));
}
template <typename T>
double std_dev(const matrix<T> &mat, double avg)
{
return std::sqrt(var(mat, avg));
}
template <typename T>
double std_dev(const matrix<T> &mat)
{
return std::sqrt(var(mat));
}
template <typename T>
double med(const matrix<T> &mat)
{
unsigned int elem = mat.elem();
std::vector<double> buf;
buf.reserve(elem);
for (unsigned int i = 0; i < elem; i++) {
if (!std::isnan(mat(i))) {
buf.push_back(mat(i));
}
}
if (buf.size() == 0) {
return NAN;
}
std::sort(buf.begin(), buf.end());
if (buf.size() % 2 == 1) {
return buf[(buf.size()-1)/2];
} else {
return 0.5*(buf[buf.size()/2-1]+buf[buf.size()/2]);
}
}
}
#endif
|
dc9a07272d4e6a225c26f3906ecf2a945813196a | 3e421f80c8b31138681e0bf92145f2e81b4e4012 | /xtree.h | 5e24b068972072134ace0c4d8fca4d11ccec62b9 | [] | no_license | anibalvale666/XTree | 9969fb6f4a2ade707d146c325bff4234e8927f05 | b9a0200a65eb3c6de41d84cabf44958dce554afe | refs/heads/master | 2020-04-11T04:29:31.491822 | 2018-12-12T17:54:41 | 2018-12-12T17:54:41 | 161,513,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,594 | h | xtree.h | #ifndef XTREE_H
#define XTREE_H
#include "xtreenode.h"
#include "xtreenode.cpp"
template<class T>
class CXTree
{
public:
CXTree(){} // constructor vacio;
CXTree(int,int,int,int,int);
bool find_point(T x,CXTreeNode<T> * &p);
//-funciones usadas en la insercion y auxiliares
bool insert_point(CPoint<T> );
void choose_leaf(CPoint<T> ,vector<pair< CXTreeNode<T> *,int > > & );
void pick_seeds(CXTreeNode<T> * ,CMbr<T> &, CMbr<T> &,int (&)[2]);
void pick_next(CXTreeNode<T> *,int &,CMbr<T> , CMbr<T> );
void adjust_tree(vector<pair< CXTreeNode<T> *,int > > & );
void split(CXTreeNode<T> *,CXTreeNode<T> * ,int );
//funciones asterisco
void split_ast(CXTreeNode<T> *,CXTreeNode<T> * ,int ); //306
int choose_split_axis(vector<CMbr<T> > );
void choose_split_index(CXTreeNode<T>, CXTreeNode<T> &, CXTreeNode<T> &, int );
//static bool sort_node_min(const CMbr<T> &, const CMbr<T> &);
//static bool sort_node_max(const CMbr<T> &, const CMbr<T> &);
//funciones xTREe
int insert(CPoint<T>,CXTreeNode<T> **);
void split_x(CXTreeNode<T> *,CXTreeNode<T> * ,int );
void topological_split(CXTreeNode<T> ,CXTreeNode<T> &, CXTreeNode<T> &); //147
void overlap_minimal_split(CXTreeNode<T> ,CXTreeNode<T> &, CXTreeNode<T> &); //
//knn
void search_k_points(int ,CPoint<T>,vector<CPoint<T> >&);
//funcion print
void print();
void drawTree();
CXTreeNode<T> *cxt_root;
private:
int cxt_M;
int cxt_x_min, cxt_y_min, cxt_x_max, cxt_y_max;
int MAX_Overlap=0.2; //20%
};
#endif
|
1e2144d9dbfb68fd26bf473a517dcc5a870e7e11 | 561943d7f7700aae9795b3a6fba6b0130ca02b77 | /include/enb.h | cb9540a1b56d3392f752e033cb579920a5ad149c | [] | no_license | ziseputi/Security_Simulator | 5985563d3364b98fefcb1765082a923c674b018f | 84898c35f3b1b605dd6997cf300ecbe25ec2f4e0 | refs/heads/master | 2021-05-21T08:09:34.935602 | 2017-05-11T08:55:07 | 2017-05-11T08:55:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | enb.h | #include "utils.h"
#include "kdf.h"
#include "eea_eia.h"
#include "rrc_pdu.h"
class enb
{
public:
enb();
~enb();
u8 *output;
int output_len;
u8 *kenb;
u8 *krrc_int;
u8 *krrc_enc;
u8 *kup_enc;
rrc_pdu *rrc;
u8 *rrc_message;
int rrc_message_len;
u8 *mac_i;
void init(u8 *k);
void update(u8 *input, int input_len);
void sec_mode_command(u8 encID, u8 incID);
private:
}; |
a91bb5e6dadf8966bf08b67e5a4c06eff036c6ad | 2fb9ace11c3d6d6012d94489a5f9a28d96ba1d33 | /백준/4344_평균은 넘겠지.cpp | 4c637c3a1d7c4306ec31b09a9831ea9470afab32 | [] | no_license | benjykim/algo-practice | 65ceb6dd9b044074bda2983b072cfef59f36b54a | 61ea6cdbd5b72c2ef896d08e8845c7229b0b0bac | refs/heads/master | 2020-03-28T03:38:15.684004 | 2019-05-25T03:29:19 | 2019-05-25T03:29:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | cpp | 4344_평균은 넘겠지.cpp | #include <stdio.h>
#include <stdlib.h>
int main()
{
int testCase, i, j, n, count = 0, sum = 0;
double average = 0;
int *arr;
double *result;
scanf("%d", &testCase);
result = (double *)malloc(sizeof(double)*testCase);
for (i = 0; i < testCase; i++) {
average = 0; sum = 0;
scanf("%d", &n);
arr = (int *)malloc(sizeof(int)*n);
for (j = 0; j < n; j++) {
scanf("%d", &arr[j]);
sum += arr[j];
}
average = sum / n;
for (j = 0;j < n;j++) {
if (arr[j] > average)
count++;
}
result[i] = count * 100.0 / n;
}
for (i = 0; i < testCase; i++)
printf("%.3lf%%\n", result[i]);
}
|
8270ec4425792f9843cf9db9487f151a337ef294 | 57842ce1d350a72b802727f3a3aee8ec4f77ac38 | /ConsoleApplication1/ConsoleApplication1.cpp | 6fec143a80a8e95595c579e69ae5d832fd446ff0 | [] | no_license | siddharthsyal/File-Encryption-Using-Intel-SGX | f4ac86f3d37a8ce08042b26da26dcdef1d9403a5 | fc4f96adb68567becd6289de78032b43d81a90bc | refs/heads/master | 2020-04-04T21:39:10.333307 | 2018-12-14T01:14:38 | 2018-12-14T01:14:38 | 156,294,142 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,968 | cpp | ConsoleApplication1.cpp | #include "pch.h"
#include "sgx_tseal.h"
#include "Enclave1_u.h"
#include "sgx_urts.h"
#include <string>
#include "sgx_tcrypto.h"
#include <fstream>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include "mbedtls/net_sockets.h"
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/certs.h"
#include <windows.h>
#include <algorithm>
#include <cctype>
#include <conio.h>
#define ENCLAVE_FILE "Enclave1.signed.dll"
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <windows.h>
#include <stdlib.h>
#include <wincrypt.h>
#define mbedtls_time time
#define mbedtls_time_t time_t
#define mbedtls_fprintf fprintf
#define mbedtls_printf printf
#define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
#define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
#endif
#define DEBUG_LEVEL 1
static void my_debug(void *ctx, int level,
const char *file, int line,
const char *str)
{
((void)level);
mbedtls_fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
fflush((FILE *)ctx);
}
using namespace std;
int makeConnection(string request,std::string &result) {
#define SERVER_PORT "443"
#define SERVER_NAME "127.0.0.1"
#define GET_REQUEST = request
//"GET /verify?username=John&&password=1password HTTP/1.0\r\n\r\n"
int ret = 1, len;
std::string result_data;
int exit_code = MBEDTLS_EXIT_FAILURE;
mbedtls_net_context server_fd;
uint32_t flags;
unsigned char buf[1024];
const char *pers = "ssl_client1";
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_x509_crt cacert;
HCERTSTORE hSystemStore;
PCCERT_CONTEXT pCertContext = NULL;
mbedtls_x509_crt_init(&cacert);
//PCCERT_CONTEXT pCertContext1 = NULL;
#if defined(MBEDTLS_DEBUG_C)
mbedtls_debug_set_threshold(DEBUG_LEVEL);
#endif
/*
* 0. Initialize the RNG and the session data
*/
mbedtls_net_init(&server_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_x509_crt_init(&cacert);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_printf("\nInitializing Random Number Generator : ");
fflush(stdout);
mbedtls_entropy_init(&entropy);
if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
(const unsigned char *)pers,
strlen(pers))) != 0)
{
mbedtls_printf(" failed\n ! mbedtls_ctr_drbg_seed returned %d\n", ret);
goto exit;
}
mbedtls_printf("ok\n");
/*
* 0. Initialize certificates
*/
/*Taking the certficates from the root windows store*/
mbedtls_printf("Loading the CA root certificate :");
fflush(stdout);
if (hSystemStore = CertOpenSystemStore(0, "ROOT")) {
while (pCertContext = CertEnumCertificatesInStore(hSystemStore, pCertContext)) {
if (pCertContext->dwCertEncodingType == X509_ASN_ENCODING) {
mbedtls_x509_crt_parse(&cacert, pCertContext->pbCertEncoded, pCertContext->cbCertEncoded);
}
}
}
ret = mbedtls_x509_crt_parse(&cacert, (const unsigned char *)mbedtls_test_cas_pem,
mbedtls_test_cas_pem_len);
if (ret < 0)
{
mbedtls_printf("\nIssue : Certificate Parsing \n");
goto exit;
}
mbedtls_printf(" ok (%d skipped)\n", ret);
/*
* 1. Start the connection
*/
mbedtls_printf("Connecting to tcp/%s/%s : ", SERVER_NAME, SERVER_PORT);
fflush(stdout);
if ((ret = mbedtls_net_connect(&server_fd, SERVER_NAME,
SERVER_PORT, MBEDTLS_NET_PROTO_TCP)) != 0)
{
mbedtls_printf("Issue : TCP Issue\n");
goto exit;
}
mbedtls_printf("ok\n");
/*
* 2. Setup stuff
*/
mbedtls_printf("Initialzing TLS stack : ");
fflush(stdout);
if ((ret = mbedtls_ssl_config_defaults(&conf,
MBEDTLS_SSL_IS_CLIENT,//Checking if SSL/TLS layer acts as client or server
MBEDTLS_SSL_TRANSPORT_STREAM,//Checking if using TLS or DTLS
MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
{
mbedtls_printf("Issue : TLS config error\n");
goto exit;
}
/*Checks for validity of the server cert. Currently verfication is optional*/
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE);
mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0)
{
goto exit;
}
if ((ret = mbedtls_ssl_set_hostname(&ssl, SERVER_NAME)) != 0)
{
goto exit;
}
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
/*
* 4. Handshake
*/
mbedtls_printf("Performing TLS handshake...");
fflush(stdout);
while ((ret = mbedtls_ssl_handshake(&ssl)) != 0)
{
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
{
mbedtls_printf(" failed\n ! mbedtls_ssl_handshake returned -0x%x\n\n", -ret);
goto exit;
}
}
mbedtls_printf(" ok\n");
/*
* 5. Verify the server certificate
*/
mbedtls_printf("Verifying peer X.509 certificate : ");
/* In real life, we probably want to bail out when ret != 0 */
if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0)
{
char vrfy_buf[512];
mbedtls_printf(" failed\n");
mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", flags);
mbedtls_printf("%s\n", vrfy_buf);
}
else
mbedtls_printf(" ok\n");
/*
* 3. Write the GET request
*/
mbedtls_printf("\nSending Request");
fflush(stdout);
len = strlen(request.c_str());
strncpy((char*)buf, request.c_str(),len);
//len = sizeof(request);
//buf = request;
while ((ret = mbedtls_ssl_write(&ssl, buf, len)) <= 0)
{
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
{
goto exit;
}
}
len = ret;
mbedtls_printf("\nRequest Sent \n");
/*
* 7. Read the HTTP response
*/
mbedtls_printf("Response from the server : ");
fflush(stdout);
do
{
len = sizeof(buf) - 1;
memset(buf, 0, sizeof(buf));
ret = mbedtls_ssl_read(&ssl, buf, len);
char *data = strstr((char *)buf, "\r\n\r\n");
if (data != NULL) {
result_data = data;
result_data.erase(std::remove_if(result_data.begin(), result_data.end(), ::isspace), result_data.end());
result = result_data;
break;
}
} while (1);
// mbedtls_ssl_close_notify(&ssl);
if (mbedtls_ssl_close_notify(&ssl) == 0)
{
mbedtls_printf("TLS Connection Terminated\n");
}
exit_code = MBEDTLS_EXIT_SUCCESS;
exit:
#ifdef MBEDTLS_ERROR_C
if (exit_code != MBEDTLS_EXIT_SUCCESS)
{
mbedtls_printf("Connection Failure\n");
}
#endif
mbedtls_net_free(&server_fd);
mbedtls_x509_crt_free(&cacert);
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
return exit_code;
}
void randomnessToFile(long flength, FILE *fp) {
long i = 0;
string random;
for (i = 0; i < flength; i++) {
random += rand();
}
fputs(random.c_str(), fp);
}
void decryptFile() {
/*Delarations*/
string plaintext_filename;
string filename;
string seal_filename;
FILE *fp;
long flength;
long seal_length;
errno_t err = 0;
size_t seal_size_check;
size_t plaintext_size_check;
/*Debug Variables*/
char debug[15] = "SUCCESS";
uint8_t debug_size = 15;
/*Enclave Initialization*/
sgx_enclave_id_t eid;//Enclave ID
sgx_status_t ret = SGX_SUCCESS; // For Checking if enclave was created successfully
//sgx_status_t ret2;
int updated = 0;
sgx_launch_token_t token = { 0 };
ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL);
if (ret != SGX_SUCCESS)
{
printf("\nEnclave Cannot be initialized\n");
return;
}
printf("\nSecure Enclave Initialized\n");
/*Sealed Data mem allocation*/
uint32_t sealed_data_size = 0;
sizeOfSealData(eid, &sealed_data_size);
sgx_sealed_data_t *sealed_data = (sgx_sealed_data_t *)malloc((sealed_data_size)*(sizeof(sgx_sealed_data_t)));
/*Getting sealed data file location*/
cin.sync();
printf("\nPlease enter the file path for sealed data file. Format : Z:\\sample1.txt\n");
cin >> seal_filename;
cin.sync();
/*Reading Sealed Data*/
if ((err = fopen_s(&fp, seal_filename.c_str(), "r")) != 0) {//"E:/sample1.txt"
printf("\nFile Read Error \n");
return;
}
if (fseek(fp, 0L, SEEK_END) == 0) //Getting the length of the text in the file
seal_length = ftell(fp);
if (fseek(fp, 0L, SEEK_SET) != 0) {
printf("\nFile Pointer Error\n");
return;
}
seal_size_check = fread(sealed_data, sizeof(sgx_sealed_data_t), sealed_data_size, fp);
if (sealed_data_size != seal_size_check) {
printf("\nThere is an issue with sealed data\n");
return;
}
fclose(fp);
/*Getting Cipher Text File Location*/
printf("\nPlease enter the file path for ciphertext file. Format : Z:\\sample1.txt\n");
cin >> filename;
cin.sync();
/*CipherText File operations*/
if ((err = fopen_s(&fp, filename.c_str(), "r+")) != 0) {//"E:/sample1.txt"
printf("\nFile Read Error \n");
return;
}
if (fseek(fp, 0L, SEEK_END) == 0) //Getting the length of the text in the file
flength = ftell(fp);
char *content = (char *)malloc((flength)*(sizeof(char)));
if (fseek(fp, 0L, SEEK_SET) != 0) {
printf("\nFile Pointer Error\n");
return;
}
size_t read_length = fread(content, sizeof(char), flength, fp);
if (read_length != flength) {
printf("Read Error");
// return;
}
/*Ramdomising content in the ciphertext file*/
if (fseek(fp, 0L, SEEK_SET) != 0) {
printf("\nFile Pointer Error\n");
return;
}
randomnessToFile(flength, fp);
fclose(fp);
/*Removing the cipher file*/
if (remove(filename.c_str()) != 0) {
printf("\nFile removal error\n");
return;
}
/*Plaintext Memory Alloc*/
int length = flength - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE;
char* plaintext = (char *)malloc((length)*(sizeof(char)));
/*Decrypting Cipher Text*/
printf("\nDecryption Started\n");
decryptText(eid, content, flength, plaintext, length, (sgx_sealed_data_t *)sealed_data, sealed_data_size, debug, debug_size);
if (!strcmp(debug, "SUCCESS")) {
printf("Error State.\nDebug Information - %s\n", debug);
goto free_memory_dnc;
}
printf("\nFile Decryption Successful\n");
/*Saving the plaintext to File*/
cin.sync();
printf("\nEnter the path with filename for storing plaintext data. Example : Z:\\sample.txt\n");
cin >> plaintext_filename;
cin.sync();
while (ifstream(plaintext_filename.c_str())) {
printf("\nFile Already Exists\n");
printf("\nEnter the path with filename for storing plaintext data. Example : Z:\\sample.txt\n");
cin.sync();
getline(cin, plaintext_filename);
}
cin.sync();
fopen_s(&fp, plaintext_filename.c_str(), "wb");
plaintext_size_check = fwrite(plaintext, (size_t)sizeof(char), (size_t)length, fp);
if (plaintext_size_check != (size_t)length)
printf("\nError in Saving plaintext Data\n");
fclose(fp);
printf("\nPlaintext data written to the disk\n");
/*Enclave Destruction*/
if (SGX_SUCCESS != sgx_destroy_enclave(eid)) {
printf("Enclave is not securely detroyed");
}
/*Free Memory Space*/
free_memory_dnc:
free(sealed_data);
free(plaintext);
free(content);
printf("\nSecure Exit\n");
return;
}
void encryptFile() {
/*Delarations*/
string filename;
FILE *fp;
FILE *f_seal;
long flength;
errno_t err = 0;
size_t seal_size_check, cipher_size_check;
/*Debug Variables*/
char debug[15] = "SUCCESS";
uint8_t debug_size = 15;
/*Getting File Location*/
cin.clear();
cin.ignore();
printf("\nPlease enter the file path for plaintext file. Format : Z:\\sample1.txt\n");
getline(cin, filename);
/*File operations*/
if ((err = fopen_s(&fp, filename.c_str(), "r+")) != 0) {//"E:\sample1.txt"
printf("\nFile Read Error \n");
return;
}
if (fseek(fp, 0L, SEEK_END) == 0) //Getting the length of the text in the file
flength = ftell(fp);
char *content = (char *)malloc((flength)*(sizeof(char)));
if (fseek(fp, 0L, SEEK_SET) != 0) {
printf("\nFile Pointer Error\n");
return;
}
size_t read_length = fread(content, sizeof(char), flength, fp);
if (read_length != flength) {
printf("Read Error");
return;
}
/*Ramdomising content in the plaintext file*/
if (fseek(fp, 0L, SEEK_SET) != 0) {
printf("\nFile Pointer Error\n");
return;
}
randomnessToFile(flength, fp);
fclose(fp);
/*Removing the plaintext file*/
if (remove(filename.c_str()) != 0) {
printf("\nFile removal error\n");
return;
}
/*Enclave Initialization*/
sgx_enclave_id_t eid;//Enclave ID
sgx_status_t ret = SGX_SUCCESS; // For Checking if enclave was created successfully
int updated = 0;
sgx_launch_token_t token = { 0 };
ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL);
if (ret != SGX_SUCCESS)
{
printf("\nEnclave Cannot be initialized\n");
return;
}
printf("\nSecure Enclave Initialized\n");
/*Enclave Sealing data declaration*/
uint32_t sealed_data_size = 0;
sizeOfSealData(eid, &sealed_data_size);
sgx_sealed_data_t *sealed_data = (sgx_sealed_data_t *)malloc((sealed_data_size)*(sizeof(sgx_sealed_data_t)));//Space allocation for sealed data
/*CipherText length allocation*/
size_t plaintext_len = flength;
size_t ciphertext_len = plaintext_len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
char* cipherText = (char *)malloc((ciphertext_len)*(sizeof(char)));
char * recovered = (char *)malloc((plaintext_len)*(sizeof(char)));
/*Getting Sealed Key for bulk enc*/
seal(eid, (sgx_sealed_data_t *)sealed_data, sealed_data_size, debug, debug_size);
if (!strcmp(debug, "SUCCESS")) {
printf("Error State.\nDebug Information - %s\n", debug);
goto free_enc_mem;
}
/*Encrypting Data*/
printf("\nFile Encryption Started\n");
encryptText(eid, content, plaintext_len, cipherText, ciphertext_len, (sgx_sealed_data_t *)sealed_data, sealed_data_size, debug, debug_size);//Calling Encalve function for encryption
if (!strcmp(debug, "SUCCESS")) {
printf("Error State.\nDebug Information - %s\n", debug);
goto free_enc_mem;
}
printf("\nFile Encryption Successful\n");
/*Func to write the cipherText to a new file*/
printf("\nEnter the path with filename for storing ciphertext. Example : Z:\\sample.txt\n");
getline(cin, filename);
while (ifstream(filename.c_str())) {
printf("\nFile Already Exists\n");
printf("\nEnter the path with filename for storing ciphertext. Example : Z:\\sample.txt\n");
getline(cin, filename);
}
fopen_s(&fp, filename.c_str(), "wb");
cipher_size_check = fwrite(cipherText, sizeof(char), ciphertext_len, fp);
if (cipher_size_check != ciphertext_len)
printf("\nError Saving Cipher Text\n");
fclose(fp);
printf("\nCiphertext written to the disk\n");
/*Funct to save sealed data*/
printf("\nEnter the path with filename for storing sealed data. Example : Z:\\sample.txt\n");
getline(cin, filename);
while (ifstream(filename.c_str())) {
printf("\nFile Already Exists\n");
printf("\nEnter the path with filename for storing sealed data. Example : Z:\\sample.txt\n");
getline(cin, filename);
}
fopen_s(&f_seal, filename.c_str(), "wb");
seal_size_check = fwrite(sealed_data, (size_t)sizeof(sgx_sealed_data_t), (size_t)sealed_data_size, f_seal);
if (seal_size_check != sealed_data_size)
printf("\nError in Saving Sealing Data\n");
fclose(f_seal);
printf("\nSealed data written to the disk\n");
/*Debug Stuff*/
//decryptText(eid, cipherText, ciphertext_len, recovered, plaintext_len, (sgx_sealed_data_t *)sealed_data, sealed_data_size, debug, debug_size);
//recovered[plaintext_len] = '\0';
//printf("\nrecovered\n");
//printf(recovered);
/*Enclave Destruction*/
if (SGX_SUCCESS != sgx_destroy_enclave(eid)) {
printf("Enclave is not securely detroyed");
}
/*Realeasing memory*/
free_enc_mem:
free(content);
free(sealed_data);
free(cipherText);
/*All Good. Exiting Now*/
printf("\nSecure Exit\n");
return;
}
int main() {
printf("************************ SGX File Encryption Utility **********************\nPlease provide the authentication data \n");
int choice = 0, user_input = 0;
string get = "GET /verify?username=";
string username;
string password;
char buffer = NULL;
char *result= NULL;
std::string result_data;
printf("Enter the Username\n");
cin >> username;
get = get + username + "&&password=";
printf("Enter the password : \n");
do {
if (buffer != NULL){
password.push_back(buffer);
}
buffer = _getch();
cout << '*';
} while (buffer != ' ');
get = get + password + " HTTP/1.0\r\n\r\n";
int connection_result = makeConnection(get,result_data);
if (connection_result != 0) {
return 0;
}
if (result_data.compare("true")==0){
printf("\nAuthentication Successful\n");
printf("Select from either one : \n1) Encrypt a file\n2) Decrypt a file\n Enter choice : ");
cin.clear();
cin >> choice;
switch (choice) {
case 1:
cin.clear();
encryptFile();
break;
case 2:
decryptFile();
break;
defualt:
printf("Ooops! Wrong input");
break;
}
}
else {
printf("Invalid Authentication\n");
}
return 0;
}
|
96d7fe7bb276cfea14209769a8cad559862fb668 | 7a2c0a3d86e0365ae0c099d06e5086e03b1ef9f0 | /Tsibu/src/common/include/BaseFSMVariable.hpp | 333684f0c7f04d10352b03503b3e3da3d9ce6935 | [] | no_license | rnvandemark/Tsibu | 9fd4f9b3b3b58a0fe51d00d2e475e79954f3d70b | ac04ad144a5ae0103d625c16679c69838bb06f3b | refs/heads/master | 2020-05-02T10:45:15.746720 | 2019-09-03T11:55:17 | 2019-09-03T11:55:17 | 177,906,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | hpp | BaseFSMVariable.hpp | #ifndef TSIBU_BASE_FSM_VARIABLE_HPP
#define TSIBU_BASE_FSM_VARIABLE_HPP
/*
* This class represents the base container for a variable value in a finite state machine.
* There is so significance to this class, it is here to act as a base type for the FSMVariable class.
*/
class BaseFSMVariable
{
public:
/*
* The default destructor.
* A virtual destructor, to establish polymorphism.
*/
virtual ~BaseFSMVariable() = default;
};
#endif /* TSIBU_BASE_FSM_VARIABLE_HPP */
|
435299d4ee3518ad64f79f73effc6b1892a3b047 | 5eaf51ca42d1c346e4b5bad5e12f8fcfede61027 | /VOI2018/POTION.cpp | dcf7d05a2d3f2b7f2d8cb5ae2b4d343d0fc1b1cb | [] | no_license | KhoaNguyenAn/Algorithm | 5d78d7b967f6a20b8b76f33c5c4abf02df1d87e5 | 6e6f1be32e3b9bccfc9b617480dd5d4840dcc999 | refs/heads/master | 2023-07-28T04:57:08.330515 | 2021-09-12T02:48:44 | 2021-09-12T02:48:44 | 405,529,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | cpp | POTION.cpp | #include <iostream>
#include <bits/stdc++.h>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#define ll long long
using namespace std;
const int N = 1e5 +2;
const int INF = 1e9 + 7;
long long n,m,a[N];
long double l,r,sum,ans,mid;
long long check(long double x)
{
long long res = 0;
for (int j = 1; j <= m; j++) res = res + long(floor(a[j]/x));
return res;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
freopen("POTION.INP","r",stdin);
freopen("POTION.OUT","w",stdout);
cin >> n >> m;
sum = 0;
for (int i = 1; i <= m; i++)
{
cin >> a[i];
sum += a[i];
}
sum /= n;
if (check(sum)==n)
{
cout << sum;
return 0;
}
l = 0;
r = sum;
for (int i = 1; i <= 600; i++)
{
mid = (l+r) /2;
ans = check(mid);
if (ans >= n) l = mid; else r = mid;
}
cout << setprecision(6) << fixed << mid;
} |
2383e81142a8fcbc8b599573e60163c652f469ee | b4481f7de9ac8491ee1ff1dadddec26740df9bca | /Spelprojekt/Spelprojekt/src/Align16.h | 62c08f8ced875a7b9999fa5f3da4e1b66ec7bc5c | [] | no_license | oroosvall/LitetSpelprojekt | d4ecb782fe977744116e80678125f59b96f47616 | 4ba093d60626e1c29fa0cd05843b1e53bf2a0912 | refs/heads/master | 2022-05-02T21:41:26.224589 | 2015-05-26T16:32:33 | 2015-05-26T16:32:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | h | Align16.h | #ifndef ALIGN16_H
#define ALIGN16_H
#include <malloc.h>
class Align_16
{
public:
void* operator new(size_t i)
{
return _aligned_malloc(i, 16);
}
void* operator new[](size_t count)
{
return _aligned_malloc(count, 16);
}
void operator delete(void* p)
{
_aligned_free(p);
}
void operator delete[](void* p)
{
_aligned_free(p);
}
};
#endif |
032ce64e7acbfc240cc0bee166eee1bf55fb60f8 | 4a258cdf90b0552ff369a51d788ecfbbaec570f2 | /include/Tracks.h | 2633a7fbbbb1a08cfcf78a8e8adbe3cad03d94df | [] | no_license | sakamoto-poteko/Chewie | 466185e52fa9494bc424b4eb97edc4637fdf4ca7 | c597ec1ef4de0f9c74d1b8395dfe33a5aaba73bf | refs/heads/master | 2020-05-29T11:51:17.606031 | 2014-12-19T21:08:20 | 2014-12-19T21:08:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,153 | h | Tracks.h | #ifndef TRACKS_H
#define TRACKS_H
#include "Analysis.h"
#include <TTreeFormula.h>
#include <TFile.h>
#include <vector>
#include <iostream>
class TH1F ;
class TH2F ;
class AnalysisManager;
class PlanesMapping ;
class XmlParser ;
class XmlPlane ;
class Tracks : public Analysis
{
public:
Tracks (AnalysisManager* analysisManager = 0, int nOfThreads = 1);
~Tracks (void );
void beginJob (void );
void analyze (const Data& data , int threadNumber );
void endJob (void );
void setCutsFormula (std::map<std::string,std::string> cutsList, std::vector<TTree*> tree);
void getInFile (TFile * ){}
void numberOfTracksAnalysis (const Data& data, int threadNumber );
private:
void PositionUnfolded_prepare (int planeID, const Data& data, int threadNumber);
void PositionUnfolded_book ();
void book (void );
void destroy (void );
bool passStandardCuts (int planeID, const Data& data );
//void makeHistograms (const Data& data, int threadNumber);
PlanesMapping* thePlaneMapping_ ;
TH1F* hChi2_ ;
TH1F* hXSlope_ ;
TH1F* hSigmaXSlope_ ;
TH1F* hYSlope_ ;
TH1F* hSigmaYSlope_ ;
TH1F* hXIntercept_ ;
TH1F* hSigmaXIntercept_ ;
TH1F* hYIntercept_ ;
TH1F* hSigmaYIntercept_ ;
std::vector<TH2F*> hClusterHits_ ;
std::vector<TH1F*> hClusterProfileX_ ;
std::vector<TH1F*> hClusterProfileY_ ;
std::vector<TH1F*> hXError_ ;
std::vector<TH1F*> hYError_ ;
std::vector<TH2F*> hTracksProjRC_ ;
std::vector<TH2F*> hTracksProjXY_ ;
std::vector<TH2F*> hTracksProjXYPix_ ;
std::vector<TH2F*> hTracksProjXYPixAboveBeam_ ;
std::vector<TH2F*> hTracksProjXYPixBelowBeam_ ;
std::vector<TH2F*> hTracksProjXYPixLeftOfBeam_ ;
std::vector<TH2F*> hTracksProjXYPixRightOfBeam_;
std::vector<TH2F*> hTracksProjXYPixQuad1_;
std::vector<TH2F*> hTracksProjXYPixQuad2_;
std::vector<TH2F*> hTracksProjXYPixQuad3_;
std::vector<TH2F*> hTracksProjXYPixQuad4_;
std::vector<TH2F*> hTracksProjRCQuad1_;
std::vector<TH2F*> hTracksProjRCQuad2_;
std::vector<TH2F*> hTracksProjRCQuad3_;
std::vector<TH2F*> hTracksProjRCQuad4_;
std::vector<TH2F*> hTracksProjRCEdges_;
std::vector<TH2F*> hTracksProjRCRecon_;
std::vector<TH1F*> hTracksProjXPixError_;
std::vector<TH1F*> hTracksProjYPixError_;
std::vector<TH1F*> hXdistribution1D_ ;
std::vector<TH1F*> hXdistribution2D_ ;
std::vector<TH2F*> hXChargedistribution1D_;
std::vector<TH2F*> hXChargedistribution2D_;
std::vector<TH1F*> hYdistribution1D_ ;
std::vector<TH1F*> hYdistribution2D_ ;
std::vector<TH2F*> hYChargedistribution1D_;
std::vector<TH2F*> hYChargedistribution2D_;
std::vector<TH2F*> XProbabilityFunc_;
std::vector<TH2F*> YProbabilityFunc_;
std::vector<TH2F*> hClusterHitsNorm_;
std::vector<TH2F*> ClusterSizeHits_;
std::vector<std::map<int, TH2F*> > hTrackHitsCols_;
std::vector<int> cols_ ;//to declare which cols to select, initiated in constructor
TH1F* hNumberOfTracks_ ;
TH1F* hRunNumber_ ;
TH1F* hEventNumber_ ;
TH1F* hTracksVsEvNumber_;
std::map<int, TH1F*> mEvNumberRun_ ;
};
#endif // TRACKS_H
|
ca61ce6d778aca55def0ea4577e00e04ac60f7d8 | 47fb53066a178fecee386fb8ca0ab942392c34b7 | /src/mg/defintArea.cpp | eb7833ea803edf1d6c6b510be0e9a1eb926d86db | [] | no_license | zephyrer/mgcl | 9eae7017ca728c6c565a74d16229146fa5e877f3 | c63b24d5c5f0423acffe84bd4a2208ab2629d2f8 | refs/heads/master | 2020-05-20T04:17:24.355869 | 2018-08-18T08:35:42 | 2018-08-18T08:35:42 | 40,066,710 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp | defintArea.cpp | /********************************************************************/
/* Copyright (c) 2011 DG Technologies Inc. and Yuzi Mizuno */
/* All rights reserved. */
/* Granted under the MIT license (see mg/MGCL.h for detail) */
/********************************************************************/
#include "MGCLStdAfx.h"
#include "mg/defintArea.h"
#if defined(_DEBUG)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//*****************************************************
// Generate points and weights of the DE formula for DEFINT
// in double precision.
// ***************************************************** *
void MGDefintArea::init(){
if(m_nend>0) return;
m_nend=mgdefintlen;
int nendm1=m_nend-1;
m_npow=6;
m_eps0=1e-32;
const double a9 = .9999999999999998;
// --- start computation of points and weights ---
double ph = atan(1.) * 2.;
m_a0[0] = 0.;
m_a0[1] = 1.;
m_b0 = ph;
double eh = exp(.0078125);
double en = 1.;
for(int i = 1; i <= m_nend; ++i){
en = eh * en;
double eni = 1. / en;
double sh = (en - eni) * .5;
double ch = (en + eni) * .5;
double exs = exp(ph * sh);
double exsi = 1. / exs;
double chsi = 2. / (exs + exsi);
m_ap[i - 1] = (exs - exsi) * .5 * chsi;
if (m_ap[i - 1] >= a9) m_ap[i - 1] = a9;
m_ap[i + nendm1] = exsi * chsi;
m_am[i - 1] = -m_ap[i - 1];
m_am[i + nendm1] = -m_ap[i + nendm1];
// Computing 2nd power
m_bb[i - 1] = ph * ch * (chsi * chsi);
}
m_ap[m_nend+nendm1] = m_ap[nendm1*2];
m_am[m_nend+nendm1] = m_am[nendm1*2];
}
MGDefintArea::MGDefintArea() :
m_eps0(1e-32),
m_nend(-1),
m_npow(-1),
m_b0(0.)
{
m_a0[0] = m_a0[1] = 0.;
std::fill_n(m_am, mgdefintlen*2, 0.);
std::fill_n(m_ap, mgdefintlen*2, 0.);
std::fill_n(m_bb, mgdefintlen, 0.);
}
MGDefintArea& MGDefintArea::instance(){
static MGDefintArea theInst;
return theInst;
} |
7cd8df7b31257bc1eb0c72b957055ed92c997b40 | 3801e85d75bf8a10174f4a1f785b66aa41dae511 | /0051. N-Queens/solution.cpp | f7e588f901cd4a3e3e05183f1a2d2bb86098b769 | [] | no_license | evshary/leetcode | 3ed62ccea55adf682cead6bdcc4d06b1aecea8ac | a37455352e34080ebee7132a5d2dc2e979747cee | refs/heads/main | 2022-08-29T16:40:34.002990 | 2022-07-20T22:33:10 | 2022-07-20T22:33:10 | 125,591,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | cpp | solution.cpp | class Solution {
private:
bool isValid(vector<string>& way, int pos_r, int pos_c) {
for (int r = pos_r-1; r >= 0; r--) {
if (way[r][pos_c] == 'Q') return false;
}
for (int r = pos_r-1, c = pos_c-1; r >= 0 && c >= 0; r--, c--) {
if (way[r][c] == 'Q') return false;
}
for (int r = pos_r-1, c = pos_c+1; r >= 0 && c < way.size(); r--, c++) {
if (way[r][c] == 'Q') return false;
}
return true;
}
void traverse(vector<vector<string>>& result, vector<string>& way, int k, int n) {
if (k == n) {
result.push_back(way);
return;
}
for (int c = 0; c < n; c++) {
if (isValid(way, k, c)) {
way[k][c] = 'Q';
traverse(result, way, k+1, n);
way[k][c] = '.';
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
string row = "";
for (int c = 0; c < n; c++) row += ".";
vector<string> way(n, row);
traverse(result, way, 0, n);
return result;
}
}; |
a64eee78e4dc9365c3d002049c1c838a38d86f71 | 2e68b0ed8651350eeebd2fecc69129e445446f41 | /蓝桥杯/官网/算法训练/最短路.cpp | ecd83e238995496bb7c07889e1b3d2f42878ec0f | [] | no_license | Violet-Guo/ACM | 1dd7104172834ad75515d4b0ecba39ec2f90c201 | 7b5781349dc77cb904f522135cb06ad6872f7646 | refs/heads/master | 2021-01-21T04:40:27.151145 | 2016-06-23T01:39:17 | 2016-06-23T01:39:17 | 50,434,940 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | 最短路.cpp | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define MAXN 20005
using namespace std;
int dis[MAXN];
int vis[MAXN];
int head[MAXN];
int n, m, cnt;
struct edge{
int v, w, next;
}edge[200005];
void addedge(int u, int v, int w){
edge[cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void spfa(int s){
int pos, v;
queue<int> q;
q.push(s);
dis[s] = 0;
vis[s] = 1;
while(!q.empty()){
pos = q.front();
q.pop();
vis[pos] = 0;
for(int i = head[pos]; i!=-1; i = edge[i].next){
v = edge[i].v;
if(dis[pos] + edge[i].w < dis[v]){
dis[v] = dis[pos] + edge[i].w;
if(!vis[v]){
vis[v] = 1;
q.push(v);
}
}
}
}
}
int main()
{
while(scanf("%d %d", &n, &m)!=EOF){
cnt = 0;
memset(head, -1, sizeof(head));
memset(dis, 0x7f, sizeof(dis));
memset(vis, 0, sizeof(vis));
while(m--){
int u, v, l;
scanf("%d %d %d", &u, &v, &l);
addedge(u, v, l);
}
spfa(1);
for(int i = 2; i <= n; i++)
printf("%d\n", dis[i]);
}
return 0;
}
|
27b5c37707c382b852701bb085d6cc249327e4b3 | 0e0b8e267a067b914d4a2260b3e9d4f5e4d96ac4 | /CSC11/Homework/Assignment7a/as7a_csc11/main.cpp | 9f358202d5e55c804425e22176135940dea631ea | [] | no_license | himkwan01/RCC | 1d41ff47193e8eae3ad09e2bd9f42a3b6e19fbe1 | 18237364864ca600367f752476c59b6abab8bfeb | refs/heads/master | 2020-06-20T05:46:59.269528 | 2016-12-04T08:46:27 | 2016-12-04T08:46:27 | 74,878,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | cpp | main.cpp | /*
*/
#include <iostream>
using namespace std;
void divMod(int &,int &,int &);
void scaleLeft(int &,int &,int &);
void scaleRight(int &,int &,int &);
void addSub(int &,int &, int &);
int main() {
//declare variable
int r0, r1, r2;
//Display the result
do{
cout<<"Input F:";
cin>>r1;
}while(r1<32 || r1>212);
r1=(r1-32)*5;
r2=9;
//Determine the quotient and remainder
divMod(r0, r1, r2);
//Display the calculated results
r1=r0;
cout<<r1<<"C\n";
//Exit
return 0;
}
void scaleLeft(int &r1,int &r2,int &r3){
do{
r3*=2;
r2*=2;
}while(r1>=r2);
r3>>=1;
r2>>=1;
}
void scaleRight(int &r1, int &r2, int &r3){
do{
r3>>=1;
r2>>=1;
}while(r1<r2);
}
void addSub(int &r0,int &r1,int &r2,int &r3){
do{
r0+=r3;
r1-=r2;
scaleRight(r1, r2, r3);
}while(r3>=1);
}
void divMod(int &r0, int &r1,int &r2){
r0=0;
int r3=1;
if(r1>=r2){
scaleLeft(r1, r2, r3);
addSub(r0, r1, r2, r3);
}
} |
c641eac86120220efe2714b82b797155dbb9eb5f | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5756407898963968_0/C++/benetin/a.cpp | 2ad16e8f32b304b4d350b0a1831213933c36c90d | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 995 | cpp | a.cpp | #include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long i64;
typedef vector<int> VI;
typedef vector<string> VS;
#define REP(i,n) for(int _n=n, i=0;i<_n;i++)
#define FOR(i,a,b) for(int i=(a),_b=(b);i<=_b;i++)
#define ALL(x) (x).begin(),(x).end()
#define SORT(x) sort(ALL(x))
#define PB push_back
int r[10][10];
set<int> s;
int main() {
int Ts;
cin>>Ts;
FOR(cs, 1, Ts) {
int x, y;
REP(i,16) s.insert(i+1);
cin >> x;
REP(i,4) REP(j,4) {
cin>>y;
if (i+1!=x) s.erase(y);
}
cin >> x;
REP(i,4) REP(j,4) {
cin>>y;
if (i+1!=x) s.erase(y);
}
cout << "Case #" << cs << ": ";
if (s.size()==1) {
cout<<(*s.begin());
} else if(s.size()==0) {
cout<<"Volunteer cheated!";
} else {
cout<<"Bad magician!";
}
cout << endl;
}
return 0;
}
|
1d5c975495eb4405d791b7fb2135315046c9ddf9 | 0459ae96bae0b3b2c9858ce5050e60e3b01b000e | /Christian/PROG_II/Uebung_4/complexnumber.h | f217669fd57f1f0ae3b0ab8af1ffd37c0990b16d | [] | no_license | DevCodeOne/WS_1617 | f03f19f1317b93483be4133f768c031bdf2bd364 | 461c7119b0854bbd35f117f0c3f0ccd0b5a3a94c | refs/heads/master | 2021-05-03T12:30:16.521386 | 2017-02-02T09:31:57 | 2017-02-02T09:31:57 | 62,337,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | h | complexnumber.h | #pragma once
#include <string>
class complexnumber {
public:
complexnumber(double real = 0, double imaginary = 0);
double real() const;
double imag() const;
std::string name() const;
bool is_real() const;
bool is_imag() const;
void real(double real);
void imag(double imag);
void name(std::string name);
void add (complexnumber c);
std::string to_string();
static complexnumber add(complexnumber c1, complexnumber c2);
private:
double m_real = 0;
double m_imag = 0;
std::string m_name = "";
};
|
059f5b757939f229ca19defaf09e178f7ce4a9ac | 762f52d0e4b51509187e91e90b67b22b9a3fd1b4 | /25. Heaps/1_basics.cpp | c5fa70fbdafa2345554bf0bef53b8f7119d8910e | [] | no_license | apoorvKautilya21/Data-Structures-And-Algorithm-in-C- | f77319e5d56897586f89c377a53f5369a588f85d | c90a8953fc21f0d7a67cb28ec53a8ccf0157c58f | refs/heads/main | 2023-03-03T14:20:37.141531 | 2021-02-06T05:08:54 | 2021-02-06T05:08:54 | 336,460,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | cpp | 1_basics.cpp | #include<iostream>
#include<vector>
using namespace std;
class Heaps {
vector<int> v;
bool minHeap;
bool compare(int a, int b) {
if(minHeap) {
return a > b;
}
else {
return a < b;
}
}
void heapify_rec(int idx) {
int left = 2 * idx;
int right = 2 * idx + 1;
int last = v.size() - 1;
int min_idx = idx;
if(left <= last and compare(v[idx] ,v[left])) {
min_idx = left;
}
if(right <= last and compare(v[min_idx], v[right])) {
min_idx = right;
}
if(min_idx != idx) {
swap(v[min_idx], v[idx]);
heapify_rec(min_idx);
}
}
public:
Heaps(int default_size = 10, bool type = true) {
v.reserve(default_size);
minHeap = type;
v.push_back(-1);
}
void push(int element) {
v.push_back(element);
int idx = v.size() - 1; // index at which element is present
int parent = idx / 2;
while(idx > 1 and compare(v[parent], v[idx])) {
swap(v[parent], v[idx]);
idx = parent;
parent = parent / 2;
}
}
int top() {
return v[1];
}
void pop() {
swap(v[1], v[v.size() - 1]);
v.pop_back();
heapify_rec(1);
}
bool isEmpty() {
return v.size() == 1;
}
};
int main() {
Heaps h;
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int no;
cin >> no;
h.push(no);
}
while(!h.isEmpty()) {
cout << h.top() << " ";
h.pop();
}
return 0;
} |
ba139a4a91ee222b62edfd21236866c066ced1f9 | 768d2722884910bc05e9baaece13dbb21fd9cb16 | /Algorithms/Maths and DP/Other Interesting Problems/D_Array.cpp | 3bc437dea2b055e8cc8182c4179743bbf57e864e | [] | no_license | sapjv/Competitive_Programming | 83e7ddc13d67240d1f2db5b4300f2d5fc2629ab1 | 157cfdf246991a625c64fdc14f614a30dbb19950 | refs/heads/master | 2022-03-07T17:13:22.975772 | 2019-11-27T19:53:41 | 2019-11-27T19:53:41 | 271,464,234 | 1 | 0 | null | 2020-06-11T05:59:21 | 2020-06-11T05:59:21 | null | UTF-8 | C++ | false | false | 2,004 | cpp | D_Array.cpp | #include "bits/stdc++.h"
using namespace std;
const int N = 1005;
const int MOD = 1000000007;
int n, q;
int arr[N], d[N];
int dp[N][N], dp_sum[N][N];
int main(){
cin >> n;
arr[0] = 0;
for(int i = 1; i <= n; i++){
cin >> arr[i];
}
cin >> q;
/*
Subtask 2 :-
dp[i][j] : Number of ways to fill [i + 1...n] such that after the (i)'th index is
processed, we have (j) elements remaining in the stack. (including arr[i])
*/
for(int i = 2; i <= n + 1; i++){
dp[n][i] = 1;
dp_sum[n][i] = dp_sum[n][i - 1] + dp[n][i];
}
for(int i = n - 1; i >= 1; i--){
for(int j = 2; j <= i + 1; j++){
dp[i][j] = dp_sum[i + 1][j + 1];
dp_sum[i][j] = dp_sum[i][j - 1] + dp[i][j];
if(dp_sum[i][j] >= MOD) dp_sum[i][j] -= MOD;
}
}
int rank = 0, total = dp_sum[1][2];
stack < int > st;
for(int i = 1; i <= n; i++){
// (i) is the first index of difference
st.push(arr[i - 1]);
int stack_size = st.size();
while(st.top() > arr[i]){
st.pop();
++d[i];
}
int cur = dp_sum[i][max(0, stack_size - d[i])];
rank = (rank + cur) % MOD;
}
for(int i = 1; i <= n; i++){
cout << d[i];
if(i < n) cout << " ";
else cout << "\n";
}
if(q >= 1){
cout << ((total - rank + MOD) % MOD) << "\n";
}
/*
Subtask 3 :-
dp[i][j] = number of ways to have arrays of length (i) such that after processing
(i), the stack has j elements (inc i), and that the stack has >= 3 elements at every
index from (2...i)
*/
memset(dp, 0, sizeof dp);
memset(dp_sum, 0, sizeof dp_sum);
dp[1][2] = dp_sum[1][2] = 1;
for(int i = 2; i <= n; i++){
for(int j = 3; j <= i + 1; j++){
dp[i][j] = (dp_sum[i - 1][i] - dp_sum[i - 1][j - 2] + MOD) % MOD;
dp_sum[i][j] = dp_sum[i][j - 1] + dp[i][j];
if(dp_sum[i][j] >= MOD) dp_sum[i][j] -= MOD;
}
}
total = 0;
for(int i = 2; i <= n; i++){
int x = (i - 1);
int y = (n - i + 1);
int cur = (dp_sum[x][x + 1] * 1LL * dp_sum[y][y + 1]) % MOD;
total = (total + cur) % MOD;
}
if(q >= 2){
cout << total << "\n";
}
} |
50fbbb835bad9bb0db618ea870e37f545711d468 | bb2ff1f055d64fd8c0a1400b08858a5d06eb1a04 | /indiancoinchange.cpp | 0aa6ac2579b63bb542b6e6964198784b3090edfc | [] | no_license | Anushka-ece/Codecorner | 23a70ecee62f524c3ab89771ed5e40aa8a9277a1 | e91794625061ebdeaeb2483b45030e0fa752c661 | refs/heads/main | 2023-08-03T02:55:41.202442 | 2021-10-06T16:44:08 | 2021-10-06T16:44:08 | 362,576,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | cpp | indiancoinchange.cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
signed main()
{
int n;
cin>>n;//no. of denominations
vector<int>a(n);
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int x;
cin>>x;
sort(a.begin(),a.end(),greater<int>());//we have added third argument here,as we have to maintain decreasing order
return 0;
int ans=0;
for(int i=0;i<n;i++)
{
ans+=x/a[i];
x-=x/a[i] *a[i];
}
cout<<ans<<endl;
return 0;
} |
ea7a67dc1051d3d446bb2b69f6ce9e47288992fb | 3a69569e820b2c733092ff5eee7c1ba55d53586c | /trafficSim/Road.h | c696762e23a68e031cfd562ad790947777fd5023 | [] | no_license | BenjHoang/Traffic_Sim | 8bea053c308a0704da836c38c01f487731f26f47 | 773ce2163c6e78b5b09cfba79697d94adbc78acb | refs/heads/master | 2021-01-19T21:47:18.160481 | 2017-04-19T05:46:59 | 2017-04-19T05:46:59 | 88,704,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,234 | h | Road.h | /*******************************************************************
* CS 307 Programming Assignment 2
* Author: Benjmin hoang
* Desc: traffic simulation
* Date: 4/15/2017
* I attest that this program is entirely my own work
*******************************************************************/
#include<string>
using namespace std;
#pragma once
class Road
{
private:
string name;
double m_dXStart, m_dYStart, m_dXEnd, m_dYEnd;
int m_iIntersStart, m_iIntersEnd;
bool m_bIsNSroad;
bool m_bIsEWroad;
double m_dSpdlimit;
int m_iNumLanes;
public:
Road(void);
~Road(void);
//all set functions
void setName(char *name);
void setxStart(double *xStart);
void setyStart(double *yStart);
void setxEnd(double *xEnd);
void setyEnd(double *yEnd);
void setintersStart(int *intersStart);
void setintersEnd(int *intersEnd);
void setspdlimit(double *spdlimit);
void setnumLanes(int *numLanes);
void setNS_EWroad();
//all get functions
string getName();
double getxStart();
double getyStart();
double getxEnd();
double getyEnd();
int getintersStart();
int getintersEnd();
double getspdlimit();
int getnumLanes();
bool isPointOnRoad(double x, double y, double dir);
};
|
9c8fd58c6eac94821e6a73fec7240b27518bbe9d | 09866ba376f9aa53ab6d129e2ff4f89076664c6d | /Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/RTSGameplayTagsComponent.cpp | dcbcba90a1697cdfb8e07240db6e896e63da171f | [
"MIT"
] | permissive | JaredP94/ue4-rts | c05dee7f6b94fbed6343b0b04df8d921421f9cee | 242aa314ea8a4ac4145af214399d2ecb6c25234c | refs/heads/develop | 2021-05-17T22:53:11.999359 | 2020-12-20T19:48:54 | 2020-12-20T19:48:54 | 250,988,884 | 1 | 1 | MIT | 2020-12-20T19:48:55 | 2020-03-29T08:45:49 | C++ | UTF-8 | C++ | false | false | 3,184 | cpp | RTSGameplayTagsComponent.cpp | #include "RTSGameplayTagsComponent.h"
#include "GameFramework/Actor.h"
#include "Net/UnrealNetwork.h"
#include "RTSGameplayTagsProvider.h"
#include "RTSLog.h"
URTSGameplayTagsComponent::URTSGameplayTagsComponent(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/)
: Super(ObjectInitializer)
{
SetIsReplicatedByDefault(true);
}
void URTSGameplayTagsComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(URTSGameplayTagsComponent, CurrentTags);
}
void URTSGameplayTagsComponent::BeginPlay()
{
Super::BeginPlay();
AActor* Owner = GetOwner();
if (!IsValid(Owner))
{
return;
}
IRTSGameplayTagsProvider* GameplayTagsProvider = Cast<IRTSGameplayTagsProvider>(Owner);
if (GameplayTagsProvider)
{
GameplayTagsProvider->AddGameplayTags(InitialTags);
}
for (UActorComponent* Component : Owner->GetComponents())
{
GameplayTagsProvider = Cast<IRTSGameplayTagsProvider>(Component);
if (GameplayTagsProvider)
{
GameplayTagsProvider->AddGameplayTags(InitialTags);
}
}
for (const FGameplayTag& Tag : InitialTags)
{
CurrentTags.AddTagFast(Tag);
UE_LOG(LogRTS, Log, TEXT("Added initial gameplay tag %s for %s."), *Tag.ToString(), *GetOwner()->GetName());
}
}
void URTSGameplayTagsComponent::GetOwnedGameplayTags(FGameplayTagContainer& TagContainer) const
{
TagContainer.AppendTags(CurrentTags);
}
FGameplayTagContainer URTSGameplayTagsComponent::GetCurrentTags() const
{
FGameplayTagContainer GameplayTagContainer;
GetOwnedGameplayTags(GameplayTagContainer);
return GameplayTagContainer;
}
void URTSGameplayTagsComponent::AddGameplayTag(const FGameplayTag& NewTag)
{
CurrentTags.AddTag(NewTag);
UE_LOG(LogRTS, Log, TEXT("Added gameplay tag %s for %s."), *NewTag.ToString(), *GetOwner()->GetName());
NotifyOnCurrentTagsChanged();
}
void URTSGameplayTagsComponent::AddGameplayTags(const FGameplayTagContainer& NewTags)
{
CurrentTags.AppendTags(NewTags);
UE_LOG(LogRTS, Log, TEXT("Added gameplay tags %s for %s."), *NewTags.ToString(), *GetOwner()->GetName());
NotifyOnCurrentTagsChanged();
}
bool URTSGameplayTagsComponent::RemoveGameplayTag(const FGameplayTag& TagToRemove)
{
bool bRemoved = CurrentTags.RemoveTag(TagToRemove);
if (bRemoved)
{
UE_LOG(LogRTS, Log, TEXT("Removed gameplay tag %s from %s."), *TagToRemove.ToString(), *GetOwner()->GetName());
NotifyOnCurrentTagsChanged();
}
return bRemoved;
}
void URTSGameplayTagsComponent::RemoveGameplayTags(const FGameplayTagContainer& TagsToRemove)
{
CurrentTags.RemoveTags(TagsToRemove);
UE_LOG(LogRTS, Log, TEXT("Removed gameplay tags %s from %s."), *TagsToRemove.ToString(), *GetOwner()->GetName());
NotifyOnCurrentTagsChanged();
}
void URTSGameplayTagsComponent::NotifyOnCurrentTagsChanged()
{
CurrentTagsChanged.Broadcast(GetOwner(), CurrentTags);
}
void URTSGameplayTagsComponent::ReceivedCurrentTags()
{
NotifyOnCurrentTagsChanged();
}
|
ed965bc857781b5605ddd096bdd75820eb8724f5 | ccbc771c062e9d55025bb8ce496ab751549be28e | /1427__소트인사이드.cpp | ce435ff051aee04858728c5120bd7cf19dabfc5e | [] | no_license | eltory/Baekjoon | 2ee69baf808c9a80f24592a1180a827412bc904a | dc008215334d5c0c7ba7d167903a499d17e57091 | refs/heads/master | 2021-01-22T05:06:44.541478 | 2018-02-10T11:50:39 | 2018-02-10T11:50:39 | 102,277,935 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | cpp | 1427__소트인사이드.cpp | //
// 소트인사이드__1427.cpp
// Algorithm_study_group
//
// Created by LSH on 2017. 9. 6..
// Copyright © 2017년 LSH. All rights reserved.
//
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
int N[10] = {0}, i = 0;
long long num;
scanf("%lld",&num);
while(num){
N[i] = num % 10;
num /= 10;
i++;
}
sort(N, N+i);
for(int j = i-1; j >= 0 ; --j)
printf("%d",N[j]);
return 0;
}
|
f43ce32a679985a276c7eef93c75e04b1f7fff46 | c18e3cba4f445613b2ed7503061cdfe088d46da5 | /docs/mfc/codesnippet/CPP/mfc-activex-controls-subclassing-a-windows-control_5.h | 206250bde31a48cd3b6aff1e5a242972d3b19ff5 | [
"CC-BY-4.0",
"MIT"
] | permissive | MicrosoftDocs/cpp-docs | dad03e548e13ca6a6e978df3ba84c4858c77d4bd | 87bacc85d5a1e9118a69122d84c43d70f6893f72 | refs/heads/main | 2023-09-01T00:19:22.423787 | 2023-08-28T17:27:40 | 2023-08-28T17:27:40 | 73,740,405 | 1,354 | 1,213 | CC-BY-4.0 | 2023-09-08T21:27:46 | 2016-11-14T19:38:32 | PowerShell | UTF-8 | C++ | false | false | 41 | h | mfc-activex-controls-subclassing-a-windows-control_5.h | class CMyAxSubCtrl : public COleControl
{ |
79efb81c68998d3a0e0cfbb195b3e3ca6fdba8be | 6ab38b394a37de35b5f22d94dbffd7c58464373d | /Code Force/519C.cpp | afcae169ad956b7d229f63423a6909cf55007126 | [] | no_license | abdullahalrifat/Programming-Problem-Solutions | 357e8277c094508d7cb4d4a8c0b95912309fd44a | d1ae9bab15f2a9f4d7cd7439969ffef0500e55d2 | refs/heads/master | 2021-05-07T05:12:48.116359 | 2020-02-20T20:53:13 | 2020-02-20T20:53:13 | 111,451,649 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222 | cpp | 519C.cpp |
// Created by abdullah on 2/9/17.
//
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
int ans=(a+b)/3;
ans=min(ans,a);
ans=min(ans,b);
cout<<ans<<endl;
}
|
f5543058625fda9a7e79ba94e7a1351a40906ac5 | 1542a50f6ff9a8606f4229b62c21dd277aa74207 | /SmartVII_Faster/DataShow.h | baa57d007ab269384588073c522d64e43274067b | [] | no_license | heryms/SmartV_Lu | f5e09233915d3217a8b4a449f0d77797543eca45 | d41de5ee26e3b6f0ceffbeeb4ccbe09bac3a5b6d | refs/heads/master | 2021-01-22T21:16:56.353552 | 2017-03-18T15:16:03 | 2017-03-18T15:16:03 | 85,407,986 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,177 | h | DataShow.h | #pragma once
// OpenGL 头文件
#include <vector>
#include <map>
using namespace std;
enum ButtonType
{
leftDown=0,
rightDown=1,
other=2
};
typedef void(*point_layer)(const vector<PointShow> ptcloud);
typedef void(*line_layer) (const vector<ckPloyLineS>linecloud);
typedef void (*mission_layer)(const vector<ckMissionPoint>missionCloud);
class CDataShow
{
public:
CDataShow(void);
~CDataShow(void);
public:
BOOL m_bIsCreate;
BOOL m_bSnapScreen;
BOOL m_bDrawPoints;
float camRot[3];
float camPos[3];
float sceneRot[3];
float scenePos[3];
float vieeDis[2];
float eyePos[3];
float eyeCenter[3];
float eyeUp[3];
double m_lfRange;
BOOL mouserightdown;
BOOL mouseleftdown;
CPoint mouseprevpoint;
int m_GLPixelIndex;
float x_move,y_move; //记录模型平移
float x_rotate,y_rotate,z_rotate; //记录模型旋转
float m_zoom; //缩放比例
float x_rotate_save,y_rotate_save,z_rotate_save;
float x_move_save,y_move_save;
int x_lbefore,y_lbefore; //记录鼠标按下时的坐标位置
int x_rbefore,y_rbefore;
int z_before1,z_before2;
int winX,winY;
int m_NumPixel;
int snapid;
public:
// 绘图设置
HGLRC m_hGLContext;
void InitialScene( CPaintDC& dc,HDC hDC);
BOOL SetWindowPixelFormat(HDC hDC);
BOOL CreateViewGLContext(HDC hDC);
int OnCreate(HWND hWnd);
void SetOneViewFocus(int index); // 重置视角
void OnLButtonDown(UINT nFlags, CPoint point);
BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
void OnLButtonUp(UINT nFlags, CPoint point);
void OnRButtonDown(UINT nFlags, CPoint point);
void OnRButtonUp(UINT nFlags, CPoint point);
void OnMouseMove(UINT nFlags, CPoint point);
int m_nButtonFlag;
// 画画
void Draw_grid (int meters_per_grid);
void Draw_compass(double x,double y,double z);
void Draw_Road_Center_Point();
void Draw_coordinate();
void Draw_current_vehicle(float x, float y , float tht);
void OnSize(UINT nType, int cx, int cy);
//画图回调函数
private:
//DrawPoint m_fpointFunc;
map<string,point_layer> m_layersSensor;
map<string,vector<PointShow>> m_sensorBuffer;
map<string,line_layer> m_layersMapLine;
map<string,vector<ckPloyLineS>> m_maplineBuffer;
map<string ,mission_layer> m_layersMission;
map<string,vector<ckMissionPoint>> m_missionBuffer;
//图层控制
private:
map<string,bool> m_layerStatus;
public:
inline void SetLayerStatus(string layer,bool status)
{
map<string,bool>::iterator it=m_layerStatus.find(layer);
it->second=status;
}
public:
void CreatePointLayer(string name,point_layer layer);
BOOL UpdatePointLayer(string name,const vector<PointShow> ptcloud);
void CreateLineLayer(string name,line_layer layer);
BOOL UpdateLineLayer(string name,const vector<ckPloyLineS> linecloud);
void CreateMissionLayer(string name,mission_layer layer);
BOOL UpdateMissionLayer(string name,const vector<ckMissionPoint> missionCloud);
public:
//int SetPointCallback(DrawPoint dpFunc){ m_fpointFunc=dpFunc;};
void SetSceneRot(int axis,int value,BOOL increment,BOOL apply);
void SetCamPos(int axis,int value,BOOL increment,BOOL apply);
void SetView(float f);
void Draw_circle(int radious, int meters_per_difference);
};
|
f48284a39d96074766d4189dbfc03d9efcbc836c | 335877f60fcf325ee654298ca546b1d069447656 | /include/Engine/Scene/Scene.h | 75f090dafe30b455a3d26c7bed28296271b09ea6 | [
"MIT"
] | permissive | FedebulLab/GameProject-1 | 9a2b48f94f66026c6b6f4791175fc6984b69eddb | 9be640add19598bc87524003ffebf5df07bfc75f | refs/heads/master | 2023-06-26T17:37:33.685168 | 2021-07-05T15:57:45 | 2021-07-05T15:57:45 | 377,394,844 | 0 | 0 | MIT | 2021-06-16T06:31:38 | 2021-06-16T06:31:37 | null | UTF-8 | C++ | false | false | 923 | h | Scene.h | //
// Created by MarcasRealAccount on 7. Nov. 2020.
//
#pragma once
#include "Engine/Scene/Entity.h"
#include "Engine/Scene/RenderableEntity.h"
#include <memory>
#include <vector>
namespace gp1::scene
{
class Scene
{
public:
void AttachEntity(Entity* entity);
void DetachEntity(Entity* entity);
void Update(float deltaTime);
const std::vector<Entity*>& GetEntities()
{
return m_Entities;
}
const std::vector<Entity*>& GetUpdatableEntities()
{
return m_UpdatableEntities;
}
const std::vector<RenderableEntity*>& GetRenderableEntities()
{
return m_RenderableEntities;
}
private:
std::vector<Entity*> m_Entities; // The entities this scene holds.
std::vector<Entity*> m_UpdatableEntities; // The entities that can update.
std::vector<RenderableEntity*> m_RenderableEntities; // The entities that can be rendered.
};
} // namespace gp1::scene
|
39e96ec24ca688fb3a08a373dac6b6e1e244ede4 | 156c0861ce5650248099d917bc22dfe1b012c7cb | /第6章/第六章/6.7.cpp | 4a272cc4203e1a3ed4d964acc04e18dd7e6dfcea | [] | no_license | bietaixian/cppPrimer5th | ba1309bdf2c0e2be80b8da26e1ee442ead611606 | 82a4866512f770f8e8d7010172db414cdf3911e0 | refs/heads/master | 2020-04-02T05:49:24.490678 | 2016-06-22T02:39:20 | 2016-06-22T02:39:20 | 61,682,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 79 | cpp | 6.7.cpp | //size_t count_calls()
//{
// static size_t ctr = 0;
// return ctr++;
//} |
a6f0fa3371199852c67f6eba3b95321479782ffb | eb677b79236dd08776d1d171e3afd9f3c62743c3 | /docs/libraries/concurrency/serial_queue.hpp/serial_queue_t/serial_queue_example.cpp | a729e6a2f9c88235a19db2b0ebcd4649e02bedb6 | [
"BSL-1.0"
] | permissive | stlab/libraries | fb7d1ea14b3b23b8a876f924f4a3d12d7d9b2e88 | 31a82820be123981e1e45468fd9939ed7458568b | refs/heads/main | 2023-08-04T08:48:03.418495 | 2023-05-06T04:37:24 | 2023-05-06T04:37:24 | 35,681,376 | 669 | 86 | BSL-1.0 | 2023-09-02T00:52:47 | 2015-05-15T15:25:09 | C++ | UTF-8 | C++ | false | false | 677 | cpp | serial_queue_example.cpp | #include <iostream>
#include <thread>
#include <string>
#include <stlab/concurrency/default_executor.hpp>
#include <stlab/concurrency/serial_queue.hpp>
using namespace std;
using namespace stlab;
serial_queue_t ioq(default_executor);
void say_hello(string to_whom) {
ioq.executor()([_whom = move(to_whom)](){
cout << "Hello, " << _whom << "!\n";
});
}
int main(int, char**) {
say_hello("fella");
say_hello("chief");
say_hello("pal");
say_hello("world");
auto done = ioq([]{});
while (!done.get_try()) { }
pre_exit();
}
/*
Result:
Hello, fella!
Hello, chief!
Hello, pal!
Hello, world!
*/
|
626cf91e39fe644eece97442f88e295bbc72a9c9 | ad7bdccdd132c6174c3a9b7acaecb5fe1f66d073 | /combination.cpp | e2234873889419b5b06e703cc99cf82fb8599fcc | [] | no_license | queran521/Cpp | c18d6c78ec1e475dd39b282647ababb98cc17ed1 | 8ae8dd3e1e4a92d68d1f5eeeb8d12074344dd098 | refs/heads/master | 2020-03-30T19:02:04.723944 | 2013-10-22T14:49:28 | 2013-10-22T14:49:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp | combination.cpp | #include<iostream>
using namespace std;
int f(int x);//函数声明部分
int main(){
int m,n,ans;
cout<<"please input two integer numbers:"<<endl;
cin>>m>>n;//输入两个整数
if(m<=0||n<0||n>m)
cout<<"input error"<<endl;//判断输入是否合法
else
{
ans=f(m)/(f(m-n)*f(n));
cout<<"the answer is "<<ans<<endl;//利用组合公式调用递归函数求结果
}
return 0;
}
int f(int x){
if(x==0||x==1){
return 1;}
else{
return(x*f(x-1));
}
}//递归函数求阶乘
|
4f6164d8ced7f7d73d32c281ccc81dc95ea52eb1 | 228e4e5777697bf0a87ed9ffdb1805c9bdad47f1 | /gtest/1/functionsTest.cpp | 4aa14950ddc1293064cf16bc8eebc69d694405de | [] | no_license | 2084567437/work | 283d3d321350e1c44014dc6de7a09851ddfc7f09 | b341f5cd37c1f098ca7e9c2c7d64df30e8eb9bc8 | refs/heads/master | 2020-12-25T14:14:00.712728 | 2016-08-16T03:16:34 | 2016-08-16T03:16:34 | 64,831,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | functionsTest.cpp | //functionsTest.cpp
#include "gtest/gtest.h"
#include "functions.h"
TEST(AddTest,AddTestCase){
ASSERT_EQ(2,add(1,1));
}
TEST(MinusTest,MinusTestCase){
ASSERT_EQ(10,myMinus(25,15));
}
TEST(MultiplyTest,MutilplyTestCase){
ASSERT_EQ(13,multiply(3,4));
}
TEST(DivideTest,DivideTestCase){
ASSERT_EQ(2,divide(7,3));
}
|
84ed1d80072eaa947d43c6933484a44ddb491bd9 | af9092f5e6a213b039a83f39438809314bd6e5c0 | /tipocomb.h | b4cf0fdadab7679b1bea88c484af5f4339789d2e | [] | no_license | Samu01Tech/ProgrammazioneAvanzata-4.1 | 365e453aa689bc935ff2ed454c403164c87135d7 | bcbd2fd406be241fde10d89ff922991cbbf859fd | refs/heads/master | 2023-08-04T07:28:12.513584 | 2021-10-06T15:23:25 | 2021-10-06T15:23:25 | 414,228,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | h | tipocomb.h | #ifndef __COMB_H__
#define __COMB_H__
using namespace std;
typedef enum {DIESEL, BENZINA, GPL} Tcombustibile;
class Tipocomb{
private:
Tcombustibile comb;
public:
Tipocomb(Tcombustibile _comb);
~Tipocomb();
friend ostream& operator<<(ostream& os, const Tipocomb& tc);
};
ostream& operator<<(ostream& os, const Tipocomb& tc);
#endif |
dc0509d661b11c73fb41d5d8da966750c974af26 | 0a1aff4d2f3a0021a0f04926adc1c64171f8cfb4 | /src/cls/interpolator/linear.hpp | f4dac08d0ef1371d0868c459929507a9fcbcbda2 | [] | no_license | FreddyWordingham/ArctorusOld | 1f1a7e226f0d8cdf129f35759a971aa952e0026b | 42254c041af37d9bc8fe2a787f3c752810c5649f | refs/heads/master | 2021-09-16T01:52:34.379570 | 2018-03-19T18:50:04 | 2018-03-19T18:50:04 | 116,527,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,218 | hpp | linear.hpp | /**
* @author Freddy Wordingham
* @email fjmw201@exeter.ac.uk
*
* @date 25/01/2018.
*/
// == GUARD ==
#ifndef ARCTORUS_SRC_CLS_INTERPOLATOR_LINEAR_HPP
#define ARCTORUS_SRC_CLS_INTERPOLATOR_LINEAR_HPP
// == INCLUDES ==
// -- System --
#include <ostream>
#include <vector>
// == NAMESPACE ==
namespace arc
{
namespace interpolator
{
// == CLASS ==
/**
* A linear interpolator class.
* Uses a given set of nodes to calculate intermediate values.
*/
class Linear
{
// == FIELDS ==
private:
// -- Bounds --
const double m_min_bound; //! Minimum bound of the interpolation range.
const double m_max_bound; //! Maximum bound of the interpolation range.
// -- Data --
const std::vector<double> m_x; //! Vector of X positions of the nodes.
const std::vector<double> m_y; //! Vector of Y positions of the nodes.
const std::vector<double> m_grad; //! Vector of intermediate gradients.
// -- Optimisations --
mutable size_t m_last_index = 0; //! Last index accessed during the interpolation.
// == INSTANTIATION ==
public:
// -- Constructors --
Linear(const std::vector<double>& t_x, const std::vector<double>& t_y);
private:
// -- Initialisation --
std::vector<double> init_grad() const;
// == OPERATORS ==
public:
// -- Interpolation --
double operator()(double t_val) const;
// -- Printing --
friend std::ostream& operator<<(std::ostream& t_stream, const Linear& t_lin);
// == METHODS ==
public:
// -- Serialisation --
std::string serialise(size_t t_samples = static_cast<size_t>(1E3)) const;
// -- Saving --
void save(const std::string& t_path, size_t t_samples = static_cast<size_t>(1E3)) const;
};
} // namespace interpolator
} // namespace arc
// == GUARD END ==
#endif // ARCTORUS_SRC_CLS_INTERPOLATOR_LINEAR_HPP
|
8180b482922cb8073495827189bbe4d7cacff727 | 5e59e1976262a7dcf5c54c5699d866562b91e173 | /Tp1_omar_alex/test/test_fill_randomly.cpp | 9bf5580b9bec184091649932fec0a106839f9541 | [] | no_license | omarala/tp_prog_cpp | b137ad78cdcb6711a21da8dfac1de3729c135a19 | 6529fce43cfed9b0d6280aa9262b56f6b1b7dffe | refs/heads/master | 2021-04-30T15:11:37.184105 | 2018-05-13T16:47:23 | 2018-05-13T16:47:23 | 121,233,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | cpp | test_fill_randomly.cpp | #include<iostream>
#include<assert.h>
#include "gtest/gtest.h"
#include<sstream>
#include"../src/Dvector.h"
TEST(Dvector, fillRandomly){
Dvector v(3, 2.5);
v.fillRandomly();
stringstream str;
v.display(str);
Dvector v2(3, 2.5);
v2.fillRandomly();
stringstream str2;
v2.display(str2);
EXPECT_NE( str.str(), str2.str()) << "Error: fillRandomly two same vectors";
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} |
532e34a4c155caf3fdb77c4cb3ade22451dce3f3 | 8237d08ea9dd0d1f9202aced9a85dea5082f708c | /day16/phase.h | e376da520b6393a6aff33c09ce86552074da23b7 | [] | no_license | rnetuka/adventofcode2019 | 58f98fafdc53cf74b4cf6fe5f0612584b7f30a6f | aae468c2edbe4a9e3231534f3d5053ed380b560d | refs/heads/master | 2020-09-21T03:13:33.815747 | 2020-01-20T09:32:41 | 2020-01-20T09:32:41 | 224,661,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | phase.h | //
// Created by rnetuka on 17.12.19.
//
#pragma once
#include "../math/matrix.h"
class phase_generator
{
private:
const int n;
int i = 0;
int count = 0;
public:
explicit phase_generator(int n);
int next();
};
matrix<int> phase_matrix(int size); |
ea53c5fa5d77bcf9bcba57674325cf0e108da317 | 7cfcc43d1eb330f56a75b9ecc76f1aa975f9a225 | /algorithmStudy/1507_curiousMinho.cpp | fa69daa7c6428ee390fe150e51498be6cfbcb859 | [] | no_license | enan501/Algorithm-study | e25f35ff6fedb7e46b154326e4145ce0948f4f5d | f8b6380b530ee08404e01b050543c81f2958169e | refs/heads/master | 2021-07-25T02:08:11.805891 | 2021-07-02T05:35:27 | 2021-07-02T05:35:27 | 162,815,602 | 0 | 3 | null | null | null | null | UHC | C++ | false | false | 1,208 | cpp | 1507_curiousMinho.cpp | #include<stdio.h>
#include<string.h>
using namespace std;
int main(void)
{
int n = 0, sum = 0;
int** arr = NULL;
bool** deleted = NULL;
scanf_s("%d", &n);
arr = new int*[n];
deleted = new bool*[n];
for (int i = 0; i < n; i++)
{
arr[i] = new int[n];
memset(arr[i], 0, sizeof(int)*n);
deleted[i] = new bool[n];
memset(deleted[i], false, sizeof(bool)*n);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf_s("%d", &arr[i][j]);
}
}
for (int k = 0; k < n; k++)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (k == i || k == j || i == j)
continue;
if (arr[i][j] > arr[i][k] + arr[k][j]) //주어진 값이 최소 이동시간이 아닌 경우 -1출력
{
printf("-1");
return 0;
}
if (arr[i][j] == arr[i][k] + arr[k][j]) //i->j는 k를 경유해서 가는 시간이므로 빼도 됨
{
deleted[i][j] = true;
}
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
if (arr[i][j] > 0 && deleted[i][j] == false) //delete배열에 포함되지 않고 값이 남아 있으면 꼭 필요한 간선
{
sum += arr[i][j];
}
}
}
printf("%d", sum);
return 0;
} |
58020c2632563a61dc9efdced025c471bb07427b | 879681c994f1ca9c8d2c905a4e5064997ad25a27 | /root-2.3.0/run/MicroChannelFOAM/TurbulenceMicroChannel/0.05/epsilon | 2a750d1c68a46026c55336b196fb46172256ed2b | [] | no_license | MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu | 3828272d989d45fb020e83f8426b849e75560c62 | daeb870be81275e8a81f5cbac4ca1906a9bc69c0 | refs/heads/master | 2020-05-17T16:36:41.848261 | 2015-04-18T09:29:48 | 2015-04-18T09:29:48 | 34,159,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,105 | epsilon | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.05";
object epsilon;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -3 0 0 0 0];
internalField nonuniform List<scalar>
545
(
2.93672e+07
2.79663e+07
2.57309e+07
2.38021e+07
2.24815e+07
2.99349e+07
2.80307e+07
2.56625e+07
2.36843e+07
2.22611e+07
3.09111e+07
2.80831e+07
2.54986e+07
2.34402e+07
2.18668e+07
3.23873e+07
2.80408e+07
2.52356e+07
2.30908e+07
2.12641e+07
3.45755e+07
2.78007e+07
2.4933e+07
2.27165e+07
2.04149e+07
2.18058e+07
2.14361e+07
2.13176e+07
2.12794e+07
2.12665e+07
2.12615e+07
2.1259e+07
2.12572e+07
2.12558e+07
2.12545e+07
2.12532e+07
2.1252e+07
2.12509e+07
2.12497e+07
2.12486e+07
2.12476e+07
2.12466e+07
2.12456e+07
2.12446e+07
2.12437e+07
2.12429e+07
2.1242e+07
2.12412e+07
2.12405e+07
2.12398e+07
2.12391e+07
2.12384e+07
2.12378e+07
2.12372e+07
2.12367e+07
2.12362e+07
2.12357e+07
2.12352e+07
2.12348e+07
2.12345e+07
2.12341e+07
2.12338e+07
2.12336e+07
2.12333e+07
2.12331e+07
2.1233e+07
2.12328e+07
2.12327e+07
2.12327e+07
2.12326e+07
2.16371e+07
2.13844e+07
2.13012e+07
2.12742e+07
2.12648e+07
2.12609e+07
2.12587e+07
2.12571e+07
2.12557e+07
2.12544e+07
2.12532e+07
2.1252e+07
2.12508e+07
2.12497e+07
2.12486e+07
2.12475e+07
2.12465e+07
2.12455e+07
2.12446e+07
2.12437e+07
2.12428e+07
2.1242e+07
2.12412e+07
2.12404e+07
2.12397e+07
2.1239e+07
2.12384e+07
2.12377e+07
2.12372e+07
2.12366e+07
2.12361e+07
2.12356e+07
2.12352e+07
2.12348e+07
2.12344e+07
2.12341e+07
2.12338e+07
2.12335e+07
2.12333e+07
2.12331e+07
2.12329e+07
2.12328e+07
2.12327e+07
2.12326e+07
2.12326e+07
2.13916e+07
2.12979e+07
2.12735e+07
2.12655e+07
2.1262e+07
2.126e+07
2.12584e+07
2.1257e+07
2.12557e+07
2.12544e+07
2.12531e+07
2.12519e+07
2.12508e+07
2.12496e+07
2.12485e+07
2.12475e+07
2.12465e+07
2.12455e+07
2.12445e+07
2.12436e+07
2.12428e+07
2.12419e+07
2.12411e+07
2.12404e+07
2.12397e+07
2.1239e+07
2.12383e+07
2.12377e+07
2.12371e+07
2.12366e+07
2.12361e+07
2.12356e+07
2.12351e+07
2.12347e+07
2.12344e+07
2.1234e+07
2.12337e+07
2.12335e+07
2.12332e+07
2.1233e+07
2.12329e+07
2.12327e+07
2.12326e+07
2.12326e+07
2.12325e+07
2.10722e+07
2.11969e+07
2.12423e+07
2.12558e+07
2.1259e+07
2.12591e+07
2.12581e+07
2.12569e+07
2.12556e+07
2.12543e+07
2.12531e+07
2.12519e+07
2.12507e+07
2.12496e+07
2.12485e+07
2.12475e+07
2.12464e+07
2.12455e+07
2.12445e+07
2.12436e+07
2.12427e+07
2.12419e+07
2.12411e+07
2.12403e+07
2.12396e+07
2.12389e+07
2.12383e+07
2.12377e+07
2.12371e+07
2.12365e+07
2.1236e+07
2.12355e+07
2.12351e+07
2.12347e+07
2.12343e+07
2.1234e+07
2.12337e+07
2.12334e+07
2.12332e+07
2.1233e+07
2.12328e+07
2.12327e+07
2.12326e+07
2.12325e+07
2.12325e+07
2.06999e+07
2.11115e+07
2.12176e+07
2.12483e+07
2.12567e+07
2.12583e+07
2.12579e+07
2.12568e+07
2.12556e+07
2.12543e+07
2.12531e+07
2.12519e+07
2.12507e+07
2.12496e+07
2.12485e+07
2.12474e+07
2.12464e+07
2.12454e+07
2.12445e+07
2.12436e+07
2.12427e+07
2.12419e+07
2.12411e+07
2.12403e+07
2.12396e+07
2.12389e+07
2.12383e+07
2.12376e+07
2.12371e+07
2.12365e+07
2.1236e+07
2.12355e+07
2.12351e+07
2.12347e+07
2.12343e+07
2.1234e+07
2.12337e+07
2.12334e+07
2.12332e+07
2.1233e+07
2.12328e+07
2.12327e+07
2.12326e+07
2.12325e+07
2.12325e+07
2.07412e+07
2.10855e+07
2.12076e+07
2.12451e+07
2.12557e+07
2.1258e+07
2.12578e+07
2.12568e+07
2.12556e+07
2.12543e+07
2.12531e+07
2.12519e+07
2.12507e+07
2.12496e+07
2.12485e+07
2.12474e+07
2.12464e+07
2.12454e+07
2.12445e+07
2.12436e+07
2.12427e+07
2.12419e+07
2.12411e+07
2.12403e+07
2.12396e+07
2.12389e+07
2.12383e+07
2.12376e+07
2.12371e+07
2.12365e+07
2.1236e+07
2.12355e+07
2.12351e+07
2.12347e+07
2.12343e+07
2.1234e+07
2.12337e+07
2.12334e+07
2.12332e+07
2.1233e+07
2.12328e+07
2.12327e+07
2.12326e+07
2.12325e+07
2.12325e+07
3.45755e+07
2.78007e+07
2.4933e+07
2.27165e+07
2.04149e+07
3.23873e+07
2.80408e+07
2.52356e+07
2.30908e+07
2.12641e+07
3.09111e+07
2.80831e+07
2.54986e+07
2.34402e+07
2.18668e+07
2.99349e+07
2.80307e+07
2.56625e+07
2.36843e+07
2.22611e+07
2.93672e+07
2.79663e+07
2.57309e+07
2.38021e+07
2.24815e+07
2.06999e+07
2.11115e+07
2.12176e+07
2.12483e+07
2.12567e+07
2.12583e+07
2.12579e+07
2.12568e+07
2.12556e+07
2.12543e+07
2.12531e+07
2.12519e+07
2.12507e+07
2.12496e+07
2.12485e+07
2.12474e+07
2.12464e+07
2.12454e+07
2.12445e+07
2.12436e+07
2.12427e+07
2.12419e+07
2.12411e+07
2.12403e+07
2.12396e+07
2.12389e+07
2.12383e+07
2.12376e+07
2.12371e+07
2.12365e+07
2.1236e+07
2.12355e+07
2.12351e+07
2.12347e+07
2.12343e+07
2.1234e+07
2.12337e+07
2.12334e+07
2.12332e+07
2.1233e+07
2.12328e+07
2.12327e+07
2.12326e+07
2.12325e+07
2.12325e+07
2.10722e+07
2.11969e+07
2.12423e+07
2.12558e+07
2.1259e+07
2.12591e+07
2.12581e+07
2.12569e+07
2.12556e+07
2.12543e+07
2.12531e+07
2.12519e+07
2.12507e+07
2.12496e+07
2.12485e+07
2.12475e+07
2.12464e+07
2.12455e+07
2.12445e+07
2.12436e+07
2.12427e+07
2.12419e+07
2.12411e+07
2.12403e+07
2.12396e+07
2.12389e+07
2.12383e+07
2.12377e+07
2.12371e+07
2.12365e+07
2.1236e+07
2.12355e+07
2.12351e+07
2.12347e+07
2.12343e+07
2.1234e+07
2.12337e+07
2.12334e+07
2.12332e+07
2.1233e+07
2.12328e+07
2.12327e+07
2.12326e+07
2.12325e+07
2.12325e+07
2.13916e+07
2.12979e+07
2.12735e+07
2.12655e+07
2.1262e+07
2.126e+07
2.12584e+07
2.1257e+07
2.12557e+07
2.12544e+07
2.12531e+07
2.12519e+07
2.12508e+07
2.12496e+07
2.12485e+07
2.12475e+07
2.12465e+07
2.12455e+07
2.12445e+07
2.12436e+07
2.12428e+07
2.12419e+07
2.12411e+07
2.12404e+07
2.12397e+07
2.1239e+07
2.12383e+07
2.12377e+07
2.12371e+07
2.12366e+07
2.12361e+07
2.12356e+07
2.12351e+07
2.12347e+07
2.12344e+07
2.1234e+07
2.12337e+07
2.12335e+07
2.12332e+07
2.1233e+07
2.12329e+07
2.12327e+07
2.12326e+07
2.12326e+07
2.12325e+07
2.16371e+07
2.13844e+07
2.13012e+07
2.12742e+07
2.12648e+07
2.12609e+07
2.12587e+07
2.12571e+07
2.12557e+07
2.12544e+07
2.12532e+07
2.1252e+07
2.12508e+07
2.12497e+07
2.12486e+07
2.12475e+07
2.12465e+07
2.12455e+07
2.12446e+07
2.12437e+07
2.12428e+07
2.1242e+07
2.12412e+07
2.12404e+07
2.12397e+07
2.1239e+07
2.12384e+07
2.12377e+07
2.12372e+07
2.12366e+07
2.12361e+07
2.12356e+07
2.12352e+07
2.12348e+07
2.12344e+07
2.12341e+07
2.12338e+07
2.12335e+07
2.12333e+07
2.12331e+07
2.12329e+07
2.12328e+07
2.12327e+07
2.12326e+07
2.12326e+07
2.18058e+07
2.14361e+07
2.13176e+07
2.12794e+07
2.12664e+07
2.12614e+07
2.12589e+07
2.12572e+07
2.12558e+07
2.12545e+07
2.12532e+07
2.1252e+07
2.12509e+07
2.12497e+07
2.12486e+07
2.12476e+07
2.12466e+07
2.12456e+07
2.12446e+07
2.12437e+07
2.12429e+07
2.1242e+07
2.12412e+07
2.12405e+07
2.12397e+07
2.12391e+07
2.12384e+07
2.12378e+07
2.12372e+07
2.12367e+07
2.12362e+07
2.12357e+07
2.12352e+07
2.12348e+07
2.12345e+07
2.12341e+07
2.12338e+07
2.12335e+07
2.12333e+07
2.12331e+07
2.1233e+07
2.12328e+07
2.12327e+07
2.12327e+07
2.12326e+07
)
;
boundaryField
{
AirInlet
{
type fixedValue;
value uniform 0.1;
}
WaterInlet
{
type fixedValue;
value uniform 0.1;
}
ChannelWall
{
type fixedValue;
value uniform 0.1;
}
Outlet
{
type inletOutlet;
inletValue uniform 0.1;
value nonuniform List<scalar>
11
(
2.12326e+07
2.12326e+07
2.12325e+07
2.12325e+07
2.12325e+07
2.12325e+07
2.12325e+07
2.12325e+07
2.12325e+07
2.12326e+07
2.12326e+07
)
;
}
FrontAndBack
{
type empty;
}
}
// ************************************************************************* //
| |
7a38186b6c26f63c65d79ce7f70bec5fa4d7eb4f | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /EngineTesting/Code/System/SystemTesting/SecuritySuite/AddAccess/AddAccessAllowedAceTesting.h | 7228e67b1a66d462cdc433390c0c8779f1462592 | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,141 | h | AddAccessAllowedAceTesting.h | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 引擎测试版本:0.9.0.1 (2023/01/27 23:53)
#ifndef SYSTEM_SECURITY_SUITE_ADD_ACCESS_ALLOWED_ACE_TESTING_H
#define SYSTEM_SECURITY_SUITE_ADD_ACCESS_ALLOWED_ACE_TESTING_H
#include "AddAccessTestingBase.h"
namespace System
{
class AddAccessAllowedAceTesting final : public AddAccessTestingBase
{
public:
using ClassType = AddAccessAllowedAceTesting;
using ParentType = AddAccessTestingBase;
public:
explicit AddAccessAllowedAceTesting(const OStreamShared& stream);
CLASS_INVARIANT_FINAL_DECLARE;
private:
void DoRunUnitTest() final;
void MainTest();
void AddAccessAllowedAccessControlEntriesTest(AccessControlListRevision accessControlListRevision);
void AddAccessTest(AccessCheckACLPtr acl, AccessControlListRevision accessControlListRevision, SpecificAccess specificAccess, SecuritySID& sid);
};
}
#endif // SYSTEM_SECURITY_SUITE_ADD_ACCESS_ALLOWED_ACE_TESTING_H |
195f13df3c34b933e4e228b61487adabb42daeae | 7fc9ca1aa8c9281160105c7f2b3a96007630add7 | /AlexandaRhombus.cpp | 53ff2b4e605152c0ec8bbebd3b6505fe33615a61 | [] | no_license | PatelManav/Codeforces_Backup | 9b2318d02c42d8402c9874ae0c570d4176348857 | 9671a37b9de20f0f9d9849cd74e00c18de780498 | refs/heads/master | 2023-01-04T03:18:14.823128 | 2020-10-27T12:07:22 | 2020-10-27T12:07:22 | 300,317,389 | 2 | 1 | null | 2020-10-27T12:07:23 | 2020-10-01T14:54:31 | C++ | UTF-8 | C++ | false | false | 295 | cpp | AlexandaRhombus.cpp | #include<bits/stdc++.h>
#define ll long long
#define M 1000000007
using namespace std;
int main(){
ll n;
cin >> n;
ll ans = 1;
for(ll i = 1; i < n; i++){
ans += 4*i;
}
cout << ans << endl;
return 0;
} |
c94a54f2f59d62b360202690e2d86ad876eaec94 | 9a3fc0a5abe3bf504a63a643e6501a2f3452ba6d | /structures/kmp.cpp | 60cca9e5d3b267957a8bb9280106483c310e9cd5 | [] | no_license | rodolfo15625/algorithms | 7034f856487c69553205198700211d7afb885d4c | 9e198ff0c117512373ca2d9d706015009dac1d65 | refs/heads/master | 2021-01-18T08:30:19.777193 | 2014-10-20T13:15:09 | 2014-10-20T13:15:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 642 | cpp | kmp.cpp | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
using namespace std;
#define MAX_L 1000000
int F[MAX_L];
void prefixFunction(string P){
int n=P.size(),k=0;
F[0]=0;
for(int i=1;i<n;i++){
while(k>0 && P[k]!=P[i])k=F[k-1];
if(P[k]==P[i])++k;
F[i]=k;
}
}
int KMP(string P, string T){
int n=P.size(),L=T.size(),k=0,ans=0;
for(int i=0;i<L;i++){
while(k>0 && P[k]!=T[i])k=F[k-1];
if(P[k]==T[i])++k;
if(k==n){
ans++;
k=F[k-1];
}
}
return ans;
}
int main(){
string T="barfoobarfoobarfoobarfoobarfoo";
string P="foobarfoo";
prefixFunction(P);
cout<<KMP(P,T)<<endl;
return 0;
}
|
3f6a13cb26e52b5fb56697d1a516070bd327bde3 | 56345c289644498f96d79dcdbee0476ea4342daa | /lc045-4.cpp | f13be370ffdc7a90e8e31a97fa6c8f50f59c8211 | [] | no_license | boyima/Leetcode | 8023dd39d06bcb3ebb4c35c45daa193c78ce2bfe | 0802822e1cbf2ab45931d31017dbd8167f3466cc | refs/heads/master | 2020-12-13T06:35:00.834628 | 2019-11-05T22:27:50 | 2019-11-05T22:27:50 | 47,539,183 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 387 | cpp | lc045-4.cpp | class Solution {
public:
int jump(vector<int>& nums) {
int lastMax = 0;
int curMax = 0;
int nStep = 0;
int i = 0;
while(lastMax < nums.size() - 1){
for(; i <= lastMax; i++){
curMax = max(curMax, i + nums[i]);
}
nStep++;
lastMax = curMax;
}
return nStep;
}
};
|
8bd6a3e344efcce087fed804b7ecd06460b4669a | 6f5febee7108d328864679b06af918a912b09831 | /src/l1_transport/packet.cpp | b3a0376e006f8e1f8ca117329f2e2721e9f5ebb5 | [
"MIT"
] | permissive | dapaulid/libremo | 7b816cff22ba5af3d078fc5c7014fdf1c06e00cc | 3aa1da6ed13586e842906f21c2eb4c82fec716fe | refs/heads/master | 2020-09-06T20:57:40.254397 | 2020-04-15T14:30:41 | 2020-04-15T14:30:41 | 220,548,548 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,784 | cpp | packet.cpp | //------------------------------------------------------------------------------
/**
* @license
* Copyright (c) Daniel Pauli <dapaulid@gmail.com>
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//------------------------------------------------------------------------------
#include "packet.h"
#include "reader.h"
#include "utils/logger.h"
#include "utils/contracts.h"
#include <iostream>
#include <iomanip>
#include <sstream>
//------------------------------------------------------------------------------
namespace remo {
namespace trans {
//------------------------------------------------------------------------------
//! logger instance
static Logger logger("Packet");
//------------------------------------------------------------------------------
// class Packet
//------------------------------------------------------------------------------
//
Packet::Packet():
m_buffer(),
m_header(),
m_payload()
{
set_header_capacity(REMO_MAX_PACKET_HEADER_SIZE);
}
//------------------------------------------------------------------------------
Packet::~Packet()
{
}
//------------------------------------------------------------------------------
void Packet::recycle()
{
// reset state
set_header_capacity(REMO_MAX_PACKET_HEADER_SIZE);
// call base
Recyclable::recycle();
}
//------------------------------------------------------------------------------
void Packet::set_header_capacity(size_t a_capacity)
{
REMO_PRECOND({
REMO_ASSERT(a_capacity <= get_buffer_size(),
"header capacity must not exceed buffer size");
});
uint8_t* border = &m_buffer[a_capacity];
m_header.init(border, a_capacity);
m_payload.init(border, get_buffer_size() - a_capacity);
}
//------------------------------------------------------------------------------
size_t Packet::get_header_capacity() const
{
return m_header.get_capacity();
}
//------------------------------------------------------------------------------
void Packet::drop_header(size_t a_size)
{
REMO_PRECOND({
REMO_ASSERT(a_size <= m_payload.get_size(),
"header size to drop must not exceed payload size");
});
m_payload.init(m_payload.get_data() + a_size, m_payload.get_capacity(),
m_payload.get_size() - a_size);
}
//------------------------------------------------------------------------------
std::string Packet::to_string() const
{
return BinaryReader(get_payload()).to_string();
}
//------------------------------------------------------------------------------
} // end namespace trans
} // end namespace remo
//------------------------------------------------------------------------------
|
8d47053a6aad74847ae5ce06583afffd992a9f9f | 6aa9fdca0bdb54ad86a7facddafbeec913120468 | /Source/src/QtDSP/qtdsp_agc.h | 425494f07f9ffe985d9bc0ad16acb5b885510ea6 | [] | no_license | n1gp/cudaSDR | b6be15d7faa96bc692bb9cc288e85dc964cf2878 | 00559c04c2fb68aeb63b2a6c526e8c006f131b32 | refs/heads/master | 2022-02-12T18:53:58.422744 | 2022-02-09T20:19:20 | 2022-02-09T20:19:20 | 33,419,824 | 12 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 2,751 | h | qtdsp_agc.h | /**
* @file qtdsp_agc.h
* @brief AGC header file for QtDSP
* @author Hermann von Hasseln, DL3HVH
* @version 0.1
* @date 2012-05-14
*/
/*
* Copyright (C) 2007, 2008, 2009, 2010 Philip A Covington, N8VB
*
* adapted for QtDSP by (C) 2012 Hermann von Hasseln, DL3HVH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _QTDSP_AGC_H
#define _QTDSP_AGC_H
#include "qtdsp_qComplex.h"
#include "../cusdr_settings.h"
//#include <QObject>
//#include <QMutex>
const int FASTLEAD = 72;
class QAGC : public QObject {
Q_OBJECT
public:
QAGC(QObject *parent = 0, int size = 0);
~QAGC();
//void ProcessAGC(CPX* in, CPX* out, int size);
void ProcessAGC(const CPX &in, CPX &out, int size);
//AGCMode Mode() const;
float gain() const;
float fastGain() const;
float hangTime() const;
float gainTop() const;
float gainBottom() const;
float attack() const;
float decay() const;
float fixedGain() const;
void setGain(float gain);
void setHangTime(float time);
void setGainTop(float gain);
void setGainBottom(float gain);
void setAttack(float attack);
void setDecay(float decay);
void setFixedGain(float gain);
public slots:
void setMode(AGCMode mode);
private:
Settings *set;
QMutex mutex;
//TReceiver m_rxData;
AGCMode m_agcMode;
CPX G;
int m_size;
qint16 m_mask;
qint16 m_index;
qint16 m_sndex;
qint16 m_hangIndex;
qint16 m_fastIndex;
qint16 m_fastHang;
float m_samplerate;
float m_gainTop;
float m_gainNow;
float m_gainFastNow;
float m_gainBottom;
float m_gainLimit;
float m_gainFix;
float m_attack;
float m_oneMAttack;
float m_decay;
float m_oneMDecay;
float m_slope;
float m_fastAttack;
float m_oneMFastAttack;
float m_fastDecay;
float m_oneMFastDecay;
float m_hangTime;
float m_hangThresh;
float m_fastHangTime;
float Scale(float in_val, float scalevalue);
};
#endif // _QTDSP_AGC_H
|
d0ab3d69bd7663c24be111656b23f830c03d057e | c1fb055ca7d0ea9adebc4c3af3a8182e0b9e4f3a | /src/Wheel.h | b6b1672e70a74aad15b65a3d39c062b963963453 | [] | no_license | Gelmes/SelfBalancingRobot | 673feaa161686d61e0ed0fcadf61d634acb42f5e | 5418270082a808338f0ea316f4f91db35a19d472 | refs/heads/main | 2022-12-26T18:50:26.819431 | 2020-10-11T23:21:43 | 2020-10-11T23:21:43 | 303,009,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | h | Wheel.h |
#ifndef _Wheel_h
#define _Wheel_h
#include <stdint.h>
#include "Motor.h"
class Wheel
{
public:
Wheel(Motor * motor);
void setVelocityInMetersPerSecond(double velocity);
void setStepsInOneMeter(uint32_t steps);
double getDistanceInMeters();
void resetDistance(){ _motor->resetSteps(); }
void stop(){ _motor->stop(); }
private:
Motor * _motor;
uint32_t _stepsInOneMeter;
};
#endif |
ff81b02e3cf4b9ca808874dbf68cfa90cde14999 | e6958883cefe5a75fb7632d49f829f43dc392519 | /labyrinth/MemoryDrawer.h | 1258542f9edc181b699621ed419b2be0332e5c7b | [] | no_license | itmoshare/computer_graphics_lab1_tron | fe2b4d272d0f973e9acd9bc8bccd1225f2acc915 | f9c50ef3a4caa262227800548b6489900b67741a | refs/heads/master | 2021-08-31T20:45:01.094781 | 2017-12-22T21:04:56 | 2017-12-22T21:04:56 | 107,770,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | h | MemoryDrawer.h | #ifndef MEMORYDRAWER_H
#define MEMORYDRAWER_H
#include <Windows.h>
#include <algorithm>
#include <iterator>
#include <tchar.h>
#include <cassert>
#include <sstream>
#include <vector>
#include <memory>
#include <map>
#include "WindowOptions.h"
#include "Bitmap.h"
#include "GDIBitmap.h"
#include "Direction.h"
class MemoryDrawer {
public:
MemoryDrawer() {};
~MemoryDrawer() {};
void OnInitializeGraphice(HWND window, int windowWidth, int windowHeight);
void OnBeginGraphics();
void OnEndGraphics();
void DrawGdi(GDIBitmap gdi, Direction direction, bool player);
void DrawString(const std::wstring text, COLORREF color, int x, int y) const;
void DrawWinGame();
void DrawLoseGame();
void DrawRect(RECT rect, HBRUSH brush);
void DrawBackgroundRect(RECT rect, HBRUSH brush);
void SetGameoverFontSettings();
int windowWidth;
int windowHeight;
HDC defaultHdc;
HWND window;
HDC backbufferDC;
HBITMAP backbufferBitmap;
HDC backgroundBufferDC;
HBITMAP backgroundBufferBitmap;
HDC bitmapDC;
HGDIOBJ oldObject;
HGDIOBJ oldObject2;
HGDIOBJ def_font;
std::vector<RECT> backRects;
std::vector<HBRUSH> brashes;
//DIBits
BYTE * bytes;
BYTE * backBytes;
BITMAPINFO bitmapInfo;
void CustomFillRect(RECT rect, int r, int g, int b);
unsigned char * GetReversePixels(unsigned char * bytes, int count);
void InitBitmap(GDIBitmap gdi);
std::vector<BITMAPINFO> bitmapInfos;
std::vector<unsigned char *> pixelPlayersBytes;
std::vector<unsigned char *> reversedPixelPlayersBytes;
private:
};
#endif |
a020aeee1248e6e006fbc411e1f7638faecf2c1b | a0873dcd5cf81acecb8845632e9283fa1a5ebf3b | /sto_pompek2016/Gracz.h | b5097830b7ab075ade41fe16581c1aa6a8ad3f3c | [] | no_license | najwer23/sto-pompek-2016 | 00eed40b5e0287d8241890e6bacdfb08786e57ae | 33d5ac3950c0f35223193817876faff0c02598a6 | refs/heads/master | 2020-09-11T06:20:35.469184 | 2019-11-15T17:15:25 | 2019-11-15T17:15:25 | 221,969,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | h | Gracz.h | #ifndef _GRACZ_H_
#define _GRACZ_H_
#include <iostream>
#include "Trener.h"
using namespace std;
class Gracz : public Trener
{
public:
int dzien;
Gracz(int d=1, int t=-1)
{
dzien=d;
test=t;
}
void nowy_trening();
void plan_treningu();
bool zapis(string nazwaPliku);
bool wczytaj_zapis(string nazwaPliku);
void czas(int a,int b);
void kalendarz();
};
#endif
|
8a0199b1298a53abc4a321255dc89f38404962db | 267d25e2c22e1c8de247767628e536d5ff1e8861 | /sampleapps/producer-starter.hpp | 28d6da1fe4ae939fd7cf99af8c335e0a7ad5880b | [] | no_license | wawawanet/ndn-cxx_to_ndnSIM | a136801cb4b9015e899bbca7abfe5828c7b08cb3 | 01f995115090b97222b2cb0894baa8dae65a7d79 | refs/heads/master | 2020-03-24T20:33:22.868362 | 2018-08-01T05:30:03 | 2018-08-01T05:33:12 | 142,984,637 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | hpp | producer-starter.hpp | #ifndef NDNSIM_EXAMPLES_NDN_CXX_SIMPLE_CUSTOM_PRODUCER_STARTER_HPP
#define NDNSIM_EXAMPLES_NDN_CXX_SIMPLE_CUSTOM_PRODUCER_STARTER_HPP
#include "producer.hpp"
#include "ns3/ndnSIM/helper/ndn-stack-helper.hpp"
#include "ns3/application.h"
namespace ns3 {
// Class inheriting from ns3::Application
class CustomProducerStarter : public Application
{
public:
static TypeId
GetTypeId()
{
static TypeId tid = TypeId("CustomProducerStarter")
.SetParent<Application>()
.AddConstructor<CustomProducerStarter>();
return tid;
}
protected:
// inherited from Application base class.
virtual void
StartApplication()
{
// Create an instance of the app, and passing the dummy version of KeyChain (no real signing)
m_instance.reset(new app::CustomProducer(ndn::StackHelper::getKeyChain()));
m_instance->run(); // can be omitted
}
virtual void
StopApplication()
{
// Stop and destroy the instance of the app
m_instance.reset();
}
private:
std::unique_ptr<app::CustomProducer> m_instance;
};
} // namespace ns3
#endif // NDNSIM_EXAMPLES_NDN_CXX_SIMPLE_REAL_APP_STARTER_HPP |
0dba36fe247a1642226c6d7bfe23ddfaf4c440b7 | 1375ca76acdfa13bd6dc230305fe7795a302066c | /Lec10/read_records.cpp | a8e8ddaa5ba2ac6cd11663b923208fb1152c6521 | [] | no_license | KartavyaKothari/cpp-lpu-x | 7c6ced2dc08d747c47db96bbdba61e25cce333fe | ccd10eb0286266644f0392a596bec804927e0aa4 | refs/heads/main | 2023-05-20T09:58:30.353851 | 2021-06-17T15:30:55 | 2021-06-17T15:30:55 | 372,839,128 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | read_records.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
ifstream f;
f.open("records.txt");
int n;
f>>n;
string name;
int age;
for(int i = 0 ; i < n ; i++){
f>>name>>age;
cout<<name<<" is "<<age<<" years old."<<endl;
}
return 0;
} |
68846a80220dfd426b217086b509ecb97dc694cf | a9b1bfe985c80f277302f6ea7320fb9a716154d4 | /test20.cpp | 23887865a97d6f1be4da65caf655240561270104 | [] | no_license | kenshimota/Learning-Cpp | b9881026657a14d15fce7d7629b51fc1506cc5e7 | 29151f94868569eb3d614e7cab252a984fab13b9 | refs/heads/master | 2021-09-14T02:20:11.937349 | 2018-02-15T01:34:15 | 2018-02-15T01:34:15 | 112,971,003 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,604 | cpp | test20.cpp | #include <iostream>
using namespace std;
class faction{
private:
int numerator;
int denominator;
public:
//constructor por defecto de nuestra clase
faction(){
this->numerator = 0;
this->denominator = 1; //use 1 porque todo numero esta dividido entre 1
}
// funcion encargada de obtener los valores nn->(numero numerador), nd -> (numero denominador)...
void getValue(int nn, int nd){
this->numerator = nn;
this->denominator = nd;
}
/* -- Funcion encargada de imrprimit los el resultado de la division -- */
void print_result(){
cout << "El resultado de (" << this->numerator << " / "
<< this->denominator << ") es: "
<< this->getResultOfFaction() << endl;
}
//funcion encargada de evaluar para ver si es posible y retornar el valor
int getResultOfFaction(){
if(this->denominator != 0)
return char (this->numerator/ this->denominator);
else{
cout << "No es posible dividir entre cero..." << endl;
system("pause");
exit(1);
}
}
};
int main(){
//crea una instancia hacia la clase faction en operation en imprimira 0
faction operation;
operation.print_result();
/* Le daremos los valores a numerador y denominador, he imprimiremos el resultado
de la fración */
operation.getValue(4,2);
operation.print_result();
/* Le daremos los valores al numerador y denominador, he trataremos de imprimir algo imposible
tratando de hacer que el programa evalue si es posible la division */
operation.getValue(1,0);
operation.print_result();
}
|
fc0d23eb95f3db2f22479c8837db117abdfcc685 | 0bd8cce1dfc3a0abb3ddecb0308d3ba6632acf2b | /YellowBelt/YellowBelt/Final/node.h | 2917ef7e334b9bc79b60a363ac10cb9ca61e9625 | [] | no_license | S3lfik/yandex_cpp | fb892a475ddcfecb58ced44965f25d55941b69a2 | 767783e679d9942d4811c1d9b4acee8d46e2d510 | refs/heads/master | 2021-05-22T17:39:45.728287 | 2020-05-30T13:50:00 | 2020-05-30T13:50:00 | 253,025,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,235 | h | node.h | #pragma once
#include <string>
#include <memory>
#include "date.h"
enum Comparison
{
NotEqual = 0,
Equal,
Less,
LessOrEqual,
Greater,
GreaterOrEqual
};
enum LogicalOperation
{
Or,
And
};
class Node
{
public:
virtual bool Evaluate(const Date& date, const std::string& event) const = 0;
};
class EmptyNode : public Node
{
bool Evaluate(const Date& date, const std::string& event) const override;
};
class DateComparisonNode : public Node
{
public:
DateComparisonNode(Comparison comp, const Date& date);
bool Evaluate(const Date& date, const std::string& event) const override;
private:
Comparison m_comp;
Date m_date;
};
class EventComparisonNode : public Node
{
public:
EventComparisonNode(Comparison comp, const std::string& ev);
bool Evaluate(const Date& date, const std::string& event) const override;
private:
Comparison m_comp;
std::string m_event;
};
class LogicalOperationNode : public Node
{
public:
LogicalOperationNode(LogicalOperation op, std::shared_ptr < Node> lhs, std::shared_ptr < Node> rhs);
bool Evaluate(const Date& date, const std::string& event) const override;
private:
LogicalOperation m_operation;
std::shared_ptr<Node> m_leftParent;
std::shared_ptr<Node> m_rightParent;
}; |
c390e3365cae86186e1181344ee4dd4510718f73 | 5d12283434dc723419fb05ae5303060cc309b044 | /second semester/oop/wannabe2-qt/mainwindow.h | a785a319d02a2c4304dd5edc04f0bd488cc32be3 | [] | no_license | alexresiga/courses | 8b33591660c887dcea3b6a850aaacf90e204a94d | c1124a848e100f97ca3589f2f7bacc3c8434c220 | refs/heads/master | 2020-04-06T07:40:31.042062 | 2019-05-12T23:58:38 | 2019-05-12T23:58:38 | 157,281,121 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | h | mainwindow.h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <controller.h>
#include <QListWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(Controller ctrl, QWidget *parent = 0);
~MainWindow();
private:
Controller ctrl;
QListWidget* elements;
QPushButton* show_button;
QLineEdit* priority;
QLabel* showPriority;
public slots:
void populate();
void handleShow();
signals:
void refresh();
};
#endif // MAINWINDOW_H
|
84da881867807c9191060108d94a6df7382886aa | 1f5930ed32ca844f062adec8a38d83746af70e20 | /66정수 3개 입력받아 짝홀 출력하기.cpp | 00e406a4b71c731d084175b32a8c98fd00c402e0 | [] | no_license | engineerjkk/CodeUp | 9e6f5022d5fccd26da595c888ed84cafc9f34221 | 35c4c84ecc3492ef283e1f8e236bdc0fec9cb997 | refs/heads/main | 2023-05-02T13:49:05.877153 | 2021-05-21T15:43:54 | 2021-05-21T15:43:54 | 369,049,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | cpp | 66정수 3개 입력받아 짝홀 출력하기.cpp | #include <stdio.h>
int main()
{
int a;
scanf_s("%d", &a);
if ((a % 2 == 0)?printf("%s\n","even"):printf("%s\n","odd"));
if ((a > 0) ? printf("%s\n", "plus") : printf("%s\n", "minus"));
return 0;
}
|
dcb2d15415b6c3c2836cc881401bb62013649458 | c534c34d907cce01d6d45ef3725f8e564b37200a | /cs3/svn/Lab7/hashmap.h | 7b4ede34a5ee951c071cd8e07ebf1adcc6563e14 | [] | no_license | PJ-Leyden/cs_projects | 4b32904a22b9d0b326a05b261eed60d6001126bf | 46b40d9364d2eff7e205e8316bd33622ecbf607a | refs/heads/master | 2021-06-11T21:10:49.365719 | 2019-12-06T00:04:32 | 2019-12-06T00:04:32 | 149,900,613 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 7,791 | h | hashmap.h | // implementation basic hashmap (unordered container)
// Mikhail Nesterenko: adapted from Proc C++
// 4/15/2014
#include <cstddef>
#include <utility>
#include <functional>
#include <vector>
#include <list>
using std::vector;
using std::list;
using std::pair;
using std::make_pair;
//////////////////////////////////////////
// hash function implemented as a class
//////////////////////////////////////////
// any Hash Class must provide
// two methods: hash() and numBuckets().
template <typename T>
class DefaultHash {
public:
DefaultHash(size_t numBuckets = defaultNumBuckets);
size_t hash(const T& key) const;
size_t numBuckets() const { return numBuckets_; }
private:
// default number of buckets in the hash
static const size_t defaultNumBuckets = 101;
size_t numBuckets_;
};
template <typename T>
DefaultHash<T>::DefaultHash(size_t numBuckets) : numBuckets_(numBuckets) {}
// uses the division method for hashing.
// treats the key as a sequence of bytes, sums the ASCII
// values of the bytes, and mods the total by the number
// of buckets.
template <typename T>
size_t DefaultHash<T>::hash(const T& key) const {
size_t res = 0;
for (size_t i = 0; i < sizeof(key); ++i) {
const unsigned char b = *(reinterpret_cast<const unsigned char *>(&key) + i);
res += b;
}
return res % numBuckets_;
}
////////////////////////////////////////////////
// container class
////////////////////////////////////////////////
template <typename Key, typename Value,
typename Compare = std::equal_to<Key>,
typename Hash = DefaultHash<Key>>
class hashmap{
public:
typedef pair<const Key, Value> Element;
// constructor
// invokes constructors for comparison and hash objects
hashmap(const Compare& comp = Compare(), const Hash& hash = Hash());
Element* find(const Key& x); // returns pointer to element with key x,
// nullptr if not found
pair<Element*, bool> insert(const Element& x); // inserts the key/value pair
pair<Element*, bool> erase(const Key& x); // erases element with key x, if exists
Value& operator[] (const Key& x); // returns reference on value of
// element with key, inserts if does not exist
void rehash(size_t n);
private:
// helper function for various searches
typename list<Element>::iterator findElement(const Key& x, const size_t bucket);
size_t size_; // number of elements in the container
Compare comp_; // comparison functor, equal_to by default
Hash hash_; // hash functor
// hash contents: vector of buckets
// each bucket is a list containing key->value pairs
vector<list<Element>> elems_;
};
////////////////////////////////////////////////
// container member functions
////////////////////////////////////////////////
// Construct elems_ with the number of buckets.
template <typename Key, typename Value, typename Compare, typename Hash>
hashmap<Key, Value, Compare, Hash>::hashmap(
const Compare& comp, const Hash& hash):
size_(0), comp_(comp), hash_(hash) {
elems_ = vector<list<Element>>(hash_.numBuckets());
}
//find a specific key in a specific bucket
template <typename Key, typename Value, typename Compare, typename Hash>
typename list<pair<const Key, Value>>::iterator // return type CAN replace with list<Element>::iterator
hashmap<Key, Value, Compare, Hash>::findElement(const Key& x, size_t bucket){
// look for the key in the bucket
for (auto it = elems_[bucket].begin(); it != elems_[bucket].end(); ++it)
if (comp_(it->first, x))
return it;
return elems_[bucket].end(); // element not found
}
// returns a pointer to the element with key x
// returns nullptr if no element with this key
template <typename Key, typename Value, typename Compare, typename Hash>
typename hashmap<Key, Value, Compare, Hash>::Element* // return value type
hashmap<Key, Value, Compare, Hash>::find(const Key& x) {
size_t bucket = hash_.hash(x);
auto it=findElement(x, bucket); // use the findElement() helper
if (it != elems_[bucket].end())
// found the element. Return a pointer to it.
return &(*it); // dereference the iterator to list
// then take the address of list element
else // didn't find the element -- return nullptr
return nullptr;
}
// finds the element with key x, inserts an
// element with that key if none exists yet. Returns a reference to
// the value corresponding to that key.
template <typename Key, typename Value, typename Compare, typename Hash>
pair<typename hashmap<Key, Value, Compare, Hash>::Element*, bool>
hashmap<Key, Value, Compare, Hash>::insert(const Element& x) {
size_t bucket = hash_.hash(x.first);
auto it = findElement(x.first, bucket); // try to find the element
// if not found, insert a new one.
if (it == elems_[bucket].end()) {
++size_;
elems_[bucket].push_back(x);
it = findElement(x.first, bucket);
return make_pair(&(*it), true);
// iff did find
}else{
return make_pair(&(*it), false);
}
}
// removes the Element with key x, if it exists
template <typename Key, typename Value, typename Compare, typename Hash>
pair<typename hashmap<Key, Value, Compare, Hash>::Element*, bool>
hashmap<Key, Value, Compare, Hash>::erase(const Key& x) {
size_t bucket = hash_.hash(x);
auto it = findElement(x, bucket); // try to find the element
int ret_mode = 0;
//if I found the element
if(it != elems_[bucket].end()){
--size_;
//if it was the last element left
if(size_ == 0){
elems_[bucket].erase(it);
return make_pair(nullptr, true);
}
//the element is not the last in the bucket
if(++it != elems_[bucket].end()){ // return the next element in the bucket.
it = elems_[bucket].erase(--it);
return make_pair(&(*it), true);
//return the begin of the next non empty bucket
}else{
int b = bucket + 1;
if(b >= hash_.numBuckets())b = 0;
while(elems_[b].empty()){
++b;
}
return make_pair(&(*elems_[b].begin()), true);
}
}else{
return make_pair(nullptr, false);
}
/*
if (it != elems_[bucket].end()) { // the element exists, erase it
--size_;
if(size == 0)ret_mode = 1;
if(ret_mode != 1 && it + 1 == elems_[bucket].end() && bucket + 1 < hash_.numBuckets())ret_mode = 2;
if(ret_mode != 1 && it + 1 == elems_[bucket].end() && bucket + 1 >= hash_.numBuckets())ret_mode = 3;
elems_[bucket].erase(it);
switch(ret_mode){
case 1:
return make_pair(nullptr, true);
case 2:
return make_pair(elems_[bucket + 1].begin(), true);
case 3:
return make_pair(elems_[0].begin(), true);
}
//if element doesn't exist
}else{
return make_pair(Element(), false);
}
*/
}
// returns reference to value of element with key x,
// inserts if does not exist
template <typename Key, typename Value, typename Compare, typename Hash>
Value& hashmap<Key, Value, Compare, Hash>::operator[] (const Key& x) {
auto p = insert(make_pair(x, Value()));
return p.first->second;
/*
Element* found = find(x);
if (found == nullptr) { // if key not found, create new element with empty value
insert(make_pair(x, Value())); // calling default constructor on Value
found = find(x); // inefficient but avoids code duplication
}
return found->second;
*/
}
template <typename Key, typename Value, typename Compare, typename Hash>
void hashmap<Key, Value, Compare, Hash>::rehash(size_t n){
//n is smaller or equal so no action
if(n <= hash_.numBuckets()) return;
//create new has func with proper num
hash_ = DefaultHash<Key>(n);
std::vector<Element> temp;
for(auto& list : elems_){
for(auto& e : list){
temp.push_back(e);
}
}
elems_.empty();
elems_ = vector<list<Element>>(hash_.numBuckets());
for(auto& item : temp){
size_t b = hash_.hash(item.first);
elems_[b].push_back(item);
}
}
|
966e2b47f483ef325cbe976533e78ee8bad5491d | f9c4d2253aee97ee66b64ab9f5063bfa6ac6ae54 | /models/synthetic/synthetic.cpp | e87c601e42ee9d74c325c9032b7032178e91f088 | [
"MIT"
] | permissive | wilseypa/warped2-models | 7f14bc8746f0bcc9dbcc9d2e446b28b393372b1a | f148dfcac33ec502e9af519b3133e11d50b09da3 | refs/heads/master | 2023-05-01T01:47:18.445972 | 2020-08-25T01:53:07 | 2020-08-25T01:53:07 | 20,306,278 | 5 | 10 | MIT | 2023-04-15T18:40:31 | 2014-05-29T19:46:51 | C++ | UTF-8 | C++ | false | false | 7,929 | cpp | synthetic.cpp | #include <cassert>
#include <random>
#include "synthetic.hpp"
#include "network.hpp"
#include "tclap/ValueArg.h"
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(InternalEvent)
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ExternalEvent)
inline std::string Node::lpName(const unsigned int lp_index) {
return std::string("Node_") + std::to_string(lp_index);
}
std::vector<std::shared_ptr<warped::Event> > Node::initializeLP() {
std::vector<std::shared_ptr<warped::Event> > events;
/* Register random number generator */
registerRNG<std::default_random_engine>(rng_);
for (unsigned int i = 0; i < num_nodes_; i++) {
unsigned int time = send_distribution_->nextRandNum(*rng_);
events.emplace_back(new InternalEvent {time});
}
return events;
}
std::vector<std::shared_ptr<warped::Event> > Node::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > response_events;
/* Check if event received is a self/internal timer event */
if (event.sender_name_ == event.receiverName()) {
/* Restart the processing_timer/internal event */
unsigned int ts = event.timestamp() + send_distribution_->nextRandNum(*rng_);
response_events.emplace_back(new InternalEvent {ts});
/* Send an external event to one of the nodes in its adjacency list.
* Select node using chosen distribution */
auto id = (unsigned int) node_sel_distribution_->nextRandNum(*rng_) - 1;
// Note: 1 subtracted since min value of distribution is 1.
response_events.emplace_back(
new ExternalEvent { adjacency_list_[id],
floating_point_ops_cnt_,
event.timestamp()+1 });
} else { /* External Event received from other LPs/nodes */
/* Process the event */
float val = 0.5;
for (unsigned int i = 0; i < floating_point_ops_cnt_; i++) {
/* Dummy floating point operation */
val += i;
}
/* Modify the state size */
std::uniform_real_distribution<double>
state_size_change_dist( min_state_size_change_, max_state_size_change_ );
state_size_ += (unsigned int)(state_size_change_dist(*rng_) * state_size_);
state_.stream_.resize(state_size_, '0');
}
return response_events;
}
int main(int argc, const char** argv) {
unsigned int num_nodes = 100000;
std::string network = "Watts-Strogatz,30,0.1";
std::string node_selection = "exponential,0.5";
std::string floating_point_ops_cnt = "1000,1000";
std::string state_size = "100,100";
std::string state_size_change = "0,0";
std::string event_send = "geometric,0.1,10";
TCLAP::ValueArg<unsigned int> num_nodes_arg("", "num-nodes",
"Number of nodes", false, num_nodes, "unsigned int");
TCLAP::ValueArg<std::string> network_arg("", "network-params",
"Network details - <network-type,<network-params>>", false, network, "string");
TCLAP::ValueArg<std::string> node_selection_arg("", "node-selection-params",
"Node selection details - <distribution-type,<distribution-params>>",
false, node_selection, "string");
TCLAP::ValueArg<std::string> floating_point_ops_cnt_arg("", "event-processing-time-range",
"Event processing time (as floating-point calculation count) range - <min,max>",
false, floating_point_ops_cnt, "string");
TCLAP::ValueArg<std::string> state_size_arg("", "state-size-range",
"Size range (in bytes) for the LP state - <min,max>",
false, state_size, "string");
TCLAP::ValueArg<std::string> state_size_change_arg("", "state-size-change-range",
"Change in LP state when an event is processed ; range=(-1,1) - <min,max>",
false, state_size_change, "string");
TCLAP::ValueArg<std::string> event_send_arg("", "event-send-time-delta-params",
"Event send time delta details - <dist-type,<dist-params>,ceiling-value>",
false, event_send, "string");
std::vector<TCLAP::Arg*> model_args = { &num_nodes_arg,
&network_arg,
&node_selection_arg,
&floating_point_ops_cnt_arg,
&state_size_arg,
&state_size_change_arg,
&event_send_arg
};
warped::Simulation synthetic_sim {"Synthetic Simulation", argc, argv, model_args};
num_nodes = num_nodes_arg.getValue();
network = network_arg.getValue();
node_selection = node_selection_arg.getValue();
floating_point_ops_cnt = floating_point_ops_cnt_arg.getValue();
state_size = state_size_arg.getValue();
state_size_change = state_size_change_arg.getValue();
event_send = event_send_arg.getValue();
std::vector<Node> lps;
std::vector<std::string> lp_names;
/* Create uniform distribution for floating point operations count */
std::string delimiter = ",";
size_t pos = floating_point_ops_cnt.find(delimiter);
unsigned int min_floating_point_ops_cnt =
(unsigned int) std::stoul(floating_point_ops_cnt.substr(0, pos));
unsigned int max_floating_point_ops_cnt =
(unsigned int) std::stoul(floating_point_ops_cnt.substr(pos+1));
std::uniform_int_distribution<unsigned int>
floating_point_ops_cnt_dist( min_floating_point_ops_cnt,
max_floating_point_ops_cnt );
/* Create uniform distribution for the state size */
pos = state_size.find(delimiter);
unsigned int min_state_size = (unsigned int) std::stoul(state_size.substr(0, pos));
unsigned int max_state_size = (unsigned int) std::stoul(state_size.substr(pos+1));
std::uniform_int_distribution<unsigned int>
state_size_dist( min_state_size, max_state_size );
/* Parse the range of state size change */
pos = state_size_change.find(delimiter);
double min_state_size_change = std::stod(state_size_change.substr(0, pos));
double max_state_size_change = std::stod(state_size_change.substr(pos+1));
/* Create the LPs */
std::default_random_engine generator (num_nodes);
for (unsigned int i = 0; i < num_nodes; i++) {
auto name = Node::lpName(i);
lp_names.push_back(name);
lps.emplace_back( name,
num_nodes,
floating_point_ops_cnt_dist(generator),
state_size_dist(generator),
min_state_size_change,
max_state_size_change,
i
);
}
std::vector<warped::LogicalProcess*> lp_pointers;
for (auto& lp : lps) {
lp_pointers.push_back(&lp);
}
/* Create the Network */
Network *graph = buildNetwork(network, lp_names);
for (auto& lp : lps) {
/* Create the send time distribution */
lp.send_distribution_ = buildDist(event_send);
/* Fetch the adjacency list for each node */
lp.adjacency_list_ = graph->adjacencyList(lp.name_);
assert(lp.adjacency_list_.size());
/* Create the node selection distribution */
node_selection += "," + std::to_string(lp.adjacency_list_.size());
lp.node_sel_distribution_ = buildDist(node_selection);
}
delete graph;
/* Simulate the synthetic model */
synthetic_sim.simulate(lp_pointers);
return 0;
}
|
1ffae100eece49c32012697f03bcf7db670dfc8a | 14a2979c0baeb2ef14b3f34bb4017d541c8b0d8f | /apps/DataCollections/participant.cpp | d185e77c1e0341b7ff715fb090120fa85be6fb3e | [
"MIT"
] | permissive | MangoCats/aosuite | 1fb6d3c929ad0634b07beb3a2fc7548dbcb6f0e9 | bddabf44eb965f55a6f8628040c73fea4902db2f | refs/heads/master | 2021-12-07T18:59:35.991784 | 2021-09-16T21:55:53 | 2021-09-16T21:55:53 | 144,416,778 | 0 | 0 | MIT | 2018-08-11T20:39:07 | 2018-08-11T20:39:06 | null | UTF-8 | C++ | false | false | 7,120 | cpp | participant.cpp | /* MIT License
*
* Copyright (c) 2018 Assign Onward
*
* 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.
*/
// Assign Onward
//
// A participant in a share assignment, either giver (negative amount) or
// receiver (positive amount).
//
// Must include a public key (participant ID)
// Must include non-zero amount.
// Negative amounts must:
// - point to a previous share assignment in this chain
// - promise no other assignment of those shares since their recording,
// through the time this assignment expires, or permanently if this assignment is recorded
// - exactly match the positive amount assigned to the public ID in that block-page-record
//
#include "participant.h"
Participant::Participant( DataItemBA di, QObject *p )
: GenericCollection( typeCodeOf( di ), p )
{ // See if there's anything interesting in the data item
setIndex( -1 );
if ( di.size() > 0 )
{ if (( typeCodeOf( di ) != AO_PARTICIPANT ) &&
( typeCodeOf( di ) != AO_PARTICIPANT_CF ))
{ // TODO: log error
return;
}
else
{ DataVarLength temp( di ); // It's our type
DataItemBA items = temp.get(); // typeCode has been stripped off
while ( items.size() > 0 )
{ int sz = typeSize( items );
if ( sz <= 0 )
{ // TODO: log error
return;
}
else
{ DataItemBA item = items.left( sz );
switch ( typeCodeOf( item ) ) // read valid items from the byte array, in any order
{ case AO_AMT:
if ( !amount ) amount = new Shares( item );
else qDebug( "Participant doesn't expect to contain more than one AO_AMT" );
break;
case AO_ECDSA_PUB_KEY2:
case AO_ECDSA_PUB_KEY3:
case AO_RSA3072_PUB_KEY:
case AO_ID_SEQ_NUM:
if ( !key ) insert( key = new PubKey( item ) );
else qDebug( "Participant doesn't expect to contain more than one public key" );
break;
case AO_PAGE_REF:
if ( !page ) insert( page = new PageRef( item ) );
else qDebug( "Participant doesn't expect to contain more than one AO_PAGE_REF" );
break;
case AO_NOTE:
if ( !note ) insert( note = new Note( item ) );
else qDebug( "Participant doesn't expect to contain more than one AO_NOTE" );
break;
case AO_INDEX:
if ( !index ) insert( index = new DataVbc64( item ) );
else qDebug( "Participant doesn't expect to contain more than one AO_INDEX" );
break;
default:
qDebug( "Unrecognized data type %lld", typeCodeOf( item ) );
// TODO: log anomaly - unrecognized data type
break;
}
items = items.mid( sz ); // move on to the next
}
}
}
}
}
/**
* @brief Participant::operator =
* @param di - data item to assign from
*/
void Participant::operator = ( const DataItemBA &di )
{ Participant temp( di );
deleteItemsLater();
amount = temp.amount;
key = temp.key;
page = temp.page;
note = temp.note;
index = temp.index;
DataItemMap tmap = temp.mmap();
foreach ( DataItem *di, tmap )
insert( di );
typeCode = temp.typeCode;
}
/**
* @brief Participant::toDataItem
* @param cf - compact (or chain) form
* @return data item in the requested form
*/
DataItemBA Participant::toDataItem( bool cf )
{ QByteArrayList dil;
if ( cf )
typeCode = AO_PARTICIPANT_CF;
else if ( typeCode == AO_PARTICIPANT_CF )
cf = true;
switch ( typeCode )
{ case AO_PARTICIPANT:
if ( amount ) dil.append( amount->toDataItem(false) );
if ( key ) if ( key->isValid() ) dil.append( key-> toDataItem(false) );
if ( page ) dil.append( page-> toDataItem(false) );
if ( note ) if ( note->size() > 0 ) dil.append( note-> toDataItem(false) );
if ( index ) if ( *index > -1 ) dil.append( index-> toDataItem(false) );
break;
case AO_PARTICIPANT_CF:
if ( amount ) if ( amount != 0 ) dil.append( amount->toDataItem(true) );
if ( key ) if ( key->isValid() ) dil.append( key-> toDataItem(true) );
if ( note ) if ( note->size() > 0 ) dil.append( note-> toDataItem(true) );
if ( index ) if ( *index > -1 ) dil.append( index-> toDataItem(true) );
break;
default:
// TODO: log error
return QByteArray();
}
std::sort( dil.begin(), dil.end() );
QByteArray ba = dil.join();
DataItemBA db;
db.append( codeToBytes( typeCode ) );
db.append( codeToBytes( ba.size() ) );
db.append( ba );
return db;
}
/**
* @brief Participant::setIndex - if it does not exist, create the index data item
* and insert it in the collection. Either way, set the index data item value to v.
* @param v - value to set index to
*/
void Participant::setIndex( qint64 v )
{ if ( !index )
if ( contains( AO_INDEX ) )
{ qDebug( "weird, we've got an AO_INDEX in the collection, but not in the index pointer" );
index = qobject_cast<DataVbc64 *>( value( AO_INDEX ) );
if ( !index )
qDebug( "weirder, AO_INDEX object would not cast to DataVbc64*" );
}
if ( index )
{ index->set( v );
return;
}
index = new DataVbc64( v, AO_INDEX, this );
if ( !index )
qDebug( "problem creating index" );
else
insert( index );
}
void Participant::setKey( PubKey *k )
{ if ( key )
{ key->deleteLater();
qDebug( "odd, overwriting existing key" );
}
insert( key = k );
}
|
d0dc9340de30eadaa8f25f4919da1ec634c266eb | 0d1645e912fc1477eef73245a75af85635a31bd8 | /XOffice/src/XCell/include/XGridDataSvrEx.hpp | a71772a053c792f1d62125e739205de72cb5b28f | [
"MIT"
] | permissive | qianxj/XExplorer | a2115106560f771bc3edc084b7e986332d0e41f4 | 00e326da03ffcaa21115a2345275452607c6bab5 | refs/heads/master | 2021-09-03T13:37:39.395524 | 2018-01-09T12:06:29 | 2018-01-09T12:06:29 | 114,638,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | hpp | XGridDataSvrEx.hpp | #pragma once
#include "xofbase.h"
#include "griddatasvr.hpp"
#include "xofobject.h"
namespace Hxsoft{ namespace XFrame{ namespace XOffice {namespace XCell
{
class XCELL_API XGridDataSvrEx : public XOfficeData
{
public:
XGridDataSvrEx(void);
~XGridDataSvrEx(void);
public:
CAxisSvr* m_pAxisSvr;
class XXmlContentSvr* m_pContentSvr;
public:
bool m_bShared;
};
}}}}
|
cbc5e7190eaa1320edcd4e121fb415cfdc686363 | e5a2eed530086b4b3772886f1daad8ed6d6b5152 | /projects/db/src/pse-db/tmHm.h | 87ffe19d12b9b6eb8a3bc5cb6521f7f877972e13 | [
"Apache-2.0"
] | permissive | junebug12851/pokered-save-editor-2 | f7cf5013652737ef24f0c7a400c6520e4df5f54b | af883fd4c12097d408e1756c7181709cf2b797d8 | refs/heads/master | 2020-06-06T09:17:16.194569 | 2020-03-18T09:45:34 | 2020-03-18T09:45:34 | 192,697,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | h | tmHm.h | /*
* Copyright 2019 June Hanabi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TMHM_H
#define TMHM_H
#include <QString>
#include <pse-common/types.h>
#include "./db_autoport.h"
struct ItemDBEntry;
struct MoveDBEntry;
// All the TM's and HM's in the game
// internally, HM's are specially treated TM's that start at TM 51
class DB_AUTOPORT TmHmsDB
{
public:
static void load();
static void deepLink();
static QVector<QString> store;
static QVector<ItemDBEntry*> toTmHmItem;
static QVector<MoveDBEntry*> toTmHmMove;
};
#endif // TMHM_H
|
ce95ee1f8b4331a72e06de59f0eec9443fd0404a | 6168e2e2c5532f0134ef1a8e814f3f85ed921f0a | /BPD/src/Register.cpp | db8583383cfd74882aa99805d00f9ea835bd92df | [] | no_license | LucasStarlingdePaulaSalles/persistent-data-storage | 1911b378455a90aa34e28d20ef12fc6bd90ad664 | d4e3c828ce0072735494443558403f4f37b8536b | refs/heads/master | 2022-01-11T14:02:42.869007 | 2019-07-09T02:10:18 | 2019-07-09T02:10:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | cpp | Register.cpp | #include <Register.hpp>
Register::Register(propertyMap propsIn){
this->properties = propsIn;
}
void Register::insertProperty(std::pair<std::string, std::string> propIn){
this->properties[propIn.first] = propIn.second;
}
std::string Register::getData(std::string name){
if(this->properties.find(name) == this->properties.end())
return DEFAULT_NULL;
return this->properties[name];
}
|
416ffce03e0b4309dfd2bdc1a2e2583c386de5df | 6a151d774c8230cf2a6a04cd6566c5aa813f9a3a | /UVa/UVa 11498 - Division of Nlogoni.cpp | 27450fd9aba07cf41395629365d1b0898170f4a3 | [] | no_license | RakibulRanak/Solved-ACM-problems | fdc5b39bdbe1bcc06f95c2a77478534362dca257 | 7d28d4da7bb01989f741228c4039a96ab307a8a6 | refs/heads/master | 2021-07-01T09:50:02.039776 | 2020-10-11T20:46:28 | 2020-10-11T20:46:28 | 168,976,930 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 675 | cpp | UVa 11498 - Division of Nlogoni.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
while(cin>>t)
{
if(t==0)
return 0;
int X,Y;
cin>>X>>Y;
int a=0,b=0;
int x,y;
for(int i=0;i<t;i++)
{
cin>>x>>y;
a=x;
b=y;
a-=X;
b-=Y;
if(a==0 || b==0)
{
cout<<"divisa"<<endl;
}
else if(a>0 && b>0)
cout<<"NE"<<endl;
else if(a>0 && b<0)
cout<<"SE"<<endl;
else if(a<0 && b>0)
cout<<"NO"<<endl;
else if(a<0 && b<0)
cout<<"SO"<<endl;
}
}
return 0;
}
|
8500efa83c6d11f809a14c2d3f2fee73ccc2b744 | dc5fbdfa0e4986ef61c05c60d9f2dfa4c3f7453a | /my_tool/my_tool/classes/tests/IManager.h | 9e000b1a0f5e08243269d35fcb88af62e330118e | [] | no_license | zhengfasheng/my_tool | 78a110bfa3828849869da2cf9020a6e9fed83cea | f9bd882de1742ff238da4c2bfff727fc9f2c75c7 | refs/heads/master | 2021-01-01T17:58:46.798307 | 2018-12-27T01:38:22 | 2018-12-27T01:38:22 | 98,209,510 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,531 | h | IManager.h | /******************************************************************************
* Copyright (c) 2017 . All rights reserved.
*
*
*
* 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.
*
* Author:Zheng Fasheng
*
* Email:zheng_fasheng@qq.com
*
* Date:2017/7/25 21:50
*
* Summary:所有测试管理器接口类
*
******************************************************************************/
#pragma once
#include "common.h"
#define IMPLEMENT_MANAGER( _TYPE_ )\
IMPLEMENT_SINGLETON(_TYPE_)\
IMPLEMENT_GET_NAME(_TYPE_)
#define RIGISTER_MANAGER( _TYPE_ )\
registerManger(_TYPE_::getInstance())
class ITest;
class IManager
{
public:
IManager();
virtual ~IManager();
virtual void run();
virtual std::string getName() = 0;
virtual bool isUsing() { return true; }
virtual void destory();
protected:
virtual void registerTest(ITest* pTest) final;
virtual void registerTest() = 0;
virtual void excuteTest() final;
private:
std::vector<ITest*> m_tests;
}; |
bf016efef448d6d1375be1c45232cfd3338606a1 | 67b37da2dfc45b56413cd676d4b590ac92625b40 | /servlib/bundling/BundleListBase.h | 602417223fa8c2d74c8de15c6427d19b3916a41e | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fvideen/DTNME | b9403e5719622baaba62b58651c8817c80ae751f | c97b598b09a8c8e97c2e4136879d9f0e157c8df7 | refs/heads/master | 2023-06-02T14:44:48.496549 | 2021-05-27T19:05:19 | 2021-05-27T19:05:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,462 | h | BundleListBase.h | /*
* Copyright 2015 United States Government as represented by NASA
* Marshall Space Flight Center. All Rights Reserved.
*
* Released under the NASA Open Source Software Agreement version 1.3;
* You may obtain a copy of the Agreement at:
*
* http://ti.arc.nasa.gov/opensource/nosa/
*
* The subject software is provided "AS IS" WITHOUT ANY WARRANTY of any kind,
* either expressed, implied or statutory and this agreement does not,
* in any manner, constitute an endorsement by government agency of any
* results, designs or products resulting from use of the subject software.
* See the Agreement for the specific language governing permissions and
* limitations.
*/
#ifndef _BUNDLE_LIST_BASE_H_
#define _BUNDLE_LIST_BASE_H_
#include <oasys/compat/inttypes.h>
#include <oasys/thread/Notifier.h>
#include <oasys/serialize/Serialize.h>
#include "BundleRef.h"
namespace oasys {
class SpinLock;
}
namespace dtn {
class Bundle;
struct BundleTimestamp;
/**
* This is the base class for BundleLists which can be of various
* flavors such as a std::list, std::map, etc. This class implements
* the common elements of the lists.
*
* The internal data structure of Bundle pointers will vary in the
* derived classes. The list is derived from Notifier, and the various
* push() calls in the derived classes must call notify() if there is
* a thread blocked on an empty list waiting for notification.
*
* List methods also maintain mappings (i.e. "back pointers") in each
* Bundle instance to the set of lists that contain the bundle.
*
* Lists follow the reference counting rules for bundles. In
* particular, the push*() methods increment the reference count, and
* erase() decrements it. In particular, the pop() variants (as well
* as the other accessors) return instances of the BundleRef classes
* that forces the caller to use the BundleRef classes as well in
* order to properly maintain the reference counts.
*
*/
class BundleListBase : public oasys::Logger, public oasys::SerializableObject {
private:
/**
* Type for the list itself (private since it's irrelevant to the
* outside).
* Derived clases should declare a private list type. Examples:
* //typedef std::list<const BundleRef*> List;
* //typedef std::map<u_int32_t, const BundleRef*> List;
*/
public:
/**
* Type for an iterator, which just wraps an stl iterator. We
* don't ever use the stl const_iterator type since list mutations
* are protected via this class' methods.
*/
//typedef List::iterator iterator;
/**
* Constructor
*/
BundleListBase(const std::string& name, oasys::SpinLock* lock = NULL,
const std::string& ltype="BundleListBase", const std::string& subpath="/listbase");
/**
* Destructor -- clears the list.
*/
virtual ~BundleListBase();
/*
* Serializes the list of (internal) bundleIDs; on deserialization,
* tries to hunt down those bundles in the all_bundles list and add
* them to the list.
*/
virtual void serialize(oasys::SerializeAction *a) = 0;
/**
* Clear out the list.
*/
virtual void clear() = 0;
/**
* Return the size of the list.
*/
virtual size_t size() const = 0;
/**
* Return whether or not the list is empty.
*/
virtual bool empty() const = 0;
/**
* Return the internal lock on this list.
*/
oasys::SpinLock* lock() const { return lock_; }
/**
* Return the identifier name of this list.
*/
const std::string& name() const { return name_; }
/**
* Set the name (useful for classes that are unserialized).
* Also sets the logpath
*/
virtual void set_name(const std::string& name);
/**
* As above, but sets ONLY the name, not the logpath.
*/
void set_name_only(const std::string& name);
private:
// Derived classes should declare the List structure here
//List list_; ///< underlying list data structure
protected:
std::string name_; ///< name of the list
std::string ltype_; ///< list type (path for the logger)
oasys::SpinLock* lock_; ///< lock for notifier
bool own_lock_; ///< bit to define lock ownership
oasys::Notifier* notifier_; ///< notifier for blocking list
};
} // namespace dtn
#endif /* _BUNDLE_LIST_BASE_H_ */
|
912804f745ef2689994cb0ffce4db201baa705a9 | 6513620f3c8ba38ca8bb16301ece76b6b213faa3 | /external/sources/objloader-0.2.5/Sources/MtlParser.hpp | d26d4112bd373388848027b3bf289d4502f83dde | [] | no_license | CDovgal/spark-opengles | ff0be35e636e4bbda0f76f8cc98d0257ffeb9280 | 1977ec593f4f55c238ee490d2e8ff9af7fc9dc02 | refs/heads/master | 2016-09-05T18:24:38.314991 | 2015-01-04T12:34:58 | 2015-01-04T12:34:58 | 32,260,747 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 404 | hpp | MtlParser.hpp | /*
* Parser.hpp
* ToolSDL
*
* Created by Seb on 18/01/06.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
#ifndef __MTLPARSER_HPP__
#define __MTLPARSER_HPP__
#include "Material.hpp"
//////////////////
//
//////////////////
class CMtlParser {
public:
static void parse(MaterialMap_t& materialMap, const string& strFilePath);
};
#endif // __MTLPARSER_HPP__ |
41533d54b10b2bcb5dd8459206f7f703d379e1ac | 3e1e10fc80793bdedcda0d41c0d347ca2c9db595 | /Volume11/1107/c++.cpp | de5440b32819a8c352fa3f2b5469ca31f7144ad9 | [] | no_license | mkut/aoj | 9a11999c113bc9fda6157ca174ebfb14e3af14ce | 1a088f15621c72c9f9d0c9ad0030cb8547b3e66e | refs/heads/master | 2016-09-05T11:17:48.734650 | 2013-07-13T13:18:06 | 2013-07-13T13:18:06 | 2,236,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | cpp | c++.cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
#define EPS 1e-8
double norm(double x, double y)
{
return sqrt(x*x+y*y);
}
double get_angle(double x1, double y1, double x2, double y2)
{
return (x1 * x2 + y1 * y2) / norm(x1, y1) / norm(x2, y2);
}
int main()
{
int n;
while(cin >> n, n)
{
vector<double> x(n), y(n);
for(int i = 0; i < n; i++)
cin >> x[i] >> y[i];
double X = 0, Y = 0;
double dx = 0, dy = 1;
double ans = 0;
while(x.size())
{
int max_i = 0;
double max_angle = -1, max_dist = 0;
for(int i = 0; i < x.size(); i++)
{
double angle = get_angle(dx, dy, x[i]-X, y[i]-Y);
double dist = norm(x[i]-X, y[i]-Y);
if(angle - max_angle > EPS || fabs(angle - max_angle) < EPS && max_dist > dist)
max_angle = angle, max_i = i, max_dist = dist;
}
//cout << X << "," << Y << endl;
dx = x[max_i]-X; dy = y[max_i]-Y;
X = x[max_i]; Y = y[max_i];
ans += max_dist;
x.erase(x.begin() + max_i); y.erase(y.begin() + max_i);
}
printf("%.1f\n", ans);
}
return 0;
}
|
fd2b994184bbf2bac0e809db6958ae7aa525c3f5 | 7bb1cd3b6ab160eef592e7d7d14120d299b61ee4 | /codeforces/B/222B.cpp | 22a159c3a2bc2301ddcdc0017431c89c00e3acc5 | [] | no_license | naveenchopra9/cp | d986a3e8c650903b8bec8c4b0665c3ef664e251a | 0f271204b2675a366f0b92081ec67a97efc5883a | refs/heads/master | 2020-05-16T12:38:25.063272 | 2019-04-23T16:12:46 | 2019-04-23T16:12:46 | 183,051,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 910 | cpp | 222B.cpp | #include <cstdio>
#include <algorithm>
using namespace std;
int column[1001],row[1001];
int g[1001][1001];
int main(){
int n, m , k;
scanf("%d%d%d", &n, &m, &k);
for(int i =0 ; i< n ; i++){
row[i]=i;
}
for(int i =0 ; i< m ; i++){
column[i]=i;
}
for(int i =0 ; i< n ; i++){
for(int j =0 ; j< m ; j++){
scanf("%d",&g[i][j]);
}
}
for(int i =0 ; i< k ; i++){
int x,y;
char si[2];
scanf("%s%d%d", si, &x, &y);
if(si[0]=='c'){
swap(column[x-1],column[y-1]);
}
else if(si[0]=='r'){
swap(row[x-1],row[y-1]);
}
else if(si[0]=='g'){
printf("%d\n",g[row[x-1]][column[y-1]]);
// cout<<g[row[x-1]][column[y-1]]<<endl;
}
}
// for(int i =0 ; i< m ; i++){
// cout<<column[i];
// }
return 0;
}
|
4f94c8cdbbe425afabc9ce7cfef2edf9268b2aed | f278f1e6ad43c9326cd03b54e3362c3aac85d9bf | /fouerierSeries/fourierseries.h | ea5e894f6dab3ce45470706b731f9c3cbe3799f1 | [] | no_license | klokaj/FourierSeries | e56fc7fb1550eaba8496dc451c713557f57c1ebe | db6a555ea6da31cbda79c5ecdc5e5a0cbda841ed | refs/heads/master | 2023-05-05T16:12:13.389815 | 2021-05-31T13:37:22 | 2021-05-31T13:37:22 | 372,509,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | h | fourierseries.h | #ifndef FOURIERSERIES_H
#define FOURIERSERIES_H
#include <cmath>
#include <stddef.h>
#include <string>
#include "harmonic.h"
#include <stddef.h>
#include <vector>
enum class FourierSeriesType{
pulse,
triangle,
sawtooth,
sine,
};
using namespace std;
class FourierSeries{
protected:
double _freq;
vector<harmonic> harmonics{};
FourierSeriesType _FSType;
public:
~FourierSeries(){}
FourierSeries() : FourierSeries(0) {}
FourierSeries(double freq): _freq(freq), harmonics{} {}
void setFrequency(double freq);
double getFrequency() const;
void calculateCoeff(FourierSeriesType FSType, size_t maxHarmonic, double amp);
void clear();
void pushBack(size_t nr, double a, double b);
void print();
vector<harmonic>& getHarmonics();
private:
void calculateCoeffPulse(size_t maxHarmonic, double amp);
void calculateCoeffTriangle(size_t maxHarmonic, double amp);
void calculateCoeffSawtooth(size_t maxHarmonic, double amp);
void calculateCoeffSine(size_t maxHarmonic, double amp);
//virtual void saveToFile(ofstream& ) = 0;
};
#endif
|
53d6498200563e0bed4f1e4cdc0ed8698e6f9fc4 | 8817aaa66bcba8563a302830a312e1e5108c90df | /from_bill/ZEUS5_IP/dvrsvr/main.cpp | 8ba392431de7dd904fcadca8e4457c890eaf5b26 | [] | no_license | dennis-tmeinc/dvr | 908428496c16343afcc969bea2f808e9389febe8 | 7064cfc66445df45d0e747e7304e301a25c214f8 | refs/heads/master | 2021-01-12T17:19:44.988144 | 2018-03-27T22:19:53 | 2018-03-27T22:19:53 | 69,481,073 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 21,124 | cpp | main.cpp | /* --- Changes ---
* 09/25/2009 by Harrison
* 1. Make this daemon
*
*/
#include "dvr.h"
#define DEAMON
char dvrconfigfile[] = "/etc/dvr/dvr.conf";
static char deftmplogfile[] = "/tmp/dvrlog.txt";
static char deflogfile[] = "dvrlog.txt";
static string tmplogfile ;
static string logfile ;
static int logfilesize ; // maximum logfile size
static string lastrecdirbase;
char g_hostname[128] ;
pthread_mutex_t mutex_init=PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP ;
static pthread_mutex_t dvr_mutex;
int system_shutdown;
int app_state; // APPQUIT, APPUP, APPDOWN, APPRESTART
int g_lowmemory ;
void writeDebug(char *fmt, ...)
{
va_list vl;
char str[256];
va_start(vl, fmt);
vsprintf(str, fmt, vl);
va_end(vl);
FILE *fp = fopen("/var/dvr/debug.txt", "a");
if (fp != NULL) {
fprintf(fp, "%s\n", str);
fclose(fp);
}
}
void dvr_lock()
{
pthread_mutex_lock(&dvr_mutex);
}
void dvr_unlock()
{
pthread_mutex_unlock(&dvr_mutex);
}
// lock with lock variable
void dvr_lock( void * lockvar, int delayus )
{
dvr_lock();
while (*(int *)lockvar) {
dvr_unlock();
usleep( delayus );
dvr_lock();
}
(*(int *)lockvar)++ ;
dvr_unlock();
}
void dvr_unlock( void * lockvar )
{
dvr_lock();
(*(int *)lockvar)-- ;
dvr_unlock();
}
// get a random number
unsigned dvr_random()
{
FILE * fd ;
unsigned ran ;
fd = fopen("/dev/urandom", "r");
if( fd ) {
fread( &ran, 1, sizeof(ran), fd );
fclose( fd );
}
return ran ;
}
// clean log file
#if 0
void dvr_cleanlog(FILE * flog)
{
int i ;
array <string> alog ;
string line ;
char lbuf[1024];
int pos = ftell(flog);
printf("current pos:%d\n",pos);
if( pos>logfilesize ) {
pos = (pos/4) ; // cut 1/4 file
fseek( flog, pos, SEEK_SET );
//printf("after seek:%d %d\n",pos,ftell(flog));
fgets(lbuf, 1024, flog );
while (fgets(lbuf, 1024, flog)) {
line=lbuf;
if( line.length()>2 ) {
alog.add( line );
}
}
// printf("size:%d\n",alog.size());
ftruncate( fileno(flog), 0);
fseek( flog, 0, SEEK_SET ) ;
for( i=0; i<alog.size(); i++ ) {
fputs(alog[i].getstring(), flog);
}
// printf("final length:%d\n",ftell(flog));
}
}
#endif
// clean log file
void dvr_cleanlog(char* logfilename)
{
int i,pos;
FILE* flog;
array <string> alog ;
string line ;
char lbuf[1024];
flog=fopen(logfilename,"r+");
if(flog==NULL)
return;
fseek(flog,0,SEEK_END);
pos = ftell(flog);
// printf("current pos:%d\n",pos);
if( pos>logfilesize ) {
pos = (pos/5) ; // cut 1/5 file
fseek( flog, pos, SEEK_SET );
//printf("after seek:%d %d\n",pos,ftell(flog));
fgets(lbuf, 1024, flog );
while (fgets(lbuf, 1024, flog)) {
line=lbuf;
if( line.length()>2 ) {
alog.add( line );
}
}
// printf("size:%d\n",alog.size());
if(alog.size()>10){
ftruncate( fileno(flog), 0);
fseek( flog, 0, SEEK_SET ) ;
for( i=0; i<alog.size(); i++ ) {
fputs(alog[i].getstring(), flog);
}
}
// printf("final length:%d\n",ftell(flog));
}
fflush(flog);
fclose(flog);
}
// write log to log file.
// return
// 1: log to recording hd
// 0: log to temperary file
int dvr_log(char *fmt, ...)
{
int res = 0 ;
static char logfilename[512] ;
char lbuf[512];
FILE *flog=NULL;
FILE *ftmplog=NULL;
int rectemp=0 ;
time_t ti;
int l;
va_list ap ;
tmplogfile="/var/dvr/dvrlog";
if (rec_basedir.length() > 0) {
sprintf(logfilename, "%s/%s", rec_basedir.getstring(), logfile.getstring());
if(strcmp(lastrecdirbase.getstring(),rec_basedir.getstring())!=0){
if(lastrecdirbase.length()>3)
unlink("/var/dvr/dvrlogfile");
lastrecdirbase= rec_basedir.getstring();
symlink(logfilename, "/var/dvr/dvrlogfile");
dvr_cleanlog(logfilename);
}
}
flog = fopen(logfilename, "a");
if (flog) {
ftmplog = fopen("/var/dvr/dvrlog1", "r"); // copy temperary log to disk
if (ftmplog) {
fputs("\n", flog);
while (fgets(lbuf, 512, ftmplog)) {
fputs(lbuf, flog);
}
fclose(ftmplog);
unlink("/var/dvr/dvrlog1");
}
ftmplog = fopen(tmplogfile.getstring(), "r"); // copy temperary log to disk
if (ftmplog) {
fputs("\n", flog);
while (fgets(lbuf, 512, ftmplog)) {
fputs(lbuf, flog);
}
fputs("\n", flog);
fclose(ftmplog);
unlink(tmplogfile.getstring());
}
res=1 ;
} else {
flog = fopen(tmplogfile.getstring(), "a");
rectemp=1 ;
}
ti = time(NULL);
ctime_r(&ti, lbuf);
l = strlen(lbuf);
if (lbuf[l - 1] == '\n')
lbuf[l - 1] = '\0';
va_start( ap, fmt );
printf("DVR:%s:", lbuf);
vprintf(fmt, ap );
printf("\n");
if (flog) {
fprintf(flog, "%s:", lbuf);
vfprintf(flog, fmt, ap );
if( rectemp ) {
fprintf(flog, " *\n");
}
else {
fprintf(flog, "\n");
}
if( fclose(flog)!=0 ) {
res = 0 ;
}
//don't abuse this,system can hang:sync();
}
va_end( ap );
return res ;
}
int dvr_getsystemsetup(struct system_stru * psys)
{
int i ;
int x ;
string tmpstr;
char buf[40] ;
string v ;
config dvrconfig(dvrconfigfile);
strcpy( psys->IOMod, "DIOTME");
strncpy(psys->ServerName, g_hostname, 80);
// psys->cameranum = dvrconfig.getvalueint("system", "camera_number") ;
// psys->alarmnum = dvrconfig.getvalueint("system", "alarm_number") ;
// psys->sensornum = dvrconfig.getvalueint("system", "sensor_number") ;
psys->cameranum = cap_channels;
psys->alarmnum = num_alarms ;
psys->sensornum = num_sensors ;
psys->breakMode = 0 ;
// maxfilelength ;
v = dvrconfig.getvalue("system", "maxfilelength");
if (sscanf(v.getstring(), "%d", &x)>0) {
i = v.length();
if (v[i - 1] == 'H' || v[i - 1] == 'h')
x *= 3600;
else if (v[i - 1] == 'M' || v[i - 1] == 'm')
x *= 60;
} else {
x = DEFMAXFILETIME;
}
if (x < 60)
x = 60;
if (x > (24 * 3600))
x = (24 * 3600);
psys->breakTime = x ;
// maxfilesize
v = dvrconfig.getvalue("system", "maxfilesize");
if (sscanf(v.getstring(), "%d", &x)>0) {
i = v.length();
if (v[i - 1] == 'M' || v[i - 1] == 'm')
x *= 1024*1024;
else if (v[i - 1] == 'K' || v[i - 1] == 'k')
x *= 1024;
} else {
x = DEFMAXFILESIZE;
}
if (x < 1024*1024)
x = 1024*1024;
if (x > 1024*1024*1024)
x = 1024*1024*1024;
psys->breakSize = x;
// mindiskspace
v = dvrconfig.getvalue("system", "mindiskspace");
if (sscanf(v.getstring(), "%d", &x)) {
i = v.length();
if (v[i - 1] == 'G' || v[i - 1] == 'g') {
x *= 1024*1024*1024;
} else if (v[i - 1] == 'K' || v[i - 1] == 'k') {
x *= 1024;
} else if (v[i - 1] == 'B' || v[i - 1] == 'b') {
x = x;
} else { // M
x *= 1024*1024;
}
if (x < 20*1024*1024)
x = 20*1024*1024;
} else {
x = 100*1024*1024;
}
psys->minDiskSpace = x;
psys->shutdowndelay = dvrconfig.getvalueint("system", "shutdowndelay") ;
psys->autodisk[0]=0 ;
if( psys->sensornum>16 )
psys->sensornum=16 ;
for( i=0; i<psys->sensornum; i++ ) {
sprintf(buf, "sensor%d", i+1);
tmpstr=dvrconfig.getvalue(buf, "name");
if( tmpstr.length()==0 ) {
strcpy( psys->sensorname[i], buf );
}
else {
strcpy( psys->sensorname[i], tmpstr.getstring() );
}
psys->sensorinverted[i] = dvrconfig.getvalueint(buf, "inverted");
}
// set eventmarker
psys->eventmarker=dvrconfig.getvalueint("eventmarker", "eventmarker") ;
psys->eventmarker_enable=(psys->eventmarker>0) ;
if( psys->eventmarker_enable ) {
psys->eventmarker=1<<(psys->eventmarker-1) ;
}
else {
psys->eventmarker=1 ;
}
psys->eventmarker_prelock=dvrconfig.getvalueint("eventmarker", "prelock" );
psys->eventmarker_postlock=dvrconfig.getvalueint("eventmarker", "postlock" );
psys->ptz_en=dvrconfig.getvalueint("ptz", "enable");
tmpstr=dvrconfig.getvalue("ptz", "device");
if( tmpstr.length()>9 ) {
i=0 ;
sscanf(tmpstr.getstring()+9, "%d", &i );
psys->ptz_port=(char)i ;
}
else {
psys->ptz_port=0 ;
}
psys->ptz_baudrate=dvrconfig.getvalueint("ptz", "baudrate" );
tmpstr=dvrconfig.getvalue("ptz", "protocol");
if( *tmpstr.getstring()=='P' )
psys->ptz_protocol=1 ;
else
psys->ptz_protocol=0 ;
psys->videoencrpt_en=dvrconfig.getvalueint("system", "fileencrypt");
strcpy( psys->videopassword, "********" );
psys->rebootonnoharddrive=0 ;
return 1 ;
}
int dvr_setsystemsetup(struct system_stru * psys)
{
int i ;
string tmpstr;
char buf[40] ;
char system[]="system" ;
config dvrconfig(dvrconfigfile);
if( strcmp( g_hostname, psys->ServerName )!=0 ) { // set hostname
FILE * phostname = NULL;
phostname=fopen("/etc/dvr/hostname", "w");
if( phostname!=NULL ) {
fprintf(phostname, "%s", psys->ServerName);
fclose(phostname);
}
sethostname(psys->ServerName, strlen(psys->ServerName)+1);
dvrconfig.setvalue(system, "hostname", psys->ServerName);
}
dvrconfig.setvalueint(system, "camera_number", psys->cameranum) ;
dvrconfig.setvalueint(system, "alarm_number", psys->alarmnum) ;
dvrconfig.setvalueint(system, "sensor_number", psys->sensornum) ;
dvrconfig.setvalueint(system, "maxfilelength", psys->breakTime) ;
dvrconfig.setvalueint(system, "maxfilesize", psys->breakSize) ;
dvrconfig.setvalueint(system, "mindiskspace", psys->minDiskSpace/(1024*1024)) ;
dvrconfig.setvalueint(system, "shutdowndelay", psys->shutdowndelay) ;
if( psys->sensornum>16 )
psys->sensornum=16 ;
for( i=0; i<psys->sensornum; i++ ) {
sprintf(buf, "sensor%d", i+1);
dvrconfig.setvalue(buf, "name", psys->sensorname[i]);
dvrconfig.setvalueint(buf, "inverted", psys->sensorinverted[i]);
}
// event marker
dvrconfig.setvalueint("eventmarker", "prelock", psys->eventmarker_prelock );
dvrconfig.setvalueint("eventmarker", "postlock", psys->eventmarker_postlock );
dvrconfig.setvalueint("eventmarker", "eventmarker",0);
if( psys->eventmarker_enable ) {
for( i=0; i< psys->sensornum; i++) {
if( psys->eventmarker & (1<<i) ) {
dvrconfig.setvalueint("eventmarker", "eventmarker", i+1 );
break;
}
}
}
dvrconfig.setvalueint("ptz", "enable", (int)psys->ptz_en );
sprintf(buf,"/dev/ttyS%d", (int)psys->ptz_port);
dvrconfig.setvalue("ptz", "device", buf);
dvrconfig.setvalueint("ptz", "baudrate", psys->ptz_baudrate );
if( psys->ptz_protocol==0 ) {
dvrconfig.setvalue("ptz", "protocol", "D");
}
else {
dvrconfig.setvalue("ptz", "protocol", "P");
}
if( psys->videoencrpt_en ) {
if( strcmp(psys->videopassword, "********")!=0 ) { // if user enable encryption by accident, do change any thing
// user set a password
dvrconfig.setvalueint(system, "fileencrypt", 1) ;
unsigned char filekey256[260] ;
char filekeyc64[512] ; // size should > 260*4/3
key_256( psys->videopassword, filekey256 ); // hash password
bin2c64(filekey256, 256, filekeyc64); // convert to c64
dvrconfig.setvalue("system", "filepassword", filekeyc64); // save password to config file
}
}
else {
dvrconfig.setvalueint(system, "fileencrypt", 0) ;
dvrconfig.removekey(system,"filepassword"); // remove password
}
psys->videoencrpt_en=dvrconfig.getvalueint("system", "fileencrypt");
strcpy( psys->videopassword, "********" );
dvrconfig.save();
app_state = APPRESTART ; // restart application
return 1 ;
}
int app_restart;
unsigned long app_signalmap=0;
int app_signal_ex=0;
void sig_handler(int signum)
{
if( signum<32 ) {
app_signalmap |= ((unsigned long)1)<<signum;
}
else {
app_signal_ex=signum ;
}
}
void sig_check()
{
unsigned long sigmap = app_signalmap ;
app_signalmap=0 ;
if( sigmap == 0 ) {
return ;
}
if( sigmap & (1<<SIGTERM) )
{
dvr_log("Signal <SIGTERM> captured.");
app_state = APPQUIT ;
}
else if( sigmap & (1<<SIGQUIT) )
{
dvr_log("Signal <SIGQUIT> captured.");
app_state = APPQUIT ;
}
else if( sigmap & (1<<SIGINT) )
{
dvr_log("Signal <SIGINT> captured.");
app_state = APPQUIT ;
}
else if( sigmap & (1<<SIGUSR2) )
{
if(!isstandbymode()){
app_state = APPRESTART ;
}
}
else if( sigmap & (1<<SIGUSR1) )
{
app_state = APPDOWN ;
}
if( sigmap & (1<<SIGPIPE) )
{
dvr_log("Signal <SIGPIPE> captured.");
}
if( app_signal_ex ) {
dvr_log("Signal %d captured.", app_signal_ex );
app_signal_ex=0 ;
}
}
static string pidfile ;
// one time application initialization
void app_init(int partial)
{
static int app_start=0;
string hostname ;
string tz ;
string tzi ;
char * p ; // general pointer
FILE * fid = NULL ;
char mbuf[256];
config dvrconfig(dvrconfigfile);
if (!partial) {
pid_t mypid ;
mypid=getpid();
pidfile=dvrconfig.getvalue("system", "pidfile");
if( pidfile.length()<=0 ) {
pidfile="/var/dvr/dvrsvr.pid" ;
}
fid=fopen(pidfile.getstring(), "w");
if( fid ) {
fprintf(fid, "%d", (int)mypid);
fclose(fid);
}
}
// setup log file names
tmplogfile = dvrconfig.getvalue("system", "temp_logfile");
if (tmplogfile.length() == 0)
tmplogfile = deftmplogfile;
logfile = dvrconfig.getvalue("system", "logfile");
if (logfile.length() == 0)
logfile = deflogfile;
logfilesize = dvrconfig.getvalueint("system", "logfilesize");
if( logfilesize< (300*1024 )){
logfilesize = 300*1024 ;
} else {
if(logfilesize>(10*1024*1024) ) {
logfilesize=10*1024*1024;
}
}
// set timezone the first time
tz=dvrconfig.getvalue( "system", "timezone" );
if( tz.length()>0 ) {
tzi=dvrconfig.getvalue( "timezones", tz.getstring() );
if( tzi.length()>0 ) {
p=strchr(tzi.getstring(), ' ' ) ;
if( p ) {
*p=0;
}
p=strchr(tzi.getstring(), '\t' ) ;
if( p ) {
*p=0;
}
setenv("TZ", tzi.getstring(), 1);
}
else {
setenv("TZ", tz.getstring(), 1);
}
}
tzset();
#if 1
fid=fopen("/mnt/nand/dvr/firmwareid","r");
if(fid){
int num;
num=fread(mbuf,1,256,fid);
fclose(fid);
mbuf[num-1]='\0';
dvr_log("DVR Firmware:%s",mbuf);
}
#endif
hostname=dvrconfig.getvalue("system", "hostname" );
if( hostname.length()>0 ){
// setup hostname
strncpy( g_hostname, hostname.getstring(), 127 );
sethostname( g_hostname, strlen(g_hostname)+1);
gethostname( g_hostname, 128 );
if (!partial)
dvr_log("Setup hostname: %s", g_hostname);
}
g_lowmemory=dvrconfig.getvalueint("system", "lowmemory" );
if( g_lowmemory<10000 ) {
g_lowmemory=10000 ;
}
if (!partial) {
// setup signal handler
signal(SIGQUIT, sig_handler);
signal(SIGINT, sig_handler);
signal(SIGTERM, sig_handler);
signal(SIGUSR1, sig_handler);
signal(SIGUSR2, sig_handler);
signal(SIGPOLL, sig_handler);
// ignor these signal
signal(SIGPIPE, SIG_IGN); // ignor this
if( app_start==0 ) {
dvr_log("Start DVR.");
app_start=1 ;
}
}
}
void app_exit(int silent)
{
//sync();
unlink( pidfile.getstring() );
if (!silent)
dvr_log("Quit DVR.\n");
}
void do_init()
{
// initial mutex
memcpy( &dvr_mutex, &mutex_init, sizeof(mutex_init));
dvr_log("Start initializing.");
app_init(0);
time_init();
event_init();
file_init();
play_init();
disk_init(0);
cap_init();
rec_init();
// ptz_init();
screen_init();
msg_init();
net_init();
cap_start(); // start capture
}
void do_uninit()
{
dvr_log("Start un-initializing.");
cap_stop(); // stop capture
net_uninit();
msg_uninit();
screen_uninit();
// ptz_uninit();
rec_uninit();
cap_uninit();
disk_uninit(0);
play_uninit();
file_uninit();
event_uninit();
time_uninit();
printf("uninitialized done\n");
//sleep(30);
pthread_mutex_destroy(&dvr_mutex);
}
// dvr exit code
#define EXIT_NORMAL (0)
#define EXIT_NOACT (100)
#define EXIT_RESTART (101)
#define EXIT_REBOOT (102)
#define EXIT_POWEROFF (103)
void closeall(int fd)
{
int fdlimit = sysconf(_SC_OPEN_MAX);
while (fd < fdlimit)
close(fd++);
}
int daemon(int nochdir, int noclose)
{
switch (fork()) {
case 0: break;
case -1: return -1;
default: _exit(0);
}
if (setsid() < 0)
return -1;
switch (fork()) {
case 0: break;
case -1: return -1;
default: _exit(0);
}
if (!nochdir)
chdir("/");
if (!noclose) {
closeall(0);
open("/dev/null", O_RDWR);
dup(0); dup(0);
}
return 0;
}
//int foo=1;
int main(int argc, char **argv)
{
unsigned int serial=0;
int app_ostate; // application status. ( APPUP, APPDOWN )
struct timeval time1, time2 ;
int t_diff ;
//while(foo)
//sleep(1);
if ((argc >= 2) && !strcmp(argv[1], "-f")) {
// force foreground
} else if ((argc >= 2) && !strcmp(argv[1], "-d")) {
app_init(1);
dio_init();
int ret = do_disk_check();
dio_uninit();
app_exit(1);
exit(ret);
} else {
#ifdef DEAMON
if (daemon(1, 0) < 0) {
perror("daemon");
exit(1);
}
#endif
}
mem_init();
app_ostate = APPDOWN ;
app_state = APPUP ;
while( app_state!=APPQUIT ) {
if( app_state == APPUP ) { // application up
serial++ ;
if( app_ostate != APPUP ) {
do_init();
app_ostate = APPUP ;
gettimeofday(&time1, NULL);
}
if( (serial%400)==119 ){ // every 3 second
// check memory
if( mem_available () < g_lowmemory && rec_basedir.length()>1 ) {
dvr_log("Memory low. reload DVR.");
app_state = APPRESTART ;
}
}
if( (serial%80)==3 ){ // every 1 second
gettimeofday(&time2, NULL);
t_diff = (int)(int)(time2.tv_sec - time1.tv_sec) ;
if( t_diff<-100 || t_diff>100 )
{
dvr_log("System time changing detected!");
rec_break ();
}
time1.tv_sec = time2.tv_sec ;
disk_check();
}
if( serial%10 == 1 ) {
event_check();
}
screen_io(12500); // do screen io
// usleep( 12500 );
}
else if (app_state == APPDOWN ) { // application down
if( app_ostate == APPUP ) {
app_ostate = APPDOWN ;
do_uninit();
}
usleep( 12500 );
}
else if (app_state == APPRESTART ) {
if( app_ostate == APPUP ) {
app_ostate = APPDOWN ;
do_uninit();
}
app_state = APPUP ;
usleep( 100 );
}
sig_check();
if(dio_poweroff()){
if(fileclosed()){
dio_setfileclose(1);
} else {
dio_setfileclose(0);
}
}
}
if( app_ostate==APPUP ) {
app_ostate=APPDOWN ;
do_uninit();
}
FiniSystem();
app_exit(0);
mem_uninit ();
if (system_shutdown) { // requested system shutdown
// dvr_log("Reboot system.");
return EXIT_REBOOT ;
}
else {
return EXIT_NOACT ;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.