blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
99d547af89e8c63953c3d1cbf545f8ab6a8480ce | C++ | driador/dawnoftime | /src/mining.cpp | UTF-8 | 7,999 | 2.703125 | 3 | [] | no_license | /**************************************************************************/
// mining.cpp - mine command, Kal
/***************************************************************************
* The Dawn of Time v1.69s.beta6 (c)1997-2010 Kalahn *
* >> A number of people have contributed to the Dawn codebase, with the *
* majority of code written by Kalahn - www.dawnoftime.org *
* >> To use this source code, you must fully comply with the dawn license *
* in licenses.txt... In particular, you may not remove this copyright *
* notice. *
**************************************************************************/
#include "include.h"
/**************************************************************************/
#define MINE_IRON (0)
#define MINE_SILVER (1)
#define MINE_GOLD (2)
#define MAX_MINE_RESULTS (5)
char *mine_name[3]=
{
"ironore ore",
"silverore ore",
"goldore ore nugget"
};
struct mine_results_type
{
char *short_descr;
char *name;
int weight;
};
struct mine_results_type mine_results[3][MAX_MINE_RESULTS]=
{
{ // iron
{"a miniscule piece of iron ore", "miniscule piece iron ore" , 130},
{"a small lump of iron ore", "small lump iron ore" , 210},
{"an average-sized lump of iron ore", "average-sized lump iron ore" , 290},
{"a large lump of iron ore", "large lump iron ore" , 370},
{"a huge lump of iron ore", "huge lump iron ore" , 490}
},
{ // silver
{"a miniscule piece of silver ore", "miniscule piece silver ore" , 120},
{"a small lump of silver ore", "small lump silver ore" , 180},
{"an average-sized lump of silver ore","average-sized lump silver ore" , 245},
{"a large lump of silver ore", "large lump silver ore" , 300},
{"a huge lump of silver ore", "huge lump silver ore" , 400}
},
{ // gold
{"a miniscule gold nugget", "ore miniscule gold nugget" , 115},
{"a small gold nugget", "ore small gold nugget" , 215},
{"an average-sized gold nugget","ore average-sized gold nugget" , 275},
{"a large gold nugget", "ore large gold nugget" , 390},
{"a huge gold nugget", "ore huge gold nugget" , 540}
}
};
const int mine_min_max_values[3][2]=
{
{5, 100}, // iron
{25, 200}, // silver
{70, 350} // gold
};
/**************************************************************************/
// Kal, Sept 02
void do_mine(char_data *ch, char*argument)
{
if(IS_NULLSTR(argument)){
ch->println("Syntax: mine ore - to attempt to mine the room for ore.");
ch->println("Note: In order to have any success, you must have the mining skill and a pickaxe.");
return;
}
if( str_prefix(argument, "ore")){
ch->println("Only ore can be mined.");
return;
}
if(IS_NPC(ch) || !ch->in_room){
ch->println("players only/must be in a room sorry.");
return;
}
if( IS_AFFECTED(ch,AFF_BLIND)){
ch->println("How would you propose to do that while being blind?");
return;
}
// check if they have the skill to mine
int skill=get_skill(ch, gsn_mining);
if(skill<1){
ch->println("What would you know about mining ore?");
return;
}
// check they are holding/wielding a pick axe
obj_data *pickaxe;
bool fpickaxe=false;
for ( pickaxe = ch->carrying; pickaxe; pickaxe = pickaxe->next_content )
{
if ( !str_cmp( pickaxe->pIndexData->material, "pickaxe" )
&& ( pickaxe->wear_loc == WEAR_HOLD
|| pickaxe->wear_loc == WEAR_WIELD )) {
fpickaxe = true;
break;
}
}
if(!fpickaxe){
ch->println("You need to be holding a pickaxe in order to mine.");
return;
}
// check they are in a mining room
// if not in a mining room, they waste a little time and get a little lagged
if(!IS_SET(ch->in_room->room2_flags, ROOM2_MINE)){
WAIT_STATE(ch, 3*PULSE_PER_SECOND); // lag them for 3 seconds
ch->println(3,"You attempt to mine with no success, perhaps you should try mining in an actual mine?!?");
return;
}
// we are in a mine, lets see what they can find
// apply the lag here, so we don't have to do it for every result
int lag=10*PULSE_PER_SECOND;// a default amount of lag, if one isn't specified
if(skill_table[gsn_mining].beats){
lag=skill_table[gsn_mining].beats;
}
if(IS_IMMORTAL(ch)){// imms get 1 second lag regardless
lag=PULSE_PER_SECOND;
}
WAIT_STATE(ch, lag);
lag/=PULSE_PER_SECOND; // get lag into seconds
act("You start to mine with $p...",ch,pickaxe, NULL,TO_CHAR);
act("$n starts to mine with $p.",ch,pickaxe, NULL,TO_ROOM);
// if mine has been used in the last 15 minutes, they get nothing
if(ch->in_room->last_mined_in_room+600>current_time){
ch->println(lag,"You attempt to mine for a while with no success, this location appears to have already been mined recently.");
return;
}
// decide on the type of ore they get, before skill mods on these values
//nothing 11% 11
//iron 44% 55
//silver 33% 88
//gold 12% 100
// skill adds up to 10% in the value
int type=number_range(-10,90) + URANGE(0, skill/10, 10); // random between 1 and 100
if(type<11){ // nothing - they failed, don't mark the room as mined
ch->println(lag,"You mine for quite some time, but fail to find any form of ore.");
return;
}
// mark the room as mined, since they are guaranteed success beyond here
if(type<55){ // iron
type=MINE_IRON;
}else if(type<88){ // silver
type=MINE_SILVER;
}else{ // gold
type=MINE_GOLD;
}
// now figure out the value of the ore
// skill and time since last mining increase the lower bound
int lower_bound=5 // up to the last 100 minutes, adds up to 30% below
+ URANGE(0, (((int)(current_time-ch->in_room->last_mined_in_room))/200), 30)
+ URANGE(0, skill/5, 20); // skill adds up to 20%
int value=number_range(1, number_range(lower_bound, 100));
// value is now number between 1 and 100
// scale this to a value ((max-min)*value/100)+min
int objvalue=
( (mine_min_max_values[type][1]-mine_min_max_values[type][0]
) // (max-min)
* value/100
)
+mine_min_max_values[type][0]; // +min
// globally scale the results by the game defined setting
objvalue*=game_settings->global_scale_mining_value_scaling_percentage/100;
int index=URANGE(0,(value/(100/MAX_MINE_RESULTS)),MAX_MINE_RESULTS-1);
// create the object
obj_index_data *ore_template=get_obj_index(OBJ_VNUM_ORE);
if(!ore_template){
ch->wraplnf("Unfortunately the ore object template is missing "
"from the realm (object vnum %d), "
"so you can't be awarded any ore "
"- please report this bug to the admin.",
OBJ_VNUM_ORE);
return;
}
obj_data *ore=create_object(ore_template);
// string the object
replace_string(ore->name, mine_results[type][index].name);
replace_string(ore->short_descr, mine_results[type][index].short_descr);
replace_string(ore->description, capitalize(FORMATF("%s is here.", ore->short_descr)));
ore->cost=objvalue*2;
// make it weigh something
ore->weight=mine_results[type][index].weight;
SET_BIT(ore->wear_flags, OBJWEAR_TAKE|OBJWEAR_HOLD);
ch->printlnf(lag, "You have unearthed %s.", ore->short_descr);
act("$n has unearthed $p.", ch, ore, NULL, TO_ROOM);
// record the last time the room was mined
ch->in_room->last_mined_in_room=current_time;
if( ch->carry_number + get_obj_number( ore ) > can_carry_n( ch )){
ch->println(lag, "You are carrying too many items to pick up your unearthed ore.");
obj_to_room(ore, ch->in_room);
return;
}
if ( !IS_SWITCHED (ch) && get_carry_weight(ch) + get_obj_weight( ore ) > can_carry_w( ch ) )
{
ch->println(lag, "You are already carrying too much weight to carry this ore.");
obj_to_room(ore, ch->in_room);
return;
}
ch->printlnf(lag, "You pick up %s.", ore->short_descr);
act("$n picks up $p.", ch, ore, NULL, TO_ROOM);
obj_to_char(ore, ch);
}
/**************************************************************************/
/**************************************************************************/
| true |
5819b315caa72a70cffcaeea67aac75f69369e6b | C++ | Giymo11/cgue18-heikousen | /src/jojo_utils.hpp | UTF-8 | 1,399 | 2.5625 | 3 | [] | no_license | //
// Created by giymo11 on 3/11/18.
//
#pragma once
#include <vector>
#include <iostream>
#include <functional>
// Wrapper functions for aligned memory allocation
// There is currently no standard for this in C++ that works across all platforms and vendors, so we abstract this
void *alignedAlloc(size_t size, size_t alignment);
void alignedFree(void *data);
std::vector<char> readFile(const std::string &filename);
class Config {
private:
Config(uint32_t width,
uint32_t height,
int navigationScreenPercentage,
int deadzoneScreenPercentage,
bool vsync,
bool fullscreen,
uint32_t refreshrate,
float gamma,
float hdrMode,
std::string map,
int dofTaps = 16,
int normalMode = 2,
bool isFrametimeOutputEnabled = false,
bool isWireframeEnabled = false);
public:
uint32_t width, height, navigationScreenPercentage, deadzoneScreenPercentage, refreshrate, normalMode;
const bool vsync, fullscreen;
float gamma, hdrMode;
bool isFrametimeOutputEnabled, isWireframeEnabled;
std::function<void()> rebuildPipelines;
std::string map;
float dofEnabled = 1.0f;
float dofFocalDistance = 7.0f;
float dofFocalWidth = 6.0f;
int dofTaps = 16;
static Config readFromFile(std::string filename);
};
| true |
cc6cc89a04e2f5a75e91bf59f4997c3bb2a7001f | C++ | ACES-DYPCOE/Data-Structure | /Vector/C++/Sum of Elements in Vector.cpp | UTF-8 | 513 | 3.21875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter no. of Elements : ";
cin>>n;
vector<int> v;
int a;
cout<<"Enter the Elements : ";
for(int i=0;i<n;i++)
{
cin>>a;
v.push_back(a);
}
cout << "\nVector: ";
for (int i = 0; i < n ;i++)
cout << v[i] << " ";
cout << endl;
cout << "\nSum = "
<< accumulate(v.begin(), v.end(), 0);
return 0;
} | true |
93f7bb8b3a3d65a4428c52fcc02021cdcb8e45c1 | C++ | tthheusalmeida/URI_Online_Judge | /C++/1143.cpp | UTF-8 | 241 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main(){
int N;
cin >> N;
for ( int i = 0 ; i < 1 ; i++ ){
for ( int j = 1 ; j <= N ; j ++){
cout << j << " " << pow(j,2) << " " << pow(j,3) << endl;
}
}
return 0;
}
| true |
9f1841aec5229df54d74dc4a67ddab67259feb01 | C++ | Tansen25/Graphics-Engine | /GraphicsObject.cpp | UTF-8 | 7,180 | 2.640625 | 3 | [] | no_license |
#include "GraphicsObject.h"
GraphicsObject::GraphicsObject()
{
this -> shaderID = FLAT;
this -> blend = false;
this -> colorGrowX = true;
this -> colorGrowY = true;
this -> colorGrowZ = true;
this -> scaleGrowX = true;
this -> scaleGrowY = true;
this -> scaleGrowZ = true;
this -> translationGrowX = true;
this -> translationGrowY = true;
this -> translationGrowZ = true;
this -> textureID = 0;
//Set the default transforms
this -> xScale = 1.0f;
this -> yScale = 1.0f;
this -> zScale = 1.0f;
this -> xAngle = 0.0f;
this -> yAngle = 0.0f;
this -> zAngle = 0.0f;
this -> axisRotAngle = 0.0f;
this -> orbitAngle = 0.0f;
this -> xTrans = 0.0f;
this -> yTrans = 0.0f;
this -> zTrans = 0.0f;
this -> xOrbitTrans = 0.0f;
this -> yOrbitTrans = 0.0f;
this -> zOrbitTrans = 0.0f;
this -> shininess = 128.0f;
this -> dissolveFactor = 0.0f;
this -> startPos = Vect(0.0f, 0.0f, 0.0f);
this -> lightPos = Vect(0.0f, 100.0f, 0.0f);
this -> transformedLightPos = Vect(0.0f, 100.0f, 0.0f);
this -> color = Vect(1.0f, 1.0f, 1.0f, 1.0f);
this -> ambientColor = Vect(1.0f, 1.0f, 1.0f, 1.0f);
this -> diffuseColor = Vect(1.0f, 1.0f, 1.0f, 1.0f);
this -> specularColor = Vect(1.0f, 1.0f, 1.0f, 1.0f);
this -> orbitAxis = Vect(0.0f, 1.0f, 0.0f);
this -> rotAxis = Vect(0.0f, 1.0f, 0.0f);
this -> world.set(IDENTITY);
this -> modelView.set(IDENTITY);
this -> modelViewProj.set(IDENTITY);
this -> normal.set(IDENTITY);
}
void GraphicsObject::blendOn()
{
blend = true;
}
void GraphicsObject::blendOff()
{
blend = false;
}
void GraphicsObject::setShaderID(const shader_ID ID)
{
this -> shaderID = ID;
}
void GraphicsObject::setColorGrow(const bool inX, const bool inY, const bool inZ)
{
this -> colorGrowX = inX;
this -> colorGrowY = inY;
this -> colorGrowZ = inZ;
}
void GraphicsObject::setScaleGrow(const bool inX, const bool inY, const bool inZ)
{
this -> scaleGrowX = inX;
this -> scaleGrowY = inY;
this -> scaleGrowZ = inZ;
}
void GraphicsObject::setTranslationGrow(const bool inX, const bool inY, const bool inZ)
{
this -> translationGrowX = inX;
this -> translationGrowY = inY;
this -> translationGrowZ = inZ;
}
void GraphicsObject::setTextureID(const int ID)
{
this -> textureID = ID;
}
void GraphicsObject::setStartPos(const Vect &inPos)
{
this -> startPos = inPos;
}
void GraphicsObject::setLightPos(const Vect &inLightPos)
{
this -> lightPos = inLightPos;
}
void GraphicsObject::setColor(const Vect &inTriangleColor)
{
this -> diffuseColor = inTriangleColor;
}
void GraphicsObject::setAmbientColor(const Vect &inAmbientColor)
{
this -> ambientColor = inAmbientColor;
}
void GraphicsObject::setDiffuseColor(const Vect &inDiffuseColor)
{
this -> diffuseColor = inDiffuseColor;
}
void GraphicsObject::setSpecularColor(const Vect &inSpecularColor)
{
this -> specularColor = inSpecularColor;
}
void GraphicsObject::setShininess(const float &inShininess)
{
this -> shininess = inShininess;
}
void GraphicsObject::setOrbitAxis(const Vect &inAxis)
{
this -> orbitAxis = inAxis;
}
void GraphicsObject::setRotAxis(const Vect &inAxis)
{
this -> rotAxis = inAxis;
}
void GraphicsObject::setColorArray(const Vect inArray[], int arraySize)
{
assert(arraySize == 4);
this -> colorArray[0][x] = inArray[0][x];
this -> colorArray[0][y] = inArray[0][y];
this -> colorArray[0][z] = inArray[0][z];
this -> colorArray[1][x] = inArray[1][x];
this -> colorArray[1][y] = inArray[1][y];
this -> colorArray[1][z] = inArray[1][z];
this -> colorArray[2][x] = inArray[2][x];
this -> colorArray[2][y] = inArray[2][y];
this -> colorArray[2][z] = inArray[2][z];
this -> colorArray[3][x] = inArray[3][x];
this -> colorArray[3][y] = inArray[3][y];
this -> colorArray[3][z] = inArray[3][z];
}
void GraphicsObject::setScale(const float &inX, const float &inY, const float &inZ)
{
this -> xScale = inX;
this -> yScale = inY;
this -> zScale = inZ;
}
void GraphicsObject::setAxisRotationAngle(const float &inAngle)
{
this -> axisRotAngle = inAngle;
}
void GraphicsObject::setRotationAngle(const float &inXAngle, const float &inYAngle, const float &inZAngle)
{
this -> xAngle = inXAngle;
this -> yAngle = inYAngle;
this -> zAngle = inZAngle;
}
void GraphicsObject::setOrbitAngle(const float &inAngle)
{
this -> orbitAngle = inAngle;
}
void GraphicsObject::setTranslation(const float &inX, const float &inY, const float &inZ)
{
this -> xTrans = inX;
this -> yTrans = inY;
this -> zTrans = inZ;
}
void GraphicsObject::setOrbitTranslation(const float &inX, const float &inY, const float &inZ)
{
this -> xOrbitTrans = inX;
this -> yOrbitTrans = inY;
this -> zOrbitTrans = inZ;
}
void GraphicsObject::setDissolveFactor(const float &inDissolveFactor)
{
this -> dissolveFactor = inDissolveFactor;
}
shader_ID GraphicsObject::getShaderID()
{
return this -> shaderID;
}
void GraphicsObject::getColorGrow(bool& outX, bool& outY, bool& outZ)
{
outX = this -> colorGrowX;
outY = this -> colorGrowY;
outZ = this -> colorGrowZ;
}
void GraphicsObject::getScaleGrow(bool& outX, bool& outY, bool& outZ)
{
outX = this -> scaleGrowX;
outY = this -> scaleGrowY;
outZ = this -> scaleGrowZ;
}
void GraphicsObject::getTranslationGrow(bool& outX, bool& outY, bool& outZ)
{
outX = this -> translationGrowX;
outY = this -> translationGrowY;
outZ = this -> translationGrowZ;
}
int GraphicsObject::getTextureID()
{
return this -> textureID;
}
Vect GraphicsObject::getStartPos()
{
return this -> startPos;
}
Vect GraphicsObject::getColor()
{
return this -> diffuseColor;
}
Vect GraphicsObject::getAmbientColor()
{
return this -> ambientColor;
}
Vect GraphicsObject::getDiffuseColor()
{
return this -> diffuseColor;
}
Vect GraphicsObject::getSpecularColor()
{
return this -> specularColor;
}
float GraphicsObject::getShininess()
{
return this -> shininess;
}
Vect GraphicsObject::getOrbitAxis()
{
return this -> orbitAxis;
}
Vect GraphicsObject::getRotAxis()
{
return this -> rotAxis;
}
void GraphicsObject::getScale(float& outX, float& outY, float& outZ)
{
outX = this -> xScale;
outY = this -> yScale;
outZ = this -> zScale;
}
void GraphicsObject::getRotationAngle(float& outXAngle, float& outYAngle, float& outZAngle)
{
outXAngle = this -> xAngle;
outYAngle = this -> yAngle;
outZAngle = this -> zAngle;
}
float GraphicsObject::getAxisRotationAngle()
{
return this -> axisRotAngle;
}
float GraphicsObject::getOrbitAngle()
{
return this -> orbitAngle;
}
void GraphicsObject::getTranslation(float& outX, float& outY, float& outZ)
{
outX = this -> xTrans;
outY = this -> yTrans;
outZ = this -> zTrans;
}
void GraphicsObject::getOrbitTranslation(float &outX, float &outY, float& outZ)
{
outX = this -> xOrbitTrans;
outY = this -> yOrbitTrans;
outZ = this -> zOrbitTrans;
}
float GraphicsObject::getDissolveFactor()
{
return this -> dissolveFactor;
} | true |
c90523bde81cc4b431f59b150fba553a43051660 | C++ | lyjeff/Object-Oriented-Programming-Class | /itsa/mm08.cpp | UTF-8 | 254 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
// 計算 i 次方的值
int main()
{
int num_1, num_2, result;
cin >> num_1 >> num_2;
result = pow((num_1 + num_2), 2);
cout << result << endl;
return 0;
} | true |
4e8c19ec10a208d299f17539f29caeb54bda18b1 | C++ | fenganli/Leetcode | /PascalTriangle.cpp | UTF-8 | 420 | 3.015625 | 3 | [] | no_license | class Solution
{
public:
vector<vector<int> > generate (int numRows)
{
vector<vector<int> > returnVec;
if (numRows == 0)
return returnVec;
for (int i = 0; i < numRows; i++)
{
vector<int> vec;
for (int j = 0; j <= i; j++)
if (j == 0 || j == i)
vec.push_back(1);
else
vec.push_back(returnVec[i-1][j] + returnVec[i-1][j-1]);
returnVec.push_back(vec);
}
return returnVec;
}
};
| true |
8bb327045b7d0bf56e664cd5453934c58090d4fb | C++ | arnab000/Problem-Solving | /codeforces/1152/B.cpp | UTF-8 | 1,172 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int f(int n){
int i=1,x=0;
while(n>0){
if(!(n&1)) x=i;
i++;
n>>=1;
}
return x;
}
int main(){
int n,i,l=0,k=0,m=0;
cin>>n;
vector<int>v;
int p=n,sura=0,x=0;
while(p>0){
if(!(p&1)) x=sura+1;
p>>=1;
sura++;
}
if(x==0)
{
cout<<0<<endl;
return 0;
}
while(1){
vector<int >v1;
// cout<<n<<endl;
k=f(n);
v.push_back(k);
int s=1;
for(i=1;i<=k;i++){
s*=2;
}
s--;
//cout<<s<<endl;
n=n^s;
// cout<<n<<endl;
m++;
p=n,sura=0,x=0;
while(p>0){
if(!(p&1)) x=sura+1;
p>>=1;
sura++;
}
if(x==0)
break;
n++;
p=n,sura=0,x=0;
while(p>0){
if(!(p&1)) x=sura+1;
p>>=1;
sura++;
}
m++;
if(x==0)
break;
}
cout<<m<<endl;
for(int y=0;y<v.size();y++)
{
cout<<v[y]<<" ";
}
}
| true |
98f68c79a58fe2c077c6b9236f2664557dfbecd2 | C++ | wolfogre-archives/ProgramDesignTraining | /1935/main.cpp | UTF-8 | 588 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int main() {
int n;
while (cin >> n) {
vector<long> a;
vector<long> b;
for (int i = 0; i < n; ++i)
{
int num;
cin >> num;
a.push_back(num);
b.push_back(num);
}
int max_value = 0;
sort(b.begin(), b.end());
for (int i = n - 1; i >= 0; --i) {
for (int j = i - max_value; j >= 0; --j) {
if (a[i] == b[j]) {
max_value = max(i - j, max_value);
break;
}
}
if (i < max_value)
break;
}
cout << max_value << endl;
}
return 0;
} | true |
e8018b28ce66e67113c04fa7571fec480da8bf9b | C++ | LITturtlee/Programming-Practice | /PAT/乙级/1038.cpp | UTF-8 | 475 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
int main(){
unordered_map<int,int> log;
int N,K;
cin >> N;
for(int i=0;i<N;i++){
int grade=0;
cin>>grade;
log[grade]++;
}
cin>>K;
for(int i=0;i<K;i++){
int grade=0;
cin>>grade;
if(i<K-1)
cout<<log[grade]<<" ";
else cout<<log[grade]<<endl;
}
return 0;
} | true |
708c4f354d8b769529f1d9741ab55eb0f0e145c3 | C++ | gstariarch/g-zipper | /include/Gzipper.hpp | UTF-8 | 4,874 | 2.640625 | 3 | [] | no_license | #ifndef GZIPPER_H_
#define GZIPPER_H_
#include <iostream>
#include <cinttypes>
#include "BitStream.hpp"
#include "LookbackOutputStream.hpp"
// decompress
namespace Gzipper {
// STRUCTS
/**
* Extract info from gzip header
*/
struct gzip_header {
unsigned short id;
unsigned char compression_method;
unsigned char flags;
uint32_t mtime;
unsigned char xfl;
unsigned char os;
};
/**
* Decompress the inputted file.
*
* @param file_stream - the stream we are decompressing. Must already be opened.
* @param output - the string we are outputting to.
*
* @return - idk yet to be honest, we'll figure it out :)
*/
int Decompress(std::ifstream& file_stream, std::string& output);
/**
* Returns the CRC32 hash of the inputted buffer.
*
* @param file - the file we are hashing. Its position is not reset, so you decide where to start.
* @param len - the number of bytes to hash.
*
* @return - The 32-bit remainder of the hashing function.
*/
uint32_t GetCRCHash(std::ifstream& file_stream, int len);
/**
* Verifies that the file's headers are valid.
* Once everything is verified, returns the offset at which
* we can start reading.
*
* Returns a -2 if the file has not been specified.
* Returns a -1 if the file can be read, but is invalid.
*
* @param file_stream - the GZIP file we want to verify.
* @returns - if fails, see above. If success, the offset where the remainder of the file starts.
*/
int VerifyHeaders(std::ifstream& file_stream);
/**
* The following three functions adhere to the following parameters:
* @param stream - the bit stream we are reading from.
* @param output - the string we are outputting the result to.
*/
/**
* Handles Gzip blocks where the data is not compressed, outputting contents to the output string.
*/
void HandleUncompressedData(std::ifstream& file_stream, LookbackOutputStream* output);
/**
* Handles Gzip blocks where the data is statically compressed.
*/
void HandleStaticHuffmanData(BitStream* stream, LookbackOutputStream* output);
/**
* Handles Gzip blocks where the data is dynamically compressed.
*/
void HandleDynamicHuffmanData(BitStream* stream, LookbackOutputStream* output);
static const unsigned short ID_VERIFY = 0x8B1F;
// GZIP FLAGS
static const unsigned char FLAG_TEXT = 1;
static const unsigned char FLAG_HCRC = 2;
static const unsigned char FLAG_EXTRA = 4;
static const unsigned char FLAG_NAME = 8;
static const unsigned char FLAG_COMMENT = 16;
// polynomial for CRC function -- reversed for her pleasure
static const unsigned int CRC_HASH = 0xEDB88320;
// constants for hclen
static const uint8_t MAX_CODE_LENGTH = 7;
static const uint8_t CODE_LENGTH_COUNT = 19;
static const uint8_t CODE_LENGTH_ORDER[CODE_LENGTH_COUNT] = {16, 17, 18, 0, 8,
7, 9, 6, 10, 5,
11, 4, 12, 3, 13,
2, 14, 1, 15};
// decoding constants for lookback length, starting from 264
static const uint16_t LENGTH_CONSTANTS[20] = {11, 13, 15, 17, 19,
23, 27, 31, 35, 43,
51, 59, 67, 83, 99,
115, 131, 163, 195, 227};
// decoding constants for lookback distance, starting from code 4
static const uint16_t DIST_CONSTANTS[26] = {5, 7, 9, 13, 17,
25, 33, 49, 65, 97,
129, 193, 257, 385, 513,
769, 1025, 1537, 2049, 3073,
4097, 6145, 8193, 12289, 16385,
24577 };
// Symbol for "end of block"
static const uint16_t END_OF_BLOCK = 256;
// huffman codes are MSB first
// read 7 bits and see if in range
// then shift and read 8th bit into lsb and see fi in either range
// then shift last bit and check that one
// if none then throw some invalid
// encodings for static huffman blocks
static const uint16_t SEVEN_BIT_LOWER_BOUND = 0x00;
static const uint16_t SEVEN_BIT_UPPER_BOUND = 0x17;
static const uint16_t SEVEN_BIT_OFFSET = 256;
static const uint16_t LOWER_EIGHT_BIT_LOWER_BOUND = 0x30;
static const uint16_t LOWER_EIGHT_BIT_UPPER_BOUND = 0xBF;
static const uint16_t LOWER_EIGHT_BIT_OFFSET = 0;
static const uint16_t UPPER_EIGHT_BIT_LOWER_BOUND = 0xC0;
static const uint16_t UPPER_EIGHT_BIT_UPPER_BOUND = 0xC7;
static const uint16_t UPPER_EIGHT_BIT_OFFSET = 280;
static const uint16_t NINE_BIT_LOWER_BOUND = 0x190;
static const uint16_t NINE_BIT_UPPER_BOUND = 0x1FF;
static const uint16_t NINE_BIT_OFFSET = 144;
};
#endif // GZIPPER_H_ | true |
71dcaa88addbebf32e72bb600e9af98e9d3f6c3e | C++ | jared-two-foxes/foundation | /include/logger/logger.hpp | UTF-8 | 1,050 | 3.171875 | 3 | [] | no_license | #ifndef FOUNDATION_LOGGER_HPP__
#define FOUNDATION_LOGGER_HPP__
#include <string>
#include <ostream>
class Logger
{
public:
virtual ~Logger() {}
virtual void write( std::string const& line ) = 0;
};
class BasicLogger : public Logger
{
private:
std::ostream& stream;
public:
BasicLogger(std::ostream& os);
void write( std::string const& line );
};
void ClearLoggers();
void RegisterLogger( Logger* logger, int threshold );
void SendToLogger( int level, std::string const& line );
template <typename... Args >
inline void Log( int level, char const * line, Args... args ) {
char buffer[256];
snprintf( buffer, 255, line, args... );
SendToLogger( level, buffer );
}
inline void Log( int level, char const * line ) {
char buffer[256];
snprintf( buffer, 255, "%s", line );
SendToLogger( level, buffer );
}
template <typename... Args >
inline void ConditionalLog( bool conditional, int level, char const * line, Args... args ) {
if (conditional) {
Log( level, line, args... );
}
}
#endif // FOUNDATION_LOGGER_HPP__
| true |
1868304be7f014ba54cddc42727990c1f0e40463 | C++ | pjames6/Piranha_ColorSwirl | /Piranha_ColorSwirl.ino | UTF-8 | 1,087 | 2.875 | 3 | [] | no_license | int redPin = 9;
int greenPin = 10;
int bluePin = 11;
int redVal = 255;
int greenVal = 1;
int blueVal = 1;
int i = 0;
int wait = 10;
int DEBUG = 0;
void setup()
{
pinMode(redPin, INPUT);
pinMode(greenPin, INPUT);
pinMode(bluePin, INPUT);
if (DEBUG) {
Serial.begin(9600);
}
}
void loop()
{
i += 1;
if (i < 255)
{
redVal -= 1;
greenVal += 1;
blueVal = 1;
}
else if (i < 509)
{
redVal = 1;
greenVal -= 1;
blueVal += 1;
}
else if (i < 763)
{
redVal += 1;
greenVal = 1;
blueVal -= 1;
}
else
{
i = 1;
}
analogWrite(redPin, redVal);
analogWrite(greenPin, greenVal);
analogWrite(bluePin, blueVal);
if (DEBUG) {
DEBUG += 1;
if (DEBUG > 10)
{
DEBUG = 1;
Serial.print(i);
Serial.print("\t");
Serial.print("R:");
Serial.print(redVal);
Serial.print("\t");
Serial.print("G:");
Serial.print(greenVal);
Serial.print("\t");
Serial.print("B:");
Serial.println(blueVal);
}
}
delay(wait);
}
| true |
3615a759fdbf094e4dd48167234942efbce96c61 | C++ | Sygmei/11Zip | /src/elzip_fs_fallback.cpp | UTF-8 | 3,983 | 2.671875 | 3 | [
"MIT"
] | permissive | #if defined _WIN32
#include <fileapi.h>
#else
#include <sys/stat.h>
#include <sys/types.h>
#endif
#include <fstream>
#include <iostream>
#include <string>
#include <tinydir/tinydir.h>
#include <elzip.hpp>
#include <unzipper.hpp>
template <typename V>
inline bool isInList(V term, const std::vector<V>& list1)
{
for (size_t k = 0; k < list1.size(); k++)
{
if (term == list1[k])
return true;
}
return false;
}
bool createDir(const std::string& dir)
{
#ifdef _WIN32
return bool(CreateDirectory(dir.c_str(), LPSECURITY_ATTRIBUTES(NULL)));
#else
return bool(mkdir(dir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR));
#endif
}
std::vector<std::string> split(const std::string& str, const std::string& delimiters)
{
std::vector<std::string> tokens;
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
std::vector<std::string> listDirInDir(std::string path)
{
tinydir_dir dir;
tinydir_open(&dir, path.c_str());
std::vector<std::string> fileList;
while (dir.has_next)
{
tinydir_file file;
tinydir_readfile(&dir, &file);
if (file.is_dir)
{
if (std::string(file.name) != "." && std::string(file.name) != "..")
{
fileList.push_back(std::string(file.name));
}
}
tinydir_next(&dir);
}
tinydir_close(&dir);
return fileList;
}
std::string join(std::vector<std::string>& vector, std::string sep, int start, int end)
{
std::string result = "";
if (end >= vector.size())
end = vector.size();
if (start >= vector.size() - 1)
start = vector.size() - 1;
for (int i = start; i < vector.size() - end; i++)
{
if (i != vector.size() - 1)
result += vector[i] + sep;
else
result += vector[i];
}
return result;
}
namespace elz
{
void extractZip(std::string zipname, std::string target)
{
ziputils::unzipper zipFile;
zipFile.open(zipname.c_str());
for (std::string filename : zipFile.getFilenames())
{
std::vector<std::string> splittedPath = split(filename, "/");
std::string parentPath = join(splittedPath, "/", 0, 1);
std::string cDir(target + ((parentPath == "") ? "" : "/") + parentPath);
std::string cFile(target + "/" + filename);
std::string fillPath;
std::string buffTest = ".";
for (std::string pathPart : split(cDir, "/"))
{
fillPath += ((fillPath != "") ? "/" : "") + pathPart;
if (!isInList(fillPath, listDirInDir(buffTest)))
{
createDir(fillPath.c_str());
}
buffTest = fillPath;
}
std::cout << "fb] Opening file : " << filename << std::endl;
zipFile.openEntry(filename.c_str());
std::ofstream wFile;
wFile.open(cFile, std::ios_base::binary | std::ios_base::out);
std::string dumped = zipFile.dump();
wFile.write(dumped.c_str(), dumped.size());
wFile.close();
}
}
void extractFile(std::string zipname, std::string filename, std::string target)
{
ziputils::unzipper zipFile;
zipFile.open(zipname.c_str());
zipFile.openEntry(filename.c_str());
std::ofstream wFile;
wFile.open(target, std::ios_base::binary | std::ios_base::out);
std::string dumped = zipFile.dump();
wFile.write(dumped.c_str(), dumped.size());
wFile.close();
}
} // namespace elz | true |
455c289f6cab8e27bfdde2e6f2b15d3075a55a62 | C++ | pltanguay/projects | /Polytechnique Montréal/Software Engeering - unit testing and other school labs/TP5/tests/main.cpp | UTF-8 | 365 | 2.5625 | 3 | [] | no_license | // Librairies CppUnit nécessaires
#include <cppunit/ui/text/TestRunner.h>
#include "Test.hpp"
int main(int argc, char** argv)
{
// On crée un TestRunner qui va encadrer le roulement des tests, ainsi que
// l'affichage des résultats de ceux-ci.
CppUnit::TextUi::TestRunner runner;
runner.addTest(Test::suite());
runner.run();
return 0;
} | true |
f31454591cfc7109550a6af88d717734ffe05595 | C++ | manolismih/OJsolutions | /australia (orac.amt.edu.au)/janitor.cpp | UTF-8 | 894 | 2.59375 | 3 | [] | no_license | #include <cstdio>
int rows,cols,q,ans,pista[15][100005], dir[5][2]={{1,0},{0,1},{-1,0},{0,-1},{0,0}};
bool check(int r, int c)
{
for (int i=0; i<4; i++)
if (pista[r+dir[i][0]][c+dir[i][1]] > pista[r][c]) return false;
return true;
}
int main()
{
freopen("janitorin.txt","r",stdin);
freopen("janitorout.txt","w",stdout);
scanf("%d%d%d",&rows,&cols,&q);
for (int r=2; r<=rows+1; r++)
for (int c=2; c<=cols+1; c++)
{
scanf("%d",&pista[r][c]);
pista[r][c]++;
}
for (int r=2; r<=rows+1; r++)
for (int c=2; c<=cols+1; c++) ans += check(r,c);
printf("%d\n",ans);
for (int r,c,neo, i=0; i<q; i++)
{
scanf("%d%d%d",&r,&c,&neo);
r++, c++, neo++;
for (int i=0; i<5; i++) ans -= check(r+dir[i][0], c+dir[i][1]);
pista[r][c] = neo;
for (int i=0; i<5; i++) ans += check(r+dir[i][0], c+dir[i][1]);
printf("%d\n",ans);
}
}
| true |
c7143251178bb730483d8b141ad57d7a88141f77 | C++ | jpvanoosten/LearningDirectX12 | /DX12Lib/inc/dx12lib/DescriptorAllocation.h | UTF-8 | 3,351 | 2.671875 | 3 | [
"MIT"
] | permissive | #pragma once
/*
* Copyright(c) 2018 Jeremiah van Oosten
*
* 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.
*/
/**
* @file DescriptorAllocation.h
* @date October 22, 2018
* @author Jeremiah van Oosten
*
* @brief A single allocation for the descriptor allocator.
*
* Variable sized memory allocation strategy based on:
* http://diligentgraphics.com/diligent-engine/architecture/d3d12/variable-size-memory-allocations-manager/
* Date Accessed: May 9, 2018
*/
#include <d3d12.h>
#include <cstdint>
#include <memory>
namespace dx12lib
{
class DescriptorAllocatorPage;
class DescriptorAllocation
{
public:
// Creates a NULL descriptor.
DescriptorAllocation();
DescriptorAllocation( D3D12_CPU_DESCRIPTOR_HANDLE descriptor, uint32_t numHandles, uint32_t descriptorSize,
std::shared_ptr<DescriptorAllocatorPage> page );
// The destructor will automatically free the allocation.
~DescriptorAllocation();
// Copies are not allowed.
DescriptorAllocation( const DescriptorAllocation& ) = delete;
DescriptorAllocation& operator=( const DescriptorAllocation& ) = delete;
// Move is allowed.
DescriptorAllocation( DescriptorAllocation&& allocation ) noexcept;
DescriptorAllocation& operator=( DescriptorAllocation&& other ) noexcept;
// Check if this a valid descriptor.
bool IsNull() const;
bool IsValid() const
{
return !IsNull();
}
// Get a descriptor at a particular offset in the allocation.
D3D12_CPU_DESCRIPTOR_HANDLE GetDescriptorHandle( uint32_t offset = 0 ) const;
// Get the number of (consecutive) handles for this allocation.
uint32_t GetNumHandles() const;
// Get the heap that this allocation came from.
// (For internal use only).
std::shared_ptr<DescriptorAllocatorPage> GetDescriptorAllocatorPage() const;
private:
// Free the descriptor back to the heap it came from.
void Free();
// The base descriptor.
D3D12_CPU_DESCRIPTOR_HANDLE m_Descriptor;
// The number of descriptors in this allocation.
uint32_t m_NumHandles;
// The offset to the next descriptor.
uint32_t m_DescriptorSize;
// A pointer back to the original page where this allocation came from.
std::shared_ptr<DescriptorAllocatorPage> m_Page;
};
} // namespace dx12lib | true |
2a33053d75039c43a1b656299f1a0a9239bc2458 | C++ | mdasifchand/DE | /src/birdsEye.cpp | UTF-8 | 9,711 | 2.515625 | 3 | [] | no_license | //
// Created by asif on 16.09.19.
//
#include "birdsEye.h"
cv::Mat birdsEye::birdsEyeFunction(cv::Mat plotted_image) {
int alpha_ = 20, beta_ = 90, gamma_ = 90;
int f_x = m_camera_fx, dist_ = 500;
int f_y = m_camera_fy;
// cv::namedWindow("BirdsEye", 1);
// cv::createTrackbar("Alpha", "BirdsEye", &alpha_, 180);
/* cv::createTrackbar("Beta", "BirdsEye", &beta_, 180);
cv::createTrackbar("Gamma", "Result", &gamma_, 180);
cv::createTrackbar("f_x", "Result", &f_x, 2000);
cv::createTrackbar("f_y","Result", &f_y, 2000);
cv::createTrackbar("Distance", "Result", &dist_, 2000);
*/
double focalLength_x, focalLength_y, dist, alpha, beta, gamma;
alpha = ((double)alpha_ - 90) * PI / 180;
beta = ((double)beta_ - 90) * PI / 180;
gamma = ((double)gamma_ - 90) * PI / 180;
focalLength_x = (double)f_x;
focalLength_y = (double)f_y;
dist = (double)dist_;
cv::Size image_size = plotted_image.size();
double w = (double)image_size.width, h = (double)image_size.height;
cv::Mat A1 =
(cv::Mat_<float>(4, 3) << 1, 0, -w / 2, 0, 1, -h / 2, 0, 0, 0, 0, 0, 1);
cv::Mat RX = (cv::Mat_<float>(4, 4) << 1, 0, 0, 0, 0, cos(alpha), -sin(alpha),
0, 0, sin(alpha), cos(alpha), 0, 0, 0, 0, 1);
cv::Mat RY = (cv::Mat_<float>(4, 4) << cos(beta), 0, -sin(beta), 0, 0, 1, 0,
0, sin(beta), 0, cos(beta), 0, 0, 0, 0, 1);
cv::Mat RZ = (cv::Mat_<float>(4, 4) << cos(gamma), -sin(gamma), 0, 0,
sin(gamma), cos(gamma), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
// R - rotation matrix
cv::Mat R = RX * RY * RZ;
// T - translation matrix
cv::Mat T = (cv::Mat_<float>(4, 4) << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, dist,
0, 0, 0, 1);
// K - intrinsic matrix
cv::Mat K = (cv::Mat_<float>(3, 4) << focalLength_x, 0, w / 2, 0, 0,
focalLength_y, h / 2, 0, 0, 0, 1, 0);
cv::Mat transformationMat = K * (T * (R * A1));
char str[200];
sprintf(str, "WARPED IMAGE, ALPHA = 25");
warpPerspective(plotted_image, _destination, transformationMat, image_size,
cv::INTER_CUBIC | cv::WARP_INVERSE_MAP);
putText(_destination, str, cv::Point2f(100, 100), cv::FONT_HERSHEY_PLAIN, 2,
cv::Scalar(0, 255, 0, 255));
/*
imshow("BirdsEye", _destination);
cv::waitKey(100);
*/
return _destination;
}
double
birdsEye::scalingFactor(std::vector<std::vector<cv::Point2f>> &aruco_corners,
sl::Resolution aruco_resolution) {}
cv::Mat birdsEye::deNoise(cv::Mat inputImage) {
cv::Mat output;
cv::GaussianBlur(inputImage, output, cv::Size(3, 3), 0, 0);
return output;
}
cv::Mat birdsEye::edgeDetector(cv::Mat img_noise) {
cv::Mat output;
cv::Mat kernel;
cv::Point anchor;
// Convert image from RGB to gray
cv::cvtColor(img_noise, output, cv::COLOR_RGB2GRAY);
// Binarize gray image
cv::threshold(output, output, 140, 255, cv::THRESH_BINARY);
// Create the kernel [-1 0 1]
// This kernel is based on the one found in the
// Lane Departure Warning System by Mathworks
anchor = cv::Point(-1, -1);
kernel = cv::Mat(1, 3, CV_32F);
kernel.at<float>(0, 0) = -1;
kernel.at<float>(0, 1) = 0;
kernel.at<float>(0, 2) = 1;
// Filter the binary image to obtain the edges
cv::filter2D(output, output, -1, kernel, anchor, 0, cv::BORDER_DEFAULT);
return output;
}
cv::Mat birdsEye::mask(cv::Mat img_edges) {
cv::Mat output;
cv::Mat mask = cv::Mat::zeros(img_edges.size(), img_edges.type());
cv::Point pts[4] = {cv::Point(210, 720), cv::Point(550, 450),
cv::Point(717, 450), cv::Point(1280, 720)};
// Create a binary polygon mask
cv::fillConvexPoly(mask, pts, 4, cv::Scalar(255, 0, 0));
// Multiply the edges image and the mask to get the output
cv::bitwise_and(img_edges, mask, output);
return output;
}
// HOUGH LINES
std::vector<cv::Vec4i> birdsEye::houghLines(cv::Mat img_mask) {
std::vector<cv::Vec4i> line;
// rho and theta are selected by trial and error
HoughLinesP(img_mask, line, 1, CV_PI / 180, 20, 20, 30);
return line;
}
std::vector<std::vector<cv::Vec4i>>
birdsEye::lineSeparation(std::vector<cv::Vec4i> lines, cv::Mat img_edges) {
std::vector<std::vector<cv::Vec4i>> output(2);
size_t j = 0;
cv::Point ini;
cv::Point fini;
double slope_thresh = 0.3;
std::vector<double> slopes;
std::vector<cv::Vec4i> selected_lines;
std::vector<cv::Vec4i> right_lines, left_lines;
// Calculate the slope of all the detected lines
for (auto i : lines) {
ini = cv::Point(i[0], i[1]);
fini = cv::Point(i[2], i[3]);
// Basic algebra: slope = (y1 - y0)/(x1 - x0)
double slope =
(static_cast<double>(fini.y) - static_cast<double>(ini.y)) /
(static_cast<double>(fini.x) - static_cast<double>(ini.x) + 0.00001);
// If the slope is too horizontal, discard the line
// If not, save them and their respective slope
if (std::abs(slope) > slope_thresh) {
slopes.push_back(slope);
selected_lines.push_back(i);
}
}
// Split the lines into right and left lines
img_center = static_cast<double>((img_edges.cols / 2));
while (j < selected_lines.size()) {
ini = cv::Point(selected_lines[j][0], selected_lines[j][1]);
fini = cv::Point(selected_lines[j][2], selected_lines[j][3]);
// Condition to classify line as left side or right side
if (slopes[j] > 0 && fini.x > img_center && ini.x > img_center) {
right_lines.push_back(selected_lines[j]);
right_flag = true;
} else if (slopes[j] < 0 && fini.x < img_center && ini.x < img_center) {
left_lines.push_back(selected_lines[j]);
left_flag = true;
}
j++;
}
output[0] = right_lines;
output[1] = left_lines;
return output;
}
// REGRESSION FOR LEFT AND RIGHT LINES
std::vector<cv::Point>
birdsEye::regression(std::vector<std::vector<cv::Vec4i>> left_right_lines,
cv::Mat inputImage) {
std::vector<cv::Point> output(4);
cv::Point ini;
cv::Point fini;
cv::Point ini2;
cv::Point fini2;
cv::Vec4d right_line;
cv::Vec4d left_line;
std::vector<cv::Point> right_pts;
std::vector<cv::Point> left_pts;
// If right lines are being detected, fit a line using all the init and final
// points of the lines
if (right_flag == true) {
for (auto i : left_right_lines[0]) {
ini = cv::Point(i[0], i[1]);
fini = cv::Point(i[2], i[3]);
right_pts.push_back(ini);
right_pts.push_back(fini);
}
if (right_pts.size() > 0) {
// The right line is formed here
cv::fitLine(right_pts, right_line, CV_DIST_L2, 0, 0.01, 0.01);
right_m = right_line[1] / right_line[0];
right_b = cv::Point(right_line[2], right_line[3]);
}
}
// If left lines are being detected, fit a line using all the init and final
// points of the lines
if (left_flag == true) {
for (auto j : left_right_lines[1]) {
ini2 = cv::Point(j[0], j[1]);
fini2 = cv::Point(j[2], j[3]);
left_pts.push_back(ini2);
left_pts.push_back(fini2);
}
if (left_pts.size() > 0) {
// The left line is formed here
cv::fitLine(left_pts, left_line, CV_DIST_L2, 0, 0.01, 0.01);
left_m = left_line[1] / left_line[0];
left_b = cv::Point(left_line[2], left_line[3]);
}
}
// One the slope and offset points have been obtained, apply the line equation
// to obtain the line points
int ini_y = inputImage.rows;
int fin_y = 470;
double right_ini_x = ((ini_y - right_b.y) / right_m) + right_b.x;
double right_fin_x = ((fin_y - right_b.y) / right_m) + right_b.x;
double left_ini_x = ((ini_y - left_b.y) / left_m) + left_b.x;
double left_fin_x = ((fin_y - left_b.y) / left_m) + left_b.x;
output[0] = cv::Point(right_ini_x, ini_y);
output[1] = cv::Point(right_fin_x, fin_y);
output[2] = cv::Point(left_ini_x, ini_y);
output[3] = cv::Point(left_fin_x, fin_y);
return output;
}
std::string birdsEye::predictTurn() {
std::string output;
double vanish_x;
double thr_vp = 10;
// The vanishing point is the point where both lane boundary lines intersect
vanish_x = static_cast<double>(
((right_m * right_b.x) - (left_m * left_b.x) - right_b.y + left_b.y) /
(right_m - left_m));
// The vanishing points location determines where is the road turning
if (vanish_x < (img_center - thr_vp))
output = "LEFT OF PLATE";
else if (vanish_x > (img_center + thr_vp))
output = "RIGHT OF PLATE";
else if (vanish_x >= (img_center - thr_vp) &&
vanish_x <= (img_center + thr_vp))
output = "GO STRAIGHT";
return output;
}
cv::Mat birdsEye::plotLane(cv::Mat inputImage, std::vector<cv::Point> lane,
std::string turn) {
std::vector<cv::Point> poly_points;
cv::Mat output;
// Create the transparent polygon for a better visualization of the lane
inputImage.copyTo(output);
poly_points.push_back(lane[2]);
poly_points.push_back(lane[0]);
poly_points.push_back(lane[1]);
poly_points.push_back(lane[3]);
cv::fillConvexPoly(output, poly_points, cv::Scalar(0, 0, 255), CV_AA, 0);
cv::addWeighted(output, 0.3, inputImage, 1.0 - 0.3, 0, inputImage);
// Plot both lines of the lane boundary
cv::line(inputImage, lane[0], lane[1], cv::Scalar(0, 255, 255), 5, CV_AA);
cv::line(inputImage, lane[2], lane[3], cv::Scalar(0, 255, 255), 5, CV_AA);
// Plot the turn message
cv::putText(inputImage, turn, cv::Point(50, 90),
cv::FONT_HERSHEY_COMPLEX_SMALL, 3, cvScalar(0, 255, 0), 1, CV_AA);
return inputImage;
// Show the final output image
// cv::namedWindow("Lane", CV_WINDOW_AUTOSIZE);
// cv::imshow("Lane", inputImage);
// cv::waitKey(100);
}
| true |
01e1371c0ec683031ab98f90bd4f8865fa87a775 | C++ | IgorFroehner/grafo_oo | /Node.cpp | UTF-8 | 968 | 3.359375 | 3 | [] | no_license | #include "Node.hpp"
#include "Edge.hpp"
#include <iostream>
unsigned int Node::proxId{0};
Node::Node(){
id = proxId++;
}
unsigned int Node::getId(){
return id;
}
void Node::addEdge(Edge* e){
edges.push_back(e);
}
const std::list<Edge*>& Node::getEdges(){
return edges;
}
void Node::removerEdge(Node* node){
std::list<Edge*>::iterator it = edges.begin();
for ( ; it!=edges.end(); it++){
if ((*it)->getNode1()==node || (*it)->getNode2()==node){
edges.erase(it);
break;
}
}
}
void Node::printAdjacentes(){
std::list<Edge*>::iterator it = edges.begin();
std::cout << "São adjacentes ao vertice " << this->getId() << ":" << std::endl;
for ( ; it!=edges.end(); it++){
if ((*it)->getNode1()!=this){
std::cout << (*it)->getNode1()->getId() << " ";
}else{
std::cout << (*it)->getNode2()->getId() << " ";
}
}
std::cout << std::endl;
} | true |
3e557c3f16233547fc66ca9a1c5ffca9cd258694 | C++ | sugyan/atcoder | /abc148/c/main.cpp | UTF-8 | 214 | 2.84375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int gcd(long long a, long long b) {
return a == 0 ? b : gcd(b % a, a);
}
int main() {
long long a, b;
cin >> a >> b;
cout << a / gcd(a, b) * b << endl;
}
| true |
ab096c6e90a8c6a2ae59e386a4f13e705ef1cf51 | C++ | awellock/SchoolFall2012 | /os/SecondProject/pManger.cpp | UTF-8 | 10,300 | 2.6875 | 3 | [] | no_license | #include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include "QueueArray.cpp"
using namespace std;
struct com {
char type;
char cmd;
int pid;
int value;
int Time;
int rid;
};
struct pcb{
int stime;
int etime;
int value;
int pid;
int quantum;
int rtime;
int priority;
int cpu_time;
bool exists;
};
int Time = 0;
int fProc = 0;
int tProcTime = 0;
bool done;
main(int argc, char *argv[]){
//set up pcb_tabel
vector<pcb> pcb_table (100);
pcb* running_proc;
//blocking queueArrays
QueueArray <int> block_reZ(4);
QueueArray <int> block_re1(4);
QueueArray <int> block_re2(4);
//ready queue
QueueArray <int> ready(4);
bool isFirst = true; // is this the first process
//Set up the pipe on this side
int comPipe[2];
comPipe[0] = atoi(argv[1]);
comPipe[1] = atoi(argv[2]);
//boolean to term
done = false;
while(!done){
com tCom;
read(comPipe[0], (com *)&tCom, sizeof(com));
switch(tCom.type){
case 'S': { //s comand set up process
pcb process;
//set fileds in the process
process.stime = Time;// start time is current time
process.value = tCom.value;//set the value
process.pid = tCom.pid;//set the pid
process.rtime = tCom.Time;//set the run time
process.priority = 0;//set priorty new process have prority of 0
process.quantum =1;//process with 0 priorty have quantum of 1
process.cpu_time = 0;//set total time on cpu
process.exists = true;
pcb_table.at(process.pid) = process;
if(isFirst){
running_proc = &pcb_table.at(process.pid);
isFirst = false;
}
else
ready.Enqueue(process.pid, process.priority);
break;
}
case 'B': {//block the process
switch(tCom.rid){
case 0 : {
//block on resorce 0
//equeue pid to prorty on block_reZ
if(running_proc->priority != 0)
running_proc->priority--;
running_proc->quantum = pow(2,running_proc->priority);
block_reZ.Enqueue(running_proc->pid, running_proc->priority);
int pid1 = ready.Dequeue();
running_proc = &pcb_table.at(pid1);
break;
}
case 1 : {
//block on resorce 1
if(running_proc->priority != 0)
running_proc->priority--;
running_proc->quantum = pow(2,running_proc->priority);
block_re1.Enqueue(running_proc->pid, running_proc->priority);
int pid1 = ready.Dequeue();
running_proc = &pcb_table.at(pid1);
break;
}
case 2 : {
//block on resorce 2
if(running_proc->priority != 0)
running_proc->priority--;
running_proc->quantum = pow(2,running_proc->priority);
block_re2.Enqueue(running_proc->pid, running_proc->priority);
int pid1 = ready.Dequeue();
running_proc = &pcb_table.at(pid1);
break;
}
}
break;
}
case 'U': {//Unblock the process
switch(tCom.rid){
case 0 : {
//block on resorce 0
//equeue pid to prorty on block_reZ
int pid1 = block_reZ.Dequeue();
pcb* pcb1 = &pcb_table.at(pid1);
ready.Enqueue(pcb1->pid, pcb1->priority);
break;
}
case 1 : {
//block on resorce 1
//equeue pid to prorty on block_reZ
int pid1 = block_re1.Dequeue();
pcb* pcb1 = &pcb_table.at(pid1);
ready.Enqueue(pcb1->pid, pcb1->priority);
break;
}
case 2 : {
//block on resorce 2
//equeue pid to prorty on block_reZ
int pid1 = block_re2.Dequeue();
pcb* pcb1 = &pcb_table.at(pid1);
ready.Enqueue(pcb1->pid, pcb1->priority);
break;
}
}
break;
}
case 'C' : {//exacute a comand on the current running process
switch(tCom.cmd){
case 'A': {//add the running process value by the value passed by the comand
running_proc->value = running_proc->value + tCom.value;
break;
}
case 'S': {//sub the running process value by the value passed by the comand
running_proc->value = running_proc->value - tCom.value;
break;
}
case 'M': {//multiply the running process value by the value passed by the comand
running_proc->value = running_proc->value * tCom.value;
break;
}
case 'D': {//div the runnig process value by the value passed by the comand
running_proc->value = running_proc->value / tCom.value;
break;
}
}
}
case 'Q': {
Time++;
if(!running_proc->exists)
break;
running_proc->quantum--;//the process was not done so reduce its quantum
running_proc->rtime--;
running_proc->cpu_time++;
if(running_proc->rtime <= 0){//if done running set finshed time and swap out
running_proc->etime = Time;
fProc++;
tProcTime += running_proc->etime - running_proc->stime;
int pid1 = ready.Dequeue();//pid of the next ready process
running_proc = &pcb_table.at(pid1);//set running process to the new one
}
else if(running_proc->quantum <=0){//if quantum is now zero lower priority and swap processes
if(running_proc->priority < 3)
running_proc->priority++;//set to lower priority
//reset quantu
running_proc->quantum = pow(2,running_proc->priority);
ready.Enqueue(running_proc->pid, running_proc->priority);//replace the current procces on the ready queue
int pid1 = ready.Dequeue();//get pid of the new process
running_proc = &pcb_table.at(pid1);//set runnig pocess to the new one
}
break;
}
case 'P': {
int c1, status; //int for the fork
if((c1 = fork()) == -1){
perror("unable to fork for print");
exit(1);
}
else if(c1 == 0){
//we have great happyness
cout << "*****************************************************" << endl;
cout << "The current system state is as follows:" << endl;
cout << "*****************************************************" << endl;
cout << "\nCURRENT TIME:\t" << Time << endl;
cout << "\nRUNNING PROCESS: " << endl;
cout << "PID\tPriority\tValue\tStart Time\t Total CPU time" << endl;
cout << running_proc->pid <<"\t" << running_proc->priority << "\t\t" << running_proc->value << "\t\t" << running_proc->stime << "\t\t" << running_proc->cpu_time << endl;
cout << "\nBLOCKED PROCESS:" << endl;
cout << "Queue of processes Blocked for resource 0:"<< endl;
cout << "PID\tPriority\tValue\tStart Time\t Total CPU time" << endl;
int *cbuf;
for(int j = 0; j < block_reZ.Asize(); j++){//block for resource 0;
if(block_reZ.Qsize(j)){
cbuf = block_reZ.Qstate(j);//what is in ready for priorty 0
for(int i = 0; i < block_reZ.Qsize(j); i++){
int pid1 = cbuf[i]; //pid of the process that is in that que
pcb process = pcb_table.at(pid1);//get the process
cout << "Should print stuff for process: "<<pid1<<endl;
cout << process.pid <<"\t" << process.priority << "\t\t" << process.value << "\t\t" << process.stime << "\t\t" << process.cpu_time << endl;
}
}
}
cout << "\nQueue of processes blocked for resource 1:" << endl;
cout << "PID\tPriority\tValue\tStart Time\t Total CPU time" << endl;
for(int j = 0; j < block_re1.Asize(); j++){//block for resource 0;
if(block_re1.Qsize(j)){
cbuf = block_re1.Qstate(j);//what is in ready for priorty 0
for(int i = 0; i < block_re2.Qsize(j); i++){
int pid1 = cbuf[i]; //pid of the process that is in that que
pcb process = pcb_table.at(pid1);//get the process
cout << process.pid <<"\t" << process.priority << "\t\t" << process.value << "\t\t" << process.stime << "\t\t" << process.cpu_time << endl;
}
}
}
cout << "\nQueue of processes blocked for resource 2:"<<endl;
cout << "PID\tPriority\tValue\tStart Time\t Total CPU time" << endl;
for(int j = 0; j < block_re2.Asize(); j++){//block for resource 0;
if(block_re2.Qsize(j)){
cbuf = block_re2.Qstate(j);//what is in ready for priorty 0
for(int i = 0; i < block_re2.Qsize(j); i++){
int pid1 = cbuf[i]; //pid of the process that is in that que
pcb process = pcb_table.at(cbuf[i]);//get the process
cout << process.pid <<"\t" << process.priority << "\t\t" << process.value << "\t\t" << process.stime << "\t\t" << process.cpu_time << endl;
}
}
}
cout <<"\nPROCESSES READY TO EXECUTE:" << endl;
for(int j = 0; j < ready.Asize(); j++){
if(ready.Qsize(j)){
cout << "Queue of process with priorty " << j+1 << ":" << endl;
cbuf = ready.Qstate(j);//what is in ready for priorty 0
for(int i = 0; i<ready.Qsize(j); i++){
cout << "PID\tPriority\tValue\tStart Time\t Total CPU time" << endl;
pcb process = pcb_table.at(cbuf[i]);
cout << process.pid <<"\t" << process.priority << "\t\t" << process.value << "\t\t" << process.stime << "\t\t" << process.cpu_time << endl;
}
}
else{
cout << "Queue of processes with priority " << j+1 << " is empty" <<endl;
continue;
}
}
}
wait(&status);
break;
}
case 'T': {
done = true;
cout << "Totatl finshed porcesses: " << fProc<< endl;
cout << "Avarage turn around time: " << tProcTime/((float)fProc)<< endl;
break;
}
}
}
//close the pipe
close(comPipe[0]);
close(comPipe[1]);
}
| true |
0c37c4bb23245a7994ada4d12ef458e9b72a4745 | C++ | uHappyLogic/testEngine | /src/Game.cpp | UTF-8 | 22,444 | 2.578125 | 3 | [] | no_license | /*
* Game.cpp
*
* Created on: Jan 18, 2014
* Author: lucas
*/
#include "Game.h"
#include "misc/Colors.h"
#include "misc/materials.h"
#include "misc/pugi/pugixml.hpp"
map_UID_pGameState Game::gameStates;
MessagesHandler* Game::messagesHandler;
GameState* Game::actualGameState;
Timer* Game::gameMainTimer ;
DisplayManager* Game::drawer;
void Game::update(){
//TODO control
//<messages Handling>
messagesHandler->handleMessages( actualGameState->actualScene->objectContainer->objects );
//</messages Handling>
//<UPDATING OBJECTS>
int timeElapsed = gameMainTimer->getNonZeroMSTimeElapsedSinceLastMeasurement();
for(map_UID_pObject::iterator iter = actualGameState->actualScene->objectContainer->objects->begin();
iter != actualGameState->actualScene->objectContainer->objects->end();
++iter){
iter->second->update(timeElapsed);
}
//</UPDATING OBJECTS>
//<DRAWING>
drawer->display(actualGameState->actualScene , actualGameState->resources );
//</DRAWING>
}
void Game::reshape( int width, int height ){
// obszar renderingu - całe okno
glViewport( 0, 0, width, height );
// wybór macierzy rzutowania
glMatrixMode( GL_PROJECTION );
// macierz rzutowania = macierz jednostkowa
glLoadIdentity();
// obliczenie aspektu obrazu z uwzględnieniem
// przypadku, gdy wysokość obrazu wynosi 0
GLdouble aspect = 1;
if( height > 0 )
aspect = width /( GLdouble ) height;
// rzutowanie perspektywiczne
gluPerspective( 90, aspect, 1.0, 5.0 );
}
void Game::checkCollisions(){
//TODO
}
void Game::loadGameFile(char* path){
int steps = 0;
printf("%i.[Loading File] %s\n" , steps++ , path);
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(path);
printf("%i.[initial] %s\n" ,steps++, result.description());
//<gameState name>
pugi::xml_node root = doc.child("GameState");
UID gameStateUID = hashFun(root.child("Name").child_value());
if(Game::gameStates.find( gameStateUID ) == Game::gameStates.end())
Game::gameStates[gameStateUID] = new GameState(); //creating new game state
printf("%i.[gameState name] %s\n" , steps++, root.child("Name").child_value());
//</gameState name>
//<scene>
pugi::xml_node sceneRoot = root.child("Scenes");
for (pugi::xml_node actualScene = sceneRoot.first_child(); actualScene; actualScene = actualScene.next_sibling()){
//<scene name>
printf("%i.[SceneName] ================ %s ===============\n" , steps++ , actualScene.child("Name").child_value());
//</scene name>
UID sceneID = hashFun(actualScene.child("Name").child_value() );
if(Game::gameStates[gameStateUID]->scenes.find(sceneID) == Game::gameStates[gameStateUID]->scenes.end())
Game::gameStates[gameStateUID]->scenes[sceneID] = new Scene(); //creating new scene
//<camera >
pugi::xml_node cameraRoot = actualScene.child("CameraStartPosition");
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->position.x = (float)toReal(cameraRoot.child("x").child_value());
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->position.y = (float)toReal(cameraRoot.child("y").child_value());
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->position.z = (float)toReal(cameraRoot.child("z").child_value());
printf("%i. [Camera Position] %f %f %f\n" , steps++ ,
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->position.x,
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->position.y,
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->position.z);
pugi::xml_node cameraLookPointRoot = actualScene.child("CameraLookPoint");
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->lookPoint.x = (float)toReal(cameraLookPointRoot.child("x").child_value());
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->lookPoint.y = (float)toReal(cameraLookPointRoot.child("y").child_value());
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->lookPoint.z = (float)toReal(cameraLookPointRoot.child("z").child_value());
printf("%i. [Camera LookPoint] %f %f %f\n" , steps++ ,
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->lookPoint.x,
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->lookPoint.y,
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->lookPoint.z);
float cameraScale = toReal( actualScene.child("CameraScale").child_value());
if(cameraScale == 0)
cameraScale = 1;
printf("%i. [Camera Scale] %f\n" , steps++ , cameraScale);
Game::gameStates[gameStateUID]->scenes[sceneID]->camera->scale = cameraScale;
//</camera >
//<loading objects>
pugi::xml_node objectsRoot = actualScene.child("Objects");
for (pugi::xml_node actualObject = objectsRoot.child("Object"); actualObject; actualObject = actualObject.next_sibling("Object"))
{
printf("%i. [Object Name] %s\n" , steps++ , actualObject.child("Name").child_value());
UID objectUID = hashFun( actualObject.child("Name").child_value());
printf("%i [Object UID] %u\n", steps++ , objectUID );
printf("%i. [Object Type] %s\n" , steps++ , actualObject.child("Type").child_value());
pugi::xml_node positionRoot = actualObject.child("Position");
Vector3f objectPosition;
objectPosition.x = toReal( positionRoot.child("x").child_value() );
objectPosition.y = toReal( positionRoot.child("y").child_value() );
objectPosition.z = toReal( positionRoot.child("z").child_value() );
printf("%i. [Object Position] %f %f %f\n" , steps++ ,
objectPosition.x,
objectPosition.y,
objectPosition.z);
Vector2f dimension;
dimension.x = (float)toReal(actualObject.child("Dimensions").child("x").child_value());
dimension.y = (float)toReal(actualObject.child("Dimensions").child("y").child_value());
printf("%i. [Dimensions] x:%f y:%f\n" , steps++ , dimension.x , dimension.y);
Vector3f rotation;
rotation.x = (float)toReal(actualObject.child("Rotation").child("x").child_value());
rotation.y = (float)toReal(actualObject.child("Rotation").child("y").child_value());
rotation.z = (float)toReal(actualObject.child("Rotation").child("z").child_value());
printf("%i. [Rotation] x:%f y:%f z:%f\n" , steps++ , rotation.x , rotation.y , rotation.z);
bool visible = (int)toReal(actualObject.child("Visible").child_value()) == 1 ? true : false;
printf("%i. [Visibility] %s\n" , steps++ , visible ? "true" : "false");
if( strcmp( actualObject.child("Type").child_value() , "PlainTexture") == 0 ){
UID textureUID = hashFun(actualObject.child("TextureID").child_value() );
printf("%i. [TextureHandler] %s (%u)\n" , steps++ , actualObject.child("TextureID").child_value() ,textureUID ) ;
Objects::PlainTexture* plainTexture = new Objects::PlainTexture();
plainTexture->dimensions = dimension;
plainTexture->position = objectPosition;
plainTexture->rotation = rotation;
plainTexture->textureUID = textureUID;
plainTexture->visible = visible;
(*Game::gameStates[gameStateUID]->scenes[sceneID]->objectContainer->objects)[objectUID] = plainTexture;
}else if( strcmp(actualObject.child("Type").child_value() , "TerrainBlock") == 0 ){
Objects::TerrainBlock* terrainBlock = new Objects::TerrainBlock();
terrainBlock->dimensions = dimension;
terrainBlock->position = objectPosition;
terrainBlock->visible = visible;
terrainBlock->frontTextureID = hashFun(actualObject.child("frontTextureID").child_value() );
terrainBlock->leftTextureID = hashFun(actualObject.child("leftTextureID").child_value() );
terrainBlock->rightTectureID = hashFun(actualObject.child("rightTectureID").child_value() );
terrainBlock->upperTextureID = hashFun(actualObject.child("upperTextureID").child_value() );
terrainBlock->brickModelID = hashFun(actualObject.child("brickModelID").child_value() );
printf("%i. [frontTextureID] %s (%u)\n" , steps++ , actualObject.child("frontTextureID").child_value() ,terrainBlock->frontTextureID ) ;
printf("%i. [leftTextureID] %s (%u)\n" , steps++ , actualObject.child("leftTextureID").child_value() ,terrainBlock->leftTextureID ) ;
printf("%i. [rightTectureID] %s (%u)\n" , steps++ , actualObject.child("rightTectureID").child_value() ,terrainBlock->rightTectureID ) ;
printf("%i. [upperTextureID] %s (%u)\n" , steps++ , actualObject.child("upperTextureID").child_value() ,terrainBlock->upperTextureID ) ;
printf("%i. [brickModelID] %s (%u)\n" , steps++ , actualObject.child("brickModelID").child_value() ,terrainBlock->brickModelID ) ;
(*Game::gameStates[gameStateUID]->scenes[sceneID]->objectContainer->objects)[objectUID] = terrainBlock;
}else if(strcmp( actualObject.child("Type").child_value() , "PlainAnimation") == 0){
Objects::PlainAnimation* animation = new Objects::PlainAnimation();
animation->dimensions = dimension;
animation->position = objectPosition;
animation->visible = visible;
animation->textureID = hashFun( actualObject.child("textureID").child_value() );
animation->duration_total = (int)toReal( actualObject.child("duration_total").child_value() );
animation->duration_perFrame = (int)toReal( actualObject.child("duration_perFrame").child_value() );
animation->fixedStart = (int)toReal( actualObject.child("fixedStart").child_value() );
(*Game::gameStates[gameStateUID]->scenes[sceneID]->objectContainer->objects)[objectUID] = animation;
}else if(strcmp( actualObject.child("Type").child_value() , "LightSource") == 0){
Objects::LightSource* tmpLight = new Objects::LightSource();
tmpLight->position = objectPosition;
tmpLight->dimensions = dimension;
tmpLight->visible = visible;
float isGlobal = toReal( actualObject.child("isSpotLight").child_value());
tmpLight->lightPosition[0] = objectPosition.x;
tmpLight->lightPosition[1] = objectPosition.y;
tmpLight->lightPosition[2] = objectPosition.z;
tmpLight->lightPosition[3] = isGlobal;
printf("%i. [LightPosition] [%f , %f , %f , %f]\n" , steps++ , tmpLight->lightPosition[0] ,tmpLight->lightPosition[1] ,tmpLight->lightPosition[2] ,tmpLight->lightPosition[3]);
printf("%i. [LightType] %s\n" , steps++ , (((int)(isGlobal)) ? "spotlight" : "global"));
pugi::xml_node tmp_crosscut = actualObject.child("ambient");
tmpLight->ambient[0] = toReal(tmp_crosscut.child("p1").child_value());
tmpLight->ambient[1] = toReal(tmp_crosscut.child("p2").child_value());
tmpLight->ambient[2] = toReal(tmp_crosscut.child("p3").child_value());
tmpLight->ambient[3] = toReal(tmp_crosscut.child("p4").child_value());
printf("%i. [Ambient] [%f , %f , %f , %f]\n" , steps++ , tmpLight->ambient[0] ,tmpLight->ambient[1] ,tmpLight->ambient[2] ,tmpLight->ambient[3]);
tmp_crosscut = actualObject.child("diffuse");
tmpLight->diffuse[0] = toReal(tmp_crosscut.child("p1").child_value());
tmpLight->diffuse[1] = toReal(tmp_crosscut.child("p2").child_value());
tmpLight->diffuse[2] = toReal(tmp_crosscut.child("p3").child_value());
tmpLight->diffuse[3] = toReal(tmp_crosscut.child("p4").child_value());
printf("%i. [Diffuse] [%f , %f , %f , %f]\n" , steps++ , tmpLight->diffuse[0] ,tmpLight->diffuse[1] ,tmpLight->diffuse[2] ,tmpLight->diffuse[3]);
tmp_crosscut = actualObject.child("specular");
tmpLight->specular[0] = toReal(tmp_crosscut.child("p1").child_value());
tmpLight->specular[1] = toReal(tmp_crosscut.child("p2").child_value());
tmpLight->specular[2] = toReal(tmp_crosscut.child("p3").child_value());
tmpLight->specular[3] = toReal(tmp_crosscut.child("p4").child_value());
printf("%i. [Specular] [%f , %f , %f , %f]\n" , steps++ , tmpLight->specular[0] ,tmpLight->specular[1] ,tmpLight->specular[2] ,tmpLight->specular[3]);
tmp_crosscut = actualObject.child("spotDirection");
tmpLight->spotDirection[0] = toReal(tmp_crosscut.child("p1").child_value());
tmpLight->spotDirection[1] = toReal(tmp_crosscut.child("p2").child_value());
tmpLight->spotDirection[2] = toReal(tmp_crosscut.child("p3").child_value());
printf("%i. [SpotDirection] [%f , %f , %f]\n" , steps++ , tmpLight->spotDirection[0] ,tmpLight->spotDirection[1] ,tmpLight->spotDirection[2] );
tmp_crosscut = actualObject.child("spotExponent");
tmpLight->spotExponent = toReal(tmp_crosscut.child("p1").child_value());
printf("%i. [SpotExponent] [%f]\n" , steps++ , tmpLight->spotExponent);
tmp_crosscut = actualObject.child("spotCutoff");
tmpLight->spotCutoff = toReal(tmp_crosscut.child("p1").child_value());
printf("%i. [SpotCutoff] [%f]\n" , steps++ , tmpLight->spotCutoff);
(*Game::gameStates[gameStateUID]->scenes[sceneID]->objectContainer->lights)[objectUID] = tmpLight;
}else if(strcmp( actualObject.child("Type").child_value() , "Doll") == 0){
Objects::Doll* doll = new Objects::Doll();
pugi::xml_node bodyPartsRoot = actualObject.child("bodyParts");
doll->position = objectPosition;
doll->dimensions = dimension;
doll->visible = visible;
doll->actualSkeletonID = hashFun( actualObject.child("defaultSkeletonID").child_value() );
printf("%i. [DefaultSkeleton] name: %s (%u) \n" , steps++ , actualObject.child("defaultSkeletonID").child_value() , doll->actualSkeletonID );
for (pugi::xml_node actualBodyPart = bodyPartsRoot.child("part"); actualBodyPart; actualBodyPart = actualBodyPart.next_sibling("part")){
UID bodyPartUID = hashFun( actualBodyPart.child("name").child_value());
UID bodyPartTextureUID = hashFun( actualBodyPart.child("textureID").child_value());
Vector2f dimm;
dimm.x = toReal( actualBodyPart.child("Dimensions").child("x").child_value() );
dimm.y = toReal( actualBodyPart.child("Dimensions").child("y").child_value() );
printf("%i. [BodyPart] name: %s (%u) \n" , steps++ , actualBodyPart.child("name").child_value(), bodyPartUID );
printf("%i. [Texture] %u\n" , steps++ , bodyPartTextureUID);
printf("%i. [Dimensions] x:%f y:%f\n" , steps++ , dimm.x , dimm.y);
(*doll->bodyParts)[bodyPartUID].first = bodyPartTextureUID;
(*doll->bodyParts)[bodyPartUID].second = dimm;
}
(*Game::gameStates[gameStateUID]->scenes[sceneID]->objectContainer->objects)[objectUID] = doll;
}else{
printf("%i[Undefined Object Type] %s\n", steps++ , actualObject.child("Type").child_value());
}
}
//</loading objects>
}
//</scene>
//<textures>
pugi::xml_node texturesRoot = root.child("Textures");
for (pugi::xml_node actualTexture = texturesRoot.child("Texture"); actualTexture; actualTexture = actualTexture.next_sibling("Texture")){
printf("%i.[Texture]\n" , steps++);
Resource::Texture* tex = new Resource::Texture();
UID textureUID = hashFun(actualTexture.child("Name").child_value());
printf("%i. [Name] %s (%u)\n" , steps++ , actualTexture.child("Name").child_value() , textureUID);
printf("%i. [Path] %s\n" , steps++ , actualTexture.child("Path").child_value());
if(!tex->loadTextureFromFile( actualTexture.child("Path").child_value() )){
printf("%i [ERROR WHILE LOADING TEXTURE] %s (%u)\n" , steps++ , actualTexture.child("Name").child_value() , textureUID);
}
(*Game::gameStates[gameStateUID]->resources->textures)[textureUID] = tex;
}
//</textures>
//<models>
pugi::xml_node modelsRoot = root.child("Models");
for (pugi::xml_node actualModel = modelsRoot.child("Model"); actualModel; actualModel = actualModel.next_sibling("Model")){
printf("%i.[Model]\n" , steps++);
UID modelID = hashFun(actualModel.child("Name").child_value());
printf("%i. [Name] %s (%i)\n" , steps++ , actualModel.child("Name").child_value() , modelID);
Resource::Model* model = new Resource::Model();
model->vertices[0].x = (float)toReal(actualModel.child("_1").child("x").child_value());
model->vertices[0].y = (float)toReal(actualModel.child("_1").child("y").child_value());
model->vertices[0].z = (float)toReal(actualModel.child("_1").child("z").child_value());
model->vertices[1].x = (float)toReal(actualModel.child("_2").child("x").child_value());
model->vertices[1].y = (float)toReal(actualModel.child("_2").child("y").child_value());
model->vertices[1].z = (float)toReal(actualModel.child("_2").child("z").child_value());
model->vertices[2].x = (float)toReal(actualModel.child("_3").child("x").child_value());
model->vertices[2].y = (float)toReal(actualModel.child("_3").child("y").child_value());
model->vertices[2].z = (float)toReal(actualModel.child("_3").child("z").child_value());
model->vertices[3].x = (float)toReal(actualModel.child("_4").child("x").child_value());
model->vertices[3].y = (float)toReal(actualModel.child("_4").child("y").child_value());
model->vertices[3].z = (float)toReal(actualModel.child("_4").child("z").child_value());
model->vertices[4].x = (float)toReal(actualModel.child("_5").child("x").child_value());
model->vertices[4].y = (float)toReal(actualModel.child("_5").child("y").child_value());
model->vertices[4].z = (float)toReal(actualModel.child("_5").child("z").child_value());
model->vertices[5].x = (float)toReal(actualModel.child("_6").child("x").child_value());
model->vertices[5].y = (float)toReal(actualModel.child("_6").child("y").child_value());
model->vertices[5].z = (float)toReal(actualModel.child("_6").child("z").child_value());
model->vertices[6].x = (float)toReal(actualModel.child("_7").child("x").child_value());
model->vertices[6].y = (float)toReal(actualModel.child("_7").child("y").child_value());
model->vertices[6].z = (float)toReal(actualModel.child("_7").child("z").child_value());
model->vertices[7].x = (float)toReal(actualModel.child("_8").child("x").child_value());
model->vertices[7].y = (float)toReal(actualModel.child("_8").child("y").child_value());
model->vertices[7].z = (float)toReal(actualModel.child("_8").child("z").child_value());
for(int i = 0; i < 8; ++i)
printf("%i. [Coord %i] [%f.%f,%f]\n" , steps++ , i , model->vertices[i].x , model->vertices[i].y ,model->vertices[i].z);
(*Game::gameStates[gameStateUID]->resources->models)[modelID] = model;
}
//</models>
//<Skeletons>
pugi::xml_node skeletonsRoot = root.child("Skeletons");
for (pugi::xml_node actualSkeleton= skeletonsRoot.child("Skeleton"); actualSkeleton; actualSkeleton = actualSkeleton.next_sibling("Skeleton")){
printf("%i.[Skeleton]\n" , steps++);
Resource::Skeleton* skeleton = new Resource::Skeleton();
UID skeletonID = hashFun( actualSkeleton.child("Name").child_value());
printf("%i. [Name] %s (%u)\n" , steps++ , actualSkeleton.child("Name").child_value() , skeletonID);
skeleton->LCMofAnimTimes = toReal(actualSkeleton.child("AnimTime").child_value() );
printf("%i. [AnimationTotalTime] %i\n" , steps++ , skeleton->LCMofAnimTimes );
printf("%i. [Parts]\n" , steps++ );
for (pugi::xml_node actualPart= actualSkeleton.child("parts").child("part"); actualPart; actualPart = actualPart.next_sibling("part")){
UID partUID = hashFun(actualPart.child("name").child_value());
(*skeleton->mountPoints)[partUID] = new vpipf();
(*skeleton->mountPoints)[partUID]->clear();
printf("%i. [partName] %s (%u)\n" , steps++ , actualPart.child("name").child_value() , partUID);
for (pugi::xml_node actualTimeSpan= actualPart.child("position"); actualTimeSpan; actualTimeSpan = actualTimeSpan.next_sibling("position")){
float* tab = new float[4];
int time;
tab[0] = toReal(actualTimeSpan.child("x").child_value());
tab[1] = toReal(actualTimeSpan.child("y").child_value());
tab[2] = toReal(actualTimeSpan.child("z").child_value());
tab[3] = toReal(actualTimeSpan.child("r").child_value());
time = (int)toReal(actualTimeSpan.child("time").child_value());
printf("%i. [time] %i\n" , steps++ , time);
printf("%i. [position] [%f,%f,%f] \n" , steps++ , tab[0] , tab[1] , tab[2]);
printf("%i. [rotation] [%f] \n" , steps++ , tab[3] );
(*skeleton->mountPoints)[partUID]->push_back( pipf( time , tab ) );
}
}
(*Game::gameStates[gameStateUID]->resources->skeletons)[skeletonID] = skeleton;
}
//</Skeletons>
printf("%i.[EOF] %s\n" , steps, path);
}
void Game::changeGameState(UID newGameStateID ){
//TODO
}
void Game::init(){
messagesHandler = new MessagesHandler();
Objects::Object::msgHandler = messagesHandler;
drawer = new DisplayManager();
actualGameState = nullptr;
gameMainTimer = nullptr;
}
void Game::close(){
for(auto i = gameStates.begin(); i != gameStates.end(); ++i){
delete i->second;
}
gameStates.clear();
delete messagesHandler;
delete drawer;
}
void Game::performKeyboardInput( unsigned char key, int x, int y ){
if( (int)key < 97)
key += 32;
switch( key )
{
case 'q':
case 'Q':
glutLeaveMainLoop();
break;
default: break;
}
}
void Game::performSpecialKeyboardInput( int key, int x, int y ){
//mainBrick->controlInfo->glutKey = (short)key;
switch(key){
case GLUT_KEY_LEFT:
actualGameState->actualScene->camera->position.x -= 0.1;
actualGameState->actualScene->camera->lookPoint.x -= 0.1;
break;
case GLUT_KEY_RIGHT:
actualGameState->actualScene->camera->position.x += 0.1;
actualGameState->actualScene->camera->lookPoint.x += 0.1;
break;
case GLUT_KEY_UP:
actualGameState->actualScene->camera->position.y += 0.1;
actualGameState->actualScene->camera->lookPoint.y += 0.1;
break;
case GLUT_KEY_DOWN:
actualGameState->actualScene->camera->position.y -= 0.1;
actualGameState->actualScene->camera->lookPoint.y -= 0.1;
break;
default: break;
}
}
void Game::performMouseDragg( int x, int y ){
/*
mouse.setMousePosition(x , y);
mainBrick->mainBrick->rotation.x -= (mouse.lastPosition.x - mouse.actualPosition.x);
mainBrick->mainBrick->rotation.y -= (mouse.lastPosition.y - mouse.actualPosition.y);
*/
}
void Game::performMouseAction(int button, int state, int x, int y){
/*
if(button == GLUT_LEFT_BUTTON)
mouse.leftButtonState = state;
else if(button == GLUT_RIGHT_BUTTON )
mouse.rightButtonState = state;
mouse.setMousePosition(x , y);
*/
}
void Game::performMouseMove( int x, int y ){
//mouse.setMousePosition(x , y);
}
void Game::initClock(){
gameMainTimer = new Timer();
}
Game::Game() {
}
Game::~Game() {
}
| true |
33f16768e0a5abe0e375f96a7aac4f38b0b715e6 | C++ | gradido/gradido_login_server | /src/cpp/JSONInterface/JsonUpdateUserInfos.cpp | UTF-8 | 3,984 | 2.96875 | 3 | [] | no_license | #include "JsonUpdateUserInfos.h"
#include "../SingletonManager/SessionManager.h"
#include "../SingletonManager/LanguageManager.h"
Poco::JSON::Object* JsonUpdateUserInfos::handle(Poco::Dynamic::Var params)
{
/*
'session_id' => $session_id,
'email' => $email,
'update' => ['User.first_name' => 'first_name', 'User.last_name' => 'last_name', 'User.disabled' => 0|1, 'User.language' => 'de']
*/
// incoming
int session_id = 0;
std::string email;
Poco::JSON::Object::Ptr updates;
auto sm = SessionManager::getInstance();
// if is json object
if (params.type() == typeid(Poco::JSON::Object::Ptr)) {
Poco::JSON::Object::Ptr paramJsonObject = params.extract<Poco::JSON::Object::Ptr>();
/// Throws a RangeException if the value does not fit
/// into the result variable.
/// Throws a NotImplementedException if conversion is
/// not available for the given type.
/// Throws InvalidAccessException if Var is empty.
try {
paramJsonObject->get("email").convert(email);
paramJsonObject->get("session_id").convert(session_id);
updates = paramJsonObject->getObject("update");
}
catch (Poco::Exception& ex) {
return stateError("json exception", ex.displayText());
}
}
else {
return stateError("parameter format unknown");
}
if (!session_id) {
return stateError("session_id invalid");
}
if (updates.isNull()) {
return stateError("update is zero or not an object");
}
auto session = sm->getSession(session_id);
if (!session) {
return customStateError("not found", "session not found");
}
auto user = session->getNewUser();
auto user_model = user->getModel();
if (user_model->getEmail() != email) {
return customStateError("not same", "email don't belong to logged in user");
}
Poco::JSON::Object* result = new Poco::JSON::Object;
result->set("state", "success");
Poco::JSON::Array jsonErrorsArray;
int extractet_values = 0;
//['User.first_name' => 'first_name', 'User.last_name' => 'last_name', 'User.disabled' => 0|1, 'User.language' => 'de']
for (auto it = updates->begin(); it != updates->end(); it++) {
std::string name = it->first;
auto value = it->second;
try {
if ( "User.first_name" == name) {
if (!value.isString()) {
jsonErrorsArray.add("User.first_name isn't a string");
}
else {
user_model->setFirstName(value.toString());
extractet_values++;
}
}
else if ("User.last_name" == name) {
if (!value.isString()) {
jsonErrorsArray.add("User.last_name isn't a string");
}
else {
user_model->setLastName(value.toString());
extractet_values++;
}
}
else if ("User.disabled" == name) {
if (value.isBoolean()) {
bool disabled;
value.convert(disabled);
user_model->setDisabled(disabled);
extractet_values++;
}
else if (value.isInteger()) {
int disabled;
value.convert(disabled);
user_model->setDisabled(static_cast<bool>(disabled));
extractet_values++;
}
else {
jsonErrorsArray.add("User.disabled isn't a boolean or integer");
}
}
else if ("User.language" == name) {
if (!value.isString()) {
jsonErrorsArray.add("User.language isn't a string");
}
else {
auto lang = LanguageManager::languageFromString(value.toString());
if (LANG_NULL == lang) {
jsonErrorsArray.add("User.language isn't a valid language");
}
else {
user_model->setLanguageKey(value.toString());
extractet_values++;
}
}
}
}
catch (Poco::Exception& ex) {
jsonErrorsArray.add("update parameter invalid");
}
}
if (extractet_values > 0) {
if (1 != user_model->updateFieldsFromCommunityServer()) {
user_model->addError(new Error("JsonUpdateUserInfos", "error by saving update to db"));
user_model->sendErrorsAsEmail();
return stateError("error saving to db");
}
}
result->set("errors", jsonErrorsArray);
result->set("valid_values", extractet_values);
result->set("state", "success");
return result;
} | true |
65347d2dae59d850b5250c22e0053dc8c14893d5 | C++ | 3DTK/3DTK | /include/slam6d/bkdIndexed.h | UTF-8 | 3,506 | 2.875 | 3 | [] | no_license | /** @file
* @brief Representation of an optimized Bkd tree.
*
* A Bkd-tree is like a kd-tree, but preserves balance and space
* utilization when inserting new or removing old points.
* It is therefore dynamicaly updated by handling multiple,
* logarithmic ordered kd-trees.
*
* See:
* Procopiuc, O., Agarwal, P. K., Arge, L., & Vitter, J. S. (2003).
* Bkd-Tree: A Dynamic Scalable kd-Tree.
* Lecture Notes in Computer Science, 46–65.
* doi:10.1007/978-3-540-45072-6_4
*
* TODO: the Bkd class derives from the SearchTree class.
* However, it does neither implement lock() nor unlock(), so it can't
* be used with the scanserver!
*
* @author Fabian Arzberger, Uni Wuerzburg
*/
#ifndef __BKD_INDEXED_H_
#define __BKD_INDEXED_H_
#include "slam6d/kdIndexed.h"
#include "slam6d/searchTree.h"
#include <vector>
// This data structure stores trees.
// The trees themselfes do not have any pts stored.
// Instead, they operate on the "DataElem" structure by reorganisation.
struct ForestElemIndexed
{
// Create an empty Forest element, i.e. an empty tree (called 'sprout')
ForestElemIndexed() : empty(true), nrpts(0) {} // empty constructor, we use c++ init list
// Create a non-empty Forest element, i.e. a KD-tree (called 'tree')
ForestElemIndexed(KDtreeIndexed* t, size_t n) : empty(false), tree(t), nrpts(n) {}
// Struct data
bool empty;
KDtreeIndexed* tree;
size_t nrpts;
};
class BkdTreeIndexed : public SearchTree
{
public:
BkdTreeIndexed(double **pts,
int n,
int bucketSize = 20);
BkdTreeIndexed(int bucketSize = 20);
virtual ~BkdTreeIndexed();
// BKD specifics
int insert(double*);
int remove(double*);
std::vector<size_t> collectPts() const;
size_t size() const;
std::string info() const;
std::string _debug_info() const;
friend std::ostream& operator<<(std::ostream&, const BkdTreeIndexed&);
// SearchTree inheritance
virtual double* FindClosest(double *_p,
double maxdist2,
int threadNum = 0) const;
virtual std::vector<size_t> fixedRangeSearchAlongDir(double *_p,
double *_dir,
double maxdist2,
int threadNum = 0) const;
virtual std::vector<size_t> fixedRangeSearchBetween2Points(double *_p,
double *_dir,
double maxdist2,
int threadNum = 0) const;
virtual std::vector<size_t> kNearestNeighbors(double *_p,
int k,
int threadNum = 0) const;
virtual std::vector<size_t> kNearestRangeSearch(double *_p,
int k,
double sqRad2,
int threadNum = 0) const;
virtual std::vector<size_t> fixedRangeSearch(double *_p,
double sqRad2,
int threadNum = 0) const;
virtual std::vector<size_t> AABBSearch(double *_p,
double* _p0,
int threadNum = 0) const;
virtual size_t segmentSearch_1NearestPoint(double *_p,
double* _p0,
double maxdist2,
int threadNum) const;
private:
// Saves all the sub-trees (thus is called 'forest')
std::vector<ForestElemIndexed> forest;
std::vector<size_t> buffer;
int bucketSize;
void mergeTreesLogarithmic(int, int);
};
#endif // __BKD_H
| true |
15935e82d4d205f2b9d2e4df0a6feaae35efb55f | C++ | lee-m/UniProject | /feasibility tests/lexers/HandLexer/src/CLexicalScanner.cpp | UTF-8 | 10,786 | 3.015625 | 3 | [] | no_license | //------------------------------------------------------------------------------------------
// File: CLexicalScanner.cpp
// Desc: Implementation of the hand written scanner
// Auth: Lee Millward
//------------------------------------------------------------------------------------------
//our headers
#include "CLexicalScanner.h"
//std headers
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cassert>
//-------------------------------------------------------------
CLexicalScanner::CLexicalScanner(const string &InputFile) : m_InputBufferSize(4)
{
//try and open it
m_FileHandle.open(InputFile.c_str());
if(!m_FileHandle.is_open())
throw exception("unable to open input file for tokenising");
//allocate the buffers and read in the first lot of characters
m_InputBuffer = new char[m_InputBufferSize + 2];
assert(m_InputBuffer);
RefreshInputBuffer();
m_CurrLineNumber = 1;
//clear out the current token
m_CurrToken = "";
//build the reserved id's list
InitialiseKeywordsList();
EatWhitespaceAndComments();
}
//-------------------------------------------------------------
//-------------------------------------------------------------
CLexicalScanner::~CLexicalScanner(void)
{
delete m_InputBuffer;
m_InputBuffer = NULL;
m_FileHandle.close();
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::InitialiseKeywordsList(void)
{
//program keywords
m_Keywords.insert(make_pair("program", TOKTYPE_PROGRAM));
m_Keywords.insert(make_pair("end_program", TOKTYPE_ENDPROGRAM));
//types
m_Keywords.insert(make_pair("integer", TOKTYPE_INTEGERTYPE));
m_Keywords.insert(make_pair("float", TOKTYPE_FLOATTYPE));
m_Keywords.insert(make_pair("boolean", TOKTYPE_BOOLEANTYPE));
m_Keywords.insert(make_pair("string", TOKTYPE_STRINGTYPE));
//control statements
m_Keywords.insert(make_pair("if", TOKTYPE_IF));
m_Keywords.insert(make_pair("end_if", TOKTYPE_ENDIF));
m_Keywords.insert(make_pair("while", TOKTYPE_WHILE));
m_Keywords.insert(make_pair("end_while", TOKTYPE_ENDWHILE));
//functions/procedures
m_Keywords.insert(make_pair("function", TOKTYPE_FUNCTION));
m_Keywords.insert(make_pair("returns", TOKTYPE_RETURNS));
m_Keywords.insert(make_pair("return", TOKTYPE_RETURN));
m_Keywords.insert(make_pair("end_function", TOKTYPE_ENDFUNC));
//Boolean types
m_Keywords.insert(make_pair("true", TOKTYPE_TRUE));
m_Keywords.insert(make_pair("false", TOKTYPE_FALSE));
//misc tokens
m_MiscTokens.insert(make_pair("=", TOKTYPE_ASSIGNMENT));
m_MiscTokens.insert(make_pair("(", TOKTYPE_OPENPAREN));
m_MiscTokens.insert(make_pair(")", TOKTYPE_CLOSEPAREN));
m_MiscTokens.insert(make_pair(";", TOKTYPE_SEMICOLON));
m_MiscTokens.insert(make_pair("<", TOKTYPE_LESSTHAN));
m_MiscTokens.insert(make_pair("<=", TOKTYPE_LESSTHANEQ));
m_MiscTokens.insert(make_pair(">", TOKTYPE_GREATTHAN));
m_MiscTokens.insert(make_pair(">=", TOKTYPE_GREATTHANEQ));
m_MiscTokens.insert(make_pair("!", TOKTYPE_NOT));
m_MiscTokens.insert(make_pair("!=", TOKTYPE_NOTEQ));
m_MiscTokens.insert(make_pair("==", TOKTYPE_EQUALITY));
m_MiscTokens.insert(make_pair("||", TOKTYPE_OR));
m_MiscTokens.insert(make_pair("&&", TOKTYPE_AND));
m_MiscTokens.insert(make_pair("const", TOKTYPE_CONST));
m_MiscTokens.insert(make_pair("]", TOKTYPE_OPENSQRPAREN));
m_MiscTokens.insert(make_pair("[", TOKTYPE_CLOSESQRPAREN));
m_MiscTokens.insert(make_pair(",", TOKTYPE_COMMA));
//arithmetic operators
m_MiscTokens.insert(make_pair("-", TOKTYPE_SUBTRACT));
m_MiscTokens.insert(make_pair("+", TOKTYPE_PLUS));
m_MiscTokens.insert(make_pair("/", TOKTYPE_DIVIDE));
m_MiscTokens.insert(make_pair("*", TOKTYPE_MULTIPLY));
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::EatWhitespaceAndComments(void)
{
bool EndOfWs = false;
while(!EndOfWs)
{
//check for a comment
if(*m_ForwardPtr == '/')
{
IncForwardPtr();
if(*m_ForwardPtr == '*')
{
//we have a comment, keep going until we hit the next non-whitespace character
while(true)
{
++m_ForwardPtr;
if(*m_ForwardPtr == '\n')
++m_CurrLineNumber;
if(*m_ForwardPtr == 0)
RefreshInputBuffer();
if(*m_ForwardPtr == '*')
{
IncForwardPtr();
if(*m_ForwardPtr == '/')
{
//found the end of comment, move past the
//comment terminator character
IncForwardPtr();
break;
}
}
}
}
else
{
--m_ForwardPtr; //we dont have the start of a comment but the division op
EndOfWs = true;
}
}
//check for whitespace
else if(*m_ForwardPtr == ' ' || *m_ForwardPtr == '\t' || *m_ForwardPtr == '\n')
{
//skip it
do
{
if(*m_ForwardPtr == '\n')
++m_CurrLineNumber;
IncForwardPtr();
}
while(*m_ForwardPtr == ' ' || *m_ForwardPtr == '\t' || *m_ForwardPtr == '\n');
}
else
EndOfWs = true;
}
if(*m_ForwardPtr == 0)
RefreshInputBuffer();
}
//-------------------------------------------------------------
//-------------------------------------------------------------
bool CLexicalScanner::IsKeyword(const string &TokStr)
{
TokenMap::iterator itr = m_Keywords.find(TokStr);
return !(itr == m_Keywords.end());
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::RefreshInputBuffer(void)
{
//if we're not at the end of the file, read the next lot in
if(!m_FileHandle.eof())
{
memset((void*)m_InputBuffer, 0, m_InputBufferSize + 1);
m_FileHandle.read(m_InputBuffer, m_InputBufferSize);
m_InputBuffer[m_InputBufferSize + 1] = '\0';
m_ForwardPtr = &m_InputBuffer[0];
}
}
//-------------------------------------------------------------
//-------------------------------------------------------------
char CLexicalScanner::IncForwardPtr(void)
{
char c = *m_ForwardPtr++;
if(*m_ForwardPtr == 0)
RefreshInputBuffer();
return c;
}
//-------------------------------------------------------------
//-------------------------------------------------------------
bool CLexicalScanner::HasMoreTokens(void)
{
if(m_FileHandle.eof())
{
if(*m_ForwardPtr == 0)
return false;
}
//in some situations we might not be at the end of the file but
//have no more tokens left if there's a lot of trailing whitespace
//or a large comment block so skip over that here
EatWhitespaceAndComments();
if(m_FileHandle.eof() && *m_ForwardPtr == 0)
return false;
else
return true;
}
//-------------------------------------------------------------
//-------------------------------------------------------------
Token_t CLexicalScanner::GetNextToken(void)
{
//take a look at the input token and see what we're pointing at,
//we can then base a decision about which token to scan based upon that.
//Each one the decisions below represents a starting state in the token
//reconisition state transition diagrams.
EatWhitespaceAndComments();
//blank out the old token
m_CurrToken = "";
//find out what we have next
if(isalpha((int)*m_ForwardPtr) || *m_ForwardPtr == '_')
ScanIdentifierToken();
else if(isdigit((int)*m_ForwardPtr))
ScanDigitToken();
else if(*m_ForwardPtr == '\"')
ScanStringToken();
else
{
//for each of the four tokens in the condition, the next character can be '=' so handle them
//all in one go
m_CurrToken.append(1, IncForwardPtr());
if(*m_ForwardPtr == '=' || *m_ForwardPtr == '>' || *m_ForwardPtr == '<' || *m_ForwardPtr == '!')
{
if(*m_ForwardPtr == '=')
m_CurrToken.append(1, IncForwardPtr());
}
else if(*m_ForwardPtr == '|')
ScanLogicalOr();
else if(*m_ForwardPtr == '&')
ScanLogicalAnd();
}
//the m_CurrToken buffer is already filled with zero's so the
//name of the token will always be NULL terminated.
Token_t RetToken;
RetToken.LineNumber = m_CurrLineNumber;
RetToken.TokenValue = m_CurrToken;
RetToken.Type = GetTokenType();
return RetToken;
}
//-------------------------------------------------------------
//-------------------------------------------------------------
TokenType CLexicalScanner::GetTokenType(void)
{
if(IsKeyword(m_CurrToken))
return m_Keywords[m_CurrToken];
else
{
//see if it's one of the misc tokens
TokenMap::iterator itr = m_MiscTokens.find(m_CurrToken);
if(itr == m_MiscTokens.end())
{
//not one of the misc tokens, must be an either a digit
if(isdigit((int)m_CurrToken[0]))
{
//if a decimal point is present, it an FP number
string Temp(m_CurrToken);
if(Temp.find(".") != string::npos)
return TOKTYPE_FLOATDIGIT;
else
return TOKTYPE_INTDIGIT;
}
else
{
//if the first character is a double quote we have a string, otherwise a nam
if(m_CurrToken[0] == '\"')
return TOKTYPE_STRING;
else
return TOKTYPE_NAME;
}
}
else
return itr->second;
}
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::ScanIdentifierToken(void)
{
while(isalpha((int)*m_ForwardPtr) || isdigit((int)*m_ForwardPtr) || *m_ForwardPtr == '_')
{
//copy the character across to the token buffer
m_CurrToken.append(1, IncForwardPtr());
}
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::ScanDigitToken(void)
{
bool FoundDecimalPoint = false;
while(isdigit((int)*m_ForwardPtr) || *m_ForwardPtr == '.')
{
//copy the character across to the token buffer
m_CurrToken.append(1, IncForwardPtr());
if(*m_ForwardPtr == '.' && FoundDecimalPoint)
break;
else
FoundDecimalPoint = true;
}
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::ScanStringToken(void)
{
//copy the opening quote
m_CurrToken.append(1, IncForwardPtr());
//copy the body of the string
while(*m_ForwardPtr != '\"')
m_CurrToken.append(1, IncForwardPtr());
//get the closing quote
m_CurrToken.append(1, IncForwardPtr());
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::ScanLogicalOr(void)
{
if(*m_ForwardPtr == '|')
m_CurrToken.append(1, IncForwardPtr());
}
//-------------------------------------------------------------
//-------------------------------------------------------------
void CLexicalScanner::ScanLogicalAnd(void)
{
if(*m_ForwardPtr == '&')
m_CurrToken.append(1, IncForwardPtr());
}
//------------------------------------------------------------- | true |
ae9d589a0dbae3aeb4d7b25241ff71aae01d3d0f | C++ | orsoromeo/contactWrenchSet | /tests/provaIpopt/src/OptimizationProblem.cpp | UTF-8 | 3,034 | 2.59375 | 3 | [] | no_license | #include <OptimizationProblem.h>
OptimizationProblem::OptimizationProblem() {}
OptimizationProblem::~OptimizationProblem() {}
void OptimizationProblem::init(bool soft_constraint)
{
// Getting the dimension of the decision vector
// state_dimension_ = 4;
// constraint_dimension_ = 2;
state_dimension_ = 2;
constraint_dimension_ = 1;
}
void OptimizationProblem::getStartingPoint(Eigen::Ref<Eigen::VectorXd> full_initial_point)
{
// full_initial_point(0) = 1.0;
// full_initial_point(1) = 5.0;
// full_initial_point(2) = 5.0;
// full_initial_point(3) = 1.0;
full_initial_point(0) = 4.0;
full_initial_point(1) = 4.0;
}
void OptimizationProblem::evaluateBounds(Eigen::Ref<Eigen::VectorXd> full_state_lower_bound,
Eigen::Ref<Eigen::VectorXd> full_state_upper_bound,
Eigen::Ref<Eigen::VectorXd> full_constraint_lower_bound,
Eigen::Ref<Eigen::VectorXd> full_constraint_upper_bound)
{
//bounds on state should be always defined (if they are not set they are set to 0,0)
// full_state_lower_bound(0) = 1.0;
// full_state_lower_bound(1) = 1.0;
// full_state_lower_bound(2) = 1.0;
// full_state_lower_bound(3) = 1.0;
// full_state_upper_bound(0) = 5.0;
// full_state_upper_bound(1) = 5.0;
// full_state_upper_bound(2) = 5.0;
// full_state_upper_bound(3) = 5.0;
full_state_lower_bound(0) = -2e19;
full_state_lower_bound(1) = -2e19;
full_state_upper_bound(0) = 2e19;
full_state_upper_bound(1) = 2e19;
full_constraint_lower_bound(0) = 0.0;
// full_constraint_lower_bound(1) = 40.0;
full_constraint_upper_bound(0) = 0.0;
// full_constraint_upper_bound(1) = 40.0;
}
void OptimizationProblem::evaluateConstraints(Eigen::Ref<Eigen::VectorXd> full_constraint,
const Eigen::Ref<const Eigen::VectorXd>& decision_var)
{
// full_constraint = Eigen::VectorXd::Zero(constraint_dimension_);
// full_constraint(0) = decision_var(0) * decision_var(1) *
// decision_var(2) * decision_var(3);
// full_constraint(1) = decision_var(0) * decision_var(0) +
// decision_var(1) * decision_var(1) + decision_var(2) * decision_var(2) +
// decision_var(3) * decision_var(3);
full_constraint(0) = decision_var(0) + decision_var(1) ;
}
void OptimizationProblem::evaluateCosts(double& cost,
const Eigen::Ref<const Eigen::VectorXd>& decision_var)
{
// cost = decision_var(0) * decision_var(3) * (decision_var(0) +
// decision_var(1) + decision_var(2)) + decision_var(2);
cost = (decision_var - Eigen::Vector2d(1,2)).norm();
}
dwl::WholeBodyTrajectory& OptimizationProblem::evaluateSolution(const Eigen::Ref<const Eigen::VectorXd>& solution)
{
std::cout << "the optimization solution is " << solution.transpose() << std::endl;
//return motion_solution_;
}
| true |
d9fc71ac1b3660813cad87082780e51f84a7f5f1 | C++ | lnfernal/buildoland-3 | /common-source/Grounds/GameGrounds.cpp | UTF-8 | 2,420 | 2.953125 | 3 | [] | no_license | #include "GameGrounds.h"
#include <limits>
#include "Ground.h"
#include "StaticGround.h"
#include "GameGrounds/GroundError.h"
#include "GameGrounds/GroundDirt.h"
#include "GameGrounds/GroundStone.h"
#include "GameGrounds/GroundSand.h"
#include "GameGrounds/GroundGrass.h"
#include "GameGrounds/GroundWater.h"
#include "GameGrounds/GroundCarpet.h"
#include "GameGrounds/GroundParquet.h"
#include "../../common-source/Utils/Log.h"
Ground const * const GameGrounds::ERROR = new GroundError("error");
Ground const * const GameGrounds::STRUCTURE_VOID = new GroundError("structural_void");
Ground const * const GameGrounds::DIRT = new GroundDirt();
Ground const * const GameGrounds::WATER = new GroundWater();
Ground const * const GameGrounds::STONE = new GroundStone();
Ground const * const GameGrounds::SAND = new GroundSand();
Ground const * const GameGrounds::GRASS = new GroundGrass();
Ground const * const GameGrounds::WOOD = new GroundParquet();
Ground const * const GameGrounds::CARPET = new GroundCarpet();
GameGrounds::GameGrounds()
{
//ctor
}
GameGrounds::~GameGrounds()
{
//dtor
}
void GameGrounds::initGrounds()
{
names.clear();
grounds.clear();
//Add all grounds here
addGround(ERROR);
addGround(STRUCTURE_VOID);
addGround(WATER);
addGround(DIRT);
addGround(STONE);
addGround(SAND);
addGround(GRASS);
addGround(WOOD);
addGround(CARPET);
}
void GameGrounds::addGround(Ground const * ground)
{
std::string name = ground->getName();
//Fail if the name is already used
assert(names.find(name) == names.end());
//Fail if theres more grounds than the id system can allow (very unlikely)
assert(grounds.size() < std::numeric_limits<uint16_t>::max() - 1);
uint16_t id = (uint16_t)grounds.size();
names.emplace(name, id);
grounds.push_back(ground);
ground->id = id;
log(INFO, "Added ground \"{}\" with id {}\n", name, id);
}
Ground const * GameGrounds::getGroundByID(uint16_t id) const
{
if (id >= grounds.size())
return ERROR;
return grounds.at(id);
}
Ground const * GameGrounds::getGroundByName(const std::string& name) const
{
auto ptr = names.find(name);
if (ptr == names.end())
return ERROR;
uint16_t id = ptr->second;
assert(id < grounds.size());
return grounds.at(id);
}
| true |
d6596df71f6a2ca31e3f3ddef15a43998a9f7482 | C++ | stfuchs/university | /ML-class/MLUtils/include/MLUtils/features.h | UTF-8 | 2,393 | 2.78125 | 3 | [] | no_license | #include <Eigen/Dense>
namespace MLUtils
{
typedef Eigen::MatrixXd Mat;
typedef Eigen::VectorXd Vec;
typedef Eigen::RowVectorXd RowVec;
/*
0: 1, x0, x1, x2, x3;
5: x0x0, x0x1, x0x2, x0x3;
9: x1x1, x1x2, x1x3;
12: x2x2, x2x3;
14: x3x3;
(0,0) = 0 (0,1) = 1 (0,2) = 2 -(0+0)
(1,1) = 3 (1,2) = 4 -(0+1)
(2,2) = 5 -(1+2)
(0,0) = 0 (0,1) = 1 (0,2) = 2 (0,3) = 3 -(0+0)
(1,1) = 4 (1,2) = 5 (1,3) = 6 -(0+1)
(2,2) = 7 (2,3) = 8 -(1+2)
(3,3) = 9 -(3+3)
*/
RowVec linearFeature(const RowVec& input)
{
RowVec m(1,1+input.cols());
m(0,0) = 1.0;
m.rightCols(input.cols()) = input;
return m;
}
RowVec quadraticFeature(const RowVec& input)
{
int d = input.cols();
int idx = d + int(0.5*d*(d+1));
RowVec m(1, idx+1);
m.leftCols(d+1) = linearFeature(input);
int inv_idx = 0;
for(int i=1; i<=d; ++i)
{
inv_idx += i;
for(int j=i; j<=d; ++j)
{
idx = (d+1)*i + j - inv_idx;
m(0, idx) = m(0,i) * m(0,j);
}
}
return m;
}
void fillFeatureMatrixLin(const Mat& data, int dim, Mat& out)
{
out = Mat(data.rows(), 1+dim);
for(int i=0; i<data.rows(); ++i)
out.row(i) = linearFeature(data.block(i,0,1,dim));
}
void fillFeatureMatrixQuad(const Mat& data, int dim, Mat& out)
{
out = Mat(data.rows(), 1+dim + int(0.5*dim*(dim+1)));
for(int i=0; i<data.rows(); ++i)
out.row(i) = quadraticFeature(data.block(i,0,1,dim));
}
// binary case
// TODO: multi-class case
double conditionalClassProbability(const Vec& xi, const Vec& beta)
{
return ( 1.0 / (1.0 + exp( -double(xi.transpose() * beta) )) );
}
double computeNegLogLikelihood(const Mat& X, const Mat& Y,
const Vec& beta, double lambda)
{
double res = 0;
for(int i=0; i<X.rows(); ++i)
{
double pi = conditionalClassProbability(X.row(i), beta);
res += Y(i)*log(pi) + (1.0-Y(i))*log(1.0-pi);
}
return (-res + lambda * beta.squaredNorm());
}
double computeClassificationRate(const Mat& X, const Mat& Y, const Vec& beta)
{
int res = 0;
for(int i=0; i<X.rows(); ++i)
{
if( fabs(Y(i) - conditionalClassProbability(X.row(i), beta)) < 0.5 ) ++res;
}
return (double(res) / X.rows());
}
}
| true |
abddedb33e9b70d8952b4015411057fe538b64c4 | C++ | noonelikechu/shearlet | /reconstruction/gadgetron/CS_LAB_Gadget/src/LAP_GADGET/LAPRegistrationGadget.cpp | UTF-8 | 7,355 | 2.53125 | 3 | [
"BSD-2-Clause"
] | permissive | /*
file name : LAPRegistrationGadget.cpp
author : Thomas Kuestner (thomas.kuestner@med.uni-tuebingen.de)
version : 1.0
date : 15.01.2018
description : implementation of the class LAPRegistrationGadget - only 4D data (x,y,z,t) provided
*/
#include "LAPRegistrationGadget.h"
#include "SomeFunctions.h"
using namespace Gadgetron;
LAPRegistrationGadget::LAPRegistrationGadget()
{
}
LAPRegistrationGadget::~LAPRegistrationGadget()
{
}
int LAPRegistrationGadget::process_config(ACE_Message_Block *mb)
{
#ifdef __GADGETRON_VERSION_HIGHER_3_6__
iLvlMin_ = LvlMin.value();
iLvlMax_ = LvlMax.value();
#else
iLvlMin_ = *(get_int_value("LvlMin").get());
iLvlMax_ = *(get_int_value("LvlMax").get());
#endif
return GADGET_OK;
}
int LAPRegistrationGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader> *m1, GadgetContainerMessage<hoNDArray<float> > *m2)
{
// create dimension variables
// first image is fixed image (end-exhale position) all other images declared to be moving images
std::vector<size_t> dimensions = *m2->getObjectPtr()->get_dimensions();
// last dimension is number of images
size_t number_of_images = dimensions.at(dimensions.size()-1);
// other dimensions are dimension of one image
std::vector<size_t> dimensions_of_image(dimensions.begin(), dimensions.end()-1);
// check for image dimensions
bool skip_registration = false;
if (dimensions_of_image.size() != 3) {
GWARN("Dataset does not contain a 3D image - Skip registration...\n");
skip_registration = true;
} else if (number_of_images <= 1) {
GWARN("There must be at least to images to register them - Skip registration...\n");
skip_registration = true;
}
// skip registration if it cannot be performed
if (skip_registration) {
if (this->next()->putq(m1) < 0) {
return GADGET_FAIL;
}
return GADGET_OK;
}
// print dimensions
std::stringstream ss;
ss << "size - ";
for (size_t i = 0; i < dimensions_of_image.size(); i++) {
ss << dimensions_of_image.at(i) << " ";
}
ss << number_of_images;
GDEBUG("%s\n", ss.str().c_str());
// multiply all other elements in vector (will be number of pixels in one image)
const size_t cuiNumberOfPixels = std::accumulate(std::begin(dimensions_of_image), std::end(dimensions_of_image), 1, std::multiplies<size_t>());
float *pfDataset = m2->getObjectPtr()->get_data_ptr();
// get fixed image from dataset
hoNDArray<float> fFixedImage(dimensions_of_image, pfDataset, false);
// create registered (output) image
std::vector<size_t> new_reg_image_dim = *m2->getObjectPtr()->get_dimensions();
hoNDArray<float> fRegisteredImage(&new_reg_image_dim);
memcpy(fRegisteredImage.get_data_ptr(), fFixedImage.get_data_ptr(), cuiNumberOfPixels*sizeof(float));
// create array for deformation field
new_reg_image_dim.at(new_reg_image_dim.size()-1) = (number_of_images - 1) * dimensions_of_image.size(); // images for deformation fields (images - fixedImage) * dimensions per image (2D/3D)
hoNDArray<float> output_deformation_field(&new_reg_image_dim);
CubeType cFixedImage = Cube<float>(dimensions_of_image.at(0), dimensions_of_image.at(1), dimensions_of_image.at(2));
CubeType cMovingImage = Cube<float>(dimensions_of_image.at(0), dimensions_of_image.at(1), dimensions_of_image.at(2));
memcpy(cFixedImage.memptr(), fFixedImage.get_data_ptr(), cuiNumberOfPixels*sizeof(float));
//Construct the LocalAllpass Algorithm Object with Level min and max
LAP3D mLAP3D(cFixedImage, cMovingImage, iLvlMin_, iLvlMax_);
/* ------------------------------------------------------------------- */
/* --------- loop over moving images and perform registration -------- */
/* ------------------------------------------------------------------- */
GINFO("Loop over moving images..\n");
// loop over respiration
// #pragma omp parallel for // Parallelising here may work, but may also introduce errors. Check that before enabling!
for (size_t iState = 1; iState < number_of_images; iState++) {
GINFO("%i of %i ...\n", iState, number_of_images-1);
// crop moving image from 4D dataset
size_t tOffset = std::accumulate(std::begin(dimensions_of_image), std::end(dimensions_of_image), 1, std::multiplies<size_t>())*iState; // accumulate() := dimensions_of_image[0]*dimensions_of_image[1]*...
hoNDArray<float> fMovingImage(dimensions_of_image, pfDataset + tOffset, false);
memcpy(cMovingImage.memptr(), fMovingImage.get_data_ptr(), cuiNumberOfPixels*sizeof(float));
mLAP3D.setMovingImage(cMovingImage);
// image registration
field<CubeType> flow_estimation = mLAP3D.exec();
// save deformation fields
for (size_t i = 0; i < dimensions_of_image.size(); i++) {
// calculate offset
size_t def_field_offset = cuiNumberOfPixels * ( // all slots (4th dimension 3D images) have same size, so multiply it with position)
+ (iState - 1) * dimensions_of_image.size() // jump to correct deformation field image position
+ i); // select correct slot
memcpy(output_deformation_field.get_data_ptr()+def_field_offset, flow_estimation(i).memptr(), cuiNumberOfPixels*sizeof(float));
}
// get output image
// Shift first image according to estimated optical flow
ShiftEngine3D shifter(cFixedImage, flow_estimation(0), flow_estimation(1), flow_estimation(2));
CubeType cRegisteredImage = shifter.execCubicShift();
// copy image to new registered 4D image
memcpy(fRegisteredImage.get_data_ptr()+tOffset, cRegisteredImage.memptr(), cuiNumberOfPixels*sizeof(float));
}
// free memory
m2->release();
// new GadgetContainer
GadgetContainerMessage<hoNDArray<float> > *cm2 = new GadgetContainerMessage<hoNDArray<float> >();
// concatenate data with header
m1->cont(cm2);
// create output
try {
cm2->getObjectPtr()->create(*fRegisteredImage.get_dimensions());
} catch (std::runtime_error &err) {
GEXCEPTION(err,"Unable to allocate new image array\n");
m1->release();
return GADGET_FAIL;
}
// copy data
memcpy(cm2->getObjectPtr()->get_data_ptr(), fRegisteredImage.begin(), sizeof(float)*fRegisteredImage.get_number_of_elements());
// Now pass on image
if (this->next()->putq(m1) < 0) {
return GADGET_FAIL;
}
// ########## create deformation field message ###########
// copy header
GadgetContainerMessage<ISMRMRD::ImageHeader> *m1_df = new GadgetContainerMessage<ISMRMRD::ImageHeader>();
fCopyImageHeader(m1_df, m1->getObjectPtr());
// correct channels value for MRIImageWriter (last dimension of output array)
m1_df->getObjectPtr()->channels = output_deformation_field.get_size(output_deformation_field.get_number_of_dimensions()-1);
// set new image number
m1_df->getObjectPtr()->image_series_index = 1;
// new GadgetContainer
GadgetContainerMessage<hoNDArray<float> > *m2_df = new GadgetContainerMessage<hoNDArray<float> >();
// concatenate data with header
m1_df->cont(m2_df);
// create output
try {
m2_df->getObjectPtr()->create(*output_deformation_field.get_dimensions());
} catch (std::runtime_error &err) {
GEXCEPTION(err,"Unable to allocate new deformation field array\n");
m1_df->release();
return GADGET_FAIL;
}
// copy data
memcpy(m2_df->getObjectPtr()->get_data_ptr(), output_deformation_field.begin(), output_deformation_field.get_number_of_bytes());
// Now pass on deformation field
if (this->next()->putq(m1_df) < 0) {
return GADGET_FAIL;
}
return GADGET_OK;
}
GADGET_FACTORY_DECLARE(LAPRegistrationGadget)
| true |
a446f35d11634a8258362a3f3f10c9ec8da337c7 | C++ | minhtriet/frozenlake | /Board.h | UTF-8 | 869 | 2.734375 | 3 | [] | no_license | #include <vector>
#include <map>
#include <queue>
#include "Point.cpp"
class Board {
private:
bool is_inside(const Point& location);
std::queue<Point> schedule;
public:
std::vector<std::vector<float>> best_value;
std::vector<std::vector<Point>> best_policy;
int width;
int height;
std::vector<Point> direction{Point(1, 0), Point(0, 1),
Point(-1, 0), Point(0, -1)};
std::vector<Point> end_states;
Point start_state;
std::vector<Point> obstacles;
float reward;
float gamma{1};
float move(const Point& current_loc, const Point& direction);
float move(const Point& current_loc, const Point& direction, float prob);
const std::vector<float> probs{0.8, 0.1, 0.1};
void init(const Point& start_state);
int run();
};
| true |
9566a759c60438c0dee176761e9dda512abd19ef | C++ | eldritchabstraction/simulation | /Tanker.h | UTF-8 | 2,600 | 3.40625 | 3 | [] | no_license | /*
A Tanker is a ship with a large corgo capacity for fuel.
It can be told an Island to load fuel at, and an Island to unload at.
Once it is sent to the loading destination, it will start shuttling between
the loading and unloading destination. At the loading destination,
it will first refuel then wait until its cargo hold is full, then it will
go to the unloading destination.
Initial values:
fuel capacity and initial amount 100 tons, maximum speed 10., fuel consumption 2.tons/nm,
resistance 0, cargo capacity 1000 tons, initial cargo is 0 tons.
*/
/*
This skeleton file shows the required public and protected interface for the class, which you may not modify.
If no protected members are shown, there must be none in your version.
If any protected or private members are shown here, then your class must also have them and use them as intended.
You should delete this comment.
*/
#ifndef TANKER_H
#define TANKER_H
#include <string>
#include "Ship.h"
#include "Island.h"
#include "geometry.h"
enum tanker_state
{
state_no_cargo = 0b1,
state_unloading = 0b10,
state_moving_loading = 0b100,
state_loading = 0b1000,
state_moving_unloading = 0b10000,
};
class Tanker : public Ship
{
public:
// initialize, the output constructor message
Tanker(const std::string& name, Point position);
// output destructor message
~Tanker();
// This class overrides these Ship functions so that it can check if this Tanker has assigned cargo destinations.
// if so, throw an Error("Tanker has cargo destinations!"); otherwise, simply call the Ship functions.
void set_destination_position_and_speed(Point destination_point, double speed) override;
void set_destination_island_and_speed(Island* destination_island, double speed) override;
void set_course_and_speed(double course, double speed) override;
// Set the loading and unloading Island destinations
// if both cargo destination are already set, throw Error("Tanker has cargo destinations!").
// if they are the same, leave at the set values, and throw Error("Load and unload cargo destinations are the same!")
// if both destinations are now set, start the cargo cycle
void set_load_destination(Island* island) override;
void set_unload_destination(Island* island) override;
// when told to stop, clear the cargo destinations and stop
void stop() override;
// perform Tanker-specific behavior
void update() override;
void describe() const override;
private:
int tanker_state_;
Island *load_destination_, *unload_destination_;
double cargo_, cargo_max_;
};
#endif
| true |
722b07708f4d656331b514c81183512ef3eb1382 | C++ | ompugao/opengl_examples | /phony_starfox/branches/murooka/object.h | UTF-8 | 575 | 2.890625 | 3 | [] | no_license | #ifndef __OBJECT_H__
#define __OBJECT_H__
#include "vector.h"
#include <cmath>
extern const double RADIAN;
class Object {
protected:
VECTOR position;
VECTOR direction;
VECTOR up;
VECTOR v;
double h_angle;
double v_angle;
double h_omega;
double v_omega;
double r;
virtual void move() = 0;
void set_position(double, double, double);
void set_direction(double, double);
void set_r(double);
public:
Object() {
set_position(0, 0, 0);
set_r(10);
set_direction(0, 0);
}
VECTOR get_pos();
double get_r();
virtual void draw() = 0;
};
#endif //__OBJECT_H__
| true |
dec07a4d362a7683856e521a9fb75801effff1c7 | C++ | zhongpuwu/DataStructA | /Stop.cpp | UTF-8 | 4,022 | 3.25 | 3 | [] | no_license | //==============================================
// 停车场问题
//----------------------------------------------
// 作者:武重甫
// 学号:17032430
// 修订:2017年10月
//==============================================
#include <iostream>
using namespace std;
#include "Move.h"
bool Jump(int &t)
{
cout << "请输入您要跳转的时间:";
cin >> t;
cout << endl;
cout << "跳转成功!\n"
<< endl;
return true;
}
bool Come(Street &St, Stop &Sp, int n, int &t)
{
TheCar c;
int time;
Label1:
// 用于重新输入 不想写循环
cout << "请依次输入车牌 到达时间" << endl;
cin >> c.id >> time;
cout << endl;
if (Search(Sp, St, n, c.id))
{
cout << "车牌已被占用,请换一个!\n"
<< endl;
goto Label1;
}
else if (time < t)
{
cout << "入站时间不能小于当前时间,请换一个!\n"
<< endl;
goto Label1;
}
else
{
c.in = time;
t = time;
In(St, Sp, c, n, t);
return true;
}
}
bool Quit(Street &St, Stop &Sp, int n, int t)
{
int id, time;
Label2:
// 用于重新输入 不想写循环
cout << "请依次输入车牌 出站时间" << endl;
cin >> id >> time;
cout << endl;
if (!Search_write(Sp, St, n, id, time))
{
cout << "查无此车\n"
<< endl;
goto Label2;
}
else if (time < t)
{
cout << "出站时间不能小于当前时间,请换一个!\n"
<< endl;
goto Label2;
}
else
{
cout << "出站意愿已经写入!" << endl;
return true;
}
}
// 假设便道无限长
// 规定车辆在停车场中和便道上的移动都是瞬时的
// 进停车场可以改变时间 出只会记录时间
int main()
{
int t = 0;
char com = ' ';
int n; // 停车场长度,车辆个数;
Stop Sp;
Street St;
InitStreet(St); // 构造便道
InitStop(Sp, n); // 构造停车场
cout << "请输入停车场的长度";
cin >> n;
while (1)
{
cout << endl;
cout << "当前时间: " << t << ":00" << endl;
Print(Sp, St, n); // 打印停车场当前状态
cout << endl;
if (com != 'Q')
{
cout << "请输入需要进行的操作:A/D/Q/J ";
cout << "PS:(A代表入站/D代表出站/Q代表结束输入/J代表跳转时间)" << endl;
cin >> com;
cout << endl;
switch (com)
{
case 'J':
Jump(t);
break;
case 'A':
Come(St, Sp, n, t);
break;
case 'D':
if (!StopEmpty(Sp))
Quit(St, Sp, n, t);
else
{
cout << "停车场为空时不能出站" << endl;
continue;
}
break;
case 'Q':
goto Label3;
// 直接判断停车场是否为空
default:
cout << "指令不存在,请重新输入" << endl;
continue;
}
}
else
{
Label3:
// 如果输入了Q就进行判断 判断成功才能结束程序
if (StreetEmpty(St) && StopEmpty(Sp))
{
cout << "停车场已空!程序结束!" << endl;
break;
}
else if (!StopEmpty(Sp))
{
cout << "停车场还有车辆未使出,请重新输入指令" << endl;
com = ' ';
continue;
}
}
if (!StopEmpty(Sp))
{
OutStop(Sp, n, t);
}
if (!StreetEmpty(St) && !Stopfull(Sp, n))
{
Fill(Sp, St, n, t);
}
}
DestroyStreet(St);
DestroyStop(Sp);
system("pause");
return 0;
}
| true |
0380698afe0f0a7100a78d3dba7706842b6e2133 | C++ | helcl42/mi-gen | /MI-GEN/strom.cpp | UTF-8 | 22,299 | 2.859375 | 3 | [] | no_license | /* strom.cpp */
#include "strom.h"
#include "gener.h"
#include "util.h"
#define DEBUG_OPT
extern FILE* debugPrint;
// konstruktory a destruktory
Var::Var(int a, bool rv) {
addr = a;
rvalue = rv;
}
Numb::Numb(int v) {
value = v;
}
int Var::getAddr() const {
return addr;
}
bool Var::isRValue() const {
return rvalue;
}
int Numb::getValue() const {
return value;
}
Bop::Bop(Operator o, Expr *l, Expr *r) {
op = o;
left = l;
right = r;
}
Bop::~Bop() {
SAFE_DELETE(left);
SAFE_DELETE(right);
}
UnMinus::UnMinus(Expr *e) {
expr = e;
}
UnMinus::~UnMinus() {
SAFE_DELETE(expr);
}
Assign::Assign(Var *v, Expr *e) {
var = v;
expr = e;
}
Assign::~Assign() {
SAFE_DELETE(var);
SAFE_DELETE(expr);
}
Write::Write(Expr *e) {
expr = e;
}
Write::~Write() {
SAFE_DELETE(expr);
}
If::If(Expr *c, Statm *ts, Statm *es) {
cond = c;
thenstm = ts;
elsestm = es;
}
If::~If() {
SAFE_DELETE(cond);
SAFE_DELETE(thenstm);
SAFE_DELETE(elsestm);
}
While::While(Expr *c, Statm *b) {
cond = c;
body = b;
}
While::~While() {
SAFE_DELETE(cond);
//SAFE_DELETE(body);
}
StatmList::StatmList() {
statm = NULL;
next = NULL;
}
void StatmList::setStm(Statm* stm) {
statm = stm;
}
Statm* StatmList::getStm() const {
return statm;
}
StatmList* StatmList::getNext() const {
return next;
}
void StatmList::setNext(StatmList* nxt) {
next = nxt;
}
StatmList::StatmList(Statm *s, StatmList *n) {
statm = s;
next = n;
}
StatmList::~StatmList() {
SAFE_DELETE(statm);
SAFE_DELETE(next);
}
Prog::Prog(StatmList *s) {
stm = s;
}
Prog::~Prog() {
SAFE_DELETE(stm);
}
int Prog::maxVarAddr = 0;
bool Prog::optimized = false;
void Prog::setMaxVarAddr(int max) {
maxVarAddr = max;
}
void Prog::setOptimized(bool is) {
optimized = is;
}
int Prog::getMaxVarAddr() {
return maxVarAddr;
}
bool Prog::isOptimized() {
return optimized;
}
void Numb::Print() const {
fprintf(debugPrint, "[ Const(%d) ]", value);
}
void Var::Print() const {
fprintf(debugPrint, "[ Var(%d) ]", addr);
}
void Assign::Print() const {
fprintf(debugPrint, "[ Assign ");
var->Print();
expr->Print();
fprintf(debugPrint, " ]\n");
}
void UnMinus::Print() const {
fprintf(debugPrint, "[ UnMinus ");
expr->Print();
fprintf(debugPrint, " ]\n");
}
void Bop::Print() const {
fprintf(debugPrint, "[ Bop(%s)", toOpString(op));
left->Print();
right->Print();
fprintf(debugPrint, " ]\n");
}
void Prog::Print() const {
fprintf(debugPrint, "[ Prog ");
stm->Print();
fprintf(debugPrint, " ]\n");
}
void StatmList::Print() const {
fprintf(debugPrint, "[ StmList ");
const StatmList *s = this;
do {
s->statm->Print();
s = s->next;
} while (s);
fprintf(debugPrint, " ]\n");
}
void While::Print() const {
fprintf(debugPrint, "[ While ");
cond->Print();
body->Print();
fprintf(debugPrint, " ]\n");
}
void If::Print() const {
fprintf(debugPrint, "[ If ");
cond->Print();
thenstm->Print();
elsestm->Print();
fprintf(debugPrint, " ]\n");
}
void Write::Print() const {
fprintf(debugPrint, "[ Write ");
expr->Print();
fprintf(debugPrint, " ]\n");
}
/*
* staticka funkce pro overeni, zda se jedna o jednu
* a tu samou konstantu
*/
bool Numb::areTheSameNumbers(Expr* e1, Expr* e2) {
Numb* n1 = dynamic_cast<Numb*> (e1);
Numb* n2 = dynamic_cast<Numb*> (e2);
if (n1 == NULL || n2 == NULL) {
return false;
}
if (n1->getValue() != n2->getValue()) {
return false;
}
return true; // jsou stejne
}
/*
* staticka funkce pro overeni, zda se jedna
* o jednu a tu samou promennou
*/
bool Var::areTheSameVars(Expr* e1, Expr* e2) {
Var* var1 = dynamic_cast<Var*> (e1);
Var* var2 = dynamic_cast<Var*> (e2);
if (var1 == NULL || var2 == NULL) {
return false;
}
if (var1->getAddr() != var2->getAddr()) {
return false;
}
return true; //jsou stejne
}
/*
* staticka funkce pro overeni, zda jsou dva Bop podvyrazy
* semanticky ekvivalentni
*/
bool Bop::areBopTreeTheSame(Expr* e1, Expr* e2) {
Bop* b1 = dynamic_cast<Bop*> (e1);
Bop* b2 = dynamic_cast<Bop*> (e2);
if (b1 == NULL || b2 == NULL) {
return false;
}
if (b1->op != b2->op) {
return false;
}
if (Var::areTheSameVars(b1->left, b2->left)) {
if (Var::areTheSameVars(b1->right, b2->right)) {
return true;
} else if (Numb::areTheSameNumbers(b1->right, b2->right)) {
return true;
} else {
return false;
}
}
if (Var::areTheSameVars(b1->left, b2->right)) {
if (Var::areTheSameVars(b1->right, b2->left)) {
return true;
} else if (Numb::areTheSameNumbers(b1->right, b2->left)) {
return true;
} else {
return false;
}
}
return false;
}
void Bop::getExpressionBops(std::vector<Bop*>& bops) {
left->getExpressionBops(bops);
bops.push_back(this);
right->getExpressionBops(bops);
}
// definice metody Optimize
Node *Bop::Optimize() {
left = (Expr*) (left->Optimize());
right = (Expr*) (right->Optimize());
Numb *l = dynamic_cast<Numb*> (left);
Numb *r = dynamic_cast<Numb*> (right);
if (!l || !r) {
return this;
}
int res;
int leftval = l->getValue();
int rightval = r->getValue();
switch (op) {
case Plus:
res = leftval + rightval;
break;
case Minus:
res = leftval - rightval;
break;
case Times:
res = leftval * rightval;
break;
case Divide:
res = leftval / rightval;
break;
case Eq:
res = leftval == rightval;
break;
case NotEq:
res = leftval != rightval;
break;
case Less:
res = leftval < rightval;
break;
case Greater:
res = leftval > rightval;
break;
case LessOrEq:
res = leftval <= rightval;
break;
case GreaterOrEq:
res = leftval >= rightval;
break;
}
delete this;
return new Numb(res);
}
Node *UnMinus::Optimize() {
expr = (Expr*) expr->Optimize();
Numb *e = dynamic_cast<Numb*> (expr);
if (!e) {
return this;
}
e = new Numb(-e->getValue());
delete this;
return e;
}
/*
* funkce, která vrací mapu Binárních operací jako kličí k hodnotám,
* které tvorí seznam, ekvivalentních binárních operací
*/
std::map<Bop*, std::vector<Bop*> > Bop::findEquivalentBops(std::vector<Bop*>& bops) {
std::map<Bop *, std::vector<Bop *> > same;
for (unsigned int i = 0; i < bops.size(); ++i) {
for (unsigned int j = i + 1; j < bops.size(); ++j) {
if (Bop::areBopTreeTheSame(bops[i], bops[j]) == true) {
same[bops[i]].push_back(bops[j]);
}
}
std::vector<Bop *> vec = same[bops[i]];
if (vec.size() > 0) {
same[bops[i]].push_back(bops[i]);
}
}
return same;
}
/*
* funkce vraci Bop, ktery bude nejvyhodnejsi optimalizovat,
* nebo prvni, ktery je nejlesi s nejakym dalsim
*/
Bop* Bop::getWhereOptimize(std::map<Bop*, std::vector<Bop*> >& same) {
std::map<Bop*, std::vector<Bop*> >::iterator itSame;
unsigned int count = 0;
Bop *ret = NULL;
for (itSame = same.begin(); itSame != same.end(); ++itSame) {
if (itSame->second.size() > count) {
count = (*itSame).second.size();
ret = itSame->first;
}
}
return ret;
}
/*
* funkce pro samotny replace za Var
*/
void Bop::replaceExpression(std::vector<Bop*>& bops) {
this->left->replaceExpression(bops);
this->right->replaceExpression(bops);
std::vector<Bop *>::iterator ii;
#ifdef DEBUG_OPT
std::cout << "BOPS size: " << bops.size() << std::endl;
for (ii = bops.begin(); ii != bops.end(); ++ii) {
(*ii)->Print();
}
#endif
for (ii = bops.begin(); ii != bops.end(); ++ii) {
if (this->left == *ii) {
//delete this->left;
this->left = new Var(Prog::getMaxVarAddr(), true);
}
if (this->right == *ii) {
//delete this->right;
this->right = new Var(Prog::getMaxVarAddr(), true);
}
}
}
/*
* Optimalizace podvyrazu
*/
Node *Assign::Optimize() {
expr = (Var*) (expr->Optimize());
// nejprve ve vyrazu najdeme vsechny podstromy
// s binarni operaci, na nez si ulozime pointery
bool isSimple = true;
std::vector<Bop*> bops;
std::vector<Bop*>::iterator itBops;
expr->getExpressionBops(bops);
#ifdef DEBUG_OPT
if (bops.size() > 0) {
printMessage("Optimalizace podvyrazu");
}
for (itBops = bops.begin(); itBops != bops.end(); ++itBops) {
(*itBops)->Print();
}
#endif
//najdeme mezi nimi ekvivalenty a vratime svazane v mape
std::map<Bop*, std::vector<Bop*> >::iterator itSame;
std::map<Bop*, std::vector<Bop*> > same = Bop::findEquivalentBops(bops);
if (same.size() > 0) {
isSimple = false;
}
#ifdef DEBUG_OPT
for (itSame = same.begin(); itSame != same.end(); ++itSame) {
itSame->first->Print();
}
#endif
//zjistime kde mistech je nejlepsi optimalizvat v ramci vyrazu
Bop* bestBop = Bop::getWhereOptimize(same);
if (bestBop != NULL) {
// zde jsou podvyrazy k prepsani
std::vector<Bop *> toReplace = same.find(bestBop)->second;
#ifdef DEBUG_OPT
std::cout << "To Replace:" << std::endl;
for (itBops = toReplace.begin(); itBops != toReplace.end(); ++itBops) {
(*itBops)->Print();
}
#endif
if (toReplace.size() > 0) {
int maxVar = Prog::getMaxVarAddr();
maxVar++;
Prog::setMaxVarAddr(maxVar);
Assign *newAssign = new Assign(new Var(maxVar, false), toReplace.back());
StatmList *oldList = new StatmList(this, NULL);
StatmList *newList = new StatmList(newAssign, oldList);
expr->replaceExpression(toReplace);
#ifdef DEBUG_OPT
std::cout << "Replaced:" << std::endl;
this->Print();
#endif
return newList;
}
}
//pokud je vyraz na rpave strane jednoduchy(neobsahuje zadne repetice)
// tak nema pravo menit priznak, ze kod je plne optimalizovany
if (!isSimple) {
Prog::setOptimized(true);
}
return this;
}
Node *Write::Optimize() {
expr = (Expr*) (expr->Optimize());
return this;
}
Node *If::Optimize() {
cond = (Expr*) (cond->Optimize());
thenstm = (Statm*) (thenstm->Optimize());
if (elsestm) {
elsestm = (Statm*) (elsestm->Optimize());
}
Numb *c = dynamic_cast<Numb*> (cond);
if (!c) {
return this;
}
Node *res;
if (c->getValue()) {
res = thenstm;
thenstm = 0;
} else {
res = elsestm;
elsestm = 0;
}
delete this;
return res;
}
/*
* funkce vraci mapu s pointry na prikazy, ktere jsou invarianty v cyklu
*/
std::map<int, StatmList *> While::getInvariants(StatmList* whileBody) {
std::map<int, StatmList *> toReplace;
Assign* assign = NULL;
//projdeme vsechny prikazy v tele
while (whileBody != NULL) {
assign = dynamic_cast<Assign *> (whileBody->getStm());
//pokud je prikaz prirazeni, muze byt invariantem
if (assign != NULL) {
#ifdef DEBUG_OPT
printf("Nalezeno prizazeni\n");
#endif
// pokdu je na prave strane prirazeni konstanta => mame invariant
if (dynamic_cast<Numb *> (assign->getExpr()) != NULL) {
#ifdef DEBUG_OPT
printf("Nalezen invariant => prirazeni konstanty do promenne %i\n", assign->getVar()->getAddr());
#endif
toReplace[assign->getVar()->getAddr()] = whileBody;
}
}
whileBody = whileBody->getNext();
}
return toReplace;
}
/*
* funkce ktera nahradi cely while novym statm listem, kde jako prvni zapoji
* invarianty a pak zbytek tela cyklu
*/
StatmList* While::replaceInvariants(std::map<int, StatmList*> toReplace, StatmList* whileBody) {
StatmList *newWhileBlock = new StatmList();
std::map<int, StatmList *>::iterator ii;
// projdeme celou mapu invariantu
for (ii = toReplace.begin(); ii != toReplace.end(); ++ii) {
StatmList* remove = ii->second;
StatmList* start = whileBody;
if (newWhileBlock->getStm() == NULL) {
newWhileBlock->setStm(this);
}
// pokud je invariant jako prvni
if (start == remove) {
StatmList *tmpStmList = new StatmList(start->getStm(), newWhileBlock);
start->setStm(new Empty());
newWhileBlock = tmpStmList;
} else {
while (start->getNext() != remove) {
start = start->getNext();
}
//minula pozice se musi preskocit
//TODO leak
if (start->getNext() != NULL) {
start->setNext(start->getNext()->getNext());
}
start = new StatmList(remove, newWhileBlock);
newWhileBlock = start;
}
}
// toto by se stat nemelo, ale je dobre to zkontrolovat
if (newWhileBlock->getStm() == NULL || newWhileBlock->getNext() == NULL) {
SAFE_DELETE(newWhileBlock);
return NULL;
}
return newWhileBlock;
}
/*
* optimalizace invarintu v cyklu
*/
Node *While::Optimize() {
cond = (Expr*) (cond->Optimize());
body = (Statm*) (body->Optimize());
Numb *c = dynamic_cast<Numb*> (cond);
if (c != NULL) {
if (!c->getValue()) {
delete this;
return new Empty();
}
}
#ifdef DEBUG_OPT
printMessage("While telo pred optimalizaci");
this->Print();
#endif
//nejprve je potreba zjistit, zda telo je typu list prikazu
StatmList *whileBody = dynamic_cast<StatmList *> (body);
if (whileBody == NULL) {
return this;
}
#ifdef DEBUG_OPT
printf("While telo je typu StatmList\n");
#endif
//nehcame vratit mapu s invarianty
std::map<int, StatmList* > replacelist = getInvariants(whileBody);
if (replacelist.empty()) {
return this;
}
//presuneme invarianty pred tento cyklus(kdyby nahodou byly potreba uvnitr)
StatmList* newWhile = replaceInvariants(replacelist, whileBody);
if (newWhile == NULL) {
return this;
}
#ifdef DEBUG_OPT
printMessage("While po uplatneni otimalizace");
newWhile->Print();
#endif
return newWhile;
}
Node *StatmList::Optimize() {
StatmList *s = this;
do {
s->statm = (Statm*) (s->statm->Optimize());
s = s->next;
} while (s);
return this;
}
Node *Prog::Optimize() {
stm = (StatmList*) (stm->Optimize());
return this;
}
/*
* pri prekladu listu AST s promennou
* udela akorat load
*/
void Var::Translate() {
if (traceCode) {
emitComment(">> Ident");
}
emitRM("LD", acc1, addr, gp, "load id value");
if (traceCode) {
emitComment("<< Ident");
}
}
/*
* pri prekladu listu AST s konstantou
* je potreba udelat LDC(load konstatny)
*/
void Numb::Translate() {
if (traceCode) {
emitComment(">> Const");
}
emitRM("LDC", acc1, value, 0, "load const");
if (traceCode) {
emitComment("<< Const");
}
}
/*
* funkce pro preklad binarni operace
* <, >, ==, !=...
*/
void Bop::Translate() {
if (traceCode) {
emitComment(">> Bop");
}
// generuje se kod leve strany(operandu)
left->Translate();
// store leveho operandu od acc
emitRM("ST", acc1, tmpOffset--, mp, "Bop: push left");
// generuje se kod prave strany(operandu)
right->Translate();
//ulozena leva strana se znovu loadne
emitRM("LD", acc2, ++tmpOffset, mp, "Bop: load left");
switch (op) {
case Plus: //u kazde aritmeticke operace se provede nad obema acc
emitRO("ADD", acc1, acc2, acc1, "Bop: +");
break;
case Minus:
emitRO("SUB", acc1, acc2, acc1, "Bop: -");
break;
case Times:
emitRO("MUL", acc1, acc2, acc1, "Bop: *");
break;
case Divide:
emitRO("DIV", acc1, acc2, acc1, "Bop: /");
break;
case Less: //zde se akorat navic resi, kam se kdy byde skakat
emitRO("SUB", acc1, acc2, acc1, "Bop: <");
emitRM("JLT", acc1, 2, pc, "branch if lower than");
emitRM("LDC", acc1, 0, acc1, "if not");
emitRM("LDA", pc, 1, pc, "jump to end");
emitRM("LDC", acc1, 1, acc1, "if true");
break;
case Eq:
emitRO("SUB", acc1, acc2, acc1, "Bop: ==");
emitRM("JEQ", acc1, 2, pc, "branch if equal");
emitRM("LDC", acc1, 0, acc1, "if not");
emitRM("LDA", pc, 1, pc, "jump to end");
emitRM("LDC", acc1, 1, acc1, "if true");
break;
case NotEq:
emitRO("SUB", acc1, acc2, acc1, "Bop: !=");
emitRM("JNE", acc1, 2, pc, "branch if not equal");
emitRM("LDC", acc1, 0, acc1, "if not");
emitRM("LDA", pc, 1, pc, "jump to end");
emitRM("LDC", acc1, 1, acc1, "if true");
break;
case Greater:
emitRO("SUB", acc1, acc2, acc1, "Bop: >");
emitRM("JGT", acc1, 2, pc, "branch if greater");
emitRM("LDC", acc1, 0, acc1, "if not");
emitRM("LDA", pc, 1, pc, "jump to end");
emitRM("LDC", acc1, 1, acc1, "if true");
break;
case LessOrEq:
emitRO("SUB", acc1, acc2, acc1, "Bop: !=");
emitRM("JLE", acc1, 2, pc, "branch if lower or equal");
emitRM("LDC", acc1, 0, acc1, "if not");
emitRM("LDA", pc, 1, pc, "jump to end");
emitRM("LDC", acc1, 1, acc1, "if true");
break;
case GreaterOrEq:
emitRO("SUB", acc1, acc2, acc1, "Bop: !=");
emitRM("JGE", acc1, 2, pc, "branch if greater or equal");
emitRM("LDC", acc1, 0, acc1, "if not");
emitRM("LDA", pc, 1, pc, "jump to end");
emitRM("LDC", acc1, 1, acc1, "if true");
break;
default:
emitComment("Hodne velka chyba -> Bop switch.");
break;
}
if (traceCode) {
emitComment("<< Bop");
}
}
/*
* unarni minus vlozi do registru nulu
* a od ni odecte hodnotu
*/
void UnMinus::Translate() {
if (traceCode) {
emitComment(">> UnMinus");
}
expr->Translate();
emitRM("LDC", acc2, 0, 0, "UnMinus: load const 0");
emitRO("SUB", acc1, acc2, acc1, "UnMinus: value = 0 - value");
if (traceCode) {
emitComment("<< UnMinus");
}
}
/*
* nejdrive se generuje kod pro vyraz
* vpravo, pak se priradi(udela store)
*/
void Assign::Translate() {
if (traceCode) {
emitComment(">> assign");
}
expr->Translate();
emitRM("ST", acc1, var->getAddr(), gp, "assign: store value");
if (traceCode) {
emitComment("<< assign");
}
}
/*
* funkce generuje prikaz pro vystup
* z nejakeho R
*/
void Write::Translate() {
// vypisuje se vyraz, ktery je potreba nejdrive prelozit(spocitat)
expr->Translate();
emitRO("OUT", acc1, 0, 0, "write ac");
}
/*
* funkce, ktera generuje kod pro podminky
*/
void If::Translate() {
if (traceCode) {
emitComment(">> if");
}
//generuje se kod podminky
cond->Translate();
//ulozi se lokace v kodu na dalsi instrukci
int savedLoc1 = emitSkip(1);
emitComment("if: jump to else belongs here");
//generovani splnene vetve
thenstm->Translate();
int savedLoc2 = emitSkip(1);
emitComment("if: jump to end belongs here");
int currentLoc = emitSkip(0);
emitBackup(savedLoc1);
emitRM_Abs("JEQ", acc1, currentLoc, "if: jmp to else");
emitRestore();
//else je nepovinny
if (elsestm) {
// generuje se nesplnena vetev
elsestm->Translate();
currentLoc = emitSkip(0);
//skoci se zpet
emitBackup(savedLoc2);
//a do pc se load ne spravna hodnota
emitRM_Abs("LDA", pc, currentLoc, "jmp to end");
emitRestore();
} else {
emitBackup(savedLoc1);
emitRestore();
}
if (traceCode) {
emitComment("<< If");
}
}
/*
* funkce, generuje cyklu
*/
void While::Translate() {
if (traceCode) {
emitComment(">> while");
}
int start = emitSkip(0);
cond->Translate();
int ifjump = emitSkip(1);
body->Translate();
emitRM_Abs("LDA", pc, start, "jmp back to cond");
int end = emitSkip(0);
emitBackup(ifjump);
emitRM_Abs("JEQ", acc1, end, "jmp to end");
// restore adresy po tele cyklu -> end
emitRestore();
if (traceCode) {
emitComment("<< While");
}
}
/*
* prochazi cely spojovy seznam prikazu
*/
void StatmList::Translate() {
StatmList *s = this;
do {
if (s->statm != NULL) {
s->statm->Translate();
}
s = s->next;
} while (s);
}
/*
* vstupni bod prekladu
*/
void Prog::Translate() {
fprintf(outputCode, "* TinyMachine Code:\n");
emitRM("LD", mp, 0, acc1, "load memsize from 0");
emitRM("ST", acc1, 0, acc1, "clear location 0");
emitComment("End of standard prelude.");
// generovani z AST od korene stm(zacatatku spojaku)
stm->Translate();
emitComment("End of execution.");
emitRO("HALT", 0, 0, 0, "");
}
Expr *VarOrConst(char *id) {
int v;
DruhId druh = idPromKonst(id, &v);
switch (druh) {
case IdProm:
return new Var(v, true);
case IdKonst:
return new Numb(v);
default:
std::cout << "Chyba: VarOrConst" << std::endl;
return NULL;
}
}
| true |
617820258da44367a2786def98aefb38b611d1b1 | C++ | Leodicap99/leetcode | /Array/1423. Maximum Points You Can Obtain from Cards.cpp | UTF-8 | 618 | 2.859375 | 3 | [] | no_license | Source:- https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/597883/Javascript-and-C%2B%2B-solutions
int maxScore(vector<int>& cardPoints, int k) {
int n=cardPoints.size();
int sum=0,ans=0;
deque<int> dq;
for(int i=n-k;i<n;i++)
{
sum+=cardPoints[i];
dq.push_back(cardPoints[i]);
}
ans=sum;
for(int i=0;i<k;i++)
{
sum-=dq.front();
dq.pop_front();
sum+=cardPoints[i];
ans=max(ans,sum);
}
return ans;
}
| true |
67330d77b06b361c6cb4f98739b668ad21ae1da5 | C++ | engineerkatie/geohashing | /sql/src/cpp/SqliteQuery.cpp | UTF-8 | 1,598 | 2.625 | 3 | [] | no_license | #include "SqliteDb.hpp"
#include "SqliteResults.hpp"
#include "SqliteQuery.hpp"
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
void SqliteQuery::nuke(void)
{
if (q)
{
sqlite3_finalize(q);
//std::cerr << "Finalize Query " << q << std::endl;
}
}
SqliteQuery::SqliteQuery(const std::string &sql, sqlite3 *db)
{
this -> db = db;
auto r = sqlite3_prepare_v2(
this -> db, /* Database handle */
sql.c_str(), /* SQL statement, UTF-8 encoded */
-1, /* Maximum length of zSql in bytes, -1 means null terminated */
&(this -> q), /* OUT: Statement handle */
NULL /* OUT: Pointer to unused portion of zSql */
);
if (r != SQLITE_OK)
{
std::cerr << "Error: " << r << " - "<< sqlite3_errmsg(this -> db) << std::endl;
nuke();
return;
}
}
SqliteQuery *SqliteQuery::bind(std::size_t index, const void *data, std::size_t size)
{
sqlite3_bind_blob(q, index, data, size, SQLITE_TRANSIENT);
return this;
}
SqliteQuery *SqliteQuery::bind(std::size_t index, const std::string &v)
{
sqlite3_bind_text(q, index, v.c_str(), v.length(), SQLITE_TRANSIENT);
return this;
}
std::shared_ptr<SqliteResults> SqliteQuery::run()
{
auto r = std::make_shared<SqliteResults>(shared_from_this(), q);
r -> next();
return r;
}
std::string SqliteQuery::getLastErrorMessage(void) const
{
return std::string(sqlite3_errmsg(db));
}
| true |
5ac16f68e5a94c64af5e56bcb539dc9ce1f22e22 | C++ | Terune/Cooktalk_system_server | /stack.h | UTF-8 | 1,899 | 3.9375 | 4 | [] | no_license | #pragma once
#include <cstddef>
template <typename Object>
class Stack
{
protected:
// 리스트의 노드
//
struct Node
{
Object obj;
Node* next;
};
typedef Node* NodePtr;
public:
Stack();
virtual ~Stack();
void push(const Object& o);
void pop();
Object& top();
const Object top() const;
int size() const;
bool empty() const;
private:
NodePtr top_;
int size_;
};
// 생성자(): top_과 size_를 초기화한다.
//
template <typename Object>
Stack<Object>::Stack() : top_(NULL), size_(0) {}
// 소멸자(): 남은 원소가 없을 때까지 pop한다. (메모리 누수 방지)
//
template <typename Object>
Stack<Object>::~Stack()
{
while (size_ > 0)
pop();
}
// push(): 입력받은 데이터를 노드로 만들어 스택에 넣는다.
//
template <typename Object>
void Stack<Object>::push(const Object& o)
{
NodePtr tmp = new Node;
tmp->obj = o;
tmp->next = empty()? NULL : top_;
top_ = tmp;
size_++;
}
// pop(): 맨 위의 원소를 리스트에서 제거하고 힙에 할당한 메모리를 해제한다.
//
template <typename Object>
void Stack<Object>::pop()
{
NodePtr tmp = top_;
top_ = top_->next;
size_--;
delete tmp;
}
// top(): 맨 위의 원소를 반환한다.
//
template <typename Object>
Object& Stack<Object>::top()
{
return top_->obj;
}
// top(): 맨 위의 원소를 상수 객체로 반환한다.
template <typename Object>
const Object Stack<Object>::top() const
{
return top_->obj;
}
// size(): 스택에 저장된 데이터의 개수를 반환한다.
//
template <typename Object>
int Stack<Object>::size() const
{
return size_;
}
// empty(): 스택이 비었으면 true, 아니면 false를 반환한다.
//
template <typename Object>
bool Stack<Object>::empty() const
{
return (size_ == 0);
}
| true |
23f95140bb223924a446be2378734b65774c868e | C++ | osmpradeep/wifitimerwithrtc | /timer_auto_priority_mode_esp8285_update_20_7_19/Rtc_custom.ino | UTF-8 | 1,581 | 2.703125 | 3 | [] | no_license |
void read_rtc_Time_date()
{
// Reset the register pointer
Wire.beginTransmission(rtc);
Wire.write(0x10);
Wire.endTransmission();
Wire.requestFrom(rtc, 7);
// A few of these need masks because certain bits are control bits
rtc_second = bcdToDec(Wire.read());
rtc_minute = bcdToDec(Wire.read());
rtc_hour = bcdToDec(Wire.read()); // Need to change this if 12 hour am/pm
rtc_day = bcdToDec(Wire.read());
rtc_date = bcdToDec(Wire.read());
rtc_month = bcdToDec(Wire.read());
rtc_year = bcdToDec(Wire.read());
Serial.print(rtc_hour);
Serial.print(":");
Serial.print(rtc_minute);
Serial.print(":");
Serial.print(rtc_second);
Serial.print(" ");
Serial.print(rtc_month);
Serial.print("/");
Serial.print(rtc_date);
Serial.print("/");
Serial.print(rtc_year);
Serial.print(" Day_of_week:");
Serial.println(rtc_day);
}
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}
void set_rtc_Time_date(byte second, byte minute, byte hour, byte day, byte date, byte month,byte year) // 0-59,0-59,1-23,1-7,1-28/29/30/31,1-12,0-99
{
Wire.beginTransmission(rtc);
Wire.write(0x10);
Wire.write(decToBcd(second)); // 0 to bit 7 starts the clock
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour));
Wire.write(decToBcd(day));
Wire.write(decToBcd(date));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));
Wire.endTransmission();
}
| true |
c63052dfdbaa614246cba58b461ef0aa8f4bc04c | C++ | ronee12/Code-Library | /My_code/Online judge solutions/Codeforces/102.2A.cpp | UTF-8 | 626 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int r1,r2,c1,c2,d1,d2;
int a,b,c,d;
cin>>r1>>r2>>c1>>c2>>d1>>d2;
set<int>l;
a=(r1-d2+c1)/2;
if(a>0&&a<10)
l.insert(a);
b=(r1+d2-c1)/2;
if(b>0&&b<10)
l.insert(b);
c=(d2-r1+c1)/2;
if(c>0&&c<10)
l.insert(c);
d=(2*r2-d2+r1-c1)/2;
if(d>0&&d<10)
l.insert(d);
if(l.size()==4)
{
if(a+b==r1&&c+d==r2&&a+c==c1&&b+d==c2&&a+d==d1&&c+b==d2)
cout<<a<<" "<<b<<endl<<c<<" "<<d<<endl;
else
cout<<-1<<endl;
}
else
cout<<-1<<endl;
return 0;
}
| true |
ff5930b6020e7bb166116e1b8b18763c281cdad1 | C++ | IzYoBoiJay/ASCII-Space-Shooter | /include/Enemy.h | UTF-8 | 907 | 3.09375 | 3 | [] | no_license | /*
* Author: Jhun-Thomas Calahatian
* Program Description / Purpose: Enemy.h header file for the ASCII space shooter that handles the enemy objects and enemy-related chance events.
*/
#ifndef ENEMY_H
#define ENEMY_H
#include "Entity.h"
#include "Item.h"
class Enemy: public Entity {
private:
//Enemy bullet position
int bulletShotY, bulletShotX;
public:
//Parameterized enemy constructor
Enemy(WINDOW* window, char symbol);
//Override movement pure virtual fuction of entity
int movement() override;
//Draw Enemy
void drawEnemy();
//Enemy Shoot Function
void shoot();
//Resets bullet position (Setter)
void reset_bullet() {
this->bulletShotY = 0;
this->bulletShotX = 0;
}
//Getters
int get_bullet_yPos() const {
return bulletShotY;
}
int get_bullet_xPos() const {
return bulletShotX;
}
};
#endif | true |
90b485912450523ae5f6cfef1e82b6d2e909336c | C++ | computerphilosopher/dfa | /CompilerHomework/main.cpp | UTF-8 | 8,750 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstring>
#include "table_driven.h"
using namespace std;
/* 파일을 문자열의 벡터로 바꾸어주는 클래스*/
class Tokenizer {
private:
vector <string> tokens;
string filePath;
public:
Tokenizer(string filePath) {
this->filePath = filePath;
}
void ToTokens() {
ifstream stream(filePath, ios::in);
string word;
while (stream >> word) {
tokens.push_back(word);
}
stream.close();
}
vector<string> GetTokens() {
return tokens;
}
};
class DFA {
private:
vector<string> tokens;
Table table;
vector<string> result;
int count_result;
public:
DFA(vector<string> tokens, Table table) {
this->tokens = tokens;
this->table = table;
}
~DFA() {
}
void run() {
int size = tokens.size();
State state = table.start_state();
string temp = "";
for (int i = 0; i < size; i++) {
State newState = table.get_next(state, tokens[i]);
if (newState != table.start_state()) {
temp.append(tokens[i]);
temp.append(" "); //공백 추가
}
else {//new_state == START
if (table.is_accept(state)) {
result.push_back(temp);
}
temp.clear();
}
if (table.is_accept(newState) && !temp.empty()) {
result.push_back(temp);
temp.clear();
}
state = newState;
}
}
void print_result() {
if (result.empty()) {
cout << "result is empty" << endl;
return;
}
int size = result.size();
for (int i = 0; i < size; i++) {
cout << result[i] << endl;
}
cout << result.size() << endl;
}
void write_to_file(string filePath) {
ofstream stream;
stream.open(filePath, ios::trunc);
int size = result.size();
int j = 1;
for (int i = 0; i < size; i++) {
if (j > 20) {
break;
}
string temp = "(" + to_string(j) + ")";
if (!result[i].empty()) {
stream << temp + result[i] << endl;
j++;
}
}
string temp = "total data pattern: ";
stream << temp + to_string(result.size());
}
};
enum SYMBOLS {
ADD, SUB, MUL, DIV, MOD,
EQUAL, MORE, LESS, AND, OR, NOT,
SEMI, COM, SMALL_X, LARGE_X,
LEFT_PAREN, RIGHT_PAREN, LEFT_CURL, RIGHT_CURL, LEFT_SQUARE, RIGHT_SQUARE,
BACK_SLASH, QUOTE, DOUBLE_QUOTE,
ALPHABET, LETTER,
DIGIT, ZERO, NON_ZERO, HEX,
NOT_TOKEN
};
enum STATES {
START,
IN_ASSIGN, IN_MORE, IN_LESS, IN_NOT, IN_ID, IN_AND, IN_OR,
IN_CHAR, IN_CHAR2, ESCAPE_CHAR,
IN_STRING, ESCAPE_STRING,
IN_ZERO, IN_DECIMAL, IN_HEX,
ACC_ADD, ACC_SUB, ACC_MUL, ACC_DIV, ACC_MOD,
ACC_ASSIGN, ACC_EQUAL, ACC_MORE, ACC_EQUAL_MORE, ACC_LESS, ACC_EQUAL_LESS,
ACC_NOT, ACC_NOT_EQUAL, ACC_AND, ACC_OR,
ACC_SEMI, ACC_COM,
ACC_LEFT_PAREN, ACC_RIGHT_PAREN, ACC_LEFT_CURL, ACC_RIGHT_CURL, ACC_LEFT_SQUARE, ACC_RIGHT_SQUARE,
ACC_ID, ACC_CHAR, ACC_STRING,
ACC_DECIMAL, ACC_HEX, ACC_ZERO
};
void table_set(Table &table) {
for (int i = SYMBOLS::ADD; i <= NOT_TOKEN; i++) {
State range = START;
switch (i) {
case ADD:
range = ACC_ADD;
break;
case SUB:
range = ACC_SUB;
break;
case MUL:
range = ACC_MUL;
break;
case DIV:
range = ACC_DIV;
break;
case MOD:
range = ACC_MOD;
break;
case EQUAL:
range = IN_ASSIGN;
break;
case MORE:
range = IN_MORE;
break;
case LESS:
range = IN_LESS;
break;
case NOT:
range = IN_NOT;
break;
case AND:
range = IN_AND;
break;
case OR:
range = IN_OR;
break;
case SEMI:
range = ACC_SEMI;
break;
case COM:
range = COM;
break;
case LEFT_PAREN:
range = ACC_LEFT_PAREN;
break;
case RIGHT_PAREN:
range = ACC_LEFT_PAREN;
break;
case LEFT_CURL:
range = ACC_LEFT_CURL;
break;
case RIGHT_CURL:
range = ACC_RIGHT_CURL;
break;
case LEFT_SQUARE:
range = ACC_LEFT_SQUARE;
break;
case RIGHT_SQUARE:
range = ACC_RIGHT_SQUARE;
break;
case QUOTE:
range = IN_CHAR;
break;
case DOUBLE_QUOTE:
range = IN_STRING;
break;
case ALPHABET:
range = IN_ID;
break;
case ZERO:
range = IN_ZERO;
case NON_ZERO:
range = IN_DECIMAL;
break;
}
table.map_state(START, i, range);
}
table.map_other(STATES::IN_ASSIGN, SYMBOLS::EQUAL, STATES::ACC_ASSIGN);
table.map_state(STATES::IN_ASSIGN, SYMBOLS::EQUAL, STATES::ACC_EQUAL);
table.map_other(STATES::IN_MORE, SYMBOLS::EQUAL, STATES::ACC_MORE);
table.map_state(STATES::IN_MORE, SYMBOLS::EQUAL, STATES::ACC_EQUAL_MORE);
table.map_other(STATES::IN_LESS, SYMBOLS::EQUAL, STATES::ACC_LESS);
table.map_state(STATES::IN_LESS, SYMBOLS::EQUAL, STATES::ACC_EQUAL_LESS);
table.map_other(STATES::IN_NOT, SYMBOLS::EQUAL, STATES::ACC_NOT);
table.map_state(STATES::IN_NOT, SYMBOLS::EQUAL, STATES::ACC_NOT_EQUAL);
table.map_state(STATES::IN_AND, SYMBOLS::AND, STATES::ACC_AND);
table.map_state(STATES::IN_OR, SYMBOLS::OR, STATES::ACC_OR);
table.map_other(STATES::IN_ID, SYMBOLS::LETTER, STATES::ACC_ID);
table.map_state(STATES::IN_ID, SYMBOLS::LETTER, STATES::IN_ID);
table.map_state(STATES::IN_CHAR, SYMBOLS::LETTER, STATES::IN_CHAR2);
table.map_state(STATES::IN_CHAR2, SYMBOLS::BACK_SLASH, STATES::ESCAPE_CHAR);
table.map_state(STATES::IN_CHAR2, SYMBOLS::QUOTE, STATES::ACC_CHAR);
table.map_state(STATES::ESCAPE_CHAR, SYMBOLS::LETTER, IN_CHAR2);
table.map_state(STATES::IN_STRING, SYMBOLS::BACK_SLASH, STATES::ESCAPE_STRING);
table.map_state(STATES::IN_STRING, SYMBOLS::DOUBLE_QUOTE, STATES::ACC_STRING);
table.map_state(STATES::ESCAPE_STRING, SYMBOLS::LETTER, STATES::IN_STRING);
table.map_other(STATES::IN_DECIMAL, SYMBOLS::DIGIT, STATES::ACC_DECIMAL);
table.map_state(STATES::IN_DECIMAL, SYMBOLS::DIGIT, STATES::IN_DECIMAL);
table.map_state(STATES::IN_ZERO, SYMBOLS::SMALL_X, STATES::IN_HEX);
table.map_state(STATES::IN_ZERO, SYMBOLS::LARGE_X, STATES::IN_HEX);
table.map_other(STATES::IN_HEX, SYMBOLS::HEX, ACC_HEX);
table.map_state(STATES::IN_HEX, SYMBOLS::HEX, STATES::IN_HEX);
State arr[29] = { ACC_ADD, ACC_SUB, ACC_MUL, ACC_DIV, ACC_MOD,
ACC_ASSIGN, ACC_EQUAL, ACC_MORE, ACC_EQUAL_MORE, ACC_LESS, ACC_EQUAL_LESS,
ACC_NOT, ACC_NOT_EQUAL, ACC_AND, ACC_OR,
ACC_SEMI, ACC_COM,
ACC_LEFT_PAREN, ACC_RIGHT_PAREN, ACC_LEFT_CURL, ACC_RIGHT_CURL, ACC_LEFT_SQUARE, ACC_RIGHT_SQUARE,
ACC_ID, ACC_CHAR, ACC_STRING,
ACC_DECIMAL, ACC_HEX, ACC_ZERO };
table.set_accept(arr, 29);
}
void add_symbolSet() {
}
int main() {
Tokenizer tokenizer("lexer_test.txt");
tokenizer.ToTokens();
vector<string> tokens = tokenizer.GetTokens();
const vector<string> specialSymbol = { "+", "-", "*", "/", "%",
"=", ">", "<", "&", "|", "!",
";", ",", "x", "X",
"(", ")", "{", "}", "[", "]",
"\\", "'", "\""
};
const vector<string> symbolName = {
"ADD", "SUB", "MUL", "DIV", "MOD",
"EQUAL", "MORE", "LESS", "AND", "OR", "NOT",
"SEMI", "COM", "x", "X",
"LEFT_PAREN", "RIGHT_PAREN", "LEFT_CURL", "RIGHT_CURL", "LEFT_SQUARE", "RIGHT_SQUARE",
"BACK_SLASH", "QUOTE", "DOUBLE_QUOTE",
"ALPHABET", "LETTER",
"DIGIT", "ZERO", "NON_ZERO", "HEX",
};
vector <SymbolSet> specialSymbolSet;
for (int i = SYMBOLS::ADD; i <= SYMBOLS::DOUBLE_QUOTE; i++) {
SymbolSet temp(symbolName[i], i, specialSymbol[i]);
specialSymbolSet.push_back(temp);
}
vector<string> alphabetString;
vector<string> digitString;
vector<string> hexString;
vector<string> nonzeroString;
for (int i = 0; i <= 9; i++) {
char c = i - '0';
string s(1, c);
digitString.push_back(s);
hexString.push_back(s);
if (i > 0) {
nonzeroString.push_back(s);
}
}
for (char i = 'A'; i <= 'Z'; i++) {
string capital(1, i);
string small(1, i + ' ');
alphabetString.push_back(capital);
if (i <= 'F') {
hexString.push_back(capital);
}
alphabetString.push_back(small);
}
/* letter = (alphabet | digit) */
vector<string> letterString(digitString.size() + alphabetString.size());
letterString.insert(letterString.end(), alphabetString.begin(), alphabetString.end());
letterString.insert(letterString.end(), digitString.begin(), digitString.end());
SymbolSet alphabet("ALPHABET", SYMBOLS::ALPHABET, alphabetString);
SymbolSet digit("DIGIT", SYMBOLS::DIGIT, digitString);
SymbolSet letter("LETTER", SYMBOLS::LETTER, letterString);
SymbolSet nonZero("NON_ZERO", SYMBOLS::NON_ZERO, nonzeroString);
SymbolSet hex("HEX", SYMBOLS::HEX, hexString);
SymbolSet zero("ZERO", SYMBOLS::ZERO, "0");
Table table(STATES::ACC_ZERO + 1, SYMBOLS::NOT_TOKEN + 1, STATES::START);
for (int i = 0; i < specialSymbolSet.size(); i++) {
table.add_symbol(specialSymbolSet[i]);
}
table.add_symbol(alphabet);
table.add_symbol(letter);
table.add_symbol(digit);
table.add_symbol(nonZero);
table.add_symbol(hex);
table.add_symbol(zero);
table_set(table);
DFA dfa(tokens, table);
dfa.run();
dfa.print_result();
getchar();
}
| true |
302092d341851debe7c9641102f33abcb578cd77 | C++ | JustinYuu/PAT-Basic | /1091.cpp | UTF-8 | 468 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int m,k;
int n,res;
cin>>m;
for(int i=0;i<m;++i)
{
cin>>k;
for(n=1;n<10;++n)
{
res=k*k*n;
if(res%10==k||res%100==k||res%1000==k)
{
cout<<n<<' '<<res<<endl;
break;
}
}
if(n==10)
cout<<"No"<<endl;
}
return 0;
}
| true |
b2ce2c43472c7141206d5636c55f1a68a20102e8 | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/23/165.c | UTF-8 | 303 | 2.765625 | 3 | [] | no_license | void main()
{
char a[100][10]={'\0'},c;
int i,j;
i=0;j=0;
c='A';
while(c!='\n')
{
scanf("%c",&c);
if(c!=' '&&c!='\n')
{
a[i][j]=c;
j=j+1;
}
else if(c==' ')
{
i=i+1;
j=0;
}
}
for(j=i;j>0;j=j-1)
{
printf("%s ",a[j]);
}
printf("%s",a[0]);
}
| true |
7f84511133950f417aecce893562b9d2e3ad3de7 | C++ | NaomyTiaraDewi/sorting | /sorting.cpp | UTF-8 | 647 | 2.859375 | 3 | [] | no_license | /*
1717051007-Oktaviana
1717051021-Brenda Natalia
1717051033-Cahyani Ramadhani
1717051045-Naomy Tiara Dewi
Link : https://github.com/oktaviana1007/sorting/edit/master/sorting.cpp
*/
#include <iostream>
using namespace std;
void selection(int a[],int x){
for(int i=0;i<x;i++){
for(int j=i+1;j<x;j++){
if(a[i]>a[j]){
int p=a[i];
a[i]=a[j];
a[j]=p;
}
}
}
}
void bubble(int a[],int x){
for(int i=0;i<x;i++){
for(int j=0;j<x-1;j++){
if(a[j]>a[j+1]){
int ptr=a[j];
a[j]=a[j+1];
a[j+1]=ptr;
}
}
}
}
int main(){
int n;
cin>>n;
selection(a,n);
tampil(a,n);
bubble(a,n);
tampil(a,n);
return 0;
}
| true |
51a7bf213a63c9387d1c250eb1832733180311e3 | C++ | Junhyung-Choi/CPP_TRAINING | /Chapter01/3/Question1_3_2.cpp | UTF-8 | 375 | 2.59375 | 3 | [] | no_license | #include <iostream>
int SimpleFunc(int a = 10)
{
return a + 1;
}
int SimpleFunc(void)
{
return 10;
}
// Compileation is performed because the condition of function overloading is statisfied.
// However if a fucntion is called without passing an argument as follows,
// a compile error occurs whenever both functions satisfy the calling condition.
// SimpleFunc();
| true |
d6a4bf1848f63b509247540125bb98a851d8ad1f | C++ | yoannfleurydev/univ2016-2017 | /cplusplus/tp/tp3/Hiring.h | UTF-8 | 321 | 2.828125 | 3 | [] | no_license | #ifndef TP3_HIRING_H
#define TP3_HIRING_H
#include "Employee.h"
class Hiring : public Employee {
public:
inline Hiring(int idNumber = 0, const char * ch = "") : Employee(ch), idNumber(idNumber) {}
void put_ident(int i);
virtual void print() override;
private:
int idNumber;
};
#endif //TP3_HIRING_H
| true |
60dfb947eea36b7a86cf69c4d5ac924d497a3f92 | C++ | WhiteCatFly/Student-Code-RUC | /The third Homework/何宗炎-2017201974/HashValueSet.h | UTF-8 | 411 | 2.578125 | 3 | [] | no_license | #ifndef HashValueSet_Hzy_H_
#define HashValueSet_Hzy_H_
#include "Hzydef.h"
#include <bits/stdc++.h>
class HashValueSet {
private:
LL Value1, Value2 ;
public:
HashValueSet(LL v1, LL v2) : Value1(v1), Value2(v2) {}
~HashValueSet() {}
bool operator < (const HashValueSet p) const {
if(Value1 == p.Value1) return Value2 < p.Value2;
else return Value1 < p.Value1;
}
};
#else
#endif
| true |
c5ac614967d990688edf9e70221e8a6c89816cd4 | C++ | zhangshy/opencvStepByStep | /src/testMethod.cpp | UTF-8 | 22,778 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include "testMethod.h"
#include "mathTest.h"
#include "histRedistribute.h"
using namespace std;
namespace zsyTestMethod {
string getTestMethodVersion() {
return "libtestMethod.so version0.2";
}
/**
一般按加权的方法转换,R , G ,B 的比一般为3:6:1将图片转化为灰度图片
*/
Mat changRGB2Gray(const Mat src) {
//取得像素点的行列数和通道数
int nrow = src.rows;
int ncol = src.cols;
int channels = src.channels(); //通道数,在OpenCV中,一张3通道图像的一个像素点是按BGR的顺序存储的
Mat dst(nrow, ncol, CV_8UC1);
int i=0, j=0;
//typedef Vec<uchar, 3> Vec3b;
//uchar* Mat::ptr(int i=0) i 是行号,返回的是该行数据的指针
for (i=0; i<nrow; i++) {
uchar* data_out = dst.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
Vec3b bgrSrc = src.at<Vec3b>(i, j); //取得像素点的RGB值, 在OpenCV中,一张3通道图像的一个像素点是按BGR的顺序存储的
//data_out[j] = (bgrSrc[0]*11+bgrSrc[1]*59+bgrSrc[2]*30)/100; //Gray=(R*30+G*59+B*11)/100
data_out[j] = (bgrSrc[0]*28+bgrSrc[1]*151+bgrSrc[2]*77)>>8; //移位方法
}
}
return dst;
}
/**
* 输入为单通道Mat, 直方图均衡化
* 参考: http://zh.wikipedia.org/wiki/%E7%9B%B4%E6%96%B9%E5%9B%BE%E5%9D%87%E8%A1%A1%E5%8C%96
* 修改:因为变换函数是由[0, 255]-->[0, 255],可以先创建数组并计算对应值,通过查表即可获得对应变换值
*/
Mat histogramEqualizate(const Mat src) {
//取得像素点的行列数和通道数
int nrow = src.rows;
int ncol = src.cols;
int channel = src.channels();
Mat dst(nrow, ncol, CV_8UC1); //直方图均衡化后的图像
if (channel != 1) {
cout << "请输入单通道矩阵,当前图像为channel is: " << channel << endl;
return dst;
}
uchar convertBuf[256] = {0};
getHistEqualConvert(src, convertBuf, false);
int i=0, j=0;
for (i=0; i<nrow; i++) {
const uchar* data_in = src.ptr<uchar>(i);
uchar* data_out = dst.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
// data_out[j] = ((cdfPixelValue[data_in[j]]-cdfMin)*255)/divNum;
data_out[j] = convertBuf[data_in[j]];
}
}
return dst;
}
/**
*@brief CLAHE自适应直方图均衡化
*@param src 单通道的Mat
*@param bIsCLAHE true使用CLAHE,false使用AHE
* 1. 将图像分成8*8块
* 2. 计算各块的变换函数
*/
Mat cladaptHistEqual(const Mat src, int method) {
int nrow = src.rows; //图像的高度
int ncol = src.cols; //列数,宽
int channel = src.channels();
Mat dst = Mat::zeros(nrow, ncol, CV_8UC1);
if (channel != 1) {
cout << "请输入单通道矩阵,当前图像为channel is: " << channel << endl;
return dst;
}
#if 0
/** 测试Mat Rect的使用 */
Mat tmpdst = histogramEqualizate(src(Rect(0, 0, ncol/4, nrow/4)));
tmpdst.copyTo(dst(Rect(0, 0, ncol/4, nrow/4)));
return dst;
#endif
//分成8*8块
int perRow = nrow/PERNUM;
int perCol = ncol/PERNUM;
/** 对应块的变换函数 */
uchar histEqualConvertBufs[PERNUM*PERNUM][256] = {0};
/** 对应块的中心点行列(x,y) */
int areaCenters[PERNUM*PERNUM][2] = {0};
// Mat tmpSrc = Mat::zeros(perRow, perCol, CV_8UC1);
int i=0, j=0;
int r=0, c=0;
for (i=0; i<PERNUM; i++) {
for (j=0; j<PERNUM; j++) {
// cout << "i: " << i << ";j: " << j << endl;
/** 注意赋值top-left = 50,50 size=100,50: Rect(50,50,100,50)
* size为Size(cols, rows),其第一个参数为cols,即图像的宽度。即Mat大小先是高度然后是宽度,而size大小显示宽度然后是高度。
*/
Mat tmpSrc = src(Rect(j*perCol, i*perRow, perCol, perRow)); ///使用数据副本:Mat image2 = image1(Rect(2,2,99,99)).clone();
// Mat tmpSrc = src(Rect(0, 399, 50, 57));
areaCenters[i*PERNUM+j][0] = i*perRow + perRow/2;
areaCenters[i*PERNUM+j][1] = j*perCol + perCol/2;
switch (method) {
case ATUOCUTVALUE:
getAutoCutConvert(tmpSrc, histEqualConvertBufs[i*PERNUM+j]);
break;
default:
getHistEqualConvert(tmpSrc, histEqualConvertBufs[i*PERNUM+j], true);
}
}
}
int uRIndex = PERNUM - 1; //右上角upper right corner
int lLIndex = (PERNUM-1)*PERNUM; //左下角lower left corner
int lRIndex = PERNUM*PERNUM-1; //右下角lower right corner
int r1=0, r2=0, c1=0, c2=0;
int k=0, t=0;
uchar z11=0, z12=0, z21=0, z22=0, zii=0;
for (i=0; i<nrow; i++) {
const uchar* data_in = src.ptr<uchar>(i);
uchar* data_out = dst.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
if ((i<=areaCenters[0][0]) && (j<=areaCenters[0][1])) {
data_out[j] = histEqualConvertBufs[0][data_in[j]]; ///左上角使用所在矩阵编号0的变换函数
} else if ((i<=areaCenters[uRIndex][0]) && (j>=areaCenters[uRIndex][1])) {
data_out[j] = histEqualConvertBufs[uRIndex][data_in[j]]; ///右上角使用所在矩阵编号uRIndex的变换函数
} else if ((i>=areaCenters[lLIndex][0]) && (j<=areaCenters[lLIndex][1])) {
data_out[j] = histEqualConvertBufs[lLIndex][data_in[j]]; ///左下角使用所在矩阵编号lLIndex的变换函数
} else if ((i>=areaCenters[lRIndex][0]) && (j>=areaCenters[lRIndex][1])) {
data_out[j] = histEqualConvertBufs[lRIndex][data_in[j]]; ///右下角使用所在矩阵编号lRIndex的变换函数
} else if ((i<=areaCenters[0][0]) && (j>=areaCenters[0][1]) && (j<=areaCenters[uRIndex][1])) {
for (k=0; k<uRIndex; k++) {
if ((j>=areaCenters[k][1]) && (j<=areaCenters[k+1][1])) {
//使用线性插值,计算两点和对应的值
c1 = areaCenters[k][1];
c2 = areaCenters[k+1][1];
z11 = histEqualConvertBufs[k][data_in[j]];
z12 = histEqualConvertBufs[k+1][data_in[j]];
break;
}
}
data_out[j] = z11 + (z12-z11)*(j-c1)/(c2-c1);
} else if ((i>=areaCenters[lLIndex][0]) && (j>=areaCenters[lLIndex][1]) && (j<=areaCenters[lRIndex][1])) {
for (k=lLIndex; k<lRIndex; k++) {
if ((j>=areaCenters[k][1]) && (j<=areaCenters[k+1][1])) {
//使用线性插值,计算两点和对应的值
c1 = areaCenters[k][1];
c2 = areaCenters[k+1][1];
z11 = histEqualConvertBufs[k][data_in[j]];
z12 = histEqualConvertBufs[k+1][data_in[j]];
break;
}
}
data_out[j] = z11 + (z12-z11)*(j-c1)/(c2-c1);
} else if ((j<=areaCenters[0][1]) && (i>=areaCenters[0][0]) && (i<=areaCenters[lLIndex][0])) {
for (k=0; k<lLIndex; k+=PERNUM) {
if ((i>=areaCenters[k][0]) && (i<=areaCenters[k+PERNUM][0])) {
r1 = areaCenters[k][0];
r2 = areaCenters[k+PERNUM][0];
z11 = histEqualConvertBufs[k][data_in[j]];
z21 = histEqualConvertBufs[k+PERNUM][data_in[j]];
data_out[j] = z11 + (z21-z11)*(i-r1)/(r2-r1);
break;
}
}
} else if ((j>=areaCenters[uRIndex][1]) && (i>=areaCenters[uRIndex][0]) && (i<=areaCenters[lRIndex][0])) {
for (k=uRIndex; k<lRIndex; k+=PERNUM) {
if ((i>=areaCenters[k][0]) && (i<=areaCenters[k+PERNUM][0])) {
r1 = areaCenters[k][0];
r2 = areaCenters[k+PERNUM][0];
z11 = histEqualConvertBufs[k][data_in[j]];
z21 = histEqualConvertBufs[k+PERNUM][data_in[j]];
data_out[j] = z11 + (z21-z11)*(i-r1)/(r2-r1);
break;
}
}
} else {
//行
for (k=0; k<PERNUM; k++) {
if ((i>=areaCenters[k*PERNUM][0]) && (i<=areaCenters[k*PERNUM+PERNUM][0])) {
break;
}
}
//列
for (t=0; t<PERNUM; t++) {
if ((j>=areaCenters[t][1]) && (j<=areaCenters[t+1][1])) {
break;
}
}
//行
c1 = areaCenters[k*PERNUM][0];
c2 = areaCenters[k*PERNUM+PERNUM][0];
//列
r1 = areaCenters[t][1];
r2 = areaCenters[t+1][1];
//计算四个点的值
z11 = histEqualConvertBufs[k*PERNUM+t][data_in[j]];
z12 = histEqualConvertBufs[k*PERNUM+t+1][data_in[j]];
z21 = histEqualConvertBufs[k*PERNUM+PERNUM+t][data_in[j]];
z22 = histEqualConvertBufs[k*PERNUM+PERNUM+t+1][data_in[j]];
bilinearInterpolation(c1, r1, c2, r2, i, j, z11, z12, z21, z22, &zii);
data_out[j] = zii;
}
// cout << " x: " << xi << " y: " << yi << " x1: " << x1 << " x2: " << x2\
// << " y1: " << y1 << " y2: " << y2<< endl;
// bilinearInterpolation(x1, y1, x2, y2, xi, yi, z11, z12, z21, z22, &zii);
// bilinearInterpolation(x1*perRow+perRow/2, y1*perRow+perRow/2, x2*perRow+perRow/2, y2*perRow+perRow/2, i, j, z11, z12, z21, z22, &zii);
}
}
return dst;
}
//参考http://zh.wikipedia.org/wiki/HSL%E5%92%8CHSV%E8%89%B2%E5%BD%A9%E7%A9%BA%E9%97%B4#.E4.BB.8ERGB.E5.88.B0HSL.E6.88.96HSV.E7.9A.84.E8.BD.AC.E6.8D.A2
Mat rgb2hsv(const Mat src) {
int nrow = src.rows;
int ncol = src.cols;
Mat tmpMat;
tmpMat = Mat::zeros(nrow, ncol, CV_32FC3); //转换为float类型,hsv是float型
src.convertTo(tmpMat, CV_32FC3, 1/255.0);
Mat dst;
dst = Mat::zeros(nrow, ncol, CV_32FC3);
int i=0, j=0;
float r, g, b;
float h, s, v;
for (i=0; i<nrow; i++) {
for (j=0; j<ncol; j++) {
Vec3f bgrSrc = tmpMat.at<Vec3f>(i, j); //BGR顺序排列
b = bgrSrc[0];
g = bgrSrc[1];
r = bgrSrc[2];
perrgb2hsv(r, g, b, &h, &s, &v);
Vec3f &bgrDst = dst.at<Vec3f>(i, j);
bgrDst[0] = h;
bgrDst[1] = s;
bgrDst[2] = v;
}
}
return dst;
}
Mat hsv2rgb(const Mat src) {
int nrow = src.rows;
int ncol = src.cols;
Mat tmpMat;
tmpMat = Mat::zeros(nrow, ncol, CV_32FC3);
Mat dst;
dst = Mat::zeros(nrow, ncol, CV_8UC3);
int i=0, j=0;
float r, g, b;
float h, s, v;
for (i=0; i<nrow; i++) {
for (j=0; j<ncol; j++) {
Vec3f bgrSrc = src.at<Vec3f>(i, j);
h = bgrSrc[0];
s = bgrSrc[1];
v = bgrSrc[2];
perhsv2rgb(h, s, v, &r, &g, &b);
Vec3f &bgrDst = tmpMat.at<Vec3f>(i, j); //BGR顺序排列
bgrDst[0] = b;
bgrDst[1] = g;
bgrDst[2] = r;
}
}
tmpMat.convertTo(dst, CV_8UC3, 255);
return dst;
}
/**
RGB图像直方图均衡,在HSV模式下将V均衡化
测试后发现有些颜色变浅或变浅了??效果不是很理想
*/
Mat rgbHistogramEqualizate(const Mat src, int method) {
int nrow = src.rows;
int ncol = src.cols;
//1. 将RGB转化为HSV,CV_32FC3,v:[0, 1]
Mat hsvSrc = rgb2hsv(src);
//2. 将V通道均衡,提取V通道:[0, 255]
int i=0, j=0;
Mat vSrc(nrow, ncol, CV_8UC1);
for (i=0; i<nrow; i++) {
uchar* data_out = vSrc.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
Vec3f hsv = hsvSrc.at<Vec3f>(i, j);
data_out[j] = hsv[2]*255;
}
}
//V通道直方图均衡化
Mat vDst;
switch (method) {
case HE:
vDst = histogramEqualizate(vSrc);
break;
case AHE:
vDst = cladaptHistEqual(vSrc, CLAHEMETHOD);
break;
case CLAHEMETHOD:
vDst = cladaptHistEqual(vSrc, CLAHEMETHOD);
break;
/*
case CLAHEMETHOD: {
//使用opencv自带的CLAHE进行测试
Ptr<CLAHE> clahe = createCLAHE();
clahe->setClipLimit(1.0);
clahe->setTilesGridSize(Size(8, 8));
clahe->apply(vSrc, vDst);
break;
}
*/
case USEACE:
vDst = useACE(vSrc, false);
break;
case USEACEWITHLSD:
vDst = useACE(vSrc, true);
break;
default:
vDst = histogramEqualizate(vSrc);
}
//将V通道放入hsv中, v: [0, 1]
for (i=0; i<nrow; i++) {
uchar* data_out = vDst.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
Vec3f &hsv = hsvSrc.at<Vec3f>(i, j);
hsv[2] = data_out[j]/255.0;
}
}
//3. 将HSV转化为RGB
Mat dst = hsv2rgb(hsvSrc);
return dst;
}
/**
* 彩色图像均衡,转化为灰度图像均衡后按原比例还原为RGB图像
* 效果好像还不如均衡hsv中的v通道??
*/
Mat rgbHistogramEqualizateGray(const Mat src, int method) {
int nrow = src.rows;
int ncol = src.cols;
int i=0, j=0;
Mat graySrc;
#if 0
//1. 转化为灰度图像
graySrc = changRGB2Gray(src);
#else
//将图像的3个通道相加后计算总体均衡
graySrc = Mat::zeros(nrow, ncol, CV_8UC1);
for (i=0; i<nrow; i++) {
uchar* data_graySrc = graySrc.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
Vec3b bgrSrc = src.at<Vec3b>(i, j);
data_graySrc[j] = (bgrSrc[0]+bgrSrc[1]+bgrSrc[2]) / 3;
}
}
#endif
//2. 灰度图像均衡
Mat grayDst;
switch (method) {
case HE:
grayDst = histogramEqualizate(graySrc);
break;
case AHE:
grayDst = cladaptHistEqual(graySrc, CLAHEMETHOD);
break;
case CLAHEMETHOD:
grayDst = cladaptHistEqual(graySrc, CLAHEMETHOD);
break;
default:
grayDst = histogramEqualizate(graySrc);
}
//将V通道放入hsv中, v: [0, 1]
//3. 按照原图像RGB的比例还原回彩色图像
Mat dst(nrow, ncol, CV_8UC3, Scalar(0, 0, 0));
int tb=0, tg=0, tr=0;
for (i=0; i<nrow; i++) {
uchar* data_grayDst = grayDst.ptr<uchar>(i);
uchar* data_graySrc = graySrc.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
Vec3b bgrSrc = src.at<Vec3b>(i, j);
Vec3b &bgrDst = dst.at<Vec3b>(i, j);
//按照比例回复bgrSrc/data_graySrc = bgrDst/data_grayDst --> bgrDst=bgrSrc/data_graySrc*data_grayDst
if (data_graySrc[j] != 0) {
tb = bgrSrc[0]*data_grayDst[j]/data_graySrc[j];
tg = bgrSrc[1]*data_grayDst[j]/data_graySrc[j];
tr = bgrSrc[2]*data_grayDst[j]/data_graySrc[j];
bgrDst[0] = tb>255 ? 255 : (tb<0 ? 0 :tb); //这里比较重要,消除颜色怪异的点
bgrDst[1] = tg>255 ? 255 : (tg<0 ? 0 :tg);
bgrDst[2] = tr>255 ? 255 : (tr<0 ? 0 :tr);
}
}
}
return dst;
}
/**
*@brief 利用双线性插值法对图像进行缩放
*
* 1. 图像的四角上的点的值直接复制
* 2. 四条边的值使用线性插值
* 3. 中间的图像使用双线性插值
*@param resize 缩放倍数
*/
Mat resizeMat(const Mat src, float resize)
{
//原图像行列数,应为要取数组,数组索引最大值为数组长度-1
int nrowSrc = src.rows-1;
int ncolSrc = src.cols-1;
//目标图像行列数
int nrow = src.rows*resize;
int ncol = src.cols*resize;
Mat dst = Mat::zeros(nrow, ncol, CV_8UC3);
int i=0, j=0;
for (i=0; i<nrow; i++) {
for (j=0; j<ncol; j++) {
//计算目标图像点在原图像对应的位置
float srcRow = i/resize;
float srcCol = j/resize;
int x1 = srcRow;
int x2 = x1+1;
int y1 = srcCol;
int y2 = y1+1;
/** 注意使用双线性插值时,目标图像上点映射到原图像上时四个点值的获取 */
if (x1>=nrowSrc) {
x1 = nrowSrc;
srcRow = nrowSrc;
x2 = nrowSrc;
}
if (y1>=ncolSrc) {
y1 = ncolSrc;
srcCol = ncolSrc;
y2 = ncolSrc;
}
Vec3b bgrSrc11 = src.at<Vec3b>(x1, y1);
// cout << " x: " << nrowSrc << " y: " << ncolSrc << " x1: " << x1 << " y2: " << y2 << endl;
Vec3b bgrSrc12 = src.at<Vec3b>(x1, y2);
Vec3b bgrSrc21 = src.at<Vec3b>(x2, y1);
Vec3b bgrSrc22 = src.at<Vec3b>(x2, y2);
Vec3b &bgrDst = dst.at<Vec3b>(i, j);
bilinearInterpolation(x1, y1, x2, y2, srcRow, srcCol, bgrSrc11[0], bgrSrc12[0], bgrSrc21[0], bgrSrc22[0], &bgrDst[0]);
bilinearInterpolation(x1, y1, x2, y2, srcRow, srcCol, bgrSrc11[1], bgrSrc12[1], bgrSrc21[1], bgrSrc22[1], &bgrDst[1]);
bilinearInterpolation(x1, y1, x2, y2, srcRow, srcCol, bgrSrc11[2], bgrSrc12[2], bgrSrc21[2], bgrSrc22[2], &bgrDst[2]);
}
}
return dst;
}
/**
* 计算图像标准差
*@param src 单通道Mat
*@param srcMean 平均值
*/
float getMatStandardDeviation(const Mat src, uchar srcMean=0);
float getMatStandardDeviation(const Mat src, uchar srcMean) {
int nrow = src.rows;
int ncol = src.cols;
int i, j;
long int varianceSum = 0; //方差总和
if (srcMean == 0) {
srcMean = mean(src).val[0];
cout << "计算平均值: " << srcMean << endl;
}
for (i=0; i<nrow; i++) {
const uchar* data_in = src.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
varianceSum += (data_in[j]-srcMean)*(data_in[j]-srcMean);
}
}
varianceSum = varianceSum/(nrow*ncol);
float ret = sqrt(varianceSum); //开平方
// cout << "标准差: " << ret << endl;
return ret;
}
/**
*@brief 使用局部标准差
*
* 1. 取区域平均值,大于平均值的更大、小于平均值的更小
* 2. 使用局部标准差,D怎么取值合适??CG的值有时太大
*@param useLSD true 使用局部标准差
* 参考:http://www.cnblogs.com/Imageshop/p/3324282.html
*/
Mat useACE(const Mat src, bool useLSD) {
int n = 50; //局部矩阵大小(2n+1)*(2n+1)
float c = 2.0;
float max = 3.0; //定义CG最大值
uchar D = 0; //全局平均值
int nrow = src.rows;
int ncol = src.cols;
Mat dst = Mat::zeros(nrow, ncol, CV_8UC1);
int i, j;
if (useLSD) {
D = mean(src).val[0];
}
for (i=0; i<nrow; i++) {
const uchar* data_in = src.ptr<uchar>(i);
uchar* data_out = dst.ptr<uchar>(i);
for (j=0; j<ncol; j++) {
/** 计算块的左上角和右下角的点 */
int row1 = i-50;
int col1 = j-50;
int row2 = i+50;
int col2 = j+50;
col1 = col1<0 ? 0 : col1;
row1 = row1<0 ? 0 : row1;
col2 = col2>ncol ? ncol : col2;
row2 = row2>nrow ? nrow : row2;
Mat tmp = src(Rect(col1, row1, col2-col1, row2-row1));
Scalar m = mean(tmp);
uchar tmpM = m.val[0];
// cout << "tmpM: " << tmpM << endl;
if (useLSD) {
float standardDeviation = getMatStandardDeviation(tmp, tmpM);
c = D/standardDeviation;
cout << "c: " << c << endl;
if (c > max)
c = max;
}
int t = tmpM + c*(data_in[j]-tmpM);
data_out[j] = t>255 ? 255 : (t<0 ? 0 : t);
}
}
cout << "D: " << (int)D << endl;
return dst;
}
/**
* 将图像分块,对rgb通道分别进行自动对比度调整,并进行双线性插值
* 参考:http://www.cnblogs.com/Imageshop/p/3395968.html
*/
Mat rgbAutoContrast(const Mat src) {
// "images" is a vector of 3 Mat arrays:
vector<Mat> images(3);
// split src,get the images (dont forget they follow BGR order in OpenCV)
split(src, images);
Mat tmpB = cladaptHistEqual(images[0], ATUOCUTVALUE);
Mat tmpG = cladaptHistEqual(images[1], ATUOCUTVALUE);
Mat tmpR = cladaptHistEqual(images[2], ATUOCUTVALUE);
Mat dst(src.rows, src.cols, CV_8UC3, Scalar(0, 0, 0));
int r, c;
for (r=0; r<src.rows; r++) {
const uchar* data_b = tmpB.ptr<uchar>(r);
const uchar* data_g = tmpG.ptr<uchar>(r);
const uchar* data_r = tmpR.ptr<uchar>(r);
for (c=0; c<src.cols; c++) {
Vec3b &bgrDst = dst.at<Vec3b>(r, c);
bgrDst[0] = data_b[c];
bgrDst[1] = data_g[c];
bgrDst[2] = data_r[c];
}
}
#if 0
/** 分别显示BGR通道 */
Mat matBlue(src.rows, src.cols, CV_8UC3, Scalar(0, 0, 0));
Mat matGreen(src.rows, src.cols, CV_8UC3, Scalar(0, 0, 0));
Mat matRed(src.rows, src.cols, CV_8UC3, Scalar(0, 0, 0));
int bfrom_to[] = {0,0};
int gfrom_to[] = {1,1};
int rfrom_to[] = {2,2};
mixChannels(&src, 1, &matBlue, 2, bfrom_to, 1);
mixChannels(&src, 1, &matGreen, 2, gfrom_to, 1);
mixChannels(&src, 1, &matRed, 2, rfrom_to, 1);
imshow("image blue", matBlue);
imshow("image green", matGreen);
imshow("image red", matRed);
waitKey(0);
#endif
return dst;
}
}
#ifdef _DEBUG
using namespace zsyTestMethod;
int main (int argc, char** argv) {
cout << getTestMethodVersion() << endl;
Mat image = imread("../out/test2.jpg", CV_LOAD_IMAGE_COLOR);
if (!image.data) {
cout << "Could not open or find the image" << std::endl ;
return -1;
}
Mat dstHE = rgbHistogramEqualizate(image, HE);
Mat dstAHE = rgbHistogramEqualizate(image, AHE);
Mat dstCLAHE = rgbHistogramEqualizate(image, CLAHEMETHOD);
// Mat dstResize = resizeMat(image, 1.7);
imshow("Display HE", dstHE);
imshow("Display AHE", dstAHE);
imshow("Display CLAHE", dstCLAHE);
// imshow("Display resize", dstResize);
waitKey(0);
return 0;
}
#endif
| true |
e686f6c203783398edd3f10ac23c7616431680bd | C++ | Jaybro/pico_tree | /examples/pico_understory/pico_understory/cover_tree.hpp | UTF-8 | 8,068 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <pico_tree/internal/point_wrapper.hpp>
#include <pico_tree/internal/search_visitor.hpp>
#include <pico_tree/internal/space_wrapper.hpp>
// Use this define to enable a simplified version of the nearest ancestor tree
// or disable it to use the regular one from "Faster Cover Trees".
//
// Testing seems to indicate that when the dataset has some structure (not
// random), the "simplified" version is faster.
// 1) Building: The performance difference can be large for a low leveling base,
// e.g., 1.3. The difference in building time becomes smaller when the leveling
// base increases.
// 2) Queries: Slower compared to the regular nearest ancestor tree for a low
// leveling base, but faster for a higher one.
//
// It seems that with structured data, both tree building and querying becomes
// faster when increasing the leveling base. Both times decreasing steadily when
// increasing the base. Here a value of 2.0 is the fastest.
//
// For random data, build and query times seem to be all over the place when
// steadily increasing the base. A value of 1.3 generally seems the fastest, but
// none of the values for this hyper parameter inspire trust.
#define SIMPLIFIED_NEAREST_ANCESTOR_COVER_TREE
#include "internal/cover_tree_builder.hpp"
#include "internal/cover_tree_data.hpp"
#include "internal/cover_tree_node.hpp"
#include "internal/cover_tree_search.hpp"
#include "metric.hpp"
namespace pico_tree {
template <typename Space_, typename Metric_ = L2, typename Index_ = int>
class CoverTree {
private:
using Index = Index_;
using Space = Space_;
using SpaceWrapperType = internal::SpaceWrapper<Space>;
using Scalar = typename SpaceWrapperType::ScalarType;
using Node = internal::CoverTreeNode<Index, Scalar>;
using BuildCoverTreeType =
internal::BuildCoverTree<SpaceWrapperType, Metric_, Index_>;
using CoverTreeDataType = typename BuildCoverTreeType::CoverTreeDataType;
public:
//! \brief Index type.
using IndexType = Index;
//! \brief Scalar type.
using ScalarType = Scalar;
//! \brief CoverTree dimension. It equals pico_tree::kDynamicSize in case Dim
//! is only known at run-time.
static constexpr int Dim = SpaceWrapperType::Dim;
//! \brief Point set or adaptor type.
using SpaceType = Space;
//! \brief The metric used for various searches.
using MetricType = Metric_;
//! \brief Neighbor type of various search resuls.
using NeighborType = Neighbor<Index, Scalar>;
public:
//! \brief The CoverTree cannot be copied.
//! \details The CoverTree uses pointers to nodes and copying pointers is not
//! the same as creating a deep copy. For now we are not interested in
//! providing a deep copy.
//! \private
CoverTree(CoverTree const&) = delete;
//! \brief Move constructor of the CoverTree.
//! \details The move constructor is not implicitly created because of the
//! deleted copy constructor.
//! \private
CoverTree(CoverTree&&) = default;
//! \brief Creates a CoverTree given \p points and a leveling \p base.
CoverTree(Space space, Scalar base)
: space_(std::move(space)),
metric_(),
data_(BuildCoverTreeType()(SpaceWrapperType(space_), metric_, base)) {}
//! \brief Searches for the nearest neighbor of point \p x.
template <typename P>
inline void SearchNn(P const& x, NeighborType& nn) const {
internal::SearchNn<NeighborType> v(nn);
SearchNearest(data_.root_node, x, v);
}
//! \brief Searches for an approximate nearest neighbor of point \p x.
template <typename P>
inline void SearchNn(P const& x, ScalarType const e, NeighborType& nn) const {
internal::SearchApproximateNn<NeighborType> v(e, nn);
SearchNearest(data_.root_node, x, v);
}
//! \brief Searches for the k nearest neighbors of point \p x, where k equals
//! std::distance(begin, end). It is expected that the value type of the
//! iterator equals Neighbor<Index, Scalar>.
template <typename P, typename RandomAccessIterator>
inline void SearchKnn(
P const& x, RandomAccessIterator begin, RandomAccessIterator end) const {
static_assert(
std::is_same_v<
typename std::iterator_traits<RandomAccessIterator>::value_type,
NeighborType>,
"ITERATOR_VALUE_TYPE_DOES_NOT_EQUAL_NEIGHBOR_TYPE");
internal::SearchKnn<RandomAccessIterator> v(begin, end);
SearchNearest(data_.root_node, x, v);
}
//! \brief Searches for the \p k nearest neighbors of point \p x and stores
//! the results in output vector \p knn.
template <typename P>
inline void SearchKnn(
P const& x, Size const k, std::vector<NeighborType>& knn) const {
// If it happens that the point set has less points than k we just return
// all points in the set.
knn.resize(std::min(k, SpaceWrapperType(space_).size()));
SearchKnn(x, knn.begin(), knn.end());
}
//! \brief Searches for the k approximate nearest neighbors of point \p x,
//! where k equals std::distance(begin, end). It is expected that the value
//! type of the iterator equals Neighbor<Index, Scalar>.
template <typename P, typename RandomAccessIterator>
inline void SearchKnn(
P const& x,
Scalar const e,
RandomAccessIterator begin,
RandomAccessIterator end) const {
static_assert(
std::is_same_v<
typename std::iterator_traits<RandomAccessIterator>::value_type,
NeighborType>,
"ITERATOR_VALUE_TYPE_DOES_NOT_EQUAL_NEIGHBOR_TYPE");
internal::SearchApproximateKnn<RandomAccessIterator> v(e, begin, end);
SearchNearest(data_.root_node, x, v);
}
//! \brief Searches for the \p k approximate nearest neighbors of point \p x
//! and stores the results in output vector \p knn.
template <typename P>
inline void SearchKnn(
P const& x,
Size const k,
Scalar const e,
std::vector<NeighborType>& knn) const {
// If it happens that the point set has less points than k we just return
// all points in the set.
knn.resize(std::min(k, SpaceWrapperType(space_).size()));
SearchKnn(x, e, knn.begin(), knn.end());
}
//! \brief Searches for all the neighbors of point \p x that are within radius
//! \p radius and stores the results in output vector \p n.
template <typename P>
inline void SearchRadius(
P const& x,
Scalar const radius,
std::vector<NeighborType>& n,
bool const sort = false) const {
internal::SearchRadius<NeighborType> v(radius, n);
SearchNearest(data_.root_node, x, v);
if (sort) {
v.Sort();
}
}
//! \brief Searches for the approximate neighbors of point \p x that are
//! within radius \p radius and stores the results in output vector \p n.
template <typename P>
inline void SearchRadius(
P const& x,
Scalar const radius,
Scalar const e,
std::vector<NeighborType>& n,
bool const sort = false) const {
internal::SearchApproximateRadius<NeighborType> v(e, radius, n);
SearchNearest(data_.root_node, x, v);
if (sort) {
v.Sort();
}
}
//! \brief Point set used by the tree.
inline Space const& points() const { return space_; }
//! \brief Metric used for search queries.
inline MetricType const& metric() const { return metric_; }
private:
//! \brief Returns the nearest neighbor (or neighbors) of point \p x depending
//! on their selection by visitor \p visitor for node \p node .
template <typename P, typename Visitor_>
inline void SearchNearest(
Node const* const node, P const& x, Visitor_& visitor) const {
internal::PointWrapper<P> p(x);
SpaceWrapperType space(space_);
internal::SearchNearestMetric<
SpaceWrapperType,
MetricType,
internal::PointWrapper<P>,
Visitor_,
IndexType>(space, metric_, p, visitor)(node);
}
//! Point set used for querying point data.
SpaceType space_;
//! Metric used for comparing distances.
MetricType metric_;
//! Data structure of the CoverTree.
CoverTreeDataType data_;
};
} // namespace pico_tree
| true |
42757299732c0310a19c1586cac14306fad682db | C++ | drew-gross/Google-AI-contest | /NoPlanetsOwnedByPlayerException.h | UTF-8 | 392 | 2.53125 | 3 | [] | no_license | #ifndef NO_PLANETS_OWNED_BY_PLAYER
#define NO_PLANETS_OWNED_BY_PLAYER
#include <stdexcept>
#include "Planet.h"
class NoPlanetsOwnedByPlayerException : public std::runtime_error {
public:
NoPlanetsOwnedByPlayerException(Player newPlayer);
~NoPlanetsOwnedByPlayerException() throw();
Player GetPlayer();
private:
Player player;
};
#endif //NO_PLANETS_OWNED_BY_PLAYER
| true |
606e92936c01a4b6a6810fb666ba9b01697eb4d7 | C++ | TomaszP17/SPOJ | /SM_01_00 - Szyfr.cpp | UTF-8 | 565 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i, l, testy;
char wyraz;
cin >> testy;
cin.get(wyraz);
while (testy--)
{
i = 4; l = 0;
while (cin.get(wyraz))
{
if (wyraz == '\n') break;
if (i == -1)
{
cout << (char)(l + 65);
i = 4;
l = 0;
}
l += (wyraz - '0') * pow(2, i);
i--;
}
cout << (char)(l + 65) << endl;
}
} | true |
4b781a5da0b099ff85cee2df700a3c1a36b32081 | C++ | jinyoung0612/Algorithm | /BOJ/brute-force/2503.cpp | UTF-8 | 1,544 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define MAX 1001
int N;
bool check[10];
int result[4];
int answer=0;
vector< pair<string, pair<int, int> > > v;
int Strike(string a, string b){
int cnt=0;
for(int i=0; i<3; i++){
if(a[i]==b[i]){
cnt++;
}
}
return cnt;
}
int Ball(string a, string b){
int cnt=0;
for(int i=0; i<3; i++){
if(a[i]!=b[i]){
if(a.find(b[i])!=string::npos){
cnt++;
}
}
}
return cnt;
}
void permutation(int depth){
if(depth==3){
string temp;
for(int i=0; i<3; i++){
temp+=(result[i]+'0');
}
int cnt=0;
for(int i=0; i<v.size(); i++){
if(Strike(temp,v[i].first)==v[i].second.first && Ball(temp,v[i].first)==v[i].second.second){
cnt++;
}
else{
break;
}
}
if(cnt==v.size()){
answer+=1;
}
return;
}
for(int i=1; i<=9; i++){
if(!check[i]){
check[i]=1;
result[depth]=i;
permutation(depth+1);
check[i]=0;
}
}
}
int main(void){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>N;
string num;
int st,ball;
while(N--){
cin>>num>>st>>ball;
v.push_back(make_pair(num, make_pair(st,ball)));
}
permutation(0);
cout<<answer;
return 0;
} | true |
edf6960b1d8c32aa4823cc4b34dabb56295282e1 | C++ | BadgerTechnologies/octomap_mapping | /octomap_server/src/SensorUpdateKeyMapHashImpl.cpp | UTF-8 | 11,411 | 2.578125 | 3 | [] | no_license | #include <octomap_server/SensorUpdateKeyMapHashImpl.h>
#include <cstring>
namespace octomap_server {
SensorUpdateKeyMapHashImpl::SensorUpdateKeyMapHashImpl(size_t initial_capacity, double max_load_factor)
: max_load_factor_(max_load_factor)
{
initializeNodeCache(initial_capacity);
calculateTableCapacity();
table_.resize(table_capacity_, NULL);
}
SensorUpdateKeyMapHashImpl::~SensorUpdateKeyMapHashImpl()
{
table_.clear();
destroyNodeCache();
}
void SensorUpdateKeyMapHashImpl::clear()
{
// clear our node pointers out. do not de-allocate the table, we will re-use
// whatever size it is.
std::memset(table_.data(), 0, table_.size() * sizeof(Node*));
// reset our node cache
resetNodeCache();
}
VoxelState SensorUpdateKeyMapHashImpl::find(const octomap::OcTreeKey& key) const
{
octomap::OcTreeKey::KeyHash hasher;
size_t hash = hasher(key);
return find(key, hash);
}
VoxelState SensorUpdateKeyMapHashImpl::find(const octomap::OcTreeKey& key, size_t hash) const
{
size_t index = hash & table_mask_;
Node *node = table_[index];
while (node)
{
if (node->key == key)
{
return node->value;
}
node = node->next;
}
return voxel_state::UNKNOWN;
}
bool SensorUpdateKeyMapHashImpl::insertFreeByIndexImpl(const octomap::OcTreeKey& key, size_t index, Node** table)
{
Node *table_node = table[index];
Node *node = table_node;
while (node) {
if (node->key == key) {
return false;
}
node = node->next;
}
// insert a new node at the head of the chain for the bucket
node = allocNodeFromCache();
node->key = key;
node->value = voxel_state::FREE;
node->next = table_node;
table[index] = node;
return true;
}
// Returns true if a node was inserted, false if the node already existed
bool SensorUpdateKeyMapHashImpl::insertFree(const octomap::OcTreeKey& key)
{
octomap::OcTreeKey::KeyHash hasher;
size_t hash = hasher(key);
size_t index = hash & table_mask_;
bool rv = insertFreeByIndexImpl(key, index, table_.data());
// if we have just run out of room, this will resize our set
if (rv) resizeIfNecessary();
return rv;
}
bool SensorUpdateKeyMapHashImpl::insertFreeCells(const octomap::OcTreeKey *free_cells, size_t free_cells_count)
{
if (free_cells_count == 0) {
return false;
}
while (node_cache_size_ + free_cells_count + 1 >= node_cache_capacity_) {
doubleCapacity();
}
const size_t n = ((free_cells_count-1) & ~7) + 8;
size_t x_keys[n] __attribute__((__aligned__(64)));
size_t y_keys[n] __attribute__((__aligned__(64)));
size_t z_keys[n] __attribute__((__aligned__(64)));
size_t indecies[n] __attribute__((__aligned__(64)));
unsigned int i=0, j=0;
for (i=0; i<free_cells_count; ++i) {
x_keys[i] = free_cells[i][0];
y_keys[i] = free_cells[i][1];
z_keys[i] = free_cells[i][2];
}
const size_t *x_keys_p = x_keys;
const size_t *y_keys_p = y_keys;
const size_t *z_keys_p = z_keys;
size_t *indecies_p = indecies;
const uint64_t table_mask = table_mask_;
for (i=0; i<n; i+=8) {
// structure this inner loop such that gcc vectorizes using best vector ops
for (j=0; j<8; ++j) {
// we can't vectorize modulus, so ensure the table is a power of two and
// use a bit mask
*indecies_p = (*x_keys_p + 1447 * *y_keys_p + 345637 * *z_keys_p) & table_mask;
++indecies_p;
++x_keys_p;
++y_keys_p;
++z_keys_p;
}
}
Node** table = table_.data();
for (i=0; i<free_cells_count; ++i)
{
insertFreeByIndexImpl(free_cells[i], indecies[i], table);
}
return true;
}
bool SensorUpdateKeyMapHashImpl::insertOccupied(const octomap::OcTreeKey& key)
{
octomap::OcTreeKey::KeyHash hasher;
size_t hash = hasher(key);
size_t index = hash & table_mask_;
Node *node = table_[index];
while (node)
{
if (node->key == key)
{
// Ensure that this key maps to occupied
node->value = voxel_state::OCCUPIED;
return false;
}
node = node->next;
}
// insert a new node at the head of the chain for the bucket
node = allocNodeFromCache();
node->key = key;
node->value = voxel_state::OCCUPIED;
node->next = table_[index];
table_[index] = node;
// if we have just run out of room, this will resize our set
resizeIfNecessary();
return true;
}
void SensorUpdateKeyMapHashImpl::insertInner(const octomap::OcTreeKey& key)
{
octomap::OcTreeKey::KeyHash hasher;
size_t hash = hasher(key);
size_t index = hash & table_mask_;
Node *node = table_[index];
while (node)
{
if (node->key == key)
{
// do not override an existing node
return;
}
node = node->next;
}
// insert a new node at the head of the chain for the bucket
node = allocNodeFromCache();
node->key = key;
node->value = voxel_state::INNER;
node->next = table_[index];
table_[index] = node;
// if we have just run out of room, this will resize our set
resizeIfNecessary();
}
void SensorUpdateKeyMapHashImpl::insert(const octomap::OcTreeKey& key, VoxelState state)
{
octomap::OcTreeKey::KeyHash hasher;
size_t hash = hasher(key);
size_t index = hash & table_mask_;
Node *node = table_[index];
while (node)
{
if (node->key == key)
{
// do not override an existing node
return;
}
node = node->next;
}
// insert a new node at the head of the chain for the bucket
node = allocNodeFromCache();
node->key = key;
node->value = state;
node->next = table_[index];
table_[index] = node;
// if we have just run out of room, this will resize our set
resizeIfNecessary();
}
void SensorUpdateKeyMapHashImpl::downSample(const octomap::OcTreeSpace& tree, SensorUpdateKeyMapImpl* output_map) const
{
SensorUpdateKeyMapImpl::downSample(tree, output_map);
unsigned int target_depth = getDepth() - output_map->getLevel();
unsigned int voxel_state_counts[voxel_state::MAX] = {0};
// first ensure the output bounds are set correctly
output_map->setBounds(min_key_, max_key_);
octomap::key_type center_offset_key = octomap::computeCenterOffsetKey(target_depth, tree.getCenterKey());
// loop over the hash table
const unsigned int table_size = table_.size();
auto table = table_.data();
for (unsigned int i=0; i<table_size; ++i)
{
const Node* node = table_[i];
while (node)
{
octomap::OcTreeKey target_key = tree.adjustKeyAtDepth(node->key, target_depth);
// if the output map doesn't yet have this key, time to add it.
if (output_map->find(target_key) == voxel_state::UNKNOWN)
{
unsigned int free_count=0;
unsigned int inner_count=0;
voxel_state_counts[voxel_state::FREE] = 0;
voxel_state_counts[voxel_state::OCCUPIED] = 0;
for (unsigned int i=0; i<8; ++i)
{
octomap::OcTreeKey child_key;
octomap::computeChildKey(i, center_offset_key, target_key, child_key);
const VoxelState voxel_state = find(child_key);
++voxel_state_counts[voxel_state];
}
if (voxel_state_counts[voxel_state::FREE] == 8)
{
output_map->insertFree(target_key);
}
else if (voxel_state_counts[voxel_state::OCCUPIED] == 8)
{
output_map->insertOccupied(target_key);
}
else
{
// There must be at least one child key to get here
// Mark the free and/or occupied bits to match the children that are
// present. This allows for implemetations that do not store free
// space to skip large sections of tree that only have free space
// under it, for example.
VoxelState new_state = voxel_state::INNER;
if (voxel_state_counts[voxel_state::FREE] > 0 ||
voxel_state_counts[voxel_state::INNER | voxel_state::FREE] > 0)
{
new_state |= voxel_state::FREE;
}
if (voxel_state_counts[voxel_state::OCCUPIED] > 0 ||
voxel_state_counts[voxel_state::INNER | voxel_state::OCCUPIED] > 0)
{
new_state |= voxel_state::OCCUPIED;
}
if (voxel_state_counts[voxel_state::INNER | voxel_state::OCCUPIED | voxel_state::FREE] > 0)
{
new_state |= voxel_state::FREE;
new_state |= voxel_state::OCCUPIED;
}
output_map->insert(target_key, new_state);
}
}
node = node->next;
}
}
}
void SensorUpdateKeyMapHashImpl::resizeIfNecessary()
{
assert(node_cache_size_ <= node_cache_capacity_);
// If we have run out of size in the node cache, double it.
if (node_cache_size_ == node_cache_capacity_) {
doubleCapacity();
}
}
void SensorUpdateKeyMapHashImpl::initializeNodeCache(size_t capacity)
{
node_cache_capacity_ = capacity;
node_cache_ = new unsigned char[sizeof(Node) * node_cache_capacity_];
node_cache_size_ = 0;
}
void SensorUpdateKeyMapHashImpl::destroyNodeCache()
{
resetNodeCache();
node_cache_capacity_ = 0;
delete [] node_cache_;
}
// Double the capacity of our set.
// We do this by re-allocating our table to keep the max load factor,
// allocating a new, double-sized node_cache, and then copying the old table
// to the new.
void SensorUpdateKeyMapHashImpl::doubleCapacity()
{
// Remember the old node cache information and table
std::vector<Node*> old_table(table_);
size_t old_capacity = node_cache_capacity_;
unsigned char * old_cache = node_cache_;
// Double the capacity and allocate new cache
initializeNodeCache(node_cache_capacity_ * 2);
// resize the hash table to keep the load factor balanced
calculateTableCapacity();
table_.resize(table_capacity_);
// clear all the old entries out
clear();
// Deep copy the old set to the newly allocated one.
for (size_t i=0; i<old_table.size(); ++i) {
Node* node = old_table[i];
while (node)
{
if (node->value == voxel_state::FREE)
{
insertFree(node->key);
}
else if (node->value == voxel_state::OCCUPIED)
{
insertOccupied(node->key);
}
else if (node->value == voxel_state::INNER)
{
insertInner(node->key);
}
node = node->next;
}
}
// Destroy the old cache
delete [] old_cache;
}
unsigned char * SensorUpdateKeyMapHashImpl::getNewNodePtr() {
assert(node_cache_size_ < node_cache_capacity_);
unsigned char * new_node_memory = node_cache_ + node_cache_size_ * sizeof(Node);
node_cache_size_++;
return new_node_memory;
}
SensorUpdateKeyMapHashImpl::Node* SensorUpdateKeyMapHashImpl::allocNodeFromCache()
{
return new(getNewNodePtr()) Node;
}
void SensorUpdateKeyMapHashImpl::resetNodeCache()
{
// We do not want to reclaim any memory, keep the cache around. It can
// only grow to the size of the largest sensor update, which is what we
// want.
// Technically, we should call the destructor of every element here,
// however for efficiency, leverage the fact that we are storing
// plain-old-data and do nothing on destruction
node_cache_size_ = 0;
}
#if 0
void SensorUpdateKeyMapHashImpl::apply(OcTreeT* tree) const
{
const unsigned int table_size = table_.size();
auto table = table_.data();
for (unsigned int i=0; i<table_size; ++i)
{
const Node* node = table_[i];
while (node)
{
tree->updateNode(node->key, node->value);
node = node->next;
}
}
}
#endif
} // end namespace octomap_server
| true |
bdcc249960b9d4587ca3c093320d7ebeaa0f50ac | C++ | dashjay/learn_cpp | /chapter7/7.14_ellipsis_arguments.cpp | UTF-8 | 776 | 3.46875 | 3 | [] | no_license | #include <cstdarg>
#include <iostream>
// should never use ellipsis
// ..... never
double findAverage(int count, ...) {
double sum = 0;
va_list list;
va_start(list, count);
for (int arg = 0; arg < count; ++arg) {
sum += va_arg(list, int);
}
va_end(list);
return sum / count;
}
double findAverage_1(int start, ...) {
double sum = start;
va_list list;
va_start(list, start);
int count = 1;
while (true) {
int arg = va_arg(list, int);
if (arg == -1) {
break;
}
sum += arg;
count++;
}
va_end(list);
return sum / count;
}
int main() {
std::cout << findAverage(5, 4, 4, 4, 3, 3) << "\n";
std::cout << findAverage_1(3, 4, 5, 6, 7, -1) << "\n";
}
| true |
8341c4b9eda4736720395bd6f0fba91b21aa7103 | C++ | gabrielnascimentost/trabalhoGrafos2020.3 | /Edge.cpp | UTF-8 | 1,856 | 3.5 | 4 | [] | no_license | #include "Edge.h"
#include <iostream>
using namespace std;
/**************************************************************************************************
* Defining the Edge's methods (definindo metodos das arestas)
**************************************************************************************************/
// Constructor
Edge::Edge(int id,int target_id){ // construtor da aresta passando como parametro o identificador do vertice alvo
this->id = id; //defini identificador do vertice de partida
this->target_id = target_id; // defini identificador do vertice alvo( de chegada )
this->next_edge = nullptr; // proxima aresta declara como null
this->weight = 0; // defini o peso como 0
}
// Destructor
Edge::~Edge(){ // destrutor
if (this->next_edge != nullptr){ //se a proxima aresta for diferente de null
delete this->next_edge; // deleta a proxima aresta
this->next_edge = nullptr; // proxima aresta igual a null
}
}
// Getters
int Edge::getId()//get do id do vertice de partida da aresta
{
return this->id;//retorna o id do vertice de partida da aresta
}
int Edge::getTargetId(){ // get do id do vertice alvo da aresta
return this->target_id;//retorna o id do vertice alvo da aresta
}
Edge* Edge::getNextEdge(){ //get da proxima aresta
return this->next_edge;// retorna a proxima aresta
}
float Edge::getWeight(){// get do peso da aresta
return this->weight;//retorna o peso da aresta
}
// Setters
void Edge::setNextEdge(Edge* edge){ // set de valores da proxima aresta passando como parametro o ponteiro pra aresta
this->next_edge = edge; // declara a proxima aresta como a aresta passada por parametro
}
void Edge::setWeight(float weight){//set do peso da aresta
this->weight = weight;//define o peso da aresta como o peso passado por parametro
}
| true |
2d1fe6055143a29e4b514168c51e8ad387e5666a | C++ | Leyla475/3 | /Source.cpp | UTF-8 | 5,430 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <chrono>
#include <random>
class IntSequence {
private:
int value;
public:
IntSequence(int initialValue) : value(initialValue) {}
int operator() () {
return value++;
}
};
template <typename T>
void print(const T& t) {
for (auto elem : t)
std::cout << elem << " ";
std::cout << std::endl;
}
class RandSequence {
private:
std::binomial_distribution<int> d;
std::default_random_engine e;
public:
RandSequence() {
d = std::binomial_distribution<int>(100, 0.5);
e = std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count());
}
int operator() () {
return this->d(this->e);
}
};
int main() {
//generate sequence 1 - 10
std::vector <int> v;
std::generate_n(back_inserter(v), 10, IntSequence(1));
print(v);
//add few numbers from cin
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), back_inserter(v));
print(v);
//shuffle elments
std::shuffle(std::begin(v), std::end(v), std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count()));
print(v);
//delete duplicates
std::vector <int> unique_elem;
std::copy(std::begin(v), std::end(v), back_inserter(unique_elem));
std::sort(unique_elem.begin(), unique_elem.end());
std::vector <int> helper;
std::copy(unique_elem.begin(), unique_elem.end(), back_inserter(helper));
unique_elem.erase(std::unique(unique_elem.begin(), unique_elem.end()), unique_elem.end());
std::vector <int> to_delete;
std::set_difference(helper.begin(), helper.end(), unique_elem.begin(), unique_elem.end(), std::inserter(to_delete, to_delete.begin()));
print(to_delete);
auto c = std::remove_if(std::begin(v), std::end(v), [&to_delete](int elem) {
auto pos1 = std::find(to_delete.begin(), to_delete.end(), elem);
if (pos1 != to_delete.end()) {
to_delete.erase(pos1);
return true;
}
else
return false;
});
v.erase(c, v.end());
print(v);
//count quantity of numbers % 2 != 0
int num = std::count_if(std::begin(v), std::end(v), [](int elem) {
return elem % 2 == 1;
});
std::cout << num << std::endl;
//find min and max values
auto mm = std::minmax(std::begin(v), std::end(v));
//std::cout << "min = " << *(mm.first) << "; max = " << *(mm.second) << std::endl;
std::cout << "min = " << *(std::min_element(std::begin(v), std::end(v))) << " ; max = " << *(std::max_element(v.begin(), v.end())) << std::endl;
//find prime number
std::cout << *(std::find_if(std::begin(v), std::end(v), [](int elem) {
for (int i = 2; i <= sqrt(elem); ++i)
if (elem % i == 0)
return false;
return true;
}));
std::cout << std::endl;
//replace all elems to elems*elems
std::for_each(std::begin(v), std::end(v), [](int& elem) {
elem = elem * elem;
});
print(v);
//create vector from random numbers
std::vector <int> v1;
std::generate_n(back_inserter(v1), v.size(), RandSequence());
print(v1);
//sum of elems of v1
int sum = 0;
std::for_each(std::begin(v1), std::end(v1), [&sum](const int& elem) {
sum += elem;
});
std::cout << sum << std::endl;
//replace few first numbers of v1
std::replace_if(std::begin(v1), std::begin(v1) + 3, [](int elem) {return true; }, 1);
print(v1);
//create vector difference betweeen v and v1
std::vector <int> v2;
std::transform(std::begin(v), std::end(v), std::begin(v1), std::back_inserter(v2), [](auto a, auto b) {return a - b; });
print(v2);
//replace all elems < 0 in v2 to 0
std::replace_if(std::begin(v2), std::end(v2), [](int elem) {return elem < 0; }, 0);
print(v2);
//delete all elems = 0 from v2
auto pos = std::remove_if(std::begin(v2), std::end(v2), [](int elem) {return elem == 0; });
v2.erase(pos, v2.end());
print(v2);
//reverse v2
std::reverse(std::begin(v2), std::end(v2));
print(v2);
//find top3 greatest elems
std::nth_element(std::begin(v2),std::begin(v2), std::end(v2), std::greater<int>());
std::cout << "The first largest element is " << v2[0] << '\n';
std::nth_element(std::begin(v2), std::begin(v2), std::end(v2), std::greater<int>());
std::cout << "The second largest element is " << v2[1] << '\n';
std::nth_element(std::begin(v2), std::begin(v2), std::end(v2), std::greater<int>());
std::cout << "The third largest element is " << v2[2] << '\n';
//sort v and v1
std::sort(std::begin(v), std::end(v));
std::sort(std::begin(v1), std::end(v1));
print(v);
print(v1);
//create v4 like merge of v and v1
std::vector <int> v3;
std::merge(std::begin(v), std::end(v), std::begin(v1), std::end(v1), std::back_inserter(v3));
print(v3);
//range for ordered insert
auto p = std::equal_range(v3.begin(), v3.end(), 1);
std::cout << *(p.first) << " - " << *(p.second) << std::endl;
//cout all vectors
print(v);
print(v1);
print(v2);
print(v3);
} | true |
73ebac687567e0424f524a35a93959193d7cc2ab | C++ | lamb-j/intro-graphics | /project1/project1B/project1B.cxx | UTF-8 | 5,001 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <vtkDataSet.h>
#include <vtkImageData.h>
#include <vtkPNGWriter.h>
#include <vtkPointData.h>
using std::cerr;
using std::endl;
double ceil441(double f)
{
return ceil(f-0.00001);
}
double floor441(double f)
{
return floor(f+0.00001);
}
vtkImageData *NewImage(int width, int height)
{
vtkImageData *img = vtkImageData::New();
img->SetDimensions(width, height, 1);
img->AllocateScalars(VTK_UNSIGNED_CHAR, 3);
return img;
}
void WriteImage(vtkImageData *img, const char *filename)
{
std::string full_filename = filename;
full_filename += ".png";
vtkPNGWriter *writer = vtkPNGWriter::New();
writer->SetInputData(img);
writer->SetFileName(full_filename.c_str());
writer->Write();
writer->Delete();
}
class Line {
public:
Line(double x1, double y1, double x2, double y2);
double getX(double y);
void printLine();
private:
double m;
double b;
int vert;
double vert_x;
};
Line::Line(double x1, double y1, double x2, double y2) {
if (x1 == x2) {
vert = 1;
vert_x = x1;
return;
}
else {
vert = 0;
}
m = (y2 - y1) / (x2 - x1);
b = y1 - m*x1;
}
double Line::getX(double y) {
if (vert) {
return vert_x;
}
else {
return (y - b) / m;
}
}
void Line::printLine() {
if (vert) {
printf("vertical line at x = %f\n", vert_x);
}
else {
printf("y = %f * x + %f\n", m, b);
}
}
class Triangle
{
public:
double X[3];
double Y[3];
unsigned char color[3];
int T, L, R;
Line *lLine;
Line *rLine;
// would some methods for transforming the triangle in place be helpful?
int getT();
int getL();
int getR();
void setPoints();
void createLines();
void freeLines();
};
int Triangle::getT() {
if (Y[0] > Y[1] && Y[0] > Y[2]) return 0;
if (Y[1] > Y[0] && Y[1] > Y[2]) return 1;
if (Y[2] > Y[1] && Y[2] > Y[0]) return 2;
return -1;
}
int Triangle::getL() {
if (T == -1) return -1;
if (T != 0 && X[0] <= X[1] && X[0] <= X[2]) return 0;
if (T != 1 && X[1] <= X[0] && X[1] <= X[2]) return 1;
if (T != 2 && X[2] <= X[0] && X[2] <= X[1]) return 2;
return -1;
}
int Triangle::getR() {
if (T == -1 || L == -1) return -1;
for (int i = 0; i < 3; i++)
if (T != i && L != i) return i;
return -1;
}
void Triangle::createLines() {
setPoints();
lLine = new Line(X[T], Y[T], X[L], Y[L]);
rLine = new Line(X[T], Y[T], X[R], Y[R]);
}
void Triangle::freeLines() {
delete lLine;
delete rLine;
}
void Triangle::setPoints() {
T = getT();
L = getL();
R = getR();
}
class Screen
{
public:
unsigned char *buffer;
int width, height;
// would some methods for accessing and setting pixels be helpful?
void ImageColor(int r, int c, unsigned char color[3]);
};
void Screen::ImageColor(int r, int c, unsigned char color[3]) {
if (r >= height || r < 0 || c >= width || c < 0) return;
int offset = 3*(r*width + c);
buffer[offset] = color[0];
buffer[offset + 1] = color[1];
buffer[offset + 2] = color[2];
}
std::vector<Triangle> GetTriangles(void)
{
std::vector<Triangle> rv(100);
unsigned char colors[6][3] = { {255,128,0}, {255, 0, 127}, {0,204,204},
{76,153,0}, {255, 204, 204}, {204, 204, 0}};
for (int i = 0 ; i < 100 ; i++)
{
int idxI = i%10;
int posI = idxI*100;
int idxJ = i/10;
int posJ = idxJ*100;
int firstPt = (i%3);
rv[i].X[firstPt] = posI;
if (i == 50)
rv[i].X[firstPt] = -10;
rv[i].Y[firstPt] = posJ;
rv[i].X[(firstPt+1)%3] = posI+99;
rv[i].Y[(firstPt+1)%3] = posJ;
rv[i].X[(firstPt+2)%3] = posI+i;
rv[i].Y[(firstPt+2)%3] = posJ+10*(idxJ+1);
if (i == 95)
rv[i].Y[(firstPt+2)%3] = 1050;
rv[i].color[0] = colors[i%6][0];
rv[i].color[1] = colors[i%6][1];
rv[i].color[2] = colors[i%6][2];
}
return rv;
}
int main()
{
vtkImageData *image = NewImage(1000, 1000);
unsigned char *buffer =
(unsigned char *) image->GetScalarPointer(0,0,0);
int npixels = 1000*1000;
for (int i = 0 ; i < npixels*3 ; i++)
buffer[i] = 0;
std::vector<Triangle> triangles = GetTriangles();
Screen screen;
screen.buffer = buffer;
screen.width = 1000;
screen.height = 1000;
// YOUR CODE GOES HERE TO DEPOSIT TRIANGLES INTO PIXELS USING THE SCANLINE ALGORITHM
for (int i = 0; i < triangles.size(); i++) {
//printf("Processing: Triangle %d\n", i);
triangles[i].createLines();
int L = triangles[i].L;
int T = triangles[i].T;
double rowMin = ceil441(triangles[i].Y[L]);
double rowMax = floor441(triangles[i].Y[T]);
// Scanline for this triangle
for (int r = rowMin; r <= rowMax; r++) {
double lEnd = triangles[i].lLine->getX(r);
double rEnd = triangles[i].rLine->getX(r);
for (int c = ceil441(lEnd); c <= floor441(rEnd); c++) {
screen.ImageColor(r, c, triangles[i].color);
}
}
triangles[i].freeLines();
}
WriteImage(image, "allTriangles");
}
| true |
d8124574032b60e597eb14dfabfcae0c13e234f7 | C++ | josephjaspers/OldProjects | /cpp/UNMAINTAINED-Matrix-Vector-Library3.0-CPP/Matrix/Matrix.h | UTF-8 | 1,950 | 3.03125 | 3 | [] | no_license | #ifndef Matrix_h
#define Matrix_h
#include <iostream>
#include <vector>
#include <fstream>
#include <ostream>
using namespace std;
class Matrix {
int l;
int w = 1;
int n;
double** theMatrix;
bool initialized = true;
public:
//Constructors
Matrix();
Matrix(unsigned int length, unsigned int width);
Matrix(const vector<vector<double>>& m);
Matrix(const Matrix& cpy);
~Matrix();
//simple accessors
int length() const;
int width() const;
int size() const;
//operators
Matrix& operator=(const Matrix & m);
bool operator== (const Matrix & m) const;
inline double& operator()(int length, int width);
Matrix operator^(const Matrix & m) const;
Matrix operator*(const Matrix & m) const;
Matrix operator/(const Matrix & m) const;
Matrix operator+(const Matrix & m) const;
Matrix operator-(const Matrix & m) const;
Matrix operator&(const Matrix& m) const;
Matrix& operator^=(const Matrix & m);
Matrix& operator/=(const Matrix & m);
Matrix& operator+=(const Matrix & m);
Matrix& operator-=(const Matrix & m);
Matrix& operator&=(const Matrix& m);
Matrix operator^(const double& d) const;
Matrix operator/(const double& d) const;
Matrix operator+(const double& d) const;
Matrix operator-(const double& d) const;
Matrix operator&(const double& d) const;
Matrix& operator^=(const double& d);
Matrix& operator/=(const double& d);
Matrix& operator+=(const double& d);
Matrix& operator-=(const double& d);
Matrix& operator&=(const double& d);
bool isColumnVector() const;
bool isRowVector() const;
Matrix transpose() const;
Matrix T() const {
return transpose();
}
vector<vector<double>> getCpyVect() const;
void print() const;
void print(int p) const;
static Matrix read(ifstream & f);
void write(ofstream & o);
const double& get(int x, int y) const;
private:
void deleteMatrix();
void initialize();
inline void chkBounds(const Matrix& m) const;
inline void chkBounds(int x, int y) const;
};
#endif | true |
8a5a4fc38c9ed9bc6a72f95109ca54f28b380c23 | C++ | lyandut/MyTravelingPurchaser | /MyTravelingPurchaser/TPPLIBInstance/TPPLIBInstance.h | GB18030 | 1,767 | 2.546875 | 3 | [] | no_license | #pragma once
#include <string>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <functional>
#include <cctype>
#include <cmath>
#include "../Main/TPPCommon.h"
class TPPLIBInstance
{
public:
std::string name;
std::string comment;
std::string instance_type;
std::string edge_weight_type;
std::string edge_weight_format; /* Ĭȫͼ: COMPLETE */
std::string edge_data_format;
std::string node_coord_type;
std::string display_data_type;
/* 㷨 */
unsigned int dimension;
std::vector<int> demands;
std::vector<std::vector<PriQua>> offer_lists;
std::vector<std::vector<NodePriQua>> offer_sort_lists;
std::vector<std::vector<int>> distance_matrix;
/* ȫͼߵӹϵ */
std::vector<std::pair<int, int>> edge_list;
/* ꣬ݾ뺯·ɿ distance_matrix */
std::vector<std::vector<double>> coordinates;
std::vector<std::vector<double>> display_coordinates;
TPPLIBInstance(){
name = "not specified";
comment = "not specified";
instance_type = "TPP";
edge_weight_type = "not specified";
edge_weight_format = "not specified";
edge_data_format = "COMPLETE";
node_coord_type = "NO_COORDS";
display_data_type = "NO_DISPLAY";
dimension = 0;
demands = std::vector<int>();
offer_lists = std::vector<std::vector<PriQua>>();
offer_sort_lists = std::vector<std::vector<NodePriQua>>();
distance_matrix = std::vector<std::vector<int>>();
edge_list = std::vector<std::pair<int, int>>();
coordinates = std::vector<std::vector<double>>();
display_coordinates = std::vector<std::vector<double>>();
}
~TPPLIBInstance() {}
};
class TPPLIBInstanceBuilder {
public:
static TPPLIBInstance * buildFromFile(std::string file_name);
};
| true |
94c66069b3bbb1cb985157e01100f00ca0e0d392 | C++ | batinkov/emtf_cell | /cactusprojects/emtf/hal_pciexpr/busAdapter/pciexpr/src/common/PCIExprLinuxBusAdapter.cc | UTF-8 | 12,981 | 2.578125 | 3 | [] | no_license | #include "hal/PCIExprLinuxBusAdapter.hh"
#include <sstream>
#include <iomanip>
HAL::PCIExprLinuxBusAdapter::PCIExprLinuxBusAdapter() throw (HAL::BusAdapterException)
try
: PCIBusAdapterInterface(),
pciBus_(){}
catch ( xpci::exception::IOError &e ) {
std::string err = std::string( e.what() );
throw BusAdapterException( e.what(), __FILE__, __LINE__, __FUNCTION__ );
}
HAL::PCIExprLinuxBusAdapter::~PCIExprLinuxBusAdapter() {
}
void HAL::PCIExprLinuxBusAdapter::findDeviceByIndex( uint32_t index )
throw (BusAdapterException,
NoSuchDeviceException) {
std::cout << "Initializing the MTF7 board #" << index;
char driver_string[100];
sprintf(driver_string, "%s%d", PCIEXPR_DEFAULT_FILE, index);
std::cout << ": driver is " << driver_string << std::endl;
device_d = open(driver_string,O_RDWR);
if (device_d < 0) {
std::cout << "ERROR: Can not open device file for SP12" << std::endl;
}
}
/*
Currently the driver for the MTF6(7) reads Vendor and Device ID to make sure it talks to the appropriate
boards. It also reads BAR registers to learn the starting addresses and sizes of address space windows
allocated for each board. However, the user-mode software is isolated from these details. As soon as one
opens a /dev/utca_sp12X device, we know that this is one of the boards.
As a consequence the methods findDeviceByBus, findDeviceByVendor and findDevice are temporarily left
empty as they are not useful.
*/
void HAL::PCIExprLinuxBusAdapter::findDeviceByBus( uint32_t busID,
uint32_t slotID,
uint32_t functionID,
const PCIAddressTable& pciAddressTable,
PCIDeviceIdentifier** deviceIdentifierPtr,
std::vector<uint32_t>& baseAddresses,
bool swapFlag )
throw (BusAdapterException,
NoSuchDeviceException) {
}
void HAL::PCIExprLinuxBusAdapter::findDeviceByVendor( uint32_t vendorID,
uint32_t deviceID,
uint32_t index,
const PCIAddressTable& pciAddressTable,
PCIDeviceIdentifier** deviceIdentifierPtr,
std::vector<uint32_t>& baseAddresses,
bool swapFlag )
throw (BusAdapterException,
NoSuchDeviceException) {
}
void HAL::PCIExprLinuxBusAdapter::findDevice( xpci::Address& deviceConfigAddress,
const PCIAddressTable& pciAddressTable,
PCIDeviceIdentifier** deviceIdentifierPtr,
std::vector<uint32_t>& baseAddresses,
bool swapFlag )
throw (BusAdapterException,
NoSuchDeviceException) {
}
void HAL::PCIExprLinuxBusAdapter::configWrite( PCIDeviceIdentifier& pciDevice,
uint32_t address,
uint32_t data)
throw( BusAdapterException ){
/*if ( (address%4 != 0) ) {
std::stringstream text;
text << "address or length not aligned to 4 byte boundary "
<< "\n address (hex) : " << std::hex << address
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
xpci::Address pciConfigAddress
= (dynamic_cast<HAL::PCIExprLinuxDeviceIdentifier&>(pciDevice)).getConfigAddress();
try {
pciBus_.write(pciConfigAddress, address, data);
} catch( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during write to address "
<< std::hex << address
<< " (data : " << data << ")"
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}*/
}
void HAL::PCIExprLinuxBusAdapter::configRead( PCIDeviceIdentifier& pciDevice,
uint32_t address,
uint32_t* data)
throw( BusAdapterException ){
/*if ( (address%4 != 0) ) {
std::stringstream text;
text << "address or length not aligned to 4 byte boundary "
<< "\n address (hex) : " << std::hex << address
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
xpci::Address pciConfigAddress
= (dynamic_cast<HAL::PCIExprLinuxDeviceIdentifier&>(pciDevice)).getConfigAddress();
try {
uint32_t val;
pciBus_.read(pciConfigAddress, address, val);
*data = val;
} catch( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during read from address "
<< std::hex << address
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}*/
}
void HAL::PCIExprLinuxBusAdapter::write( PCIDeviceIdentifier& device,
uint32_t address,
uint32_t data )
throw( BusAdapterException ) {
if ( (address%4 != 0) ) {
std::stringstream text;
text << "address or length not aligned to 4 bytes boundary "
<< "\n address (hex) : " << std::hex << address
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
// mwrite is the write function defined in the mtf7 driver
try {
mwrite(device_d, &data, 4, address);
}
catch ( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during write to address "
<< std::hex << address
<< " (data : " << data << ")"
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
}
void HAL::PCIExprLinuxBusAdapter::read( PCIDeviceIdentifier& device,
uint32_t address,
uint32_t* result )
throw( BusAdapterException ) {
if ( (address%4 != 0) ) {
std::stringstream text;
text << "address or length not aligned to 4 byte boundary "
<< "\n address (hex) : " << std::hex << address
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
try {
// mread is the standard read function defined in the mtf7 driver
mread(device_d, result, 4, address);
} catch( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during read from address "
<< std::hex << address
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
}
void HAL::PCIExprLinuxBusAdapter::writeBlock( PCIDeviceIdentifier& device,
uint32_t startAddress,
uint32_t length,
char *buffer,
HalAddressIncrement addressBehaviour)
throw( BusAdapterException ) {
//std::cout << "Do nothing for the time being..." << std::endl;
//std::cout << "startAddress="<< startAddress << std::endl;
//std::cout << "length=" << length << std::endl;
//std::cout << "buffer=" << buffer << std::endl; //this does not print anything
const int nWords = length/4;
uint32_t write_buf[nWords];
uint32_t* sourcePtr = (uint32_t*) buffer;
uint32_t ic;
for ( ic = 0; ic<nWords; ic++, sourcePtr++ ) {
//std::cout << "sourcePtr in writeBlock= " << *sourcePtr << std::endl;
write_buf[ic] = *sourcePtr;
//std::cout << std::dec << "HAL::PCIExprLinuxBusAdapter::writeBlock -> write_buf[" << ic << "]=" << write_buf[ic] << std::endl;
}
try {
mwrite(device_d, write_buf, length, startAddress-0x10);
}
catch( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during writeBlock to address "
<< std::hex << startAddress
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
// should I add an extra method? for like uint64_t and no HalAddressIncrement?...
// let's require the address to be aligned to 64 bit and then read
// uint32_ts
//if ( (startAddress%8 != 0) ||
// (length%8 != 0) ) {
// std::stringstream text;
// text << "Start address or length not aligned to 8 byte boundary "
// << "\n StartAddress (hex) : " << std::hex << startAddress
// << "\n BlockLength (hex) : " << std::hex << length
// << std::ends;
// std::string textStr = text.str();
// throw( BusAdapterException( textStr, __FILE__, __LINE__, __FUNCTION__ ) );
//}
//
/* // let's require the address to be aligned to 32 bit and then read
// uint32_ts
if ( (startAddress%4 != 0) ||
(length%4 != 0) ) {
std::stringstream text;
text << "Start address or length not aligned to 4 byte boundary "
<< "\n StartAddress (hex) : " << std::hex << startAddress
<< "\n BlockLength (hex) : " << std::hex << length
<< std::ends;
std::string textStr = text.str();
throw( BusAdapterException( textStr, __FILE__, __LINE__, __FUNCTION__ ) );
}
uint32_t* sourcePtr = (uint32_t*) buffer;
uint32_t nWords = length/4;
uint32_t ioff=0;
xpci::Address pciAddress = xpci::Address::getMemorySpaceAddress( startAddress );
try {
if ( device.doSwap() ) {
if ( addressBehaviour == HAL_DO_INCREMENT ) {
for ( uint32_t ic = 0; ic<nWords; ic++, sourcePtr++, ioff+=4 ) {
pciBus_.write( pciAddress, ioff, bswap_32(*sourcePtr) );
}
} else { // do not increment destination address
for (uint32_t ic = 0; ic<nWords; ic++, sourcePtr++ ) {
pciBus_.write( pciAddress, 0, bswap_32(*sourcePtr) );
}
}
} else {
if ( addressBehaviour == HAL_DO_INCREMENT ) {
for ( uint32_t ic = 0; ic<nWords; ic++, ioff+=4, sourcePtr++ ) {
pciBus_.write( pciAddress, ioff, *sourcePtr );
}
} else { // do not increment destination address
for (uint32_t ic = 0; ic<nWords; ic++, sourcePtr++ ) {
pciBus_.write( pciAddress, 0, *sourcePtr );
}
}
}
} catch( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during writeBlock to address "
<< std::hex << startAddress
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}*/
}
void HAL::PCIExprLinuxBusAdapter::readBlock( PCIDeviceIdentifier& device,
uint32_t startAddress,
uint32_t length,
char *buffer,
HalAddressIncrement addressBehaviour)
throw( BusAdapterException ) {
// std::cout << "startAddress=" << startAddress-0x10 << std::endl;
//std::cout << "length=" << length << std::endl;
try {
mread(device_d, buffer, length, startAddress-0x10);
}
catch( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during readBlock from startAddress "
<< std::hex << startAddress
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}
//std::cout << "mread command issued\n";
// const int nWords = length/4;
// uint32_t read_buf[nWords];
// uint32_t* sourcePtr = (uint32_t*) buffer;
// uint32_t ic;
// for ( ic = 0; ic<nWords; ic++, sourcePtr++ ) {
// read_buf[ic] = *sourcePtr;
// std::cout << "read_buf[" << ic << "]=" << read_buf[ic] << std::endl;
// }
/* // let's require the address to be aligned to 32 bit and then read
// uint32_ts
if ( (startAddress%4 != 0) ||
(length%4 != 0) ) {
std::stringstream text;
text << "Start address or length not aligned to 4 byte boundary "
<< "\n StartAddress (hex) : " << std::hex << startAddress
<< "\n BlockLength (hex) : " << std::hex << length
<< std::ends;
std::string textStr = text.str();
throw( BusAdapterException( textStr, __FILE__, __LINE__, __FUNCTION__ ) );
}
uint32_t* destPtr = (uint32_t*) buffer;
uint32_t nWords = length/4;
uint32_t ioff = 0;
xpci::Address pciAddress = xpci::Address::getMemorySpaceAddress( startAddress );
try {
if ( device.doSwap() ){
// byte swapping
if ( addressBehaviour == HAL_DO_INCREMENT ) {
for ( uint32_t ic = 0; ic<nWords; ic++, destPtr++, ioff+=4 ) {
uint32_t val;
pciBus_.read( pciAddress, ioff, val );
*destPtr = bswap_32( val );
}
} else { // do not increment source address
for (uint32_t ic = 0; ic<nWords; ic++, destPtr++ ) {
uint32_t val;
pciBus_.read( pciAddress, 0, val );
*destPtr = bswap_32( val );
}
}
// no byte swapping
} else {
if ( addressBehaviour == HAL_DO_INCREMENT ) {
for ( uint32_t ic = 0; ic<nWords; ic++, destPtr++, ioff+=4 ) {
uint32_t val;
pciBus_.read( pciAddress, ioff , val );
*destPtr = val;
}
} else { // do not increment source address
for (uint32_t ic = 0; ic<nWords; ic++, destPtr++ ) {
uint32_t val;
pciBus_.read( pciAddress, 0, val );
*destPtr = val;
}
}
}
} catch( xpci::exception::IOError &e ) {
std::stringstream text;
text << "error during readBlock from startAddress "
<< std::hex << startAddress
<< std::ends;
throw( BusAdapterException( text.str(), __FILE__, __LINE__, __FUNCTION__ ) );
}*/
}
void HAL::PCIExprLinuxBusAdapter::closeDevice( PCIDeviceIdentifier* deviceIdentifierPtr )
throw() {
/*delete(deviceIdentifierPtr); // this destroys the maps !!! */
}
| true |
d07855189437b32fdae6fe49ebdc83429d2ee45f | C++ | ITShadow/practiceCode | /topic/LeetCode/0692topKFrequent.cpp | UTF-8 | 1,614 | 3.265625 | 3 | [] | no_license | /* 给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。
示例 2:
输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。
注意:
假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
输入的单词均由小写字母组成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> hash;
priority_queue<pair<int, string>> q;
vector<string> re(k);
for(auto item : words) hash[item]++;
for(auto item : hash)
{
q.push(make_pair(-item.second, item.first));
if(q.size() > k) q.pop();
}
for(int i = k - 1; i >= 0; i --)
{
re[i] = q.top().second;
q.pop();
}
return re;
}
}; */
/* 注意字母排序是ASCII码大小 */ | true |
f27b0009db9eba7b4114fc6072ff7ecf525bd1f3 | C++ | bessszilard/Udemy-Learn-Advanced-Cpp-Programming | /src/L47_Initializer_Lists.cpp | UTF-8 | 544 | 3.65625 | 4 | [
"MIT"
] | permissive | //L47_Initializer_Lists.cpp
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
class Test {
public:
Test(initializer_list<string> texts) {
for(auto value : texts) {
cout << value << endl;
}
}
void print(initializer_list<string> texts) {
for(auto value : texts) {
cout << value << endl;
}
}
};
int main() {
vector<int> vInts = {1, 3, 4, 5, 6};
Test test1{"apple", "banana", "girafe"};
cout << endl;
return 0;
} | true |
82f5982252a955929650c66c1d830b77f8ecef88 | C++ | ibokuri/libvmm | /tests/kvm/vm.cpp | UTF-8 | 13,678 | 2.546875 | 3 | [
"MIT"
] | permissive | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "vmm/kvm/kvm.hpp"
TEST_CASE("VM creation") {
REQUIRE_NOTHROW(vmm::kvm::System{}.vm());
}
TEST_CASE("vCPU creation") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
const auto kvm_max_vcpus = kvm.check_extension(KVM_CAP_MAX_VCPUS);
const auto kvm_max_vcpu_id = kvm.check_extension(KVM_CAP_MAX_VCPU_ID);
REQUIRE(kvm_max_vcpu_id >= kvm_max_vcpus);
SECTION("Max # of vCPUs") {
for (auto id = 0; id < kvm_max_vcpus; id++)
REQUIRE_NOTHROW(vm.vcpu(id));
REQUIRE_THROWS(vm.vcpu(kvm_max_vcpus));
}
if (kvm_max_vcpu_id > kvm_max_vcpus) {
SECTION("Max IDs") {
for (auto id = kvm_max_vcpu_id - kvm_max_vcpus; id < kvm_max_vcpu_id; id++)
REQUIRE_NOTHROW(vm.vcpu(id));
REQUIRE_THROWS(vm.vcpu(kvm_max_vcpu_id));
}
}
}
TEST_CASE("Empty memory region") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
auto mem_region = kvm_userspace_memory_region{};
REQUIRE_THROWS(vm.set_memslot(mem_region));
}
TEST_CASE("vCPU and memory slot information") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
REQUIRE(vm.num_vcpus() >= 4);
REQUIRE(vm.max_vcpus() >= vm.num_vcpus());
REQUIRE(vm.num_memslots() >= 32);
}
TEST_CASE("IOEvent") {
using EventFd = vmm::types::EventFd;
using IoEventAddress = vmm::types::IoEventAddress;
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
auto eventfd = EventFd{EFD_NONBLOCK};
SECTION("Attach") {
if (vm.check_extension(KVM_CAP_IOEVENTFD) > 0) {
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Mmio>(eventfd, 0x1000));
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Pio>(eventfd, 0xf4));
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Pio>(eventfd, 0xc1, 0x7f));
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Pio>(eventfd, 0xc2, 0x1337));
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Pio>(eventfd, 0xc4, 0xdead'beef));
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Pio>(eventfd, 0xc8, 0xdead'beef'dead'beef));
}
}
SECTION("Detach") {
if (vm.check_extension(KVM_CAP_IOEVENTFD) > 0) {
auto pio_addr = uint64_t{0xf4};
auto mmio_addr = uint64_t{0x1000};
REQUIRE_THROWS(vm.detach_ioevent<IoEventAddress::Pio>(eventfd, pio_addr));
REQUIRE_THROWS(vm.detach_ioevent<IoEventAddress::Pio>(eventfd, mmio_addr));
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Pio>(eventfd, pio_addr));
REQUIRE_NOTHROW(vm.attach_ioevent<IoEventAddress::Pio>(eventfd, mmio_addr, 0x1337));
REQUIRE_NOTHROW(vm.detach_ioevent<IoEventAddress::Pio>(eventfd, pio_addr));
REQUIRE_NOTHROW(vm.detach_ioevent<IoEventAddress::Pio>(eventfd, mmio_addr, 0x1337));
}
}
}
#if defined(__i386__) || defined(__x86_64__) || \
defined(__arm__) || defined(__aarch64__)
TEST_CASE("IRQ Chip creation") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
if (vm.check_extension(KVM_CAP_IRQCHIP) > 0) {
REQUIRE_NOTHROW(vm.irqchip());
}
}
TEST_CASE("Fail MSI signal") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
auto msi = kvm_msi{};
// This throws b/c MSI vectors aren't chosen from the HW side (VMM). The
// guest OS (or anything that runs inside the VM) is supposed to allocate
// the MSI vectors, and usually communicates back through PCI
// configuration space. Sending a random MSI vector through signal_msi()
// will always result in a failure.
REQUIRE_THROWS(vm.signal_msi(msi));
}
#endif
#if defined(__i386__) || defined(__x86_64__)
// FIXME: In the kernel's KVM selftests, there is a FIXME for this test on
// aarch64 and s390x. On those platforms, KVM_RUN fails with ENOEXEC or EFAULT
// instead of successfully returning KVM_EXIT_INTERNAL_ERROR.
//
// Because of this, this test is currently x86 only. Once the fix is made in
// the kernel, the test should be made available for all platforms.
TEST_CASE("No memory region") {
const auto N = 64;
const auto VCPU_ID = 0;
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
auto vcpu = vm.vcpu(VCPU_ID);
REQUIRE_NOTHROW(vm.set_num_mmu_pages(N));
REQUIRE(vm.num_mmu_pages() == N);
REQUIRE(static_cast<uint32_t>(vcpu.run()) == KVM_EXIT_INTERNAL_ERROR);
}
TEST_CASE("IRQ chip") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
if (vm.check_extension(KVM_CAP_IRQCHIP) > 0) {
vm.irqchip();
auto irqchip1 = kvm_irqchip{KVM_IRQCHIP_PIC_MASTER};
irqchip1.chip.pic.irq_base = 10;
auto irqchip2 = kvm_irqchip{};
irqchip2.chip_id = KVM_IRQCHIP_PIC_MASTER;
REQUIRE_NOTHROW(vm.set_irqchip(irqchip1));
REQUIRE_NOTHROW(vm.get_irqchip(irqchip2));
REQUIRE(irqchip1.chip.pic.irq_base == irqchip2.chip.pic.irq_base);
}
}
TEST_CASE("Clock") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
if (vm.check_extension(KVM_CAP_ADJUST_CLOCK) > 0) {
auto orig = vm.get_clock();
auto other = kvm_clock_data{10};
vm.set_clock(other);
auto newtime = vm.get_clock();
REQUIRE(orig.clock > newtime.clock);
REQUIRE(newtime.clock > other.clock);
}
}
TEST_CASE("Bootstrap processor (BSP)") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
if (vm.check_extension(KVM_CAP_SET_BOOT_CPU_ID) > 0) {
SECTION("No vCPU") {
REQUIRE_NOTHROW(vm.set_bsp(0));
}
SECTION("vCPU") {
auto vcpu = vm.vcpu(0);
REQUIRE_THROWS(vm.set_bsp(0));
}
}
}
TEST_CASE("GSI routing") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
if (vm.check_extension(KVM_CAP_IRQ_ROUTING) > 0) {
auto table = vmm::kvm::IrqRouting<0>{};
SECTION("No IRQ chip") {
REQUIRE_THROWS(vm.gsi_routing(table));
}
SECTION("IRQ chip") {
vm.irqchip();
REQUIRE_NOTHROW(vm.gsi_routing(table));
}
}
}
TEST_CASE("IRQ line") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
REQUIRE_NOTHROW(vm.irqchip());
REQUIRE_NOTHROW(vm.set_irq_line(4, vmm::kvm::IrqLevel::Active));
REQUIRE_NOTHROW(vm.set_irq_line(4, vmm::kvm::IrqLevel::Inactive));
REQUIRE_NOTHROW(vm.set_irq_line(4, vmm::kvm::IrqLevel::Active));
}
TEST_CASE("IRQ file descriptor") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
auto eventfd1 = vmm::types::EventFd{EFD_NONBLOCK};
auto eventfd2 = vmm::types::EventFd{EFD_NONBLOCK};
auto eventfd3 = vmm::types::EventFd{EFD_NONBLOCK};
REQUIRE_NOTHROW(vm.irqchip());
REQUIRE_NOTHROW(vm.register_irqfd(eventfd1, 4));
REQUIRE_NOTHROW(vm.register_irqfd(eventfd2, 8));
REQUIRE_NOTHROW(vm.register_irqfd(eventfd3, 4));
// NOTE: On x86_64, this fails as the event fd was already matched with
// a GSI.
REQUIRE_THROWS(vm.register_irqfd(eventfd3, 4));
REQUIRE_THROWS(vm.register_irqfd(eventfd3, 5));
// NOTE: KVM doesn't report the 2nd, duplicate unregister as an error
REQUIRE_NOTHROW(vm.unregister_irqfd(eventfd2, 8));
REQUIRE_NOTHROW(vm.unregister_irqfd(eventfd2, 8));
// NOTE: KVM doesn't report unregisters with different levels as errors
REQUIRE_NOTHROW(vm.unregister_irqfd(eventfd3, 5));
}
TEST_CASE("TSS address") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
REQUIRE_NOTHROW(vm.set_tss_address(0xfffb'd000));
}
TEST_CASE("PIT2") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
SECTION("Creation/get") {
// NOTE: For some reason, create_pit2() doesn't throw even when irqchip
// support isn't enabled via irqchip().
REQUIRE_NOTHROW(vm.irqchip());
REQUIRE_NOTHROW(vm.create_pit2());
REQUIRE_NOTHROW(vm.pit2());
}
SECTION("Set") {
REQUIRE_NOTHROW(vm.irqchip());
REQUIRE_NOTHROW(vm.create_pit2());
auto pit2 = vm.pit2();
REQUIRE_NOTHROW(vm.set_pit2(pit2));
auto other = vm.pit2();
// Overwrite load times as they may differ
other.channels[0].count_load_time = pit2.channels[0].count_load_time;
other.channels[1].count_load_time = pit2.channels[1].count_load_time;
other.channels[2].count_load_time = pit2.channels[2].count_load_time;
for (std::size_t i = 0; i < 3; i++) {
REQUIRE(pit2.channels[i].count == other.channels[i].count);
REQUIRE(pit2.channels[i].latched_count == other.channels[i].latched_count);
REQUIRE(pit2.channels[i].count_latched == other.channels[i].count_latched);
REQUIRE(pit2.channels[i].status_latched == other.channels[i].status_latched);
REQUIRE(pit2.channels[i].status == other.channels[i].status);
REQUIRE(pit2.channels[i].read_state == other.channels[i].read_state);
REQUIRE(pit2.channels[i].write_state == other.channels[i].write_state);
REQUIRE(pit2.channels[i].write_latch == other.channels[i].write_latch);
REQUIRE(pit2.channels[i].rw_mode == other.channels[i].rw_mode);
REQUIRE(pit2.channels[i].mode == other.channels[i].mode);
REQUIRE(pit2.channels[i].bcd == other.channels[i].bcd);
REQUIRE(pit2.channels[i].gate == other.channels[i].gate);
}
}
}
#endif
#if defined(__arm__) || defined(__aarch64__)
TEST_CASE("IRQ chip") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
if (vm.check_extension(KVM_CAP_IRQCHIP)) {
REQUIRE_NOTHROW(vm.device(KVM_DEV_TYPE_ARM_VGIC_V2, KVM_CREATE_DEVICE_TEST));
REQUIRE_NOTHROW(vm.irqchip());
}
}
TEST_CASE("GSI routing") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
if (vm.check_extension(KVM_CAP_IRQ_ROUTING) > 0) {
auto entry = kvm_irq_routing_entry{};
auto routing_list = vmm::kvm::IrqRouting<1>{entry};
REQUIRE_NOTHROW(vm.gsi_routing(routing_list));
}
}
#endif
#if defined(__arm__) || defined(__aarch64__)
TEST_CASE("Preferred target") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
REQUIRE_NOTHROW(vm.preferred_target());
}
#endif
#if defined(__aarch64__)
TEST_CASE("IRQ line") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
auto vcpu = vm.vcpu(0);
auto vgic = vm.device(KVM_DEV_TYPE_ARM_VGIC_V3);
// Set supported # of IRQs
auto attributes = kvm_device_attr {
0, // flags
KVM_DEV_ARM_VGIC_GRP_NR_IRQS, // group
0, // attr
128, // addr
};
REQUIRE_NOTHROW(vgic.set_attr(attributes));
// Request vGIC initialization
attributes = kvm_device_attr {
0, // flags
KVM_DEV_ARM_VGIC_GRP_CTRL, // group
KVM_DEV_ARM_VGIC_CTRL_INIT, // attr
128, // addr
};
REQUIRE_NOTHROW(vgic.set_attr(attributes));
// On arm/aarch64, irq field is interpreted like so:
//
// bits: | 31 ... 24 | 23 ... 16 | 15 ... 0 |
// field: | irq_type | vcpu_index | irq_id |
//
// The irq_type field has the following values:
//
// - irq_type[0]: out-of-kernel GIC: irq_id 0 is IRQ, irq_id 1 is FIQ
// - irq_type[1]: in-kernel GIC: SPI, irq_id between 32 and 1019 (incl.) (the vcpu_index field is ignored)
// - irq_type[2]: in-kernel GIC: PPI, irq_id between 16 and 31 (incl.)
// Case 1: irq_type = 1, irq_id = 32 (decimal)
REQUIRE_NOTHROW(vm.set_irq_line(0x01'00'0020, vmm::kvm::IrqLevel::Active));
REQUIRE_NOTHROW(vm.set_irq_line(0x01'00'0020, vmm::kvm::IrqLevel::Inactive));
REQUIRE_NOTHROW(vm.set_irq_line(0x01'00'0020, vmm::kvm::IrqLevel::Active));
// Case 2: irq_type = 2, vcpu_index = 0, irq_id = 16 (decimal)
REQUIRE_NOTHROW(vm.set_irq_line(0x02'00'0010, vmm::kvm::IrqLevel::Active));
REQUIRE_NOTHROW(vm.set_irq_line(0x02'00'0010, vmm::kvm::IrqLevel::Inactive));
REQUIRE_NOTHROW(vm.set_irq_line(0x02'00'0010, vmm::kvm::IrqLevel::Active));
}
TEST_CASE("IRQ file descriptor") {
auto kvm = vmm::kvm::System{};
auto vm = kvm.vm();
auto vgic = vm.device(KVM_DEV_TYPE_ARM_VGIC_V3);
auto eventfd1 = vmm::types::EventFd{EFD_NONBLOCK};
auto eventfd2 = vmm::types::EventFd{EFD_NONBLOCK};
auto eventfd3 = vmm::types::EventFd{EFD_NONBLOCK};
// Set supported # of IRQs
auto attributes = kvm_device_attr {
0, // flags
KVM_DEV_ARM_VGIC_GRP_NR_IRQS, // group
0, // attr
128, // addr
};
REQUIRE_NOTHROW(vgic.set_attr(attributes));
// Request vGIC initialization
attributes = kvm_device_attr {
0, // flags
KVM_DEV_ARM_VGIC_GRP_CTRL, // group
KVM_DEV_ARM_VGIC_CTRL_INIT, // attr
128, // addr
};
REQUIRE_NOTHROW(vgic.set_attr(attributes));
REQUIRE_NOTHROW(vm.register_irqfd(eventfd1, 4));
REQUIRE_NOTHROW(vm.register_irqfd(eventfd2, 8));
REQUIRE_NOTHROW(vm.register_irqfd(eventfd3, 4));
// NOTE: On aarch64, duplicate registrations fail b/c setting up the
// interrupt controller is mandatory before any IRQ registration.
REQUIRE_THROWS(vm.register_irqfd(eventfd3, 4));
REQUIRE_THROWS(vm.register_irqfd(eventfd3, 5));
// NOTE: KVM doesn't report the 2nd, duplicate unregister as an error
REQUIRE_NOTHROW(vm.unregister_irqfd(eventfd2, 8));
REQUIRE_NOTHROW(vm.unregister_irqfd(eventfd2, 8));
// NOTE: KVM doesn't report unregisters with different levels as errors
REQUIRE_NOTHROW(vm.unregister_irqfd(eventfd3, 5));
}
#endif
| true |
49dad42b05322ac2e1aaa433ff9f594e78dc3ba9 | C++ | yi-juchung/lanarts | /src/objects/GameInst.h | UTF-8 | 2,762 | 2.734375 | 3 | [] | no_license | /*
*GameInst.h:
* Base object of the game object inheritance heirarchy
* Life cycle of GameInst initialization:
* ->Constructor
* ->GameState::add_instance(obj) called
* ->GameInstSet::add_instance(obj) called from GameState::add_instance, sets id
* ->GameInst::init(GameState) called from GameState::add_instance, does further initialization
* ->
*/
#ifndef GAMEINST_H_
#define GAMEINST_H_
#include <cassert>
#include <luawrap/LuaValue.h>
#include <lcommon/geometry.h>
#include <lcommon/math_util.h>
#include "lanarts_defines.h"
struct lua_State;
class GameState;
class GameMapState;
class SerializeBuffer;
//Base class for game instances
class GameInst {
public:
/* Reference count functions*/
static void retain_reference(GameInst* inst);
static void free_reference(GameInst* inst);
GameInst(float x, float y, float radius, bool solid = true, int depth = 0) :
reference_count(0), id(0), last_x(iround(x)), last_y(iround(y)), x(x), y(y), radius(
radius), target_radius(radius), depth(depth), solid(solid), destroyed(
false), current_floor(-1) {
if (this->radius > 14)
this->radius = 14;
}
virtual ~GameInst();
/* Initialize the object further, 'id' will be set*/
virtual void init(GameState* gs);
/* Deinitialize the object, removing eg child instances*/
virtual void deinit(GameState* gs);
virtual void step(GameState* gs);
virtual void draw(GameState* gs);
virtual void copy_to(GameInst* inst) const;
virtual void serialize(GameState* gs, SerializeBuffer& serializer);
void serialize_lua(GameState* gs, SerializeBuffer& serializer);
virtual void deserialize(GameState* gs, SerializeBuffer& serializer);
void deserialize_lua(GameState* gs, SerializeBuffer& serializer);
virtual GameInst* clone() const;
//Used for integrity checking
virtual unsigned int integrity_hash();
virtual void update_position(float newx, float newy);
bool try_callback(const char* callback);
void lua_lookup(lua_State* L, const char* key);
GameMapState* get_map(GameState* gs);
BBox bbox() {
return BBox(iround(x - radius), iround(y - radius), iround(x + radius),
iround(y + radius));
}
PosF pos() {
return PosF(x, y);
}
Pos ipos() {
return Pos(iround(x), iround(y));
}
//Used for keeping object from being deleted arbitrarily
//Important for the GameInst lua binding
int reference_count;
/*Should probably keep these public, many functions operate on these*/
obj_id id;
int last_x, last_y;
float x, y, radius, target_radius;
int depth;
bool solid, destroyed;
level_id current_floor;
LuaValue lua_variables;
};
typedef bool (*col_filterf)(GameInst* o1, GameInst* o2);
#endif /* GAMEINST_H_ */
| true |
96d744daa986221c4c173e8189898e1e5d7571b0 | C++ | SiChiTong/sclagv | /odom_tutorial/src/odom_pose.cpp | UTF-8 | 2,787 | 2.59375 | 3 | [] | no_license | #include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include "tf2/LinearMath/Quaternion.h"
#include "tf2/LinearMath/Matrix3x3.h"
#include <string>
#define RAD2DEG 57.295779513
/**
* This tutorial demonstrates receiving ZED odom and pose messages over the ROS system.
*/
double tx, ty, tz;
double roll, pitch, yaw;
/**
* Subscriber callbacks
*/
void poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) {
// Camera position in map frame
tx = msg->pose.position.x;
ty = msg->pose.position.y;
tz = msg->pose.position.z;
// Orientation quaternion
tf2::Quaternion q(
msg->pose.orientation.x,
msg->pose.orientation.y,
msg->pose.orientation.z,
msg->pose.orientation.w);
// 3x3 Rotation matrix from quaternion
tf2::Matrix3x3 m(q);
// Roll Pitch and Yaw from rotation matrix
m.getRPY(roll, pitch, yaw);
// Output the measure
ROS_INFO("Received pose in '%s' frame : X: %.2f Y: %.2f Z: %.2f - R: %.2f P: %.2f Y: %.2f",
msg->header.frame_id.c_str(),
tx, ty, tz,
roll * RAD2DEG, pitch * RAD2DEG, yaw * RAD2DEG);
}
/**
* Node main function
*/
int main(int argc, char** argv) {
// Node initialization
ros::init(argc, argv, "odom_pose");
ros::NodeHandle n;
tf::TransformBroadcaster odom_broadcaster;
ros::Publisher odom_pub = n.advertise<nav_msgs::Odometry>("odom0", 50);
// Topic subscribers
ros::Subscriber subPose = n.subscribe("/orb_slam2_rgbd/pose", 10, &poseCallback);
ros::Rate loop_rate(1);
while(n.ok())
{
ros::spinOnce();
geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(yaw);
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = ros::Time::now();
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_footprint";
odom_trans.transform.translation.x = tx - 0.275;
odom_trans.transform.translation.y = ty;
odom_trans.transform.translation.z = -0.66;
odom_trans.transform.rotation = odom_quat;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
nav_msgs::Odometry odom;
odom.header.stamp = ros::Time::now();
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = tx - 0.275;
odom.pose.pose.position.y = ty;
odom.pose.pose.position.z = -0.66;
odom.pose.pose.orientation = odom_quat;
odom.child_frame_id = "base_footprint";
//publish the message
odom_pub.publish(odom);
loop_rate.sleep();
}
return 0;
}
| true |
44c3b9f4061de99df6cc9c50e68e3d2408357eb9 | C++ | darksworm/hksel | /src/config/ConfigBuilder.h | UTF-8 | 318 | 2.609375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Config.h"
class ConfigBuilder {
private:
Config* config;
public:
ConfigBuilder() {
config = new Config();
}
ConfigBuilder& setIsDebug(bool isDebug) {
config->isDebug = isDebug;
return *this;
}
Config* build() {
return config;
}
};
| true |
ea1821128df972441f62aaa98f702bdd72ed398f | C++ | walkccc/LeetCode | /solutions/1631. Path With Minimum Effort/1631.cpp | UTF-8 | 1,316 | 2.984375 | 3 | [
"MIT"
] | permissive | struct T {
int i;
int j;
int d;
T(int i, int j, int d) : i(i), j(j), d(d) {}
};
class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {
const int m = heights.size();
const int n = heights[0].size();
const vector<int> dirs{0, 1, 0, -1, 0};
auto compare = [](const T& a, const T& b) { return a.d > b.d; };
priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);
// diff[i][j] := max absolute difference to reach (i, j).
vector<vector<int>> diff(m, vector<int>(n, INT_MAX));
vector<vector<bool>> seen(m, vector<bool>(n));
minHeap.emplace(0, 0, 0);
diff[0][0] = 0;
while (!minHeap.empty()) {
const auto [i, j, d] = minHeap.top();
minHeap.pop();
if (i == m - 1 && j == n - 1)
return d;
seen[i][j] = true;
for (int k = 0; k < 4; ++k) {
const int x = i + dirs[k];
const int y = j + dirs[k + 1];
if (x < 0 || x == m || y < 0 || y == n)
continue;
if (seen[x][y])
continue;
const int newDiff = abs(heights[i][j] - heights[x][y]);
const int maxDiff = max(diff[i][j], newDiff);
if (diff[x][y] > maxDiff) {
diff[x][y] = maxDiff;
minHeap.emplace(x, y, maxDiff);
}
}
}
throw;
}
};
| true |
4419fa498e02667aa3f995e4c50ca433938ce139 | C++ | abhiramrp/LoShuSquare | /Player.h | UTF-8 | 2,561 | 3.109375 | 3 | [] | no_license | /******************************************************************
CIS 22B
Lab6: Header File - This class initiaties the base Lo Shu game.
Author: Abhiram Rishi Prattipati
Date: March 22, 2019
*******************************************************************/
#ifndef PLAYER_H_INCLUDED
#define PLAYER_H_INCLUDED
#include <iostream>
#include <string>
#include "LoShuSquare.h"
using namespace std;
class Player : public LoShuSquare {
private:
LoShuSquare gamer; //only Player can use LoShuSquare as object
public:
Player(LoShuSquare gamer)
{
bool trail = false;
while(!trail)
{
cout << endl;
gamer.getNum();
gamer.print();
bool check = gamer.checkTotalSum();
if(check)
{
cout << "Good job!" << endl;
trail = check;
}
else
{
cout << "Try again!" << endl;
trail = check;
}
}
}
};
#endif // PLAYER_H_INCLUDED
/******************************************************************
Welcome to Lo Shu Square Game!
Enter a number between 1 to 9 for row 1 and column 1:1
Enter a number between 1 to 9 for row 1 and column 2:20
Number should be between 1 and 9.3
Enter a number between 1 to 9 for row 1 and column 3:-4
Number should be between 1 and 9.
4
Enter a number between 1 to 9 for row 2 and column 1:5
Enter a number between 1 to 9 for row 2 and column 2:6
Enter a number between 1 to 9 for row 2 and column 3:7
Enter a number between 1 to 9 for row 3 and column 1:8
Enter a number between 1 to 9 for row 3 and column 2:9
Enter a number between 1 to 9 for row 3 and column 3:5
The Lo Shu Square
1 3 4
5 6 7
8 9 5
Try again!
Enter a number between 1 to 9 for row 1 and column 1:4
Enter a number between 1 to 9 for row 1 and column 2:9
Enter a number between 1 to 9 for row 1 and column 3:2
Enter a number between 1 to 9 for row 2 and column 1:3
Enter a number between 1 to 9 for row 2 and column 2:5
Enter a number between 1 to 9 for row 2 and column 3:7
Enter a number between 1 to 9 for row 3 and column 1:8
Enter a number between 1 to 9 for row 3 and column 2:1
Enter a number between 1 to 9 for row 3 and column 3:6
The Lo Shu Square
4 9 2
3 5 7
8 1 6
Good job!
Process returned 0 (0x0) execution time : 44.861 s
Press any key to continue.
*******************************************************************/
| true |
fc68244b8e3c66d58cc0101ba0cd5b7b95ebccea | C++ | ng29/My-Codes | /stl-containers/stack.cpp | UTF-8 | 1,092 | 4.40625 | 4 | [] | no_license | /*
Stack is very specific container, it allows to store multiple values
But only one that is on top is accessible (via std::stack.top() function)
You can of course pop value from the top of the stack
*/
#include <stack>
#include <iostream>
template <typename T>
void prints(std::stack<T> s) {
// We have to copy our stack instead of referencing it,
// because we will need to pop values in order to print all of them
while (!s.empty()) {
std::cout << s.top() << std::endl;
s.pop();
}
}
int main() {
// Stack initializatoin
std::stack<int> stack;
// Inserting values into the stack
stack.push(10); // stack.push() pushes values on the top of the stack
stack.push(20);
stack.push(30);
stack.push(2137);
// Getting size of the stack
std::cout << stack.size() << std::endl;
// Accessing value from the top of the stack
std::cout << stack.top() << std::endl;
// Popping value from the stack
stack.pop(); // This will remove 2137 as it's the value on top
// Printing whole stack
prints(stack);
} | true |
0bf92d1272d8840b16c8aa89c7fa8751ab28530e | C++ | MazenAli/HTFI | /htucker/oldtools/indexmapper.h | UTF-8 | 704 | 2.609375 | 3 | [] | no_license | #ifndef LAWA_HTUCKER_TENSOR_H
#define LAWA_HTUCKER_TENSOR_H 1
//wrapps a discrete function into a tensor, i.e.
#include <fima/HTucker/dimensionindex.h>
template <typename T>
class tensor{
public:
typedef T (*funpoint)(DimensionIndex);
funpoint f;
int dimension;
DimensionIndex minval,maxval;
//constructors
tensor():dimension(0){};
tensor(funpoint g, int d):f(g),dimension(d){};
tensor(funpoint g, int d, int _min, int _max);
tensor(funpoint g, int d, DimensionIndex _min, DimensionIndex _max);
T
LinfNorm(int n);
//Evaluation operator
T operator()(DimensionIndex para);
};
#include <fima/HTucker/tensor.tcc>
#endif // LAWA_HTUCKER_TENSOR_H
| true |
d4e327b906b2d568ec573b010ac3cae60a63eaa8 | C++ | GJnghost/ACM-Template-by-forever97 | /Graph-Theory/Steine-Tree.cpp | UTF-8 | 13,865 | 2.8125 | 3 | [] | no_license | // 斯坦纳树:只用包含关键点的最小生成树
/*
* Problem: 给出一张图,要求i属于1~d号点与n-i+1号点对应连通,求最小边权和
* Solution: f[i][msk]表示i为根,关键点连通状态为msk时候的最小代价
* Ans[msk]表示连通态为msk时最小代价,如果对应点同时连通或不连通则可以更新
*/
// Demo1
#include <bits/stdc++.h>
using namespace std;
const int N = 10005;
const int MOD = 1e9 + 7;
int n, m, d, x, y, z;
int nxt[N << 1], g[N], v[N << 1], w[N << 1], tot;
int a[N], All, f[N][(1 << 8) + 10], INF, vis[N];
int Ans[(1 << 8) + 10];
void add_edge(int a, int b, int c) {
nxt[++tot] = g[a];
g[a] = tot;
v[tot] = b;
w[tot] = c;
}
void Add(int a, int b, int c) {
add_edge(a, b, c);
add_edge(b, a, c);
}
typedef pair<int, int> seg;
priority_queue<seg, vector<seg>, greater<seg>> q;
namespace Steiner {
void init() {
memset(f, 63, sizeof(f));
INF = f[0][0];
int num = 0;
for (int i = 1; i <= d; i++) f[i][1 << num] = 0, num++;
for (int i = n - d + 1; i <= n; i++) f[i][1 << num] = 0, num++;
All = (1 << num) - 1;
}
void Dijkstra(int msk) {
while (q.size()) {
int x = q.top().second;
q.pop();
for (int e = g[x]; e; e = nxt[e]) {
int y = v[e];
if (f[y][msk] > f[x][msk] + w[e]) {
f[y][msk] = f[x][msk] + w[e];
if (!vis[y]) {
vis[y] = 1;
q.push(make_pair(f[y][msk], y));
}
}
}
vis[x] = 0;
}
}
void Deal() {
for (int msk = 0; msk <= All; msk++) {
for (int i = 1; i <= n; i++) {
for (int sub = msk; sub; sub = (sub - 1) & msk)
f[i][msk] = min(f[i][msk], f[i][sub] + f[i][msk ^ sub]);
if (f[i][msk] != INF) {
q.push(make_pair(f[i][msk], i));
vis[i] = 1;
}
}
Dijkstra(msk);
}
}
} // namespace Steiner
bool Check(int msk) {
for (int i = 0, j = (d << 1) - 1; i < d; i++, j--)
if (((msk & (1 << i)) == 0) != ((msk & (1 << j)) == 0)) return 0;
return 1;
}
int main() {
scanf("%d%d%d", &n, &m, &d);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &z);
Add(x, y, z);
}
Steiner::init();
Steiner::Deal();
memset(Ans, 63, sizeof(Ans));
for (int msk = 0; msk <= All; msk++)
if (Check(msk)) {
for (int i = 1; i <= n; i++) Ans[msk] = min(Ans[msk], f[i][msk]);
}
for (int msk = 0; msk <= All; msk++)
for (int sub = msk; sub; sub = (sub - 1) & msk)
Ans[msk] = min(Ans[msk], Ans[sub] + Ans[msk ^ sub]);
if (Ans[All] == INF)
printf("-1");
else
printf("%d", Ans[All]);
return 0;
}
// Demo2
#include <bits/stdc++.h>
const int MOD = 1e9 + 7;
using Info = std::pair<int, int>;
template <typename T>
using PQ = std::priority_queue<T, std::vector<T>, std::greater<T>>;
static const Info ONE{1, 1};
int lowbit(int msk) { return msk & -msk; }
Info add(const Info& a, const Info& b) {
return {a.first + b.first, 1LL * a.second * b.second % MOD};
}
void update(Info& x, const Info& a) {
if (a.first < x.first) {
x = {a.first, 0};
}
if (a.first == x.first) {
x.second += a.second;
if (x.second >= MOD) {
x.second -= MOD;
}
}
}
int n, m, l;
int Ans[(1 << 8) + 10];
bool Check(int msk) {
for (int i = 0, j = (l << 1) - 1; i < l; i++, j--)
if (((msk & (1 << i)) == 0) != ((msk & (1 << j)) == 0)) return 0;
return 1;
}
int main() {
while (~scanf("%d%d%d", &n, &m, &l)) {
memset(Ans, 63, sizeof(Ans));
int INF = Ans[0];
std::vector<std::vector<int>> graph(n);
std::vector<std::vector<int>> W(n);
for (int i = 0, a, b, c; i < m; i++) {
scanf("%d%d%d", &a, &b, &c);
a--, b--;
graph[a].push_back(b);
W[a].push_back(c);
graph[b].push_back(a);
W[b].push_back(c);
}
int All = (1 << (l << 1)) - 1;
std::vector<std::vector<Info>> dp(All + 1,
std::vector<Info>(n, Info{INF, 0})),
merged(n, std::vector<Info>(All + 1, Info{INF, 0}));
int num = 0;
for (int i = 0; i < l; i++) {
dp[1 << num][i] = {0, 1};
num++;
}
for (int i = n - l; i < n; i++) {
dp[1 << num][i] = {0, 1};
num++;
}
for (int msk = 0; msk < 1 << (l << 1); msk++) {
for (int u = 0; u < n; u++) {
auto& ref = merged.at(u);
for (int subset = msk; subset > 0; subset = subset - 1 & msk) {
if (lowbit(subset) == lowbit(msk)) {
update(ref.at(msk),
add(dp.at(subset).at(u), ref.at(msk ^ subset)));
}
}
}
for (int u = 0; u < n; u++) {
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
int w = W[u][i];
update(dp.at(msk).at(v),
add(merged.at(u).at(msk), Info{w, 1}));
}
}
auto& ref = dp.at(msk);
PQ<std::pair<int, int>> pq;
for (int u = 0; u < n; u++) {
pq.emplace(ref.at(u).first, u);
}
while (!pq.empty()) {
auto top = pq.top();
pq.pop();
int u = top.second;
if (top.first == ref.at(u).first) {
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
int w = W[u][i];
Info todo = add(ref.at(u), Info{w, 1});
if (todo.first < ref.at(v).first) {
pq.emplace(todo.first, v);
}
update(ref.at(v), todo);
}
}
}
for (int u = 0; u < n; u++) {
update(merged.at(u).at(msk), dp.at(msk).at(u));
}
}
for (int msk = 0; msk <= All; msk++)
if (Check(msk)) {
for (int i = 0; i < n; i++) {
int tmp = merged.at(i).at(msk).first;
Ans[msk] = std::min(Ans[msk], tmp);
}
}
for (int msk = 0; msk <= All; msk++)
for (int sub = msk; sub; sub = (sub - 1) & msk)
Ans[msk] = std::min(Ans[msk], Ans[sub] + Ans[msk ^ sub]);
if (Ans[All] == INF)
printf("-1");
else
printf("%d", Ans[All]);
}
return 0;
}
/*
* 超级源点题
* 给出一些庙宇的位置,以及另一些位置,每个位置都可以打井,打井的费用不同,
* 现在这些位置不连通,让两个位置连通需要修路,给出修每条路的代价,
* 现在问这些庙宇都能喝上水(该处是水井或者能到有水井的地方)需要的最小总代价
*
* 建立一个超级源点表示水源,打井的代价转化为该地到水源的路的代价
* 那么题目转化为将水源与所有庙宇连在一起需要的最小代价,斯坦纳树求解即可
*/
#include <bits/stdc++.h>
const int MOD = 1e9 + 7;
using Info = std::pair<int, int>;
template <typename T>
using PQ = std::priority_queue<T, std::vector<T>, std::greater<T>>;
static const Info ONE{1, 1};
int lowbit(int msk) { return msk & -msk; }
Info add(const Info& a, const Info& b) {
return {a.first + b.first, 1LL * a.second * b.second % MOD};
}
void update(Info& x, const Info& a) {
if (a.first < x.first) {
x = {a.first, 0};
}
if (a.first == x.first) {
x.second += a.second;
if (x.second >= MOD) {
x.second -= MOD;
}
}
}
int n, m, l;
int main() {
while (~scanf("%d%d%d", &n, &m, &l)) {
std::vector<std::vector<int>> graph(n + m + 1);
std::vector<std::vector<int>> W(n + m + 1);
for (int i = 1, c; i <= n + m; i++) {
scanf("%d", &c);
graph[i].push_back(0);
W[i].push_back(c);
graph[0].push_back(i);
W[0].push_back(c);
}
int INF = 1 << 28;
for (int i = 0, a, b, c; i < l; i++) {
scanf("%d%d%d", &a, &b, &c);
graph[a].push_back(b);
W[a].push_back(c);
graph[b].push_back(a);
W[b].push_back(c);
}
int All = (1 << (n + 1)) - 1;
std::vector<std::vector<Info>> dp(
All + 1, std::vector<Info>(n + m + 1, Info{INF, 0})),
merged(n + m + 1, std::vector<Info>(All + 1, Info{INF, 0}));
int num = 0;
for (int i = 0; i <= n; i++) {
dp[1 << num][i] = {0, 1};
num++;
}
for (int msk = 0; msk < 1 << (n + 1); msk++) {
for (int u = 0; u <= n + m; u++) {
auto& ref = merged.at(u);
for (int subset = msk; subset > 0; subset = subset - 1 & msk) {
if (lowbit(subset) == lowbit(msk)) {
update(ref.at(msk),
add(dp.at(subset).at(u), ref.at(msk ^ subset)));
}
}
}
for (int u = 0; u <= n + m; u++) {
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
int w = W[u][i];
update(dp.at(msk).at(v),
add(merged.at(u).at(msk), Info{w, 1}));
}
}
auto& ref = dp.at(msk);
PQ<std::pair<int, int>> pq;
for (int u = 0; u <= n + m; u++) {
pq.emplace(ref.at(u).first, u);
}
while (!pq.empty()) {
auto top = pq.top();
pq.pop();
int u = top.second;
if (top.first == ref.at(u).first) {
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
int w = W[u][i];
Info todo = add(ref.at(u), Info{w, 1});
if (todo.first < ref.at(v).first) {
pq.emplace(todo.first, v);
}
update(ref.at(v), todo);
}
}
}
for (int u = 0; u <= n + m; u++) {
update(merged.at(u).at(msk), dp.at(msk).at(u));
}
}
int ans = INF;
for (int i = 0; i <= n + m; i++) {
int tmp = merged.at(i).at(All).first;
ans = std::min(ans, tmp);
}
printf("%d\n", ans);
}
return 0;
}
// 给出一张图,求斯坦纳树的方案数
#include <bits/stdc++.h>
const int MOD = 1e9 + 7;
using Info = std::pair<int, int>;
template <typename T>
using PQ = std::priority_queue<T, std::vector<T>, std::greater<T>>;
static const Info ONE{1, 1};
int lowbit(int msk) { return msk & -msk; }
Info add(const Info& a, const Info& b) {
return {a.first + b.first, 1LL * a.second * b.second % MOD};
}
void update(Info& x, const Info& a) {
if (a.first < x.first) {
x = {a.first, 0};
}
if (a.first == x.first) {
x.second += a.second;
if (x.second >= MOD) {
x.second -= MOD;
}
}
}
int main() {
int n, m, l;
while (~scanf("%d%d%d", &n, &m, &l)) {
std::vector<std::vector<int>> graph(n);
for (int i = 0, a, b; i < m; i++) {
scanf("%d%d", &a, &b);
a--, b--;
graph[a].push_back(b);
graph[b].push_back(a);
}
if (l == 1) {
puts("1");
continue;
}
l--;
std::vector<std::vector<Info>> dp(1 << l,
std::vector<Info>(n, Info{m + 1, 0})),
merged(n, std::vector<Info>(1 << l, Info{m + 1, 0}));
int root = l;
for (int i = 0; i < l; i++) {
dp[1 << i][i] = {0, 1};
}
for (int msk = 0; msk < 1 << l; msk++) {
for (int u = 0; u < n; u++) {
auto& ref = merged.at(u);
for (int subset = msk; subset > 0; subset = subset - 1 & msk) {
if (lowbit(subset) == lowbit(msk)) {
update(ref.at(msk),
add(dp.at(subset).at(u), ref.at(msk ^ subset)));
}
}
}
for (int u = 0; u < n; u++) {
for (int v : graph[u]) {
update(dp.at(msk).at(v), add(merged.at(u).at(msk), ONE));
}
}
auto& ref = dp.at(msk);
PQ<std::pair<int, int>> pq;
for (int u = 0; u < n; u++) {
pq.emplace(ref.at(u).first, u);
}
while (!pq.empty()) {
auto top = pq.top();
pq.pop();
int u = top.second;
if (top.first == ref.at(u).first) {
for (int v : graph.at(u)) {
Info todo = add(ref.at(u), ONE);
if (todo.first < ref.at(v).first) {
pq.emplace(todo.first, v);
}
update(ref.at(v), todo);
}
}
}
for (int u = 0; u < n; u++) {
update(merged.at(u).at(msk), dp.at(msk).at(u));
}
}
printf("%d\n", merged.at(root).at((1 << l) - 1).second);
}
return 0;
} | true |
9a819aac1ca05e2b10aaaa64321a52ce71f19d99 | C++ | likstepan/source | /mediatek/source/frameworks/libs/a3m/engine/facility/api/a3m/colour.h | UTF-8 | 4,121 | 3.015625 | 3 | [] | no_license | /*****************************************************************************
*
* Copyright (c) 2010 MediaTek Inc. All Rights Reserved.
* --------------------
* This software is protected by copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc.
*
*****************************************************************************/
/** \file
* Colour type
*
*/
#pragma once
#ifndef A3M_COLOUR_H
#define A3M_COLOUR_H
/*****************************************************************************
* Include Files
*****************************************************************************/
#include <a3m/base_types.h> /* A3M base type defines */
namespace a3m
{
/** \defgroup a3mTypeCol Colour (RGBA) type and constants
* \ingroup a3mRefTypes
* Type to hold colour values as R,G,B and Alpha quartets. At present
* only the Float implementation exists.
*
* @{
*/
/**
* Colour4f structure.
* Stores RGBA colour values as A3M_FLOAT's. No
* attempt is made to clamp values to [0.0 1.0].
*/
struct Colour4f
{
A3M_FLOAT r; /**< Red colour channel */
A3M_FLOAT g; /**< Green colour channel */
A3M_FLOAT b; /**< Blue colour channel */
A3M_FLOAT a; /**< Alpha colour channel */
/** Red colour constant. */
static const Colour4f RED;
/** Green colour constant. */
static const Colour4f GREEN;
/** Blue colour constant. */
static const Colour4f BLUE;
/** White colour constant. */
static const Colour4f WHITE;
/** Black colour constant (alpha = 1). */
static const Colour4f BLACK;
/** 33% grey colour constant. */
static const Colour4f LIGHT_GREY;
/** 67% grey colour constant. */
static const Colour4f DARK_GREY;
/** Default constructor */
Colour4f() : r(0.0), g(0.0), b(0.0), a(1.0) {}
/**
* Constructor: initialises local member variables
* with the supplied values
*/
Colour4f(A3M_FLOAT r /**< Red coefficient 0..1 */,
A3M_FLOAT g /**< Green coefficient 0..1 */,
A3M_FLOAT b /**< Blue coefficient 0..1 */,
A3M_FLOAT a /**< Alpha coefficient 0..1 */);
/** Set Colour
*
* Sets colour with byte vales
*/
void setColour( A3M_UINT8 rbyte /**< red channel */,
A3M_UINT8 gbyte /**< green channel */,
A3M_UINT8 bbyte /**< blue channel */,
A3M_UINT8 abyte /**< alpha channel */ );
/** Scale
*
* Scales the float values of the colour components
*/
void scale(A3M_FLOAT scalar /**< amount to scale colour */);
/** Equals operator for Colour4f objects.
* \return TRUE if the objects are the same.
*/
A3M_BOOL operator==( Colour4f const &c /**< other colour */) const
{
return ( r == c.r ) && ( g == c.g ) && ( b == c.b ) && ( a == c.a );
}
/** Not-Equals operator for Colour4f objects.
* \return TRUE if the objects are different.
*/
A3M_BOOL operator!=( Colour4f const &c /**< other colour */) const
{
return !( *this == c );
}
};
/** Component-wise addition for Colour4f.
*/
Colour4f operator+( Colour4f const& lhs, /**< left-hand operand */
Colour4f const& rhs /**< right-hand operand */ );
/** Component-wise subtract for Colour4f.
*/
Colour4f operator-( Colour4f const& lhs, /**< left-hand operand */
Colour4f const& rhs /**< right-hand operand */ );
/** Component-wise multiply for Colour4f.
*/
Colour4f operator*( Colour4f const& lhs, /**< left-hand operand */
Colour4f const& rhs /**< right-hand operand */ );
/** Component-wise divide for Colour4f.
*/
Colour4f operator/( Colour4f const& lhs, /**< left-hand operand */
Colour4f const& rhs /**< right-hand operand */ );
/** @} */
}; /* namespace a3m */
#endif /* A3M_COLOUR_H */
| true |
805c84106f1b5987203345c248abbfb6db7c89ab | C++ | ganeshredcobra/CPP | /Array_Pointer/std_Vector/vector_bools/main.cpp | UTF-8 | 267 | 3.5 | 4 | [] | no_license | #include <vector>
#include <iostream>
int main()
{
std::vector<bool> array { true, false, false, true, true };
std::cout << "The size is: " << array.size() << '\n';
for (auto const &element: array)
std::cout << element << ' ';
return 0;
};
| true |
b65df3d5c18f3dea6d39b800463f8755e5b18f00 | C++ | itsprathvi/3rd_sem_B_E | /oops/pointer1.cpp | UTF-8 | 644 | 4.03125 | 4 | [] | no_license | //Program to demonstrate the function that returns this pointer.
#include<iostream>
#include<string.h>
using namespace std;
class person{
char name[20];
float age;
public:
person(char *s,float a)
{
strcpy(name,s);
age=a;
}
person greater(person x)
{
if(x.age>=age)
return x;
else
return(*this);
}
void display()
{
cout<<"name:"<<name<<"\n";
cout<<"age:"<<age<<"\n";
}
};
int main()
{
person p1("Jyothi",37);
person p2("Srinivas",40);
person p3("Ajay",27);
person p=p1.greater(p2);
cout<<"person elder is\n";
p.display();
cout<<"person elder is\n";
p=p1.greater(p3);
p.display();
}
| true |
d95188cc9e9f34d0bfa64bbdf180d71f98946921 | C++ | AlvesCPP/000.CPP_Intro | /CPP_Intro/main.cpp | UTF-8 | 565 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <string>
int main()
{
int nInteger = 0;
double dblDouble = 0.0f;
char cChar = 'a';
bool blnBoolean = 1;
std::string strString = "Bob";
//Output
std::cout << "Hellow world!" << std::endl;
//Input
std::cin >> nInteger;
//Output
std::cout << "Valeur de l'entier : " << nInteger << std::endl;
std::cout << strString << std::endl;
std::cout << "Entrez votre prenom" << std::endl;
std::getline(std::cin, strString);
std::cout << "Prenom : " << strString << std::endl;
system("pause");
return 0;
} | true |
4f9bd2203388d2109ea0f7b88b70d00346fe17a2 | C++ | maximilianop/prog08_mpp647 | /directory.h | UTF-8 | 2,658 | 3.671875 | 4 | [] | no_license | //
// Created by paxm on 4/24/19.
//
#ifndef PROJECT_8_DIRECTORY_H
#define PROJECT_8_DIRECTORY_H
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
// I decided to set it up by using 1 class called directory which holds all the information about all the files in that directory as well as the chunk size that the user chooses to use.
// There is a vector called allFiles which holds the information about the all the files in the directory. It is a vector of structs, where the struct is called file, and holds information specific
// to each file in the directory.
// The information in the struct includes the name of the file, a vector that holds all the fixed words from the file (no punctuation, no symbols, all lowercase, etc.) to make it easier to create chunks
// there is also a queue class that holds strings, this is where the chunks are stored. Since it is a queue i just pushed eached chunk, and then to hash the chunk we can just pop each chunk.
// The other information in the class is the chunkSize and the name of the directory
// if anything is confusing hit me up bro
using namespace std;
class Directory
{
private:
struct files {
string fileName;
vector<string> fixedWords;
queue<string> chunks;
};
vector<files> allFiles;
string dirName;
int chunkSize;
public:
Directory();
//initializes the class variables with the input from the user
Directory(char* dirName, int chunkSize){
this->dirName = dirName;
this->chunkSize = chunkSize;
}
//getter for the vector holding all the structs with info on the files
vector<files>& getFiles () {
return allFiles;
}
string getFileName (int index){
return allFiles[index].fileName;
}
//getter for the name of the directory (if needed)
string getDirName (){
return dirName;
}
//Goes through the directory and places all the files into the vector, each file gets it's own struct and is initialized with the name of the file
int addFiles ();
//reads file, corrects all the words (all lowercase, no punctuation, etc.) and places each word into a vector
void readFile (int fileNum);
//prints all the file names in the directory (testing purposes)
void printFiles ();
//goes through the vector of fixed words and creates chunks of the input size for all the files
void makeChunks ();
~Directory() = default;
};
#endif //PROJECT_8_FILE_H
| true |
093b91f8bd0e59690e21a7c296b50d4d9eca9986 | C++ | bubleegames/Project2_Zelda | /Motor2D/ShopManager.h | UTF-8 | 1,609 | 2.578125 | 3 | [] | no_license | #ifndef _SHOPMANAGER_H_
#define _SHOPMANAGER_H_
#include <vector>
#include "Item.h"
class UI_Image;
class UI_Text;
class UI_Window;
class Player;
class Animator;
struct item_info
{
Item* item = nullptr;
UI_Image* item_image = nullptr;
};
struct shop
{
UI_Image* background = nullptr;
vector<item_info> items;
UI_Text* power = nullptr;
UI_Text* hp = nullptr;
UI_Text* speed = nullptr;
UI_Text* upgrade = nullptr;
UI_Text* upgrade_from = nullptr;
UI_Text* item_text = nullptr;
UI_Text* item_name = nullptr;
UI_Text* price = nullptr;
UI_Text* power_num = nullptr;
UI_Text* hp_num = nullptr;
UI_Text* speed_num = nullptr;
UI_Image* upgrade_item = nullptr;
UI_Image* upgrade_from_item = nullptr;
UI_Image* player_items[3] = { nullptr,nullptr,nullptr };
UI_Image* selector = nullptr;
int selected_item = 0;
UI_Image* buy_icon = nullptr;
bool item_selected = false;
bool active = false;
UI_Image* shop_icon = nullptr;
Animator* shop_icon_anim = nullptr;
};
class ShopManager
{
public:
ShopManager();
~ShopManager();
bool Start();
bool Update();
bool CleanUp();
SDL_Rect GetPlayerItem(int player_index, int item_index);
void UpdatePlayerItems(int view, Player* player);
bool IsActive(int viewport);
private:
void ChangeShopState(int view, Player* player = nullptr);
void UpdateItemInfo(int view, Player* player = nullptr);
public:
UI_Window* shop_window = nullptr;
iPoint team_shop[2] = { NULLPOINT,NULLPOINT };
private:
shop* shops[4] = { nullptr,nullptr,nullptr };
};
#endif // !_SHOPMANAGER_H_
| true |
52f4601e6fcab24ba9bff30e3c8fc8805ea7e688 | C++ | logicalclick/web | /cpp/2014/diana/game_file.cpp | UTF-8 | 734 | 2.75 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
int x;
int n;
int cnt;
srand (time(NULL));
x = 1 + rand()%100;
cout<<"Poznai chisloto"<<endl<<endl;
cnt=0;
while(cnt<5)
{
cout<<"Dai svoeto predlojenie:";
cin >> n;
if(n > x)
cout<<"Tvarde Golqmo Chislo!"<< endl <<endl;
else
if(n< x)
cout<<"Tvarde Malko Chislo!"<< endl <<endl;
else
{
cout<<"Razpolagash s broi tochki:"<< 100-(cnt+1)*20 <<endl;
cout <<"Bravo ti pozna chisloto!!!"<< endl;
break;
}
cnt++;
}
if (cnt==5)
cout<<"no more check";
return 0;
}
| true |
114823f0230705cf53ef3b18fc1171bc59cd058b | C++ | xryuseix/SA-Plag | /test/training_data/plag_original_codes/07_064_plag.cpp | UTF-8 | 778 | 2.6875 | 3 | [
"MIT"
] | permissive | // 引用元 : https://atcoder.jp/contests/abc130/submissions/5962060
// 得点 : 300
// コード長 : 304
// 実行時間 : 1
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
// vector vの中のn以下の数で最大のものを返す
int bs(vector<ll> &v, ll x){
int ok = -1; //これがx以下
int ng = v.size(); //x以上
// 問題によってokとngを入れ替える
while(abs(ok - ng) > 1){
int mid = (ok + ng)/2;
if(v[mid] <= x) ok = mid;
else ng = mid;
}
return ok;
}
int main(){
double W,H,x,y;
cin >> W >> H >> x >> y;
double ans=W/2.0*H;
int f;
if(W/x==2.0 and H/y==2.0) f=1;
else f=0;
cout << ans << " " << f << endl;
return 0;
}
| true |
e3c885ec8864feb5f1361bc35493ec8ced6bc75a | C++ | ForeverDavid/postwimp | /extlibs/headers/PolyVoxCore/PolyVoxCore/PagedVolume.h | UTF-8 | 18,890 | 2.703125 | 3 | [] | no_license | /*******************************************************************************
Copyright (c) 2005-2009 David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
#ifndef __PolyVox_PagedVolume_H__
#define __PolyVox_PagedVolume_H__
#include "PolyVoxCore/BaseVolume.h"
#include "PolyVoxCore/Region.h"
#include "PolyVoxCore/Vector.h"
#include <limits>
#include <cstdlib> //For abort()
#include <cstring> //For memcpy
#include <unordered_map>
#include <list>
#include <map>
#include <memory>
#include <stdexcept> //For invalid_argument
#include <vector>
namespace PolyVox
{
/// The PagedVolume class provides a memory efficient method of storing voxel data while also allowing fast access and modification.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// A PagedVolume is essentially a 3D array in which each element (or <i>voxel</i>) is identified by a three dimensional (x,y,z) coordinate.
/// We use the PagedVolume class to store our data in an efficient way, and it is the input to many of the algorithms (such as the surface
/// extractors) which form the heart of PolyVox. The PagedVolume class is templatised so that different types of data can be stored within each voxel.
///
/// Basic usage
/// -----------
///
/// The following code snippet shows how to construct a volume and demonstrates basic usage:
///
/// \code
/// PagedVolume<int> volume(Region(Vector3DInt32(0,0,0), Vector3DInt32(63,127,255)));
/// volume.setVoxel(15, 90, 42, int(5));
/// std::cout << "Voxel at (15, 90, 42) has value: " << volume.getVoxel(15, 90, 42) << std::endl;
/// std::cout << "Width = " << volume.getWidth() << ", Height = " << volume.getHeight() << ", Depth = " << volume.getDepth() << std::endl;
/// \endcode
///
/// The PagedVolume constructor takes a Region as a parameter. This specifies the valid range of voxels which can be held in the volume, so in this
/// particular case the valid voxel positions are (0,0,0) to (63, 127, 255). The result of attempts to access voxels outside this range will result
/// are defined by the WrapMode). PolyVox also has support for near infinite volumes which will be discussed later.
///
/// Access to individual voxels is provided via the setVoxel() and getVoxel() member functions. Advanced users may also be interested in
/// the Sampler nested class for faster read-only access to a large number of voxels.
///
/// Lastly the example prints out some properties of the PagedVolume. Note that the dimentsions getWidth(), getHeight(), and getDepth() are inclusive, such
/// that the width is 64 when the range of valid x coordinates goes from 0 to 63.
///
/// Data Representaion
/// ------------------
/// If stored carelessly, volume data can take up a huge amount of memory. For example, a volume of dimensions 1024x1024x1024 with
/// 1 byte per voxel will require 1GB of memory if stored in an uncompressed form. Natuarally our PagedVolume class is much more efficient
/// than this and it is worth understanding (at least at a high level) the approach which is used.
///
/// Essentially, the PagedVolume class stores its data as a collection of chunks. Each of these chunk is much smaller than the whole volume,
/// for example a typical size might be 32x32x32 voxels (though is is configurable by the user). In this case, a 256x512x1024 volume
/// would contain 8x16x32 = 4096 chunks. Typically these chunks do not need to all be in memory all the time, and the Pager class can
/// be used to control how they are loaded and unloaded. This mechanism allows a
/// potentially unlimited amount of data to be loaded, provided the user is able to take responsibility for storing any data which PolyVox
/// cannot fit in memory, and then returning it back to PolyVox on demand. For example, the user might choose to temporarily store this data
/// on disk or stream it to a remote database.
///
/// Essentially you are providing an extension to the PagedVolume class - a way for data to be stored once PolyVox has run out of memory for it. Note
/// that you don't actually have to do anything with the data - you could simply decide that once it gets removed from memory it doesn't matter
/// anymore.
///
/// Cache-aware traversal
/// ---------------------
/// *NOTE: This needs updating for PagedVolume rather than the old LargeVolume*
/// You might be suprised at just how many cache misses can occur when you traverse the volume in a naive manner. Consider a 1024x1024x1024 volume
/// with chunks of size 32x32x32. And imagine you iterate over this volume with a simple three-level for loop which iterates over x, the y, then z.
/// If you start at position (0,0,0) then ny the time you reach position (1023,0,0) you have touched 1024 voxels along one edge of the volume and
/// have pulled 32 chunks into the cache. By the time you reach (1023,1023,0) you have hit 1024x1024 voxels and pulled 32x32 chunks into the cache.
/// You are now ready to touch voxel (0,0,1) which is right next to where you started, but unless your cache is at least 32x32 chunks large then this
/// initial chunk has already been cleared from the cache.
///
/// Ensuring you have a large enough cache size can obviously help the above situation, but you might also consider iterating over the voxels in a
/// different order. For example, if you replace your three-level loop with a six-level loop then you can first process all the voxels between (0,0,0)
/// and (31,31,31), then process all the voxels between (32,0,0) and (63,0,0), and so forth. Using this approach you will have no cache misses even
/// is your cache size is only one. Of course the logic is more complex, but writing code in such a cache-aware manner may be beneficial in some situations.
///
/// Threading
/// ---------
/// The PagedVolume class does not make any guarentees about thread safety. You should ensure that all accesses are performed from the same thread.
/// This is true even if you are only reading data from the volume, as concurrently reading from different threads can invalidate the contents
/// of the chunk cache (amoung other problems).
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename VoxelType>
class PagedVolume : public BaseVolume<VoxelType>
{
public:
/// The PagedVolume stores it data as a set of Chunk instances which can be loaded and unloaded as memory requirements dictate.
class Chunk;
/// The Pager class is responsible for the loading and unloading of Chunks, and can be overridden by the user.
class Pager;
class Chunk
{
friend class PagedVolume;
public:
Chunk(Vector3DInt32 v3dPosition, uint16_t uSideLength, Pager* pPager = nullptr);
~Chunk();
VoxelType* getData(void) const;
uint32_t getDataSizeInBytes(void) const;
VoxelType getVoxel(uint16_t uXPos, uint16_t uYPos, uint16_t uZPos) const;
VoxelType getVoxel(const Vector3DUint16& v3dPos) const;
void setVoxelAt(uint16_t uXPos, uint16_t uYPos, uint16_t uZPos, VoxelType tValue);
void setVoxelAt(const Vector3DUint16& v3dPos, VoxelType tValue);
private:
/// Private copy constructor to prevent accisdental copying
Chunk(const Chunk& /*rhs*/) {};
/// Private assignment operator to prevent accisdental copying
Chunk& operator=(const Chunk& /*rhs*/) {};
// This is updated by the PagedVolume and used to discard the least recently used chunks.
uint32_t m_uChunkLastAccessed;
// This is so we can tell whether a uncompressed chunk has to be recompressed and whether
// a compressed chunk has to be paged back to disk, or whether they can just be discarded.
bool m_bDataModified;
uint32_t calculateSizeInBytes(void);
static uint32_t calculateSizeInBytes(uint32_t uSideLength);
VoxelType* m_tData;
uint16_t m_uSideLength;
uint8_t m_uSideLengthPower;
Pager* m_pPager;
// Note: Do we really need to store this position here as well as in the block maps?
Vector3DInt32 m_v3dChunkSpacePosition;
};
/**
* Users can override this class and provide an instance of the derived class to the PagedVolume constructor. This derived class
* could then perform tasks such as compression and decompression of the data, and read/writing it to a file, database, network,
* or other storage as appropriate. See FilePager for a simple example of such a derived class.
*/
class Pager
{
public:
/// Constructor
Pager() {};
/// Destructor
virtual ~Pager() {};
virtual void pageIn(const Region& region, Chunk* pChunk) = 0;
virtual void pageOut(const Region& region, Chunk* pChunk) = 0;
};
//There seems to be some descrepency between Visual Studio and GCC about how the following class should be declared.
//There is a work around (see also See http://goo.gl/qu1wn) given below which appears to work on VS2010 and GCC, but
//which seems to cause internal compiler errors on VS2008 when building with the /Gm 'Enable Minimal Rebuild' compiler
//option. For now it seems best to 'fix' it with the preprocessor insstead, but maybe the workaround can be reinstated
//in the future
//typedef Volume<VoxelType> VolumeOfVoxelType; //Workaround for GCC/VS2010 differences.
//class Sampler : public VolumeOfVoxelType::template Sampler< PagedVolume<VoxelType> >
#ifndef SWIG
#if defined(_MSC_VER)
class Sampler : public BaseVolume<VoxelType>::Sampler< PagedVolume<VoxelType> > //This line works on VS2010
#else
class Sampler : public BaseVolume<VoxelType>::template Sampler< PagedVolume<VoxelType> > //This line works on GCC
#endif
{
public:
Sampler(PagedVolume<VoxelType>* volume);
~Sampler();
/// \deprecated
POLYVOX_DEPRECATED VoxelType getSubSampledVoxel(uint8_t uLevel) const;
inline VoxelType getVoxel(void) const;
void setPosition(const Vector3DInt32& v3dNewPos);
void setPosition(int32_t xPos, int32_t yPos, int32_t zPos);
inline bool setVoxel(VoxelType tValue);
void movePositiveX(void);
void movePositiveY(void);
void movePositiveZ(void);
void moveNegativeX(void);
void moveNegativeY(void);
void moveNegativeZ(void);
inline VoxelType peekVoxel1nx1ny1nz(void) const;
inline VoxelType peekVoxel1nx1ny0pz(void) const;
inline VoxelType peekVoxel1nx1ny1pz(void) const;
inline VoxelType peekVoxel1nx0py1nz(void) const;
inline VoxelType peekVoxel1nx0py0pz(void) const;
inline VoxelType peekVoxel1nx0py1pz(void) const;
inline VoxelType peekVoxel1nx1py1nz(void) const;
inline VoxelType peekVoxel1nx1py0pz(void) const;
inline VoxelType peekVoxel1nx1py1pz(void) const;
inline VoxelType peekVoxel0px1ny1nz(void) const;
inline VoxelType peekVoxel0px1ny0pz(void) const;
inline VoxelType peekVoxel0px1ny1pz(void) const;
inline VoxelType peekVoxel0px0py1nz(void) const;
inline VoxelType peekVoxel0px0py0pz(void) const;
inline VoxelType peekVoxel0px0py1pz(void) const;
inline VoxelType peekVoxel0px1py1nz(void) const;
inline VoxelType peekVoxel0px1py0pz(void) const;
inline VoxelType peekVoxel0px1py1pz(void) const;
inline VoxelType peekVoxel1px1ny1nz(void) const;
inline VoxelType peekVoxel1px1ny0pz(void) const;
inline VoxelType peekVoxel1px1ny1pz(void) const;
inline VoxelType peekVoxel1px0py1nz(void) const;
inline VoxelType peekVoxel1px0py0pz(void) const;
inline VoxelType peekVoxel1px0py1pz(void) const;
inline VoxelType peekVoxel1px1py1nz(void) const;
inline VoxelType peekVoxel1px1py0pz(void) const;
inline VoxelType peekVoxel1px1py1pz(void) const;
private:
//Other current position information
VoxelType* mCurrentVoxel;
};
#endif
public:
/// Constructor for creating a fixed size volume.
PagedVolume
(
const Region& regValid,
Pager* pPager = nullptr,
uint16_t uChunkSideLength = 32
);
/// Destructor
~PagedVolume();
/// Gets a voxel at the position given by <tt>x,y,z</tt> coordinates
template <WrapMode eWrapMode>
VoxelType getVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tBorder = VoxelType()) const;
/// Gets a voxel at the position given by a 3D vector
template <WrapMode eWrapMode>
VoxelType getVoxel(const Vector3DInt32& v3dPos, VoxelType tBorder = VoxelType()) const;
/// Gets a voxel at the position given by <tt>x,y,z</tt> coordinates
VoxelType getVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, WrapMode eWrapMode = WrapModes::Validate, VoxelType tBorder = VoxelType()) const;
/// Gets a voxel at the position given by a 3D vector
VoxelType getVoxel(const Vector3DInt32& v3dPos, WrapMode eWrapMode = WrapModes::Validate, VoxelType tBorder = VoxelType()) const;
/// Gets a voxel at the position given by <tt>x,y,z</tt> coordinates
POLYVOX_DEPRECATED VoxelType getVoxelAt(int32_t uXPos, int32_t uYPos, int32_t uZPos) const;
/// Gets a voxel at the position given by a 3D vector
POLYVOX_DEPRECATED VoxelType getVoxelAt(const Vector3DInt32& v3dPos) const;
/// Sets the number of chunks for which uncompressed data is stored
void setMemoryUsageLimit(uint32_t uMemoryUsageInBytes);
/// Sets the voxel at the position given by <tt>x,y,z</tt> coordinates
void setVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tValue, WrapMode eWrapMode = WrapModes::Validate);
/// Sets the voxel at the position given by a 3D vector
void setVoxel(const Vector3DInt32& v3dPos, VoxelType tValue, WrapMode eWrapMode = WrapModes::Validate);
/// Sets the voxel at the position given by <tt>x,y,z</tt> coordinates
bool setVoxelAt(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tValue);
/// Sets the voxel at the position given by a 3D vector
bool setVoxelAt(const Vector3DInt32& v3dPos, VoxelType tValue);
/// Tries to ensure that the voxels within the specified Region are loaded into memory.
void prefetch(Region regPrefetch);
/// Ensures that any voxels within the specified Region are removed from memory.
void flush(Region regFlush);
/// Removes all voxels from memory
void flushAll();
/// Calculates approximatly how many bytes of memory the volume is currently using.
uint32_t calculateSizeInBytes(void);
protected:
/// Copy constructor
PagedVolume(const PagedVolume& rhs);
/// Assignment operator
PagedVolume& operator=(const PagedVolume& rhs);
private:
// FIXME - We can probably ove this into the constructor
void initialise();
// A trick to implement specialization of template member functions in template classes. See http://stackoverflow.com/a/4951057
template <WrapMode eWrapMode>
VoxelType getVoxelImpl(int32_t uXPos, int32_t uYPos, int32_t uZPos, WrapModeType<eWrapMode>, VoxelType tBorder) const;
VoxelType getVoxelImpl(int32_t uXPos, int32_t uYPos, int32_t uZPos, WrapModeType<WrapModes::Validate>, VoxelType tBorder) const;
VoxelType getVoxelImpl(int32_t uXPos, int32_t uYPos, int32_t uZPos, WrapModeType<WrapModes::Clamp>, VoxelType tBorder) const;
VoxelType getVoxelImpl(int32_t uXPos, int32_t uYPos, int32_t uZPos, WrapModeType<WrapModes::Border>, VoxelType tBorder) const;
VoxelType getVoxelImpl(int32_t uXPos, int32_t uYPos, int32_t uZPos, WrapModeType<WrapModes::AssumeValid>, VoxelType tBorder) const;
std::shared_ptr<Chunk> getChunk(int32_t uChunkX, int32_t uChunkY, int32_t uChunkZ) const;
void purgeNullPtrsFromAllChunks(void) const;
// The chunk data is stored in the pair of maps below. This will often hold the same set of chunks but there are occasions
// when they can differ (more on that in a moment). The main store is the set of 'recently used chunks' which holds shared_ptr's
// to the chunk data. When memory is low chunks can be removed from this list and, assuming there are no more references to
// them, they will be deleted. However, it is also possible that a Sampler is pointing at a given chunk, and in this case the
// reference counting will ensure that the chunk survives until the sampler has finished with it.
//
// However, this leaves us open to a subtle bug. If a chunk is removed from the recently used set, continues to exist due to a
// sampler using it, and then the user tries to access it through the volume interface, then the volume will page the chunk
// back in (not knowing the sampler still has it). This would result in two chunks in memory with the same position is space.
// To avoid this, the 'all chunks' set tracks chunks with are used by the volume *and/or* the samplers. It holds weak pointers
// so does not cause chunks to persist.
//
// TODO: Do we really need maps here? It means we are storing the chunk positions in the map, but they are also stored in the
// chunks themselves (so they can be passed to the pager from the chunks destructor). Can we use a set here? What is a better approach?
typedef std::unordered_map<Vector3DInt32, std::weak_ptr< Chunk > > WeakPtrChunkMap;
mutable WeakPtrChunkMap m_pAllChunks;
typedef std::unordered_map<Vector3DInt32, std::shared_ptr< Chunk > > SharedPtrChunkMap;
mutable SharedPtrChunkMap m_pRecentlyUsedChunks;
mutable uint32_t m_uTimestamper;
mutable Vector3DInt32 m_v3dLastAccessedChunkPos;
mutable std::shared_ptr<Chunk> m_pLastAccessedChunk;
uint32_t m_uChunkCountLimit;
// The size of the volume
Region m_regValidRegionInChunks;
// The size of the chunks
uint16_t m_uChunkSideLength;
uint8_t m_uChunkSideLengthPower;
Pager* m_pPager;
// Enough to make sure a chunks and it's neighbours can be loaded, with a few to spare.
const uint32_t uMinPracticalNoOfChunks = 32;
// Should prevent multi-gigabyte volumes when chunk sizes are reasonable.
const uint32_t uMaxPracticalNoOfChunks = 32768;
};
}
#include "PolyVoxCore/PagedVolume.inl"
#include "PolyVoxCore/PagedVolumeChunk.inl"
#include "PolyVoxCore/PagedVolumeSampler.inl"
#endif //__PolyVox_PagedVolume_H__
| true |
f19bf57d7fa3fde7096f42a1371ebc7b81b008db | C++ | gulraeezgulshan/arduino-workshop | /project29_writing_data_to_memory_card/writing_data_to_memory_card/writing_data_to_memory_card.ino | UTF-8 | 973 | 3.34375 | 3 | [] | no_license | // Project 29 - Writing Data to the Memory Card
int b = 0;
#include <SD.h>
void setup()
{
Serial.begin(9600);
Serial.print("Initializing SD card...");
pinMode(10, OUTPUT);
// check that the microSD card exists and is usable
if (!SD.begin(8))
{
Serial.println("Card failed, or not present");
// stop sketch
return;
}
Serial.println("microSD card is ready");
}
void loop()
{
// create the file for writing
File dataFile = SD.open("DATA.TXT", FILE_WRITE);
// if the file is ready, write to it:
if (dataFile)
{
for ( int a = 0 ; a < 11 ; a++ )
{
dataFile.print(a);
dataFile.print(" multiplied by two is ");
b = a * 2;
dataFile.println(b, DEC);
}
dataFile.close(); // close the file once the system has finished with it
// (mandatory)
}
// if the file isn't ready, show an error:
else
{
Serial.println("error opening DATA.TXT");
}
Serial.println("finished");
do {} while (1);
}
| true |
142957b0e003763ee05a0ec4267c61b24d29393f | C++ | Dwijesh522/AI_assn_5 | /The_Cannon/assn5_ml/minimax_ids.cpp | UTF-8 | 6,747 | 3.171875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include "classes.h"
#include<cmath>
#include "functions.h"
#include <algorithm>
#include <exception>
using namespace std;
// assumption - board result(board& s, const int soldier_r, const int soldier_c, const int target_r, const int target_c, action_type action_t, action_by whose_action)
// - vector<actions> get_possible_action(board s)
// - boolean terminal_test(board s)
// - int utility_function(board s)
// terminal test returns true if number of townhalls of either team is 2
// false if number of townhalls of both teams are greater than 2
// 1) clearly this function does not considers the fact that if there are no moves possible
// for either team, the state is a leaf node. Incorporating this fact will increase the
// time complexity bcz then we will need to see the possible moves of the player.
// BUT we can incorporate this later in the code when we will identify the possible
// moves, so if no move possible then stop and return it's utility function.
//
// utility function just implements the table given in the assignment. It will work as expected.
//float max_value(board state, int depth);
//float min_value(board state, int depth)
float max_value(board state, int depth, const int &cut_off_depth, float alpha, float beta, time_point<system_clock> &start_time_point, int time_per_move, color my_color);
// min_value and max_value are interdependent
float min_value(board state, int depth, const int &cut_off_depth, float alpha, float beta, time_point<system_clock> &start_time_point, int time_per_move, color my_color)
{
try
{
// half a second per move
if( ((duration<double>)(system_clock::now() - start_time_point)).count()*1000 >= time_per_move) throw runtime_error("Time out.");
if (state.terminal_test(depth, cut_off_depth))
{
// state.update_white_feature_values();
// state.update_black_feature_values();
// return state.eval_function();
return state.dynamic_eval_function();
}
else
{
action_by action_by_me, action_by_opponent;
vector<action> moves_possible;
if(state.get_my_color() == BLACK) { moves_possible = state.get_opponent_action(); action_by_me = OUR_ACTION; action_by_opponent = OPPONENT_ACTION;}
else { moves_possible = state.get_possible_action(); action_by_me = OPPONENT_ACTION; action_by_opponent = OUR_ACTION;}
float v = INFINITY;
// check if no move possible
if (moves_possible.size() == 0)
{
return state.utility_function(true); // opponent does not have moves, so i have moves
}
for (action move : moves_possible)
{
v = min(v, max_value(result(state, move.get_soldier_r(), move.get_soldier_c(),
move.get_target_r(), move.get_target_c(),
move.get_action_type(), action_by_opponent, my_color).first,
depth+1, cut_off_depth, alpha, beta, start_time_point, time_per_move, my_color));
if (v <= alpha) return v;
beta = min(beta, v);
}
return v;
}
}
catch(exception e)
{
throw e;
}
}
//float max_value(board state, int depth)
float max_value(board state, int depth, const int &cut_off_depth, float alpha, float beta, time_point<system_clock> &start_time_point, int time_per_move, color my_color)
{
try
{
// half a second for each move
if( ((duration<double>)(system_clock::now() - start_time_point)).count()*1000 >= time_per_move) throw runtime_error("Time out.");
if (state.terminal_test(depth, cut_off_depth))
{
// state.update_white_feature_values();
// state.update_black_feature_values();
// return state.eval_function();
return state.dynamic_eval_function();
}
else
{
action_by action_by_me, action_by_opponent;
vector<action> moves_possible;
if(state.get_my_color() == BLACK) { moves_possible = state.get_possible_action(); action_by_me = OUR_ACTION; action_by_opponent = OPPONENT_ACTION;}
else { moves_possible = state.get_opponent_action(); action_by_me = OPPONENT_ACTION; action_by_opponent = OUR_ACTION;}
float v = -INFINITY;
// check if no moves possible
if (moves_possible.size() == 0)
{
return state.utility_function(false); // i dont have moves
}
for (action move : moves_possible)
{
v = max(v, min_value(result (state,move.get_soldier_r(), move.get_soldier_c(),
move.get_target_r(), move.get_target_c(),
move.get_action_type(), action_by_me, my_color).first,
depth+1, cut_off_depth, alpha, beta, start_time_point, time_per_move, my_color));
if (v >= beta) return v;
alpha = max(alpha, v);
}
return v;
}
}
catch(exception e)
{
throw e;
}
}
bool compare_decr_cost(action &a1, action &a2)
{
return a1.get_action_cost() > a2.get_action_cost();
}
action minimax_decision(board root_state, int time_per_move, color my_color)
{
// getting the start time
time_point<system_clock> start;
start = system_clock::now();
duration<double> elapsed_seconds = start-start;
vector<action> moves_possible;
action_by action_by_me, action_by_opponent;
if(root_state.get_my_color() == BLACK) { moves_possible = root_state.get_possible_action(); action_by_me = OUR_ACTION; action_by_opponent = OPPONENT_ACTION;}
else { moves_possible = root_state.get_opponent_action(); action_by_me = OPPONENT_ACTION; action_by_opponent = OUR_ACTION;}
action best = moves_possible[0], move;
// if time_per_move is negative then return random move
if(time_per_move < 0)
{
while(true)
{
int random_index = rand() % (moves_possible.size());
if(moves_possible[random_index].get_action_type() != CANNON_SHOT) return moves_possible[random_index];
}
}
int moves_possible_size = moves_possible.size(), cut_off_depth = 2;
float v = -1, i=0;
// if time has not elapsed
// half a second for one move
while(true)
{
try
{
// cout << " \n\ncut_off_depth: " << cut_off_depth << endl;
// root_state.print_all_actions(moves_possible);
for(i=0; i<moves_possible_size; i++)
{
move = moves_possible[i];
float bound = min_value(result(root_state, move.get_soldier_r(), move.get_soldier_c(),
move.get_target_r(), move.get_target_c(), move.get_action_type(), action_by_me, my_color).first,
1, cut_off_depth, -INFINITY, INFINITY, start, time_per_move, my_color);
moves_possible[i].set_action_cost(bound);
if (v <= bound) //WARNING: NO ORDERING OF MOVES WITH SAME VALUE
{
// cerr << "backed up value is: " << bound << endl;
v = bound;
best = move;
}
}
// running out of time
sort(moves_possible.begin(), moves_possible.end(), compare_decr_cost);
cut_off_depth++;
}
catch(exception e)
{
break;
}
}
return best;
}
| true |
6322bb824744a58433d15129ade10792b39c121b | C++ | shenfy/imgpp | /src/include/imgpp/glhelper.hpp | UTF-8 | 1,396 | 2.703125 | 3 | [
"MIT"
] | permissive | #ifndef IMGPP_GLHELPER_HPP
#define IMGPP_GLHELPER_HPP
/*! \file glhelper.hpp */
#include <imgpp/texturedesc.hpp>
namespace imgpp { namespace gl {
/*! \enum Profile
\brief Specifies gl context version
*/
enum Profile: uint8_t {
ES20, // no sRGB
ES30, // has swizzle
GL32,
GL33, // has swizzle
};
/*! \struct GLFormatDesc
Specifies texture format, data type in OpenGL
*/
struct GLFormatDesc {
uint16_t internal_format; /*!< For compressed textures, equals the compressed internal format.
For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D */
uint16_t external_format; /*!< For compressed textures, euqals 0. For uncompressed textures,
specifies the format parameter passed to glTex{, Sub}Image*D, usually one of {GL_RGB, GL_RGBA, GL_BGRA, etc.}*/
uint16_t base_internal_format; /*!< Specifies base internal format of texture*/
uint16_t type; /*!< For compressed textures, equals 0. For uncompressed textures, specifies the type
parameter passed to glTex{, Sub}Image*D, usually one of {GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, etc.}*/
};
TextureFormat TranslateFromGL(uint16_t internal, uint16_t external,
uint16_t base_internal, uint16_t type);
GLFormatDesc TranslateToGL(TextureFormat format, Profile profile);
GLFormatDesc TranslateToGL(TextureFormat format);
uint32_t GetTypeSize(uint16_t type);
}}
#endif
| true |
d077b754e110aa1a169c31a288e073a73d03e945 | C++ | caitouwww/probable-octo-doodle | /leetcode top 100/002两数相加.cpp | UTF-8 | 1,606 | 3.203125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(0);
ListNode* node = dummy;
int add = 0, val = 0,sum = 0;
while(l1||l2||add){
if(l1&&l2){
sum = l1->val+l2->val+add;
}else if(l1){
sum = l1->val+add;
}else if(l2){
sum = l2->val+add;
}else sum = add;
add = sum/10;
ListNode* cur = new ListNode(sum%10);
node->next = cur;
node = node->next;
if(l1)l1 = l1->next;
if(l2)l2 = l2->next;
}
return dummy->next;
// ListNode* dummy = new ListNode(0);
// ListNode* cur = dummy;
// int carry = 0;
// while(l1 != nullptr || l2 != nullptr || carry != 0){
// int l1val = l1 != nullptr ? l1->val : 0;
// int l2val = l2 != nullptr ? l2->val : 0;
// int sum = l1val + l2val + carry;
// carry = sum / 10;
//
// ListNode* sumNode = new ListNode(sum % 10);
// cur->next = sumNode;
// cur = cur->next;
//
// if(l1 != nullptr) l1 = l1->next;
// if(l2 != nullptr) l2 = l2->next;
// }
// return dummy->next;
}
};
| true |
37fea33ae77f21e5dc4c25855b9289debcd20d05 | C++ | jventura10/Ventura_Javier_CSC5_Summer2017 | /Hmwk/Assignment_1/Gaddis_8thEd_Chap2_Prog_Prob15_TrianglePattern/main.cpp | UTF-8 | 877 | 3.5625 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Javier Ventura
* Purpose: Using the character selected, program will make a triangle shape
* Created on June 23, 2017, 9:29 PM
*/
//Include Libraries Here
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
//Declare all Variables Here
char key; //Character can be any found on keyboard and chosen by user
//Number,letter,or even grammar tool
//Initialize by input from command line
cout<<"What character would you like to use ";
cout<<"to make a Triangle Pattern"<<endl;
cin>>key;
//Output Transformed data
cout<<" "<<" "<<" "<<key<<" "<<" "<<" "<<endl;
cout<<" "<<" "<<key<<key<<key<<" "<<" "<<endl;
cout<<" "<<key<<key<<key<<key<<key<<" "<<endl;
cout<<key<<key<<key<<key<<key<<key<<key<<endl;
//Exit
return 0;
}
| true |
51253bd052c472cad43d22a80dfac94d3fac107c | C++ | bstelly/IntroToCpp | /Functions Assignment 2/Source.cpp | UTF-8 | 1,170 | 4.5625 | 5 | [] | no_license | #include <iostream>
//1. Create a function for each of the following math operators. They must return a value.
// and take in at least two argument. Once all the functions have been created you will need to
// invoke them and print out the return.
//a. Addition
//b. Subtraction
//c. Multliplication
//d. Division
int Add(int a, int b)
{
int result = a + b;
return result;
}
int Subtraction(int a, int b)
{
int result = a - b;
return result;
}
int Multiplication(int a, int b)
{
int result = a * b;
return result;
}
int Division(int a, int b)
{
int result = a / b;
return result;
}
//2. Create a function that takes in two arguments, one being an array of float and the other
// being the size of the array. It must return the largest value in the array.
//3. Using recursion write a function that prints out the Fibonacci sequence.
//4. The following statement calls a function named Half. The Half function returns a value that
// is half that of the argument. Write the function.
//5. Write a function that takes as its parameters an array of intergers and the size of the array
// and returns the sum of the values in the array.
| true |
2b0d32718f092ff7d5414628e363eb371492e542 | C++ | andywu1998/C_and_Cpp | /C++primerplus/第十一章:使用类/计算时间/mytime0.cpp | UTF-8 | 843 | 3.546875 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include "mytime0.h"
Time::Time(int h = 0, int m = 0):hours(h), minutes(m)
{
}
Time::Time(const Time &t)
{
this->hours = t.hours;
this->minutes = t.minutes;
}
Time Time::operator+(const Time &other)const
{
Time t;
int t_minutes = this->minutes + other.minutes;
t.minutes = t_minutes % 60;
t.hours += (t_minutes / 60) % 24;
t.hours = (this->hours + other.hours) % 24;
return t;
}
void Time::operator-(const Time &t)
{
this->minutes -= t.minutes;
if (this->minutes < 0)
{
this->minutes += 60;
this->hours--;
}
this->hours -= t.hours;
if (this->hours < 0)
{
this->hours += 24;
}
}
void Time::print()
{
printf("%02d:%02d\n", this->hours, this->minutes);
}
std::ostream & operator<<(std::ostream & os, const Time &t)
{
printf("%02d:%02d\n", t.hours, t.minutes);
return os;
} | true |
f10c5689c8a65e37e5bda67804f29e6f57b744e2 | C++ | sammyne/LeetCodeCpp | /621-Task-Scheduler/main.cpp | UTF-8 | 3,383 | 3.375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <tuple>
#include <vector>
using namespace std;
class Solution {
public:
static int leastIntervalV2(vector<char> &tasks, int n) {
// priority queue
// the 1st element is the length of freeze zone of the task
// the 2nd element is the frequency of the task
vector<pair<int, int>> pq;
// frequency counter
int f[26] = {0};
// count the frequency for each task
for (const auto &t:tasks) { ++f[t - 'A']; }
// make up the underlying vector for pq
for (int i = 0; i < 26; ++i) {
if (f[i]) {
pq.push_back(std::make_pair(-1, f[i]));
//pq.push_back(std::make_tuple(-1, f[i], (char) ('A' + i)));
}
}
std::make_heap(std::begin(pq), std::end(pq));
int ticks{};
while (!pq.empty()) {
++ticks;
for (auto &pr:pq) {
if (pr.first < 0) {
pr.first += 1;
}
}
if (pq[0].first < 0) { continue; }
std::make_heap(std::begin(pq), std::end(pq));
std::pop_heap(std::begin(pq), std::end(pq));
// no more current task
if (1 == pq.back().second) {
pq.pop_back();
} else {
// decrement the frequency
pq.back().second -= 1;
// update the freeze zone
pq.back().first = -n - 1;
}
}
return ticks;
}
static int leastInterval(vector<char> &tasks, int n) {
// priority queue
// the 1st element is the length of freeze zone of the task
// the 2nd element is the frequency of the task
vector<tuple<int, int>> pq;
// frequency counter
int f[26] = {0};
// count the frequency for each task
for (const auto &t:tasks) { ++f[t - 'A']; }
// make up the underlying vector for pq
for (int i = 0; i < 26; ++i) {
if (f[i]) {
pq.push_back(std::make_tuple(-1, f[i]));
//pq.push_back(std::make_tuple(-1, f[i], (char) ('A' + i)));
}
}
std::make_heap(std::begin(pq), std::end(pq));
int ticks{};
while (!pq.empty()) {
++ticks;
for (auto &v:pq) {
if (std::get<0>(v) < 0) { std::get<0>(v) += 1; }
}
if (std::get<0>(pq[0]) < 0) { continue; }
std::make_heap(std::begin(pq), std::end(pq));
std::pop_heap(std::begin(pq), std::end(pq));
// no more current task
if (1 == std::get<1>(pq.back())) {
pq.pop_back();
} else {
// decrement the frequency
std::get<1>(pq.back()) -= 1;
// update the freeze zone
std::get<0>(pq.back()) = -n - 1;
}
}
return ticks;
}
};
int main() {
///*
vector<char> tasks = {'A', 'A', 'A', 'B', 'B', 'B'};
const int n = 2;
//*/
/*
vector<char> tasks{'A'};
const int n = 2;
*/
/*
vector<char> tasks{'A', 'A', 'A', 'A', 'A', 'A', 'B', 'C', 'D', 'E', 'F', 'G'};
const int n = 2;
*/
cout << Solution::leastIntervalV2(tasks, n) << endl;
return 0;
} | true |
063066efdff298be9905c3a2ccc3dfdad266c628 | C++ | getopenmono/mono_framework | /src/display/ui/text_label_view.h | UTF-8 | 14,091 | 2.78125 | 3 | [
"MIT"
] | permissive | // This software is part of OpenMono, see http://developer.openmono.com
// and is available under the MIT license, see LICENSE.txt
#ifndef __mono__text_label_view__
#define __mono__text_label_view__
#include <deprecated.h>
#include "view.h"
#include "mn_string.h"
#include <font_interface.h>
#include <gfxfont.h>
#include <text_render.h>
namespace mono { namespace ui {
class ButtonView;
class TouchCalibrateView;
/**
* @brief A Text Label displays text strings on the display
*
* Use this UI view whenever you need to display text on the screen.
*
* A text label renders text strings on the display. As all views the label
* lives inside a defined rectangle (@ref viewRect), where the text is
* rendered. If the rectangle is smaller than the length of the text
* content, the content will cropped. If the rectangle is larger, then you
* can align the text inside the rectangle (left, center or right).
*
* ### Example
*
* You can mix and match mono strings with standard C strings when
* constructing TextLabels.
*
* **Create a label using a `static const` C string:**
* @code
* TextLabelView lbl("This is a contant string");
* @endcode
*
* Also you can use C strings allocated on the stack:
* @code
* char text[4] = {'m', 'o', 'n', 'o'};
* TextLabelView lbl(text);
* @endcode
*
* Above the TextLabel will take a copy of the input string, to ensure it
* can be accessed asynchronously.
*
* ### Content
*
* The text view contains it content (a @ref String object), and therefore
* has a state. You get and set the content to update the rendered text on
* the display.When you set new text content the label automatically
* re-renders itself. (By calling @ref scheduleRepaint)
*
* Because the view is rendered asynchronously, its text content must be
* allocated on the heap. Therefore it uses the @ref String as text storage.
* You can provide it with C strings, but these must allocated inside the
* .rodata segment of your binary. (Meaning they are `static const`.)
*
* ### Text Format
*
* Currently there are only one font type. But the text color and font can
* changed. You change these for parameters:
*
* * Text font (including size)
* * Text color
* * Text background color (the color behind the characters)
*
* ### Getting text dimensions
*
* To help you layout your views, you can query the `TextLabel` of the current
* width and height of its contents. The methods @ref TextPixelWidth and
* @ref TextPixelHeight, will return the texts dimensions in pixels
* - regardless of view rectangle. Also, you can use these methods before
* the view has been rendered.
*
*/
class TextLabelView : public View {
friend ButtonView;
friend TouchCalibrateView;
public:
/**
* @brief Three ways of justifing text inside the TextLabel
*/
enum TextAlignment
{
ALIGN_LEFT, /**< Align text to the left */
ALIGN_CENTER, /**< Align text in the center */
ALIGN_RIGHT /**< Align text to the right */
};
/**
* @brief The Vertical justification of the text, inside the labels @ref Rect
*/
enum VerticalTextAlignment
{
ALIGN_TOP, /**< Align the text at the top of the label */
ALIGN_MIDDLE, /**< Align the text at in the middle of the label */
ALIGN_BOTTOM /**< Align the text at the bottom of the label */
};
/**
* @brief This is the default font for all TextLabelView's
*
* This points to the default Textlabel font. You can overwrite this in
* your own code to change the default appearence of all TextLabels.
*
* You can also overwrite it to use a less memory expensive
* (lower quality) font face.
*
* @deprecated Use StandardGfxFont
*/
static const MonoFont *StandardTextFont __DEPRECATED("use the similar variable of the GfxFontType", "StandardGfxFont");
/**
* @brief This is the default font for all TextLabelView's
*
* This points to the default Textlabel font. You can overwrite this in
* your own code to change the default appearence of all TextLabels.
*
* You can also overwrite it to use a less memory expensive
* (lower quality) font face.
*/
static const GFXfont *StandardGfxFont;
protected:
String text;
String prevText;
geo::Rect prevTextRct;
int incrementCharOffset;
int incrementCharPosition;
mono::display::TextRender *incrementTextRender;
const MonoFont *currentFont;
const GFXfont *currentGfxFont;
uint8_t textSize;
display::Color textColor;
display::Color bgColor;
TextAlignment alignment;
VerticalTextAlignment vAlignment;
bool textMultiline;
/**
* @brief Check if the current text has newline characters
*
* This runs O(n)
* @return `true` is newlines are found
*/
bool isTextMultiline() const;
void repaintGfx(geo::Rect &txtRct);
void repaintLegacy(geo::Rect &txtRct);
void repaintGfxIncremental(geo::Rect &txtRct);
void repaintLegacyIncremental(geo::Rect &txtRct);
bool canUseIncrementalRepaint() const;
void drawIncrementalChar(const geo::Point &position, const GFXfont &font, const GFXglyph *gfxGlyph, geo::Rect const &boundingRect, const int lineHeight);
public:
// MARK: Public Constructors
/**
* @brief Construct a text label with defined content, but no dimensions
*
* Before you can render the label you still need to set the view
* dimensions. This constructor take the String object as defined in the
* mono framework.
*
* @param txt The labels text content (as a mono lightweight string)
*/
TextLabelView(String txt = String());
/**
* @brief Construct a text label with defined content, but no dimensions
*
* Before you can render the label you still need to set the view
* dimensions. This constructor takes a `static const` C string pointer
* that must *not* exist on the stack! (It must live inside the `.rodata`
* segment.
*
* @param txt A pointer to the static const C string (.rodata based)
*/
TextLabelView(const char *txt);
/**
* @brief Construct a label in a defined rectangle and with a string
*
* You provide the position and size of the label, along with its text
* content. You can call this constructor using a mono type string or a
* stack based C string - and it is automatically converted to a mono
* string:
*
* @code
* int celcius = 22;
*
* // char array (string) on the stack
* char strArray[50];
*
* // format the string content
* sprintf(strArray,"%i celcius", celcius);
*
* // construct the label with our stack based string
* TextLabelView lbl(geo::Rect(0,0,100,100), strArray);
* @endcode
*
*/
TextLabelView(geo::Rect rct, String txt);
/**
* @brief Construct a label in a defined rectangle and with a string
*
* You provide the position and size of the label, along with its text
* content. You can call this constructor using `static const` C string:
*
* @code
* // construct the label with our stack based string
* TextLabelView lbl(geo::Rect(0,0,100,100), "I am a .rodata string!");
* @endcode
*
*/
TextLabelView(geo::Rect rct, const char *txt);
// MARK: Getters
/**
* The text size will be phased out in coming releases. You control text
* by changing the font.
*
* @deprecated Font sizes are controlled by the bitmap font set by the font property
*/
uint8_t TextSize() const __DEPRECATED("Font sizes are controlled by the bitmap font set by the font property","setFont");
/** @brief Get the current color of the text */
display::Color TextColor() const;
/** @brief Get the current horizontal text alignment */
TextAlignment Alignment() const;
/** @brief Get the current vertical text alignment */
VerticalTextAlignment VerticalAlignment() const;
/** This indicate if the next repaint should only repaint differences */
bool incrementalRepaint;
/** @brief Get the width of the current text dimension */
uint16_t TextPixelWidth() const;
/** @brief Get the height of the current text dimension */
uint16_t TextPixelHeight() const;
/** @brief If not NULL, then returns the current selected @ref MonoFont */
const MonoFont* Font() const __DEPRECATED("Old MonoFont system is being outphased","GfxFont");
/** @brief If not NULL, then returns the current selected @ref GFXfont */
const GFXfont* GfxFont() const;
/** @brief Returns the dimensions ( @ref Size and offset @ref Point ) of the text. */
geo::Rect TextDimension() const;
// MARK: Setters
/**
* We will phase out this attribute in the coming releases. To change
* the font size you should rely on the font face.
*
* If you set this to 1 the old font (very bulky) font will be used. Any
* other value will load the new default font.
*
* @deprecated ont sizes are controlled by the bitmap font set by the font property
*/
void setTextSize(uint8_t newSize) __DEPRECATED("Font sizes are controlled by the bitmap font set by the font property","setFont");
/**
* @deprecated Name will change. Use @ref setText
*/
void setTextColor(display::Color col) __DEPRECATED("Use the new method, with out the color-postfix","setText");
/**
* @deprecated Name will change. Use @ref setBackground
*/
void setBackgroundColor(display::Color col) __DEPRECATED("Use the new method, with out the color-postfix","setBackground");
/** @brief Set the text color */
void setText(display::Color col);
/** @brief Set the color behind the text */
void setBackground(display::Color col);
/** @brief Controls text justification: center, right, left */
void setAlignment(TextAlignment align);
/** @brief Set the texts vertical alignment: top, middle or bottom */
void setAlignment(VerticalTextAlignment vAlign);
/**
* @brief Change the text content of the Text label, and schedules repaint
*
* This method updates the text that is rendered by the textlabel. It
* automatically schedules an incremental (fast) repaint.
*
* @param text The C string text to render
*/
void setText(const char *text);
/**
* @brief Change the text content of the Text label, and schedules repaint
*
* This method updates the text that is rendered by the textlabel. It
* automatically schedules an incremental (fast) repaint.
*
* @param text The Mono string text to render
*/
void setText(String text);
/** @deprecated */
void setText(const char *txt, bool resizeViewWidth) __DEPRECATED("the textLabel crops overflowing text", "setText");
/** @deprecated */
void setText(String text, bool resizeViewWidth) __DEPRECATED("the textLabel crops overflowing text", "setText");
/**
* @brief Set a new font face on the label
*
* You can pass any @ref MonoFont to the label to change its appearence.
* Fonts are header files that you must include youself. Each header file
* defines a font in a specific size.
*
* The header file defines a global `const` variable that you pass to
* to this method.
*
* @deprecated Use the Adafruit GfxFont version of this method
* @param newFont The mono-spaced to use with the textlabel
*/
void setFont(MonoFont const &newFont) __DEPRECATED("The MonoFont system types are being out phased", "setFont");
/**
* @brief Set a new font face on the label
*
* You can pass any Adafruit @ref GfxFont to the label to change its appearence.
* Fonts are header files that you must include youself. Each header file
* defines a font in a specific size.
*
* The header file defines a global `const` variable that you pass to
* to this method.
*/
void setFont(GFXfont const &font);
// MARK: Getters
/**
* @brief Gets the content of the text label
*/
String Text() const;
public:
/**
* @brief Repaints the view, using incremental repaints if possible
*
* This method might be faster than @ref scheduleRepaint, since this
* repaint allows the text to be repainted incrementally. This means
* fast repaint of counters or fade animations.
*
* If you experience rendering errors, you should use the normal
* @ref scheduleRepaint method.
*/
void scheduleFastRepaint();
void scheduleRepaint();
void repaint();
};
} }
#endif /* defined(__marqueeApp__text_label_view__) */
| true |
6199a86a66b8692c8f86954bf813fd6e69702e33 | C++ | kandabi/OpenFTP | /OpenFTP Server/sources/worker_manager.cpp | UTF-8 | 653 | 2.703125 | 3 | [
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Apache-2.0",
"GPL-1.0-or-later",
"GPL-3.0-only"
] | permissive | #include "stdafx.h"
#include "worker_manager.h"
WorkerThread::WorkerThread(const QString& filePath, QSslSocket* _socket) : socket(_socket)
{
qFile.setFileName(filePath);
size = qFile.size();
}
void WorkerThread::run() {
QByteArray fileData;
if (!qFile.open(QIODevice::ReadOnly) || !qFile.isReadable())
return;
while (writtenBytes < size)
{
loadFile(fileData);
writtenBytes += packetSize;
emit writeDataSignal(socket ,fileData);
QThread::msleep(60);
}
}
void WorkerThread::loadFile(QByteArray& fileData) {
qFile.seek(writtenBytes);
fileData = qFile.read(packetSize);
} | true |
8bbcb86825ab9500b4d4c9996790ee1a6969a5e9 | C++ | gaitee1/TanvirGaiteeara_48102 | /Homework/Assignment_1/Gaddis_7thEd_Chap2_Prob8_TotalPurchase/main.cpp | UTF-8 | 1,716 | 3.65625 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Gaitee ara Tanvir
* Created on September 18, 2016, 10:14 AM
* Purpose: Calculate the subtotal of the sale, the amount of sales tax, and the total.
*/
//System Libraries
#include <iostream> //Input/Output objects
using namespace std; //Name-space used in the System Library
//User Libraries
//Global Constants
const char PERCENT=100; //Conversion to percentage
//Function prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Declaration of Variables
float prItem1=12.95, //Price of item 1 in $'s
prItem2=24.95, //Price of item 2 in $'s
prItem3=6.95, //Price of item 3 in $'s
prItem4=14.95, //Price of item 4 in $'s
prItem5=3.95; //Price of item 5 in $'s
float sal_tax=6; //sales tax percentage
float stSal,salTax,total; //Subtotal of sale, amount of Sales Tax, Total in $'s
//Process values -> Map inputs to Outputs
stSal=prItem1+prItem2+prItem3+prItem4+prItem5;
salTax=stSal*sal_tax/PERCENT;
total=stSal+salTax;
//Display Output
cout<<"Price of item 1 =$"<<prItem1<<endl;
cout<<"Price of item 2 =$"<<prItem2<<endl;
cout<<"Price of item 3 =$"<<prItem3<<endl;
cout<<"Price of item 4 =$"<<prItem4<<endl;
cout<<"Price of item 5 =$"<<prItem5<<endl;
cout<<"The subtotal of Sale =$"<<stSal<<endl;
cout<<"The sales tax ="<<static_cast<int>(sal_tax)<<"%"<<endl;
cout<<"The amount of sales tax on items purchased =$"<<salTax<<endl;
cout<<"Total =$"<<total<<endl;
//Exit Program
return 0;
} | true |
4719100d8a05c4d5cdaf95f76fdb36aee30d9606 | C++ | Cyber-SiKu/nowcoder | /64-OR127/64-1.cpp | UTF-8 | 1,157 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
vector<int> outs;
public:
Solution(const vector<int>& data);
~Solution();
friend ostream& operator<<(ostream& os, const Solution& s);
};
Solution::Solution(const vector<int>& data)
{
for (size_t i = 0, e = data.size(); i < e; i++) {
bool no_multiple = true;
if (data[i] == 0) {
continue;
}
for (size_t j = 0; j < e; j++) {
if ((data[j] / data[i]) * data[i] == data[j]) {
if (i == j) {
continue;
}
no_multiple = false;
break;
}
}
if (no_multiple == true) {
outs.push_back(data[i]);
}
}
}
Solution::~Solution()
{
}
ostream& operator<<(ostream& os, const Solution& s)
{
for (const int& i : s.outs) {
os << i << " ";
}
return os;
}
int main(int argc, char* argv[])
{
int n;
cin >> n;
vector<int> data(n);
for (size_t i = 0; i < n; i++) {
cin >> data[i];
}
cout << Solution(data) << endl;
return 0;
} | true |
e7aa6ecbb48e47491ae66b344fa4f80edd8c2a14 | C++ | Chaomin702/cmserver | /cmver/threadpoll.cpp | UTF-8 | 1,215 | 3.15625 | 3 | [
"MIT"
] | permissive | #include "threadPoll.h"
ThreadPoll::ThreadPoll(size_t queueSize, size_t pollSize)
: empty_(mutex_)
, full_(mutex_)
, queueSize_(queueSize)
, pollSize_(pollSize)
, isStarted_(false){}
ThreadPoll::~ThreadPoll(){
if (isStarted_)
stop();
}
void ThreadPoll::start(){
if (isStarted_)
return;
isStarted_ = true;
for (size_t i = 0; i < pollSize_; ++i){
threads_.push_back(std::make_shared<Thread>(std::bind(&ThreadPoll::runInThread, this)));
}
for (auto &i : threads_){
i->start();
}
}
void ThreadPoll::addTask(const Task& t){
MutexGuard lock(mutex_);
while (queue_.size() == queueSize_){
full_.wait();
}
queue_.push(t);
empty_.notify();
}
ThreadPoll::Task ThreadPoll::getTask(){
MutexGuard lock(mutex_);
while (queue_.empty() && isStarted_){
empty_.wait();
}
Task t;
if (!queue_.empty()) {
t = queue_.front();
queue_.pop();
full_.notify();
}
return t;
}
void ThreadPoll::runInThread(){
while (isStarted_){
Task t = getTask();
if(t)
t();
}
}
void ThreadPoll::stop(){
if (isStarted_ == false)
return;
{
MutexGuard lock(mutex_);
isStarted_ = false;
empty_.notifyAll();
}
for (auto &i : threads_){
i->join();
}
while (!queue_.empty())
queue_.pop();
} | true |
f48e0e9fa25f617d05d3c3d41e92e84b50c3db66 | C++ | ayoubserti/asio | /samples/hello-world/main.cc | UTF-8 | 2,187 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <functional>
#include <memory>
#define ASIO_STANDALONE 1
#include "asio.hpp"
using namespace std;
using namespace asio;
using TcpEndPoint = ip::tcp::endpoint;
using TcpSocket = ip::tcp::socket;
using namespace std::placeholders;
class Reciever;
template<class T>
void Handler(shared_ptr<Reciever> reciever, const asio::error_code& ec, std::size_t bytes_received){
if (!ec){
//synchronously write file
FILE* file = fopen("file.html", "a+");
fwrite(reciever->buf_,1, bytes_received, file);
fclose(file);
reciever->total_read_len_ += bytes_received;
reciever->socket_->async_receive(buffer(reciever->buf_), std::bind(Handler<T>, reciever, _1,_2));
}
if (ec == asio::error::eof)
{
cout << reciever->total_read_len_ << endl;
std::cout << "EOF" << std::endl;
}
}
class Reciever
{
public:
char buf_[100];
std::size_t total_read_len_;
shared_ptr<TcpSocket> socket_;
windows::stream_handle sh_;
/*template<class T>
friend void Handler(shared_ptr<Reciever> reciever, shared_ptr<TcpSocket> socket, T& buf, const asio::error_code& ec, std::size_t bytes_received);*/
Reciever(shared_ptr<TcpSocket> socket) :total_read_len_(0),socket_(socket),sh_(socket->get_io_service()){ }
Reciever(const Reciever& other) : Reciever(other.socket_){}
void operator()(){
socket_->async_receive(buffer(buf_), bind(Handler<char*>, make_shared<Reciever>(const_cast<Reciever&>(*this)), _1, _2));
}
};
int main()
{
io_service myservice;
shared_ptr<TcpSocket> sock(new TcpSocket(myservice));
TcpEndPoint ep(ip::address::from_string("185.53.179.8"),80);
Reciever recv(sock);
sock->async_connect(ep, [&sock, &recv](const asio::error_code& ec){
if (!ec)
{
char* header = "GET /docs/index.html HTTP/1.1\n"
"Host: www.nowhere123.com\n"
"Accept : image / gif, image / jpeg, */*\n"
"Accept-Language: en-us\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\n\n";
sock->async_send(buffer(header,strlen(header)), [&sock, &recv](const asio::error_code& ec, std::size_t bytes_transferred){
if (!ec){
recv();
}
});
}
});
myservice.run();
return 0;
} | true |
809d195315d7e9f3f3f669413601b1778501b1d4 | C++ | vincent-picaud/LinearAlgebra | /test/LinearAlgebra/dense/memory_chunk_aliasing_p.cpp | UTF-8 | 2,912 | 2.890625 | 3 | [] | no_license | #include "LinearAlgebra/dense/memory_chunk_aliasing_p.hpp"
#include "LinearAlgebra/dense/matrix.hpp"
#include "LinearAlgebra/dense/matrix_view.hpp"
#include "LinearAlgebra/dense/vector.hpp"
#include "LinearAlgebra/dense/vector_view.hpp"
#include <gtest/gtest.h>
using namespace LinearAlgebra;
TEST(Memory_Chunck_Aliasing, vector)
{
Vector<int> V1(10);
Tiny_Vector<int, 4> V2;
EXPECT_FALSE(are_not_aliased_p(V1, V1));
EXPECT_TRUE(are_not_aliased_p(V1, V2));
EXPECT_TRUE(are_possibly_aliased_p(V1, V1));
EXPECT_FALSE(are_possibly_aliased_p(V1, V2));
auto V1_view_1 = create_vector_view(V1, 2, 5);
auto V1_view_2 = create_vector_view(V1.as_const(), 6, 8);
EXPECT_TRUE(are_not_aliased_p(V1_view_1, V1_view_2));
EXPECT_TRUE(are_possibly_aliased_p(V1_view_2, V1));
EXPECT_TRUE(are_possibly_aliased_p(V1, V1_view_2));
EXPECT_FALSE(are_possibly_aliased_p(V2, V1_view_2));
}
TEST(Memory_Chunck_Aliasing, matrix)
{
Matrix<int> M1(10, 10);
Tiny_Matrix<int, 4, 3> M2;
EXPECT_FALSE(are_not_aliased_p(M1, M1));
EXPECT_TRUE(are_not_aliased_p(M1, M2));
EXPECT_TRUE(are_possibly_aliased_p(M1, M1));
EXPECT_FALSE(are_possibly_aliased_p(M1, M2));
auto M1_view_1 = create_matrix_view(M1, 2, 5, 4, 6);
auto M1_view_2 = create_matrix_view(M1.as_const(), 6, 8, 4, 6);
auto M1_view_3 = create_matrix_view(M1.as_const(), 2, 5, 2, 4);
// CAVEAT: this is not a bug, they are considered aliased as the
// whole column is "stored" (leading dimension > I_size)
//
// 0 1 1 0
// 0 1 1 0
// 0 1 1 0
// 0 0 0 0
// 0 2 2 0
// 0 2 2 0
EXPECT_TRUE(are_possibly_aliased_p(M1_view_1, M1_view_2));
// Ok here as columns are different
//
// 0 0 0 0 0
// 3 3 1 1 0
// 3 3 1 1 0
// 3 3 1 1 0
// 0 0 0 0 0
// 0 0 0 0 0
EXPECT_TRUE(are_not_aliased_p(M1_view_1, M1_view_3));
EXPECT_TRUE(are_possibly_aliased_p(M1_view_2, M1));
EXPECT_TRUE(are_possibly_aliased_p(M1, M1_view_2));
EXPECT_FALSE(are_possibly_aliased_p(M2, M1_view_2));
}
// Mix of matrix and vector (->think to diagonal or row/col views)
//
TEST(Memory_Chunck_Aliasing, matrix_vector)
{
Matrix<int> M1(10, 10);
auto diagonal = create_vector_view_matrix_diagonal(M1);
Vector<double> V1(10);
EXPECT_TRUE(are_not_aliased_p(M1, V1));
EXPECT_TRUE(are_possibly_aliased_p(M1, diagonal));
}
| true |
224dee7ba17bf25f7120f1dae5c63845bc0ef526 | C++ | singerinsky/omgserver | /soccer_ai/entity_manager.cpp | UTF-8 | 599 | 2.6875 | 3 | [] | no_license | #include "../common/head.h"
#include "entity_manager.h"
EntityManager::EntityManager(void)
: _map(64)
{
}
void EntityManager::enregister(GameEntity *entity)
{
std::pair<MapIter, bool> insert_result;
insert_result = _map.insert(Map::value_type(entity->get_id(), entity));
LOG_IF(FATAL, insert_result.second == false) << "entity id dup";
}
void EntityManager::unregister(uint32_t id)
{
_map.erase(id);
}
GameEntity *EntityManager::get(uint32_t id)
{
Map::iterator iter = _map.find(id);
if (iter != _map.end())
{
return iter->second;
}
return NULL;
}
| true |
361ccbf3a7f9cc1cb98208441ac1edad1cbd04ca | C++ | Merfoo/CS-162 | /assignments/Maze/Maze/Game.cpp | UTF-8 | 3,309 | 2.875 | 3 | [] | no_license | #include "Game.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include "Util.h"
#include "Player.h"
#include "Swan.h"
using namespace std;
using namespace Util;
Game::Game()
{
m_gameSteps = 0;
m_levelsLength = 0;
m_levels = 0;
m_actors = 0;
}
Game::~Game()
{
if (m_levels != 0)
delete[] m_levels;
if (m_actors != 0)
{
for (int i = 0; i < m_actorsLength; i++)
delete m_actors[i];
delete[] m_actors;
}
}
void Game::play(int numberOfLevels)
{
if (!createLevels(numberOfLevels))
return;
int levelIndex = 0;
createActors();
setupActors(m_levels[levelIndex]);
Player* player = (Player*)m_actors[0];
while (true)
{
m_gameSteps++;
m_levels[levelIndex].print(m_actors, m_actorsLength);
cout << "Apples: " << player->getApples();
cout << ", Keys: " << player->getKeys();
cout << ", Game Step: " << m_gameSteps << endl;
if ((m_gameSteps + 1) % m_swanSpawnSteps == 0)
spawnSwan(m_levels[levelIndex]);
for (int i = 0; i < m_actorsLength; i++)
m_actors[i]->update(m_levels[levelIndex]);
if (m_levels[levelIndex].shouldLoadNext())
{
if (++levelIndex < numberOfLevels)
{
setupActors(m_levels[levelIndex]);
m_gameSteps = 0;
}
else
{
cout << "You have escaped the maze!" << endl;
break;
}
}
else if (m_levels[levelIndex].shouldQuit())
{
cout << "Bye you quitter!" << endl;
break;
}
else if (!player->immuneToSwans())
for (int i = 1; i < m_actorsLength; i++)
if (nextToEachOther(player, m_actors[i]))
player->setPos(m_levels[levelIndex].getPlayerSpawnPos());
}
}
bool Game::nextToEachOther(Actor* a, Actor* b)
{
return abs(a->getX() - b->getX()) <= 1 && abs(a->getY() - b->getY()) <= 1;
}
bool Game::createLevels(int numberOfLevels)
{
if (m_levels != 0)
delete[] m_levels;
m_levelsLength = numberOfLevels;
m_levels = new Level[m_levelsLength];
for (int i = 0; i < m_levelsLength; i++)
{
string filename = "floor_" + to_string((long long)(i + 1)) + ".txt";
if (!m_levels[i].create(filename, i == m_levelsLength - 1))
return false;
}
return true;
}
void Game::createActors()
{
if (m_actors != 0)
{
for (int i = 0; i < m_actorsLength; i++)
delete m_actors[i];
delete[] m_actors;
}
m_actorsLength = 1;
m_actors = new Actor*[m_actorsLength];
m_actors[0] = new Player;
}
void Game::setupActors(Level& level)
{
Actor* tmpPlayer = m_actors[0];
for (int i = 1; i < m_actorsLength; i++)
delete m_actors[i];
delete[] m_actors;
m_actorsLength = 2;
m_actors = new Actor*[m_actorsLength];
m_actors[0] = tmpPlayer;
m_actors[1] = new Swan;
m_actors[0]->setPos(level.getPlayerSpawnPos());
m_actors[1]->setPos(level.getSwanSpawnPos());
}
void Game::spawnSwan(Level& level)
{
Actor** tmp = new Actor*[m_actorsLength + 1];
for (int i = 0; i < m_actorsLength; i++)
tmp[i] = m_actors[i];
Swan* swan = new Swan;
while (!level.isEmpty(swan->getX(), swan->getY()))
{
int x = getRandomInt(0, level.getBoardWidth());
int y = getRandomInt(0, level.getBoardHeight());
swan->setPos(x, y);
}
tmp[m_actorsLength] = swan;
delete[] m_actors;
m_actors = tmp;
m_actorsLength++;
}
| true |
ec80ec0de4cabc7f497dfbd58a7b5521a8111db3 | C++ | mshiihara/openal_sample | /WaveFileLoadSample/WaveFile.h | SHIFT_JIS | 960 | 2.640625 | 3 | [] | no_license | #pragma once
#include <stdio.h>
#include <Windows.h>
#include "type.h"
class WaveFile {
private:
// `Nʂׂ̒l
static const uint32 CHUNK_RIFF_TAG = 'FFIR';
static const uint32 CHUNK_FMT_TAG = ' tmf';
static const uint32 CHUNK_DATA_TAG = 'atad';
// RIFF`N͒ʏ̃`NɃtH[}bg
struct RIFFHeader {
uint32 tag;
uint32 size;
uint32 format;
};
// Wavet@C̃`Ni[邽߂̌^
struct WaveChunk {
uint32 tag;
uint32 size;
};
FILE* fp = nullptr;
WAVEFORMATEX format;
long fileSize = -1;
long dataSize = -1;
public:
WaveFile();
WaveFile(const char* path);
virtual ~WaveFile();
bool open(const char* path);
void close();
WAVEFORMATEX const * getFormat();
long getFileSize();
long getDataSize();
int read(void* dest, int length);
private:
int parseHeader();
bool parseWaveChunk(WaveChunk* chunk, uint32 tag);
}; | true |
422a5e951bcdf1ec3ffc7cd6ef64f1632d2b9c91 | C++ | beibeisongs/C-HomeworkInMyUniversityLife | /Struct-Huffman-MinHeap/Heap.h | UTF-8 | 4,447 | 3.46875 | 3 | [] | no_license | #ifndef __HP_H__
#define __HP_H__
#include<iostream>
#include"HuffmanTree.h"
using namespace std;
enum BOOL {False, True};
template<class T, class E>
class MinHeap {
public:
MinHeap(int sz); // 构造函数:建立空堆
MinHeap(E arr[], int n); // 构造函数:通过一个数组
~MinHeap() { // 析构函数
delete[] heap;
}
bool Insert(E x); // 将x插入到最小堆中
bool removeMin(E &x); // 删除堆顶元素
bool isEmpty() const {
return (this->currentSize == 0) ? true : false;
}
bool IsFull() const {
return (this->currentSize == this->maxHeapSize) ? true : false;
}
void makeEmpty() { // 置空堆
currentSize = 0;
}
private:
E * heap; // 存放最小堆中元素的数组
int currentSize; // 最小堆中当前的元素
int maxHeapSize; // 最小堆最多允许存放元素个数
void siftDown(int start, int m); // 从start到m下滑调整为最小堆
void siftUp(int start); // 从start到0上划成为最小堆
};
template<class T, class E>
MinHeap<T, E>::MinHeap(int maxHeapSize) {
this->maxHeapSize = maxHeapSize;
this->heap = new E[this->maxHeapSize];
if (heap == NULL) {
cout << "堆分配内存失败 !" << endl;
exit(1);
}
this->currentSize = 0;
}
template<class T, class E>
MinHeap<T, E>::MinHeap(E arr[], int n) {
this->maxHeapSize = n;
this->heap = new E[this->maxHeapSize];
if (heap == NULL) {
cout << "堆内存分配失败" << endl;
exit(1);
}
for (int i = 0; i < n; i++) { // 复制堆数组,建立当前大小
this->heap[i] = arr[i];
}
this->currentSize = n;
int currentPos = (currentSize - 2) / 2; // 找最初调整位置:最后分支结点
// 这是最后一个结点的根结点
while (currentPos >= 0) { // 自底向上逐步扩大形成堆
this->siftDown(currentPos, currentSize - 1);
currentPos--;
}
}
template<class T, class E>
void MinHeap<T, E>::siftDown(int start, int m) {
// 私有函数:从结点start开始到m为止,自上向下比较,如果子女的值小于父结点的值
// 则关键码小的上浮,继续向下层比较,这样将一个集合局部调整为最小堆
int i = start;
int j = 2 * i + 1; // 从而j得到i的左子节点的下标(计算机思维)
// 请注意这个基础算法
E temp = heap[i]; // temp被赋值当前结点值
E job = heap[j];
E j2 = heap[j + 1];
while (j <= m) {
if (j < m && job->data > j2->data) j++; // 让j指向两子女中的小者
if (temp->data <= job->data) break; // 小则不做调整
else {
heap[i] = heap[j]; // 否则小者上移,i,j下降
i = j;
j = 2 * j + 1; // j移动到它的左结点的下标(计算机思维)
}
}
heap[i] = temp; // i 要么移动过,要么保持原来的值不变
}
template<class T, class E>
bool MinHeap<T, E>::Insert(E x) {
// 公有函数:将x插入到最小堆中
if (this->currentSize == this->maxHeapSize) {
cout << "Heap Full ! " << endl;
return false;
}
this->heap[currentSize] = x; // 插入
this->siftUp(currentSize); // 向上调整
this->currentSize++; // 堆计数+1
E job;
for (int i = 0; i < this->currentSize; i++) {
job = heap[i];
cout << "data: " << job->data << endl;
}
cout << endl;
return true;
}
template<class T, class E>
void MinHeap<T, E>::siftUp(int start) {
// 私有函数:从结点start开始到结点0为止,自下向上比较
// 如果子女的值小于父结点的值
// 则相互交换,这样重新将集合调整为最小堆
int j = start;
int i = (j - 1) / 2; // 因为现在是自下向上调整,所以j是最底部的那个结点
// 该指令让i得到j的根节点的下标(计算机思维)
E temp = heap[j];
E job = heap[i];
while (j > 0) {
if (job->data <= temp->data) break; // 父结点值小,不作调整
else { // 父结点值大,调整
heap[j] = heap[i];
j = i; // j的值在这里被更新
i = (i - 1) / 2;
}
}
heap[j] = temp; // 值回送
}
template<class T, class E>
bool MinHeap<T, E>::removeMin(E &x) {
if (!this->currentSize) { // 堆空,返回false
cout << "Heap Empty !" << endl;
return false;
}
x = heap[0];
heap[0] = heap[currentSize - 1];
currentSize--;
this->siftDown(0, currentSize - 1); // 自小向下调整为堆
E job;
for (int i = 0; i < this->currentSize; i++) {
job = heap[i];
cout << "data: " << job->data << endl;
}
cout << endl;
return true;
}
#endif // __HP_H__
| true |
0890fb61cbc4fa89b71336b2281b006c58125090 | C++ | piyush1146115/Competitive-Programming | /Intra University Contest/MBSTU individual contest on bin search 29 march, 2017/D - Calm Down.cpp | UTF-8 | 1,007 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define eps 1e-7
#define sq(x) x*x
#define pi acos(-1)
int main()
{
int test;
scanf("%d", &test);
double n, r;
for(int tc = 1; tc <= test; tc++){
scanf("%lf %lf", &r, &n);
double a, b, c;
double lo = 0.0, hi = r, mid;
while(1){
mid = (lo + hi)/2.0;
a = 2.0 * mid;
b = r - mid;
c = r - mid;
double temp = ((sq(b) + sq(c) - sq(a))/(2.0*b*c));
double angle = acos(temp) * (180 / pi);
double total = angle * n;
//cout << mid << " " << angle << endl;
// printf("%lf %lf %lf\n",mid, temp, angle);
//getchar();
if(abs(total - 360.0) <= eps)
break;
if(total > 360.0)
hi = mid;
else
lo = mid;
}
printf("Case %d: %.10lf\n", tc, mid);
}
return 0;
}
| true |