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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2d016f5994782761a7137cfd2e9b7bbd722b296f | C++ | jesusma3009/final | /include/ConjuntoParticulas.h | UTF-8 | 886 | 2.59375 | 3 | [] | no_license | #ifndef _CONJUNTOPARTICULA_
#define _CONJUNTOPARTICULA_
#include "Particula.h"
#include <iostream>
const int MIN_SIZE = 5;
const int TAM_BLOQUE = 3;
using std::cout;
using std::endl;
class ConjuntoParticulas
{
private:
Particula *set;
int capacidad;
int utiles;
void Redimensiona(bool agrandar);
void Iniciar(int tamanio);
public:
ConjuntoParticulas(int tamanio = 0);
void liberar();
int GetCapacidad() const;
int GetUtiles() const;
void AgregaParticula(const Particula p);
void BorraParticula(const int pos);
Particula ObtieneParticula(int pos) const{ return set[pos]; };
void ReemplazaParticula (const int pos, const Particula p);
void Mover(const int ancho, const int alto);
void Rebotar(const int ancho, const int alto);
void Mostrar();
};
#endif | true |
7bd50ba1b1f1e2a8316b5d0f02081edf9c28a875 | C++ | AndrewMorris-scsu/CSClassFiles | /CSCI331 final review/CLion/BPlusTree/BPlusTree.cpp | UTF-8 | 40,655 | 2.921875 | 3 | [] | no_license | /**
* @file BPlusTree.cpp
* implementation file for B+ tree
* @authors Jeff Witthuhn, Ross Kostron, Subodh Bhattarai, Andrew Morris, Alex Gatzke
*/
#include "BPlusTree.h"
#include "fileOperations.h"
template <class keyType>
BPlusTree<keyType>::BPlusTree(){}
template <class keyType>
BPlusTree<keyType>::BPlusTree(int _keyNum, string _originalFileName, string _treeFileName, int _order){
order =_order;
keyNum=_keyNum;
originalFileName=_originalFileName;
treeFileName=_treeFileName;
}
template <class keyType>
void BPlusTree<keyType>::search(string parameterKey)
{
int order = 0;
int key = 0;
int rootRBN = 0;
string mySearchKey = parameterKey;
string searchKey = 0;
int elementsUsed = 0;
int pointer = 0;
Record tempRecord;
/* update tree variables */
order = BPlusTree.getField("order");
key = BPlusTree.getField("key");
rootRBN = BPlusTree.getField("rootRBN");
/* load root block into memory */
Block block(rootRBN, file);
block.readBlock(rootRBN, file);
/* update block variables */
elementsUsed = block.getUsed();
/* while at an interior node */
while (!block.isLeaf())
{
/* locate appropriate searchKey value */
int i = 0;
for (i = 0; i < elementsUsed; i++)
{
searchKey = block.getKey[i];
if (mySearchKey.compare(searchKey) < 0)//CHANGE TO STRING COMPARE
break;
}
/* get child RBN associated with appropriate searchKey value */
pointer = block.getChild[i];
/* read child block (new current block) into memory */
block.readBlock(pointer, file);
/* update elementsUsed */
elementsUsed = block.getUsed()
}
int i = 0;
for (i = 0; i < elementsUsed - 1; i++)
{
tempRecord = block.getChild[i];
if (key == 1)
{
/* key is Last */
searchKey = tempRecord.Last;
}
else if (key == 2)
{
/* key is First */
searchKey = tempRecord.First;
}
else if (key == 3)
{
/* key is ID1 */
searchKey = tempRecord.ID1;
}
else if (key == 4)
{
/* key is ID2 */
searchKey = tempRecord.ID2;
}
if (searchKey > mySearchKey)
break;
}
if (searchKey.compare(mySearchKey) == 0)
{
cout << "Record found: " << tempRecord.Last ", " << tempRecord.First
<< " " << tempRecord.ID1 << " " << tempRecord.ID2 << endl;
}
else
{
cout << "Sorry, no record with that key exists in the tree" << endl;
}
return 0;
}
template <class keyType>
void BPlusTree<keyType>::Print(ostream& outfile){
fstream file(treeFileName, std::fstream::in | std::fstream::out);
Block root_block;
root_block.readBlock(rootRBN, file);
outfile<<"root block:"<<endl;
//root_block.writeBlock(outfile);
Record r;
if(root_block.leaf()){
outfile<<"LEAF BLOCKS\n";
for(int i=0; i<root_block.getUsed(); i++){
r=root_block.getRecord(i);
outfile <<"|"<<setfill(' ')<<setw(10)<<r.Last<<" | ";
}
outfile<<endl;
for(int i=0; i<root_block.getUsed(); i++){
r=root_block.getRecord(i);
outfile <<"|"<<setfill(' ')<<setw(10)<<r.First<<" | ";
}
outfile<<endl;
for(int i=0; i<root_block.getUsed(); i++){
r=root_block.getRecord(i);
outfile <<"|"<<setfill('0')<<setw(10)<<r.ID1<<" | ";
}
outfile<<endl;
for(int i=0; i<root_block.getUsed(); i++){
r=root_block.getRecord(i);
outfile <<"|"<<setfill('0')<<setw(10)<<r.ID2<<" | ";
}
outfile<<endl;
}
}
template <class keyType>
void BPlusTree<keyType>::open(string _treeFileName) {
treeFileName = _treeFileName;
ifstream infile(treeFileName);
keyNum = getField("KY",infile);
rootRBN = getField("RR",infile);
order = getField("OR",infile);
}
template <class keyType>
void BPlusTree<keyType>::create(string _originalFileName, string _treeFileName, int _keyNum, int _order) {
order =_order;
keyNum=_keyNum;
originalFileName=_originalFileName;
treeFileName=_treeFileName;
extractKeys(originalFileName,"tmp_extracted_"+originalFileName, keyNum);
int memory=15;///number of items allowed in memory for replacement selection
bool ascending=true;
ifstream inputFile("tmp_extracted_"+originalFileName);
ofstream otemp("tmp_runs_"+originalFileName, std::ios_base::binary | std::ios_base::out |std::ios_base::trunc );
if(keyNum==1||keyNum==2){
ReplacementSelection<KeyPos<string> > sortedRuns(memory,inputFile,otemp,ascending);
otemp.close();
MergeFile<KeyPos<string> >("tmp_sortedRuns_"+originalFileName,"tmp_runs_"+originalFileName,ascending);
}
else{
ReplacementSelection<KeyPos<int> > sortedRuns(memory,inputFile,otemp,ascending);
otemp.close();
MergeFile<KeyPos<int> >("tmp_sortedRuns_"+originalFileName,"tmp_runs_"+originalFileName,ascending);
}
rewriteRecordFromKey(originalFileName, "tmp_sortedRuns_"+originalFileName);
initSequenceSet ("sorted"+originalFileName,treeFileName,order,keyNum);
buildFromSS(treeFileName);
}
template <class keyType>
void BPlusTree<keyType>::close(){
}
template <class keyType>
void BPlusTree<keyType>::insert(const keyType key, const int recAddr) {
}
/*
addRecord() is called from insertRecord(). It uses splitBlock() to
handle overfull blocks.
*/
int addRecord(Record record, int RBN, fstream& file)
{
Record tempRecord;
int key = 0;
int elementsUsed = 0;
int searchKey = 0;
int mySearchKey = 0;
/* load block into memory */
Block block(RBN, file);
block.readBlock(RBN, file);
/*set block variables */
key = BPlusTree.getField("key");
elementsUsed = block.getUsed();
/* get position at which to insert new record */
/* this is done by iterative comparison */
int i = 0;
for (i = 0; i < elementsUsed; i++)
{
tempRecord = block.getChild[i];
if (key == 3)
{ //case is ID1
searchKey = tempRecord.ID1;
mySearchKey = record.ID1;
if (searchKey > mySearchKey)
break;
}
else if (key == 4)
{ //case is ID2
searchKey = tempRecord.ID2;
mySearchKey = record.ID2;
if (searchKey > mySearchKey)
break;
}
}
/* put child in appropriate place in block */
if (i == elementsUsed)
block.putRecord(record);
else
block.putRecordAt(record, i);
/* if block is now overfull, time to split */
block.readBlock(RBN, file);
elementsUsed = block.getUsed();
if (elementsUsed > (order - 1))
splitBlock(RBN, file);
return 0;
}
/****************************************************************/
/* SPLIT BLOCK */
/****************************************************************/
int splitBlock(int rel_bl_num, filestream& filename) {
// Handle 4 cases:
// i. Root
// a. Root is the only node in tree
// b. Otherwise
// ii. Leaf
// iii. Internal node
// Local objects
Block overfullBlock(rel_bl_num, filename);
BPlusTree tree_object;
Record rec;
// Number of elements in the block
int elements = 0;
elements = overfullBlock.getUsed();
getLeftOverfull = overfullBlock.getLeft();
getRightOverfull = overfullBlock.getRight();
getRBNOverfull = overfullBlock.getRBN();
// Block order
int order = 0;
order = tree_object.getField("order");
// Midpoint of block
int splitted; // Split the block into two
splitted = cut(elements);
// Local Rel block number
int rbn;
if (overfullBlock.root()) { // When root
// ROOT: HANDLE BOTH CASES
if (!overfullBlock.getParent() && elements == (order - 1)) {
// Root is the only node here
/*****************************************************************/
// Allocate new leaf and move half the block's elements to new block
/*****************************************************************/
// Split it into two nodes and push the root up from the bottom
Block newBlock(false, true, rel_bl_num); // Root Block (parent)
Block newBlock1(); // Leaf
Block newBlock2(); // Leaf
newBlock1 = overfullBlock.putRecordAt(rec, 0, splitted);
newBlock2 = overfullBlock.putRecordAt(rec, (splitted+1), elements);
/*****************************************************************/
/* Insert the new leaf's smallest key and address into the parent*/
/*****************************************************************/
// Point the first pointer (left) of the root block (newBlock) to
// point to newBlock1
newBlock.setParent(rel_bl_num);
newBlock1.setLeaf(true);
newBlock2.setLeaf(true);
int _newBlock1_RBN = newBlock1.getRBN();
int _newBlock2_RBN = newBlock2.getRBN();
setLeft(_newBlock1_RBN);
setRight(_newBlock2_RBN);
// Copy the first key of the newBlock2 and pop up to the first key
// of the root block (newBlock)
newBlock.putKey(newBlock2.KeyFromRecord(rec));
// Kill the overfull block
overfullBlock.killBlock();
} else {
// Other cases
// Check if the minimum node is at least 2
if (elements == 1) {
// Boundary testing
// Exit out of this
cout << "Problem with the logic! This shouldn't happen!\n";
break;
}
// Check if the root's pointers all have children and
// if the root if overfull again
if (overfullBlock.getUsed() == order) {
/*****************************************************************/
// Allocate new leaf and move half the block's elements to new block
/*****************************************************************/
Block newBlock(false, true, rel_bl_num); // Root (parent)
Block newBlock1(); // Internal
Block newBlock2(); // Internal
/*****************************************************************/
/* Insert the new leaf's smallest key and address into the parent*/
/*****************************************************************/
// Point the first pointer (left) of the root block (newBlock) to
// point to newBlock1
newBlock.setParent(rel_bl_num);
newBlock1.setLeaf(false);
newBlock2.setLeaf(false);
int _newBlock1_RBN = newBlock1.getRBN();
int _newBlock2_RBN = newBlock2.getRBN();
setLeft(_newBlock1_RBN);
setRight(_newBlock2_RBN);
putChild(_newBlock1_RBN);
putChild(_newBlock2_RBN);
// Copy the first key of the newBlock2 and pop up to the first key
// of the root block (newBlock)
newBlock.putKey(newBlock2.KeyFromRecord(rec));
// Kill the overfull block
overfullBlock.killBlock();
} else {
/*****************************************************************/
// Allocate new leaf and move half the block's elements to new block
/*****************************************************************/
Block newBlock(false, true, rel_bl_num); // Root (parent)
Block newBlock1(); // Leaf
Block newBlock2(); // Leaf
newBlock1 = overfullBlock.putRecordAt(rec, 0, splitted);
newBlock2 = overfullBlock.putRecordAt(rec, (splitted+1), elements);
/*****************************************************************/
/* Insert the new leaf's smallest key and address into the parent*/
/*****************************************************************/
// Point the first pointer (left) of the root block (newBlock) to
// point to newBlock1
newBlock.setParent(rel_bl_num);
newBlock1.setLeaf(true);
newBlock2.setLeaf(true);
int _newBlock1_RBN = newBlock1.getRBN();
int _newBlock2_RBN = newBlock2.getRBN();
setLeft(_newBlock1_RBN);
setRight(_newBlock2_RBN);
// Copy the first key of the newBlock2 and pop up to the first key
// of the root block (newBlock)
newBlock.putKey(newBlock2.getKey());
// Kill the overfull block
overfullBlock.killBlock();
}
} // END of ROOT CASES
} else if (overfullBlock.leaf()) { // leaf
// LEAF BLOCK
// The block is a leaf
/*****************************************************************/
// Allocate new leaf and move half the block's elements to new block
/*****************************************************************/
Block newBlock(false, false, rel_bl_num); // Internal node (parent)
Block newBlock1(); // Leaf
Block newBlock2(); // Leaf
newBlock1 = overfullBlock.putRecordAt(rec, 0, splitted);
newBlock2 = overfullBlock.putRecordAt(rec, (splitted+1), elements);
/*****************************************************************/
/* Insert the new leaf's smallest key and address into the parent*/
/*****************************************************************/
// Point the first pointer (left) of the leaf block (newBlock) to
// point to newBlock1
newBlock.setParent(rel_bl_num);
newBlock1.setLeaf(true);
newBlock2.setLeaf(true);
int _newBlock1_RBN = newBlock1.getRBN();
int _newBlock2_RBN = newBlock2.getRBN();
setLeft(_newBlock1_RBN);
setRight(_newBlock2_RBN);
// Copy the first key of the newBlock2 and pop up to the first key
// of the leaf block (newBlock)
newBlock.putKey(newBlock2.KeyFromRecord(rec));
// Kill the overfull block
overfullBlock.killBlock();
// Check if the parent is full
// If yes, split it too
// add the middle key to the parent node
// Repeat until a parent if found that need not split.
if (newBlock.getParent()) {
rbn = newBlock.getRBN();
splitBlock(rbn, filename);
}
// END OF LEAF CASES
} else { // internal node
// INTERNAL BLOCK
/*****************************************************************/
// Allocate new leaf and move half the block's elements to new block
/*****************************************************************/
Block newBlock(false, false, rel_bl_num); // Internal node (parent)
Block newBlock1(); // Int node
Block newBlock2(); // Int node
//newBlock1 = overfullBlock.putRecordAt(rec, 0, splitted);
//newBlock2 = overfullBlock.putRecordAt(rec, (splitted+1), elements);
/*****************************************************************/
/* Insert the new leaf's smallest key and address into the parent*/
/*****************************************************************/
// Point the first pointer (left) of the internal node block (newBlock) to
// point to newBlock1
newBlock.setParent(rel_bl_num);
newBlock1.setLeaf(false);
newBlock2.setLeaf(false)
int _newBlock1_RBN = newBlock1.getRBN();
int _newBlock2_RBN = newBlock2.getRBN();
setLeft(_newBlock1_RBN);
setRight(_newBlock2_RBN);
putChild(_newBlock1_RBN);
putChild(_newBlock2_RBN);
// Copy the first key of the newBlock2 and pop up to the first key
// of the internal node block (newBlock)
newBlock.putKey(newBlock2.getKey(0));
// Kill the overfull block
overfullBlock.killBlock();
// Check if the parent is full
// If yes, split it too
// add the middle key to the parent node
// Repeat until a parent if found that need not split.
if (newBlock.getParent()) {
rbn = newBlock.getRBN();
splitBlock(rbn, filename);
}
// END OF INTERNAL BLOCK
}
return 0;
}
int cut (int length) {
if (length % 2 == 0) {
return length/2;
} else {
return ((length/2) + 1);
}
}
/*
removeRecord() is called from deleteRecord(). It uses mergeBlock() to
handle underfull blocks.
*/
int removeRecord(Record record, int RBN, fstream& file)
{
Record tempRecord;
int key = 0;
int elementsUsed = 0;
int order = 0;
int searchKey = 0;
int mySearchKey = 0;
/* load block into memory */
Block block(RBN, file);
block.readBlock(RBN, file);
/*set block variables */
key = BPlusTree.getField("key");
order = BPlusTree.getField("order");
elementsUsed = block.getUsed();
/* get position at which to remove record */
/* this is done by iterative comparison */
int i = 0;
for (i = 0; i < elementsUsed; i++)
{
tempRecord = block.getChild[i];
if (key == 3)
{ //case is ID1
searchKey = tempRecord.ID1;
mySearchKey = record.ID1;
if (searchKey == mySearchKey)
{
/* we have located the record to delete */
break;
}
else if (searchKey > mySearchKey)
{
/* This element is not found in the tree */
return 0;
}
}
else if (key == 4)
{ //case is ID2
searchKey = tempRecord.ID2;
mySearchKey = record.ID2;
if (searchKey == mySearchKey)
{
/* we have located the record to delete */
break;
}
else if (searchKey > mySearchKey)
{
/* This element is not found in the tree */
return 0;
}
}
}
/* remove child from appropriate place in block */
/* extra if check: in case the loop is completed, and mySearchKey > searchKey */
if (searchKey == mySearchKey)
{
block.removeRecordAt(i);
}
/* reload block */
/* if block is now underfull, time to merge */
block.readBlock(RBN, file);
elementsUsed = block.getUsed();
/* calculate min number of records */
float floatOrder = (float)order;
float floatElementsUsed = (float)elementsUsed;
if (floatElementsUsed < ((ceil(floatElementsUsed / 2)) - 1))
mergeBlock(RBN, file);
return 1;
}
/*
This is nearly identical to insertRecord, except it calls
removeRecord() instead of addRecord(). They could be combined,
and sent a parameter, bool isInsert, or isDelete.
*/
/*
This pseudo-code is for (key == Last || key == First),
not ID1 or ID2. This must be also implemented using strings.
*/
/*
"-->" signifies "calls":
insertRecord() --> addRecord() --> split()
deleteRecord() --> removeRecord() --> merge()
insertRecord() and deleteRecord() will locate the block in which
to insert or delete, then call add/removeRecord. It may send
add/removeRecord() a request to add record to a full block.
addRecord() and removeRecord() will be sent the RBN and handle
inserting the record into the block. They will utilize split/merge
in the case of an overfull leaf block OR interior block. (2 functions?)
split() and merge() will be recursive functions to ensure no blocks are
overfull or underfull
*/
int deleteRecord(Record record, fstream& file)
{
int order = 0;
int key = 0;
int rootRBN = 0;
int searchKey = 0;
int pointer = 0;
int mySearchKey = 0;
int RBN = 0;
/* update tree variables */
order = BPlusTree.getField("order");
key = BPlusTree.getField("key");
rootRBN = BPlusTree.getField("rootRBN");
switch (key)
{
case 1: mySearchKey = record.Last; break;
case 2: mySearchKey = record.First; break;
case 3: mySearchKey = record.ID1; break;
case 4: mySearchKey = record.ID2; break;
}
/* load root block into memory */
Block block(rootRBN, file);
block.readBlock(rootRBN, file);
/* update block variables */
elementsUsed = block.getUsed();
while (!block.isLeaf())
{
/* get appropriate searchKey value */
int i = 0;
for (i = 0; i < elementsUsed; i++)
{
searchKey = block.getKey[i];
if (searchKey > mySearchKey)
break;
}
/* get child RBN associated with appropriate searchKey value */
pointer = block.getChild[i];
/* read child block (new current block) into memory */
block.readBlock(pointer, file);
}
RBN = block.getRBN();
removeRecord(record, RBN, file);
return 0;
}
/*
FUNCTION NOT WORKING, THIS IS SORT OF PSEUDO-CODE!
This function is called from removeRecord().
It is sent the RBN of an underfull block.
Its task is to fix the tree so no blocks are underfull.
*/
int mergeBlock(int RBN, fstream& file)
{
Record movingRecord;
Record nextRecord;
int key = 0;
int order = 0;
int left = 0;
int right = 0;
int parent = 0;
bool right = false;
bool left = false;
oldSearchKey = 0;
newSearchKey = 0;
/* set tree variables */
key = BPlusTree.getField("key");
order = BPlusTree.getField("order");
/* load block into memory */
Block block(RBN, file);
block.readBlock(RBN, file);
/*set block variables */
elementsUsed = block.getUsed();
parent = block.getParent();
if (block.isLeaf())
{
left = block.getLeft();
right = block.getRight();
/* if we can only use values from one side */
if (left == -9999 || right == -9999)
{
if (left == -9999)
{
Block rightBlock(right, file);
rightBlock.readBlock(right, file);
float floatUsed = rightBlock.getUsed();
/* if right block has more than minimum number of records */
if (floatUsed > ((ceil(order / 2) - 1)))
{
/* move a record from right block to current block */
movingRecord = rightBlock.getRecord(0);
rightBlock.removeRecordAt(0);
block.putRecordAt(movingRecord, elementsUsed);
/* get next record in right block to copy in the key into parent */
nextRecord = rightBlock.getRecord(0);
/* get search keys to update keys in interior node */
if (key == 3)
{
oldSearchKey = movingRecord.ID1;
newSearchKey = nextRecord.ID1;
}
else if (key == 4)
{
oldSearchKey = movingRecord.ID2;
newSearchKey = nextRecord.ID2;
}
/* if blocks have same parent */
if (block.getParent() == rightBlock.getParent())
{
/* get parent block */
Block parentBlock(block.getParent(), file);
parentBlock.readBlock(block.getParent(), file);
int j = 0;
for (j = 0; j < order -1; j++)
{
if (parentBlock.getKey(i) == oldSearchKey)
{
parentBlock.setKey(newSearchKey, i);
break;
}
}
}
}
/* else right block has min number of records, merge */
else
{
/* delete current block and move its parts to right block */
int j = 0;
/* move all records in block to right block */
while (block.getUsed() > 0)
{
movingRecord = block.getRecord(block.getUsed() - 1);
block.removeRecordAt(block.getUsed() - 1);
rightBlock.putRecordAt(movingRecord, 0);
}
block.killBlock();
}
}
else if (right == -9999)
{
Block leftBlock(left, file);
leftBlock.readBlock(left, file);
float floatUsed = leftBlock.getUsed();
/* if left block has more than minimum number of records */
if (floatUsed > ((ceil(order / 2) - 1)))
{
/* move record from left block to current block */
movingRecord = leftBlock.getRecord(leftBlock.getUsed() - 1);
leftBlock.removeRecordAt(leftBlock.getUsed() - 1);
block.putRecordAt(movingRecord, 0);
/* get next record in left block to copy the key into parent */
nextRecord = leftBlock.getRecord(leftBlock.getUsed() - 1);
/* get search keys to update keys in interior node */
if (key == 3)
{
oldSearchKey = movingRecord.ID1;
newSearchKey = nextRecord.ID1;
}
else if (key == 4)
{
oldSearchKey = movingRecord.ID2;
newSearchKey = nextRecord.ID2;
}
/* if blocks have same parent */
if (block.getParent() == leftBlock.getParent())
{
/* get parent block */
Block parentBlock(block.getParent(), file);
parentBlock.readBlock(block.getParent(), file);
int j = 0;
for (j = 0; j < order -1; j++)
{
if (parentBlock.getKey(i) == oldSearchKey)
{
char *intStr = itoa(newSearchKey);
string str = string(intStr);
parentBlock.setKey(newSearchKey, i);
break;
}
}
}
}
/* else left block has min number of records, merge */
else
{
/* delete current block and move its parts to left block */
int j = 0;
/* move all records in block to left block */
while (block.getUsed() > 0)
{
movingRecord = block.getRecord(block.getUsed() - 1);
block.removeRecordAt(block.getUsed() - 1);
leftBlock.putRecord(movingRecord);
}
block.killBlock();
}
}
}
else
{
Block leftBlock(left, file);
Block rightBlock(right, file);
leftBlock.readBlock(left, file);
rightBlock.readBlock(right,file);
/* if both left and right blocks have minimum values */
if (leftBlock.getUsed() == elementsUsed+1 && rightBlock.getUsed() == elementsUsed+1)
{
/* delete current block and move its parts to left block */
int j = 0;
/* move all records in block to leftBlock */
while (block.getUsed() > 0)
{
movingRecord = block.getRecord(0);
block.removeRecordAt(0);
leftBlock.putRecord(movingRecord);
}
block.killBlock();
}
/* if left block has less values */
else if (leftBlock.getUsed() < rightBlock.getUsed())
{
/* move record from right block to current block */
movingRecord = rightBlock.getRecord(0);
rightBlock.removeRecordAt(0);
block.putRecordAt(movingRecord, elementsUsed);
/* get next record in right block to copy in the key into parent */
nextRecord = rightBlock.getRecord(0);
/* get search keys to update keys in interior node */
if (key == 3)
{
oldSearchKey = movingRecord.ID1;
newSearchKey = nextRecord.ID1;
}
else if (key == 4)
{
oldSearchKey = movingRecord.ID2;
newSearchKey = nextRecord.ID2;
}
/* if blocks have same parent */
if (block.getParent() == rightBlock.getParent())
{
/* get parent block */
Block parentBlock(block.getParent(), file);
parentBlock.readBlock(block.getParent(), file);
int j = 0;
for (j = 0; j < order -1; j++)
{
if (parentBlock.getKey(i) == oldSearchKey)
{
parentBlock.setKey(newSearchKey, i);
break;
}
}
}
}
/* else choose left (less or equal values) */
else
{
/* move record from left block to current block */
movingRecord = leftBlock.getRecord(leftBlock.getUsed() - 1);
leftBlock.removeRecordAt(leftBlock.getUsed() - 1);
block.putRecordAt(movingRecord, 0);
/* get next record in left block to copy the key into parent */
nextRecord = leftBlock.getRecord(leftBlock.getUsed() - 1);
/* get search keys to update keys in interior node */
if (key == 3)
{
oldSearchKey = movingRecord.ID1;
newSearchKey = nextRecord.ID1;
}
else if (key == 4)
{
oldSearchKey = movingRecord.ID2;
newSearchKey = nextRecord.ID2;
}
/* if blocks have same parent */
if (block.getParent() == leftBlock.getParent())
{
/* get parent block */
Block parentBlock(block.getParent(), file);
parentBlock.readBlock(block.getParent(), file);
int j = 0;
for (j = 0; j < order -1; j++)
{
if (parentBlock.getKey(i) == oldSearchKey)
{
parentBlock.setKey(newSearchKey, i);
break;
}
}
}
}
}
}
else //block is interior block
{
Block parentBlock(parent, file);
parentBlock.readBlock(parent, file);
Block rightBlock;
Block leftBlock;
int i = 0;
for (i = 0; i < order; i++)
{
if (parentBlock.getChild[i] == RBN)
{
break;
}
}
//i now holds the index of the block to be merged
/* if there is a left/right neighbor, link and load */
int parentUsed = parentBlock.getUsed();
if (i == getUsed() - 1)
{
rightBlock.read(parentBlock.getChild[i+1], file);
right = parentBlock.getChild[i+1];
}
else
right = -9999;
if (i == 0)
{
leftBlock.read(parentBlock.getChild[i-1], file);
left = parentBlock.getchild[i-1];
}
else
left = -9999;
/* if we can only use values from one side */
if (left == -9999 || right == -9999)
{
/* if left node is null */
if (left == -9999)
{
float floatUsed = rightBlock.getUsed() + 1;
/* if right block has more than minimum number of keys */
if (floatUsed > (ceil(order / 2)))
{
/* move a child and key from right block to current block */
movingRBN = rightBlock.getChildAt(0);
rightBlock.removeChildAt(0);
movingKey = rightBlock.getKey(0);
rightBlock.removeKeyAt(0);
block.putChild(movingRBN);
block.putKey(movingKey);
/* get search keys to update keys in interior node */
int childRBN = block.getChildAt(getUsed());
Block childBlock(childRBN, file);
childBlock.read(childRBN, file);
if (childBlock.isLeaf())
{
nextRecord = childBlock.getRecordAt(0);
if (key == 3)
{
oldSearchKey = movingKey;
newSearchKey = nextRecord.ID1;
}
else if (key == 4)
{
oldSearchKey = movingKey;
newSearchKey = nextRecord.ID2;
}
int j = 0;
for (int j = 0; j < order - 1; j++)
{
if (block.getKey(j) == oldSearchKey)
{
block.setKey(newSearchKey, j);
break;
}
}
}
else
//childBlock is not a leaf
{
oldSearchKey = movingKey;
newSearchKey = childBlock.getKey(0);
int j = 0;
for (int j = 0; j < order - 1; j++)
{
if (block.getKey(j) == oldSearchKey;
{
block.setKey(newSearchKey, j);
break;
}
}
}
}
/* else right block has min number of keys, merge */
else
{
/* delete right block and move its parts to current block */
movingRBN = rightBlock.getChildAt(0);
Block rightChildBlock(movingRBN, file);
rightChildBlock.readBlock(movingRBN, file);
/* get new search key */
if (rightChildBlock.isLeaf())
{
if (key == 3)
newSearchKey = (rightChildBlock.getRecordAt(0)).ID1;
else if (key ==4)
newSearchKey = (rightChildBlock.getRecordAt(0)).ID2;
}
else
{
newSearchKey = rightChildBlock.getKey(0);
}
block.putKey(newSearchKey);
/* move all records in block to right block */
while (rightBlock.getUsed() > 0)
{
movingRBN = rightBlock.getChildAt(0);
rightBlock.removeChildAt(0);
movingKey = rightBlock.getKey(0);
rightBlock.removeKeyAt(0);
block.putChild(movingRBN);
block.putKey(movingKey);
}
movingRBN = rightBlock.getChildAt(0);
rightBlock.removeChildAt(0);
block.putChild(movingRBN);
rightBlock.killBlock();
}
}
/* else if right node is null */
else if (right == -9999)
{
float floatUsed = leftBlock.getUsed() + 1;
/* if left block has more than minimum number of keys */
if (floatUsed > (ceil(order / 2)))
{
Block childBlock(block.getChild(0), file);
childBlock.readBlock(block.getChild(0), file);
oldSearchKey = childBlock.findKey(block.getChild(0), file);
/* move a child and key from left block to current block */
movingRBN = leftBlock.getChildAt(leftBlock.getUsed());
leftBlock.removeChildAt(leftBlock.getUsed());
leftBlock.removeKeyAt(leftBlock.getUsed() - 1);
block.putChildAt(movingRBN, 0);
block.putKeyAt(oldSearchKey, 0);
childBlock.readBlock(block.getChild(0),file);
newSearchKey = childBlock.findKey(childBlock, file);
/* update keys */
Block parentBlock(block.getParent(), file);
parentBlock.readBlock(block.getParent(), file);
int k = 0;
for (int k = 0; k < order - 1; k++)
{
if (parentBlock.getKey(k) == oldSearchKey)
{
parentBlock.setKey(newSearchKey, k);
break;
}
}
}
/* else left block has min number of keys, merge */
else
{
/* delete left block and move its parts to current block */
movingRBN = leftBlock.getChildAt(leftBlock.getUsed());
Block leftChildBlock(movingRBN, file);
leftChildBlock.readBlock(movingRBN, file);
newSearchKey = leftChildBlock.findKey(leftChildBlock, file);
oldSearchKey = block.findKey(block, file);
leftBlock.removeChildAt(leftBlock.getUsed());
block.putChildAt(movingRBN, 0);
block.putKeyAt(oldSearchKey, 0);
int k = 0;
for (k = 0; k < order - 1; k++)
{
if (parentBlock.getKey(k) == oldSearchKey)
{
parentBlock.setKey(newSearchKey, k);
}
}
/* move all records in left block to current block */
while (leftBlock.getUsed() > 0)
{
movingRBN = leftBlock.getChildAt(leftBlock.getUsed() - 1);
leftBlock.removeChildAt(leftBlock.getUsed() - 1);
movingKey = leftBlock.getKey(getUsed() - 1);
leftBlock.removeKeyAt(getUsed() - 1);
block.putChildAt(movingRBN, 0);
block.putKeyAt(movingKey, 0);
}
leftBlock.killBlock();
}
}
}
else
{
/* if both left and right blocks have minimum values */
if (leftBlock.getUsed() == elementsUsed+1 && rightBlock.getUsed() == elementsUsed+1)
{
/* delete right block and move its parts to current block */
Block rightChildBlock(movingRBN, file);
rightChildBlock.readBlock(movingRBN, file);
newSearchKey = rightChildBlock.findKey(rightChildBlock, file);
/* move all records in block to right block */
while (rightBlock.getUsed() > 0)
{
movingRBN = rightBlock.getChildAt(0);
newSearchKey = block.findKey(rightBlock.getChildAt(0), file);
rightBlock.removeChildAt(0);
movingKey = rightBlock.getKey(0);
rightBlock.removeKeyAt(0);
block.putChild(movingRBN);
block.putKey(newSearchKey);
}
movingRBN = rightBlock.getChildAt(0);
rightBlock.removeChildAt(0);
block.putChild(movingRBN);
rightBlock.killBlock();
}
/* else if right block has more records than left, choose right */
else if(leftBlock.getUsed() < rightBlock.getUsed())
{
/* move a child and key from right block to current block */
movingRBN = rightBlock.getChildAt(0);
rightBlock.removeChildAt(0);
movingKey = rightBlock.getKey(0);
rightBlock.removeKeyAt(0);
block.putChild(movingRBN);
block.putKey(movingKey);
/* get search keys to update keys in interior node */
int childRBN = block.getChildAt(getUsed());
Block childBlock(childRBN, file);
childBlock.read(childRBN, file);
if (childBlock.isLeaf())
{
nextRecord = childBlock.getRecordAt(0);
if (key == 3)
{
oldSearchKey = movingKey;
newSearchKey = nextRecord.ID1;
}
else if (key == 4)
{
oldSearchKey = movingKey;
newSearchKey = nextRecord.ID2;
}
int j = 0;
for (int j = 0; j < order - 1; j++)
{
if (block.getKey(j) == oldSearchKey)
{
block.setKey(newSearchKey, j);
break;
}
}
}
else
//childBlock is not a leaf
{
oldSearchKey = movingKey;
newSearchKey = childBlock.getKey(0);
int j = 0;
for (int j = 0; j < order - 1; j++)
{
if (block.getKey(j) == oldSearchKey;
{
block.setKey(newSearchKey, j);
break;
}
}
}
}
/* else choose left (less or equal values) */
else
{
/* move a child and key from left block to current block */
movingRBN = leftBlock.getChildAt(leftBlock.getUsed());
leftBlock.removeChildAt(leftBlock.getUsed());
leftBlock.removeKeyAt(leftBlock.getUsed() - 1);
block.putChildAt(movingRBN, 0);
block.putKeyAt(oldSearchKey, 0);
childBlock.readBlock(block.getChild(0),file);
newSearchKey = childBlock.findKey(childBlock, file);
/* update keys */
Block parentBlock(block.getParent(), file);
parentBlock.readBlock(block.getParent(), file);
int k = 0;
for (int k = 0; k < order - 1; k++)
{
if (parentBlock.getKey(k) == oldSearchKey)
{
parentBlock.setKey(newSearchKey, k);
break;
}
}
}
}
}
}
/*
This pseudo-code is for (key == Last || key == First),
not ID1 or ID2. This must be implemented using strings.
*/
/*
"-->" signifies "calls":
insertRecord() --> addRecord() --> split()
deleteRecord() --> removeRecord() --> merge()
insertRecord() and deleteRecord() will locate the block in which
to insert or delete, then call add/removeRecord. It may send
add/removeRecord() a request to add record to a full block.
addRecord() and removeRecord() will be sent the RBN and handle
inserting the record into the block. They will utilize split/merge
in the case of an overfull leaf block OR interior block. (2 functions?)
split() and merge() will be recursive functions to ensure no blocks are
overfull or underfull
*/
int insertRecord(Record record, fstream& file)
{
int order = 0;
int key = 0;
int rootRBN = 0;
int searchKey = 0;
int pointer = 0;
int mySearchKey = 0;
int RBN = 0;
/* update tree variables */
order = BPlusTree.getField("order");
key = BPlusTree.getField("key");
rootRBN = BPlusTree.getField("rootRBN");
switch (key)
{
case 1: mySearchKey = record.Last; break;
case 2: mySearchKey = record.First; break;
case 3: mySearchKey = record.ID1; break;
case 4: mySearchKey = record.ID2; break;
}
/* load root block into memory */
Block block(rootRBN, file);
block.readBlock(rootRBN, file);
/* update block variables */
elementsUsed = block.getUsed();
while (!block.isLeaf())
{
/* get appropriate searchKey value */
int i = 0;
for (i = 0; i < elementsUsed; i++)
{
searchKey = block.getKey[i];
if (searchKey > mySearchKey)
break;
}
/* get child RBN associated with appropriate searchKey value */
pointer = block.getChild[i];
/* read child block (new current block) into memory */
block.readBlock(pointer, file);
}
RBN = block.getRBN();
addRecord(record, RBN, file);
return 0;
}
template class BPlusTree<string>;
| true |
7476073eb95aefceed5c2cbffb8ba07219e95508 | C++ | MaryBagratunyan/GuessTheMovie | /GuessTheMovie/GetImageURLFromText.h | UTF-8 | 1,980 | 3.078125 | 3 | [] | no_license | #pragma once
#include <fstream>
#include <algorithm>
#include <iostream>
#include "Utils.h"
#include "Image.h"
int str_to_int(std::string& s)
{
for (int i = s.size() - 1; i >= 0; --i)
{
if (s[i] >= '0' && s[i] <= '9')
{
break;
}
else
{
s.pop_back();
}
}
int res = 0;
for (int i = 0; i < s.size(); ++i)
{
res += (s[i] - '0')*pow(10, s.size() - i - 1);
}
return res;
}
struct GetImageURLFromText
{
std::vector<Link> extract_image_url(const std::string& path)
{
std::string txt_path = path + "\\html.txt";
std::ifstream ifs(txt_path);
int unneunnecessary_strings = 765;
while (unneunnecessary_strings > 0)
{
std::string s;
std::getline(ifs, s);
--unneunnecessary_strings;
}
std::string temp = "src=\"";
std::string start_from = " <div class=\"media_index_pagination leftright\">";
bool need_to_check = true;
int count = 0;
std::vector<Link> v;
while (ifs.is_open())
{
std::string s;
std::getline(ifs, s);
if (need_to_check && (s != start_from))
{
continue;
}
if (need_to_check && (s == start_from))
{
need_to_check = false;
std::string s;
std::getline(ifs, s);
std::string num;
if (s.find("1-") == std::string::npos)
{
num = s.substr(35, 4);
}
else
num = s.substr(37, 4);
count = str_to_int(num);
continue;
}
if (count > 30)
count = 30;
while (count > 0)
{
bool match = true;
std::string s;
std::getline(ifs, s);
if (s.empty())
continue;
for (int i = 0; i < temp.size(); ++i)
{
if (temp[i] != s[i])
{
match = false;
break;
}
}
if (match)
{
std::string temp = "_V1";
auto it = std::search(s.begin(), s.end(), temp.begin(), temp.end());
std::string res = s.substr(5, it - s.begin() - 2) + ".jpg";
v.push_back(Link(res));
--count;
}
}
std::cout << "The URLs are succesfully exracted\n";
return v;
}
}
};
| true |
0c3271adfe0879a2b77b9f7c762a1d638ab8083f | C++ | akawashiro/competitiveProgramming | /clib/BridgeBiconnectedComponent.cpp | UTF-8 | 2,819 | 3.125 | 3 | [] | no_license | // 二重辺連結成分とは、「その成分に含まれるどの1辺を除いても、
// その成分が非連結にならないような部分グラフ」のことです。
// 橋という言葉を定義すると、二重辺連結成分とは、
// 「すべての橋をグラフから取り除いたときの連結成分」であると言うこともできます。
// 橋とは、その1辺を取り除いただけでグラフが非連結となるような辺のことです。
// よって橋を列挙することができれば、二重辺連結成分も列挙することができます。
struct Edge{
int to,cost;
};
bool operator < (const Edge &e,const Edge &f){ return e.cost>f.cost; }; //INVERSE!!
typedef vector<vector<Edge>> Graph;
void addEdge(Graph &g,int from,int to,int cost){
g[from].push_back((Edge){to,cost});
}
void bridgeDfs(const Graph &g,int cur, int prev, vector<pair<int,int> > &brg, vector<vector<int> > &each_bcc, stack<int> &roots, stack<int> &S, vector<bool> &inS, vector<int> &order, int &k){
// fprintf(stderr,"LINE=%d\n",__LINE__);
order[cur] = ++k;
S.push(cur); inS[cur] = true;
roots.push(cur);
for(int i=0;i<(int)g[cur].size();i++){
int to = g[cur][i].to;
if(order[to]==0){
bridgeDfs(g,to,cur,brg,each_bcc,roots,S,inS,order,k);
}
else if(to!=prev && inS[to]){ //後退辺をたどる
// fprintf(stderr,"LINE=%d\n",__LINE__);
while(order[roots.top()] > order[to])
roots.pop(); //cur〜toまで(toは含まない)の頂点をrootsから捨てる
}
}
// fprintf(stderr,"LINE=%d\n",__LINE__);
if(cur==roots.top()){
if(prev!=-1)brg.push_back(pair<int,int>(prev,cur));
vector<int> bcc;
while(1){
int node = S.top(); S.pop(); inS[node] = false;
bcc.push_back(node);
if(node==cur)break;
}
each_bcc.push_back(bcc);
roots.pop();
}
}
void bridge(const Graph &g,vector<pair<int,int>> &brg, vector<vector<int>> &each_bcc){
vector<int> order(MAX_V);
vector<bool> inS(MAX_V);
stack<int> roots, S;
int k=0;
for(int i=0;i<(int)g.size();i++){
if(order[i]==0){
bridgeDfs(g,i,-1,brg,each_bcc,roots,S,inS,order,k);
}
}
}
// m is a map from old vertex in g to new vertex in h
void compressToTree(const Graph &g,const vector<vector<int>> &each_bcc,Graph &h,map<int,int> &m){
for(int i=0;i<(int)each_bcc.size();i++){
for(int j=0;j<(int)each_bcc[i].size();j++)
m[each_bcc[i][j]] = i;
}
h = Graph(each_bcc.size());
for(int i=0;i<(int)g.size();i++){
for(auto e : g[i])
if(m[i] != m[e.to]){
addEdge(h,m[i],m[e.to],e.cost);
}
}
}
| true |
b41051466351134a1ab40cd667242b952219bad2 | C++ | x1aoo/ecn_arpro | /lecture_examples/hello.cpp | UTF-8 | 520 | 2.78125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <time.h>
#include <math.h>
#include <tuple>
int main(int argc, char ** argv)
{
/*std::cout << "Hello world!!" << std::endl;
std::cout << "You have " << argc << " arguments :" << std::endl;
for(unsigned int i=0;i<argc;++i)
std::cout << " - " << argv[i] << std::endl;
*/
int x = 5;
int* p = new int(4);
p = &x;
std::cout << *p << std::endl;
delete p;
//std::cout << *p << std::endl;
std::cout << x << std::endl;
}
| true |
b3b804a092010ee08dc595eb309b2c368646eebc | C++ | raulfe06/TPV | /PRÁCTICAS/Práctica 2/HolaSDL/Files/GameMap.h | ISO-8859-1 | 1,432 | 3.078125 | 3 | [] | no_license | #pragma once
#include "GameObject.h"
#include "Texture.h"
#include "SDL.h"
class Game;
// Tipos de celda para el mapa
enum mapCell { Empty, Wall, Food, Vitamins };
typedef struct {
// 1) Nombre del archivo de la imagen
string filename;
// 2) Fila y columna de la textura (por si estuviera dividida como un sprite sheet)
int row = 0;
int col = 0;
} textAtributes;
const int NUM_MAP_TEXTURES = 4; // Casilla vaca, Muro, Comida, Vitamina
// Arrays con los atrubitos de cada textura del mapa
const textAtributes TEXTURE_ATRIBUTES[NUM_MAP_TEXTURES] = { {"empty.png",1,1}, { "wall.png", 1, 1 },{ "food.png", 1, 1 },{ "vitamin.png", 1, 1 } };
/*
Clase GameMap: crea la matriz, a partir de la cual se crear y actualizar el nivel
- Crea la matriz dinmica de celdas.
- Crea sus texturas estticas.
- Se comunica con <Game> -> Indica, actualiza, etc., sus celdas
*/
class GameMap : public GameObject
{
private:
SDL_Rect destRect;
// Matriz dinmica de celdas
mapCell **map = nullptr;
// Array de texturas del mapa
Texture* textures[NUM_MAP_TEXTURES];
// Filas y columnas del mapa
int rows, cols;
public:
GameMap(Game*game);
void initializeTextures(SDL_Renderer* renderer);
void loadFromFile(ifstream& file);
void saveToFile(ofstream& file);
void render(SDL_Renderer* renderer);
mapCell getCell(int posX, int posY) const;
void setCell(int posX, int posY, mapCell cellKind);
~GameMap();
};
| true |
ace4c3744b320853eec8eb3a94be420441d47c8c | C++ | precht/imgproc | /src/core/Image.cpp | UTF-8 | 8,465 | 2.984375 | 3 | [] | no_license | /**
* Created: 19th Nov 2016
* Author: Jakub Precht
*/
#include "core/Image.hpp"
#include <iomanip>
//#include <iostream>
#include <memory>
#include <ostream>
#include <stdexcept>
#include <string>
namespace imgproc
{
namespace core
{
Image::Image()
: rows_(0)
, columns_(0)
, channels_(0)
, data_(nullptr)
, helper_(nullptr)
, input_name_("")
, output_name_("")
{ }
Image::Image(std::shared_ptr<ImageHelper> helper, std::string input_name, std::string output_name_)
: rows_(0)
, columns_(0)
, channels_(0)
, data_(nullptr)
, helper_(std::move(helper))
, input_name_(std::move(input_name))
, output_name_(std::move(output_name_))
{ }
Image::Image(int rows, int columns, int channels , std::shared_ptr<ImageHelper> helper,
std::string input_name, std::string output_name)
: rows_(rows)
, columns_(columns)
, channels_(channels)
, data_(nullptr)
, helper_(std::move(helper))
, input_name_(std::move(input_name))
, output_name_(std::move(output_name))
{
if(rows_ < 0) throw std::invalid_argument("image rows cannot be negative");
if(columns_ < 0) throw std::invalid_argument("image columns cannot be negative");
if(channels_ < 0) throw std::invalid_argument("image channels cannot be negative");
if(channels_ > MAX_CHANNELS) throw std::invalid_argument("image channels too big");
data_ = new unsigned char[rows_ * columns_ * channels_]();
}
Image::Image(const unsigned char *data, int rows, int columns, int channels, std::shared_ptr<ImageHelper> helper,
std::string input_name, std::string output_name)
: Image(rows, columns, channels, std::move(helper), std::move(input_name), std::move(output_name))
{
for(int i = 0; i < rows_ * columns_ * channels_; i++) data_[i] = data[i];
}
Image::Image(const Image& other)
: rows_(other.rows_)
, columns_(other.columns_)
, channels_(other.channels_)
, helper_(other.helper_)
, input_name_(other.input_name_)
, output_name_(other.output_name_)
{
const int n = rows_ * columns_ * channels_;
data_ = new unsigned char[n]();
for(int i = 0; i < n; i++) data_[i] = other.data_[i];
// std::cout << "Image(&)" << std::endl;
}
Image&Image::operator=(const Image& other)
{
// std::cout << "Image=(&)" << std::endl;
if(this != &other)
{
rows_ = other.rows_;
columns_ = other.columns_;
channels_ = other.channels_;
helper_ = std::move(other.helper_);
input_name_ = std::move(other.input_name_);
output_name_ = std::move(other.output_name_);
delete[] data_;
data_ = new unsigned char[rows_ * columns_ * channels_]();
const int n = rows_ * columns_ * channels_;
for(int i = 0; i < n; i++) data_[i] = other.data_[i];
}
return *this;
}
Image::Image(Image &&other)
: rows_(other.rows_)
, columns_(other.columns_)
, channels_(other.channels_)
, data_(other.data_)
, helper_(std::move(other.helper_))
, input_name_(other.input_name_)
, output_name_(other.output_name_)
{
other.rows_ = 0;
other.columns_ = 0;
other.channels_ = 0;
other.data_ = nullptr;
// std::cout << "Image(&&)" << std::endl;
}
Image& Image::operator=(Image &&other)
{
// std::cout << "Image=(&&)" << std::endl;
if(this != &other)
{
delete[] data_;
rows_ = other.rows_;
columns_ = other.columns_;
channels_ = other.channels_;
data_ = other.data_;
helper_ = std::move(other.helper_);
input_name_ = std::move(other.input_name_);
output_name_ = std::move(other.output_name_);
other.rows_ = 0;
other.columns_ = 0;
other.channels_ = 0;
other.data_ = nullptr;
}
return *this;
}
Image::~Image()
{
// std::cout << "start destructing..." << std::endl;
delete[] data_;
// std::cout << "end destructing..." << std::endl;
}
int Image::rows() const
{
return rows_;
}
int Image::columns() const
{
return columns_;
}
int Image::channels() const
{
return channels_;
}
int Image::size() const
{
return rows_ * columns_ * channels_;
}
std::shared_ptr<ImageHelper> Image::getHelper() const
{
return helper_;
}
void Image::setHelper(std::shared_ptr<ImageHelper> helper)
{
helper_ = helper;
}
std::string Image::getInputName() const
{
return input_name_;
}
void Image::setInputName(std::string input_name)
{
input_name_ = std::move(input_name);
}
std::string Image::getOutputName() const
{
return output_name_;
}
void Image::setOutputName(std::string output_name)
{
output_name_ = std::move(output_name);
}
unsigned char& Image::operator()(int index)
{
if(index < 0) throw std::out_of_range("image index cannot be negative");
if(index >= rows_ * columns_ * channels_) throw std::out_of_range("image index has to be smaller then size");
return data_[index];
}
unsigned char& Image::operator()(int row, int column, int channel)
{
if(row < 0) throw std::out_of_range("image row cannot be negative");
if(row >= rows_) throw std::out_of_range("image row has to be smaller then rows");
if(column < 0) throw std::out_of_range("image column cannot be negative");
if(column >= columns_) throw std::out_of_range("image column has to be smaller then columns");
if(channel < 0) throw std::out_of_range("image channel cannot be negative");
if(channel >= channels_) throw std::out_of_range("image channel has to be smaller then channels");
return data_[(row * (columns_ * channels_)) + (column * channels_) + channel];
}
void Image::resize(int rows, int columns, int channels)
{
rows_ = rows;
columns_ = columns;
channels_ = channels;
delete[] data_;
data_ = new unsigned char[rows_ * columns_ * channels_]();
}
bool Image::load()
{
if(!helper_) throw std::logic_error("need to set helper before loading image");
return helper_->load(*this);
}
bool Image::load(std::string name)
{
if(!helper_) throw std::logic_error("need to set helper before loading image");
input_name_ = std::move(name);
return helper_->load(*this);
}
bool Image::save()
{
if(!helper_) throw std::logic_error("need to set helper before saving image");
return helper_->save(*this);
}
bool Image::save(std::string name)
{
if(!helper_) throw std::logic_error("need to set helper before saving image");
output_name_ = std::move(name);
return helper_->save(*this);
}
void Image::crop(int rows_from_start, int rows_from_end, int columns_from_start, int columns_from_end)
{
if(rows_from_start < 0 || rows_from_end < 0)
throw std::invalid_argument("cannot crop negative number of rows");
if(columns_from_start < 0 || columns_from_end < 0)
throw std::invalid_argument("cannot crop negative number of columns");
if(rows_from_start + rows_from_end > rows_)
throw std::invalid_argument("cannot crop more rows than image has");
if(columns_from_start + columns_from_end > columns_)
throw std::invalid_argument("cannot crop more columns than image has");
int new_rows = rows_ - rows_from_start - rows_from_end;
int new_columns = columns_ - columns_from_start - columns_from_end;
Image tmp = Image(new_rows, new_columns, channels_, helper_, input_name_, output_name_);
for(int x = 0; x < new_rows; ++x)
for(int y = 0; y < new_columns; ++y)
for(int c = 0; c < channels_; c++)
tmp(x, y, c) = this->operator()(x + rows_from_start, y + columns_from_start, c);
this->swap(tmp);
}
void Image::swap(Image &other)
{
Image tmp = std::move(*this);
*this = std::move(other);
other = std::move(tmp);
}
void Image::clear()
{
rows_ = 0;
columns_ = 0;
channels_ = 0;
delete[] data_;
data_ = nullptr;
}
void Image::print(std::ostream &where) const
{
// if(!size()) return;
const int size_y = columns_ * channels_;
const int size_total = size_y * rows_;
where << "{";
for(int i = 0; i < size_total; ++i)
{
if(i == 0) where << "\n";
else if(i % size_y == 0) where << ",\n";
else if(i % channels_ == 0) where << ", ";
else where << ",";
where << std::setw(4) << (int)data_[i];
}
where << "\n}";
}
std::ostream& operator<<(std::ostream &out, const Image &image)
{
image.print(out);
return out;
}
} // core
} // imgproc
| true |
2c9239aeab1d5f72e96e95695b0fb53ad3dc63c3 | C++ | EthanSteinberg/GLUtil-old- | /src/render/render.cpp | UTF-8 | 4,996 | 2.625 | 3 | [] | no_license | #include "render.h"
#include "glUtil.h"
#include <GL/glew.h>
#include <iostream>
#include <boost/format.hpp>
#include <vector>
#include "imageUtil.h"
#include "matrix.h"
#include "renderList.h"
#include <cassert>
inline
void *offset(int floatNum)
{
return (void *)(sizeof(float) * floatNum);
}
void Render::setClearColor(float red,float green, float blue, float alpha)
{
glClearColor(red,green,blue,alpha);
}
void Render::clear()
{
glClear(GL_COLOR_BUFFER_BIT);
}
int Render::getWidth() const
{
return width;
}
int Render::getHeight() const
{
return height;
}
void Render::setSize(int _width,int _height)
{
assert(initialized);
width = _width;
height = _height;
glViewport(0,0,_width, _height);
}
Render::Render() : initialized(false)
{}
void Render::createAndBindBuffers(int numOfRects)
{
unsigned int buffers[2];
glGenBuffers(2,buffers);
checkGLError();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,buffers[1]);
checkGLError();
std::vector<unsigned short> indexes(6 * numOfRects);
for (int l = 0; l < 6 * numOfRects; l++)
{
int b = l % 6;
int c = l/6;
if (b < 3)
{
indexes[l] = b + c * 4;
}
else
{
indexes[l] = b -2 + c * 4;
}
}
glBufferData(GL_ELEMENT_ARRAY_BUFFER,6 * numOfRects * sizeof(short),&indexes[0],GL_STATIC_DRAW);
checkGLError();
glBindBuffer(GL_ARRAY_BUFFER,buffers[0]);
checkGLError();
glBufferData(GL_ARRAY_BUFFER,4 * numOfRects * sizeof(inputData),NULL,GL_STREAM_DRAW);
checkGLError();
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(inputData) ,offset(0));
checkGLError();
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,sizeof(inputData) ,offset(3));
checkGLError();
glVertexAttribPointer(2,2,GL_FLOAT,GL_FALSE,sizeof(inputData) ,offset(6));
checkGLError();
glVertexAttribPointer(3,1,GL_FLOAT,GL_FALSE,sizeof(inputData) ,offset(8));
checkGLError();
glEnableVertexAttribArray(0);
checkGLError();
glEnableVertexAttribArray(1);
checkGLError();
glEnableVertexAttribArray(2);
checkGLError();
glEnableVertexAttribArray(3);
checkGLError();
glBindAttribLocation(program,0,"in_Position");
checkGLError();
glBindAttribLocation(program,1,"in_Translation");
checkGLError();
glBindAttribLocation(program,2,"in_TextCord");
checkGLError();
glBindAttribLocation(program,3,"in_ZRotation");
checkGLError();
}
void Render::initialize(const std::string &frag, const std::string &vert, int numOfRects)
{
initialized = true;
GLenum err = glewInit();
if (GLEW_OK != err)
{
std::cout<<boost::format("Glew error: %s\n") % glewGetErrorString(err);
exit(1);
}
std::cout<<boost::format("Status: Using GLEW %s\n") % glewGetString(GLEW_VERSION);
GLuint vertShader = createShader(vert, GL_VERTEX_SHADER);
GLuint fragShader = createShader(frag, GL_FRAGMENT_SHADER);
program = createProgram(vertShader,fragShader);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
createAndBindBuffers(numOfRects);
activateProgram(program);
bindTexture();
}
Render::Render(const std::string &frag, const std::string &vert, int numOfRects)
{
initialize(frag,vert,numOfRects);
}
void Render::bindTexture()
{
glEnable(GL_TEXTURE_2D);
checkGLError();
glActiveTexture(GL_TEXTURE0);
checkGLError();
int texturePosition = glGetUniformLocation(program,"in_Texture");
checkGLError();
glUniform1i(texturePosition,0);
checkGLError();
textRenderModePosition = glGetUniformLocation(program,"textRenderMode");
checkGLError();
glUniform1i(textRenderModePosition,0);
checkGLError();
}
void Render::loadImage(const std::string &filename)
{
assert(initialized);
if (textMap.count(filename) == 0)
{
unsigned int texture;
glGenTextures(1,&texture);
checkGLError();
glBindTexture(GL_TEXTURE_2D,texture);
checkGLError();
loadTexture(filename);
textMap[filename] = texture;
}
else
{
glBindTexture(GL_TEXTURE_2D,textMap[filename]);
checkGLError();
}
}
void Render::perspectiveOrtho(double left,double right,double bottom, double top, double near, double far)
{
assert(initialized);
int perspectivePosition = glGetUniformLocation(program,"in_ProjectionMatrix");
checkGLError();
float matrix[16] = {};
makeOrtho(left,right,bottom,top,near,far,matrix);
glUniformMatrix4fv(perspectivePosition,1,false,matrix);
checkGLError();
}
void Render::setTextRenderMode(bool mode)
{
assert(initialized);
glUniform1i(textRenderModePosition,mode);
checkGLError();
}
void Render::drawVertices(const std::vector<inputData> &vertices)
{
assert(initialized);
glBufferSubData(GL_ARRAY_BUFFER,0, vertices.size() * sizeof(inputData),&vertices[0]);
checkGLError();
glDrawElements(GL_TRIANGLES,6 * vertices.size()/4,GL_UNSIGNED_SHORT,0);
checkGLError();
}
| true |
0a956221baea759d484adedcb3607b05ac3828a9 | C++ | daniel-bryant/parser | /parse.cpp | UTF-8 | 1,204 | 2.703125 | 3 | [] | no_license | #include "parse.h"
#include <iostream> // for std::cerr
#include "gram.hpp"
#include "lexer.yy.hpp"
#include "lexglobal.h"
#include "token.h"
void* ParseAlloc(void* (*allocProc)(size_t));
void Parse(void* parser, int token, Token tokenInfo, bool* valid);
void ParseFree(void* parser, void(*freeProc)(void*));
YYSTYPE yylval;
int parse(const char* str) {
int retval = 1;
// Set up the scanner
yyscan_t scanner;
yylex_init(&scanner);
YY_BUFFER_STATE bufferState = yy_scan_string(str, scanner);
// Set up the parser
void* gramParser = ParseAlloc(malloc);
int lexCode;
struct Token tokenInfo;
bool validParse = true;
do {
lexCode = yylex(scanner);
tokenInfo.str = yylval.sval;
tokenInfo.num = 123; // will be removed
Parse(gramParser, lexCode, tokenInfo, &validParse);
}
while (lexCode > 0 && validParse);
if (-1 == lexCode) {
retval = -1;
std::cerr << "The scanner encountered an error.\n";
}
if (!validParse) {
retval = -1;
std::cerr << "The parser encountered an error.\n";
}
// Cleanup the scanner and parser
yy_delete_buffer(bufferState, scanner);
yylex_destroy(scanner);
ParseFree(gramParser, free);
return retval;
}
| true |
d68d38d2797d5304acaf97a6e3d3ecc7d5cf85a9 | C++ | JinyuChata/leetcode_cpp | /leetcode/editor/cn/1621_number-of-sets-of-k-non-overlapping-line-segments.cpp | UTF-8 | 1,555 | 3.234375 | 3 | [] | no_license | //给你一维空间的 n 个点,其中第 i 个点(编号从 0 到 n-1)位于 x = i 处,请你找到 恰好 k 个不重叠 线段且每个线段至少覆盖两个点的方案数
//。线段的两个端点必须都是 整数坐标 。这 k 个线段不需要全部覆盖全部 n 个点,且它们的端点 可以 重合。
//
// 请你返回 k 个不重叠线段的方案数。由于答案可能很大,请将结果对 10⁹ + 7 取余 后返回。
//
//
//
// 示例 1:
//
//
//输入:n = 4, k = 2
//输出:5
//解释:
//如图所示,两个线段分别用红色和蓝色标出。
//上图展示了 5 种不同的方案 {(0,2),(2,3)},{(0,1),(1,3)},{(0,1),(2,3)},{(1,2),(2,3)},{(0,1),
//(1,2)} 。
//
// 示例 2:
//
//
//输入:n = 3, k = 1
//输出:3
//解释:总共有 3 种不同的方案 {(0,1)}, {(0,2)}, {(1,2)} 。
//
//
// 示例 3:
//
//
//输入:n = 30, k = 7
//输出:796297179
//解释:画 7 条线段的总方案数为 3796297200 种。将这个数对 10⁹ + 7 取余得到 796297179 。
//
//
// 示例 4:
//
//
//输入:n = 5, k = 3
//输出:7
//
//
// 示例 5:
//
//
//输入:n = 3, k = 2
//输出:1
//
//
//
// 提示:
//
//
// 2 <= n <= 1000
// 1 <= k <= n-1
//
// Related Topics 数学 动态规划 👍 37 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
int numberOfSets(int n, int k) {
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
Solution s;
} | true |
15b539e1572615a439e6c05785a10ac1bf044b85 | C++ | rzuniga64/cplusplus | /cosc1337/Source Files/lectures/lecture6/while_loops_and_loop_patterns/MaxOfNumbers.cpp | UTF-8 | 564 | 3.609375 | 4 | [] | no_license | // Reads in positive values and reports the largest
// when all are read. User indicates the end of the
// input by entering a negative number.
#include <iostream>
using namespace std;
int main()
{
double num, biggest = 0;
cout << "Enter a number: ";
cin >> num;
while (num >= 0)
{
//biggest = (num > biggest ? num : biggest);
if (num > biggest)
biggest = num;
cout << "Enter a number: ";
cin >> num;
}
cout << "Biggest number: " << biggest << endl;
system("PAUSE");
return 0;
}
| true |
6ff10d1c097c7fee2627ff9d34cafaa7f8bb2e49 | C++ | abdullah-al-jamil/LightOJ-Solutions | /1113 - Discover the Web.cpp | UTF-8 | 1,520 | 2.71875 | 3 | [] | no_license |
#include<bits/stdc++.h>
using namespace std;
int main()
{
stack<string>Stackfor;
stack<string>Stackback;
string s;
string ns;
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
printf("Case %d:\n",i);
//int k=1;
Stackback.push("http://www.lightoj.com/");
while(cin>>s)
{
//if(k==1) printf("Case 1:\n");
//k++;
if(s=="QUIT") break;
if(s=="VISIT")
{
cin>>ns;
Stackback.push(ns);
cout<<Stackback.top()<<endl;
while(!Stackfor.empty()) Stackfor.pop();
}
if(s=="BACK")
{
if(Stackback.size()!=1)
{
Stackfor.push(Stackback.top());
Stackback.pop();
cout<<Stackback.top()<<endl;
}
else{
cout<<"Ignored"<<endl;
}
}
if(s=="FORWARD")
{
if(Stackfor.size()!=0)
{
Stackback.push(Stackfor.top());
Stackfor.pop();
cout<<Stackback.top()<<endl;
}
else cout<<"Ignored"<<endl;
}
}
while(!Stackfor.empty()) Stackfor.pop();
while(!Stackback.empty()) Stackback.pop();
}
return 0;
}
| true |
0402d78bea0d280f7c9d20329d12c8e462291807 | C++ | NancyFulda/cs142SolutionCode | /Recitation_4_recursive_snakes/snakes.cpp | UTF-8 | 442 | 3.546875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int snake1(int x, int y);
int snake2(int x, int y);
int snake1(int x, int y) {
if ((x+y) % 2 == 0) return snake2(x-1,y);
else return x+y;
}
int snake2(int x, int y) {
if (x*y < 100) return snake1(x,y-1);
else return 1;
}
int main() {
int x,y;
cout << "Enter x and y" << endl;
cin >> x;
cin >> y;
cout << "The result is " << snake1(x,y) << endl;
return 0;
}
| true |
b33479108424d58cb51ca9ebf52253d801308fec | C++ | hleclerc/Evel | /test/test_Tcp.cpp | UTF-8 | 2,226 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #include "../src/Evel/System/Print.h"
#include "../src/Evel/TcpConnection_WF.h"
#include "../src/Evel/Listener_WF.h"
#include "../src/Evel/Timer_WF.h"
#include "../src/Evel/EvLoop.h"
#include <gtest/gtest.h>
using namespace Evel;
//TEST( Tcp, client ) {
// size_t msg_len = 0;
// EvLoop el;
// auto *conn_client = new TcpConnection_WF( { "127.0.0.1", 8080 } );
// conn_client->f_parse = [&]( TcpConnection_WF *c, char **data, size_t size, size_t rese ) {
// conn_client->close(); // should be closed also by the peer
// msg_len += size;
// };
// conn_client->send( "GET /rcds HTTP/1.0\n\n" );
// el << conn_client;
// auto *timer = new Timer_WF( 2.0, [&]( Timer_WF *, unsigned ) { ADD_FAILURE() << "Timeout"; return el.stop(); }, /* don't block the loop */ false );
// el << timer;
// el.run();
// delete timer;
// DISP_INFO( "received from server: {}", msg_len );
// EXPECT_TRUE( msg_len > 10 );
//}
TEST( Tcp, server_and_client ) {
size_t msg_len = 0;
EvLoop el;
// echo server
auto *listener = new Listener_WF( 5424, /* block_the_loop */ false );
listener->f_connection = []( Listener_WF *l, int fd, const InetAddress &addr ) {
auto *conn_server = new TcpConnection_WF( fd );
conn_server->f_parse = []( TcpConnection_WF *c, char **data, size_t size, size_t rese ) {
// I( "sending", *data, size );
c->send( *data, size );
c->close();
};
*l->ev_loop << conn_server;
};
el << listener;
// client
auto *conn_client = new TcpConnection_WF( { "127.0.0.1", 5424 } );
conn_client->f_parse = [&]( TcpConnection_WF *c, char **data, size_t size, size_t rese ) {
msg_len += size;
c->close();
};
// conn_client->f_close = []( TcpConnection_WF *c ) {
// I( "closing client" )
// };
conn_client->send( "pouet" );
el << conn_client;
// a timer for the test
auto *timer = new Timer_WF( 2.0, [&]( Timer_WF *, unsigned ) { ADD_FAILURE() << "Timeout"; return el.stop(); }, /* block_the_loop */ false );
el << timer;
el.run();
delete timer;
delete listener;
EXPECT_TRUE( msg_len == 5 );
}
| true |
b05de6dbbb1d57e4faef654a608c34b04c308788 | C++ | avisekksarma/OOP-labwork | /lab8/program3.cpp | UTF-8 | 811 | 3.984375 | 4 | [] | no_license | // 3. Write a program to overload stream operators to read a complex number and display the complex number in a+ib format.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Complex
{
private:
int r, i;
public:
Complex(int r = 0, int i = 0) : r(r), i(i) {}
friend std::istream &operator>>(std::istream &in, Complex &c);
friend std::ostream &operator<<(std::ostream &out, Complex &c);
};
std::istream &operator>>(std::istream &in, Complex &c)
{
cout << "Enter real part:" << endl;
in >> c.r;
cout << "Enter imag part:" << endl;
in >> c.i;
return in;
}
std::ostream &operator<<(std::ostream &out, Complex &c)
{
out<<c.r<<"+i"<<c.i<<endl;
return out;
}
int main()
{
Complex c;
cin>>c;
cout<<"You entered:"<<endl;
cout<<c;
} | true |
c4ac71a289c774cf4517e73e218f6aa5a158bb37 | C++ | thinhemb/Lap_Trinh_Co_Ban | /4_5.cpp | UTF-8 | 340 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class array
{
int *value;
int n;
public:
array(/* args */);
array(int n);
~array();
void nhap();
void xuat();
};
void array::nhap()
{
}
array::array(/* args */)
{
n=0;
value=null;
}
array::~array()
{
n=0
}
int main()
{
return 0;
}
| true |
bd9b8a9b07df956d9bc87af9ff7aeb4920aec9a3 | C++ | syzwdong/ThinkingInCppNote | /common/printBinary.cpp | UTF-8 | 282 | 3 | 3 | [] | no_license | //
// Created by 何时夕 on 2017/12/10.
//
#include <iostream>
using namespace std;
void printBinary(const unsigned char val){
for (int i = 7 ; i >= 0 ; --i) {
if (val & (1 << i)){
cout << "1";
} else {
cout << "0";
}
}
}
| true |
4a6c2c7bddaee8ed75b9650ab73428cf03597f91 | C++ | qpdf/qpdf | /examples/pdf-count-strings.cc | UTF-8 | 2,806 | 2.984375 | 3 | [
"Artistic-1.0",
"Artistic-2.0",
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"MIT",
"AGPL-3.0-or-later"
] | permissive | //
// This example illustrates the use of QPDFObjectHandle::TokenFilter with filterContents. See also
// pdf-filter-tokens.cc for an example that uses QPDFObjectHandle::TokenFilter with
// addContentTokenFilter.
//
#include <cstdlib>
#include <iostream>
#include <qpdf/Pl_StdioFile.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QUtil.hh>
static char const* whoami = nullptr;
void
usage()
{
std::cerr << "Usage: " << whoami << " infile" << std::endl
<< "Applies token filters to infile" << std::endl;
exit(2);
}
class StringCounter: public QPDFObjectHandle::TokenFilter
{
public:
StringCounter() = default;
~StringCounter() override = default;
void handleToken(QPDFTokenizer::Token const&) override;
void handleEOF() override;
int getCount() const;
private:
int count{0};
};
void
StringCounter::handleToken(QPDFTokenizer::Token const& token)
{
// Count string tokens
if (token.getType() == QPDFTokenizer::tt_string) {
++this->count;
}
// Preserve input verbatim by passing each token to any specified downstream filter.
writeToken(token);
}
void
StringCounter::handleEOF()
{
// Write a comment at the end of the stream just to show how we can enhance the output if we
// want.
write("\n% strings found: ");
write(std::to_string(this->count));
}
int
StringCounter::getCount() const
{
return this->count;
}
int
main(int argc, char* argv[])
{
whoami = QUtil::getWhoami(argv[0]);
if (argc != 2) {
usage();
}
char const* infilename = argv[1];
try {
QPDF pdf;
pdf.processFile(infilename);
int pageno = 0;
for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
++pageno;
// Pass the contents of a page through our string counter. If it's an even page, capture
// the output. This illustrates that you may capture any output generated by the filter,
// or you may ignore it.
StringCounter counter;
if (pageno % 2) {
// Ignore output for odd pages.
page.filterContents(&counter);
} else {
// Write output to stdout for even pages.
Pl_StdioFile out("stdout", stdout);
std::cout << "% Contents of page " << pageno << std::endl;
page.filterContents(&counter, &out);
std::cout << "\n% end " << pageno << std::endl;
}
std::cout << "Page " << pageno << ": strings = " << counter.getCount() << std::endl;
}
} catch (std::exception& e) {
std::cerr << whoami << ": " << e.what() << std::endl;
exit(2);
}
return 0;
}
| true |
fdf5432010ae4e1be1daa2c7f94cc210e6abbcb3 | C++ | wishedeom/COMP371_A2 | /COMP371_A2/COMP371_A2.cpp | UTF-8 | 7,905 | 2.515625 | 3 | [] | no_license | // ----------------------------------------------------------------------------
//
// COMP 371 - COMPUTER GRAPHICS
// ASSIGNMENT 2
// CONCORDIA UNIVERSITY
//
// Author: Michael Deom
// Submission Date: March 1, 2016
//
// ----------------------------------------------------------------------------
// For precompiled headers
#include "stdafx.h"
// OpenGl, GLFW, and GLM library inclusions
#define GLEW_STATIC // Use static GLEW libraries
#include "glew.h" // GL Extension Wrangler
#include "glfw3.h" // GLFW helper library
#include "glm.hpp" // Vector types
#include "gtc/matrix_transform.hpp" // Matrix types
#include "gtc/type_ptr.hpp" // Pointers to the above types
#include "gtc/constants.hpp" // Various constants
// Standard library inclusions
#include <iostream>
#include <vector>
// C libraries
#include <climits>
// Project file inclusions
#include "hermitepolynomial.h"
#include "polyline.h"
#include "hermitespline.h"
#include "shaders.h"
#include "vector_constants.h"
#include "point_collector.h"
#include "flatten.h"
#include "triangle.h"
#include "vec3_to_string.h"
// Function prototypes
void initialize();
void keyCallback(const GLFWwindow *window, const int key, const int scancode, const int action, const int mods);
void windowSizeCallback(const GLFWwindow* window, const int width, const int height);
glm::vec3 windowToWorldCoords(const glm::vec2 p);
//----------------------------- CONSTANTS -----------------------------
// Shader paths
const std::string vertexShaderPath = "vertexShader.vs";
const std::string fragmentShaderPath = "fragmentShader.fs";
// Initial window dimensions
const GLsizei WIDTH = 800;
const GLsizei HEIGHT = 800;
// Control
const GLfloat controlSensitivity = 0.1f;
// Triangle speed
const int initialSpeed = 50;
const int speedIncremenet = 5;
//----------------------------------------------------------------------
//----------------------------- GLOBAL VARIABLES ----------------------
GLFWwindow* window; // Pointer to OpenGL window objects
Shader shader; // Shader program object
// Transformation matrices
glm::mat4 viewMatrix;
glm::mat4 modelMatrix;
glm::mat4 projMatrix;
glm::mat4 transformationMatrix;
// To hold user-provided points
PointCollector* p_pointCollector;
// Polyline
Polyline* p_polyline;
// Triangle speed
int triangleSpeed = initialSpeed;
// Done collecting points
bool doneCollecting = false;
// True for collecting points, false for drawing splines
bool collectMode = true;
bool reset = false;
//----------------------------------------------------------------------
//------------------------- MAIN ---------------------------------------
int main() try
{
initialize(); // Set up OpenGL context
std::cout << "Please enter the number of points to interpolate: (>1)";
int numPoints = 0;
while (numPoints <= 1)
{
std::cin >> numPoints;
}
p_pointCollector = new PointCollector(numPoints);
Polyline polyline(true);
p_polyline = &polyline;
int i = 0;
Triangle triangle(0.1f, 0.05f, origin, up);
while (!glfwWindowShouldClose(window))
{
if (reset) // For resetting the program
{
reset = false;
std::cout << "Please enter the number of points to interpolate: (>1)";
int numPoints = 0;
while (numPoints <= 1)
{
std::cin >> numPoints;
}
delete p_pointCollector;
p_pointCollector = new PointCollector(numPoints);
}
// Pre-draw preparation
glfwPollEvents();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Use the shader program and pass the three transformation matrices to the shader program
transformationMatrix = projMatrix * viewMatrix * modelMatrix;
shader.use(transformationMatrix);
// Check to see if there are enough points to create a spline
if (p_pointCollector->isFull() || doneCollecting)
{
if (p_pointCollector->hasMinNumPoints())
{
polyline = p_pointCollector->hermiteSpline().polyline();
collectMode = false;
}
else
{
doneCollecting = false;
}
}
if (collectMode) // While collecting
{
p_pointCollector->draw();
}
else // After collecting
{
polyline.draw();
triangle.snapTo(polyline, i);
i = (i + triangleSpeed) % INT_MAX;
triangle.draw();
}
glfwSwapBuffers(window); // Swap buffers
}
// End program
glfwTerminate();
delete p_pointCollector;
return 0;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
exit(0);
}
// Manages keyboard input
void keyCallback(GLFWwindow *window, const int key, const int scancode, const int action, const int mods)
{
switch (key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE); // Escape key exits the application
break;
case GLFW_KEY_BACKSPACE: // Backspace resets
reset = true;
collectMode = true;
break;
case GLFW_KEY_ENTER: // Enter prematurely ends point collection
doneCollecting = true;
break;
case GLFW_KEY_LEFT: // Arrow keys translate camera
viewMatrix = glm::translate(viewMatrix, - controlSensitivity * left);
break;
case GLFW_KEY_RIGHT:
viewMatrix = glm::translate(viewMatrix, - controlSensitivity * right);
break;
case GLFW_KEY_UP:
viewMatrix = glm::translate(viewMatrix, -controlSensitivity * up);
break;
case GLFW_KEY_DOWN:
viewMatrix = glm::translate(viewMatrix, -controlSensitivity * down);
break;
case GLFW_KEY_EQUAL: // Plus and minus increase and decrease triangle speed
if (action == GLFW_PRESS && mods == GLFW_MOD_CONTROL)
{
triangleSpeed += speedIncremenet;
}
break;
case GLFW_KEY_MINUS:
if (action == GLFW_PRESS && mods == GLFW_MOD_CONTROL)
{
triangleSpeed -= speedIncremenet;
}
break;
case GLFW_KEY_P: // P and L set point/line draw mode
p_polyline->setPoints();
break;
case GLFW_KEY_L:
p_polyline->setLines();
break;
default:
break;
}
}
// Manages mouse click input
void mouseButtonCallback(GLFWwindow* window, const int button, const int action, const int mods)
{
switch (button)
{
case (GLFW_MOUSE_BUTTON_LEFT):
if (action == GLFW_PRESS)
{
double x, y;
glfwGetCursorPos(window, &x, &y);
if (!p_pointCollector->isFull())
{
p_pointCollector->collectPoint(windowToWorldCoords(glm::vec2(x, y)));
}
else
{
std::cout << "Full\n";
}
}
break;
default:
break;
}
}
// Manages window resizing
void windowSizeCallback(GLFWwindow* window, const int width, const int height)
{
glViewport(0, 0, width, height);
}
// Performs OpenGL set-up
void initialize()
{
// Initialize GLFW
glfwInit();
// Create window and check for errors
window = glfwCreateWindow(WIDTH, HEIGHT, "COMP 371 - Assignment 2", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window." << std::endl;
glfwTerminate();
}
// Make the window the current context
glfwMakeContextCurrent(window);
// Register callback functions
glfwSetKeyCallback(window, keyCallback);
glfwSetWindowSizeCallback(window, windowSizeCallback);
glfwSetMouseButtonCallback(window, mouseButtonCallback);
// Initialize GLEW and check for errors
glewExperimental = GL_TRUE; // Required for latest version of GLEW
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW." << std::endl;
exit(0);
}
// Compile and link the shaders into a shader program
shader = Shader(vertexShaderPath, fragmentShaderPath);
glPointSize(2.f);
}
// Converts a point in window coordinates to world coordinates
glm::vec3 windowToWorldCoords(const glm::vec2 p)
{
// Get window dimensions
int w, h;
glfwGetWindowSize(window, &w, &h);
// Transform to camera coordinates; we assume the z-coordinate to be 0
const GLfloat cameraX = 2 * p.x / w - 1;
const GLfloat cameraY = -(2 * p.y / h - 1);
// Transform to world coordinates by inverting the transformation matrix
return glm::vec3(glm::inverse(transformationMatrix) * glm::vec4(cameraX, cameraY, 0.0f, 1.0f));
} | true |
b6e336f69e52535e1d8e60f183abf78012b43eea | C++ | PolarisJunior/collection | /collection/ui/Keyboard.cpp | UTF-8 | 1,020 | 2.828125 | 3 | [] | no_license |
#include "Keyboard.h"
#include <SDL.h>
#include <set>
Keyboard::KeyStates Keyboard::states;
std::array<bool, Keyboard::NUM_SCANCODES> Keyboard::keys_pressed = {0};
static std::set<uint32_t> pressed_keys_to_reset;
static std::set<uint32_t> released_keys_to_reset;
void Keyboard::init() {
states = KeyStates{SDL_GetKeyboardState(nullptr)};
}
void Keyboard::Update() {
for (uint32_t key_index : pressed_keys_to_reset) {
keys_pressed[key_index] = false;
}
pressed_keys_to_reset.clear();
}
bool Keyboard::keyDown(uint32_t scanCode) {
return states.keyStates[scanCode];
}
bool Keyboard::keyUp(uint32_t scanCode) {
return !keyDown(scanCode);
}
bool Keyboard::KeyPressed(uint32_t scan_code) {
return keys_pressed[scan_code];
}
void Keyboard::NotifyKeyPressed(uint32_t scan_code) {
pressed_keys_to_reset.insert(scan_code);
keys_pressed[scan_code] = true;
}
bool Keyboard::KeyReleased(uint32_t scan_code) {
return false;
}
bool Keyboard::NotifyKeyReleased(uint32_t scan_code) {
return false;
} | true |
0808c2252efcc4b7c80b62ebdd6148b3e2299aa1 | C++ | loyso/StructureOfArrays | /StructureOfArrays/StructureOfArrays.h | UTF-8 | 1,214 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
struct Vec3 {
float x = 0;
float y = 0;
float z = 0;
Vec3() = default;
Vec3(float x, float y, float z);
Vec3& operator+=(const Vec3& v);
};
class Object {
public:
using Offset = size_t;
static void Init(Offset maxObjects);
static void Done();
static Object* New();
static void Delete(Object* obj);
Vec3& Position();
Vec3& Velocity();
float& Health();
float& Damage();
// position += velocity;
void Update();
struct All {
class iterator {
public:
explicit iterator(Offset offset) : offset(offset) {}
iterator& operator++() {
++offset;
return *this;
}
Object* operator->();
Object& operator*();
bool operator!=(iterator& i) {
return i.offset != offset;
}
private:
Offset offset;
};
iterator begin();
iterator end();
};
static All all;
private:
union {
Offset offset = 0;
Object* next;
};
static void CopyData(Offset from, Offset to);
struct Shared;
static Shared shared;
};
| true |
ce31fc8ab4f3491c3735788e46f2fc347c484f4b | C++ | Ghassen-kh/Cpp_Training | /revision/standard_library/file-management.cpp | UTF-8 | 494 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int main (int argc, char ** agv){
/*
const char * fn1 = "file1";
FILE * fh = fopen(fn1,"w");//create a file if it doesn't exist, if it already exist it will
// override it with an empty file
fclose(fh);
puts("file created !");
*/
/*
// to rename the file :
const char * fn2 = "file2";
rename(fn1,fn2);
*/
/*
// to delete a file :
remove(fn2);
puts("file deleted");
*/
return 0;
} | true |
1d14ffe6b5194fd05599cbc5a6649416b24f69ef | C++ | HEXcube/BTechLabs | /C++ source codes/Fair Record/9.Area of Shapes.cpp | UTF-8 | 1,554 | 4.03125 | 4 | [
"MIT"
] | permissive | /*Find the area of rectangle, triangle and sphere.
Use function overloading*/
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<iomanip.h>
unsigned int area(unsigned int,unsigned int); //rectangle
float area(unsigned int,unsigned int,unsigned int);//triangle
float area(float); //sphere
void main()
{
unsigned int l,b,h;
float r;
clrscr();
cout<<"I.Rectangle\n"
<<"Enter length and breadth : ";
cin>>l>>b;
cout<<"Area of Rectangle = "<<area(l,b)
<<" square units\n\n";
cout<<"II.Triangle\n"
<<"Enter lengths of the 3 sides : ";
cin>>l>>b>>h;
cout<<"Area of Triangle = "<<setprecision(3)<<area(l,b,h)
<<" square units\n\n";
cout<<"III.Sphere\n"
<<"Enter the radius : ";
cin>>r;
cout<<"Surface Area of Sphere = "<<setprecision(3)<<area(r)
<<" square units";
getch();
}
unsigned int area(unsigned int l,unsigned int b)
{
return l*b;
}
float area(unsigned int a,unsigned int b,unsigned int c)
{
float S;
S=(a+b+c)/2.0;
return sqrt( (S-a)*(S-b)*(S-c) )*S;
//Area of triangle = S√(S-a)x(S-b)x(S-c)
}
float area(float radius)
{
return 4*(22/7.0)*radius*radius;
//Surface area of Sphere = 4πr^2
}
/*OUTPUT
I.Rectangle
Enter length and breadth : 3 4
Area of Rectangle = 12 square units
II.Triangle
Enter lengths of the 3 sides : 2 3 4
Area of Triangle = 6.162 square units
III.Sphere
Enter the radius : 5
Surface Area of Sphere = 314.286 square units
*/ | true |
22d89d2447366e984dcac253058cc2c480766b38 | C++ | gayasha754/DSA | /Selection sort.cpp | UTF-8 | 2,082 | 3.984375 | 4 | [] | no_license | #include<iostream>
using namespace std;
// this program implements the Selection sort
/*
repetedly finding the minimum element(considering ascending order) from the unsorted part and puttting it at the beginning
algorithm maintains 2 subarrays
1.The subarray which is already sorted
2. Remaining subarray which is unsorted.
in every itertion of selsction sort, the minimum element from the unsorted subarrray s picked and moved to the sorted subarray
*/
void selectionSort(int *array , int size);
void print(int *array, int size);
int main(){
int list[] = {20,18,24,33,60,10,2};
int size = sizeof(list)/4;
cout << "The unsorted list is: \n" ;
print(list,size);
selectionSort(list, size);
return (0);
}
// first & second iteration are commented
void selectionSort(int *array, int size){
int min; //index of temporary minimum value
int temp; //Tepmorary variable used for swapping
//first iteration //second iteration
for(int i=0; i<size-1; i++){ // i=0 //i=1
min = i; // min = 0 // min=1
for(int j=i+1; j < size; j++){ //j=0+1=1 //j = 1+1 =2
if(array[j] < array[min]){ // ?(array[1] < array[0])...... ? (18<20)->true // ?(array[2] <array[1])...?(24<18)->false
min = j; // min = 1 //won't go into if
}
}
//then comes here.... if i = j then its the same index...no swapping can be done //directly comes here min=1 & i=1
if(min!=i){ // ? min= j = 1 ; ?(1 != 0) ->true... //this if statement also false
//swaping
temp = array[min];
array[min] = array[i]; //No swapping
array[i] = temp;
}
}
cout << "\nSorted list(Selection Sort) is: \n";
print(array,size);
}
void print(int *array, int size){
for(int k=0; k<size; k++){
cout << array[k] << " " ;
}
cout << endl;
}
| true |
316a6f49ca6853162693966fb6f388dd123823ea | C++ | nikhilbadgujar/Projects | /JavaPreProcessor/Analyser.cpp | UTF-8 | 3,775 | 2.96875 | 3 | [] | no_license | #include"Header.h"
unordered_map<string, string>table;
extern FILE *p;
//gets input as string terminated by '\0' or '\n'
// calls searchHash and nextElementAfterSpace functions
void analyser(char buffer[], int len)
{
if (buffer[0] == '#' || buffer[nextElementAfterSpace(buffer)] == '#')
{
int i = 0;
if (buffer[0] == '#')
i = 1 + nextElementAfterSpace(buffer + 1);
else
{
i = nextElementAfterSpace(buffer);
i++;
i = i + nextElementAfterSpace(buffer + i);
}
if (i + 7 < len)
if (buffer[i] == 'd' && buffer[i + 1] == 'e' && buffer[i + 2] == 'f' && buffer[i + 3] == 'i' && buffer[i + 4] == 'n' && buffer[i + 5] == 'e')
{
i = i + 6;
i = i + nextElementAfterSpace(buffer + i); if (i == 0) return;
int offset = i;
i = i + wordLength(buffer + i);
string skey(buffer + offset, buffer + i);
i = i + nextElementAfterSpace(buffer + i);
buffer[len - 1] = '\0';
string sbuffer = buffer + i;
table.insert(make_pair(skey, sbuffer));
//Search for existing macro
unordered_map<string, string>::iterator itr;
for (itr = table.begin(); itr != table.end(); itr++)
{
if (itr->second == skey)
itr->second = sbuffer;
}
}
else if (buffer[i] == 'i' && buffer[i + 1] == 'n' && buffer[i + 2] == 'c' && buffer[i + 3] == 'l' && buffer[i + 4] == 'u' && buffer[i + 5] == 'd' && buffer[i + 6] == 'e')
{
i = i + 7;
i = i + nextElementAfterSpace(buffer + i); if (i == 0) return;
if (buffer[i] == '"')
{
int offset = subStringLength(buffer + i, '"');
if (buffer[offset + i] != '"')
return;
Inclusion(buffer + i, offset);
}
if (buffer[i] == '<')
{
int offset = subStringLength(buffer + i, '>');
if (buffer[offset + i] != '>')
return;
Inclusion(buffer + i + 1, offset - 1);
}
}
}
else // comment whitespace removal and macro expansions
{
char write[BUFFERSIZE + 1];
int wrOffset = 0;
int split = nextElementAfterSpace(buffer), offset = 0, temp2;
unordered_map<string, string>::iterator itr;
do
{
temp2 = wordLength(buffer + split);
//if element is not a word then insert that single element
if (temp2 == 0)
{
if (buffer[split] == ' ')
{
split++;
continue;
}
if ((buffer[split] == '/' && buffer[split + 1] == '/') || buffer[split] == '\n' || buffer[split] == '\0')
{
write[wrOffset] = buffer[len - 1];
break;
}
write[wrOffset] = buffer[split];
wrOffset++;
split++;
}
else
{
split = split + temp2;
//write parsed element or word in char * key
string skey(buffer + offset, buffer + split);
//find that key in table
itr = table.find(skey);
if (itr == table.end())
{
//if not found write that word as it is in char write[]
for (int loop = offset; loop < split; loop++)
{
write[wrOffset] = buffer[loop];
wrOffset++;
}
}
else
{
//else substitute the macro
int l = (itr->second).length();
for (int loop = 0; loop < l; loop++)
{
write[wrOffset] = itr->second[loop];
wrOffset++;
}
}
}
if (buffer[split] == ' ')
{
write[wrOffset] = buffer[split];
wrOffset++;
split++;
}
if ((buffer[split] == '/' && buffer[split + 1] == '/') || buffer[split] == '\n' || buffer[split] == '\0')
{
write[wrOffset] = buffer[len - 1];
break;
}
split = split + nextElementAfterSpace(buffer + split);
offset = split;
} while (split <= len);
write[wrOffset] = '\n';
wrOffset++;
if (wrOffset > 1)
fwrite(write, sizeof(char), wrOffset, p);
}
}
| true |
ca73cc8e822f96ad060311fd2c08b2772529ca7f | C++ | RBalmoreA27/robot-car-arduino | /examples/Automata/AutomataCarro.ino | UTF-8 | 994 | 2.53125 | 3 | [
"MIT"
] | permissive | #include<robot-car-arduino.h>
Carro carrito;
int detener=3;
int giro=-90;
void setup(){
//configuraciones del carro
carrito.potenciaMAX=150; //velocidad del carro
}
void loop(){
//si la estructura del sensor central es mayor a los cms para detener pues avanzamos
if(carrito.UltraC.medirCM()>detener){
//mover carro hacia delante
carrito.mover(10,10);
}else{
//detener carro
carrito.mover(0,0);
delay(100);
//evaluar con los sensores el lado despejado
if(carrito.UltraI.medirCM()>carrito.UltraD.medirCM()){
// si tengo la apertura a la izquierda
carrito.girar(giro);
//si no tengo contadores de vuelta
//carrito.mover(-10,10);
//delay(1000);
}else{
//giro a la derecha
carrito.girar(-1*giro);
//si no tengo contadores de vuelta
//carrito.mover(10,-10);
//delay(1000);
}
}
} | true |
889d81553c354c697369e753858b8ff0ad0bd6c0 | C++ | eduardorasgado/CppZerotoAdvance2018 | /season2/pointers/dynamicArrays/main.cpp | UTF-8 | 879 | 3.875 | 4 | [] | permissive | #include <iostream>
using namespace std;
void takeGrades(int*, int&);
void showGrades(int*, int&);
int main()
{
std::cout << "[DYNAMIC ARRAYS]" << std::endl;
int N, *grades;
std::cout << "Grades quantity: ";
std::cin >> N;
// creating a dynamic array
grades = new int[N];
takeGrades(grades, N);
showGrades(grades, N);
delete[] grades;
return 0;
}
void takeGrades(int* grades, int& N)
{
// do not define de dynammic array inside
// a function, this will leads to memory leaks
// and bugs
//grades = new int[N];
for(int i = 0; i < N; ++i)
{
std::cout << "Add a grade: ";
std::cin >> grades[i];
}
}
void showGrades(int* grades, int& N)
{
std::cout << "[SHOWING ALL GRADES]\n";
for(int i =0; i < N; ++i)
{
std::cout << grades[i] << " ";
}
std::cout << "\n";
}
| true |
a8464af14656bfb5c1d3bace413a79c28723159b | C++ | mforys/bridge_mf_cpp | /test/Bid_test.cpp | UTF-8 | 782 | 3.03125 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "Bid.h"
TEST (BidTest, Basic)
{
Bid bid;
EXPECT_EQ (bid.volume(), NO_BID);
EXPECT_EQ (bid.suit(), NO_TRUMP);
}
TEST (BidTest, Basic_with_args)
{
Bid bid(ONE_B, CLUB);
EXPECT_EQ (bid.volume(), ONE_B);
EXPECT_EQ (bid.suit(), CLUB);
}
TEST (BidTest, LessThan)
{
Bid bid1(ONE_B, CLUB);
Bid bid2(TWO_B, CLUB);
EXPECT_LT(bid1, bid2);
}
TEST (BidTest, LessThan_same_volume)
{
Bid bid1(ONE_B, CLUB);
Bid bid2(ONE_B, DIAMOND);
EXPECT_LT(bid1, bid2);
}
TEST (BidTest, GreaterThan)
{
Bid bid1(THREE_B, CLUB);
Bid bid2(TWO_B, CLUB);
EXPECT_GT(bid1, bid2);
}
TEST (BidTest, GreaterThan_same_volume)
{
Bid bid1(THREE_B, HEART);
Bid bid2(THREE_B, CLUB);
EXPECT_GT(bid1, bid2);
}
| true |
42dd72f34ab28ac80d0410d19d89551fedea87be | C++ | lisiynos/lisiynos | /py_latex/a.cpp | UTF-8 | 1,008 | 2.84375 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <iomanip>
using namespace std;
int main() {
freopen("sqrteq.in", "r", stdin);
freopen("sqrteq.out", "w", stdout);
long double a, b, c, D, x1, x2;
cin >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
if (abs(a) < 0.0000001) {
if (abs(b) < 0.0000001) {
if (abs(c) < 0.0000001) {
cout << -1;
} else {
cout << 0;
}
} else {
x1 = -c / b;
cout << 1 << ' ' << setiosflags(ios::fixed) << setprecision(15) << x1;
}
} else {
D = b * b - 4 * a * c;
if (abs(D) < 0.0000001) {
cout << 1 << ' ' << setiosflags(ios::fixed) << setprecision(15) << -b / (2 * a);
} else {
if (D < 0) {
cout << 0;
} else {
D = sqrt(D);
x1 = (-b + D) / (2 * a);
x2 = (-b - D) / (2 * a);
cout << 2 << ' ' << setiosflags(ios::fixed) << setprecision(15) << min(x1, x2) << ' ' << max(x1, x2);
}
}
}
} | true |
da387bc77daba5c5939c3414a54744eea9ccdaa3 | C++ | JinnyJingLuo/Expanse | /Paradis_Hydrogen/ParadisJHU06012020/ParadisJHU06012020/paradis/Meminfo.cpp | UTF-8 | 2,493 | 2.703125 | 3 | [] | no_license | /*-------------------------------------------------------------------------
*
* Function: Meminfo
* Description: Attempts to obtain an estimate of the memory
* footprint of the current process and returns the
* value to the caller.
*
* NOTE: The function first attempts to use the
* getrusage() call to obtain the processes maximum
* resident set size. If this fails, or returns a
* rss of 0, it attempts to determine the current
* heap size and return that as an estimate.
* Args:
* wss pointer to integer value in which to return to the
* caller the estimated maximum memory use in units
* of kilobytes.
*
*-----------------------------------------------------------------------*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "Home.h"
#ifdef PARALLEL
#include <mpi.h>
#endif
void Meminfo(int *wss) {
struct rusage psinfo;
void *curr_heap_ptr;
static void *init_heap_ptr = (void *)NULL;
static int first_time = 1;
/*
* First try to get the maximum resident set size.
*/
if (getrusage(RUSAGE_SELF, &psinfo) >= 0)
*wss = (int)psinfo.ru_maxrss;
else
*wss = 0;
#ifdef _BGL
/*
* For now, BGL is not returning an error from getrusage(),
* but the data is garbage, so force *wss to zero which will
* force an estimate based on heap size. Once BGL returns
* valid data from getrusage(), this can be removed.
*/
*wss = 0;
#endif
/*
* If we don't have a valid value yet, get the heap size. (The
* first time into this code, the initialheap pointer is set and
* preserved for later calls. Subsequent calls then calculate
* the difference between the initial heap pointer and the current
* pointer to determine the heap size.
*/
if (*wss == 0) {
curr_heap_ptr = sbrk(0);
init_heap_ptr =
(void *)((long)init_heap_ptr + (first_time * (long)curr_heap_ptr));
first_time = 0;
*wss = ((long)curr_heap_ptr - (long)init_heap_ptr) / 1000l;
}
return;
}
void _CheckMemUsage(Home_t *home, char *msg) {
int localMemMax, globalMemMax = 0;
Meminfo(&localMemMax);
#ifdef PARALLEL
MPI_Allreduce(&localMemMax, &globalMemMax, 1, MPI_INT, MPI_MAX,
MPI_COMM_WORLD);
#else
globalMemMax = localMemMax;
#endif
if (globalMemMax == localMemMax) {
printf(" *** %s: est. max memory usage is %dk bytes on task %d\n", msg,
globalMemMax, home->myDomain);
fflush(NULL);
}
}
| true |
47fb63590535f08461d9f6a8b8f850ca897edcd9 | C++ | zjkang/algorithm | /leetcode/538. Convert BST to Greater Tree.cpp | UTF-8 | 1,239 | 3.609375 | 4 | [] | no_license | /*
Author: Zhengjian Kang
Email: zhengjian.kang@nyu.edu
Problem: Convert BST to Greater Tree
Source: https://leetcode.com/problems/convert-bst-to-greater-tree/#/description
Difficulty: Medium
Company: Amazon
Tags: {Tree}
Notes:
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void convertBSTHelper(TreeNode* root, int& sum) {
if (!root) return;
convertBSTHelper(root->right, sum);
root->val += sum;
sum = root->val;
convertBSTHelper(root->left, sum);
}
TreeNode* convertBST(TreeNode* root) {
int sum = 0;
convertBSTHelper(root, sum);
return root;
}
}; | true |
d80ac168cea6f06b9b1e784af14ee21bd28b6b1a | C++ | jockm/smallnet | /env.h | UTF-8 | 1,748 | 2.6875 | 3 | [] | no_license | #pragma once
#include <string>
#include <list>
#include <map>
#include "ast.h"
#include "decl.h"
class EnvironmentVar
{
public:
std::string id;
std::string type;
FieldInfo *fi;
int temp_reg;
EnvironmentVar() { }
EnvironmentVar(const EnvironmentVar& v) : id(v.id), type(v.type), fi(v.fi), temp_reg(v.temp_reg) { }
EnvironmentVar(std::string id, std::string type) : id(id), type(type), fi(NULL), temp_reg(0) { }
EnvironmentVar(std::string id, FieldInfo *fi) : id(id), fi(fi), temp_reg(0) { }
EnvironmentVar(std::string id, int temp_reg) : id(id), fi(NULL), temp_reg(temp_reg) { }
};
typedef std::list<std::map<std::string, EnvironmentVar> > EnvironmentVarStack;
class Environment {
private:
std::list<std::string> ns_stack;
std::list<AST::Class*> cs_stack;
std::list<AST::MethodFeature*> mf_stack;
EnvironmentVarStack vars_stack;
public:
Declarations *decl;
int errors;
Environment(Declarations *decl) : decl(decl), errors(0) { }
void push_namespace(AST::Namespace *ns);
void pop_namespace();
void push_class(AST::Class *cs);
void pop_class();
void push_method(AST::MethodFeature *mf);
void pop_method();
std::string get_current_ns();
AST::Class *get_current_cs() { return cs_stack.back(); }
AST::MethodFeature *get_current_mf() { return mf_stack.back(); }
void push_vars();
void pop_vars();
void add_var(const EnvironmentVar &v);
EnvironmentVar *find_var(std::string id);
AST::MethodFeature *find_method(std::string id);
};
| true |
b255ebf816bbfb60f867a7385a59251562be1d4a | C++ | alex031029/LeetCode | /Move Zeroes/answer.cpp | UTF-8 | 615 | 3.296875 | 3 | [] | no_license | // in this solution the number of operations is same as nums.size()
// where an operation is defined as the number of writing in nums
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int p = 0;
int i = 0;
for(i=0;i<nums.size();i++)
{
if(nums[i]==0)
{
continue;
}
else if(i!=p)
{
nums[p] = nums[i];
p++;
}
else
p++;
}
for(i = p;i<nums.size();i++)
{
nums[i] = 0;
}
}
};
| true |
887dc8ed1904bce4fe5cd90e77d7dda38213f736 | C++ | Idianale/au_uav_pkg | /src/au_uav_ros/src/a_star/DiscretizedPlane.h | UTF-8 | 19,874 | 2.78125 | 3 | [] | no_license | //
// DiscretizedPlane.h
// Header file for the plane class for use in the Auburn REU program 2011
// By Thomas Crescenzi, with additions from Tyler Young
#ifndef PLANE
#define PLANE
#include <iostream>
#include <math.h>
#include <vector>
#include "Position.h"
#include "map_tools.h"
#include "au_uav_ros/standardFuncs.h"
#ifndef RADIAN_CONSTANTS
#define RADIAN_CONSTANTS
const double MY_PI = 4.0*atan(1.0);// pi
const double TWO_MY_PI = 2.0*MY_PI;
const double MY_RADIANS_TO_DEGREES = 180.0/MY_PI;//Conversion factor from Radians to Degrees
const double MY_DEGREES_TO_RADIANS = MY_PI/180.0;//Conversion factor from Degrees to Radians
#endif
class DiscretizedPlane
{
private:
// The plane's ID number; should be unique
int id;
// The plane's current location, as might be updated through a telemetry callback
Position current;
// The plane's "next" destination; this might be a collision avoidance waypoint,
// or it might be identical to the final destination
Position destination;
// The plane's true goal; NOT a collision avoidance waypoint
Position finalDestination;
// The plane's previous location; used to calculate its current baring
Position lastPosition;
// The bearing from the plane's current location to its FINAL destination
// (its goal), in degrees
double bearingToDest;
// The bearing from the plane's previous location to its current one, in degrees
double bearing;
// The plane's speed, in whatever units you want to use (we aren't using this)
double speed;
/**
* Updates the plane's current bearing and its bearing to its goal.
* Current bearing is calculated as the bearing from the previous location to
* the current one, so you should only call this function when you update the
* current location.
*/
void calculateBearings();
// Indicates whether your current position is a "virtual" position; see the
// virtual_update_current() for more
bool current_is_virtual;
// additions for full path planning A*
// list of waypoints (including collision avoidance), all the way to the end of mission
vector<Position> allWaypoints;
// index represents what time step in the entire simulation the plane is at that point
vector<Position> locationsThroughTime;
//avoidance waypoint paths for the plane
std::vector<map_tools::waypointPath> avoidancePaths;
vector<Position> generateCombinedWaypoints(vector<int> &realWaypoints);
public:
// Additions for full path planning A*
void setAllWaypoints(vector<Position> allWaypointsIn);
vector<Position> getAllWaypoints();
void addAvoidancePath(map_tools::waypointPath wayPath);
vector<map_tools::waypointPath> getAvoidancePaths();
void setLocationsThroughTime(vector<Position> locs);
vector<Position> * getLocationsThroughTime();
void moveThroughTime(double bearingAtStart, bool isFirstPositionWaypoint);
/**
* Update a plane's current position without affecting its goal. This will
* automatically update the plane's bearing
*
* TODO: Take positions as pointers rather than memory-heavy objects
* @param current The plane's location, as might be obtained through a telemetry
* update
*/
void update_current( Position current );
/**
* Update a plane's waypoint on its way to the goal. This will not affect the
* plane's bearing.
*
* TODO: Take positions as pointers rather than memory-heavy objects
* @param next The plane's intermediate waypoint, possibly a collision avoidance
* waypoint
*/
void update_intermediate_wp( Position next );
/**
* It's probably a bad idea to use this function. It changes what is stored as the
* plane's current location without affecting the plane's bearing or bearing to
* destination. This might be useful if you wanted other aircraft to "see" this
* plane as being somewhere else.
*
* TODO: Take positions as pointers rather than memory-heavy objects
*
* Note that this DOES set the Boolean flag current_is_virtual so that you can
* always tell whether a plane is ACTUALLY where it says it is.
* @param virtual_current The position to store as
*/
void virtual_update_current( Position virtual_current );
/**
* Updates a plane's current location, its given intermediate waypoint, and its
* speed. The plane will automatically calculate its bearing as the angle between
* its previous, real (i.e., non-virtual) position and the new current location.
*
* TODO: Take positions as pointers rather than memory-heavy objects
*
* @param current The plane's current location, as might be obtained through a
* telemetry update
* @param destination The plane's commanded "next" location; might be the same
* as its final goal, or it might be an intermediate waypoint
* for collision avoidance
* @param speed The plane's speed (you could use ground speed, indicated airspeed,
* or true air speed... we don't actually use it for anything!)
*/
void update(Position current, Position destination, double speed);
/**
* Sets the plane's final destination (i.e., its goal) to a given
* latitude-longitude
*
* TODO: Swap lat and lon parameter order for the sake of consistency!
* @param lon The longitude coordinate of the goal
* @param lat The latitude coordinate of the goal
*/
void setFinalDestination(double lon, double lat);
/**
* Sets the plane's final destination (i.e., its goal) to a given (x, y) in your
* grid space.
* @param x The x coordinate of the goal
* @param y The y coordinate of the goal
*/
void setFinalDestination(int x, int y);
/**
* Sets the plane's next destination (i.e., its intermediate waypoint, such as
* a collision avoidance waypoint) to a given latitude-longitude
*
* TODO: Swap lat and lon parameter order for the sake of consistency!
* @param lon The longitude coordinate of the "next" location
* @param lat The latitude coordinate of the "next" location
*/
void setDestination(double lon, double lat);
/**
* Sets the plane's next destination (i.e., its intermediate waypoint, such as
* a collision avoidance waypoint) to a given (x, y) in your grid space.
* @param x The x coordinate of the "next" location
* @param y The y coordinate of the "next" location
*/
void setDestination(int x, int y);
/**
* @return the plane's current bearing, calculated as the bearing from its previous
* location to its current location, with any intervening "virtual"
* position updates ignored
*/
double getBearing() const;
double setBearing(double bearingIn);
/**
* @return a discretized version of the current bearing--this is N, NE, E, &c.
*/
map_tools::bearing_t get_named_bearing() const;
/**
* @return the bearing from the plane's current location to its FINAL destination
* (i.e., its goal)
*/
double getBearingToDest() const;
/**
* @return a discretized version of the bearing to the destination--this is N, NE, E, &c.
*/
map_tools::bearing_t get_named_bearing_to_dest() const;
/**
* @return the plane's stored speed. At the moment, this isn't used for anything.
*/
double getSpeed();
/**
* @return the plane's ID number--if you're using this right, this number will be
* unique in your airspace
*/
int getId();
/**
* @return TRUE if this plane was not created with the default, dummy constructor;
* FALSE otherwise
*/
bool is_initialized();
/**
* TODO: Return a pointer instead of the whole, memory-heavy object
*
* @return The Position object representing plane's NEXT location (may be an
* intermediate, collision-avoidance waypoint or may be its final goal)
*/
Position getDestination();
/**
* TODO: Return a pointer instead of the whole, memory-heavy object
*
* @return The Position object representing plane's final location (its goal)
*/
Position getFinalDestination();
/**
* TODO: Return a pointer instead of the whole, memory-heavy object
*
* @return The Position object representing plane's current location
*/
Position getLocation();
/**
* The default constructor for a plane object. Since a plane needs so much
* information to actually be useful, you should probably never use this.
* @param id The plane's unique ID, which defaults to -100
*/
DiscretizedPlane(int id=-100);
/**
* The only constructor you should probably use.
*
* TODO: Take positions as pointers rather than memory-heavy objects
* @param newid The unique ID number of the plane
* @param initial The Position object representing the plane's current location
* @param goal The Position object representing the plane's final goal
*/
DiscretizedPlane(int newid, Position initial, Position goal );
};
// TODO definitely comment this to make it more understandable
vector<Position> DiscretizedPlane::generateCombinedWaypoints(vector<int> &realWaypoints) {
int avoidanceIndex = 0;
vector<Position> combined;
Position temp = current;
temp.setIsWaypoint(true);
int tracker = 0;
for (int i = 0; i < allWaypoints.size(); i++) {
// i-1 is for if the first avoidance path is from the plane's start position to the first waypoint
if (avoidanceIndex < avoidancePaths.size() && i-1 == avoidancePaths[avoidanceIndex].startWaypointIndex) {
for (int j = 0; j < avoidancePaths[avoidanceIndex].pathWaypoints.size(); j++) {
double latTemp = avoidancePaths[avoidanceIndex].pathWaypoints[j].latitude;
double lonTemp = avoidancePaths[avoidanceIndex].pathWaypoints[j].longitude;
temp.setLatLon(latTemp, lonTemp);
combined.push_back(temp);
tracker++;
}
avoidanceIndex++;
}
// add next waypoint
temp.setLatLon(allWaypoints[i].getLat(), allWaypoints[i].getLon());
combined.push_back(temp);
realWaypoints.push_back(tracker);
tracker++;
}
return combined;
}
#define maxTurningAngle 45.0
// @param bearingAtStart is assumed to be zero at start of simulation. This parameter can also be used
// to move the plane through time from any point in the simulation onward though
void DiscretizedPlane::moveThroughTime(double bearingAtStart, bool isFirstPositionWaypoint) {
locationsThroughTime.clear();
int waypointIndex = 0;
current.setIsWaypoint(isFirstPositionWaypoint);
locationsThroughTime.push_back(current);
double actualBearing = bearingAtStart;
Position currentPosition = current;
vector<int> realWaypointIndices;
int realIndex = 0;
vector<Position> combined = generateCombinedWaypoints(realWaypointIndices);
while (waypointIndex < combined.size()) {
double lat1 = currentPosition.getLat() * MY_DEGREES_TO_RADIANS;
double long1 = currentPosition.getLon() * MY_DEGREES_TO_RADIANS;
double lat2 = combined[waypointIndex].getLat() * MY_DEGREES_TO_RADIANS;
double long2 = combined[waypointIndex].getLon() * MY_DEGREES_TO_RADIANS;
double deltaLat = lat2 - lat1;
double deltaLong = long2 - long1;
double y = sin(deltaLong)*cos(lat2);
double x = cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(deltaLong);
double bearingToGoal = atan2(y, x)*MY_RADIANS_TO_DEGREES;
//calculate the real bearing based on our maximum angle change
//first create a temporary bearing that is the same as bearing but at a different numerical value
double tempBearing = -1000;
if(bearingToGoal < 0)
{
tempBearing = bearingToGoal + 360;
}
else
{
tempBearing = bearingToGoal - 360;
}
double diff1 = fabs(actualBearing - bearingToGoal);
double diff2 = fabs(actualBearing - tempBearing);
//check for easy to calculate values first
if(diff1 < maxTurningAngle || diff2 < maxTurningAngle)
{
//the difference is less than our maximum angle, set it to the bearing
actualBearing = bearingToGoal;
}
else
{
//we have a larger difference than we can turn, so turn our maximum
double mod;
if(diff1 < diff2)
{
if(bearingToGoal > actualBearing) mod = maxTurningAngle;
else mod = 0 - maxTurningAngle;
}
else
{
if(tempBearing > actualBearing) mod = maxTurningAngle;
else mod = 0 - maxTurningAngle;
}
//add our mod, either +22.5 or -22.5
actualBearing = actualBearing + mod;
//tweak the value to keep it between -180 and 180
if(actualBearing > 180) actualBearing = actualBearing - 360;
if(actualBearing <= -180) actualBearing = actualBearing + 360;
}
//1) Estimate new latitude using basic trig and this equation
double currentLatitude = lat1*MY_RADIANS_TO_DEGREES + (11.176*cos(actualBearing*MY_DEGREES_TO_RADIANS))*(1.0/111200.0);
//2) Use the law of haversines to find the new longitude
//double temp = pow(sin((MPS_SPEED/EARTH_RADIUS)/2.0), 2);
double temp = 7.69303281*pow(10, -13); //always the same, see above calculation
temp = temp - pow(sin((currentLatitude*MY_DEGREES_TO_RADIANS - lat1)/2.0), 2);
temp = temp / (sin(M_PI/2.0 - lat1)*sin((M_PI/2.0)-currentLatitude*MY_DEGREES_TO_RADIANS));
temp = 2.0 * MY_RADIANS_TO_DEGREES * asin(sqrt(temp));
double currentLongitude = currentPosition.getLon();
//depending on bearing, we should be either gaining or losing longitude
if(actualBearing > 0)
{
currentLongitude += temp;
}
else
{
currentLongitude -= temp;
}
currentPosition.setLatLon(currentLatitude, currentLongitude);
currentPosition.setBearing(actualBearing);
currentPosition.setIsWaypoint(false);
// Do haversine calculations because that's what simulation does to caculate
// if the waypoint has been reached
lat1 = currentLatitude*MY_DEGREES_TO_RADIANS;
//lat2 up above still applicable
long1 = currentLongitude*MY_DEGREES_TO_RADIANS;
//long2 above still applicable
deltaLat = lat2 - lat1;
deltaLong = long2 - long1;
double a = pow(sin(deltaLat / 2.0), 2);
a = a + cos(lat1)*cos(lat2)*pow(sin(deltaLong/2.0), 2);
a = 2.0 * asin(sqrt(a));
if((a * 6371000) < 30) {
if (waypointIndex == realWaypointIndices[realIndex]) {
currentPosition.setIsWaypoint(true);
realIndex++;
}
waypointIndex++;
}
locationsThroughTime.push_back(currentPosition);
}
}
void DiscretizedPlane::addAvoidancePath(map_tools::waypointPath wayPath) {
avoidancePaths.push_back(wayPath);
}
vector<map_tools::waypointPath> DiscretizedPlane::getAvoidancePaths() {
return avoidancePaths;
}
void DiscretizedPlane::setLocationsThroughTime(vector<Position> locs) {
locationsThroughTime = locs;
}
vector<Position> * DiscretizedPlane::getLocationsThroughTime() {
return &locationsThroughTime;
}
void DiscretizedPlane::setAllWaypoints(vector<Position> allWaypointsIn) {
allWaypoints = allWaypointsIn;
}
vector<Position> DiscretizedPlane::getAllWaypoints() {
return allWaypoints;
}
void DiscretizedPlane::update_current( Position newcurrent )
{
// Only if the "current" location came from a telemetry update should it affect
// our last position
if( !current_is_virtual )
lastPosition.setLatLon( current.getLat(), current.getLon() );
current = newcurrent; //.setLatLon( newcurrent.getLat(), newcurrent.getLon() );
current_is_virtual = false;
// Find both the plane's current bearing and its bearing to its destination,
// saving them to the proper variables
calculateBearings();
}
void DiscretizedPlane::virtual_update_current( Position virtual_current )
{
current = virtual_current;
current_is_virtual = true;
// Note: We do not change bearings, since this is only a "virtual" update
}
void DiscretizedPlane::update_intermediate_wp( Position next )
{
destination = next;
// NOTE: Changing the intermediate waypoint does not change our bearing
}
void DiscretizedPlane::update(Position newcurrent, Position newdestination, double newspeed)
{
if( !current_is_virtual )
lastPosition.setLatLon( current.getLat(), current.getLon() );
current = newcurrent; //.setLatLon( newcurrent.getLat(), newcurrent.getLon() );
current_is_virtual = false;
destination = newdestination;//.setLatLon( newdestination.getLat(), newdestination.getLon() );
speed=newspeed;
// finds both the plane's current bearing and its bearing to its destination,
// saving them to the proper variables
calculateBearings();
}
void DiscretizedPlane::setFinalDestination(double lon, double lat)
{
finalDestination.setLatLon(lat, lon);
calculateBearings();
}
void DiscretizedPlane::setDestination(double lon, double lat)
{
destination.setLatLon( lat, lon);
}
void DiscretizedPlane::setFinalDestination(int x, int y)
{
finalDestination.setXY(x, y);
calculateBearings();
}
Position DiscretizedPlane::getFinalDestination()
{
return finalDestination;
}
void DiscretizedPlane::setDestination(int x, int y)
{
destination.setXY(x, y);
}
double DiscretizedPlane::setBearing(double bearingIn) {
bearing = bearingIn;
}
double DiscretizedPlane::getBearing() const
{
return bearing;
}
map_tools::bearing_t DiscretizedPlane::get_named_bearing() const
{
return map_tools::name_bearing( bearing );
}
double DiscretizedPlane::getBearingToDest() const
{
return bearingToDest;
}
map_tools::bearing_t DiscretizedPlane::get_named_bearing_to_dest() const
{
return map_tools::name_bearing( bearingToDest );
}
void DiscretizedPlane::calculateBearings()
{
// NOTE: the map_tools::calculateBearing() fn takes lat and long in DEGREES
double lat1 = current.getLat();
double lon1 = current.getLon();
// If our current location isn't the same as our previous location . . .
if( !(current==lastPosition) )
{
//uses the same method that the simulator uses to find the planes bearing
bearing = map_tools::calculateBearing( lastPosition.getLat(),
lastPosition.getLon(),
lat1, lon1 );
}
bearingToDest = map_tools::calculateBearing( lat1, lon1,
finalDestination.getLat(),
finalDestination.getLon() );
}
double DiscretizedPlane::getSpeed()
{
return speed;
}
int DiscretizedPlane::getId()
{
return id;
}
bool DiscretizedPlane::is_initialized()
{
if( id == -1 )
return false;
return true;
}
Position DiscretizedPlane::getLocation()
{
return current;
}
Position DiscretizedPlane::getDestination()
{
return destination;
}
DiscretizedPlane::DiscretizedPlane(int newid)
{
id=newid;
}
DiscretizedPlane::DiscretizedPlane(int newid, Position initial, Position goal )
{
id=newid;
current = Position(initial);
destination = Position(goal);
finalDestination = Position(goal);
lastPosition = Position(initial);
bearing = 0;
current_is_virtual = false;
calculateBearings();
}
#endif
| true |
8cac0553ebc168db73fcd94fe9ecc24ba784c391 | C++ | markitus18/Development | /GUI/Motor2D/j1Console.h | UTF-8 | 4,577 | 2.609375 | 3 | [] | no_license | #ifndef __j1CONSOLE_H__
#define __j1CONSOLE_H__
#include "j1Module.h"
#define LINE_SPACING 16
enum CVarTypes
{
c_float = 0,
c_int,
c_string,
c_bool,
};
struct Command
{
public:
Command(){}
Command(char* str, char* dsc, uint n, char* abr = NULL, char* newTag = "Miscellaneous"){ command = str; desc = dsc, nArgs = n; abreviation = abr; tag = newTag; }
public:
p2SString desc;
p2SString command;
p2SString abreviation;
p2SString tag;
uint nArgs;
virtual void function(const p2DynArray<p2SString>* arg);
};
class CVar
{
public:
CVar(const char* newName, float* newRference, bool newSerialize = false);
CVar(const char* newName, int* newReference, bool newSerialize = false);
CVar(const char* newName, char* newReference, bool newSerialize = false);
CVar(const char* newName, bool* newReference, bool newSerialize = false);
public:
bool serialize;
private:
p2SString desc;
p2SString name;
p2SString tag;
CVarTypes type;
Command* command = NULL;
j1Module* listener = NULL;
union {
float* floatRef;
int* intRef;
char* stringRef;
bool* boolRef;
} reference;
union {
float floatVar;
int intVar;
char* stringVar;
bool boolVar;
} value;
public:
void LinkCommand(Command* toLink);
void Set(float newValue);
void Set(int newValue);
void Set(char* newValue);
void Set(bool newValue);
void Set(p2SString* data);
void SetListener(j1Module* module);
CVarTypes GetType();
p2SString GetName();
const j1Module* GetListener() const;
void Read(void* ret, CVarTypes expectedData);
bool Read(float* output);
bool Read(int* output);
bool Read(char* output);
bool Read(bool* output);
void* ForceRead();
void Display();
};
class UIInputText;
class UIRect;
class UILabel;
class UIScrollBar;
class j1Console : public j1Module
{
public:
j1Console(bool);
// Destructor
virtual ~j1Console();
// Called before render is available
bool Awake(pugi::xml_node&);
// Called before the first frame
bool Start();
// Called every frame
bool Update(float dt);
bool PostUpdate(float dt);
// Called before quitting
bool CleanUp();
void OnGUI(UI_Event _event, UIElement* _element);
void AddCommand(Command*);
uint AddCVar(const char* _name, float* reference, j1Module* listener = NULL, bool serialize = false);
uint AddCVar(const char* _name, int* reference, j1Module* listener = NULL, bool serialize = false);
uint AddCVar(const char* _name, char* reference, j1Module* listener = NULL, bool serialize = false);
uint AddCVar(const char* _name, bool* reference, j1Module* listener = NULL, bool serialize = false);
void GetNewInput(char* src);
void Output(char* str);
void Open();
void Close();
void Clear();
void DisplayCommands(p2SString str) const;
void DisplayAllCommands() const;
void DisplayTags() const;
bool isActive() const;
bool SaveCVars(pugi::xml_node& data) const;
bool LoadCVars(pugi::xml_node&);
private:
void CutString(char* src, p2DynArray<p2SString>* dst);
Command* FindCommand(const char* str, uint nArgs) const;
CVar* FindCVar(const char* str);
void SetCVar(const char* value);
private:
p2List<Command*> commandList;
p2List<CVar*> CVarList;
p2DynArray<p2SString> tags;
UIInputText* inputText;
UIRect* consoleRect;
UIRect* inputRect;
UILabel* console_defLabel;
UIScrollBar* scrollbar;
UIRect* scrollbar_rect;
UIRect* scrollbar_thumb;
p2DynArray<UILabel*> output;
bool active = false;
bool dragText = false;
int textStart = 0;
int outputHeight = 0;
bool closeGame = false;
#pragma region Commands
struct C_commandList : public Command
{
C_commandList() : Command("list", "Display command list", 1, NULL, "Console"){}
void function(const p2DynArray<p2SString>* arg);
};
C_commandList c_commandList;
struct C_tagList : public Command
{
C_tagList() : Command("tags", "Display tag list", 0, NULL, "Console"){}
void function(const p2DynArray<p2SString>* arg);
};
C_tagList c_tagList;
struct C_closeConsole : public Command
{
C_closeConsole() : Command("close", "Close console", 0, NULL, "Console"){}
void function(const p2DynArray<p2SString>* arg);
};
C_closeConsole c_closeConsole;
struct C_clearConsole : public Command
{
C_clearConsole() : Command("cls", "Clear console output", 0, NULL, "Console"){}
void function(const p2DynArray<p2SString>* arg);
};
C_clearConsole c_clearConsole;
struct C_Quit : public Command
{
C_Quit() : Command("quit", "Quit the application", 0, NULL, "Console"){}
void function(const p2DynArray<p2SString>* arg);
};
C_Quit c_Quit;
#pragma endregion
};
#endif // __j1CONSOLE_H__ | true |
4af2230411071c417829e1e6f0e4f6146088babd | C++ | AzizulTareq/virtual-judge | /HolidayOfEquality.cpp | UTF-8 | 336 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n];
int sum = 0;
for(int i=0; i<(sizeof(arr)/sizeof(*arr)); i++){
cin>>arr[i];
}
sort(arr,arr+n);
for(int i=0;i<n;i++){
sum+=arr[i];
}
cout<<(arr[n-1]*n-sum)<<endl;
}
| true |
272d988e9e32830a59fb6a7847a55b3aae5a9019 | C++ | professor9999/DSA | /Graphs/Single_Source_Shortest_Path_Using_BFS.cpp | UTF-8 | 1,508 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <queue>
#include <list>
using namespace std;
template <typename T>
class Graph
{
// Considering the graph to be unweighted and bidirectional
map<T, list<T>> l;
public:
void AddEdge(int x, int y)
{
l[x].push_back(y);
l[y].push_back(x);
}
void bfs(T source)
{
map<T, int> distance;
queue<T> q;
// All other nodes will have int_max
for (auto node_pair : l) // node_pair stores node number and its list
{
T node = node_pair.first;
distance[node] = INT_MAX;
}
// Except source node all other nodes have infinite distance
q.push(source);
distance[source] = 0;
while (!q.empty())
{
T node = q.front();
q.pop();
for (auto nbr : l[node])
{
if (distance[nbr] == INT_MAX)
{
q.push(nbr);
distance[nbr] = distance[node] + 1;
}
}
}
// Print the distance to every node
for (auto node_pair : l)
{
T node = node_pair.first;
int d = distance[node];
cout << "Node " << node << " Distance from source " << d << endl;
}
}
};
int main()
{
Graph<int> g;
g.AddEdge(0, 1);
g.AddEdge(0, 3);
g.AddEdge(1, 2);
g.AddEdge(3, 2);
g.AddEdge(3, 4);
g.bfs(0);
return 0;
} | true |
07b0a6dbadba3d6a646e3f0c9943f2c72d616542 | C++ | acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-Fortress117 | /src/homework/tic_tac_toe/main.cpp | UTF-8 | 1,189 | 3.296875 | 3 | [
"MIT"
] | permissive | #include "tic_tac_toe.h"
#include <iostream>
#include <string>
#include "tic_tac_toe_manager.h"
#include "tic_tac_toe_3.h"
#include "tic_tac_toe_4.h"
using std::cout;
using std::cin;
using std::string;
using std::vector;
using std::ostream;
int main()
{
unique_ptr<TicTacToeManager> manager = std::make_unique<TicTacToeManager>();
int game_type;
string menu_choice = "y";
while (menu_choice == "y" || menu_choice == "Y")
{
cout << "Welcome to tic tac toe! \n";
cout << " Play win by 3 or 4?: ";
cin >> game_type;
unique_ptr<TicTacToe> game;
if (game_type == 3)
{
game = std::make_unique<TicTacToe3>();
}
else
{
game = std::make_unique < TicTacToe4>();
}
cout << "\n";
string player;
cout << "Player 1 please enter capital 'X' or 'O' : ";
cin >> player;
game ->start_game(player);
while (game->game_over() == false)
{
cin >> *game;
cout << *game;
}
cout << "Winner: ";
cout << game->get_winner()<<"\n";
manager -> save_game(game);
cout << "Do you want to play again? press 'y' to repeat";
cin >> menu_choice;
}
cout << "History: \n";
cout << *manager;
return 0;
} | true |
bb774d46d7a10e30049d50d4f75071c38513d467 | C++ | rundun159/th1231 | /Problem_Solving/14888.cpp | UTF-8 | 2,343 | 2.78125 | 3 | [] | no_license | //50�� ��.
//index�� ��������.
//index �Ҽ��� �� ����س��� ���� ����.
//dfs ������ ��츦 �� �����س���
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> op_given;
vector<int> num_given;
int n;
int cal_opt(const vector<int> &op_v);
void doDFS(int opIdx, int startIdx, int cnt, vector<int>& op_v, vector<int>& op_cnt);
long long int max_ret, min_ret;
void main()
{
freopen("input.txt", "r", stdin);
cin >> n;
num_given = vector<int>(n);
op_given = vector<int>(4);
for (int i = 0; i < n; i++)
cin >> num_given[i];
for (int i = 0; i < 4; i++)
cin >> op_given[i];
max_ret = -9999999999;
min_ret = 9999999999;
vector<int> op_v = vector<int>(n - 1, -1);
vector<int> op_cnt = vector<int>(4, 0);
doDFS(0, 0, 0, op_v, op_cnt);
cout << max_ret << endl;
cout << min_ret << endl;
}
int cal_opt(const vector<int>& op_v)
{
long long int ret = 0;
if (op_v[0] == 0)
ret = num_given[0] + num_given[1];
else if (op_v[0] == 1)
ret = num_given[0] - num_given[1];
else if (op_v[0] == 2)
ret = num_given[0] * num_given[1];
else if (op_v[0] == 3)
ret = num_given[0] / num_given[1];
if (n == 2)
return ret;
for (int i = 1; i < n - 1; i++)
{
if (op_v[i] == 0)
ret = ret + num_given[i + 1];
else if (op_v[i] == 1)
ret = ret - num_given[i + 1];
else if (op_v[i] == 2)
ret = ret * num_given[i + 1];
else if (op_v[i] == 3)
ret = ret / num_given[i + 1];
}
return ret;
}
void doDFS(int opIdx, int startIdx, int cnt, vector<int>& op_v, vector<int>& op_cnt)
{
if (opIdx == 4)
{
int sum = 0;
for (int i = 0; i < 4; i++)
sum += op_cnt[i];
if (sum == (n - 1))
{
long long int ret = cal_opt(op_v);
if (ret > max_ret)
max_ret = ret;
if (ret < min_ret)
min_ret = ret;
return;
}
else
{
return;
}
}
if (cnt < op_given[opIdx])
{
if (startIdx >= n-1)
return;
for (int i = startIdx; i < n-1; i++)
{
if (op_v[i] == -1)
{
op_v[i] = opIdx;
op_cnt[opIdx]++;
doDFS(opIdx, i + 1, cnt + 1, op_v, op_cnt);
op_v[i] = -1;
op_cnt[opIdx]--;
}
}
}
else
{
doDFS(opIdx + 1, 0, 0, op_v, op_cnt);
}
}
| true |
768e1212964e2766e9fdcce8c16173062013d663 | C++ | FullMentalPanic/IB_client | /src/SymbolContracts.cpp | UTF-8 | 2,583 | 3.265625 | 3 | [] | no_license | #include "SymbolContracts.h"
#include <fstream>
#include <stdexcept> // std::runtime_error
#include <sstream> // std::stringstream
#include <iostream>
using namespace std;
SymbolContracts::SymbolContracts(string filename, int basetickID )
{
read_csv(filename, basetickID);
}
SymbolContracts::SymbolContracts(string filename)
{
read_csv(filename);
}
SymbolContracts::SymbolContracts()
{
total = 0;
}
SymbolContracts::~SymbolContracts()
{
contracts.clear();
tickIDs.clear();
BidSize.clear();
AskSize.clear();
BidPrice.clear();
AskPrice.clear();
LastPrice.clear();
contracts.shrink_to_fit();
tickIDs.shrink_to_fit();
BidSize.shrink_to_fit();
AskSize.shrink_to_fit();
BidPrice.shrink_to_fit();
AskPrice.shrink_to_fit();
LastPrice.shrink_to_fit();
}
void SymbolContracts::DisplayContracts(){
for (int i = 0; i < contracts.size(); i++)
cout << tickIDs[i] << ':' << contracts[i].symbol << ' '<<contracts[i].secType << ' '<<contracts[i].currency << ' '<<contracts[i].exchange << ' '<<contracts[i].primaryExchange << ' '<< endl;
}
void SymbolContracts::DisplayPrice(){
for (int i = 0; i < LastPrice.size(); i++)
cout << i << ':' << LastPrice[i] << endl;
}
void SymbolContracts::read_csv(string filename, int basetickID){
ifstream myFile(filename);
if(!myFile.is_open()) throw runtime_error("Could not open file");
string line, word;
vector<string> colnames, row;
Contract temp;
// Read the column names
if(myFile.good())
{
// Extract the first line in the file
getline(myFile, line);
// Create a stringstream from line
stringstream ss(line);
// Extract each column name
while(getline(ss, word, ',')){
colnames.push_back(word);
}
}
int count = 0;
while(getline(myFile, line))
{
// Create a stringstream of the current line
stringstream ss(line);
row.clear();
while (getline(ss, word, ',')){
row.push_back(word);
}
temp.symbol = row[0];
temp.secType = row[1];
temp.currency = row[2];
temp.exchange = row[3];
temp.primaryExchange = row[4];
contracts.push_back(temp);
tickIDs.push_back (count + basetickID);
BidSize.push_back(0);
AskSize.push_back(0);
BidPrice.push_back(0.0);
AskPrice.push_back(0.0);
LastPrice.push_back(0.0);
count++;
}
total = count;
// Close file
myFile.close();
}
| true |
60072802e6fc7d482774cf83dc8beaef94a13fc8 | C++ | maximepasquier/Diversity | /Multiples_Simulations/src/main.cpp | UTF-8 | 13,154 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include <string>
#include <mutex>
#include <chrono>
#include <random>
#include "Simulation.h"
//* Nombre de threads maximum dédiés aux simulations
#define NB_THREADS 8
std::vector<std::mutex> verrous(NB_THREADS);
void thread_function(std::string path)
{
unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
Simulation Reference(path, generator);
}
int main(int argc, char const *argv[])
{
auto start = std::chrono::steady_clock::now();
std::vector<std::thread> threads;
/*
threads.push_back(std::thread(thread_function, "./Simulations/Mutation/ImmunisationGroupe/zero"));
threads.push_back(std::thread(thread_function, "./Simulations/Mutation/ImmunisationGroupe/moins1"));
threads.push_back(std::thread(thread_function, "./Simulations/Mutation/ImmunisationGroupe/moins2"));
threads.push_back(std::thread(thread_function, "./Simulations/Mutation/ImmunisationGroupe/moins3"));
threads.push_back(std::thread(thread_function, "./Simulations/Mutation/ImmunisationGroupe/moins4"));
threads.push_back(std::thread(thread_function, "./Simulations/Mutation/ImmunisationGroupe/moins5"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite20"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite24"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite28"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite20"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite24"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite28"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite20"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite24"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite28"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite20"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite24"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite28"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite36"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite40"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale1/diversite1000"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite20"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite24"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite28"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite36"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite40"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale075/diversite1000"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite20"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite24"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite28"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite36"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite40"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/PandemiePartielle/perfect_mix/charge_virale05/diversite1000"));
// charge virale = 1
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/1mouvement/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/1mouvement/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/1mouvement/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/1mouvement/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/10mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/10mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/10mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/10mouvements/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/50mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/50mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/50mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale1/50mouvements/diversite32"));
// charge virale = 0.75
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/1mouvement/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/1mouvement/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/1mouvement/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/1mouvement/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/10mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/10mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/10mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/10mouvements/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/50mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/50mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/50mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale075/50mouvements/diversite32"));
// charge virale = 0.50
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/1mouvement/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/1mouvement/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/1mouvement/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/1mouvement/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/10mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/10mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/10mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/10mouvements/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/50mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/50mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/50mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale05/50mouvements/diversite32"));
// charge virale = 0.25
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/1mouvement/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/1mouvement/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/1mouvement/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/1mouvement/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/10mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/10mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/10mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/10mouvements/diversite32"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/50mouvements/diversite4"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/50mouvements/diversite8"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/50mouvements/diversite16"));
threads.push_back(std::thread(thread_function, "./Simulations/Diversite/1sur16/charge_virale025/50mouvements/diversite32"));
*/
for (auto &t : threads)
{
t.join();
}
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
std::cout << "Le temps total est de : " << std::chrono::duration<double, std::milli>(diff).count() << " ms" << std::endl;
return 0;
} | true |
a96bb27ef0c92556d1938c904e50481bffbbbfac | C++ | rpaschen/project2 | /PROJECT/Configuration.cpp | UTF-8 | 3,163 | 3.015625 | 3 | [] | no_license | //
// Created by raylyn on 11/20/18.
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include "Configuration.h"
// Default constructor definition
Configuration::Configuration() {
interval = 0;
count = 0;
reportFile = "report.adt";
blk_read = 0;
blk_read_s = 0;
kb_read_s = 0;
blk_write = 0;
blk_write_s = 0;
kb_write_s = 0;
}
// Constructor definition
Configuration::Configuration(std::string configFile) {
std::ifstream inFile;
inFile.open(configFile);
if (!inFile) {
std::cerr << "Error opening file, reverting to default configuration.\n\n";
inFile.close();
new (this) Configuration();
}
else {
inFile >> interval >> count >> blk_read >> blk_read_s >> kb_read_s >> blk_write >> blk_write_s >> kb_write_s;
inFile.close();
reportFile = "report.adt";
}
}
// GET function definitions
int Configuration::getInterval() {
return interval;
}
int Configuration::getCount() {
return count;
}
std::string Configuration::getReportFile() {
return reportFile;
}
int Configuration::getBlk_read() {
return blk_read;
}
int Configuration::getBlk_read_s() {
return blk_read_s;
}
int Configuration::getKb_read_s() {
return kb_read_s;
}
int Configuration::getBlk_write() {
return blk_write;
}
int Configuration::getBlk_write_s() {
return blk_write_s;
}
int Configuration::getKb_write() {
return kb_write_s;
}
// SET function definitions
void Configuration::setInterval(int _interval) {
interval = _interval;
}
void Configuration::setCount(int _count) {
count = _count;
}
void Configuration::setReportFile(std::string _reportFile) {
reportFile = _reportFile;
}
void Configuration::setBlk_read(int _blk_read) {
blk_read = _blk_read;
}
void Configuration::setBlk_read_s(int _blk_read_s) {
blk_read_s = _blk_read_s;
}
void Configuration::setKb_read_s(int _kb_read_s) {
kb_read_s = _kb_read_s;
}
void Configuration::setBlk_write(int _blk_write) {
blk_write = _blk_write;
}
void Configuration::setBlk_write_s(int _blk_write_s) {
blk_write_s = _blk_write_s;
}
void Configuration::setKb_write(int _kb_write_s) {
kb_write_s = _kb_write_s;
}
// Save config file
bool Configuration::saveConfig(std::string configFile) {
std::ofstream outFile;
outFile.open(configFile);
if (!outFile) {
return false;
}
outFile << interval << " " << count << " " << blk_read << " " << blk_read_s << " " << kb_read_s << " " << blk_write << " " << blk_write_s << " " << kb_write_s;
outFile.close();
return true;
}
void Configuration::printConf() {
std::cout << "Monitoring time = " << interval << " Seconds, Number of records = " << count << "," << std::endl;
std::cout << "print_blk_read = " << blk_read << ", print_blk_read/s = " << blk_read_s << ", print_kb_read/s = " << kb_read_s << "," << std::endl;
std::cout << "print_blk_write = " << blk_write << ", print_blk_write/s = " << blk_write_s << ", print_kb_write/s = " << kb_write_s << "," << std::endl;
std::cout << "report file name = '" << reportFile << "'\n";
}
| true |
17e08261430e23f9f8441c6c5d31fc00c0eb1a53 | C++ | Antilurker77/DragonStarArena | /DragonStarArena/ui/tacticWindow.cpp | UTF-8 | 1,753 | 2.515625 | 3 | [] | no_license | // ================================================================
//
// tacticWindow.cpp
//
// ================================================================
#include "tacticWindow.hpp"
#include "dataString.hpp"
#include "../core/assetManager.hpp"
#include "../core/settings.hpp"
#include "../entity/actor.hpp"
TacticWindow::TacticWindow() {
background.setSize(sf::Vector2f(800.f, 450.f));
background.setFillColor(sf::Color(0, 0, 0, 191));
background.setOutlineThickness(1.f);
background.setOutlineColor(sf::Color(255, 255, 255, 255));
background.setPosition(settings.ScreenWidthF / 2.f - 400.f, settings.ScreenHeightF / 2.f - 225.f);
}
void TacticWindow::Update(float secondsPerUpdate, sf::Vector2i mousePos, bool leftClick, bool rightClick, bool draggingLeft, bool scrollUp, bool scrollDown) {
sf::Vector2f mousePosF{ static_cast<float>(mousePos.x), static_cast<float>(mousePos.y) };
displayTooltip = false;
for (size_t i = 0; i < playerButtons.size(); i++) {
if (playerButtons[i].Update(secondsPerUpdate, mousePos)) {
if (leftClick) {
viewedPlayer = i;
}
}
}
}
void TacticWindow::Render(sf::RenderTarget& window) {
window.draw(background);
for (size_t i = 0; i < playerButtons.size(); i++) {
playerButtons[i].Render(window);
}
if (displayTooltip) {
tooltip.Render(window);
}
}
void TacticWindow::SetPlayerList(std::vector<ActorPtr>& list) {
players = list;
auto pos = background.getPosition();
pos.y -= 30.f;
for (size_t i = 0; i < players.size(); i++) {
playerButtons[i].SetString(players.at(i)->GetName(), 16u);
if (i > 0) {
auto buttonSize = playerButtons[i - 1].GetSize();
pos.x += 4.f + buttonSize.x + playerButtons[i].GetSize().x / 2.f;
}
playerButtons[i].SetPosition(pos);
}
} | true |
db8a7a40edd378f31457c8851ffdbbf3e76aac9e | C++ | ardamavi/Web-Satranc | /SatrancProgrami/Fil.cpp | UTF-8 | 3,530 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | // Arda Mavi - ardamavi.com
#include <iostream>
#include "Tas.h"
#include "Fil.h"
using namespace std;
Fil::Fil(takim renk, int x, int y): Tas(renk, "Fil", x, y){}
bool Fil::yolKntrl(vector<Tas*> taslar, pair <int, int> gidilecekyer){
// Capraz gider.
// Onune biri cikana kadar.
// Capraz gitme kontrol :
// X azalirsa ayni oranda y de azalir YA DA x artarken ayni oranda y de artar.
// Kendi Yerine oynayamaz :
if(this->getKonum() == gidilecekyer){
return false;
}
// Gittigi yerde tas olma :
for(int i = 0; i < taslar.size(); i++){
if(taslar[i]->getKonum() == this->getKonum()){
continue;
}
if(taslar[i]->getKonum() == gidilecekyer) {
if(taslar[i]->getTakim() == this->getTakim()){
return false;
}
}
}
// Karsisina tas cıkma:
// x Azaliyorsa : Sol ya da Sag Yukari cikiliyor
if(this->getKonum().first-gidilecekyer.first > 0) {
if (this->getKonum().second-gidilecekyer.second > 0) {
// Sol Yukari Çikiliyor.
if( ( this->getKonum().first-gidilecekyer.first != this->getKonum().second-gidilecekyer.second ) ){
return false;
}
for (int i = this->getKonum().first - 1, j = this->getKonum().second - 1; i > gidilecekyer.first; i--, j--) {
for (int k = 0; k < taslar.size(); k++) {
if(taslar[k]->getKonum() == make_pair(i,j)){
return false;
}
}
}
}else{
// Sag Yukari Çikiliyor.
// X azalirsa ayni oranda y de azalir YA DA x artarken ayni oranda y de artar.
if((gidilecekyer.first - this->getKonum().first != this->getKonum().second - gidilecekyer.second)){
return false;
}
for (int i = this->getKonum().first-1, j = this->getKonum().second+1; i > gidilecekyer.first; i--, j++) {
for (int k = 0; k < taslar.size(); k++) {
if(taslar[k]->getKonum() == make_pair(i,j)){
return false;
}
}
}
}
}else {
// x Artiyorsa : Sol ya da Sag Asagi Iniliyor
if(this->getKonum().second-gidilecekyer.second > 0){
// Sol Aşagi Iniliyor.
// X azalirsa ayni oranda y de azalir YA DA x artarken ayni oranda y de artar.
if((this->getKonum().first - gidilecekyer.first != gidilecekyer.second - this->getKonum().second)){
return false;
}
for (int i = this->getKonum().first+1, j = this->getKonum().second-1; i < gidilecekyer.first; i++, j--) {
for (int k = 0; k < taslar.size(); k++) {
if(taslar[k]->getKonum() == make_pair(i,j)){
return false;
}
}
}
}else{
// Sag Asagi Iniliyor.
if( ( this->getKonum().first-gidilecekyer.first != this->getKonum().second-gidilecekyer.second ) ){
return false;
}
for (int i = this->getKonum().first+1, j = this->getKonum().second+1; i < gidilecekyer.first; i++, j++) {
for (int k = 0; k < taslar.size(); k++) {
if(taslar[k]->getKonum() == make_pair(i,j)){
return false;
}
}
}
}
}
return true;
}
| true |
e929c0709fb2f4eb0ca9fdb9881cbf6498465298 | C++ | AlumaK/security-system-based-rules-and-Intel-SGX | /final/SecureFunctions/SecureApplication/SecureApplication.cpp | UTF-8 | 2,970 | 2.546875 | 3 | [] | no_license | // SecureApplication.cpp : Defines the entry point for the console application.
#pragma check_stack(off)
#include "stdafx.h"
#include "sgx_urts.h"
#include "SecureFunctions_u.h"
#include <tchar.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define ENCLAVE_FILE _T("SecureFunctions.signed.dll")
using namespace std;
/* OCall functions */
void ocall_print_string(const char *str)
{
/* Proxy/Bridge will check the length and null-terminate
* the input string to prevent buffer overflow.
*/
printf("%s", str);
}
sgx_status_t createEnclave(sgx_enclave_id_t *eid) {
sgx_status_t ret = SGX_SUCCESS;
sgx_launch_token_t token = { 0 };
int updated = 0;
ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, eid, NULL);
return ret;
}
sgx_enclave_id_t eid;
//
// This file was generated by the Retargetable Decompiler
// Website: https://retdec.com
// Copyright (c) 2017 Retargetable Decompiler <info@retdec.com>
//
#include <stdint.h>
#include <stdio.h>
#include <string.h>
// ------------------- Function Prototypes --------------------
int32_t bar(void);
int32_t foo(char * str2);
// ------------------------ Functions -------------------------
// Address range: 0x80484fd - 0x804855b
int32_t foo(char * str2) {
int32_t v1 = 0;
int32_t v2 = 0;
printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n", (char *)v2, str2);
int32_t str = 0;
//strcpy((char *)&str, str2);
enclaveStrcpy(eid, (char *)&str, str2);
puts((char *)&str);
printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n", str2, str2);
int32_t v3 = 0;
if (v3 != v1) {
// 0x8048555
// branch -> 0x804855a
}
// 0x804855a
return v3 ^ v1;
}
// Address range: 0x804855c - 0x804856f
int32_t bar(void) {
// 0x804855c
return puts("Augh! I've been hacked!");
}
// Address range: 0x8048570 - 0x80485ff
int main(int argc, char ** argv) {
// 0x8048570
printf("Address of foo = %p\n", (int32_t *)foo);
printf("Address of bar = %p\n", (int32_t *)bar);
int32_t * str = (int32_t *)((int32_t)argv + 4); // 0x80485a7_0
printf("strlen of input string is: %i\n", strlen((char *)*str));
int32_t result = 0;
if (argc == 2) {
// 0x80485da
foo((char *)*str);
result = 0;
// branch -> 0x80485ef
}
else {
// 0x80485c7
puts("Please supply a string as an argument!");
result = -1;
// branch -> 0x80485ef
}
// 0x80485ef
return result;
}
// --------------- Dynamically Linked Functions ---------------
// void __stack_chk_fail(void);
// int printf(const char * restrict format, ...);
// int puts(const char * s);
// char * strcpy(char * restrict dest, const char * restrict src);
// size_t strlen(const char * s);
// --------------------- Meta-Information ---------------------
// Detected compiler/packer: gcc (4.8.2)
// Detected functions: 3
// Decompiler release: v2.2.1 (2016-09-07)
// Decompilation date: 2017-07-02 07:43:00
| true |
640a514f66d7e6ff1b8b2fbfef4ec81780dd7009 | C++ | vitamin-caig/zxtune | /src/sound/receiver.h | UTF-8 | 832 | 2.59375 | 3 | [] | no_license | /**
*
* @file
*
* @brief Defenition of sound receiver interface
*
* @author vitamin.caig@gmail.com
*
**/
#pragma once
// common includes
#include <data_streaming.h>
// library includes
#include <sound/chunk.h>
#include <sound/multichannel_sample.h>
namespace Sound
{
//! @brief Simple sound stream endpoint receiver
using Receiver = DataReceiver<Chunk>;
using Converter = DataConverter<Chunk, Chunk>;
//! @brief Channel count-specific receivers
template<unsigned Channels>
class FixedChannelsReceiver : public DataReceiver<typename MultichannelSample<Channels>::Type>
{};
using OneChannelReceiver = FixedChannelsReceiver<1>;
using TwoChannelsReceiver = FixedChannelsReceiver<2>;
using ThreeChannelsReceiver = FixedChannelsReceiver<3>;
using FourChannelsReceiver = FixedChannelsReceiver<4>;
} // namespace Sound
| true |
92ab67a283232df9d4b74bcfd5b6be0af1fbffdd | C++ | pontsuyo/procon | /aoj/alds1/0101c.cpp | UTF-8 | 493 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
bool is_prime(int x){
if(x==2){
return true;
}else if(x < 2 || x % 2 == 0){
return false;
}
for(int i=3;i <= sqrt(x);i += 2){
if(x % i ==0){
return false;
}
}
return true;
}
int main(){
int n; cin >> n;
int x;
int cnt=0;
for(int i=0; i<n; i++){
cin >> x;
if(is_prime(x)){
cnt++;
}
}
cout << cnt << endl;
} | true |
e4e23e7c5e3cf9eddbabee24b991131310ec0aab | C++ | maker91/VoxMysticum | /src/IDFactory.cpp | UTF-8 | 192 | 2.546875 | 3 | [] | no_license | #include "IDFactory.hpp"
uid IDFactory::generate(const std::string &what)
{
if (!ids.count(what))
ids[what] = 0;
return ids[what]++;
}
std::map<std::string, uid> IDFactory::ids; | true |
5c2c0bc475c47370511ef9215cd6ef6e83d87cd1 | C++ | gosu/gosu | /src/ClipRectStack.hpp | UTF-8 | 465 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <Gosu/Utility.hpp>
#include "GraphicsImpl.hpp"
#include <limits>
#include <optional>
#include <stdexcept>
#include <vector>
namespace Gosu
{
class ClipRectStack
{
std::vector<Rect> m_stack;
std::optional<Rect> m_effective_rect;
public:
void clear();
void push(const Rect& rect);
void pop();
const std::optional<Rect>& effective_rect() const { return m_effective_rect; }
};
}
| true |
69911b34fca82953ed1fb444e09638fad92d1dbb | C++ | Bluegent/CommProto | /CommProtoLib/interface/commproto/utils/Math.h | UTF-8 | 560 | 2.765625 | 3 | [] | no_license | #ifndef CP_MATH_H
#define CP_MATH_H
#include <math.h>
namespace commproto
{
namespace math
{
inline bool floatEq(float a, float b, float epsilon = 0.0001f)
{
return fabs(a - b) < epsilon;
}
inline float getNearest(float left, float right, float value, float step)
{
float compute = left + value * (right - left);
if (floatEq(step, 0.f))
{
return compute;
}
if(right - compute < step )
{
return right;
}
float div = compute / step;
compute = floor(div) * step;
return compute;
}
}
}
#endif//CP_MATH_H | true |
72d86060adfa3b6828438b452f86c5cb81e9002f | C++ | robhagemans/bethe-solver | /bethe-xxz/main.cc | UTF-8 | 1,105 | 3.359375 | 3 | [
"MIT"
] | permissive | #include "exception.h"
string Command;
vector< stringstream* > Arguments;
stringstream Command_Line;
int main(int argc, char* argv[])
{
Command = argv[0];
for (int argn=1; argn < argc; ++argn) {
Command_Line << argv[argn] << "\t";
Arguments.push_back(new stringstream(argv[argn]));
}
try {
return run();
}
catch (Exception error) {
cerr << "Error: " << error<< endl;
return 1;
}
catch (const char* error) {
cerr << "Error: " << error<< endl;
return 1;
}
catch (char* error) {
cerr << "Error: " << error<< endl;
return 1;
}
catch (int error) {
cerr << "Error: " << error<< endl;
return 1;
}
catch (const int error) {
cerr << "Error: " << error<< endl;
return 1;
}
catch (std::bad_alloc) {
cerr << "Error: badalloc"<<endl;
return 1;
}
catch (std::bad_exception) {
cerr << "Error: badexception"<<endl;
return 1;
}
catch (std::out_of_range) {
cerr << "Error: index out of range"<<endl;
return 1;
}
catch (...) {
cerr << "Unknown error. Sorry 'bout that. "<<endl;
return 1;
}
for (int i=0; i < Arguments.size(); ++i) delete Arguments[i];
}
| true |
f7d11560f04709ceea7651d7dbb15d7bf8cba662 | C++ | federicodangelo/SimpleCompiler | /SimpleCompiler-C/CSimboloSimple.cpp | UTF-8 | 558 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "CSimboloSimple.h"
#include "CTablaSimbolos.h"
#include "FuncionesUnix.h"
CSimboloSimple::CSimboloSimple()
{
m_Type = SIMBOLO_TIPO_CONSTANTE_INT;
}
void CSimboloSimple::Imprimir(int n)
{
for (int i = 0; i < n; i++)
printf(" ");
switch(GetType())
{
case SIMBOLO_TIPO_CONSTANTE_INT:
printf("Constante int: %ld\n", GetInt());
break;
case SIMBOLO_TIPO_CONSTANTE_FLOAT:
printf("Constante float: %f\n", GetFloat());
break;
case SIMBOLO_TIPO_CONSTANTE_STRING:
printf("Constante string: %s\n", GetString());
break;
}
} | true |
13c6df1e833e84979e4f9aa8fc8529d3a1a0905f | C++ | xczhang07/leetcode | /g/swap_adjacent_in_lr_string.cpp | UTF-8 | 1,442 | 3.78125 | 4 | [] | no_license |
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL",
a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR".
Given the starting string start and the ending string end,
return True if and only if there exists a sequence of moves to transform one string to the other.
Example:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: True
Explanation:
We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Time Complexity is: O(n)
Space Complexity is: O(n)
class Solution {
public:
bool canTransform(string start, string end) {
if(start.size() != end.size())
return false;
string s1, s2;
int n = start.size();
for(int i = 0; i < n; ++i)
{
if(start[i] != 'X')
s1 += start[i];
if(end[i] != 'X')
s2 += end[i];
}
if(s1 != s2)
return false;
int i = 0, j = 0;
while(i < n && j < n)
{
if(start[i] == 'X')
++i;
else if(end[j] == 'X')
++j;
else
{
if((start[i] == 'L' && i < j) || (start[i] == 'R' && i > j))
return false;
++i;
++j;
}
}
return true;
}
};
| true |
0024e1d214ab1a75eabeadd88ff4e3f53bad31b8 | C++ | BaldomeroVargas/BlackJack | /Deck.h | UTF-8 | 783 | 3.421875 | 3 | [] | no_license | #ifndef __DECK__
#define __DECK__
#include <iostream>
#include <vector>
using namespace std;
struct Card{
private:
string face;
string suit;
int value;
public:
//Card constructor
Card(string cardFace, string cardSuit, int cardValue);
//prints card
void printCard();
//returns card value
int val_return();
//alters ace value
void ace(int num);
};
class Deck
{
private:
vector<Card> c;
unsigned shuffle_seed;
public:
//Deck default constructor
Deck();
//prints deck
void printDeck();
//shuffles deck
void shuffle_deck();
//draws a card
Card draw_card(int &totDrawn);
};
#endif | true |
e9d1867ca4395d0f22469b6435d035dd04f40ffd | C++ | juris-97/COM-LocalServer-Power | /Server/Factory.cpp | UTF-8 | 1,264 | 2.6875 | 3 | [] | no_license | #include "Factory.h"
#include "Power.h"
Factory::Factory() {
InterlockedIncrement(&UCServer);
m_ref = 0;
};
Factory::~Factory() {
InterlockedDecrement(&UCServer);
};
HRESULT STDMETHODCALLTYPE Factory::QueryInterface(REFIID id, void** ptr) {
if (ptr == NULL) return E_POINTER;
*ptr = NULL;
if (id == IID_IUnknown)* ptr = this;
else if (id == IID_IClassFactory)* ptr = this;
if (*ptr != NULL) { AddRef(); return S_OK; };
return E_NOINTERFACE;
};
ULONG STDMETHODCALLTYPE Factory::AddRef() {
return InterlockedIncrement(&m_ref);
};
ULONG STDMETHODCALLTYPE Factory::Release() {
ULONG result = InterlockedDecrement(&m_ref);
if (result == 0) delete this;
return result;
};
HRESULT STDMETHODCALLTYPE Factory::LockServer(BOOL v) {
if (v) InterlockedIncrement(&UCServer);
else InterlockedDecrement(&UCServer);
return S_OK;
};
HRESULT STDMETHODCALLTYPE Factory::CreateInstance(IUnknown* outer, REFIID iid, void** ptr) {
Power* power;
if (ptr == NULL) return E_POINTER;
*ptr = NULL;
if (iid != IID_IUnknown && iid != IID_IPower) return E_NOINTERFACE;
power = new Power();
if (power == NULL) return E_OUTOFMEMORY;
HRESULT result = power->QueryInterface(iid, ptr);
if (FAILED(result)) {
delete power;
*ptr = NULL;
}
return result;
}; | true |
58130abd3a92068c04b93b37871727e2d29d6e58 | C++ | gianbelinche/TallerTP2 | /Cocinero.cpp | UTF-8 | 445 | 2.609375 | 3 | [] | no_license | #include "Cocinero.h"
#include "CocineroInterno.h"
#include "PuntosDeBeneficio.h"
#include "Inventario.h"
#include <utility>
Cocinero::Cocinero(Inventario& inventario,PuntosDeBeneficio& puntos) :
cocinero_interno(CocineroInterno(inventario,puntos)){}
void Cocinero::empezar(){
std::thread thread(cocinero_interno);
this->thread = std::move(thread);
}
Cocinero::~Cocinero(){
if (thread.joinable()){
thread.join();
}
}
| true |
52ba10602fc40a2e68c472c58237030c92698b67 | C++ | Bilonel/Game-Top-Down | /Object.h | UTF-8 | 537 | 2.828125 | 3 | [] | no_license | #pragma once
#include "Game.h"
class Object
{
public:
int tag;
sf::Vector2f bulletPos;
Object(int tag=0) :tag(tag), bulletPos(-111, -111) {}
virtual void update(float deltaTime) {}
virtual void render(sf::RenderWindow& window,float deltaTime) {}
virtual bool isAlive() {return true; }
};
class SpriteObject : public Object
{
public:
sf::Sprite sprite;
SpriteObject(sf::Texture& texture, int tag=0) :Object(tag), sprite(texture) {}
virtual void render(sf::RenderWindow& window,float deltTime) { window.draw(sprite);}
};
| true |
8b5a050b96c86d7d1d8e55adc8e6ad02db759696 | C++ | redaaa99/HackerRankSolutions | /algortihms/implementation/acmIcpcTeam.cpp | UTF-8 | 842 | 2.75 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
string topic[n];
for(int topic_i = 0; topic_i < n; topic_i++){
cin >> topic[topic_i];
}
int known, max_known = 0, know_all = 0;
for(int i = 0; i < n-1; i++) {
for(int j = i+1; j < n; j++) {
known = 0;
for(int k = 0; k < m; k++) {
if(topic[i][k] == '1' || topic[j][k] == '1')
known++;
if(max_known < known) {
max_known = known;
know_all = 0;
}
if(known == max_known)
know_all++;
}
}
}
cout << max_known << endl << know_all<<endl;
return 0;
}
| true |
5497ee1a58a26622dc2b09a56c624562302649eb | C++ | derekzhang79/Algorithm-Training | /Challenge/DFS/1979m.cpp | UTF-8 | 1,019 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<cmath>
using namespace std;
char RedAndBlack[20][20];
int RBState[20][20] = {0};
int w,h;
int result;
int dfs(int a,int b);
int main()
{
while(cin>>w>>h&&(w||h)){
int posX = 0;int posY = 0;
result = 0;
memset(RedAndBlack,0,sizeof(RedAndBlack));
memset(RBState,0,sizeof(RBState));
for(int i=0;i<h;i++)
for(int j=0;j<w;j++){
cin>>RedAndBlack[i][j];
if(RedAndBlack[i][j]=='@'){
posX = i;
posY = j;
}
}
dfs(posX,posY);
cout<<result + 1 <<endl;
}
return 0;
}
int dfs(int a,int b){
if(a<0||a>=h||b<0||b>=w)
return 0;
if(RBState[a][b]==0){
if(RedAndBlack[a][b]=='#')
return 0;
if(RedAndBlack[a][b]=='.')
result++;
RBState[a][b] = 1;
dfs(a+1,b);
dfs(a-1,b);
dfs(a,b+1);
dfs(a,b-1);
}
return 0;
} | true |
4987050fbcad2badecb6305baa07f9f2e2ce956d | C++ | draetus/faculdade_trabalhos | /Estrutura_de_Dados/Trabalho_M2/Atividade_1/Deque.h | UTF-8 | 511 | 3.09375 | 3 | [] | no_license | #ifndef DEQUE_H_INCLUDED
#define DEQUE_H_INCLUDED
#include <iostream>
using namespace std;
const int dequeSize = 5;
class Deque {
int elements [dequeSize], elementsQuantity, right, left;
public:
Deque();
void pushRight(int data);
void pushLeft(int data);
void popRight();
void popLeft();
bool isEmpty();
bool isFull();
bool elementExistence(int data);
int getElementsQuantity();
int getRight();
int getLeft();
void print();
};
#endif // DEQUE_H_INCLUDED
| true |
f4283613a3925108aa83ca33c1a3a7386ab89832 | C++ | SevenLines/Wave | /gui/mainwindow.cpp | UTF-8 | 2,452 | 2.609375 | 3 | [] | no_license | #include <core/Waveprocessor.h>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <opencv2/opencv.hpp>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
ui->setupUi(this);
}
MainWindow::~MainWindow() {
delete ui;
}
inline cv::Mat QImageToCvMat(const QImage &inImage, bool inCloneImageData = true) {
switch (inImage.format()) {
// 8-bit, 4 channel
case QImage::Format_ARGB32:
case QImage::Format_ARGB32_Premultiplied: {
cv::Mat mat(inImage.height(), inImage.width(),
CV_8UC4,
const_cast<uchar *>(inImage.bits()),
static_cast<size_t>(inImage.bytesPerLine())
);
return (inCloneImageData ? mat.clone() : mat);
}
// 8-bit, 3 channel
case QImage::Format_RGB32:
case QImage::Format_RGB888: {
if (!inCloneImageData) {
qWarning() << "ASM::QImageToCvMat() - Conversion requires cloning because we use a temporary QImage";
}
QImage swapped = inImage;
if (inImage.format() == QImage::Format_RGB32) {
swapped = swapped.convertToFormat(QImage::Format_RGB888);
}
swapped = swapped.rgbSwapped();
return cv::Mat(swapped.height(), swapped.width(),
CV_8UC3,
const_cast<uchar *>(swapped.bits()),
static_cast<size_t>(swapped.bytesPerLine())
).clone();
}
// 8-bit, 1 channel
case QImage::Format_Indexed8: {
cv::Mat mat(inImage.height(), inImage.width(),
CV_8UC1,
const_cast<uchar *>(inImage.bits()),
static_cast<size_t>(inImage.bytesPerLine())
);
return (inCloneImageData ? mat.clone() : mat);
}
default:
qWarning() << "ASM::QImageToCvMat() - QImage format not handled in switch:" << inImage.format();
break;
}
return cv::Mat();
}
void MainWindow::on_actionProcess_triggered() {
QImage image = ui->graphicsView->image();
std::cout << image.format();
auto processor = WaveProcessor(QImageToCvMat(image));
auto skeleton = processor.process();
ui->graphicsView->setSkeleton(skeleton);
}
| true |
1c97c4b3db0132617afe49416d64f905ad7a73f2 | C++ | zeroplusone/AlgorithmPractice | /Other/2015_google_code_jam/qb/qb.cpp | UTF-8 | 1,347 | 2.6875 | 3 | [] | no_license | #include<cstdio>
#include<cstdlib>
using namespace std;
#define MAXD 1100
int tmp[MAXD];
int d;
int findMin(int p[],int sum,int ans)
{
printf("~%d %d\n",ans,sum);
for(int i=0;i<d;++i)
printf("%d ",p[i]);
printf("\n");
if(sum<=0)
{
return ans;
}
int sp,nsp,tsum,maxn,maxi,i;
// non special time
printf("nsp\n");
tsum=sum;
for(i=0;i<d;++i)
{
tmp[i]=p[i];
if(tmp[i]!=0)
{
tmp[i]=tmp[i]-1;
tsum-=1;
}
}
nsp=findMin(tmp,tsum,ans+1);
//special time
printf("sp\n");
tsum=sum;
maxn=p[0];
tmp[0]=p[0];
maxi=0;
for(i=1;i<d;++i)
{
tmp[i]=p[i];
if(tmp[i]>maxn)
{
maxn=tmp[i];
maxi=i;
}
}
if(maxn==1)
sp=MAXD;
else
{
tsum=(maxn-1)/2;
tmp[maxi]=(tmp[maxi]+1)/2;
sp=findMin(tmp,tsum,ans+1);
}
printf("!%d %d %d\n",sp,nsp,ans);
return sp>nsp?nsp:sp;
}
int main()
{
int tt,T;
int i,sum;
int p[MAXD];
scanf("%d",&T);
for(tt=1;tt<=T;++tt)
{
sum=0;
scanf("%d",&d);
for(i=0;i<d;++i)
{
scanf("%d",&p[i]);
sum+=p[i];
}
printf("Case #%d: %d\n",tt,findMin(p,sum,0));
}
return 0;
}
| true |
7dcd85d487fd29a71c7eb389ee757c32061d7ef0 | C++ | andrejlevkovitch/KaliLaska | /src/graphics/imp/SceneIteratorImp.hpp | UTF-8 | 1,063 | 2.953125 | 3 | [] | no_license | // SceneIteratorImp.hpp
#pragma once
#include <iterator>
#include <memory>
namespace KaliLaska {
class GraphicsItem;
class SceneIteratorImp {
public:
virtual ~SceneIteratorImp() = default;
virtual GraphicsItem *operator*() const = 0;
virtual GraphicsItem *operator->() const = 0;
virtual SceneIteratorImp &operator++() = 0;
virtual SceneIteratorImp &operator++(int) = 0;
virtual bool operator==(const SceneIteratorImp &rhs) const = 0;
virtual bool operator!=(const SceneIteratorImp &rhs) const = 0;
/**\brief this method needed for copy SceneIterator, which contains unique_ptr
* with object of this class
*/
virtual std::unique_ptr<SceneIteratorImp> copyItSelf() const = 0;
};
} // namespace KaliLaska
namespace std {
template <>
struct iterator_traits<KaliLaska::SceneIteratorImp> {
using iterator_category = std::forward_iterator_tag;
using value_type = KaliLaska::GraphicsItem *;
using pointer = KaliLaska::GraphicsItem *;
using reference = KaliLaska::GraphicsItem *;
};
} // namespace std
| true |
fbc787963da4566c5e4e7665eecf9cce963a9f3e | C++ | sanjosh/smallprogs | /basic/array/longest_increasing_subseq2.cpp | UTF-8 | 1,400 | 3.515625 | 4 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
int32_t LIS(const std::vector<int32_t> &v)
{
std::vector<int32_t> highest_in_sequence(v.size());
std::vector<int32_t> length_of_sequence(v.size());
highest_in_sequence[0] = v[0];
length_of_sequence[0] = 1;
int num_sequences = 1;
for (size_t i = 1; i < v.size(); i ++)
{
if (v[i] < highest_in_sequence[0]) {
highest_in_sequence[0] = v[i]; // new smallest
} else if (v[i] > highest_in_sequence[num_sequences - 1]) {
highest_in_sequence[num_sequences] = v[i];
length_of_sequence[num_sequences] = length_of_sequence[num_sequences - 1] + 1;
num_sequences ++;
} else {
// find sequence which has value less than v[i]
// SOME PROBLEM IN USAGE
auto iter = std::lower_bound(highest_in_sequence.begin(), highest_in_sequence.end(), v[i]);
int32_t found = std::distance(highest_in_sequence.begin(), iter);
cout << "bin: " << *iter << "," << found << endl;
highest_in_sequence[found] = v[i];
length_of_sequence[found] ++;
}
}
for (int i = 0; i < num_sequences; i++) {
cout << highest_in_sequence[i] << "," << length_of_sequence[i] << endl;
}
return 0;
}
int main()
{
std::vector<int32_t> v = { 1, 4, 8, 0, 3, 12 };
LIS(v);
}
| true |
51c984a26f261c607dbfbeb38b0c8db5848dcf53 | C++ | TolgaV/IL2452-System-Design-Languages | /sc-programs/channel-queue/queue_if.h | UTF-8 | 1,423 | 3.203125 | 3 | [] | no_license | #pragma once
/* Queue Interface header file */
#include "stdafx.h"
#include "systemc.h"
/* Step 1: Declare an abstract interface class
-derived from sc_interface
-use Virtual inheritance to allow multiple inheritance without
multiple inclusion of the base class members
-pure virtual functions because it is mandatory for users
to supply the implementation
*/
class queue_write_if : virtual public sc_interface {
public:
virtual void write(int c) = 0;
};
class queue_read_if : virtual public sc_interface {
public:
virtual int read() = 0;
};
class queue_if: public queue_write_if, public queue_read_if{};
/* Step 2: Channel Implementation
-Declare the queue class as our own channl
-the interface class is declared but does nothing
-it is the channel's responsibility to override th
pure virtual methods and describe functionality
-Derived from sc_object
-Since the queue channel is neither a hierarchical
nor a primitive channel, it is recommended that such
channels are at least derived from sc_object so that
they own attributes such as a hierarchical name and a
position in the module hierarchy.
-sc_object is the base class for all objects in the
module hierarchy!
*/
class Queue : public queue_if, public sc_object {
public:
Queue(char *_nm, int _size)
: sc_object(_nm), size(_size) {
data = new int[size];
w = r = n = 0;
}
void write(int c);
int read();
private:
int *data;
int size, w, r, n;
}; | true |
00215ad3fa352f6ab809fc99df68ac8dd72f5599 | C++ | NullCodex/Straights | /DialogTesting/helloworld.cc | UTF-8 | 1,251 | 3.453125 | 3 | [] | no_license | /*
* Displays a group of radio buttons in a dialog box when the button in the window is clicked.
*/
#include "helloworld.h"
#include "MyDialogBox.h"
#include "TurnDialog.h"
// Creates a new button with the label "Hello World".
HelloWorld::HelloWorld() : button("Bring up dialog box"), button1("Bring up dialog box 2"){
// Sets the border width of the window.
set_border_width( 10 );
// When the button receives the "clicked" signal, it will call the onButtonClicked() method defined below.
button.signal_clicked().connect( sigc::mem_fun( *this, &HelloWorld::onButtonClicked ) );
button1.signal_clicked().connect(sigc::mem_fun(*this, &HelloWorld::onButtonClicked2));
// This packs the button into the Window (a container).
add(mainWindow);
mainWindow.add( button );
mainWindow.add(button1);
// The final step is to display this newly created widget.
show_all();
} // HelloWorld::HelloWorld
HelloWorld::~HelloWorld() {}
void HelloWorld::onButtonClicked() {
// Create the message dialog box with stock "Ok" button. Waits until the "Ok" button has been pressed.
MyDialogBox dialog( *this, "Winner" );
} // HelloWorld::onButtonClicked
void HelloWorld::onButtonClicked2() {
TurnDialog dialog(*this, "Error");
}
| true |
97ecf18f4909c143095062ffdcb35fe09104b05b | C++ | j-seeger/ProjektArbeitSpiel | /zeichenfeld.cpp | UTF-8 | 4,247 | 2.53125 | 3 | [] | no_license | using namespace std;
#include <QtGui>
#include <QMessageBox>
#include <QKeyEvent>
#include <QLabel>
#include <QTextStream>
#include "zeichenFeld.h"
zeichenFeld::zeichenFeld(QWidget *parent): QWidget(parent)
{
/*hier wird das Design des Spielfeldes festgelegt*/
setPalette(QPalette(QColor(46, 139, 87)));
setAutoFillBackground(true);
setMouseTracking(false);
/*hier wird die Start-Position des Avatar festgelegt*/
x=225, y=450;
/*hier wird der Timer für die "Gegner-Objekte" generiert*/
timer=new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
/*hier wird die y-Start-Position der "Gegner-Objeket" festgelegt*/
lastU=-1000;
lastV=-50;
lastW=-100;
/*hier wird die x-Start-Position der "Gegner-Objekte" festgelegt*/
lastA=25;
lastB=125;
lastC=346;
increment=0;
zaehler=0;
/*hier wird der Punktestand eingeblendet*/
label = new QLabel(this);
label->setNum(zaehler);
label->setFont(QFont("Times", 18, QFont::Bold));
label->setGeometry(0,0,100,30); /*ist notwendig, damit auch mehrstellige Zahlen gezeigt werden*/
}
void zeichenFeld::paintEvent(QPaintEvent * )
{
QPainter painter;
int a,b,c,u,v,w;
a=lastA;b=lastB;c=lastC;
u=lastU;v=lastV;w=lastW;
painter.begin(this);
/*hier wird der Avatar generiert*/
painter.setBrush(QBrush(Qt::Dense2Pattern));
painter.drawRect(x,y,50,50);
/*hier werden die Objekete generiert*/
painter.setBrush(QBrush(Qt::red));
painter.drawEllipse(a,u,70,70);
if (increment)
{
if (lastU<500)lastU++;
else
{
zaehler=zaehler+50; //Punkte Anzahl wird erhöht, je nach Größe der Objekte gibt es unterschiedliche Punkte
label->setNum(zaehler);
lastU=(rand() % 1)-700; // mit Hilfe von rand() gelingt es, dass die Objekte immer von unterschiedlichen Startpositionen aus starten
lastA=rand()%450;
}
}
painter.setBrush(QBrush(Qt::green));
painter.drawRect(b,v,30, 30);
if (increment)
{
if (lastV<500)lastV++;
else
{
zaehler=zaehler+10;
label->setNum(zaehler);
lastV=(rand() % 1)-10;
lastB=rand()%450;
}
}
painter.setBrush(QBrush(Qt::blue));
painter.drawRect(c,w,90, 50);
if (increment)
{
if (lastW<500)lastW++;
else
{
zaehler=zaehler+100;
label->setNum(zaehler);
lastW=(rand() % 1)-200;
lastC=rand()%450;
}
}
/*hier werden die Lebenszeichen generiert*/
painter.setBrush(QBrush(Qt::darkRed));
painter.drawEllipse(450,10,10,10);
painter.drawEllipse(465,10,10,10);
painter.drawEllipse(480,10,10,10);
painter.end();
}
void zeichenFeld::keyPressEvent(QKeyEvent *event)
{
/* hier wird die Beweglichkeit des Avatars it Hilfe der Pfeiltasten gereglet*/
if (event->key()==Qt::Key_Left)
{
if(x>=25)
x = x - 25;
update();
}
if (event->key() == Qt::Key_Right)
{
if(x<450)
x = x + 25;
update();
}
}
void zeichenFeld::serialize(QFile &file)
{
QTextStream out(&file);
/*hier werden die Integers gespeichert*/
out << "p " << x << "p " <<zaehler << "p " <<lastA << "p " <<lastB << "p " <<lastC << "p " <<lastU << "p " <<lastV << "p " <<lastW;
}
void zeichenFeld::deserialize(QFile &file)
{
char c;
QTextStream in(&file);
while (in.status() == QTextStream::Ok)
{
in >> c;
if (in.status() == QTextStream::ReadPastEnd) break;
if (c!='p')
{
QMessageBox::warning(this, tr("Objektfehler"),
tr("Folgender Objekttyp ist unbekannt: ") + c,QMessageBox::Ok);
return;
}
/*hier werden die integers mit den gespeicherten Zahlen befüllt*/
in >>x >> c >> zaehler >> c >> lastA >> c >> lastB >> c >> lastC >>c >> lastU >>c >> lastV >>c >> lastW;
label->setNum(zaehler); //ist notwendig, damit die gespeicherte und geladene zahl auch angezeigt wird.
}
update();
}
| true |
465f8f31266bd4799377854de80a9d14520b16b5 | C++ | npruehs/pinned-down-server | /Source/PinnedDownGameplay/PinnedDownGameplay/Util/Random.h | UTF-8 | 547 | 2.59375 | 3 | [
"MIT"
] | permissive | #pragma once
namespace PinnedDownGameplay
{
namespace Util
{
// Implementation of the Ranq1 struct found in Numerical Recipes in C: 3rd Edition.
// Combined generator (Ranq1 = D1(A1(right-shift first)) with a period of 1.8 x 10^19.
class Random
{
public:
Random();
Random(unsigned long long seed);
unsigned long long NextUnsignedLong();
unsigned int NextUnsignedInt();
unsigned int NextUnsignedInt(unsigned int maxExclusive);
double NextDouble();
float NextFloat();
private:
unsigned long long v;
};
}
} | true |
7535deb6b799f68d675defbcb39a92165fd73207 | C++ | Aryaman2912/DSA | /Binary_Trees/breadth_first_traversal.cpp | UTF-8 | 2,024 | 4.375 | 4 | [] | no_license | // The below program demonstrates breadth first traversal of a binary tree
#include<bits/stdc++.h>
using namespace std;
struct BstNode{
int data;
BstNode* left;
BstNode* right;
};
// Function to create a new node
BstNode* GetNewNode(int value){
BstNode* node = new BstNode();
node->data = value;
node->left = node->right = NULL;
return node;
}
// Function to insert a new node into the BST
BstNode* Insert(BstNode* root, int value){
// if tree is empty, assign node to root
if(root == NULL){
// create new node with data field as value and left, right pointers as null
BstNode* node = GetNewNode(value);
root = node;
}
// if value of new node is less than or equal to the data at current root, insert to the left
else if(value <= root->data){
root->left = Insert(root->left,value);
}
// if value of new node is greater than the data at current root, insert to the right
else{
root->right = Insert(root->right,value);
}
return root;
}
// Function to perform breadth first traversal of binary tree
void BreadthFirstTraversal(BstNode* root){
// handle empty tree case
if(root == NULL){
return;
}
// we use a queue to store the addresses of nodes that we have to visit
queue<BstNode*> Q;
Q.push(root);
// when the queue is empty, we are done
while(!Q.empty()){
BstNode* current = Q.front();
cout << current->data <<" ";
if(current->left != NULL)
Q.push(current->left);
if(current->right != NULL)
Q.push(current->right);
Q.pop();
}
cout << endl;
}
int main(){
BstNode* root = NULL;
// create perfect binary tree
root = Insert(root,20);root = Insert(root,10);root = Insert(root,40);root = Insert(root,5);root = Insert(root,15);
root = Insert(root,30);root = Insert(root,50);root = Insert(root,1);root = Insert(root,7);root = Insert(root,14);
root = Insert(root,17);root = Insert(root,22);root = Insert(root,31);root = Insert(root,45);root = Insert(root,55);
cout << "Breadth first traversal takes place in the following order:\n";
BreadthFirstTraversal(root);
} | true |
8c2c64caa14385629e1973c1ca357e06f401ae4a | C++ | 2020lwy/CppPratice | /C++/gdb/test.cpp | UTF-8 | 202 | 2.90625 | 3 | [] | no_license | #include <iostream>
int test(int *var){
int a = 200;
var = &a;
return *var;
}
int main(void){
int *var = NULL;
std::cout << "return = " << test(var) << std::endl;
return 0;
} | true |
46f8f2981e7b58b5ce5f6f78cb79d5f23a67a74e | C++ | ArapovXD/QT-Quick-todo- | /src/authhandler.cpp | UTF-8 | 2,813 | 2.765625 | 3 | [] | no_license | #include "authhandler.h"
#include <QDebug>
#include <QVariantMap>
#include <QNetworkRequest>
#include <QJsonObject>
AuthHandler::AuthHandler(QObject *parent)
: QObject(parent)
, m_apiKey( QString() )
{
m_networkAccessManager = new QNetworkAccessManager( this );
}
AuthHandler::~AuthHandler()
{
m_networkAccessManager->deleteLater();
}
void AuthHandler::setAPIKey(const QString &apiKey)
{
m_apiKey = apiKey;
}
Q_INVOKABLE void AuthHandler::signUserUp(const QString &emailAddress, const QString &password)
{
m_userEmail = emailAddress;
QString signUpEndpoint = "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=" + m_apiKey;
QVariantMap variantPayload;
variantPayload["email"] = emailAddress;
variantPayload["password"] = password;
variantPayload["returnSecureToken"] = true;
QJsonDocument jsonPayload = QJsonDocument::fromVariant( variantPayload );
performPOST( signUpEndpoint, jsonPayload );
}
Q_INVOKABLE void AuthHandler::signUserIn(const QString &emailAddress, const QString &password)
{
m_userEmail = emailAddress;
QString signInEndpoint = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=" + m_apiKey;
QVariantMap variantPayload;
variantPayload["email"] = emailAddress;
variantPayload["password"] = password;
variantPayload["returnSecureToken"] = true;
QJsonDocument jsonPayload = QJsonDocument::fromVariant( variantPayload );
performPOST( signInEndpoint, jsonPayload );
}
QString AuthHandler::getUserEmail()
{
return m_userEmail;
}
void AuthHandler::networkReplyReadyRead()
{
QByteArray response = m_networkReply->readAll();
//qDebug() << response;
m_networkReply->deleteLater();
parseResponse( response );
}
void AuthHandler::performPOST(const QString &url, const QJsonDocument &payload)
{
QNetworkRequest newRequest( (QUrl( url )) );
newRequest.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/json"));
m_networkReply = m_networkAccessManager->post( newRequest, payload.toJson());
connect( m_networkReply, &QNetworkReply::readyRead, this, &AuthHandler::networkReplyReadyRead );
}
void AuthHandler::parseResponse(const QByteArray &response)
{
QJsonDocument jsonDocument = QJsonDocument::fromJson( response );
if ( jsonDocument.object().contains("error") )
{
qDebug() << "Error occured!" << response;
}
else if ( jsonDocument.object().contains("kind"))
{
QString idToken = jsonDocument.object().value("idToken").toString();
//qDebug() << "Obtained user ID Token: " << idToken;
qDebug() << "User signed in successfully!";
m_idToken = idToken;
emit userSignedIn();
}
else
qDebug() << "The response was: " << response;
}
| true |
ba025c9d6e63a653f2789e850d596ca80bf7ccf4 | C++ | shiv-30/Algorithms | /Dynamic Programming/3CatlanNumber.cpp | UTF-8 | 5,120 | 3.359375 | 3 | [] | no_license | // Catlan numbers
// c0 = 1
// c1 = 1
// c2 = c0c1 + c1c0 = 1 + 1 = 2
// cn = c0c(n - 1) + c0c(n - 2) + ..... + c(n - 2)c0 + c(n - 1)c0
// Applications :
// Number of possible Binary Search Trees with n keys.
// Number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).
// Number of ways a convex polygon of n + 2 sides can split into triangles by connecting vertices.
// convex
// Number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n + 1 leaves.
// Number of different Unlabeled Binary Trees can be there with n nodes.
// The number of paths with 2n steps on a rectangular grid from bottom left, i.e., (n - 1, 0) to top right (0, n - 1) that do not cross above the main diagonal.
// rectangle
// Number of ways to insert n pairs of parentheses in a word of n + 1 letters, e.g., for n = 2 there are 2 ways : ((ab)c) or (a(bc)). For n = 3 there are 5 ways, ((ab)(cd)), (((ab)c)d), ((a(bc))d), (a((bc)d)), (a(b(cd))).
// Number of noncrossing partitions of the set {1, …, 2n} in which every block is of size 2. A partition is noncrossing if and only if in its planar diagram, the blocks are disjoint (i.e. don’t cross). For example, below two are crossing and non - crossing partitions of {1, 2, 3, 4, 5, 6, 7, 8, 9} . The partition {{1, 5, 7}, {2, 3, 8}, {4, 6}, {9}} is crossing and partition {{1, 5, 7}, {2, 3}, {4}, {6}, {8, 9}} is non - crossing.
// partitiom
// Number of Dyck words of length 2n. A Dyck word is a string consisting of n X’s and n Y’s such that no initial segment of the string has more Y’s than X’s. For example, the following are the Dyck words of length 6: XXXYYY XYXXYY XYXYXY XXYYXY XXYXYY.
// Number of ways to tile a stairstep shape of height n with n rectangles. The following figure illustrates the case n = 4:
// stair
// Number of ways to connect the points on a circle disjoint chords. This is similar to point 3 above.
// Number of ways to form a “mountain ranges” with n upstrokes and n down - strokes that all stay above the original line.The mountain range interpretation is that the mountains will never go below the horizon.Mountain_Ranges
// Number of stack - sortable permutations of {1, …, n} . A permutation w is called stack - sortable if S(w) = (1, …, n), where S(w) is defined recursively as follows: write w = unv where n is the largest element in w and u and v are shorter sequences, and set S(w) = S(u)S(v)n, with S being the identity for one - element sequences.
// Number of permutations of {1, …, n} that avoid the pattern 123 ( or any of the other patterns of length 3); that is, the number of permutations with no three - term increasing subsequence. For n = 3, these permutations are 132, 213, 231, 312 and 321. For n = 4, they are 1432, 2143, 2413, 2431, 3142, 3214, 3241, 3412, 3421, 4132, 4213, 4231, 4312 and 4321
// /*Om Namah Shivay*/
#include <bits/stdc++.h>
#define int long long int
using namespace std;
// Recursive Solution
// Time - Exponential
// c(0) -> 0
// c(1) -> 1
// c(2) -> C(1) + C(0) = 2
// C(3) -> 8
// A recursive function to find nth catalan number
int catalanNumberR(int n)
{
// Base case
if (n == 0 or n == 1) {
return 1;
}
// catalan(n) is sum of
// catalan(i)*catalan(n-i-1)
int result = 0;
for (int i = 0; i <= n - 1; ++i) {
result += catalanNumberR(i) * catalanNumberR(n - 1 - i);
}
return result;
}
// Dynamic Programming (Memoization)
// Time Complexity - o(n^2)
int catalanNumberM(vector<int> &dp, int n) {
if (n == 0 or n == 1) {
return 1;
}
else if (dp[n] != -1) {
return dp[n];
}
int result = 0;
for (int i = 0; i < n; ++i) {
result += catalanNumberM(dp, i) * catalanNumberM(dp, n - 1 - i);
}
return dp[n] = result;
}
// Dynamic Programming Tabulation
int catalanNumberT(int n) {
if (n == 0 or n == 1) {
return 1;
}
vector<int> dp(n + 1, 0);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[i] = 0;
for (int j = 0; j <= n - 1; ++j) {
dp[i] += dp[j] * dp[n - 1 - j];
}
}
return dp[n];
}
// A Binomial coefficient based function to find nth catalan
// number in O(n) time and O(1) space
int BCoeff(int n, int k) {
// Since C(n, k) = C(n, n-k)
if (k > n - k) {
k = n - k;
}
int result = 1;
// Calculate value of [n*(n-1)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for (int i = 0; i < k; ++i) {
result *= (n - i);
result /= (i + 1);
}
return result;
}
// A Binomial coefficient based function to find nth catalan
// number in O(n) time and O(1) space
int catalanNumberBC(int n) {
if (n == 0 or n == 1) {
return 1;
}
// Calculate value of 2nCn
int result = BCoeff(2 * n, n);
// return 2nCn/(n+1)
return result / (n + 1);
}
// Driver code
int32_t main()
{
int n;
cin >> n;
vector<int> dp(n + 1, -1);
cout << catalanNumberM(dp, n) << "\n";
return 0;
}
| true |
de375602970d004e2d74de5df5afd7be9de87d90 | C++ | aeremin/Codeforces | /alexey/Solvers/6xx/617/Solver617E.cpp | UTF-8 | 2,709 | 2.59375 | 3 | [] | no_license | #include <Solvers/pch.h>
#include "algo/query/mo_query_processor.h"
#include "algo/query/order_independent_slider.h"
#include "algo/io/printvector.h"
#include "algo/io/readvector.h"
using namespace std;
// Solution for Codeforces problem http://codeforces.com/contest/617/problem/E
class Solver617E
{
public:
void run();
class GoodPairsCalculator
{
public:
using InType = uint32_t;
using OutType = int64_t;
GoodPairsCalculator(uint32_t goodXOR) : goodXOR_(goodXOR), count_(1 << 20) {}
void insert(uint32_t a)
{
value_ += count_[a ^ goodXOR_];
++count_[a];
}
void erase(uint32_t a)
{
--count_[a];
value_ -= count_[a ^ goodXOR_];
}
int64_t value() const { return value_; }
void reset() { fill(begin(count_), end(count_), 0); value_ = 0; }
private:
const uint32_t goodXOR_;
vector<int> count_;
int64_t value_ = 0;
};
};
void Solver617E::run()
{
size_t dataSize, nQueries, favXOR;
cin >> dataSize >> nQueries >> favXOR;
auto data = readVector<uint32_t>(dataSize);
vector<uint32_t> prefixXOR = { 0 };
partial_sum(begin(data), end(data), back_inserter(prefixXOR), bit_xor<uint32_t>());
vector<Query> queries(nQueries);
for (auto& q : queries)
{
cin >> q.first >> q.second;
q.first--;
q.second++;
}
auto res = MoQueryProccessor<OrderIndependentSlider<GoodPairsCalculator>>(prefixXOR).
processQueries(queries, OrderIndependentSlider<GoodPairsCalculator>(GoodPairsCalculator(favXOR)));
printVector(res, "\n");
}
class Solver617ETest : public ProblemTest
{
};
TEST_F( Solver617ETest, Example1 )
{
setInput("5 3 1 1 1 1 1 1 1 5 2 4 1 3");
Solver617E().run();
EXPECT_EQ("9\n4\n4", getOutput());
}
TEST_F( Solver617ETest, Example2 )
{
setInput("6 2 3 1 2 1 1 0 3 1 6 3 5");
Solver617E().run();
EXPECT_EQ("7\n0", getOutput());
}
TEST_F(Solver617ETest, Example3)
{
setInput("6 1 0 1 2 1 1 0 3 1 3 3 5");
Solver617E().run();
EXPECT_EQ("0", getOutput());
}
TEST_F(Solver617ETest, RandomMaxTest)
{
srand(6);
int n = 100000;
stringstream ss;
ss << n << " " << n << " " << 123321 << " ";
for (int i = 0; i < n; ++i)
ss << (rand() % 1000000) << " ";
for (int i = 0; i < n; ++i)
{
int l, r;
tie(l, r) = minmax((rand() % (n / 10)) + 1, n);
ss << l << " " << r << " ";
}
setInput(ss.str());
Solver617E().run();
}
| true |
f0f90dd289bfd30dac273c2dceabf1408bfd1d73 | C++ | JonnyKong/GoogleCodeJam | /2018/Qualification/d.cpp | UTF-8 | 2,249 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <ostream>
#include <fstream>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
// #define cin infile
// ifstream infile("in.txt", ios::in);
vector<vector<double>> matmul(const vector<vector<double>> & a,
const vector<vector<double>> & b) {
int x = a.size(), y = b.size(), z = b[0].size();
vector<vector<double>> result(x, vector<double>(z));
for(int i = 0; i < x; ++i) {
for(int j = 0; j < z; ++j) {
double sum = 0;
for(int k = 0; k < y; ++k) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}
void matprint(const vector<vector<double>> & a) {
for(int i = 0; i < a.size(); ++i) {
for(int j = 0; j < a[0].size(); ++j) {
if(a[i][j] < 1e-16 && a[i][j] > -1 * 1e-16) {
cout << 0;
}
else {
cout << a[i][j];
}
if(j < a[0].size() - 1) cout << ' ';
}
cout << endl;
}
}
int main() {
cout.precision(16);
int t; cin >> t;
for(int z = 0; z < t; ++z) {
double a; cin >> a;
vector<vector<double>> origin = {
{0.5, 0.0, 0.0},
{0.0, 0.5, 0.0},
{0.0, 0.0, 0.5}
};
vector<vector<double>> rotation, result;
// Rotate only once
if(a < sqrt(2.0)) {
double x = asin(a / sqrt(2.0)) - M_PI / 4.0;
rotation = {
{1.0, 0.0, 0.0},
{0, cos(x), -1 * sin(x)},
{0, sin(x), cos(x)}
};
result = matmul(origin, rotation);
}
// Rotate 45 x-axis, then rotate y axis
else {
// double x = M_PI / 4.0;
double y = asin(a / sqrt(3.0)) - asin(sqrt(6.0) / 3);
rotation = {
{cos(y), 0, sin(y)},
{sin(y) / sqrt(2), sqrt(2) / 2, -1 * cos(y) / sqrt(2)},
{-1 * sin(y) / sqrt(2), sqrt(2) / 2, cos(y) / sqrt(2)}
};
result = matmul(origin, rotation);
}
cout << "Case #" << z + 1 << ':' << endl;
matprint(result);
}
return 0;
} | true |
14e25d5be6a24390f1086ce543c68b356dd07983 | C++ | lache/anyang | /client/samples/Cpp/HelloCpp/Classes/mdgen/data_reloader.h | UTF-8 | 2,341 | 2.734375 | 3 | [] | no_license | #pragma once
#define THREAD_SAFE_RELOADER 0
namespace data { ;
class data_reloader {
public:
virtual bool is_reloadable() = 0;
virtual void reload() = 0;
};
template <typename _Ty>
class data_referer {
public:
void add();
void release();
};
template <typename _Ty>
class data_reloader_impl : public data_reloader {
public:
virtual bool is_reloadable();
virtual void reload();
};
class data_depend_map {
public:
static data_depend_map& instance();
public:
void add(int index);
void release(int index);
bool is_depend(int index);
void clear();
data_depend_map();
~data_depend_map();
#if THREAD_SAFE_RELOADER
typedef boost::interprocess::interprocess_recursive_mutex mutex_type;
typedef boost::interprocess::scoped_lock<mutex_type> lock_type;
mutex_type mutex;
#endif
private:
void do_reload();
public:
typedef std::deque<data_reloader*> reloader_queue_t;
reloader_queue_t reloader_queue;
private:
static const int max_size = 1024;
int depend_map[max_size];
};
inline data_depend_map& data_depend_map::instance()
{
static data_depend_map _instance;
return _instance;
}
inline void data_depend_map::add(int index)
{
#if THREAD_SAFE_RELOADER
lock_type lock(mutex);
#endif
++depend_map[index];
}
inline void data_depend_map::release(int index)
{
#if THREAD_SAFE_RELOADER
lock_type lock(mutex);
#endif
--depend_map[index];
do_reload();
}
inline void data_depend_map::do_reload()
{
static bool reloading = false;
if (reloading)
return;
reloading = true;
while (!reloader_queue.empty()) {
data_reloader* reloader = reloader_queue.front();
if (reloader->is_reloadable()) {
reloader->reload();
reloader_queue.pop_front();
delete reloader;
} else break;
}
reloading = false;
}
inline bool data_depend_map::is_depend(int index)
{
return depend_map[index] != 0;
}
inline void data_depend_map::clear()
{
std::for_each(reloader_queue.begin(), reloader_queue.end(), [=] (data_reloader* reloader) {
delete reloader;
});
reloader_queue.clear();
}
inline data_depend_map::data_depend_map()
{
memset(depend_map, 0, sizeof(depend_map));
}
inline data_depend_map::~data_depend_map()
{
clear();
}
} | true |
845cd5cf74ef6ca8c3816580c00cee27ec64a979 | C++ | zldzksk1/OSU-CS325-Argorithm | /Portfolio/tetris3/Coordination.cpp | UTF-8 | 1,142 | 3.015625 | 3 | [] | no_license | #include "Coordination.hpp"
using namespace std;
int Coordination::GetX() const //return x coordination
{
return xpos;
}
int Coordination::GetY() const //return y coordination
{
return ypos;
}
void Coordination::SetX(int x) //set x and y coordination
{
xpos = x;
}
void Coordination::SetY(int y)
{
ypos = y;
}
Coordination Coordination::operator+(const Coordination&pt) // class opperator
{
return Coordination(xpos + pt.xpos, ypos + pt.ypos);
}
Coordination Coordination::operator-(const Coordination& pt)
{
return Coordination(xpos - pt.xpos, ypos - pt.ypos);
}
void Coordination::GotoXY(int x, int y)
{
COORD Pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos); //control cursor
}
void Coordination::GotoXY(Coordination pos)
{
GotoXY(pos.GetX(), pos.GetY());
}
Coordination Coordination::GetScreenpos(const Coordination &pos) //Change the array position to Screen Coordination
{
return Coordination(2 * pos.xpos + 2, (-1) * pos.ypos + 20); //Since the block size two bytes and the other char is 1bytes, for time 2 on X
} //if (-1) times to the block can be down from top | true |
0cd60b2ff7008cd34c0b96f5071d58473765b759 | C++ | Cybot101/HIT3172-CS1-Monopoly | /HIT3172-CS1-Monopoly/Player.cpp | UTF-8 | 1,264 | 3.296875 | 3 | [] | no_license | /*
HIT3172 - Object Orientated Programming C++
Case Study 1 :: Monopoly
Kyle Harris 9621121
http://github.com/Cybot101/HIT3172-CS1-Monopoly
**********************************************
Player - Implementation
*/
#include "Player.h"
#include <sstream>
/**
Creates a player object with a name.
@param string Player name
*/
Player::Player(std::string _aName)
{
_isOn = NULL;
_name = _aName;
}
Player::~Player(void)
{
}
/**
Performs player "move" operation.
Rolls dice, leaves current tile (if allowed) and move across board.
@param Dice* Dice object to roll
*/
void Player::move(Dice *_aDice)
{
// Roll of the dice
_aDice->roll();
if (_isOn != NULL) // Player is on a tile
{
_isOn->leave(this);
_isOn->move(this, _aDice, _aDice->get_total_value());
}
}
/**
Places the player on a particular Tile by letting the tile know it has landed on it.
*/
void Player::place_on(Tile *_aTile)
{
if (_aTile != NULL)
{
_isOn = _aTile;
_isOn->land(this);
}
}
/**
Public getter for tile player is currently on.
@return Tile* Tile player is currently on
*/
Tile *Player::on_tile()
{
return _isOn;
}
std::string Player::str()
{
std::stringstream desc;
desc << _name << " - Current tile: " << _isOn << " ";
return desc.str();
} | true |
b00d847052bea8031e8091053bb52b6dc6913185 | C++ | lhmouse/asteria | /test/ascii_numput_double.cpp | UTF-8 | 3,155 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | // This file is part of Asteria.
// Copyleft 2018 - 2023, LH_Mouse. All wrongs reserved.
#include "utils.hpp"
#include "../rocket/ascii_numput.hpp"
#include "../rocket/ascii_numget.hpp"
#include <float.h>
#include <math.h>
using namespace ::rocket;
int main()
{
ascii_numput nump;
ascii_numget numg;
char* eptr;
double value, t;
// go up to infinity
value = 1234567890123456789.0;
for(;;) {
// decimal plain
nump.put_DD(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// decimal scientific
nump.put_DED(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// hex plain
nump.put_XD(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// hex scientific
nump.put_XED(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// binary plain
nump.put_XD(value);
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// binary scientific
nump.put_XED(value);
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
if(value == HUGE_VAL)
break;
value *= 11;
}
// go down to zero
value = -1234567890123456789.0;
for(;;) {
// decimal plain
nump.put_DD(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// decimal scientific
nump.put_DED(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// hex plain
nump.put_XD(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// hex scientific
nump.put_XED(value);
ASTERIA_TEST_CHECK(::strtod(nump.begin(), &eptr) == value);
ASTERIA_TEST_CHECK(eptr == nump.end());
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// binary plain
nump.put_XD(value);
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
// binary scientific
nump.put_XED(value);
numg.get(t, nump.begin(), nump.size());
ASTERIA_TEST_CHECK(t == value);
if(value == 0)
break;
value /= 11;
}
}
| true |
f8eb7271c673f94559e0f95b369c458f62e11567 | C++ | OK-BOOMERS/ProjetFlou | /src/combat/Enemy.cpp | UTF-8 | 987 | 3.09375 | 3 | [] | no_license | //
// Created by pz on 05/05/2020.
//
#include <iostream>
#include "Enemy.h"
#include "Player.h"
combat::Enemy::Enemy() {
hp=100;
energy=200;
block=false;
}
int combat::Enemy::attack(){
srand (time(nullptr));
int damage = rand() % 10 + 10;
substractEnergy(80);
return damage;
}
void combat::Enemy::addEnergy(int i){
energy +=i;
if (energy>200){
energy=200;
}
}
void combat::Enemy::substractEnergy(int i){
energy-=i;
if(energy < 0){
energy=0;
}
}
void combat::Enemy::substractHP(int i) {
hp-=i;
if(hp < 0){
hp=0;
}
}
int combat::Enemy::getHP() {
return hp;
}
int combat::Enemy::getEnergy(){
return energy;
}
int combat::Enemy::makeDecision( float decisione ){
std::cout << std::endl << decisione << std::endl;
if(decisione <= 2){
addEnergy(50);
}
else if(decisione <= 4 ){
block = true;
}
else{
return attack();
}
return 0;
}
| true |
22e32190d7577b789877f41dd422582c6e78cb74 | C++ | mccabmic/dumbZoo | /Penguin.cpp | UTF-8 | 765 | 2.71875 | 3 | [] | no_license | /*************************
Author:Michael McCabe
Date: Janaury 19, 2018
IDE: Visual Studio
**************************/
#include "Penguin.hpp"
Penguin::Penguin() {
isFed = false;
setAge(1);
setCost(1000);
setBabies(5);
setFoodCost(base);
setPayoff(100);
}
Penguin::Penguin(int age) {
isFed = false;
setAge(age);
setCost(1000);
setBabies(5);
setFoodCost(base);
setPayoff(100);
}
Penguin& Penguin::operator=(const Penguin &right) {
if (this != &right) {
age = right.age;
cost = right.cost;
babies = right.babies;
baseFoodCost = right.baseFoodCost;
payoff = right.payoff;
}
return *this;
}
bool Penguin::checkHunger() {
return isFed;
}
void Penguin::setFed(bool hunger) {
isFed = hunger;
}
string Penguin::getSpecies() {
return species;
} | true |
2b4b75fa52fcf34792a3d517a86d7006cee15a39 | C++ | rmShoeb/OnlineCourses | /Udemy/Mastering Data Structures and Algorithms using C and C++/hashing-linear-probing.cpp | UTF-8 | 1,553 | 3.734375 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class LinearProbing
{
private:
int *hashTable;
bool *isThereAnyElement;
int numberOfKeys;
public:
LinearProbing(){
LinearProbing(50);
}
LinearProbing(int number_of_keys){
this->numberOfKeys = number_of_keys;
this->hashTable = new int[number_of_keys];
this->isThereAnyElement = new bool[number_of_keys];
for(int i=0; i<number_of_keys; i++) isThereAnyElement[i] = false;
}
~LinearProbing(){delete []hashTable;}
int hashKey(int data){return (data%this->numberOfKeys);}
void insert(int data){
int i=0;
int index;
while(true){
index = this->hashKey(this->hashKey(data)+i);
if(!this->isThereAnyElement[index]){
this->hashTable[index] = data;
this->isThereAnyElement[index] = true;
break;
}else i++;
}
return;
}
bool search(int data){
cout << data << endl;
int i=0;
int index;
while(true){
index = this->hashKey(this->hashKey(data)+i);
if(!this->isThereAnyElement[index]) return false;
else{
if(this->hashTable[index] == data) return true;
}
i++;
}
}
void printTable(void){
int index;
for(index=0; index<this->numberOfKeys; index++){
if(this->isThereAnyElement[index]) printf("%d\t", this->hashTable[index]);
else printf("NULL\t");
}
printf("\n");
return;
}
};
int main(int argc, char const *argv[])
{
srand(time(0));
LinearProbing arr(100);
for(int i=0; i<50; i++){
arr.insert(rand()%51);
}
arr.printTable();
cout << arr.search(rand()%51) << endl;
return 0;
} | true |
97bbf33d1f745c949f007da32f5a30b793c67752 | C++ | kevinkraft/RTS_3 | /include/ArgContainer.h | UTF-8 | 2,143 | 2.703125 | 3 | [
"MIT"
] | permissive | #ifndef ARGCONTAINER_H_
#define ARGCONTAINER_H_
#include <string>
#include <iostream>
//#include "Menu.h"
class Menu;
class InfoMenu;
class Action;
class Entity;
class EntityHP;
class TextBox;
class SelectionMenu;
class ExchangeMenu;
class Resource;
class Construction;
class ArgContainer
{
public:
ArgContainer()
{
mPosX = 0.;
mPosY = 0.;
mSelectedEntity = nullptr;
mTargetEntity = nullptr;
mMenu = nullptr;
mTextBox = nullptr;
mInfoMenu = nullptr;
mExchangeMenu = nullptr;
mInt = 0;
mResource = nullptr;
mConstruction = nullptr;
}
virtual ~ArgContainer()
{}
void setConstruction(Construction * c)
{
mConstruction = c;
}
void setInfoMenu(InfoMenu * im)
{
mInfoMenu = im;
}
void setExchangeMenu(ExchangeMenu * em)
{
mExchangeMenu = em;
}
void setInt( int i)
{
mInt = i;
}
void setMenu(Menu * m)
{
mMenu = m;
}
void setPosX(float x)
{
mPosX = x;
}
void setPosY(float y)
{
mPosY = y;
}
void setResource(Resource * res)
{
mResource = res;
}
void setSelectedEntity(Entity * entity)
{
mSelectedEntity = entity;
}
void setSelectionMenu(SelectionMenu * sm)
{
mSelectionMenu = sm;
}
void setTargetEntity(Entity * entity)
{
mTargetEntity = entity;
}
void setTargetEntityHP(EntityHP * entityhp)
{
mTargetEntityHP = entityhp;
}
float mPosX;
float mPosY;
Entity * mSelectedEntity;
Entity * mTargetEntity;
EntityHP * mTargetEntityHP;
Resource * mResource;
Menu * mMenu;
TextBox * mTextBox;
InfoMenu * mInfoMenu;
ExchangeMenu * mExchangeMenu;
int mInt;
SelectionMenu * mSelectionMenu;
Construction * mConstruction;
};
class ReturnContainer
{
public:
ReturnContainer(int outcome, Action * act)
{
mAction = act;
mOutcome = outcome;
}
ReturnContainer()
: ReturnContainer(0, nullptr)
{}
virtual ~ReturnContainer()
{}
void setAction(Action * act)
{
mAction = act;
}
void setOutcome(int b)
{
mOutcome = b;
}
Action * mAction;
int mOutcome;
};
#endif
| true |
1faf2e8a68d03bfd640ae793eac8feeb2dee7d6d | C++ | Honepa/projects | /kvadric/big_knok/auto_knok/auto_knok.ino | UTF-8 | 4,278 | 2.546875 | 3 | [] | no_license | #define INIT 0
#define CMP_TURN 1
#define CMP_ON 2
#define EXPECT_KNOK 3
#define ALL_OFF 4
#define ARD_OFF 5
#define LED_PWR_OK 3
#define LED_PWR_ON 2
#define LED_CMP_ON 4
#define knok A1
#define key A0
#define big_ard A7
#define rele_mass A6
#define rele_cmp A5
float t = 0;
void setup()
{
pinMode(LED_PWR_OK, OUTPUT);
pinMode(LED_PWR_ON, OUTPUT);
pinMode(LED_CMP_ON, OUTPUT);
pinMode(knok, INPUT);
pinMode(key, INPUT);
pinMode(big_ard, OUTPUT);
pinMode(rele_mass, OUTPUT);
pinMode(rele_cmp, OUTPUT);
t = millis();
Serial.begin(9600);
digitalWrite(rele_mass, 1);
digitalWrite(rele_cmp, 1);
digitalWrite(LED_PWR_OK, 1);
digitalWrite(9, 0); //не трогать, dont touch, nicht!
}
int state = 0;
int key_on, knok_on = 0;
String arr_st[7] = {"INIT", "CMP_TURN", "CMP_ON", "EXPECT_KNOK", "ALL_OFF", "ARD_OFF"};
void loop()
{
key_on = is_key();
knok_on = is_knok();
Serial.print(arr_st[state]);
Serial.print(" ");
Serial.print(key_on);
Serial.print(" ");
Serial.print(knok_on);
Serial.println(" ");
switch (state)
{
case INIT:
{
digitalWrite(LED_PWR_OK, 1);
if ((key_on == 1) and (knok_on == 1))
{
digitalWrite(LED_PWR_ON, 1);
digitalWrite(rele_mass, 0);
t = millis();
state = CMP_TURN;
}
else if (knok_on == 3)
{
digitalWrite(rele_mass, 1);
}
break;
}
case CMP_TURN:
{
digitalWrite(rele_cmp, 0);
if ((millis() - t > 31000) and (knok_on == 1))
{
digitalWrite(LED_CMP_ON, 1);
state = EXPECT_KNOK;
}
else if (knok_on == 3)
{
digitalWrite(rele_mass, 1);
digitalWrite(rele_cmp, 1);
digitalWrite(LED_CMP_ON, 0);
digitalWrite(LED_PWR_ON, 0);
state = INIT;
}
break;
}
case EXPECT_KNOK:
{
if (knok_on == 2)
{
t = millis();
state = ARD_OFF;
}
else if (knok_on == 3)
{
digitalWrite(LED_CMP_ON, 0);
digitalWrite(LED_PWR_ON, 0);
state = ALL_OFF;
}
else if (key_on == 1)
{
int k = 0;
while (k < 25)
{
for (int i = 2; i < 5; i++)
{
digitalWrite(i, 1);
delay(100);
digitalWrite(i, 0);
}
k++;
}
k = 0;
digitalWrite(LED_PWR_ON, 1);
digitalWrite(LED_CMP_ON, 1);
digitalWrite(LED_PWR_OK, 1);
state = EXPECT_KNOK;
}
break;
}
case ARD_OFF:
{
digitalWrite(big_ard, 1);
if (millis() - t > 31000)
{
digitalWrite(LED_CMP_ON, 0);
digitalWrite(LED_PWR_ON, 0);
digitalWrite(rele_mass, 1);
digitalWrite(rele_cmp, 1);
state = INIT;
}
break;
}
case ALL_OFF:
{
digitalWrite(rele_mass, 1);
digitalWrite(rele_cmp, 1);
state = INIT;
break;
}
}
}
int is_key()
{
int code_key = 0;
int is_key = 0;
if (digitalRead(key))
{
for (int i = 1; i <= 1000; i++)
{
is_key += digitalRead(key);
delay(1);
}
if (is_key > 800)
{
code_key = 1;
}
else
{
code_key = 0;
}
}
else
{
code_key = 0;
}
return code_key;
}
int is_knok()
{
int code_knok = 1;
int is_knok = 0;
if (digitalRead(knok) == 0)
{
for (int i = 1; i <= 1000; i++)
{
is_knok += !digitalRead(knok);
delay(1);
}
if (is_knok > 150)
{
if (digitalRead(knok) == 0)
{
for (int i = 1; i <= 3000; i++)
{
is_knok += !digitalRead(knok);
delay(1);
}
if (is_knok > 3800)
{
code_knok = 3;
is_knok = 0;
}
else
{
code_knok = 1;
is_knok = 0;
}
}
else
{
code_knok = 2;
}
}
else
{
code_knok = 1;
is_knok = 0;
}
}
else
{
code_knok = 1;
}
return code_knok;
}
| true |
f10523dc62ac63fd658730c5e4b67c9318048ead | C++ | thiagoclassen/TrieTree | /src/TrieTree.h | UTF-8 | 610 | 2.59375 | 3 | [] | no_license | /*
* TrieTree.h
*
* Created on: 18 de jun de 2016
* Author: Thiago
*/
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <cctype>
#include <iostream>
#include <list>
#include <iomanip>
#ifndef TRIETREE_H_
#define TRIETREE_H_
#define TAM (26)
struct TrieNode
{
struct TrieNode *children[TAM];
bool folha;
int nr;
std::list<int> *pos;
}typedef TrieNode;
TrieNode *getNode(void);
void insert(TrieNode *root, const char *key, int pos);
bool search(TrieNode *root, const char *key);
int getPos(char l);
void traverse(TrieNode* node, std::string key);
#endif /* TRIETREE_H_ */
| true |
7dfaed8a8da4ad42c8e38ebdecb6e0e744691a83 | C++ | sturgle/LeetCode | /3Sum.cpp | UTF-8 | 1,363 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > result;
sort(num.begin(), num.end());
int N = num.size();
for (int i = 0; i < N; i++)
{
if (i != 0 && num[i] == num[i - 1])
continue;
int left = i + 1;
int right = N - 1;
while (left < right)
{
if (num[left] + num[right] == -num[i])
{
vector<int> tmp;
tmp.push_back(num[i]);
tmp.push_back(num[left]);
tmp.push_back(num[right]);
result.push_back(tmp);
left++;
right--;
while (left < right && num[left] == num[left - 1]) left++;
while (left < right && num[right] == num[right + 1]) right--;
}
else if (num[left] + num[right] < -num[i])
{
left++;
while (left < right && num[left] == num[left - 1]) left++;
}
else
{
right--;
while (left < right && num[right] == num[right + 1]) right--;
}
}
}
return result;
}
};
| true |
c563d6c670266dc55aa67d7669452cb5a339daae | C++ | JJMyring/NewEngineAgain---Copy-2- | /vendor/IMAT3904/include/include/independent/rendering/cameras/camera.h | UTF-8 | 701 | 2.828125 | 3 | [] | no_license | /** \file camera.h
*/
#pragma once
#include <glm/glm.hpp>
namespace Engine
{
/** \class Camera Abstract base class for a camera*/
class Camera
{
protected:
glm::mat4 m_projection; //!< Projection matrix
glm::mat4 m_view; //!< View matric
glm::mat4 m_viewProjection; //!< View projection matrix
public:
virtual void updateView() = 0; //!< Called by a controller to update the view matrix
const glm::mat4& getProjection() { return m_projection; } //!< Accessor for the projection matrix
const glm::mat4& getView() { return m_view; } //!< Accessor for the viewmatrix
const glm::mat4& getViewProjection() { return m_viewProjection; } //!< Accessor for the view projection matrix
};
} | true |
b8a527112111aafc5a0a79f0a7ba519452c1dbda | C++ | hegoimanzano/KIMERA | /src/Atom.cpp | UTF-8 | 14,086 | 3 | 3 | [
"MIT"
] | permissive | #include "Atom.h"
Atom::Atom( long long int id_, double x_, double y_, double z_,long long int type_, bool insurface_)
{
id = new long long int;
x = new double;
y = new double;
z = new double;
atom_type = new string;
type = new long long int;
insurface = new bool;
mass=new double;
*id=id_;
*x=x_;
*y=y_;
*z=z_;
*type=type_;
*insurface=insurface_;
*mass=1.0;
}
Atom::Atom( long long int id_, double x_, double y_, double z_, string atom_type_, bool insurface_)
{
id = new long long int;
x = new double;
y = new double;
z = new double;
type = new long long int;
atom_type = new string;
insurface = new bool;
mass=new double;
*type=NORMAL;
*id=id_;
*x=x_;
*y=y_;
*z=z_;
*atom_type=atom_type_;
*insurface=insurface_;
*mass=1.0;
}
Atom::~Atom()
{
delete x;
delete y;
delete z;
delete type;
delete atom_type;
delete id;
delete insurface;
delete mass;
}
void Atom::set_id( long long int id_)
{
*id=id_;
}
long long int Atom::get_id()
{
return *id;
}
void Atom::set_mass(double mass_)
{
*mass=mass_;
}
double Atom::get_mass()
{
return *mass;
}
void Atom::set_x(double x_)
{
*x=x_;
}
double Atom::get_x()
{
return *x;
}
void Atom::set_y(double y_)
{
*y=y_;
}
double Atom::get_y()
{
return *y;
}
void Atom::set_z(double z_)
{
*z=z_;
}
double Atom::get_z()
{
return *z;
}
void Atom::set_type(long long int type_)
{
*type=type_;
}
long long int Atom::get_type()
{
return *type;
}
void Atom::set_atom_type(string atom_type_)
{
*atom_type=atom_type_;
}
string Atom::get_atom_type()
{
return *atom_type;
}
void Atom::set_insurface(bool insurface_)
{
*insurface=insurface_;
}
bool Atom::get_insurface()
{
return *insurface;
}
double Atom::get_distance(Atom *otheratom)
{
double otheratomx=otheratom->get_x();
double otheratomy=otheratom->get_y();
double otheratomz=otheratom->get_z();
double thisatomx=get_x();
double thisatomy=get_y();
double thisatomz=get_z();
double distance=sqrt((otheratomx-thisatomx)*(otheratomx-thisatomx)+
(otheratomy-thisatomy)*(otheratomy-thisatomy)+
(otheratomz-thisatomz)*(otheratomz-thisatomz));
return distance;
}
long long int Atom::add_neighbour(Atom *neighbour)
{
neighbours.push_back(neighbour);
return 0;
}
Atom* Atom::get_neighbour(long long int pos_)
{
return neighbours.at(pos_);
}
long long int Atom::get_size_neighbour()
{
return neighbours.size();
}
long long int Atom::rm_neighbour( long long int id)
{
for ( long long int i=0; i<(long long int)neighbours.size(); i++)
{
if (id == neighbours.at(i)->get_id())
{
neighbours.erase(neighbours.begin()+i);
return 0;
}
}
return 1;
}
long long int Atom::rm_allneighbour()
{
neighbours.clear();
return 0;
}
long long int Atom::get_id_neighbour(long long int pos_)
{
return neighbours.at(pos_)->get_id();
}
bool Atom::get_insurface_neighbour(long long int pos_)
{
return neighbours.at(pos_)->get_insurface();
}
double Atom::get_x_neighbour(long long int pos_)
{
return neighbours.at(pos_)->get_x();
}
double Atom::get_y_neighbour(long long int pos_)
{
return neighbours.at(pos_)->get_y();
}
double Atom::get_z_neighbour(long long int pos_)
{
return neighbours.at(pos_)->get_z();
}
long long int Atom::get_type_neighbour(long long int pos_)
{
return neighbours.at(pos_)->get_type();
}
vector<Atom*> Atom::get_neighbours()
{
return neighbours;
}
vector<double> Atom::get_distances_to_neighbours()
{
return distances_to_neighbours;
}
long long int Atom::add_distance_to_neighbours(double distance_)
{
distances_to_neighbours.push_back(distance_);
return distances_to_neighbours.size();
}
double Atom::get_distance_to_neighbours_by_pos(long long int pos_)
{
return distances_to_neighbours.at(pos_);
}
long long int Atom::set_neigh_record() //lo estamos llamando dos veces.. que pasa si lo llamamos dos veces??!! pues que estamos metiendo el doble de vecinos.. \clap
{
long long int sizeneighbours=neighbours.size();
bool any=false;
for (long long int i=0; i < sizeneighbours; i++)
{
long long int sizeneighrecord=neigh_record.size();
for (long long int j=0; j< sizeneighrecord;j++)
{
if (neighbours.at(i)->get_atom_type().compare(neigh_record.at(j).get_type())==0 &&
Util::isEqualDistances(distances_to_neighbours.at(i),neigh_record.at(j).get_distance()))
{
neigh_record.at(j).increment_number_by_1();
any=true;
break;
}
}
if (!any)
{
//create a new record
Record record1=Record(neighbours.at(i)->get_atom_type(),distances_to_neighbours.at(i));
//add
neigh_record.push_back(record1);
}
any=false;
}
return neigh_record.size();
}
vector<Record> Atom::get_neigh_record()
{
return neigh_record;
}
long long int Atom::reduce_record_count_by_1(string type_, double distance_)
{
long long int count;
long long int sizeneighrecord=neigh_record.size();
for (long long int i=0; i< sizeneighrecord;i++)
{
if (type_.compare(neigh_record.at(i).get_type())==0 &&
Util::isEqualDistances(distance_,neigh_record.at(i).get_distance()))
{
count = neigh_record.at(i).reduce_number_by_1();
if (count <0)
{
return 2; // if size smaller than 0
}
return 0;
}
}
return 1; //not finded
}
long long int Atom::rm_neighbour_and_record(long long int id_neigh)
{
double distance_to_neigh=0.0;
string type_neigh;
for ( long long int i=0; i<(long long int)neighbours.size(); i++)
{
if (id_neigh == neighbours.at(i)->get_id())
{
distance_to_neigh=get_distances_to_neighbours().at(i);
type_neigh=neighbours.at(i)->get_atom_type();
reduce_record_count_by_1( type_neigh , distance_to_neigh);
distances_to_neighbours.erase(distances_to_neighbours.begin()+i);
neighbours.erase(neighbours.begin()+i);
if (linked.size()>0)
{
linked.erase(linked.begin()+i);
linked_type.erase(linked_type.begin()+i);
}
return 0;
}
}
return 1;
}
long long int Atom::rm_neighbour_and_record_both_directions(long long int id_neigh) //id of the atom which is dissolved
{
double distance_to_neigh=0.0;
string type_neigh;
string this_type;
long long int thisid=get_id();
for ( long long int i=0; i<(long long int)neighbours.size(); i++)
{
if (id_neigh == neighbours.at(i)->get_id())
{
distance_to_neigh=get_distances_to_neighbours().at(i);
type_neigh=neighbours.at(i)->get_atom_type();
reduce_record_count_by_1( type_neigh , distance_to_neigh);
distances_to_neighbours.erase(distances_to_neighbours.begin()+i);
neighbours.at(i)->rm_neighbour_and_record(thisid);
neighbours.erase(neighbours.begin()+i);
if (linked.size()>0)
{
linked.erase(linked.begin()+i);
linked_type.erase(linked_type.begin()+i);
}
return 0;
}
}
return 1;
}
long long int Atom::get_number(string type_, double distance_)
{
long long int size_neigh_record=neigh_record.size();
for (long long int i=0;i<size_neigh_record;i++)
{
if (neigh_record.at(i).get_type().compare(type_)==0 && Util::isEqualDistances(distance_,neigh_record.at(i).get_distance()))
{
return neigh_record.at(i).get_number();
}
}
cout<<"error in Atom::get_number(), it is possible that the definition of the events is not correct, otherwise, please contact the authors"<<endl;
return 0;
}
vector<Atom*> Atom::get_affected()
{
return affected;
}
long long int Atom::add_affected(Atom *affected_)
{
affected.push_back(affected_);
return affected.size();
}
long long int Atom::rm_affected( long long int id)
{
for ( long long int i=0; i<(long long int)affected.size(); i++)
{
if (id == affected.at(i)->get_id())
{
affected.erase(affected.begin()+i);
return 0;
}
}
return 1;
}
vector<vector<Atom*>> Atom::get_linked()
{
return linked;
}
void Atom::add_void_vector_in_linked()
{
vector<Atom*> emptyvector;
linked.push_back(emptyvector);
}
void Atom::remove_neighbours_with_out_linkeds()
{
/**
for(long long int joder=0;joder<linked_type.size();joder++)
{
cout<<"neighbours.at(joder)->get_type(): "<<distances_to_neighbours.at(joder);
cout<<endl;
cout<<"linked.at(joder).size(): "<<linked.at(joder).size();
cout<<endl;
cout<<"linked_type.at(joder): "<<linked_type.at(joder);
cout<<endl;
cout<<endl;
}
cout<<endl<<endl<<endl;;
*/
long long int sizelinkedtype=linked_type.size();
if (sizelinkedtype !=0)
{
if (linked.at(sizelinkedtype-1).size()==0)
{
distances_to_neighbours.erase(distances_to_neighbours.begin()+(sizelinkedtype-1));
neighbours.erase(neighbours.begin()+(sizelinkedtype-1));
linked.erase(linked.begin()+(sizelinkedtype-1));
linked_type.erase(linked_type.begin()+(sizelinkedtype-1));
}
}
}
long long int Atom::add_linked_to(Atom * linked_, long long int pos_)
{
linked.at(pos_).push_back(linked_);
return linked.at(pos_).size();
}
long long int Atom::rm_linked(long long int pos_)
{
linked.erase(linked.begin()+pos_);
return linked.size();
}
bool Atom::is_bulk(vector<long long int> max_to_bulk, vector<string>types_, vector<double>distances_)
{
long long int sizetypes=types_.size();
long long int sizerecord=neigh_record.size();
for (long long int i=0; i<sizetypes ;i++)
{
if (max_to_bulk.at(i)!=0)
{
for (long long int j=0;j<sizerecord;j++)
{
if (types_.at(i).compare(neigh_record.at(j).get_type())==0 && Util::isEqual(distances_.at(i),neigh_record.at(j).get_distance())
&& get_number(types_.at(i),distances_.at(i))==max_to_bulk.at(i))
{
return true;
}
}
}
}
return false;
}
bool Atom::is_bulk_with_links(vector<long long int> max_to_bulk, vector<string> types_, vector<double> distances_, vector<Linked_neighbour> link_vector)
{
long long int sizetypes=types_.size();
for (long long int i=0; i<sizetypes ;i++)
{
if (max_to_bulk.at(i)!=0)
{
long long int typelink_from_event_def=link_vector.at(i).get_type();
long long int truenumber= get_number_complex(types_.at(i),distances_.at(i),typelink_from_event_def);
if (truenumber<max_to_bulk.at(i)) return false;
}
}
return true;
}
long long int Atom::get_number_complex( string type_event_definition, double distance_event_definition, long long int typelink_from_event_def)
{
long long int truenumber=0;
//#pragma omp parallel for shared (truenumber) //este aumenta mucho el tiempo de sim
for(long long int s=0; s<(long long int)linked.size() ;s++)
{
long long int type = linked_type.at(s);
double distance_to_neight=distances_to_neighbours.at(s);
string type_neight=neighbours.at(s)->get_atom_type();
if (type==NO_LINKED_TYPE && typelink_from_event_def==NO_LINKED_TYPE && type_event_definition.compare(type_neight)==0 && Util::isEqualDistances(distance_event_definition,distance_to_neight) )
{
truenumber++;
}
if (type == LINKED_TYPE_NORMAL && typelink_from_event_def==LINKED_TYPE_NORMAL && type_event_definition.compare(type_neight)==0 && Util::isEqualDistances(distance_event_definition,distance_to_neight) )
{
//comprobamos que los linked que tiene el mismo id correspondiente, estan (todos ellos) tenemos que seleccionar por distancia y tipo
vector<Atom*> inlinkeds= linked.at(s);
bool enter=true;
for (long long int l=0;l<(long long int)inlinkeds.size() ;l++)
{
if (inlinkeds.at(l)->get_type()!=NORMAL)
{
enter=false; break;
}
}
if(enter) truenumber++;
}
if (type == LINKED_TYPE_DISSOLVED && typelink_from_event_def==LINKED_TYPE_DISSOLVED && type_event_definition.compare(type_neight)==0 && Util::isEqualDistances(distance_event_definition,distance_to_neight) )
{
//comprobamos que los linked que tiene el mismo id correspondiente, estan (todos ellos)
vector<Atom*> inlinkeds= linked.at(s);
bool enter=true;
for (long long int l=0;l<(long long int)inlinkeds.size() ;l++)
{
if (inlinkeds.at(l)->get_type()!=DISSOLVED && inlinkeds.at(l)->get_type()!=REMOVED)
{
enter=false; break;
}
}
if(enter) truenumber++;
}
}
return truenumber;
}
| true |
42cccfa828b8dbb55707c732c701cfd2a7881a81 | C++ | imSarfaroz/Algorithms-Analysis-2021 | /lab-06/p02/main.cpp | UTF-8 | 1,506 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <string>
#include <stdexcept>
using namespace std;
enum class Color
{
White,
Red,
Black
};
void dfs(int v, const vector<vector<int>> &graph, vector<Color> &colors, vector<int> &order)
{
colors[v] = Color::Red;
for (auto &e : graph[v])
{
if(colors[e] == Color::Red)
{
throw runtime_error("Error: input is not a Directed Acyclic graph. Vertex: " + to_string(e + 1));
}
if (colors[e] == Color::White)
{
dfs(e, graph, colors, order);
}
}
order.push_back(v);
colors[v] = Color::Black;
}
int main()
try
{
string line;
getline(cin, line);
int nVertices = stoi(line);
vector<vector<int>> graph(nVertices);
for (int i = 0; i < nVertices; i++)
{
getline(cin, line);
if (line != "-")
{
istringstream sinp(line);
for (int v; sinp >> v;)
{
graph[i].push_back(v - 1);
}
}
}
vector<Color> colors(nVertices, Color::White);
vector<int> order;
for (int i = 0; i < graph.size(); i++)
{
if (colors[i] == Color::White)
{
dfs(i, graph, colors, order);
}
}
reverse(order.begin(), order.end());
for (int e : order)
{
cout << " " << e + 1;
}
cout << "\n";
}
catch (runtime_error& e){
cerr << e.what() << endl;
}
| true |
cc9f1bda21ad98b81f0df986f144e5a4ad109f8f | C++ | nicolgorostiaga/Application_Stack | /LStack.cpp | ISO-8859-2 | 5,000 | 3.71875 | 4 | [] | no_license | //--- LStack.cpp -------------------------------------------------
#include <new>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
#include "LStack.h"
//--- Definition of Stack constructor
Stack::Stack(){myTop = NULL;}
//--- Definition of Stack copy constructor
Stack::Stack(const Stack & original)
{
myTop = NULL;
if (!original.empty())
{
// Copy first node
myTop = new Stack::Node(original.top());
// Set pointers to run through the stacks linked lists
Stack::NodePointer lastPtr = myTop,
origPtr = original.myTop->next;
while (origPtr != NULL)
{
lastPtr->next = new Stack::Node(origPtr->data);
lastPtr = lastPtr->next;
origPtr = origPtr->next;
}
}
}// end copy constructor
//--- Definition of Stack destructor
Stack::~Stack()
{
// Set pointers to run through the stack
Stack::NodePointer currPtr = myTop; // node to be deallocated
while (currPtr != NULL)
{
myTop = myTop->next;
delete currPtr;
currPtr = myTop;
}
}//end destructor
//--- Definition of assignment operator
const Stack & Stack::operator=(const Stack & rightHandSide)
{
if (this != &rightHandSide) // check that not st = st
{
this->~Stack(); // destroy current linked list
// if (rightHandSide.empty()) // empty stack
// myTop = 0;
//else
//{ // copy rightHandSide's list
// Copy first node
myTop = new Stack::Node(rightHandSide.top());
// Set pointers to run through the stacks' linked lists
Stack::NodePointer lastPtr = myTop,
rhsPtr = rightHandSide.myTop->next;
while (rhsPtr != 0)
{
lastPtr->next = new Stack::Node(rhsPtr->data);
lastPtr = lastPtr->next;
rhsPtr = rhsPtr->next;
}
//}
}
return *this;
}// end overloaded assignment operator
//--- Definition of empty()
bool Stack::empty() const
{
return (myTop == NULL);
}// end empty
//--- Definition of push()
void Stack::push(const StackElement & value)
{
Stack::NodePointer top = new Stack::Node(value);
top->next = myTop;
myTop = top;
//myTop = new Stack::Node(value, myTop);
}// end push
//--- Definition of display()
void Stack::display(ostream & out) const
{
Stack::NodePointer ptr;
for (ptr = myTop; ptr != 0; ptr = ptr->next)
out << ptr->data << endl;
}// end display
//--- Definition of top()
StackElement Stack::top() const
{
if (!empty())
return (myTop->data);
else
{
cerr << "*** Stack is empty "
" -- returning garbage ***\n";
StackElement * temp = new(StackElement);
StackElement garbage = *temp; // "Garbage" value
delete temp;
return garbage;
}
}// end top
//--- Definition of pop()
void Stack::pop()
{
if (!empty())
{
Stack::NodePointer ptr = myTop;
myTop = myTop->next;
delete ptr;
}
else
cerr << "*** Stack is empty -- can't remove a value ***\n";
}// end pop
int Stack::performOperation(char symbol, int operand1, int operand2) {
switch (symbol) {
case '+': return operand2 + operand1;
case '-':return operand2 - operand1;
case '*':return operand2 * operand1;
case '/':return operand2 / operand1;
default: return -1;// if operator is not found.
}
}
bool Stack::isNum(const char &input) {
if (input >= '0' && input <= '9')return true;
return false;
}
bool Stack::isOperator(const char &input) {
switch (input) {
case '+':return true;
case '-':return true;
case '*':return true;
case '/':return true;
}
return false;
}
void Stack::checkOperand(const int &input,const int &counter) {
if (!isOperator(input) && counter < 2) {
cout << "Error - malformed postfix expression." << endl;
exit(1107);
}
}
void Stack::postFixExpression(string &input) {
Stack s;
int result;
for (int unsigned i = 0; i < input.length(); i++) {
//if (input.at(i) == ' ')continue;// skip over space
if (isOperator(input.at(i))) {
cout << "\nToken: " << input.at(i) << " ";
int operand1 = s.top();
checkOperand(operand1, i);
cout << "Pop " << s.top() << " ";
s.pop();
int operand2 = s.top();
checkOperand(operand2, i);
cout << "Pop " << s.top() << " ";
s.pop();
result = performOperation(input.at(i), operand1, operand2);
if (result < 0)
cout << "error - malformed postfix expression." << endl;
else {
s.push(result);
cout << "Push " << result << endl;
}
}
//cout << "error - malformed postfix expression." << endl;
//exit(1107);
else if(isNum(input.at(i))){
s.push(input.at(i) - '0');
cout << "\nToken = " << input.at(i) << " ";
cout << "Push " << s.top() << endl;
}
else {
cout << "\nToken = " << input.at(i) << " ";
cout << "Pop " << result << endl;
exit(1107);
}
}//end for
}
| true |
4f4df4c359c3ee29295a5fd29eaefc1c751a7b82 | C++ | sibirbil/PMBSolve | /cpp/openmp/rosenbrock_solver.cpp | UTF-8 | 1,766 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <random>
#include "pmb_driver.hpp"
#include "common.h"
using namespace std;
struct Rosenbrock {
int n;
Rosenbrock(int n) : n(n) {}
void operator()(opt_prec_t* x, opt_prec_t &f, opt_prec_t* g) {
f = 0.0;
for (int i=0; i<n/2; i++) {
f += 100.0*pow(x[2*i+1] - pow(x[2*i], 2.0), 2.0) + pow((1.0 - x[2*i]), 2.0);
}
g[0] = -400.0*x[0]*(x[1] - pow(x[0], 2.0)) - 2.0*(1.0 - x[0]);
for (int i=1; i<n-1; i++) {
g[i] = 200.0*(x[i] - pow(x[i-1], 2.0)) - 400.0*x[i]*(x[i+1] - pow(x[i], 2.0)) - 2.0*(1.0-x[i]);
}
g[n-1] = 200.0*(x[n-1] - pow(x[n-2], 2.0));
}
};
int main(int argc, char * argv[]) {
if(argc != 2) {
cout << "Usage: executable dimension" << endl;
return 0;
}
int n = atoi(argv[1]);
Rosenbrock fun(n);
//initial solution
std::random_device r;
std::default_random_engine eng(r());
std::uniform_real_distribution<> unif(5, 15);
opt_prec_t* x_0 = new opt_prec_t[n];
for (int i = 0; i < n; i++) {
x_0[i] = unif(eng);
}
//options
Options options;
options.gtol = 1e-05;
options.maxiter = 500;
options.maxinneriter = 100;
options.M = 5;
options.display = true;
options.history = true;
Output* output;
pmb_driver<Rosenbrock>(x_0, options, output, fun);
cout << "Exit: " << output->exit << endl;
cout << "Fval: " << output->fval << endl;
opt_prec_t ngf = fabs(output->g[0]);
for (int i = 1; i < n; i++) {
ngf = max(ngf, fabs(output->g[i]));
}
cout << "Norm: " << ngf << endl;
cout << "Iterations: " << output->niter << endl;
cout << "Evaluations: " << output->fcalls << endl;
cout << "Models built: " << output->nmbs << endl;
cout << "Time Spent in seconds: " << output->time << endl;
return 0;
}
| true |
b9b553f9bbaa2d7a442646c3835bf085dcae436f | C++ | dkhonker/sysu | /数据结构/数据结构实验课文件/EXP6-EXAM01/EX6学生代码/20354032/task1.cpp | ISO-8859-7 | 728 | 2.96875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
typedef struct Queue{
char* base;
int front;
int rear;
}Queue;
int main()
{
//ն
Queue Q;
int m,n;
int num;
char s;
char null;
int count = 0;
int i;
scanf("%d%d",&m,&n);
Q.base = (char*)malloc(m*sizeof(char));
Q.front = 0;
Q.rear = 0;
while(((Q.rear-Q.front+1+m)%m!=m)&&(count!=n))
{
count = count+1;
scanf("%d",&num);
scanf("%c",&s);
if(num==1)
{
scanf("%c",&s);
Q.base[Q.rear] = s;
Q.rear = (Q.rear+1)%m;
printf("%d %d\n",Q.front,Q.rear);
}
else if(num==2)
{
Q.front = Q.front+1;
printf("%d %d\n",Q.front,Q.rear);
}
}
for(int i=Q.front;i<Q.front+count-1;i++)
{
printf("%c",Q.base[i]);
}
return 0;
}
| true |
888ff67b647c2a9f8c4166a6fa11d29912835eb4 | C++ | mirrzamustafa/OpenGL | /Application.cpp | UTF-8 | 3,234 | 2.875 | 3 | [] | no_license | #include<GL/glew.h>
#include<GLFW/glfw3.h>
#include<iostream>
static unsigned int CompileShader(unsigned int type, const std::string& source)
{
unsigned int id = glCreateShader(type);
const char * str = &source[0];
glShaderSource(id, 1, &str, nullptr);
glCompileShader(id);
// only Error Handling below
int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
int length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
char* message = (char*)alloca(length * sizeof(char));
glGetShaderInfoLog(id, length, &length, message);
std::cout << "Failed To Compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << " Shader !" << std::endl;
std::cout << message << std::endl;
glDeleteShader(id);
return 0;
}
// till here
return id;
}
static unsigned int CreateShader(const std::string& vertexShader, const std::string& fragmentShader)
{
unsigned int program = glCreateProgram();
unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vs);
glDeleteShader(fs);
return program;
}
int main()
{
GLFWwindow * window;
glfwInit();
if (glfwInit())
{
std::cout << "GLFW WORKS" << std::endl;
}
if (!glfwInit())
{
return -1;
}
window = glfwCreateWindow(640, 380, "Open GL Window", NULL, NULL);
if (!window)
{
return -1;
}
glfwMakeContextCurrent(window);
glewInit();
if (glewInit() == GLEW_OK)
{
std::cout << "GLEW WORKS" << std::endl;
std::cout << glGetString(GL_VERSION) << std::endl;
}
float positions[12] = {
-0.5f,0.5f, //0
-0.5f,-0.5f, //1
0.5f,-0.5f, //2
0.5f,0.5f //3
};
unsigned int buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
/* I changed it 6 to 4 */
glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(float), positions, GL_STATIC_DRAW);
unsigned int indices[] = {
0 , 1 , 2,
3 , 2 , 0
};
unsigned int ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * 2 * sizeof(unsigned int), indices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
std::string vertexShader1 =
"#version 330 core\n"
"\n"
"layout(location = 0) in vec4 position;"
"\n"
"void main()\n"
"{\n"
" gl_Position = position;\n"
"}\n";
std::string fragmentShader1 =
"#version 330 core\n"
"\n"
"layout(location = 0) out vec4 color;"
"\n"
"void main()\n"
"{\n"
" color = vec4( 1.0, 0.0, 0.0, 1.0);\n"
"}\n";
unsigned int shader = CreateShader(vertexShader1, fragmentShader1);
glUseProgram(shader);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
glfwSwapBuffers(window);
glfwPollEvents();
}
if (glfwWindowShouldClose(window))
{
glDeleteProgram(shader);
glfwTerminate();
}
return 0;
}
| true |
cfe2646196b7a5fd69fbc0d11ff819391f9213eb | C++ | VerEeckeDaan/OOP3 | /Woman/main.cpp | UTF-8 | 299 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include "Woman.h" //Include of project header
using namespace std;
int main() {
//int number;
Woman mila(19, "Mila");
cout << mila.to_string() << endl;
//change age and print again
mila.setAge(30);
cout << mila.to_string() << endl;
return 0;
}
| true |
a670feff3b6f429e42f1d8fa5101dd3c0232140d | C++ | MYildizz/Syllabus | /Codes/KardeslerScheduler/Course.hpp | ISO-8859-13 | 2,228 | 3.15625 | 3 | [] | no_license | #ifndef COURSE_H_
#define COURSE_H_
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
class Course
{
protected:
//string courseCode;
string courseName;
string courseSemasterYear;
string credit;
string Status;
string DepartOrSer;
string courseinstructor;
vector <string>BusyTimes;
vector <string>BusyDays;
bool isService; // Servis Kurs ise true olacak degilse false
//string ServiceDay; /* Eer objenin isService elemani true ise set fonksiyonu ile bunlari doldurcaz degilse null string ile doldurcaz*/
//string ServiceTime;
public:
string courseCode;
string ServiceDay; /* Eer objenin isService elemani true ise set fonksiyonu ile bunlari doldurcaz degilse null string ile doldurcaz*/
string ServiceTime;
Course() {
}
Course(string courseC, string courseN, string courseSY,
string crdt, string Stts,string DepartmentOrS, string courseIns,bool isServiceB) {
courseCode = courseC;
courseName = courseN;
courseSemasterYear = courseSY;
credit = crdt;
Status = Stts;
DepartOrSer = DepartmentOrS;
courseinstructor = courseIns;
isService = isServiceB;
ServiceDay = "";
ServiceTime = "";
}
~Course()
{
}
void setBusy(string Bday, string Btime) {
BusyDays.push_back(Bday);
BusyTimes.push_back(Btime);
}
int checkBusy(string day, string time)
{
if (BusyDays.empty() == true)
return 1;
for (int i = 0; i < BusyDays.size(); i++)
{
if(BusyDays[i]==day)
{
for (int k = 0; k < BusyTimes.size(); k++)
{
if (BusyTimes[k]==time)
return 0;
}
}
}
return 1;
}
void setService(string Sday, string Stime) {
ServiceDay = Sday;
ServiceTime = Stime;
}
void toString() {
cout << courseCode << " " << courseName << " " << courseSemasterYear << " "
<< credit << " " << Status << " " << DepartOrSer <<
" " << courseinstructor;
if (isService && ServiceDay != "")
{
cout << " ||| Service Day:" << ServiceDay << " Service Time:" << ServiceTime << "\n";
}
else {
cout << "\n";
}
}
bool isEqual(string CCod) {
if (CCod == courseCode)
{
return true;
}
else {
return false;
}
}
};
#endif | true |
1e85e73260139a146d3289b3aff9d6c2f8168354 | C++ | github188/SClass | /main/Text/StrInt32WAcc.cpp | UTF-8 | 792 | 2.515625 | 3 | [] | no_license | #include "Stdafx.h"
#include "MyMemory.h"
#include "Core/Core.h"
#include "IO/ConsoleWriter.h"
#include "Text/MyString.h"
#include "Text/MyStringW.h"
#include "Text/StringBuilderUTF8.h"
Int32 MyMain(Core::IProgControl *progCtrl)
{
WChar sbuff[32];
Int32 i = 100000000;
Int32 j;
Bool succ = true;
IO::ConsoleWriter *console;
NEW_CLASS(console, IO::ConsoleWriter());
while (i-- > 0)
{
Text::StrInt32(sbuff, i);
j = Text::StrToInt32(sbuff);
if (i != j)
{
Text::StringBuilderUTF8 sb;
sb.AppendI32(i);
sb.Append((const UTF8Char*)" != ");
sb.AppendI32(j);
console->WriteLine(sb.ToString());
succ = false;
break;
}
}
if (succ)
{
console->WriteLine((const UTF8Char*)"Success");
}
DEL_CLASS(console);
return 0;
}
| true |
0ffaa10b02a9f6a95a6c2b3c29be2416db695360 | C++ | Cha-M/Talkquest | /Talkquest.cpp | UTF-8 | 1,981 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>
using std::endl;
using std::cout;
using std::cin;
using std::string;
using std::vector;
class cha_cla
{
public:
string nam;
int exp;
int lvl = 0;
vector<int> points = {0, 10, 20, 50, 100, 150, 200, 500, 1000, 1500, 2000, 3000, 10000};
vector<string> canned = {"Elf Stranger: Nice to hear it.\n", "Elf Stranger: Really?\n", "Elf Stranger: Tell me more.\n", "Elf Stranger: You go girlfriend\n", "Elf Stranger: Totes emosh\n", "Elf Stranger: The important thing is you tried\n", "Elf Stranger: Wow, that's so insightful :^)\n"};
string choose_string (vector<string> pickvec)
{
int random_index = rand() % pickvec.size();
string result_str;
result_str = pickvec[random_index];
return result_str;
}
string incr ()
{
int rm = rand() % 9 + 1;
exp += rm;
string upd8;
upd8 = "You have gained " + std::to_string(rm) + " experience point(s) and now have " + std::to_string(exp) +". ";
return upd8;
}
string intera ()
{
string vo;
cout << nam << ": ";
cin >> vo;
cout << choose_string(canned) << endl;
cout << incr() << endl;
if (points[lvl]<exp )
{
lvl++;
cout << nam << " gained a level and is now level " << lvl << "!";
}
cout << endl << endl;
intera();
// cout << "You have gained" << incr() << " experience points" << endl;
};
}cha;
int main ()
{
cout << "Talkquest 0.1\n'I want a game that fufills my fantasy of rewarding all social interaction with no upkeep required.' - Conal\n\nEnter your name:" << std::endl;
cin >> cha.nam;
cout << "\nElf Stranger: Hello " << cha.nam << ". How are you today?\n";
cout << cha.intera() << endl;
return 1;
}
| true |
e15f4efa34d9609eff847d273d3b82493cf0e973 | C++ | DaveeFTW/henkaku_installer | /3rdparty/include/stateless++/detail/trigger_behaviour.hpp | UTF-8 | 2,860 | 2.640625 | 3 | [
"MIT"
] | permissive | /**
* Copyright 2013 Matt Mason
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STATELESS_DETAIL_TRIGGER_BEHAVIOUR_HPP
#define STATELESS_DETAIL_TRIGGER_BEHAVIOUR_HPP
#include <functional>
#include "../error.hpp"
namespace stateless
{
namespace detail
{
class abstract_trigger_behaviour
{
public:
typedef std::function<bool()> TGuard;
abstract_trigger_behaviour(const TGuard& guard)
: guard_(guard)
{}
bool is_condition_met() const
{
return guard_();
}
virtual ~abstract_trigger_behaviour() = 0;
private:
TGuard guard_;
};
inline abstract_trigger_behaviour::~abstract_trigger_behaviour()
{}
template<typename TState, typename TTrigger>
class trigger_behaviour
: public abstract_trigger_behaviour
{
public:
typedef std::function<bool(const TState&, TState&)> TDecision;
trigger_behaviour(
const TTrigger& trigger,
const abstract_trigger_behaviour::TGuard& guard,
const TDecision& decision)
: abstract_trigger_behaviour(guard)
, trigger_(trigger)
, decision_(decision)
{}
const TTrigger& trigger() const
{
return trigger_;
}
bool results_in_transition_from(const TState& source, TState& destination) const
{
if (!decision_)
{
throw error("Static trigger behaviour decision is not set. "
"The state machine is misconfigured.");
}
return decision_(source, destination);
}
trigger_behaviour(
const TTrigger& trigger,
const abstract_trigger_behaviour::TGuard& guard)
: abstract_trigger_behaviour(guard)
, trigger_(trigger)
{}
private:
const TTrigger trigger_;
TDecision decision_;
};
template<typename TState, typename TTrigger, typename... TArgs>
class dynamic_trigger_behaviour
: public trigger_behaviour<TState, TTrigger>
{
public:
typedef typename std::function<TState(const TState&, TArgs...)> TDecision;
dynamic_trigger_behaviour(
const TTrigger& trigger,
const abstract_trigger_behaviour::TGuard& guard,
const TDecision& decision)
: trigger_behaviour<TState, TTrigger>(trigger, guard)
, decision_(decision)
{}
bool results_in_transition_from(const TState& source, TState& destination, TArgs... args) const
{
destination = decision_(source, args...);
return true;
}
private:
TDecision decision_;
};
}
}
#endif // STATELESS_DETAIL_TRIGGER_BEHAVIOUR_HPP
| true |
e27e05240933c71307a67d7ec9b48eebf4e9e483 | C++ | Jhecks/ITMO-Algorithms-and-Data-Structures | /Lab 13/Lab_3.cpp | UTF-8 | 659 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
vector <int> PrefixFunc;
string String;
void PrefixFunction()
{
PrefixFunc.resize(String.size());
PrefixFunc[0] = 0;
for (int i = 1; i < String.size(); i++)
{
int j = PrefixFunc[i - 1];
while (j != 0 && String[j] != String[i])
j = PrefixFunc[j - 1];
PrefixFunc[i] = (String[j] == String[i]) ? ++j : j;
}
}
int main()
{
freopen("prefix.in", "r", stdin);
freopen("prefix.out", "w", stdout);
cin >> String;
PrefixFunction();
for (auto i : PrefixFunc)
cout << i << ' ';
return 0;
}
| true |
7a44fb53ef4ca5f54f4444e9948d33d14c28b9f2 | C++ | JulioMelo-Classes/lista-1-taleshrocha | /inverter/src/function.cpp | UTF-8 | 528 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <array>
#include <iterator>
using std::iter_swap;
template <size_t SIZE>
/*ok!*/
void reverse( std::array< std::string, SIZE > & arr )
{
auto first = arr.begin();
auto last = arr.end()-1;
if(!(arr.size()%2)){
//std::cout<<"Batata"<<std::endl;
for(int i = 0; i < arr.size()/2; ++i){
std::iter_swap(first++, last--);
}
}
else{
while(first != last and first != last-1 and first != 0)
std::iter_swap(first++, last--);
}
}
| true |
7a3f1fd49d6c1e1fe07692428b260d66384637ad | C++ | ugovaretto-accel/rocm-scratch | /block-matrix-mul.cpp | UTF-8 | 6,247 | 3.515625 | 4 | [] | no_license | /// Block matrix-matrix multiply with non square matrices and non-square blocks
/// @author Ugo Varetto
#include <cassert>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using Float = float;
/// Used for dimensions (x = columns, y = rows) and offsets.
struct dim2 {
size_t x = 0;
size_t y = 0;
};
/// Swap x and y.
dim2 Invert(const dim2& d) { return {d.y, d.x}; }
/// Compute dimension of matrix resulting from multiplying two matrices
/// of sizes b1 and b1.
dim2 DimMul(const dim2& b1, const dim2& b2) { return {b1.y, b2.x}; }
/// Print matrix
void Print(const dim2& size, const Float* m) {
for (size_t row = 0; row != size.y; ++row) {
for (size_t col = 0; col != size.x; ++col)
cout << m[row * size.x + col] << " ";
cout << endl;
}
}
/// Multiply one sub-matrix from matrix A, one sub-matrix from matrix B
/// and store the result as a sub-matrix of C. Note that A, B, C can be
/// matrices of arbitrary size with no requirement of having rows(C) == rows(A)
/// and columns(C) == columns(B).
///
/// @param a input matrix A
/// @param b input matrix B
/// @param c output matrix C
/// @param blockDimA dimensions of A sub-matrix
/// @param blockDimB dimensions of B sub-batrix
/// @param dimensions of matrix A
/// @param dimensions of matrix B
/// @param dimensions of matrix C
/// @param offsetA location of input sub-matrix inside A
/// @param offsetB location of input sub-batrix inside B
/// @param offsetB location of output sub-matrix inside C
void BlockMul(const Float* a, const Float* b, Float* c, dim2 blockDimA,
dim2 blockDimB, dim2 dimA, dim2 dimB, dim2 dimC, dim2 offsetA,
dim2 offsetB, dim2 offsetC) {
const size_t nAcols = dimA.x;
const size_t nArows = dimA.y;
const size_t nBcols = dimB.x;
const size_t nBrows = dimB.y;
const size_t nABlockRows = blockDimA.y;
const size_t nABlockCols = blockDimB.x;
const size_t nBBlockCols = blockDimB.x;
const size_t nCcols = dimC.x;
for (size_t row = 0; row != nABlockRows; ++row) {
for (size_t col = 0; col != nBBlockCols; ++col) {
Float v = Float(0);
for (size_t x = 0; x != nABlockCols; ++x) {
v += a[(row + offsetA.y) * nAcols + offsetA.x + x] *
b[(x + offsetB.y) * nBcols + offsetB.x + col];
}
c[(row + offsetC.y) * nCcols + offsetC.x + col] = v;
}
}
}
/// Add sub-matrix to sub-matrix in place.
///
/// @param a input matrix A
/// @param c output matrix C
/// @param dimA dimensions of A
/// @param dimC dimensions of C
/// @param blockDimA dimensions or A sub-matrix == dimensions of C sub-matrix
/// @param offsetA location of sub-matrix in matrix A
/// @param offsetC location of sub-matrix in matrix C
void InplaceMatAdd(const Float* a, Float* c, dim2 dimA, dim2 dimC,
dim2 blockDimA, dim2 offsetA, dim2 offsetC) {
const size_t nAcols = dimA.x;
const size_t nArows = dimA.y;
const size_t nABlockRows = blockDimA.y;
const size_t nABlockCols = blockDimA.x;
const size_t nCcols = dimC.x;
const size_t nCrows = dimC.y;
for (size_t row = 0; row != nABlockRows; ++row) {
for (size_t col = 0; col != nABlockCols; ++col) {
c[(offsetC.y + row) * nCcols + offsetC.x + col] +=
a[(offsetA.y + row) * nAcols + offsetA.x + col];
}
}
}
/// Generic matrix-matrix multiply algorithm, use blockDim = {1, 1}
/// if no blocking required.
///
/// @param a input matrix A
/// @param b input matrix B
/// @param c output matrix C
/// @param b cache to store intermediate multiply results
/// @param blockDim block dimension, does not need to be square,
/// if not square block size in matrix B is computed
/// such as C blocks are square
/// @param dimA matrix A dimensions
/// @param dimB matrix B dimensions
void MatMul(const Float* a, const Float* b, Float* c, Float* block,
dim2 blockDim, dim2 dimA, dim2 dimB) {
assert(a);
assert(b);
assert(c);
assert(block);
assert(blockDim.x > 0 && blockDim.y > 0);
assert(dimA.x > 0 && dimA.y > 0);
assert(dimB.x > 0 && dimB.y > 0);
const size_t nAcols = dimA.x / blockDim.x;
const size_t nArows = dimA.y / blockDim.y;
const dim2 blockDimB = Invert(blockDim);
const dim2 blockDimC = DimMul(blockDim, blockDimB);
const size_t nBcols = dimB.x / blockDimB.x;
const size_t nBrows = dimB.y / blockDimB.y;
const size_t nCcols = nBcols;
const size_t nCrows = nArows;
const dim2 dimC = {dimB.x, dimA.y};
const dim2 offsetBlock = {0, 0};
for (size_t row = 0; row != nArows; ++row) {
for (size_t col = 0; col != nBcols; ++col) {
const dim2 offsetC = {col * blockDim.x, row * blockDim.y};
for (size_t y = 0; y != nAcols; ++y) {
// C[row][col] = A[row][c] x B[c][col];
const dim2 offsetA = {y * blockDim.x, row * blockDim.y};
const dim2 offsetB = {col * blockDim.x, y * blockDim.y};
BlockMul(a, b, block, blockDim, blockDimB, dimA, dimB,
blockDimC, offsetA, offsetB, offsetBlock);
InplaceMatAdd(block, c, blockDimC, dimC, blockDimC, {0, 0},
offsetC);
}
}
}
}
/// Generate matrices, multiply and print.
void Test(const dim2& size, const dim2& blockSize) {
vector<Float> a(size.x * size.y, Float(1));
vector<Float> b(size.x * size.y, Float(1));
vector<Float> c(size.x * size.y, Float(0));
vector<Float> block(blockSize.x * blockSize.y);
MatMul(a.data(), b.data(), c.data(), block.data(), blockSize, size, size);
Print(size, c.data());
}
/// Invoke matrix multiply test
int main(int argc, char** argv) {
#if 0
if(argc != 4) {
cerr << "usage: " << argv[0] << " <num rows> <num columns> <block size>"
<< endl;
exit(EXIT_FAILURE);
}
const dim2 size = {stoul(argv[2]), stoul(argv[1])};
const dim2 blockSize = {stoul(argv[3]), stoul(argv[3])};
#endif
const dim2 size = {50, 50};
const dim2 blockSize = {5, 5};
Test(size, blockSize);
return 0;
}
| true |