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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f8e638bdc792de813de3f0cf4ae207ab9daab439 | C++ | MuhammadNurYanhaona/ITandPCubeS | /compilers/multicore-backend/src/codegen/thread_state_mgmt.cc | UTF-8 | 24,172 | 2.53125 | 3 | [] | no_license | #include "thread_state_mgmt.h"
#include "space_mapping.h"
#include "../semantics/task_space.h"
#include "../utils/list.h"
#include "../syntax/ast_task.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
// This function is simple. It just copy the dimension information from the global array metadata object to the
// partition dimensions of individual arrays. Memory for these arrays are not allocated as it is not done for
// any LPU in any LPS. For memory allocation further analysis of the compute block is needed and the whole allocation
// logic will be handled in a separate module.
void generateRootLpuComputeRoutine(std::ofstream &programFile, MappingNode *mappingRoot) {
std::cout << "\tGenerating routine for root LPU calculation" << std::endl;
programFile << "// Construction of task specific root LPU\n";
std::string statementSeparator = ";\n";
std::string singleIndent = "\t";
// specify the signature of the set-root-LPU function matching the virtual function in Thread-State class
std::ostringstream functionHeader;
functionHeader << "void ThreadStateImpl::setRootLpu(Metadata *metadata)";
std::ostringstream functionBody;
functionBody << "{\n\n";
// first cast the generic metadata object into task specific array metadata object
functionBody << singleIndent;
functionBody << "ArrayMetadata *arrayMetadata = (ArrayMetadata*) metadata";
functionBody << statementSeparator;
functionBody << std::endl;
// allocate an LPU for the root
Space *rootLps = mappingRoot->mappingConfig->LPS;
functionBody << singleIndent;
functionBody << "Space" << rootLps->getName() << "_LPU *lpu = new Space";
functionBody << rootLps->getName() << "_LPU";
functionBody << statementSeparator;
// initialize each array in the root LPU
List<const char*> *localArrays = rootLps->getLocallyUsedArrayNames();
for (int i = 0; i < localArrays->NumElements(); i++) {
if (i > 0) functionBody << std::endl;
const char* arrayName = localArrays->Nth(i);
ArrayDataStructure *array = (ArrayDataStructure*) rootLps->getLocalStructure(arrayName);
int dimensionCount = array->getDimensionality();
functionBody << singleIndent << "lpu->" << arrayName << " = NULL" << statementSeparator;
std::ostringstream varName;
varName << "lpu->" << arrayName << "PartDims";
for (int j = 0; j < dimensionCount; j++) {
functionBody << singleIndent << varName.str() << "[" << j << "] = ";
functionBody << "PartDimension()" << statementSeparator;
functionBody << singleIndent << varName.str() << "[" << j << "].partition = ";
functionBody << "arrayMetadata->" << arrayName << "Dims[" << j << "]";
functionBody << statementSeparator;
functionBody << singleIndent << varName.str() << "[" << j << "].storage = ";
functionBody << "arrayMetadata->" << arrayName << "Dims[" << j;
functionBody << "].getNormalizedDimension()" << statementSeparator;
}
}
// store the LPU in the proper LPS state
functionBody << std::endl;
functionBody << singleIndent << "lpu->setValidBit(true)" << statementSeparator;
functionBody << singleIndent << "lpsStates[Space_" << rootLps->getName() << "]->lpu = lpu";
functionBody << statementSeparator;
functionBody << singleIndent << "//threadLog << \"set up root LPU\" << std::endl";
functionBody << statementSeparator;
functionBody << singleIndent << "//threadLog.flush()";
functionBody << statementSeparator << "}\n";
programFile << functionHeader.str() << " " << functionBody.str();
programFile << std::endl;
}
void generateSetRootLpuRoutine(std::ofstream &programFile, MappingNode *mappingRoot) {
programFile << "// Setting up the Root LPU reference \n";
std::string statementSeparator = ";\n";
std::string singleIndent = "\t";
Space *rootLps = mappingRoot->mappingConfig->LPS;
// specify the signature of the set-root-LPU function matching the virtual function in Thread-State class
std::ostringstream functionHeader;
functionHeader << "void ThreadStateImpl::setRootLpu(LPU *lpu)";
std::ostringstream functionBody;
functionBody << "{\n";
// store the LPU in the proper LPS state
functionBody << singleIndent << "lpu->setValidBit(true)" << statementSeparator;
functionBody << singleIndent << "lpsStates[Space_" << rootLps->getName() << "]->lpu = lpu";
functionBody << statementSeparator;
functionBody << singleIndent << "//threadLog << \"set up root LPU\" << std::endl";
functionBody << statementSeparator;
functionBody << singleIndent << "//threadLog.flush()";
functionBody << statementSeparator << "}\n";
programFile << functionHeader.str() << " " << functionBody.str();
programFile << std::endl;
}
void generateInitializeLpuSRoutine(std::ofstream &programFile, MappingNode *mappingRoot) {
std::cout << "\tGenerating function for initializing LPU pointers" << std::endl;
programFile << "// Initialization of LPU pointers of different LPSes\n";
std::string statementSeparator = ";\n";
std::string singleIndent = "\t";
programFile << "void ThreadStateImpl::initializeLPUs() {\n";
// Note that we skip the root LPU as it must be set correctly for computation to be able to make
// progress and it is been correctly initialized by the setRootLpu() routine.
std::deque<MappingNode*> nodeQueue;
for (int i = 0; i < mappingRoot->children->NumElements(); i++) {
nodeQueue.push_back(mappingRoot->children->Nth(i));
}
while (!nodeQueue.empty()) {
MappingNode *node = nodeQueue.front();
nodeQueue.pop_front();
for (int i = 0; i < node->children->NumElements(); i++) {
nodeQueue.push_back(node->children->Nth(i));
}
Space *lps = node->mappingConfig->LPS;
programFile << singleIndent;
programFile << "lpsStates[Space_" << lps->getName() << "]->lpu = ";
programFile << "new Space" << lps->getName() << "_LPU";
programFile << statementSeparator;
programFile << singleIndent;
programFile << "lpsStates[Space_" << lps->getName() << "]->lpu->setValidBit(false)";
programFile << statementSeparator;
}
programFile << singleIndent << "//threadLog << \"initialized LPU pointers\" << std::endl";
programFile << statementSeparator;
programFile << singleIndent << "//threadLog.flush()";
programFile << statementSeparator;
programFile << "}" << std::endl << std::endl;
}
void generateParentIndexMapRoutine(std::ofstream &programFile, MappingNode *mappingRoot) {
std::cout << "\tGenerating parent pointer index map" << std::endl;
programFile << "// Construction of task specific LPS hierarchy index map\n";
std::string statementSeparator = ";\n";
std::string singleIndent = "\t";
std::ostringstream allocateStmt;
std::ostringstream initializeStmts;
allocateStmt << singleIndent << "lpsParentIndexMap = new int";
allocateStmt << "[Space_Count]" << statementSeparator;
initializeStmts << singleIndent << "lpsParentIndexMap[Space_";
initializeStmts << mappingRoot->mappingConfig->LPS->getName();
initializeStmts << "] = INVALID_ID" << statementSeparator;
std::deque<MappingNode*> nodeQueue;
for (int i = 0; i < mappingRoot->children->NumElements(); i++) {
nodeQueue.push_back(mappingRoot->children->Nth(i));
}
while (!nodeQueue.empty()) {
MappingNode *node = nodeQueue.front();
nodeQueue.pop_front();
for (int i = 0; i < node->children->NumElements(); i++) {
nodeQueue.push_back(node->children->Nth(i));
}
Space *lps = node->mappingConfig->LPS;
initializeStmts << singleIndent;
initializeStmts << "lpsParentIndexMap[Space_" << lps->getName() << "] = ";
initializeStmts << "Space_" << lps->getParent()->getName();
initializeStmts << statementSeparator;
}
programFile << "void ThreadStateImpl::setLpsParentIndexMap() {\n";
programFile << allocateStmt.str() << initializeStmts.str();
programFile << singleIndent << "//threadLog << \"set up parent LPS index map\" << std::endl";
programFile << statementSeparator;
programFile << singleIndent << "//threadLog.flush()";
programFile << statementSeparator;
programFile << "}\n\n";
}
void generateComputeLpuCountRoutine(std::ofstream &programFile, MappingNode *mappingRoot,
Hashtable<List<PartitionParameterConfig*>*> *countFunctionsArgsConfig) {
std::cout << "\tGenerating compute LPU count function" << std::endl;
programFile << "// Implementation of task specific compute-LPU-Count function ";
std::string statementSeparator = ";\n";
std::string singleIndent = "\t";
std::string doubleIndent = "\t\t";
std::string tripleIndent = "\t\t\t";
std::string parameterSeparator = ", ";
// specify the signature of the compute-Next-Lpu function matching the virtual function in Thread-State class
std::ostringstream functionHeader;
functionHeader << "int *ThreadStateImpl::computeLpuCounts(int lpsId)";
std::ostringstream functionBody;
functionBody << "{\n";
std::deque<MappingNode*> nodeQueue;
nodeQueue.push_back(mappingRoot);
while (!nodeQueue.empty()) {
MappingNode *node = nodeQueue.front();
nodeQueue.pop_front();
for (int i = 0; i < node->children->NumElements(); i++) {
nodeQueue.push_back(node->children->Nth(i));
}
Space *lps = node->mappingConfig->LPS;
// if the space is unpartitioned then we can return NULL as there is no need for a counter then
functionBody << singleIndent << "if (lpsId == Space_" << lps->getName() << ") {\n";
if (lps->getDimensionCount() == 0) {
functionBody << doubleIndent << "return NULL" << statementSeparator;
// otherwise, we have to call the appropriate get-LPU-count function generated before
} else {
// declare a local variable for PPU count which is a default argument to all count functions
functionBody << doubleIndent << "int ppuCount = ";
functionBody << "threadIds->ppuIds[Space_" << lps->getName() << "].ppuCount";
functionBody << statementSeparator;
// create local variables for ancestor LPUs that will be needed to determine the dimension
// arguments for the get-LPU-Count function
List<PartitionParameterConfig*> *paramConfigs
= countFunctionsArgsConfig->Lookup(lps->getName());
if (paramConfigs == NULL) std::cout << "strange!!" << std::endl;
Hashtable<const char*> *parentLpus = new Hashtable<const char*>;
Hashtable<const char*> *arrayToParentLpus = new Hashtable<const char*>;
for (int i = 0; i < paramConfigs->NumElements(); i++) {
PartitionParameterConfig *currentConfig = paramConfigs->Nth(i);
const char *arrayName = currentConfig->arrayName;
if (arrayName == NULL) continue;
Space *parentLps = lps->getLocalStructure(arrayName)->getSource()->getSpace();
// no variable is yet created for the parent LPU so create it
if (parentLpus->Lookup(parentLps->getName()) == NULL) {
std::ostringstream parentLpuStr;
functionBody << doubleIndent;
functionBody << "Space" << parentLps->getName() << "_LPU *";
parentLpuStr << "space" << parentLps->getName() << "Lpu";
functionBody << parentLpuStr.str() << std::endl;
functionBody << doubleIndent << doubleIndent;
functionBody << " = (Space" << parentLps->getName() << "_LPU*) ";
functionBody << "lpsStates[Space_" << parentLps->getName() << "]->lpu";
functionBody << statementSeparator;
arrayToParentLpus->Enter(arrayName, strdup(parentLpuStr.str().c_str()));
parentLpus->Enter(parentLps->getName(), strdup(parentLpuStr.str().c_str()));
// otherwise just get the reference of the already created LPU
} else {
arrayToParentLpus->Enter(arrayName, parentLpus->Lookup(parentLps->getName()));
}
}
// call the get-LPU-Count function with appropriate parameters
functionBody << doubleIndent << "return getLPUsCountOfSpace" << lps->getName();
functionBody << "(ppuCount";
for (int i = 0; i < paramConfigs->NumElements(); i++) {
PartitionParameterConfig *currentConfig = paramConfigs->Nth(i);
const char *arrayName = currentConfig->arrayName;
if (arrayName != NULL) {
functionBody << parameterSeparator << "\n" << doubleIndent << doubleIndent;
functionBody << arrayToParentLpus->Lookup(arrayName) << "->" << arrayName;
functionBody << "PartDims[" << currentConfig->dimensionNo - 1;
functionBody << "].partition";
}
// pass any partition arguments used by current count function
for (int j = 0; j < currentConfig->partitionArgsIndexes->NumElements(); j++) {
int index = currentConfig->partitionArgsIndexes->Nth(j);
functionBody << parameterSeparator << "\n" << doubleIndent << doubleIndent;
functionBody << "partitionArgs[" << index << "]";
}
}
functionBody << ")" << statementSeparator;
}
functionBody << singleIndent << "}\n";
}
functionBody << singleIndent << "return NULL" << statementSeparator;
functionBody << "}\n";
programFile << std::endl << functionHeader.str() << " " << functionBody.str();
programFile << std::endl;
}
void generateComputeNextLpuRoutine(std::ofstream &programFile, MappingNode *mappingRoot,
Hashtable<List<int>*> *lpuPartFunctionsArgsConfig) {
std::cout << "\tGenerating compute next LPU function" << std::endl;
programFile << "// Implementation of task specific compute-Next-LPU function ";
std::string statementSeparator = ";\n";
std::string singleIndent = "\t";
std::string doubleIndent = "\t\t";
std::string tripleIndent = "\t\t\t";
std::string parameterSeparator = ", ";
// specify the signature of the compute-Next-Lpu function matching the virtual function in Thread-State class
std::ostringstream functionHeader;
functionHeader << "LPU *ThreadStateImpl::computeNextLpu(int lpsId, int *lpuCounts, int *nextLpuId)";
std::ostringstream functionBody;
functionBody << "{\n";
std::deque<MappingNode*> nodeQueue;
// we skip the mapping root and start iterating with its descendents because the LPU for the root space should
// not change throughout the computation of the task
for (int i = 0; i < mappingRoot->children->NumElements(); i++) {
nodeQueue.push_back(mappingRoot->children->Nth(i));
}
while (!nodeQueue.empty()) {
MappingNode *node = nodeQueue.front();
nodeQueue.pop_front();
for (int i = 0; i < node->children->NumElements(); i++) {
nodeQueue.push_back(node->children->Nth(i));
}
Space *lps = node->mappingConfig->LPS;
functionBody << singleIndent << "if (lpsId == Space_" << lps->getName() << ") {\n";
// create a list of local variables from parent LPUs needed to compute the current LPU for current LPS
Hashtable<const char*> *parentLpus = new Hashtable<const char*>;
Hashtable<const char*> *arrayToParentLpus = new Hashtable<const char*>;
List<const char*> *localArrays = lps->getLocallyUsedArrayNames();
for (int i = 0; i < localArrays->NumElements(); i++) {
const char *arrayName = localArrays->Nth(i);
DataStructure *structure = lps->getLocalStructure(arrayName);
Space *parentLps = structure->getSource()->getSpace();
// if the array is inherited from parent LPS by a subpartitioned LPS then correct parent reference
if (structure->getSpace() != lps) {
parentLps = structure->getSpace();
}
if (parentLpus->Lookup(parentLps->getName()) == NULL) {
std::ostringstream parentLpuStr;
functionBody << doubleIndent;
functionBody << "Space" << parentLps->getName() << "_LPU *";
parentLpuStr << "space" << parentLps->getName() << "Lpu";
functionBody << parentLpuStr.str() << std::endl;
functionBody << doubleIndent << doubleIndent;
functionBody << " = (Space" << parentLps->getName() << "_LPU*) ";
functionBody << "lpsStates[Space_" << parentLps->getName() << "]->lpu";
functionBody << statementSeparator;
arrayToParentLpus->Enter(arrayName, strdup(parentLpuStr.str().c_str()));
parentLpus->Enter(parentLps->getName(), strdup(parentLpuStr.str().c_str()));
} else {
arrayToParentLpus->Enter(arrayName, parentLpus->Lookup(parentLps->getName()));
}
}
// get the reference of the current LPU for update
const char *lpsName = lps->getName();
functionBody << doubleIndent;
functionBody << "Space" << lpsName << "_LPU *currentLpu";
functionBody << std::endl << doubleIndent << doubleIndent;
functionBody << " = (Space" << lpsName << "_LPU*) ";
functionBody << "lpsStates[Space_" << lpsName << "]->lpu";
functionBody << statementSeparator;
// if the LPS is partitioned then copy queried LPU id to the lpuId static array of the created LPU
if (lps->getDimensionCount() > 0) {
for (int i = 0; i < lps->getDimensionCount(); i++) {
functionBody << doubleIndent;
functionBody << "currentLpu->lpuId[" << i << "] = nextLpuId[" << i << "]";
functionBody << statementSeparator;
}
}
// if the LPS is unpartitioned then we need to create the new LPU by extracting elements from
// LPUs of ancestor LPSes for common data structures.
if (lps->getDimensionCount() == 0) {
for (int i = 0; i < localArrays->NumElements(); i++) {
const char *arrayName = localArrays->Nth(i);
const char *parentLpu = arrayToParentLpus->Lookup(arrayName);
functionBody << doubleIndent << "currentLpu->" << arrayName << " = ";
functionBody << "space" << lpsName << "Content." << arrayName;
functionBody << statementSeparator;
ArrayDataStructure *array = (ArrayDataStructure*) lps->getLocalStructure(arrayName);
int dimensionCount = array->getDimensionality();
for (int j = 0; j < dimensionCount; j++) {
functionBody << doubleIndent << "currentLpu->" << arrayName;
functionBody << "PartDims" << '[' << j << "] = ";
functionBody << parentLpu << "->" << arrayName << "PartDims";
functionBody << '[' << j << "]" << statementSeparator;
}
}
// otherwise we need to call appropriate get-Part functions for invidual data structures of the LPU
} else {
for (int i = 0; i < localArrays->NumElements(); i++) {
const char *arrayName = localArrays->Nth(i);
ArrayDataStructure *array = (ArrayDataStructure*) lps->getLocalStructure(arrayName);
functionBody << doubleIndent << "currentLpu->" << arrayName << " = ";
functionBody << "space" << lpsName << "Content." << arrayName;
functionBody << statementSeparator;
// if the structure is replicated then just copy its information from the parent
// NOTE the second condition is for arrays inherited by a subpartitioned LPS
if (!(array->isPartitioned() && array->getSpace() == lps)) {
const char *parentLpu = arrayToParentLpus->Lookup(arrayName);
int dimensionCount = array->getDimensionality();
for (int j = 0; j < dimensionCount; j++) {
functionBody << doubleIndent << "currentLpu->" << arrayName;
functionBody << "PartDims[" << j << "] = ";
functionBody << parentLpu << "->" << arrayName << "PartDims";
functionBody << '[' << j << "]" << statementSeparator;
}
// otherwise get the array part for current LPU by calling appropriate function
} else {
functionBody << doubleIndent;
functionBody << "get" << arrayName << "PartForSpace" << lps->getName() << "Lpu(";
// pass current LPU's dimension parameter to be updated in the function
functionBody << "currentLpu->" << arrayName << "PartDims";
functionBody << parameterSeparator;
// pass the default parent dimension parameter to the function
const char *parentLpu = arrayToParentLpus->Lookup(arrayName);
functionBody << "\n" << doubleIndent << doubleIndent;
functionBody << parentLpu << "->" << arrayName << "PartDims";
// pass default LPU-Count and LPU-Id parameters to the function
functionBody << parameterSeparator << "lpuCounts";
functionBody << parameterSeparator << "nextLpuId";
// then pass any additional partition arguments needed for computing part
// for current data structurre
std::ostringstream entryName;
entryName << lps->getName() << "_" << arrayName;
List<int> *argList = lpuPartFunctionsArgsConfig->Lookup(entryName.str().c_str());
if (argList->NumElements() > 0) {
functionBody << parameterSeparator << "\n";
functionBody << doubleIndent << doubleIndent;
}
for (int j = 0; j < argList->NumElements(); j++) {
if (j > 0) functionBody << parameterSeparator;
functionBody << "partitionArgs[" << argList->Nth(j) << "]";
}
functionBody << ")";
functionBody << statementSeparator;
}
}
}
functionBody << doubleIndent << "currentLpu->setValidBit(true)" << statementSeparator;
functionBody << doubleIndent << "return currentLpu" << statementSeparator;
functionBody << singleIndent << "}\n";
}
functionBody << singleIndent << "return NULL" << statementSeparator;
functionBody << "}\n";
programFile << std::endl << functionHeader.str() << " " << functionBody.str();
programFile << std::endl;
}
void generateThreadStateImpl(const char *headerFileName, const char *programFileName,
MappingNode *mappingRoot,
Hashtable<List<PartitionParameterConfig*>*> *countFunctionsArgsConfig,
Hashtable<List<int>*> *lpuPartFunctionsArgsConfig) {
std::cout << "Generating task spacific Thread State implementation task" << std::endl;
std::ofstream programFile, headerFile;
headerFile.open (headerFileName, std::ofstream::out | std::ofstream::app);
programFile.open (programFileName, std::ofstream::out | std::ofstream::app);
if (!programFile.is_open() || !headerFile.is_open()) {
std::cout << "Unable to open program or header file";
std::exit(EXIT_FAILURE);
}
// write the common class definition from the sample file in the header file
headerFile << "/*-----------------------------------------------------------------------------------\n";
headerFile << "Thread-State implementation class for the task" << std::endl;
headerFile << "------------------------------------------------------------------------------------*/\n\n";
std::string line;
std::ifstream classDefinitionFile("config/thread-state-class-def.txt");
if (classDefinitionFile.is_open()) {
while (std::getline(classDefinitionFile, line)) {
headerFile << line << std::endl;
}
headerFile << std::endl;
classDefinitionFile.close();
} else {
std::cout << "Unable to open the file containing thread-state superclass definition\n";
std::exit(EXIT_FAILURE);
}
headerFile.close();
// write the implementions of virtual functions in the program file
programFile << "/*-----------------------------------------------------------------------------------\n";
programFile << "Thread-State implementation class for the task" << std::endl;
programFile << "------------------------------------------------------------------------------------*/\n\n";
// construct the index array that encode the LPS hierarchy for this task
generateParentIndexMapRoutine(programFile, mappingRoot);
// generate the function for creating the root LPU from array metadata information
generateRootLpuComputeRoutine(programFile, mappingRoot);
// generate the function for setting the root LPU constructed using some other means
generateSetRootLpuRoutine(programFile, mappingRoot);
// generate the function for allocating a pointer for each LPS'es LPU that will be updated over and over
generateInitializeLpuSRoutine(programFile, mappingRoot);
// then call the compute-LPU-Count function generator method for class specific implementation
generateComputeLpuCountRoutine(programFile, mappingRoot, countFunctionsArgsConfig);
// then call the compute-Next-LPU function generator method for class specific implementation
generateComputeNextLpuRoutine(programFile, mappingRoot, lpuPartFunctionsArgsConfig);
programFile.close();
}
| true |
51d857dde66ca784867694ce1e46ff0eee0f6ca8 | C++ | WhiZTiM/coliru | /Archive2/e1/506948ab3c6066/main.cpp | UTF-8 | 269 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
template<typename Container>
void foo(Container && v)
{
v[100] = 1;
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int main()
{
foo(std::vector<int>(1000));
std::vector<int> buffer(100);
foo(buffer);
} | true |
660a98b4b623f7c9f4117928054691ad49397ebb | C++ | jonasmr/screenbsp | /src/math.h | UTF-8 | 13,429 | 2.703125 | 3 | [
"Unlicense"
] | permissive | #pragma once
#define PI 3.14159265358979323846f
#define TWOPI 6.2831853071795864769f
#define TORAD (PI/180.f)
#include <string.h>
#include "immintrin.h"
struct v2;
struct v3;
struct v4;
struct v2
{
float x;
float y;
void operator +=(const v2& r);
void operator -=(const v2& r);
void operator *=(const v2& r);
void operator /=(const v2& r);
void operator +=(const float r);
void operator -=(const float r);
void operator *=(const float r);
void operator /=(const float r);
};
struct v3
{
float x;
float y;
float z;
void operator +=(const v3& r);
void operator -=(const v3& r);
void operator *=(const v3& r);
void operator /=(const v3& r);
void operator +=(const float r);
void operator -=(const float r);
void operator *=(const float r);
void operator /=(const float r);
v2 tov2();
v4 tov4();
v4 tov4(float w);
uint32_t tocolor();
};
struct v4
{
float x;
float y;
float z;
float w;
void operator +=(const v4& r);
void operator -=(const v4& r);
void operator *=(const v4& r);
void operator /=(const v4& r);
void operator +=(const float r);
void operator -=(const float r);
void operator *=(const float r);
void operator /=(const float r);
v2 tov2();
v3 tov3();
uint32_t tocolor();
};
///
/// ROW-MAJOR
///
/// x y z w x
/// x y z w * y
/// x y z w z
/// x y z w w
#ifdef _WIN32
#define ALIGN16 __declspecl(align(16))
#else
#define ALIGN16 __attribute__((aligned(16)))
#endif
struct m
{
//{
v4 x;
v4 y;
v4 z;
// union
// {
v4 trans;
// v4 w;
// };
//};
// struct
// {
// v4 r0;
// v4 r1;
// v4 r2;
// v4 r3;
// };
};
inline
m mload(const float* pFloats)
{
m temp;
memcpy(&temp, pFloats, 16*sizeof(float));
return temp;
}
inline
bool operator ==(const m& l, const m& r)
{
return 0 == memcmp(&l, &r, sizeof(m));
}
v2 operator +(const v2 l, const v2 r);
v2 operator -(const v2 l, const v2 r);
v2 operator *(const v2 l, const v2 r);
v2 operator /(const v2 l, const v2 r);
bool operator <(const v2 l, const v2 r);
v2 operator +(const v2 l, float f);
v2 operator -(const v2 l, float f);
v2 operator *(const v2 v, float f);
v2 operator /(const v2 v, float f);
v2 operator +(float f, const v2 l);
v2 operator -(float f, const v2 l);
v2 operator *(float f, const v2 v);
v2 operator /(float f, const v2 v);
float v2length(v2 v);
v2 v2normalize(v2 v);
v2 v2hat(v2 v);
v2 v2reflect(v2 normal, v2 direction);
inline v2 v2neg(v2 v)
{ v.x = -v.x; v.y = -v.y; return v;}
float v2dot(v2 v);
float v2dot(v2 v0, v2 v1);
inline
float v2length2(v2 v){return v2dot(v,v);}
inline float v2distance2(v2 a, v2 b)
{
return v2length2(a-b);
}
inline float v2distance(v2 a, v2 b)
{
return v2length(a-b);
}
inline
v2 v2init(float x, float y){v2 r; r.x = x; r.y = y; return r;}
inline
v2 v2init(float f){v2 r; r.x = f; r.y = f; return r;}
inline
v2 v2zero(){v2 z = {0,0};return z;}
inline
v2 v2max(v2 v0, v2 v1)
{
v2 r;
r.x = v0.x < v1.x ? v1.x : v0.x;
r.y = v0.y < v1.y ? v1.y : v0.y;
return r;
}
inline
v2 v2min(v2 v0, v2 v1)
{
v2 r;
r.x = v0.x < v1.x ? v0.x : v1.x;
r.y = v0.y < v1.y ? v0.y : v1.y;
return r;
}
v2 v2round(v2 v);
v2 v2sign(v2 v);
v2 v2abs(v2 v);
inline
void v2swap(v2& va, v2& vb) { v2 vtmp = vb; vb = va; va = vtmp; }
inline
v2 v2floor(v2 v){v2 r = v; r.x = floor(r.x); r.y = floor(r.y); return r;}
inline
v2 v2clamp(v2 value, v2 min_, v2 max_){ return v2min(max_, v2max(min_, value)); }
inline
v2 v2lerp(v2 from_, v2 to_, float fLerp) { return from_ + (to_-from_) * fLerp; }
inline
float v2ManhattanDistance(v2 from_, v2 to_) { return (fabs(from_.x-to_.x) + fabs(from_.y-to_.y)); }
inline
float fclamp(float value, float min_, float max_){ if(value<min_) return min_; if(value>max_) return max_; return value; }
float v2findpenetration(v2 pos, v2 dir, v2 size, v2 p0, v2 p1, v2 p2, v2 p3, v2& dirout, v2& pointout);
void v2createbounds(v2 vPosition, v2 vDirection, v2 vSize, v2& min_, v2& max_);
void v2createcorners(v2 vPosition, v2 vDirection, v2 vSize, v2& p0, v2& p1, v2& p2, v2& p3);
bool v2fucked(v2 v);
v2 v2fromangle(float fAngle);
inline bool v2iszero(v2 v){return v2length2(v)<1e-8f;}
v3 operator +(const v3 l, const v3 r);
v3 operator -(const v3 l, const v3 r);
v3 operator *(const v3 l, const v3 r);
v3 operator /(const v3 l, const v3 r);
v3 operator +(const v3 l, float f);
v3 operator -(const v3 l, float f);
v3 operator *(const v3 v, float f);
v3 operator /(const v3 v, float f);
v3 operator +(float f, const v3 l);
v3 operator -(float f, const v3 l);
v3 operator *(float f, const v3 v);
v3 operator /(float f, const v3 v);
v3 operator -(const v3 v);
inline
v3 v3init(float f){v3 r; r.x = f; r.y = f; r.z = f; return r;}
inline
v3 v3init(v2 v, float f){v3 r; r.x = v.x; r.y = v.y; r.z = f; return r;}
inline
v3 v3init(float x, float y, float z){v3 r; r.x = x; r.y = y;r.z = z; return r;}
inline
v3 v3init(v4 v)
{ v3 r; r.x = v.x; r.y = v.y; r.z = v.z; return r;}
inline
v3 v3load(float* f)
{
v3 r;
r.x = f[0];
r.y = f[1];
r.z = f[2];
return r;
}
inline
v3 v3lerp(v3 from_, v3 to_, float fLerp) { return from_ + (to_-from_) * fLerp; }
inline
float v3dot(v3 v0, v3 v1)
{
return v0.x * v1.x + v0.y * v1.y + v0.z * v1.z;
}
float v3distance(v3 p0, v3 p1);
v3 v3fromcolor(uint32_t nColor);
v3 v3cross(v3 v0, v3 v1);
float v3length(v3 v);
float v3lengthsq(v3 v);
v3 v3normalize(v3 v);
v3 v3min(v3 a, v3 b);
v3 v3min(v3 a, float f);
v3 v3max(v3 a, v3 b);
v3 v3max(v3 a, float f);
v3 v3abs(v3 a, v3 b);
v3 v3splatx(v3 v);
v3 v3splaty(v3 v);
v3 v3splatz(v3 v);
inline
v3 v3zero(){v3 z = {0,0,0};return z;}
inline
v3 v3rep(float f){ v3 r = {f,f,f}; return r;}
inline
v4 v4init(float f){v4 r; r.x = f; r.y = f; r.z = f; r.w = f; return r;}
inline
v4 v4zero(){v4 z = {0,0,0,0};return z;}
inline
v4 v4init(float x, float y, float z, float w) {v4 r; r.x = x; r.y = y; r.z = z; r.w = w; return r;}
inline
v4 v4init(v3 v, float w){ v4 r; r.x = v.x; r.y = v.y; r.z = v.z; r.w = w; return r; }
inline
v4 v4init(v4 v, float w){ v4 r; r.x = v.x; r.y = v.y; r.z = v.z; r.w = w; return r; }
v4 operator +(const v4 l, const v4 r);
v4 operator -(const v4 l, const v4 r);
v4 operator *(const v4 l, const v4 r);
v4 operator /(const v4 l, const v4 r);
v4 operator +(const v4 l, float f);
v4 operator -(const v4 l, float f);
v4 operator *(const v4 v, float f);
v4 operator /(const v4 v, float f);
v4 operator +(float f, const v4 l);
v4 operator -(float f, const v4 l);
v4 operator *(float f, const v4 v);
v4 operator /(float f, const v4 v);
v4 operator -(const v4 v);
v4 v4fromcolor(uint32_t nColor);
v4 v4neg(v4 v);
float v4dot(v4 v0, v4 v1);
float v4length(v4 v0);
float v4length2(v4 v0);
v4 v4makeplane(v3 p, v3 normal);
inline float v4length2(v4 v0){ return v0.x * v0.x + v0.y * v0.y + v0.z * v0.z + v0.w * v0.w;}
inline float v4distance(v4 v0, v4 v1){ return v4length(v0-v1);}
inline float v4distance2(v4 v0, v4 v1){ return v4length2(v0-v1);}
inline
v4 v4lerp(v4 from_, v4 to_, float fLerp) { return from_ + (to_-from_) * fLerp; }
m minit(v3 vx, v3 vy, v3 vz, v3 vtrans);
m mid();
m mcreate(v3 vDir, v3 vRight, v3 vPoint);
m mcreate(v3 vDir, v3 vRight, v3 vUp, v3 vPoint);
m mmult(m m0, m m1);
m mmult_sse(const m* m0, const m* m1);
m mtranspose(m mat);
m mrotatex(float fAngle);
m mrotatey(float fAngle);
m mrotatez(float fAngle);
m mscale(float fScale);
m mscale(float fScaleX, float fScaleY, float fScaleZ);
m mtranslate(v3 trans);
m mviewport(float x, float y, float w, float h);
m mperspective(float fFovY, float fAspect, float fNear, float fFar);
m mortho(float fXWidth, float fYWidth, float fZRange);
m morthogl(float left, float right, float top, float bottom, float near, float far);
v3 mtransform(m mat, v3 point);
v4 mtransform(m mat, v4 vector);
v3 mrotate(m mat, v3 vector);
m minverse(m);
void msetxaxis(m& mat, v3 axis);
void msetyaxis(m& mat, v3 axis);
void msetzaxis(m& mat, v3 axis);
inline v3 mgetxaxis(const m& mat){v3 r; r.x = mat.x.x; r.y = mat.x.y; r.z = mat.x.z; return r;}
inline v3 mgetyaxis(const m& mat){v3 r; r.x = mat.y.x; r.y = mat.y.y; r.z = mat.y.z; return r;}
inline v3 mgetzaxis(const m& mat){v3 r; r.x = mat.z.x; r.y = mat.z.y; r.z = mat.z.z; return r;}
m minverserotation(m mat);
m maffineinverse(m mat);
void ZASSERTAFFINE(m mat);
v3 obbtoaabb(m mrotation, v3 vHalfSize);
#define INTERSECT_FAIL (-FLT_MAX)
float rayplaneintersect(v3 r0, v3 rdir, v4 plane);
float rayplaneintersect(v3 r0, v3 rdir, v3 p0, v3 pnormal);
float rayboxintersect(v3 r0, v3 rdir, m boxtransform, v3 boxsize);
float frand();
int32_t randrange(int32_t nmin, int32_t nmax);
float frandrange(float fmin, float fmax);
v2 v2randir();
v2 v2randdisc();
uint32 randcolor();
uint32 randredcolor();
uint64_t rand64();
uint64_t rand64(uint64_t nPrev);
uint32_t rand32();
void randseed(uint32_t k, uint32_t j);
#define ZASSERTNORMALIZED2(v) ZASSERT(fabs(v2length(v)-1.f) < 1e-4f)
#define ZASSERTNORMALIZED3(v) ZASSERT(fabs(v3length(v)-1.f) < 1e-4f)
#define ZASSERTNORMALIZED4(v) ZASSERT(fabs(v4length(v)-1.f) < 1e-4f)
inline float signf(float f) { return f<0.0f ? -1.0f : 1.0f; }
#ifdef _WIN32
inline
float round(float f)
{
return floor(f+0.5f);
}
#endif
template<typename T>
T Min(T a, T b)
{ return a < b ? a : b; }
template<typename T>
T Max(T a, T b)
{ return a > b ? a : b; }
template<typename T>
T Clamp(T v, T a, T b)
{ return Max(Min(v,b), a); }
template<typename T>
void Swap(T& a, T& b)
{
T t = a;
a = b;
b = t;
}
//#ifndef _WINDOWS
//#define inline __inline __attribute__((always_inline))
//#endif
inline v2 v3::tov2()
{
v2 r;
r.x = x;
r.y = y;
return r;
}
inline v4 v3::tov4()
{
v4 r;
r.x = x;
r.y = y;
r.z = z;
r.w = 0.f;
return r;
}
inline uint32_t v3::tocolor()
{
return 0xff000000
| ((uint32_t(z * 255.f) << 16)&0xff0000)
| ((uint32_t(y * 255.f) << 8)&0xff00)
| (uint32_t(z * 255.f));
}
inline v4 v3::tov4(float w)
{
v4 r;
r.x = x;
r.y = y;
r.z = z;
r.w = w;
return r;
}
inline v3 v3cross(v3 v0, v3 v1)
{
v3 r;
r.x = v0.y * v1.z - v0.z * v1.y;
r.y = v0.z * v1.x - v0.x * v1.z;
r.z = v0.x * v1.y - v0.y * v1.x;
return r;
}
inline v3 v4::tov3()
{
v3 r;
r.x = x;
r.y = y;
r.z = z;
return r;
}
inline v2 v4::tov2()
{
v2 r;
r.x = x;
r.y = y;
return r;
}
inline v4 v4neg(v4 v)
{
v.x = -v.x;
v.y = -v.y;
v.z = -v.z;
v.w = -v.w;
return v;
}
inline float v4dot(v4 v0, v4 v1)
{
return v0.x * v1.x + v0.y * v1.y + v0.z * v1.z + v0.w * v1.w;
}
inline __m128 rsqrt(__m128 x)
{
__m128 v = _mm_rsqrt_ps(x);
__m128 halfx = _mm_mul_ps(x, _mm_set1_ps(-0.5f));
__m128 x2 = _mm_mul_ps(v, v);
__m128 foo = _mm_mul_ps(v, _mm_add_ps(_mm_set1_ps(1.5f), _mm_mul_ps(x2, halfx)));
return foo;
}
inline v3 v3normalize(v3 v_)
{
#if 1
__m128 v;
__m128 x = _mm_load_ss(&v_.x);
__m128 y = _mm_load_ss(&v_.y);
__m128 z = _mm_load_ss(&v_.z);
__m128 xy = _mm_movelh_ps(x, y);
v = _mm_shuffle_ps(xy, z, _MM_SHUFFLE(2, 0, 2, 0));
__m128 r0 = _mm_mul_ps(v, v);
__m128 r1 = _mm_hadd_ps(r0, r0);
__m128 r2 = _mm_hadd_ps(r1, r1);
__m128 result = _mm_mul_ps(rsqrt(r2), v);
return *(v3*)&result;
#else
return v_ / v3length(v_);
#endif
}
inline
m mmult_sse(const m* m0_, const m* m1_)
{
__m128* p0 = (__m128*)m0_;
__m128* p1 = (__m128*)m1_;
__m128 m0_x = _mm_loadu_ps((float*)&p0[0]);
__m128 m0_y = _mm_loadu_ps((float*)&p0[1]);
__m128 m0_z = _mm_loadu_ps((float*)&p0[2]);
__m128 m0_w = _mm_loadu_ps((float*)&p0[3]);
__m128 m1_x = _mm_loadu_ps((float*)&p1[0]);
__m128 m1_y = _mm_loadu_ps((float*)&p1[1]);
__m128 m1_z = _mm_loadu_ps((float*)&p1[2]);
__m128 m1_w = _mm_loadu_ps((float*)&p1[3]);
__m128 rx = _mm_mul_ps(m0_x, _mm_shuffle_ps(m1_x, m1_x, 0));
rx = _mm_add_ps(rx, _mm_mul_ps(m0_y, _mm_shuffle_ps(m1_x,m1_x, 0x55)));
rx = _mm_add_ps(rx, _mm_mul_ps(m0_z, _mm_shuffle_ps(m1_x, m1_x, 0xaa)));
rx = _mm_add_ps(rx, _mm_mul_ps(m0_w, _mm_shuffle_ps(m1_x, m1_x, 0xff)));
__m128 ry = _mm_mul_ps(m0_x, _mm_shuffle_ps(m1_y, m1_y, 0));
ry = _mm_add_ps(ry, _mm_mul_ps(m0_y, _mm_shuffle_ps(m1_y,m1_y, 0x55)));
ry = _mm_add_ps(ry, _mm_mul_ps(m0_z, _mm_shuffle_ps(m1_y, m1_y, 0xaa)));
ry = _mm_add_ps(ry, _mm_mul_ps(m0_w, _mm_shuffle_ps(m1_y, m1_y, 0xff)));
__m128 rz = _mm_mul_ps(m0_x, _mm_shuffle_ps(m1_z, m1_z, 0));
rz = _mm_add_ps(rz, _mm_mul_ps(m0_y, _mm_shuffle_ps(m1_z,m1_z, 0x55)));
rz = _mm_add_ps(rz, _mm_mul_ps(m0_z, _mm_shuffle_ps(m1_z, m1_z, 0xaa)));
rz = _mm_add_ps(rz, _mm_mul_ps(m0_w, _mm_shuffle_ps(m1_z, m1_z, 0xff)));
__m128 rw = _mm_mul_ps(m0_x, _mm_shuffle_ps(m1_w, m1_w, 0));
rw = _mm_add_ps(rw, _mm_mul_ps(m0_y, _mm_shuffle_ps(m1_w,m1_w, 0x55)));
rw = _mm_add_ps(rw, _mm_mul_ps(m0_z, _mm_shuffle_ps(m1_w, m1_w, 0xaa)));
rw = _mm_add_ps(rw, _mm_mul_ps(m0_w, _mm_shuffle_ps(m1_w, m1_w, 0xff)));
m r1;
_mm_storeu_ps((float*)&((__m128*)&r1)[0], rx);
_mm_storeu_ps((float*)&((__m128*)&r1)[1], ry);
_mm_storeu_ps((float*)&((__m128*)&r1)[2], rz);
_mm_storeu_ps((float*)&((__m128*)&r1)[3], rw);
return r1;
}
| true |
30da04f145f8f05ff129718313ff2ea30723fdd6 | C++ | yzysonic/DirectX-first-game | /DirectX 初ゲーム/Core/Color.h | UTF-8 | 734 | 2.640625 | 3 | [] | no_license | #pragma once
class Color
{
public:
unsigned char b;
unsigned char g;
unsigned char r;
unsigned char a;
//unsigned long data;
Color(void);
Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
//unsigned char getR(void);
//unsigned char getG(void);
//unsigned char getB(void);
//unsigned char getA(void);
void setRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
//void setR(unsigned char value);
//void setG(unsigned char value);
//void setB(unsigned char value);
//void setA(unsigned char value);
public:
static const Color white;
static const Color black;
static const Color red;
static const Color green;
static const Color blue;
static const Color none;
}; | true |
36a0b09ca356de00ddbefb68d5e17ab0e0a0b0fb | C++ | JOLO1011/ESP32-PWM-FAN-CONTROL | /PWM_FANControl_Webserver.ino | UTF-8 | 25,442 | 2.671875 | 3 | [] | no_license |
#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
////////////////////////////////////////////////////////
// Webserver
////////////////////////////////////////////////////////
WiFiServer server(80); //Port 80
// Variable to store the HTTP request
String header;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 20000;
////////////////////////////////////////////////////////
// WiFi connect
////////////////////////////////////////////////////////
//Enter your SSID and PASSWORD
const char* ssid = "********";
const char* password = "*******";
////////////////////////////////////////////////////////
// Fan modes
////////////////////////////////////////////////////////
// Output Status
String luefter1State = "auto";
String luefter2State = "auto";
String luefter3State = "auto";
String luefter4State = "auto";
// definition of PWM pins:
const int luefter1 = 16; // 16 corresponds to GPIO16, sets fan1(luefter1) to GPIO16
const int luefter2 = 17; // 17 corresponds to GPIO17, sets fan2(luefter2) to GPIO17
const int luefter3 = 18; // 18 corresponds to GPIO18, sets fan3(luefter3) to GPIO18
const int luefter4 = 19; // 19 corresponds to GPIO19, sets fan4(luefter4) to GPIO19
////////////////////////////////////////////////////////
// Temperatur Sensor
////////////////////////////////////////////////////////
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
////////////////////////////////////////////////////////
// PWM Werte setzen
////////////////////////////////////////////////////////
// setting PWM properties
const int freq1 = 200; //frequency fan1(luefter1)
const int freq2 = 200; //frequency fan2(luefter2)
const int freq3 = 200; //frequency fan3(luefter3)
const int freq4 = 200; //frequency fan4(luefter4)
const int resolution = 8; //bit-resolution
const int pwmChannel1 = 0; //inner PWM-Channels
const int pwmChannel2 = 1; //inner PWM-Channels
const int pwmChannel3 = 2; //inner PWM-Channels
const int pwmChannel4 = 3; //inner PWM-Channels
//FanSpeed Variablen
int fanSpeed = 0; //basic fanspeed(set to 0)
int tempMin = 22; //definition of minimum temperature
int tempMax = 28; //definition of maximum temperature
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// Setup
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
void setup() {
Serial.begin(115200); //baud rate
Serial.println("Ready");
// configure PWM functionalitites
ledcSetup(pwmChannel1, freq1, resolution);
ledcSetup(pwmChannel2, freq2, resolution);
ledcSetup(pwmChannel3, freq3, resolution);
ledcSetup(pwmChannel4, freq4, resolution);
// channelvariable for GPIO-control
ledcAttachPin(luefter1, pwmChannel1);
ledcAttachPin(luefter2, pwmChannel2);
ledcAttachPin(luefter3, pwmChannel3);
ledcAttachPin(luefter4, pwmChannel4);
// temperaturesensor start
sensors.begin();
// initializing Output variables
pinMode(luefter1, OUTPUT);
pinMode(luefter2, OUTPUT);
pinMode(luefter3, OUTPUT);
pinMode(luefter4, OUTPUT);
// Set outputs to LOW
pinMode(luefter1, LOW);
pinMode(luefter2, LOW);
pinMode(luefter3, LOW);
pinMode(luefter4, LOW);
// connection to Network, for example WLAN
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Output of the connection options
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// start web server
server.begin();
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// loop
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
void loop(void) {
// read temperature sensor
sensors.requestTemperatures(); //Request to temperature sensor
float temperatureC = sensors.getTempCByIndex(0); //sets temperatureC to input value
String StemperatureC; //StemperatureC for Webserver, (actually Value)
StemperatureC = String(temperatureC); //cast temperature variable too String Casten for output an the Webserver
Serial.print(temperatureC);
Serial.println("ºC");
delay(100);
//------------------------------------------------------------------------
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns Luefter status auto -> on -> off -> auto...
if (header.indexOf("GET /1/on") >= 0) { //fan1, Url-extension
Serial.println("L\x81fter 1 on"); //print "fan1 on" to output
luefter1State = "on"; //sets fan1state "on"
}
else if (header.indexOf("GET /1/off") >= 0) { //fan1
Serial.println("L\x81fter 1 off");
luefter1State = "off";
} else if (header.indexOf("GET /1/auto") >= 0) { //fan1
Serial.println("L\x81fter 1 auto");
luefter1State = "auto";
}
else if (header.indexOf("GET /2/on") >= 0) { //fan2
Serial.println("L\x81fter 2 on");
luefter2State = "on";
} else if (header.indexOf("GET /2/off") >= 0) { //fan2
Serial.println("L\x81fter 2 off");
luefter2State = "off";
} else if (header.indexOf("GET /2/auto") >= 0) { //fan2
Serial.println("L\x81fter 2 auto");
luefter2State = "auto";
}
else if (header.indexOf("GET /3/on") >= 0) { //fan3
Serial.println("L\x81fter 3 on");
luefter3State = "on";
} else if (header.indexOf("GET /3/off") >= 0) { //fan3
Serial.println("L\x81fter 3 off");
luefter3State = "off";
} else if (header.indexOf("GET /3/auto") >= 0) { //fan3
Serial.println("L\x81fter 3 auto");
luefter3State = "auto";
}
else if (header.indexOf("GET /4/on") >= 0) { //fan4
Serial.println("L\x81fter 4 on");
luefter4State = "on";
} else if (header.indexOf("GET /4/off") >= 0) { //fan4
Serial.println("L\x81fter 4 off");
luefter4State = "off";
} else if (header.indexOf("GET /4/auto") >= 0) { //fan4
Serial.println("L\x81fter 4 auto");
luefter4State = "auto";
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" http-equiv=\"refresh\" content=\"2\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
// Three Button colors for the three modes "on","off","auto"
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button3 {background-color: #D8D800;border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// current temperature
client.println("<h1>Temperatur: " + StemperatureC + "°C</h1>");
// Display current state, and ON/OFF/AUTO buttons for fan1(luefter1)
client.println("<p>Lüfter1 - Status " + luefter1State + "</p>");
// If the luefter1State is off, it displays the auto button
if (luefter1State == "off") {
client.println("<p><a href=\"/1/auto\"><button class=\"button button3\">AUTO</button></a></p>");
luefter1State = "off";
}
// If the luefter1State is auto, it displays the on button
else if (luefter1State == "auto") {
client.println("<p><a href=\"/1/on\"><button class=\"button \">ON</button></a></p>");
luefter1State = "auto";
}
// If the luefter1State is on, it displays the off button
else {
client.println("<p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>");
luefter1State = "on";
}
// If the luefter2State is off, it displays the auto button
client.println("<p>Lüfter2 - Status " + luefter2State + "</p>");
if (luefter2State == "off") {
client.println("<p><a href=\"/2/auto\"><button class=\"button button3\">AUTO</button></a></p>");
luefter2State = "off";
}
// If the luefter2State is auto, it displays the on button
else if (luefter2State == "auto") {
client.println("<p><a href=\"/2/on\"><button class=\"button \">ON</button></a></p>");
luefter2State = "auto";
}
// If the luefter2State is on, it displays the off button
else {
client.println("<p><a href=\"/2/off\"><button class=\"button button2\">OFF</button></a></p>");
luefter2State = "on";
}
// If the luefter3State is off, it displays the auto button
client.println("<p>Lüfter3 - Status " + luefter3State + "</p>");
if (luefter3State == "off") {
client.println("<p><a href=\"/3/auto\"><button class=\"button button3\">AUTO</button></a></p>");
luefter3State = "off";
}
// If the luefter3State is auto, it displays the on button
else if (luefter3State == "auto") {
client.println("<p><a href=\"/3/on\"><button class=\"button \">ON</button></a></p>");
luefter3State = "auto";
}
// If the luefter3State is on, it displays the off button
else {
client.println("<p><a href=\"/3/off\"><button class=\"button button2\">OFF</button></a></p>");
luefter3State = "on";
}
// If the luefter4State is off, it displays the auto button
client.println("<p>Lüfter4 - Status " + luefter4State + "</p>");
if (luefter4State == "off") {
client.println("<p><a href=\"/4/auto\"><button class=\"button button3\">AUTO</button></a></p>");
luefter4State = "off";
}
// If the luefter4State is auto, it displays the on button
else if (luefter4State == "auto") {
client.println("<p><a href=\"/4/on\"><button class=\"button \">ON</button></a></p>");
luefter4State = "auto";
}
// If the luefter4State is on, it displays the off button
else {
client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
luefter4State = "on";
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
//-------------------------------------------------
// fan1(Luefter 1) state requesting
if (luefter1State == "auto") // auto = automatical PWM regulation
{
if (temperatureC < tempMin)
{
//Temperature below tempMin fan1 off
fanSpeed = 0;
Serial.println("L1 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel1, fanSpeed);
}
else if (temperatureC >= tempMin && temperatureC < tempMax)
{
//Temperature from tempMin fan1 20% -80%
//0...255 = 256 values because of 8-bit
// 32 means 20% of 256 values and 80% means 216
//fanSpeed = map(tempC, tempMin, tempMax, 32, 255);
fanSpeed = map(temperatureC, tempMin, tempMax, 32, 216);
Serial.println("L1 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel1, fanSpeed);
}
else if (temperatureC >= tempMax)
{
//Temperature from temMax fan1 100%
fanSpeed = 255; //fanSpeed 100% means 255
Serial.println("L1 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel1, fanSpeed);
}
}
else if (luefter1State == "off") // no terms -> fan 1 off
{
fanSpeed = 0;
Serial.println("L1 = off , fanSpeed= " + String(fanSpeed));
ledcWrite(pwmChannel1, fanSpeed);
}
else if (luefter1State == "on") // no terms -> fan 1 on
{
fanSpeed = 255;
Serial.println("L1 = on , fanSpeed= " + String(fanSpeed));
ledcWrite(pwmChannel1, fanSpeed);
}
// fan2(Luefter 2) state requesting
if (luefter2State == "auto") // auto = automatical PWM regulation
{
if (temperatureC < tempMin)
{
//Temperature below tempMin fan2 off
fanSpeed = 0;
Serial.println("L2 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel2, fanSpeed);
}
else if (temperatureC >= tempMin && temperatureC < tempMax)
{
//Temperature from tempMin fan2 20% -80%
//0...255 = 256 values because of 8-bit
// 32 means 20% of 256 values and 80% means 216
//fanSpeed = map(tempC, tempMin, tempMax, 32, 255)
fanSpeed = map(temperatureC, tempMin, tempMax, 32, 216);
Serial.println("L2 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel2, fanSpeed);
}
else if (temperatureC >= tempMax)
{
//Temperature from temMax fan2 100%
fanSpeed = 255; //fanSpeed 100% means 255
Serial.println("L2 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel2, fanSpeed);
}
}
else if (luefter2State == "off") // no terms -> fan 2 off
{
fanSpeed = 0;
Serial.println("L2 = off , fanSpeed= " + String(fanSpeed));
ledcWrite(pwmChannel2, fanSpeed);
}
else if (luefter2State == "on") // no terms -> fan 2 on
{ fanSpeed = 255;
Serial.println("L2 = on , fanSpeed= " + String(fanSpeed));
ledcWrite(pwmChannel2, fanSpeed);
}
// fan3(Luefter 3) state requesting
if (luefter3State == "auto") // auto = automatical PWM regulation
{
if (temperatureC < tempMin)
{
//Temperature below tempMin fan3 off
fanSpeed = 0;
Serial.println("L3 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel3, fanSpeed);
}
else if (temperatureC >= tempMin && temperatureC < tempMax)
{
//Temperature from tempMin fan3 20% -80%
//0...255 = 256 values because of 8-bit
// 32 means 20% of 256 values and 80% means 216
//fanSpeed = map(tempC, tempMin, tempMax, 32, 255);
fanSpeed = map(temperatureC, tempMin, tempMax, 32, 216);
Serial.println("L3 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel3, fanSpeed);
}
else if (temperatureC >= tempMax)
{
//Temperature from tempMax fan3 100%
fanSpeed = 255; //fanSpeed 100% means 255
Serial.println("L3 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel3, fanSpeed);
}
}
else if (luefter3State == "off") // no terms -> fan 3 off
{
fanSpeed = 0;
Serial.println("L3 = off , fanSpeed= " + String(fanSpeed));
ledcWrite(pwmChannel3, fanSpeed);
}
else if (luefter3State == "on") // no terms -> fan 3 on
{
fanSpeed = 255;
Serial.println("L3 = on , fanSpeed= " + String(fanSpeed));
ledcWrite(pwmChannel3, fanSpeed);
}
// fan4(Luefter 4) state requesting
if (luefter4State == "auto") // auto = automatical PWM regulation
{
if (temperatureC < tempMin)
{
//Temperature below tempMin fan4 off
fanSpeed = 0;
Serial.println("L4 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel4, fanSpeed);
}
else if (temperatureC >= tempMin && temperatureC < tempMax)
{
//Temperature from tempMin fan4 20% -80%
//0...255 = 256 values because of 8-bit
// 32 means 20% of 256 values and 80% means 216
//fanSpeed = map(tempC, tempMin, tempMax, 32, 255);
fanSpeed = map(temperatureC, tempMin, tempMax, 32, 216);
Serial.println("L4 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel4, fanSpeed);
}
else if (temperatureC >= tempMax)
{
//Temperature from tempMax fan4 100%
fanSpeed = 255; //fanSpeed 100% means 255
Serial.println("L4 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed)); //print in serial interface the temperature,the current terms and the fan speed
ledcWrite(pwmChannel4, fanSpeed);
}
}
else if (luefter4State=="off") // no terms -> fan 4 off
{
fanSpeed = 0;
Serial.println("L4 = off , fanSpeed= "+String(fanSpeed));
ledcWrite(pwmChannel4, fanSpeed);
}
else if (luefter4State=="on") // no terms -> fan 4 on
{
fanSpeed = 255;
Serial.println("L4 = on , fanSpeed= "+String(fanSpeed));
ledcWrite(pwmChannel4, fanSpeed);
}
}
| true |
700db65cb045498d857545e2fe44b9567c6b21c0 | C++ | xuanjin001/Leetcode | /C++/139.word-break.cpp | UTF-8 | 1,057 | 3.015625 | 3 | [] | no_license | /*
* @lc app=leetcode id=139 lang=cpp
*
* [139] Word Break
*/
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
std::vector<int>::iterator it;
if(wordDict.size()==0) return false;
vector<bool> dp(s.size()+1, false);
dp[0]=true;
for(int i=1; i<=s.size(); i++) {
for(int i=i-1; i>=0; i--) {
for(int j=i-1; j>=0; j--) {
if(dp[j]){
string word = s.substr(j, i-j);
// std::find function call
it = std::find(wordDict.begin(), wordDict.end(), word);
//if(wordDict.find(word) != wordDict.end()){
if (it != wordDict.end()) {
dp[j]=true;
break; //next i
}
}
}
}
return dp[s.size()];
//it = std::find (vec.begin(), vec.end(), ser);
}
}
};
| true |
2dbff50fe428eaa4d5489d48e20563805407fc76 | C++ | drago-96/competitive-programming | /lezione19/bipartite.cpp | UTF-8 | 1,877 | 3.53125 | 4 | [] | no_license | // https://practice.geeksforgeeks.org/problems/bipartite-graph/1
/*
We use the algorithm seen in class: run a BFS colouring greedily the vertices. If at some points we fail to do so, we have an odd cycle and the graph isn't bipartite; otherwise it is.
Running time is O(V+E).
*/
// C++ program to find out whether a given graph is Bipartite or not.
// It works for disconnected graph also.
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
bool isBipartite(int G[][MAX],int V);
int main()
{
int t;
cin>>t;
int g[MAX][MAX];
while(t--)
{
memset(g,0,sizeof (g));
int n;
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>g[i][j];
}
}
cout<<isBipartite(g,n)<<endl;
}
return 0;
}
/*This is a function problem.You only need to complete the function given below*/
/*The function takes an adjacency matrix representation of the graph (g)
and an integer(v) denoting the no of vertices as its arguments.
You are required to complete below method */
bool isBipartite(int G[][MAX],int N)
{
queue<pair<int,int>> Q;
int colors[N];
bool visited[N];
for (int i=0;i<N;i++) colors[i] = -1;
for (int i=0;i<N;i++) visited[i] = false;
for (int idx=0;idx<N;idx++) {
if (!visited[idx]) {
Q.push(make_pair(idx,0));
while (!Q.empty()) {
pair<int,int> cur = Q.front();
Q.pop();
int other_col = 1 - cur.second;
if (colors[cur.first] == other_col) return false;
colors[cur.first] = cur.second;
if (!visited[cur.first]) {
visited[cur.first] = true;
for (int x=0;x<N;x++) {
if (G[cur.first][x] == 1) Q.push(make_pair(x, other_col));
}
}
}
}
}
return true;
}
| true |
a2823900bf2ac23fae9c90e75173213c3022a448 | C++ | FlyingFishPeng/jianzhioffer | /minDepth.cpp | GB18030 | 409 | 3.609375 | 4 | [] | no_license | /*
ĿСȡ
*/
/*
˼·ݹ顣
*/
int minDepth(TreeNode* root)
{
if (root == NULL)
return 0;
if (root->left == NULL&&root->right == NULL)
return 1;
int left = minDepth(root->left);
int right = minDepth(root->right);
if (root->left == NULL)
return right + 1;
if (root->right == NULL)
return left + 1;
return left > right ? (right + 1) : (left + 1);
}
| true |
ec3daf8643f854d10f3b5fd39fe45bcae3bb2d63 | C++ | Bhoomikapanwar/Prac | /Array_prodpair.cpp | UTF-8 | 538 | 2.53125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int t,n,p;
cin>>t;
while(t){
int flag=0;
cin>>n>>p;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int j=0;j<n;j++){
for(int k=j+1;k<n;k++){
if((a[j]*a[k])==p)
{
flag=1;
break;
}
}
}
if(flag==1)
cout<<"Yes";
else
cout<<"No";
cout<<"\n";
t--;
}
return 0;
}
| true |
47049df97fe65c169a734fa3bbf889c5b7a92906 | C++ | Evalir/Algorithms | /Problems/codeforces/144-A/144-A-31608832.cpp | UTF-8 | 881 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> soldiers;
for(int i = 0; i < n; i++) {
int x;
cin >> x;
soldiers.push_back(x);
}
int hsoldier = 0, lsoldier = 100;
int hpos = 0, lpos = 0;
int seconds;
for (int i = 0; i < n; i++) {
if (soldiers[i] > hsoldier) {
hsoldier = soldiers[i];
hpos = i;
}
if (soldiers[i] < lsoldier) {
lsoldier = soldiers[i];
lpos = i;
}
if (soldiers[i] == hsoldier && i < hpos) {
hsoldier = soldiers[i];
hpos = i;
}
if (soldiers[i] == lsoldier && i > lpos) {
lsoldier = soldiers[i];
lpos = i;
}
}
//cout << hpos << " HIGH LOW " << lpos << endl;
//calculate seconds;
if (hpos < lpos) seconds = hpos + ((soldiers.size() - 1) - lpos);
else if (lpos < hpos) seconds = (hpos - 1) + ((soldiers.size() - 1) - lpos);
cout << seconds << endl;
} | true |
a4b5d83142570e7a924ffcd3373efb00afa7921f | C++ | akeskimo/salary-administration-gui | /SalaryAdministrationGui/src/model/MonthlyPaidEmployee.h | UTF-8 | 1,016 | 3.15625 | 3 | [] | no_license | //============================================================================
// Name : MonthlyPaidEmployee.h
// Author : Aapo Keskimolo
// Description : Definition file for monthly paid employee class. Inherits from
// Employee base-class.
//============================================================================
#pragma once
#ifndef MONTHLYPAIDEMPLOYEE_H_
#define MONTHLYPAIDEMPLOYEE_H_
#include "Employee.h"
class MonthlyPaidEmployee: public Employee
{
private:
double monthlySalary;
public:
MonthlyPaidEmployee(string newFirstName, string newLastName,
string newSsn, double newMonthlySalary);
virtual ~MonthlyPaidEmployee();
void setMonthlySalary(double newMonthlySalary);
double getMonthlySalary();
double getSalary();
friend std::ofstream& operator<<(std::ofstream& os, const MonthlyPaidEmployee& e);
friend std::ifstream& operator>>(std::ifstream& is, MonthlyPaidEmployee& e);
};
#endif /* MONTHLYPAIDEMPLOYEE_H_ */
| true |
571a5c1940dbaf965131a76eae63a1966e4b840f | C++ | RishabhDevbanshi/C-Codes | /Bactracking/Knights-Tour.cpp | UTF-8 | 1,026 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define n 8
bool valid(int nx, int ny,int mat[n][n])
{
return (nx>=0 and nx<n and ny>=0 and ny<n and mat[nx][ny]==-1);
}
bool go(int mat[n][n],int x,int y,int dx[n],int dy[n],int mv)
{
if(mv==n*n)
{
return 1;
}
for(int k=0;k<8;k++)
{
int nx = x + dx[k];
int ny = y + dy[k];
if(valid(nx,ny,mat))
{
mat[nx][ny]=mv;
if(go(mat,nx,ny,dx,dy,mv+1)==1)
{
return true;
}
mat[nx][ny] = -1;
}
}
return 0;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int mat[n][n],mv=1;
memset(mat,-1,sizeof(mat));
mat[0][0]=0;
int dx[8]={2,1,-1,-2,-2,-1,1,2};
int dy[8]={1,2,2,1,-1,-2,-2,-1};
if(go(mat,0,0,dx,dy,mv))
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<mat[i][j]<<"\t";
}
cout<<endl;
}
}
return 0;
}
| true |
e079f20ffc7a3f95d173b72e6aa071101bd7037f | C++ | CAHenry/AudioProgramming | /Coursework Three/Source/DelayLine.cpp | UTF-8 | 1,179 | 2.921875 | 3 | [] | no_license | /*
==============================================================================
DelayLine.cpp
Created: 9 Jan 2018 10:41:34pm
Author: Craig
==============================================================================
*/
#include "DelayLine.h"
Delay::Delay (int numSamplesToAllocate)
: delayLine (1, numSamplesToAllocate)
{
samplesAllocated = numSamplesToAllocate;
delayTimes[0] = 22100;
writeIndex = 0;
}
Delay::~Delay ()
{
}
void Delay::write (float val)
{
float* writePointer = delayLine.getWritePointer (0, writeIndex);
*writePointer = val;
}
void Delay::increment ()
{
writeIndex = (writeIndex + 1) % samplesAllocated;
}
float Delay::read (int tap)
{
float delayTime = delayTimes[tap].getNextValue ();
int low = floor (delayTime);
int high = (low + 1) % samplesAllocated;
float fPart = delayTime - low;
const float* lowIndex = delayLine.getReadPointer (0, (writeIndex - low + samplesAllocated) % samplesAllocated);
const float* highIndex = delayLine.getReadPointer (0, (writeIndex - high + samplesAllocated) % samplesAllocated);
return (*lowIndex * (1 - fPart)) + (*highIndex * fPart);
}
| true |
0e4f45726b95d94e2be9dcbb0dff935e7516f709 | C++ | caasI25Vilen/bst_in_bst | /bst_in_bst/bst_in_bst.h | UTF-8 | 2,983 | 3.40625 | 3 | [] | no_license | #pragma once
#include<cmath>
///////////////////////////////////// ** BST ** /////////////////////////////////////
template<typename T>
class BST
{
public:
BST();
BST(const BST& src);
~BST();
const T& findMin() const;
const T& findMax() const;
bool contain(const T& item) const;
bool isEmpty() const;
void makeEmpty();
void insert(const T& item);
void remove(const T& item);
private:
struct BinaryNode
{
T element_;
BinaryNode* left_;
BinaryNode* right_;
BinaryNode(const T& element, BinaryNode* left, BinaryNode* right)
: element_(element), left_(left), right_(right) {};
};
BinaryNode* root_;
bool contain(const T& item, BinaryNode* node) const;
void insert(const T& item, BinaryNode*& node);
void remove(const T& item, BinaryNode* node);
void makeEmpty(BinaryNode*& node);
BinaryNode* findMin(BinaryNode* node) const;
BinaryNode* findMax(BinaryNode* node) const;
BinaryNode* clone(BinaryNode* node) const;
};
///////////////////////////////////// ** BST in BST ** /////////////////////////////////////
template<typename T>
class BST_BST
{
public:
BST_BST(const unsigned short int& elemNumb = 7); // Maximum Depth of Nested Binary Search Tree
BST_BST(const BST_BST& src);
~BST_BST();
const T& findMin() const;
const T& findMax() const;
bool isEmpty() const;
bool contain(const T& item) const;
void makeEmpty();
void insert(const T& item);
void remove(const T& item);
private:
struct BST_Node
{
struct BinaryNode
{
T element_;
BinaryNode* BN_left;
BinaryNode* BN_right;
BinaryNode(const T& element, BinaryNode* lt, BinaryNode* rt)
: element_(element), BN_left(lt), BN_right(rt), counter_(counter_ - 1), depth_(depth_ - 1) {}
};
BinaryNode* BN_root;
T* minNode_;
T* maxNode_;
BST_Node* BST_left;;
BST_Node* BST_right;
unsigned short int counter_ = 7; // Maximum Number of Nodes (Binary Nodes)
short int depth_ = log2(counter_ + 1) - 1; // Maximum Depth of Nested Binary Search Tree
BST_Node(BinaryNode* BNroot, BST_Node* BSTleft, BST_Node* BSTright)
: BN_root(BNroot), BST_left(BSTleft), BST_right(BSTright), minNode_(nullptr), maxNode_(nullptr) {}
bool contain(const T& item, BinaryNode* node) const;
bool isFull() const;
void insert(const T& item, BinaryNode* node);
void remove(const T& item, BinaryNode* node);
void makeEmpty(BinaryNode*& node);
void clone(BinaryNode* node) const;
//BinaryNode* findMin(BinaryNode* node) const; //** I think it won't be necessary
//BinaryNode* findMax(BinaryNode* node) const; //** I think it won't be necessary
};
BST_Node* BST_root;
bool contain(const T& item, BST_Node* node) const;
void insert(const T& item, BST_Node*& node);
void remove(const T& item, BST_Node*& node);
void makeEmpty(BST_Node*& node);
void clone(BST_Node* node) const;
BST_Node* findMin(BST_Node* node) const; //** I think it won't be necessary
BST_Node* findMax(BST_Node* node) const; //** I think it won't be necessary
}; | true |
cca0689da1517650cffe97864ebeca2e193f0830 | C++ | DragonJoker/Castor3D | /include/Core/CastorUtils/Graphics/UnsupportedFormatException.hpp | UTF-8 | 1,267 | 2.59375 | 3 | [
"MIT"
] | permissive | /*
See LICENSE file in root folder
*/
#ifndef ___CU_UnsupportedFormatException_H___
#define ___CU_UnsupportedFormatException_H___
#include "CastorUtils/Graphics/GraphicsModule.hpp"
#include "CastorUtils/Exception/Exception.hpp"
namespace castor
{
class UnsupportedFormatException
: public castor::Exception
{
public:
/**
*\~english
*\brief Constructor
*\param[in] description Error description
*\param[in] file Function file
*\param[in] function Function name
*\param[in] line Function line
*\~french
*\brief Constructeur
*\param[in] description Description de l'erreur
*\param[in] file Fichier contenant la fonction
*\param[in] function Nom de la fonction
*\param[in] line Ligne dans la fonction
*/
UnsupportedFormatException( std::string const & description
, char const * file
, char const * function
, uint32_t line )
: Exception( description, file, function, line )
{
}
};
}
/**
*\~english
*\brief english Helper macro to use UnsupportedFormatException
*\~french
*\brief Macro écrite pour faciliter l'utilisation de UnsupportedFormatException
*/
#define CU_UnsupportedError( text ) throw castor::UnsupportedFormatException{ text, __FILE__, __FUNCTION__, uint32_t( __LINE__ ) }
#endif
| true |
d9337e1c6d28e1500375b951248c724374b71bf2 | C++ | Nebrija-Programacion/Programacion-II | /examenes/1819/extraordinaria/solucion/ejercicio1/caballo.cpp | UTF-8 | 327 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include "caballo.h"
Caballo::Caballo(string nombre, string sexo, int edad):
nombre{nombre},
sexo{sexo},
edad{edad}
{
}
void Caballo::printInfo() const
{
cout << "Mi nombre es: " << nombre << endl;
cout << "Mi edad es: " << edad << endl;
cout << "Mi sexo es: " << sexo << endl;
}
| true |
3c2b1689024c73a0780144a8f8b0eb1cb10ba90f | C++ | fanmanqian/learnCplusplus | /20190104/const.cc | UTF-8 | 870 | 3.28125 | 3 | [] | no_license | #include<iostream>
using std::cout;
using std::endl;
//C++/Java/C 编译型(静态)语言
//动态语言 没有太好的调试工具 解释执行 没有编译的过程
//宏定义发生的时机是预处理,只会简单的进行字符串替换,没有类型检查;在运行时出现了bug
//不利于错误的发现
#define Max 1024
//#define multi(x,y) x*y //仅仅是进行字符串的替换 1+2*3+4 = 11 出错
//避免这种错误的发生就是加上小括号
#define multi(x,y) (x)*(y)
//C++更多的一种定义常量的方式
//
//发生的时机是编译时,有类型检查,如果出现问题,在编译时就会报错
int const kMax=1024;
const int kMin=1;
int multiply(int x)
{
return x * Max;
}
int add(int x,int y)
{
return x+y+kMin+kMax;
}
int main()
{
cout<<multiply(10)<<endl;
cout<<add(3,4)<<endl;
cout<<multi(1+2,3+4)<<endl;
return 0;
}
| true |
07ec0e42bc99c0477048afca5abd5f128cb334e8 | C++ | snikolova27/UP-2.0 | /Week03_If statements/task05.cpp | UTF-8 | 1,272 | 3.890625 | 4 | [] | no_license | #include <iostream>
int main()
{
int num1, num2, num3;
std::cin >> num1 >> num2 >> num3;
int max = 0, min = 0;
if (num1 == num2 && num2 == num3)
{
std::cout << "All numbers are equal \n";
return 0;
}
else if (num1 > num2 && num1 > num3)
{
max = num1;
min = num2 > num3 ? num3 : num2;
}
else if (num2 > num1 && num2 > num3)
{
max = num2;
min = num1 > num3 ? num3 : num1;
}
else if (num3 > num1 && num3 > num2)
{
max = num3;
min = num1 > num2 ? num2 : num1;
}
else if (num1 == num2 && num1 > num3)
{
min = num3;
max = num1;
}
else if (num1 == num2 && num1 < num3)
{
min = num1;
max = num3;
}
else if (num1 == num3 && num2 < num1)
{
min = num2;
max = num1;
}
else if (num1 == num3 && num2 > num1)
{
min = num1;
max = num2;
}
else if (num2 == num3 && num1 > num3)
{
max = num1;
min = num2;
}
else if (num2 == num3 && num1 < num3)
{
max = num3;
min = num1;
}
std::cout << "Max num is: " << max << std::endl;
std::cout << "Min num is: " << min << std::endl;
return 0;
} | true |
b9b1cefb5dfb276f7c6895f140f7e8ac7b2448dd | C++ | hi-takeda/test | /pointer/src/call_by_value.cpp | UTF-8 | 338 | 3.1875 | 3 | [] | no_license | #include <iostream>
void twice (int a)
{
std::cout << a << " : in twice(int a)" << std::endl;
a *= 2;
std::cout << a << " : in twice(int a)" << std::endl;
}
int main(int argc, char *argv[])
{
int v = 16;
std::cout << v << " : in main()" << std::endl;
twice(v);
std::cout << v << " : in main()" << std::endl;
return 0;
}
| true |
8e7d5b6824fe05dda614ce5ab76e12ef2d71919f | C++ | Qkrka/OS1_project | /h/WList.h | UTF-8 | 407 | 2.875 | 3 | [] | no_license | #ifndef WLIST_H_
#define WLIST_H_
#include "PCB.h"
struct Node{
PCB* pcb;
Time time;
Node* next;
Node(PCB* p, Time t){
pcb=p;
time=t;
next=NULL;
}
};
class WaitList {
private:
Node* first;
public:
WaitList(){
first=NULL;
}
~WaitList();
void add(PCB* p, Time t);
PCB* pop();
PCB* remove();
int decTime();
int isEmpty(){
return ((first!=NULL) ? 0:1);
}
};
#endif | true |
c525673e76568ce3c60a05dcef00b7127b93c3ae | C++ | LonglongSang/Life_of_XDU | /PTA/Basic_Level/1013.cpp | UTF-8 | 656 | 3 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <math.h>
using namespace std;
bool is_o(int n);
int main(){
int count=0;
int low,high;
cin>>low>>high;
vector<int> oo;
int o_count=0;
for(int i=1;i<=10000000000;i++){
if(is_o(i)){
oo.push_back(i);
o_count++;
}
if(o_count==high) break;
}
for(int i=low-1;i<=high-1;i++){
if(count){
cout<<" "<<oo[i];
}else{
cout<<oo[i];
}
count++;
if(count==10){
cout<<endl;
count=0;
}
}
return 0;
}
bool is_o(int n){
if(n==1) return false;
for(int i=2;i<=(int)sqrt(n);i++){
if(n%i==0){
return false;
}
}
return true;
} | true |
9b7d2f678bbaacd210dafa8110aab2b015fac95d | C++ | Aleshkev/algoritmika | /archive/2/po_prostu_xor.cpp | UTF-8 | 673 | 2.875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #include <iostream>
using namespace std;
typedef unsigned I;
int main()
{
cout.sync_with_stdio(false);
I n, k;
cin >> n >> k;
I *t = new I[n];
for(I i = 0; i < n; ++i) {
cin >> t[i];
}
I *prefixes = new I[n];
prefixes[0] = t[0];
for(I i = 1; i < n; ++i) {
prefixes[i] = prefixes[i - 1] ^ t[i];
}
I *prefixes_xored = new I[n];
for(I i = 0; i < n; ++i) {
prefixes_xored[i] = prefixes[i] ^ k;
}
for(I i = 0; i < n; ++i) {
cout << prefixes[i] << " ";
} cout << endl;
for(I i = 0; i < n; ++i) {
cout << prefixes_xored[i] << " ";
} cout << endl;
return 0;
}
| true |
984bfe61971e04451b6ce4bacdde646c69a2ce2f | C++ | freds0/HighPrecisionAdaptiveMesh | /OpenGL/openGL.cpp | UTF-8 | 6,530 | 2.71875 | 3 | [] | no_license | #include "openGL.h"
static bool
CONFIG_LOCAL_SHOW_TRIANGLE = true,
CONFIG_LOCAL_SHOW_CIRCLE = true,
CONFIG_LOCAL_SHOW_VORONOI_DIAGRAM = true,
CONFIG_LOCAL_SHOW_VERTEX_LABEL = true;
void openGL::drawLine( mpfr::real<MPFR_BITS_PRECISION> x1, mpfr::real<MPFR_BITS_PRECISION> y1, mpfr::real<MPFR_BITS_PRECISION> x2, mpfr::real<MPFR_BITS_PRECISION> y2, double r, double g, double b )
{
double x1_double = 0, y1_double = 0, x2_double = 0, y2_double = 0;
x1.conv(x1_double);
y1.conv(y1_double);
x2.conv(x2_double);
y2.conv(y2_double);
glColor3f(r, g, b); // Line color
glBegin(GL_LINES);
glVertex2d(x1_double,y1_double);
glVertex2d(x2_double,y2_double);
glEnd();
}
void openGL::drawVertex( Vertex *v )
{
double x_double = 0, y_double = 0;
mpfr::real<MPFR_BITS_PRECISION> x = v->x;
mpfr::real<MPFR_BITS_PRECISION> y = v->y;
x.conv(x_double);
y.conv(y_double);
glPointSize(5.5);
glBegin(GL_POINTS);
glColor3f(0.0, 0.0, 0.0);
glVertex2d(x_double, y_double);
glEnd();
//
// Print the vertex value
//
std::stringstream s1;
double value_double = 0;
v->u.conv(value_double);
//s1 << value_double;
s1 << v->label;
string str = s1.str();
RenderBitmap(x_double, y_double, str);
}
void openGL::drawVertex( mpfr::real<MPFR_BITS_PRECISION> x, mpfr::real<MPFR_BITS_PRECISION> y )
{
double x_double = 0, y_double = 0;
x.conv(x_double);
y.conv(y_double);
//glPointSize(5.5);
glBegin(GL_POINTS);
glColor3f(0.0, 0.0, 0.0);
glVertex2d(x_double, y_double);
glEnd();
//
// Print the vertex coordinates
//
std::stringstream s1;
s1 << x << "," << y;
string str = s1.str();
RenderBitmap(x_double, y_double, str);
}
void openGL::RenderBitmap(mpfr::real<MPFR_BITS_PRECISION> x, mpfr::real<MPFR_BITS_PRECISION> y, string str)
{
double x_double = 0, y_double = 0;
x.conv(x_double);
y.conv(y_double);
glColor3f( 255,0,0 );
const char *c;
glRasterPos2f (x_double, y_double);
for (c = str.c_str(); *c != '\0' && *(c-3) != '.'; c++)
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *c);
//glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
}
void openGL::drawTriangle( Vertex *v1, Vertex *v2, Vertex *v3 )
{
glColor3f( 0, 0, 0 );
if (CONFIG_LOCAL_SHOW_TRIANGLE || (v1->isBorder && v2->isBorder))
{
drawLine( v1->x, v1->y, v2->x, v2->y, 0, 0, 0 );
}
if (CONFIG_LOCAL_SHOW_TRIANGLE || (v1->isBorder && v3->isBorder))
{
drawLine( v1->x, v1->y, v3->x, v3->y, 0, 0, 0 );
}
if (CONFIG_LOCAL_SHOW_TRIANGLE || (v3->isBorder && v2->isBorder))
{
drawLine( v3->x, v3->y, v2->x, v2->y, 0, 0, 0 );
}
if (CONFIG_LOCAL_SHOW_VERTEX_LABEL)
{
drawVertex(v1);
drawVertex(v2);
drawVertex(v3);
}
}
void openGL::drawCcircle( Vertex *v, mpfr::real<MPFR_BITS_PRECISION> ccenterX, mpfr::real<MPFR_BITS_PRECISION> ccenterY )
{
double ccenterX_double = 0, ccenterY_double = 0, angle_double = 0, raio_double = 0;
mpfr::real<MPFR_BITS_PRECISION> raio = sqrt( ( v->x - ccenterX )*( v->x - ccenterX ) +
( v->y - ccenterY )*( v->y - ccenterY ) );
raio.conv(raio_double);
mpfr::real<MPFR_BITS_PRECISION> angle;
glColor3f(0, 255, 0);
glBegin(GL_LINE_LOOP);
if (CONFIG_LOCAL_SHOW_CIRCLE) {
for( int i=0; i < 300; i++ )
{
angle = (2*3.1415926535*i)/300;
angle.conv(angle_double);
ccenterX.conv(ccenterX_double);
ccenterY.conv(ccenterY_double);
glVertex2d(ccenterX_double + raio_double*cos(angle_double), ccenterY_double + raio_double*sin(angle_double));
}
}
glEnd();
}
void openGL::drawGrid( list<Triangle *> &tlist, list<Adjacency *> &edges, bool CONFIG_SHOW_VERTEX_LABEL, bool CONFIG_SHOW_TRIANGLE, bool CONFIG_SHOW_CIRCLE, bool CONFIG_SHOW_VORONOI_DIAGRAM)
{
CONFIG_LOCAL_SHOW_TRIANGLE = CONFIG_SHOW_TRIANGLE,
CONFIG_LOCAL_SHOW_CIRCLE = CONFIG_SHOW_CIRCLE,
CONFIG_LOCAL_SHOW_VORONOI_DIAGRAM = CONFIG_SHOW_VORONOI_DIAGRAM,
CONFIG_LOCAL_SHOW_VERTEX_LABEL = CONFIG_SHOW_VERTEX_LABEL;
//list<Adjacency *>::iterator ite;
// TODO: descobrir o que faz esse codigo
/*for( ite = edges.begin(); ite != edges.end(); ite++ )
{
Vertex *v0 = (*ite)->getVertex(0);
Vertex *v1 = (*ite)->getVertex(1);
if( (*ite)->type == 1 )
{
glLineWidth(3);
drawLine( v0->x, v0->y, v1->x, v1->y, 0, 0, 0 );
glLineWidth(1);
}
else
drawLine( v0->x, v0->y, v1->x, v1->y, 0, 0, 0 );
}*/
list<Triangle *>::iterator ite;
for( ite = tlist.begin(); ite != tlist.end(); ite++ )
{
Triangle *it = *ite;
Vertex *v1 = it->getVertex(0), *v2 = it->getVertex(1), *v3 = it->getVertex(2);
//
// Draw Triangle
//
drawTriangle(v1, v2, v3);
//
// Draw Circle
//
drawCcircle(it->getVertex(0), it->cCenter[0], it->cCenter[1]);
// TODO: Descobrir o que faz esse codigo
// drawLine( it->cCenter[0], it->cCenter[1], it->getVertex(0)->x, it->getVertex(0)->y, 255,0,255 );
// drawLine( it->cCenter[0], it->cCenter[1], it->getVertex(1)->x, it->getVertex(1)->y, 255,0,255 );
// drawLine( it->cCenter[0], it->cCenter[1], it->getVertex(2)->x, it->getVertex(2)->y, 255,0,255 );
//
// Draws the Voronoi diagram
//
if (CONFIG_LOCAL_SHOW_VORONOI_DIAGRAM) {
if( it->getNeighbor(0) != 0 )
{
drawLine( it->cCenter[COORDINATE_X], it->cCenter[COORDINATE_Y], it->getNeighbor(0)->cCenter[COORDINATE_X], it->getNeighbor(0)->cCenter[COORDINATE_Y], 0,0,255 );
}
if( it->getNeighbor(1) != 0 )
{
drawLine( it->cCenter[COORDINATE_X], it->cCenter[COORDINATE_Y], it->getNeighbor(1)->cCenter[COORDINATE_X], it->getNeighbor(1)->cCenter[COORDINATE_Y], 0,0,255 );
}
if( it->getNeighbor(2) != 0 )
{
drawLine( it->cCenter[COORDINATE_X], it->cCenter[COORDINATE_Y],it->getNeighbor(2)->cCenter[COORDINATE_X], it->getNeighbor(2)->cCenter[COORDINATE_Y], 0,0,255 );
}
}
}
} | true |
9eb3e66ad4a947a27d6df12f058109940134530d | C++ | ant512/WoopsiExtras | /classes/fixedwidthfontbase.h | UTF-8 | 4,489 | 3.0625 | 3 | [] | no_license | #ifndef _FIXED_WIDTH_FONT_BASE_H_
#define _FIXED_WIDTH_FONT_BASE_H_
#include <nds.h>
#include "fontbase.h"
namespace WoopsiUI {
/**
* Abstract class defining the basic properties of a fixed-width font and
* providing some of the essential functionality. Should be used as a base
* class for all fixed-width fonts.
*/
class FixedWidthFontBase : public FontBase {
public:
/**
* Constructor.
* @param bitmapWidth The width of the bitmap containing the font's
* glyph data.
* @param bitmapHeight The height of the bitmap containing the font's
* glyph data.
* @param width The width of an individual glyph.
* @param height The height of the font.
* @param transparentColour The colour in the font bitmap used as the
* background colour.
*/
FixedWidthFontBase(const u16 bitmapWidth, const u16 bitmapHeight, const u8 width, const u8 height, const u16 transparentColour = 0);
/**
* Destructor.
*/
virtual inline ~FixedWidthFontBase() { };
/**
* Gets the width of the font's glyph bitmap.
* @return The width of the font's glyph bitmap.
*/
inline const u16 getBitmapWidth() const { return _bitmapWidth; };
/**
* Gets the height of the font's glyph bitmap.
* @return The height of the font's glyph bitmap.
*/
inline const u16 getBitmapHeight() const { return _bitmapHeight; };
/**
* Get the colour of the pixel at specified co-ordinates.
* @param x The x co-ordinate of the pixel.
* @param y The y co-ordinate of the pixel.
* @return The colour of the pixel.
*/
virtual const u16 getPixel(const s16 x, const s16 y) const = 0;
/**
* Gets the width of an individual glyph.
* @return The width of an individual glyph.
*/
inline const u8 getWidth() const { return _width; };
/**
* Get the width of a string in pixels when drawn with this font.
* @param text The string to check.
* @return The width of the string in pixels.
*/
u16 getStringWidth(const WoopsiString& text) const;
/**
* Get the width of a portion of a string in pixels when drawn with this
* font.
* Useful if you want to determine the length of a string without a
* terminator, or
* the length of a section of a string.
* @param text The string to check.
* @param startIndex The start point of the substring within the string.
* @param length The length of the substring in chars.
* @return The width of the substring in pixels.
*/
inline u16 getStringWidth(const WoopsiString& text, s32 startIndex, s32 length) const { return length * getWidth(); };
/**
* Get the width of an individual character.
* @param letter The character to get the width of.
* @return The width of the character in pixels.
*/
inline u16 getCharWidth(u32 letter) const { return getWidth(); };
/**
* Checks if supplied character is blank in the current font.
* @param letter The character to check.
* @return True if the glyph contains any pixels to be drawn. False if
* the glyph is blank.
*/
virtual inline const bool isCharBlank(const u32 letter) const { return !(_glyphMap[letter >> 3] & (1 << (letter % 8))); };
protected:
/**
* Populates the previously created glyph map with the data on which
* glyphs have data and which do not. Does this by scanning through
* each pixel in each glyph and adding true to the map if data is found
* or false if no data is found.
* @see initGlyphMap().
*/
virtual void createGlyphMap();
/**
* Scans the glyph bitmap at the specified co-ordinates to see if it
* contains data or not. Must be overridden.
* @param x The x co-ordinate of the start of the glyph.
* @param y The y co-ordinate of the start of the glyph.
* @return True if the glyph bitmap contains data for this glyph.
*/
virtual const bool scanGlyph(const u16 x, const u16 y) const = 0;
protected:
/**
* Creates a map of which glyphs have data and which do not.
* @see createGlyphMap().
*/
void initGlyphMap();
u8 _glyphMap[GLYPH_MAP_SIZE]; /**< Map of which characters have glyphs in the current font. */
private:
u8 _width; /**< The width of a single glyph. */
u16 _bitmapWidth; /**< Width of the bitmap containing glyph data. */
u16 _bitmapHeight; /**< Height of the bitmap containing glyph data. */
};
}
#endif
| true |
0b9e9e570c9612dce937312f1ee0f35e3fa5feff | C++ | kbm0818/Portfolio | /GameProject_L/Systems/GameSystems/Fog.h | UTF-8 | 881 | 2.8125 | 3 | [] | no_license | #pragma once
#include "Object\Shader\ShaderBuffer.h"
class FogBuffer : public ShaderBuffer
{
public:
FogBuffer()
: ShaderBuffer(&data, sizeof(Data))
{
data.fogColor = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);
data.zStart = 10.0f;
data.zEnd = 50.0f;
data.yStart = 3.0f;
data.yEnd = 0.0f;
}
void SetZFog(float start, float end)
{
data.zStart = start;
data.zEnd = end;
}
void SetYFog(float start, float end)
{
data.yStart = start;
data.yEnd = end;
}
private:
friend class Fog;
struct Data
{
D3DXCOLOR fogColor;
float zStart;
float zEnd;
float yStart;
float yEnd;
};
Data data;
};
class Fog
{
public:
Fog();
~Fog();
void Render();
void PostRender();
void SetData(float zStart, float zEnd, float yStart, float yEnd);
void SetZData(float zStart, float zEnd);
void SetYData(float yStart, float yEnd);
private:
FogBuffer* buffer;
}; | true |
80589e02e0ce810bf65e3c948b69afed2d6aa33b | C++ | johnjsb/projectChimaera | /Soft_Nodes/logger/src/log.cpp | UTF-8 | 4,321 | 2.796875 | 3 | [] | no_license | /* *******************************************************************
Rule:
Each team will produce a log file of the mission within around 10 minutes of the end of
the run.
The format of the log file will be a comma separated ASCII file of the format:
Time, position, action, a comment between simple quotes.
(SSSSS,XXX.x,YYY.y,ZZZ.z,AA.aa).
Logged data will be plotted by plotting routine
written by the organising committee. This will be used to score the log file. For acoustic
modem task the additional file of AUV heading and light on/off data and cooperative
AUV heading command will need to be provided. For the ASV tracking task the
additional file of range and bearing data from the AUV to the pinger will need to be
provided.
************************************************************************ */
#include <stdio.h>
#include <stdlib.h>
#include <string>
// writing on a text file
#include <iostream>
#include <fstream>
#include "ros/ros.h"
#include "std_msgs/Int32.h"
#include "std_msgs/Float32.h"
#include "std_msgs/String.h"
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseStamped.h>
void xCallback(const std_msgs::Int32::ConstPtr& logX);
void yCallback(const std_msgs::Int32::ConstPtr& logY);
void zCallback(const std_msgs::Float32::ConstPtr& svpDepth);
void aCallback(const std_msgs::String::ConstPtr& logAction);
void odomCallBack (const nav_msgs::Odometry::ConstPtr& odomData);
int x, y;
float z;
char aa[100];
using namespace std;
int main(int argc, char **argv)
{
//Get start time, to take off from current time
time_t startTime;
startTime=time(NULL);
ros::init(argc, argv, "logger");
ros::NodeHandle n;
//Set up subscriptions
ros::Subscriber sub1 = n.subscribe("odom", 0, odomCallBack);
//ros::Subscriber sub1 = n.subscribe("logX", 100, xCallback);
//ros::Subscriber sub2 = n.subscribe("logY", 100, yCallback);
ros::Subscriber sub3 = n.subscribe("svpDepth", 100, zCallback);
ros::Subscriber sub4 = n.subscribe("logAction", 100, aCallback);
char tmpName[100];
char buff[20];
time_t now = time(NULL);
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));
printf("%s\n", buff);
ofstream logFile ("/home/alex/projectChimaera/Logs/log.txt");
ros::spinOnce();
//Set loop rate (in Hz);
ros::Rate r(5);
while (ros::ok())
{
//Check for new data:
ros::spinOnce();
//Print log file for debugging:
printf("%ld,%f,%f,%f,%s\n", time(NULL) - startTime, x, y, z, aa);
//Save log to file:
if (logFile.is_open())
{
logFile << (time(NULL) - startTime) << ",";
logFile << x << ",";
logFile << y << ",";
logFile << z << ",";
logFile << aa << "\n";
//logFile << "This is a line.\n";
}
else
{
printf("Unable to open file, logging stopped :(.\n");
}
r.sleep();
}
logFile.close();
}
/*************************************************
** Returns the X pose
*************************************************/
void xCallback(const std_msgs::Int32::ConstPtr& logX)
{
x = logX->data;
return;
}
/*************************************************
** Returns the Y pose
*************************************************/
void yCallback(const std_msgs::Int32::ConstPtr& logY)
{
y = logY->data;
return;
}
/*************************************************
** Returns the depth (Z)
*************************************************/
void zCallback(const std_msgs::Float32::ConstPtr& svpDepth)
{
//1 decibar = 1.019716 meters
//convert from milibar to decibar and times by meters per decibar.
z = (100 * svpDepth->data) * 1.019716;
return;
}
/*************************************************
** Returns the sonar bearing **
*************************************************/
void aCallback(const std_msgs::String::ConstPtr& logAction)
{
//aa = logAction->data;
strcpy(aa, (logAction->data.c_str()));
//strcpy(char * dest, const char * src);
//logAction ->data;
return;
}
void odomCallBack (const nav_msgs::Odometry::ConstPtr& odomData)
{
geometry_msgs::PoseStamped odom_pose;
odom_pose.header.frame_id = "odom";
odom_pose.header.stamp = odomData->header.stamp;
odom_pose.pose.position = odomData->pose.pose.position;
odom_pose.pose.orientation = odomData->pose.pose.orientation;
x = odom_pose.pose.position.x;
y = odom_pose.pose.position.y;
return;
}
| true |
e1d143aaa1666840a231a30e710351eaf5f2215c | C++ | gozwei/fuw-programowanie-mikrokontrolerow | /CW04/button_ls/button.cc | UTF-8 | 1,414 | 2.8125 | 3 | [] | no_license | #include <avr/io.h>
#include <avr/interrupt.h>
#include <inttypes.h>
#include "biblio.h"
// Program rozpoznaje krotkie i dlugie (powyzej sekundy) nacisniecie
// przycisku.
//
// Wymagane polaczenia w ukladzie ZL15AVR:
//
// PB0 - SW0
// PD1 - TxD
//
// Autor: Pawel Klimczewski, 12 marca 2012.
static uint8_t t = 0;
#define T1S (61)
uint8_t volatile krotko, dlugo;
ISR( TIMER2_OVF_vect )
{
if ( ( PINB & 1 << PB0 ) == 0 )
{
// Przycisk jest nacisniety. Jezeli akurat uplynela sekunda od chwili
// wcisniecia to klasyfikujemy jako "dlugie" nacisniecie.
if ( t != T1S && ++t == T1S )
++dlugo;
}
else
{
// Przycisk nie jest nacisniety. Jezeli akurat zakonczylo sie
// nacisniecie trwajace ponizej 1 sekundy to klasyfikujemy jako
// "krotkie" nacisniecie.
if ( t != 0 && t != T1S )
++krotko;
t = 0;
}
}
void configure_timer()
{
// Licznik 2 zlicza z czestotliwoscia F_CPU / 1024 = 15 625 Hz
// Przepelnienie nastepuje co 16 ms (61 Hz) i generuje przerwanie
// TIMER2_OVF.
TCCR2 = 1 << CS22 | 1 << CS21 | 1 << CS20;
TIMSK |= 1 << TOIE2;
}
int main()
{
usart( stdout );
configure_timer();
sei();
printf( "nacisnij SW0\n\n" );
int16_t n = 0;
while ( true )
{
if ( krotko )
{
printf( "%d krotko\n", ++n );
--krotko;
}
if ( dlugo )
{
printf( "%d dlugo\n", ++n );
--dlugo;
}
}
return 0;
}
| true |
58c219efbf059122c69040295ebcd0b97368b401 | C++ | thijsking/AirHandlingUnit | /Eind code AHU/_TheUnit/Include/CoolingElement.h | UTF-8 | 627 | 3.015625 | 3 | [] | no_license | #ifndef COOLINGELEMENT_H
#define COOLINGELEMENT_H
#include "iActuator.h"
/**
* \brief This class handles a CoolingElement.
*/
class CoolingElement : public iActuator
{
public:
/**
* \brief Creates a CoolingElement object.
*
* @param iCommunication* is the type of communication that the actuator uses.
* @param uint8_t Unique address that the specific Cooling element has.
*/
CoolingElement(iCommunication*, uint8_t);
/**
* Destroy the CoolingElement object
*/
virtual ~CoolingElement();
/**
* /brief Sets a value to the CoolingElement
*
* @param uint8_t The value to set
*/
virtual void SetValue(uint8_t);
};
#endif | true |
d6c94367c83172eb4d8562bdc3263862763f3add | C++ | ogutetsu/CppDesignPattern | /CppDesignPattern/Composite/NeuralNetwork.cpp | UTF-8 | 1,780 | 3.296875 | 3 | [] | no_license | //
// NeuralNetwork.cpp
// CppDesignPattern
//
// Created by ogurotetsuro on 2019/06/10.
// Copyright © 2019 ogurotetsuro. All rights reserved.
//
#include "NeuralNetwork.hpp"
#include <vector>
#include <iostream>
using namespace std;
struct Neuron;
template<typename Self>
struct SomeNeurons
{
template<typename T> void ConnectTo(T& other)
{
for(auto& from : *static_cast<Self*>(this))
{
for(auto& to : other)
{
from.out.push_back(&to);
to.in.push_back(&from);
}
}
}
};
struct Neuron : SomeNeurons<Neuron>
{
vector<Neuron*> in, out;
unsigned int id;
Neuron()
{
static int id(1);
this->id = id++;
}
Neuron* begin() { return this; }
Neuron* end() { return this+1; }
friend ostream& operator<<(ostream& os, const Neuron& obj)
{
for(Neuron* n : obj.in)
{
os << n->id << "\t-->\t[" << obj.id << "]" << endl;
}
for(Neuron* n : obj.out)
{
os << "[" << obj.id << "]\t-->\t" << n->id << endl;
}
return os;
}
};
struct NeuronLayer : vector<Neuron>, SomeNeurons<NeuronLayer>
{
NeuronLayer(int count)
{
while(count --> 0)
{
emplace_back(Neuron{});
}
}
friend ostream& operator<<(ostream& os, const NeuronLayer& obj)
{
for(auto& n : obj) os << n;
return os;
}
};
void NeuronMain()
{
Neuron n1, n2;
n1.ConnectTo(n2);
cout << n1 << n2 << endl;
NeuronLayer layer1{2}, layer2{3};
n1.ConnectTo(layer1);
layer2.ConnectTo(n2);
layer1.ConnectTo(layer2);
cout << layer1 << layer2 << endl;
}
| true |
4156326590cbfe918fe81080388066ed461c7b59 | C++ | MoraxAlvizo/ProyectoADA | /GLEngine/src/GLShader.cpp | UTF-8 | 1,193 | 2.703125 | 3 | [] | no_license | #include "GLShader.h"
GLShader::GLShader(string shaderFile, unsigned int typeShader)
{
this->shaderFile = shaderFile;
this->typeShader = typeShader;
codigoGLSL = NULL;
if( !readShader() )
cerr << "Error al leer archivo: " << shaderFile << endl;
compileShader();
}
GLShader::~GLShader(void)
{
if(codigoGLSL)
delete codigoGLSL;
glDeleteShader(id);
}
bool GLShader::readShader()
{
ifstream fe(shaderFile);
string linea;
string codigo = string();
if(!fe)
return false;
while( getline(fe,linea,'\n') )
codigo += (linea + "\n");
codigo += "\0";
if( codigoGLSL )
delete codigoGLSL;
codigoGLSL = new GLchar[codigo.length()];
for(int index = 0; index < codigo.length(); index++)
codigoGLSL[index] = codigo.at(index);
codigoGLSL[codigo.length()] = '\0';
return true;
}
bool GLShader::compileShader()
{
const GLchar* codigo = codigoGLSL;
id = glCreateShader(typeShader);
glShaderSource(id, 1, &codigo, NULL);
glCompileShader(id);
int params = -1;
glGetShaderiv(id, GL_COMPILE_STATUS, ¶ms);
if(GL_TRUE != params)
{
cerr << "Error: GL shader index did not compile: "<< id << endl;
//_print_shader_info_log(vs);
return false;
}
return true;
} | true |
6ccc2fbdc89ad47013b3922350040029575b9f3d | C++ | Mayur1496/Solutions-to-UVa | /augustLunchTime17.cpp | UTF-8 | 581 | 2.65625 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int cases;
scanf("%d",&cases);
while(cases--){
int cost[26];
char temp;
vector<char> c;
vector<char>::iterator it;
for(int i=0;i<26;i++){
scanf("%d ",&cost[i]);
c.push_back(i+97);
}
while((temp=getchar())!='\n'){
if(c.empty())
break;
it=search_n(c.begin(), c.end(), 1, temp);
if(it!=c.end())
c.erase(it);
}
if(c.empty())
printf("0\n");
else{
int sum=0;
for(int j=0; j<c.size(); j++)
sum+=cost[c[j]-97];
printf("%d\n",sum);
}
}
} | true |
ebed1b6a690cd0a7783e3996b2773d4a0224ec65 | C++ | galaxysd/GalaxyCodeBases | /c_cpp/etc/KaKs_Calculator/src/ConcatenatePairs.cpp | UTF-8 | 2,145 | 3.171875 | 3 | [] | no_license | /************************************************************
* Copyright (C) 2005, BGI of Chinese Academy of Sciences
* All rights reserved.
* Filename: ConcatenatePairs.cpp
* Abstract: Concatenate all pairs of sequences with AXT format
to a pair of sequences (maybe very long).
* Version: 1.0
* Author: Zhang Zhang (zhanghzhang@genomics.org.cn)
* Date: Feb.2, 2005
* Modified Version:
* Modified Author:
* Modified Date:
*************************************************************/
#include<string>
#include<iostream>
#include<fstream>
using namespace std;
string result; //Result for outputing into a file
bool readFile(const char *filename) {
bool flag = true;
string seq1, seq2;
seq1 = seq2 ="";
try {
ifstream is(filename);
if (!is) {
cout<<"\nError in opening file..."<<endl;
throw 1;
}
cout<<"\nPlease wait while reading sequences and concatenating..."<<endl;
string temp="", name="", str="";
while (getline(is, temp, '\n')) {
name = temp;
getline(is, temp, '\n');
while (temp!="") {
str += temp;
getline(is, temp, '\n');
}
seq1 += str.substr(0, str.length()/2);
seq2 += str.substr(str.length()/2, str.length()/2);
name = str = "";
}
is.close();
is.clear();
result += "Concatenate-"; result += filename; result += '\n';
result += seq1; result += '\n';
result += seq2; result += '\n';
result += '\n';
}
catch (...) {
flag = false;
}
return flag;
}
bool writeFile(const char *filename, const char *content) {
bool flag=true;
try {
ofstream os(filename);
os<<content;
os.close();
}
catch (...) {
cout<<"Error in writing file..."<<endl;
flag = false;
}
return flag;
}
int main(int argc, char* argv[]) {
if (argc!=3) {
cout<<"Description: Concatenate all pairs of sequences with AXT format to a pair of sequences."<<endl;
cout<<"Usage: ConPairs [AXT Filename] [Output Filename]"<<endl;
return 0;
}
try {
if (!readFile(argv[1])) throw 1;
if (!writeFile(argv[2], result.c_str())) throw 1;
cout<<"Mission accomplished."<<endl;
}
catch (...) {
cout<<"Mission failed."<<endl;
}
return 1;
}
| true |
5bff30c65d856be58e52ad86cf537ffc8d192454 | C++ | AndreiutDev/Lab2OOP | /complex_main.cpp | UTF-8 | 482 | 3.140625 | 3 | [] | no_license | // lab2_oop.cpp : This file contains the 'main' function. Program execution begins and ends there.
///
#include <iostream>
#include "complex.h"
using namespace std;
NumarComplex add(NumarComplex c1, NumarComplex c2) {
NumarComplex c3(0, 0);
c3.setReal(c1.getReal() + c2.getReal());
return c3;
}
int main()
{
NumarComplex c1 = NumarComplex(1, 5);
NumarComplex c2(17, -5);
NumarComplex c3 = add(c1, c2);
std::cout << c3.getReal();
} | true |
d0f783d6feecbef531089ce4ec89428e70fb2a48 | C++ | kBeliczynski/umcs-asd1 | /zad6/main.cpp | UTF-8 | 12,233 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
struct licznik{ // kazda komorka posiada własny licznik ktory pokazuje ile przejsc i miejsc monitorowanych bylo po drodze
int licznik_przejsc=0;
int miejsca_monitorowane=0;
};
int nS,mS; // wspolrzedne siedziby opercyjnej
int nX,mX; // wspolrzedne miejsca spotkania
int nTMP,mTMP; // wspolrzedne aktualnej pozycji
queue<int> Q;
void znajdz_droge(char **tab, int n, int m, licznik **l){
tab[nS][mS] = 'o'; // oznaczamy pierwsza komorke jako odwiedzona
Q.push(nS); // wrzucamy jej wspolrzedne do kolejki
Q.push(mS);
while(!Q.empty()) // dziala dopoki kolejka nie jest pusta
{
nTMP = Q.front(); Q.pop(); // odczytujemy z kolejki współrzędne
mTMP = Q.front(); Q.pop();
if((mTMP-1) >= 0) // sprawdzamy czy nie wyszlismy poza tabele
if((tab[nTMP][mTMP-1] == '.') ||(tab[nTMP][mTMP-1] == 'X')) // jezeli miejsce bylo nieodwiedzone lub jest to miejsce docelowe zwiekszamy licznik
{
tab[nTMP][mTMP-1] = 'o'; // odwiedamy pole
Q.push(nTMP); Q.push(mTMP-1); // wrzucamy aktualne wspolrzedne go kolejki
l[nTMP][mTMP-1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1); // licznik przejsc w nowym liczniku jest rowny przejsciom starego + 1
l[nTMP][mTMP-1].miejsca_monitorowane = l[nTMP][mTMP].miejsca_monitorowane; // licznik miejsc monitorowanych sie nie zmienia bo nie bylo to miejsce monitorowane
}
else if((tab[nTMP][mTMP-1] == 'M')){ // jesli trafimy na miejsce monitorowane
tab[nTMP][mTMP-1] = 'O'; // odwiedzamy je O aby odroznic ze te miejsce bylo miejscem moitorowanym
Q.push(nTMP); Q.push(mTMP-1);
l[nTMP][mTMP-1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1); // licznik przejsc w nowym liczniku jest rowny przejsciom starego + 1
l[nTMP][mTMP-1].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1); // trafilismy na miejsce monitorowane wiec nowy licznik miejsc monitorowanych to stary +1
}
else if((tab[nTMP][mTMP-1] == 'o' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP][mTMP-1].licznik_przejsc)){ // jesli trafilismy na miejsce odwiedzone (niemonitorowane) to sprawdzamy czy zrobilismy mniej krokow by do niego dotrzec (+1 poniewaz miejsce o jest o 1 wieksze) jesli tak to te miejsce przyjmuje nowe dane z licznika
l[nTMP][mTMP-1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane < (l[nTMP][mTMP-1].miejsca_monitorowane))
l[nTMP][mTMP-1].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane);
}
else if((tab[nTMP][mTMP-1] == 'O' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP][mTMP-1].licznik_przejsc)){ // jesli trafilismy na miejsce odwiedzone (monitorowane) to sprawdzamy czy zrobilismy mniej krokow by do niego dotrzec jesli tak to te miejsce przyjmuje nowe dane z licznika
l[nTMP][mTMP-1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane+1 < (l[nTMP][mTMP-1].miejsca_monitorowane))
l[nTMP][mTMP-1].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
if((mTMP+1) < m) // sprawdzamy czy nie wyszlismy poza tabele
if((tab[nTMP][mTMP+1] == '.') || (tab[nTMP][mTMP+1] == 'X'))
{
tab[nTMP][mTMP+1] = 'o';
Q.push(nTMP); Q.push(mTMP+1);
l[nTMP][mTMP+1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
l[nTMP][mTMP+1].miejsca_monitorowane = l[nTMP][mTMP].miejsca_monitorowane;
}
else if((tab[nTMP][mTMP+1] == 'M')){
tab[nTMP][mTMP+1] = 'O';
Q.push(nTMP); Q.push(mTMP+1);
l[nTMP][mTMP+1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
l[nTMP][mTMP+1].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1);
}else if((tab[nTMP][mTMP+1] == 'o' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP][mTMP+1].licznik_przejsc)){
l[nTMP][mTMP+1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane < (l[nTMP][mTMP+1].miejsca_monitorowane))
l[nTMP][mTMP+1].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane);
}
else if((tab[nTMP][mTMP+1] == 'O' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP][mTMP+1].licznik_przejsc)){
l[nTMP][mTMP+1].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane+1 < (l[nTMP][mTMP+1].miejsca_monitorowane))
l[nTMP][mTMP+1].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
if((nTMP+1) < n) // sprawdzamy czy nie wyszlismy poza tabele
if((tab[nTMP+1][mTMP] == '.') || (tab[nTMP+1][mTMP] == 'X'))
{
tab[nTMP+1][mTMP] = 'o';
Q.push(nTMP+1); Q.push(mTMP);
l[nTMP+1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
l[nTMP+1][mTMP].miejsca_monitorowane = l[nTMP][mTMP].miejsca_monitorowane;
}
else if((tab[nTMP+1][mTMP] == 'M')){
tab[nTMP+1][mTMP] = 'O';
Q.push(nTMP+1); Q.push(mTMP);
l[nTMP+1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
l[nTMP+1][mTMP].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1);
}else if((tab[nTMP+1][mTMP] == 'o' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP+1][mTMP].licznik_przejsc)){
l[nTMP+1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane < (l[nTMP+1][mTMP].miejsca_monitorowane))
l[nTMP+1][mTMP].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane);
}
else if((tab[nTMP+1][mTMP] == 'O' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP+1][mTMP].licznik_przejsc)){
l[nTMP+1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane+1 < (l[nTMP+1][mTMP].miejsca_monitorowane))
l[nTMP+1][mTMP].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
if((nTMP-1) >= 0 ) // sprawdzamy czy nie wyszlismy poza tabele
if((tab[nTMP-1][mTMP] == '.') || (tab[nTMP-1][mTMP] == 'X'))
{
tab[nTMP-1][mTMP] = 'o';
Q.push(nTMP-1); Q.push(mTMP);
l[nTMP-1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
l[nTMP-1][mTMP].miejsca_monitorowane = l[nTMP][mTMP].miejsca_monitorowane;
}
else if((tab[nTMP-1][mTMP] == 'M')){
tab[nTMP-1][mTMP] = 'O';
Q.push(nTMP-1); Q.push(mTMP);
l[nTMP-1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
l[nTMP-1][mTMP].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1);
}else if((tab[nTMP-1][mTMP] == 'o' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP-1][mTMP].licznik_przejsc)){
l[nTMP-1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane < (l[nTMP-1][mTMP].miejsca_monitorowane))
l[nTMP-1][mTMP].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane);
}
else if((tab[nTMP-1][mTMP] == 'O' && (l[nTMP][mTMP].licznik_przejsc+1) <= l[nTMP-1][mTMP].licznik_przejsc)){
l[nTMP-1][mTMP].licznik_przejsc = (l[nTMP][mTMP].licznik_przejsc+1);
if(l[nTMP][mTMP].miejsca_monitorowane+1 < (l[nTMP-1][mTMP].miejsca_monitorowane))
l[nTMP-1][mTMP].miejsca_monitorowane = (l[nTMP][mTMP].miejsca_monitorowane+1);
}
}
}
void wyswietl_najlepsze_przejscie(licznik **l, int n, int m, char **tab){ // skrawdzamy kazda strone X o ile istnieje i z tych stron wybieramy przejscie ktore ma najmniej przejsc i najmniej miejsc monitorowanych
l[nX][mX].licznik_przejsc = 99999; // ustawiamy na duza wartosc poniewaz chcemy by zawsze zostala zmieniona
l[nX][mX].miejsca_monitorowane = 99999;
if((nX-1) >= 0 && tab[nX-1][mX] != '#') // jezeli nie wyszlismy poza tabele i te miejsce nie jest #
if(l[nX-1][mX].licznik_przejsc < l[nX][mX].licznik_przejsc){ // jezeli w nX-1 byla mniejsza wartosc niz w miejscu docelowym X to zmieniamy wartosc
l[nX][mX].miejsca_monitorowane = l[nX-1][mX].miejsca_monitorowane;
l[nX][mX].licznik_przejsc = l[nX-1][mX].licznik_przejsc;
}
else if(l[n-1][mX].licznik_przejsc == l[nX][mX].licznik_przejsc) // jezeli licznik przejsc jest taki sam to wybieramy przejscie ktore ma mniej miejsc monitorowanych
if(l[nX-1][mX].miejsca_monitorowane < l[nX][mX].miejsca_monitorowane)
l[nX][mX].miejsca_monitorowane = l[nX-1][mX].miejsca_monitorowane;
if((nX+1) < n && tab[nX+1][mX] != '#')
if(l[nX+1][mX].licznik_przejsc < l[nX][mX].licznik_przejsc){
l[nX][mX].licznik_przejsc = l[nX+1][mX].licznik_przejsc;
l[nX][mX].miejsca_monitorowane = l[nX+1][mX].miejsca_monitorowane;
}
else if(l[nX+1][mX].licznik_przejsc == l[nX][mX].licznik_przejsc)
if(l[nX+1][mX].miejsca_monitorowane < l[nX][mX].miejsca_monitorowane)
l[nX][mX].miejsca_monitorowane = l[nX+1][mX].miejsca_monitorowane;
if((mX-1) >= 0 && tab[nX][mX-1] != '#')
if(l[nX][mX-1].licznik_przejsc < l[nX][mX].licznik_przejsc){
l[nX][mX].licznik_przejsc = l[nX][mX-1].licznik_przejsc;
l[nX][mX].miejsca_monitorowane = l[nX][mX-1].miejsca_monitorowane;
}
else if(l[nX][mX-1].licznik_przejsc == l[nX][mX].licznik_przejsc)
if(l[nX][mX-1].miejsca_monitorowane < l[nX][mX].miejsca_monitorowane)
l[nX][mX].miejsca_monitorowane = l[nX][mX-1].miejsca_monitorowane;
if((mX+1) < m && tab[nX][mX+1] != '#')
if(l[nX][mX+1].licznik_przejsc < l[nX][mX].licznik_przejsc){
l[nX][mX].licznik_przejsc = l[nX][mX+1].licznik_przejsc;
l[nX][mX].miejsca_monitorowane = l[nX][mX+1].miejsca_monitorowane;
}
else if(l[nX][mX+1].licznik_przejsc == l[nX][mX].licznik_przejsc)
if(l[nX][mX+1].miejsca_monitorowane < l[nX][mX].miejsca_monitorowane)
l[nX][mX].miejsca_monitorowane = l[nX][mX+1].miejsca_monitorowane;
//dlatego dodajemy 1 poniewaz przejscie na pole X tez sie liczy a nie zliczylismy go wczesniej
cout << (l[nX][mX].licznik_przejsc+1) << " " << l[nX][mX].miejsca_monitorowane << endl;
}
int main()
{
int n=0,m=0;
cin >> n >> m; // wczytujemy wyiary naszej tabeli
licznik **l = new licznik *[m]; // tworzymy licznik w ktorym bedziemy zapisywac dane kazdej komorki w tabeli
char **tab = new char *[m]; // tworzymy tabele char do przechowywania wartosci
for(int i=0; i<n; i++){ // tworzenie licznika i tabeli
l[i] = new licznik[m];
tab[i] = new char[m];
for(int j=0; j<m; j++){
cin >> tab[i][j];
if(tab[i][j] == 'S'){ // gdy dodamy miejsce S zapisujemy jego wspolrzedne
nS = i;
mS = j;
}
if(tab[i][j] == 'X'){ // gdy dodamy miejsce X zapisujemy jego wspolrzedne
nX = i;
mX = j;
}
}
}
nTMP = nS; // przypisujemy wartosci poniewaz nie chcemy zmieniac wartosci Startu tylko operowac na zzmiennym TMP ktore beda zmieniane co kazde przejscie
mTMP = mS;
znajdz_droge(tab, n, m,l); // szukamy najmniejszej drogi do X
wyswietl_najlepsze_przejscie(l,n,m,tab); // z 4 stron X o ile istnieja wybiera najlepsze przejscie i je wyswietla dodajac 1 poniewaz wejscie na pole X tez sie zalicza
return 0;
}
| true |
59d7d26d47979ff4eec57eddc2c7680c0450ef70 | C++ | danilodesouzapereira/plataformasinap_exportaopendss | /Fontes/Mapa/TParede.cpp | ISO-8859-1 | 5,374 | 2.53125 | 3 | [] | no_license | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "TParede.h"
#include "..\Rede\VTBarra.h"
#include "..\..\DLL_Inc\Funcao.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
VTParede* __fastcall NewObjParede(void)
{
try{//cria objeto TParede
return(new TParede());
}catch(Exception &e)
{
return(NULL);
}
}
//---------------------------------------------------------------------------
__fastcall TParede::TParede(void)
{
//inicia atributos
Rede = NULL;
//cria lista
lisBARRA = new TList();
lisLIGACAO = new TList();
}
//---------------------------------------------------------------------------
__fastcall TParede::~TParede(void)
{
//destri lista sem destruir seus objetos
if (lisBARRA ) {delete lisBARRA ; lisBARRA = NULL;}
if (lisLIGACAO) {delete lisLIGACAO; lisLIGACAO = NULL;}
}
//---------------------------------------------------------------------------
bool __fastcall TParede::ExisteBarra(VTBarra *barra)
{
return(lisBARRA->IndexOf(barra) >= 0);
}
//---------------------------------------------------------------------------
bool __fastcall TParede::ExisteLigacao(VTLigacao *ligacao)
{
return(lisLIGACAO->IndexOf(ligacao) >= 0);
}
//---------------------------------------------------------------------------
bool __fastcall TParede::InsereBarra(VTBarra *barra)
{
//proteco
if (barra == NULL) return(false);
//verifica se a Barra j existe em lisBARRA
if (lisBARRA->IndexOf(barra) < 0) lisBARRA->Add(barra);
return(true);
}
//---------------------------------------------------------------------------
bool __fastcall TParede::InsereLigacao(VTLigacao *ligacao)
{
//proteo
if (ligacao == NULL) return(false);
//verifica se a Ligacao j existe em lisLIGACAO
if (lisLIGACAO->IndexOf(ligacao) < 0) lisLIGACAO->Add(ligacao);
return(true);
}
//---------------------------------------------------------------------------
TList* __fastcall TParede::LisBarra(void)
{
return(lisBARRA);
}
//---------------------------------------------------------------------------
int __fastcall TParede::LisBarra(TList *lisEXT)
{
//variveis locais
int count_ini = lisEXT->Count;
VTBarra *barra;
//determina objetos VTEqbar do tipo indicado
for (int nb = 0; nb < lisBARRA->Count; nb++)
{
barra = (VTBarra*)lisBARRA->Items[nb];
if (lisEXT->IndexOf(barra) < 0) lisEXT->Add(barra);
}
return (lisEXT->Count - count_ini);
}
//---------------------------------------------------------------------------
int __fastcall TParede::LisEqbar(TList *lisEXT, int tipo)
{
//variveis locais
int count_ini = lisEXT->Count;
VTBarra *barra;
//determina objetos VTEqbar do tipo indicado
for (int nb = 0; nb < lisBARRA->Count; nb++)
{
barra = (VTBarra*)lisBARRA->Items[nb];
barra->LisEqbar(lisEXT, tipo);
}
return (lisEXT->Count - count_ini);
}
//---------------------------------------------------------------------------
int __fastcall TParede::LisEqpto(TList *lisEXT, int tipo)
{
//variveis locais
int count_ini = lisEXT->Count;
//verifica tipo de eqpto solicitado
if (tipo == eqptoBARRA) LisBarra(lisEXT);
else if (tipo == eqptoEQBAR) LisEqbar(lisEXT);
else if (tipo == eqptoLIGACAO) LisLigacao(lisEXT);
else if (tipo == -1)
{//todos os equipamentos
LisBarra(lisEXT);
LisEqbar(lisEXT);
LisLigacao(lisEXT);
}
else
{//um tipo de equipamento especfico (Eqbar ou Ligacao)
LisEqbar(lisEXT, tipo);
LisLigacao(lisEXT, tipo);
}
return(lisEXT->Count - count_ini);
}
//---------------------------------------------------------------------------
TList* __fastcall TParede::LisLigacao(void)
{
return(lisLIGACAO);
}
//---------------------------------------------------------------------------
int __fastcall TParede::LisLigacao(TList *lisEXT, int tipo)
{
//variveis locais
int count_ini = lisEXT->Count;
VTEqpto *eqpto;
//verifica o tipo de objeto VTLigacao solicitado
if ((tipo < 0)||(tipo == eqptoLIGACAO))
{//copia todas Ligacoes
for (int n = 0; n < lisLIGACAO->Count; n++)
{
eqpto = (VTEqpto*)lisLIGACAO->Items[n];
//insere objeto VTEqpto em lisEQP
if (lisEXT->IndexOf(eqpto)) lisEXT->Add(eqpto);
}
}
else
{//copia somente os objetos VTLigacao do tipo solicitado
for (int n = 0; n < lisLIGACAO->Count; n++)
{
eqpto = (VTEqpto*)lisLIGACAO->Items[n];
if (eqpto->Tipo() == tipo)
{//insere objeto VTEqpto em lisEQP
if (lisEXT->IndexOf(eqpto)) lisEXT->Add(eqpto);
}
}
}
return(lisEXT->Count - count_ini);
}
//---------------------------------------------------------------------------
void __fastcall TParede::ReiniciaLisEqpto(void)
{
//limpa listas lisBARRA e lisLIGACAO
lisBARRA->Clear();
lisLIGACAO->Clear();
}
//---------------------------------------------------------------------------
//eof
| true |
62f0e9c293bdb60d9a5065854eb0cd25fd556785 | C++ | LimitW/ACM-repo | /AOAPC/AOAPC I book/AOAPC_11_2_4.cpp | UTF-8 | 1,419 | 2.53125 | 3 | [] | no_license | /************************************************
* Title:
* Author:LimitW
* Date:2014.9.12
* Source:AOAPC I
* Note:SPFA, Bellman-Ford的队列优化
*************************************************/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1000;
const int maxm = 4000;
int n,m;
int d[maxn];
int first[maxn];
int u[maxm],v[maxm],w[maxm],next[maxm];
queue<int> q;
bool inq[maxn];
void read_graph(){
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++) first[i] = -1;
for(int e = 0; e < m; e++)
{
scanf("%d%d%d",&u[e],&v[e],&w[e]);
next[e] = first[u[e]];
first[u[e]] = e;
}
}
void BF(){
for(int i = 0; i < n; i++) d[i] == (i == 0) ? 0 : INF;
memset(inq,0,sizeof(inq)); // 在队列中的标志
q.push(0);
while(!q.empty()){
int x = q.front(); q.pop();
inq[x] = false; //清除“在队列中”标志
for(int e = first[x]; e != -1; e = next[e])
if(d[v[e]] > d[x] + w[e]){
d[v[e]] = d[x] + w[e];
if(!inq[v[e]]) //如果已在队列中就不重复加了
{
inq[v[e]] = true;
q.push(v[e]);
}
}
}
}
int main(){
return 0;
} | true |
0493db7b866b9b99ccff5c84f1a66faebc563fba | C++ | sosch17/SysProg_2 | /Parser/src/ParseTree.cpp | UTF-8 | 21,088 | 3.359375 | 3 | [] | no_license | #include "../includes/ParseTree.h";
/*
* basis von treenode und leafnode, vor allem für linkedList von Children.
* Type: für TypeCheck (type oder operation für leafnode)
*/
BasicNode::BasicNode() {
this->type = noType;
this->leaf = false;
}
Types BasicNode::getTypes() {
return this->type;
}
void BasicNode::setTypes(Types t) {
this->type = t;
}
bool BasicNode::isLeaf()
{
return this->leaf;
}
void BasicNode::setLeaf(bool leaf)
{
this->leaf = leaf;
}
/*
* besteht aus parent und NodeTypes (welche regel benutzt wurde)
* children: alle direkten nachfolger des Knoten
*/
TreeNode::TreeNode(TreeNode* parent, NodeTypes type) {
this->parent = parent;
this->nodeType = type;
this->children = new LinkedList<BasicNode>;
this->setLeaf(false);
}
/*
* erster TreeNode (Wurzelknoten)
*/
TreeNode::TreeNode() {
this->nodeType = PROG;
this->children = new LinkedList<BasicNode>;
this->setLeaf(false);
}
/*
* ParseTree nimmt scanner, der gibt Ihm die Token durch getNextToken()
* holt Token -> erschafft wurzelknoten PROG -> initiale Methode zum Baumbau wird aufgerufen (erste Regel)
*/
ParseTree::ParseTree(Scanner* scanner) {
this->scanner = scanner;
this->currentToken = scanner->getNextToken();
this->root = new TreeNode();
cout << "Building Tree..." << endl;
this->prog(this->root);
cout << "Building Finished" << endl;
}
TreeNode* ParseTree::getRoot() {
return this->root;
}
/*
* parent TreeNode:
* terminal: stateType des Tokens
*/
LeafNode::LeafNode(TreeNode* parent, StateTypes::State terminal, Token* token) {
this->parent = parent;
this->terminal = terminal;
this->token = token;
this->setLeaf(true);
}
/*
* create LeafNode -> hängt leafNode an Chilrden LinkedList von parent (TreeNode) an -> next Token
*/
LeafNode* ParseTree::addLeaf(TreeNode* parent, StateTypes::State terminal, Token* token) {
// cout << "addLeaf: " << token->getName() << endl;
if(this->currentToken->getContent() == '\0') {
cout << 'ENDE' << endl;
this->currentToken = NULL;
}
LeafNode* leafNode = new LeafNode(parent, terminal, token);
if(parent->getChildren()->isEmpty()) {
parent->getChildren()->initNode(leafNode);
} else {
parent->getChildren()->addNode(leafNode);
}
this->currentToken = scanner->getNextToken();
return leafNode;
}
StateTypes::State LeafNode::getTerminal() {
return this->terminal;
}
NodeTypes TreeNode::getNodeType() {
return this->nodeType;
}
TreeNode* TreeNode::getParent() {
return this->parent;
}
TreeNode* LeafNode::getParent() {
return this->parent;
}
Token* LeafNode::getToken() {
return this->token;
}
/*
* Syntax Fehler: beendet das Programm
*/
void ParseTree::error() {
cout << "Unexpected Token: In Line - " << this->currentToken->getLine() << " Column - " << this->currentToken->getColumn() << endl;
exit (EXIT_FAILURE); //exitcode 0 oder 1
}
LinkedList<BasicNode>* TreeNode::getChildren() {
return this->children;
}
/*
* prüft ob aktuelles Token den übergebenen State hat -> sonst error
*/
void ParseTree::checkTokenType(StateTypes::State stateType)
{
if(this->currentToken->getName() != stateType)
{
this->error();
}
}
/*
* fügt TreeNode hinzu: s. AddLeaf aber mit Treenode
*/
TreeNode* ParseTree::addNode(TreeNode* parent, NodeTypes type) {
TreeNode* treeNode = new TreeNode(parent, type);
// cout << "addNode: " << type << ", " << endl;
if(parent->getChildren()->isEmpty()) {
parent->getChildren()->initNode(treeNode);
} else {
parent->getChildren()->addNode(treeNode);
}
return treeNode;
}
/*
* vgl. Tabelle
* prüft ob terminal (token) von dem Regel Type erreicht werden kann
*/
bool ParseTree::isReachableTerminal(Token* token, NodeTypes type) {
StateTypes::State tokenType = token->getName();
//DECL := int ARRAY identifier
if(type == DECL) {
return tokenType == StateTypes::intState3;
//DECLS := DECL ; DECLs | E
} else if(type == DECLS) {
return tokenType == StateTypes::intState3 //intState? write read states gibt es nicht... sind die im umgebauten automat??
|| tokenType == StateTypes::identifierState
|| tokenType == StateTypes::geschwKlammerAufState
|| tokenType == StateTypes::IFgrossState2
|| tokenType == StateTypes::IFkleinState2
|| tokenType == StateTypes::WHILEgrossState5
|| tokenType == StateTypes::WHILEkleinState5
|| tokenType == StateTypes::writeState5
|| tokenType == StateTypes::readState4;
//STATEMENTS := STATEMENT ; STATEMENTs | E
} else if(type == STATEMENTS) {
return tokenType == StateTypes::identifierState
|| tokenType == StateTypes::writeState5
|| tokenType == StateTypes::readState4
|| tokenType == StateTypes::IFgrossState2
|| tokenType == StateTypes::IFkleinState2
|| tokenType == StateTypes::WHILEgrossState5
|| tokenType == StateTypes::WHILEkleinState5
|| tokenType == StateTypes::geschwKlammerAufState
|| tokenType == StateTypes::geschwKlammerZuState;
/*STATEMENT := identifier INDEX := EXP
|write ( EXP )
|read ( identifier INDEX )
|{ STATEMENTs }
|if ( EXP ) STATEMENT else STATEMENT
|while ( EXP ) STATEMENT
*/
} else if(type == STATEMENT) {
return tokenType == StateTypes::identifierState
||tokenType ==StateTypes::writeState5
||tokenType == StateTypes::readState4
|| tokenType == StateTypes::IFgrossState2
||tokenType == StateTypes::IFkleinState2
|| tokenType == StateTypes::WHILEgrossState5
||tokenType == StateTypes::WHILEkleinState5
||tokenType == StateTypes::geschwKlammerAufState;
// ARRAY := [ integer ] | E
} else if(type == ARRAY) {
return tokenType == StateTypes::identifierState
|| tokenType == StateTypes::eckigeKlammerAufState;
//EXP := EXP2 OP_EXP
} else if(type == EXP) {
return tokenType == StateTypes::identifierState
|| tokenType == StateTypes::integerState
|| tokenType == StateTypes::klammerAufState
|| tokenType == StateTypes::minusState
|| tokenType == StateTypes::ausrufezeichenState;
/*EXP2 := ( EXP )
* |identifier INDEX
* |integer
* |- EXP2
* |! EXP2
*/
} else if(type == EXP2) {
return tokenType == StateTypes::identifierState
||tokenType == StateTypes::integerState
||tokenType == StateTypes::klammerAufState
|| tokenType == StateTypes::minusState
|| tokenType == StateTypes::ausrufezeichenState;
//OP_EXP := OP EXP | E
} else if(type == OPEXP) {
return tokenType == StateTypes::elseGrossState4
||tokenType == StateTypes::elseKleinState4
||tokenType == StateTypes::semikolonState
||tokenType == StateTypes::eckigeKlammerZuState
||tokenType == StateTypes::klammerZuState
||tokenType == StateTypes::geschwKlammerZuState
||tokenType == StateTypes::plusState
||tokenType == StateTypes::minusState
||tokenType == StateTypes::sternState
||tokenType == StateTypes::doppelpunktState
||tokenType == StateTypes::groesserState
||tokenType == StateTypes::kleinerState
||tokenType == StateTypes::gleichState
||tokenType == StateTypes::gleichDoppelpunktGleichState
||tokenType == StateTypes::undUndState;
//OP := + | - | * | : | < | > | = | =:= | &&
} else if(type == OP) {
return tokenType == StateTypes::plusState
||tokenType == StateTypes::minusState
||tokenType == StateTypes::sternState
||tokenType == StateTypes::doppelpunktState
||tokenType == StateTypes::groesserState
||tokenType == StateTypes::kleinerState
||tokenType == StateTypes::gleichState
||tokenType == StateTypes::gleichDoppelpunktGleichState
||tokenType == StateTypes::undUndState;
//INDEX := [ EXP ] | E
} else if(type == INDEX) {
return tokenType == StateTypes::eckigeKlammerAufState
||tokenType == StateTypes::eckigeKlammerZuState
||tokenType == StateTypes::klammerZuState
||tokenType == StateTypes::geschwKlammerZuState
||tokenType == StateTypes::doppepunktGleichState;
}
return false;
}
/*
* PROG := DECLS STATEMENTS
* wenn token nicht reachable füge EPSILON TreeNode hinzu
*/
void ParseTree::prog(TreeNode* parent){
if(this->isReachableTerminal(this->currentToken, DECLS)) {
this->decls(parent);
} else {
TreeNode* node = this->addNode(parent, DECLS);
this->addNode(node, EPSILON);
}
if(this->isReachableTerminal(this->currentToken, STATEMENTS)) {
this->statements(parent);
} else {
TreeNode* node = this->addNode(parent, STATEMENTS);
this->addNode(node, EPSILON);
}
// not needed
if(this->isReachableTerminal(this->currentToken, DECLS) && this->isReachableTerminal(this->currentToken, STATEMENTS))
{
this->error();
}
}
/* DECLS := DECL; DECLS | ep
* while: regel wiederholt sich für mehrere DECLS
*/
void ParseTree::decls(TreeNode* parent){
if(this->isReachableTerminal(this->currentToken, DECL)) {
TreeNode* node = this->addNode(parent, DECLS);
this->decl(node);
this->checkTokenType(StateTypes::semikolonState);
this->addLeaf(node, StateTypes::semikolonState, this->currentToken);
// GIBTS JA SCHON IN DECLS WEIL WIR IN DER METHODE SIND
this->decls(node);
// DECL oder DECLS
while(this->isReachableTerminal(this->currentToken, DECL)) {
this->decl(node);
this->addLeaf(node, StateTypes::semikolonState, this->currentToken);
}
} else {
TreeNode* node = this->addNode(parent, DECLS);
this->addNode(node, EPSILON);
}
//kein error() da decls epsilon sein kann
}
/* DECL := int ARRAY identifier
* checkt ob token intState ist -> addLead -> check ob reachable mit ARRAY -> addNode -> check ob token
* identifier ist -> addLeaf
*/
void ParseTree::decl(TreeNode* parent){
TreeNode* node = this->addNode(parent, DECL);
this->checkTokenType(StateTypes::intState3);
this->addLeaf(node, StateTypes::intState3, this->currentToken);
if(this->isReachableTerminal(this->currentToken, ARRAY)) {
this->array(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::identifierState);
this->addLeaf(node, StateTypes::identifierState, this->currentToken);
}
/*
* ARRAY := [integer] | ep
*/
void ParseTree::array(TreeNode* parent){
if(this->currentToken->getName() == StateTypes::eckigeKlammerAufState)
{
TreeNode* node = this->addNode(parent, ARRAY);
this->addLeaf(node, StateTypes::eckigeKlammerAufState, this->currentToken);
this->checkTokenType(StateTypes::integerState);
this->addLeaf(node, StateTypes::integerState, this->currentToken);
this->checkTokenType(StateTypes::eckigeKlammerZuState);
this->addLeaf(node, StateTypes::eckigeKlammerZuState, this->currentToken);
} else {
TreeNode* node = this->addNode(parent, ARRAY);
this->addNode(node, EPSILON);
}
//kein error() da array epsilon sein kann
}
/* STATEMENTS := STATEMENT; STATEMENTS | ep
*/
void ParseTree::statements(TreeNode* parent){
if(this->isReachableTerminal(this->currentToken, STATEMENT)) {
TreeNode* node = this->addNode(parent, STATEMENTS);
this->statement(node);
this->checkTokenType(StateTypes::semikolonState);
this->addLeaf(node, StateTypes::semikolonState, this->currentToken);
this->statements(node);
// STATEMENT oder STATEMENTS
while(this->isReachableTerminal(this->currentToken, STATEMENT)) {
this->statement(node);
this->checkTokenType(StateTypes::semikolonState);
this->addLeaf(node, StateTypes::semikolonState, this->currentToken);
}
} else {
TreeNode* node = this->addNode(parent, STATEMENTS);
this->addNode(node, EPSILON);
}
//kein error() da array epsilon sein kann
}
/*
* STATEMENT := identifier INDEX := EXP | write( EXP ) | read ( identifier INDEX) | {STATEMENTS} |
* if ( EXP ) STATEMENT else STATEMENT | while ( EXP ) STATEMENT
*/
void ParseTree::statement(TreeNode* parent){
if(this->currentToken->getName() == StateTypes::identifierState) {
TreeNode* node = this->addNode(parent, STATEMENT);
this->addLeaf(node, StateTypes::identifierState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, INDEX)) {
this->index(node);
}
else{
this->error();
}
//HIER
this->checkTokenType(StateTypes::doppepunktGleichState);
this->addLeaf(node, StateTypes::doppepunktGleichState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, EXP)) {
this->exp(node);
}
else{
this->error();
}
} else if(this->currentToken->getName() == StateTypes::writeState5) {
TreeNode* node = this->addNode(parent, STATEMENT2);
this->addLeaf(node, StateTypes::writeState5, this->currentToken);
this->checkTokenType(StateTypes::klammerAufState);
this->addLeaf(node, StateTypes::klammerAufState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, EXP)) {
this->exp(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::klammerZuState);
this->addLeaf(node, StateTypes::klammerZuState, this->currentToken);
} else if(this->currentToken->getName() == StateTypes::readState4) {
TreeNode* node = this->addNode(parent, STATEMENT3);
this->addLeaf(node, StateTypes::readState4, this->currentToken);
this->checkTokenType(StateTypes::klammerAufState);
this->addLeaf(node, StateTypes::klammerAufState, this->currentToken);
this->checkTokenType(StateTypes::identifierState);
this->addLeaf(node, StateTypes::identifierState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, INDEX)) {
this->index(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::klammerZuState);
this->addLeaf(node, StateTypes::klammerZuState, this->currentToken);
} else if(this->currentToken->getName() == StateTypes::geschwKlammerAufState) {
TreeNode* node = this->addNode(parent, STATEMENT4);
this->addLeaf(node, StateTypes::geschwKlammerAufState ,this->currentToken);
if(this->isReachableTerminal(this->currentToken, STATEMENTS)) {
this->statements(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::geschwKlammerZuState);
this->addLeaf(node, StateTypes::geschwKlammerZuState, this->currentToken);
} else if(this->currentToken->getName() == StateTypes::IFkleinState2) {
TreeNode* node = this->addNode(parent, STATEMENT5);
this->addLeaf(node, StateTypes::IFkleinState2 ,this->currentToken);
this->checkTokenType(StateTypes::klammerAufState);
this->addLeaf(node, StateTypes::klammerAufState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, EXP)) {
this->exp(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::klammerZuState);
this->addLeaf(node, StateTypes::klammerZuState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, STATEMENT)) {
this->statement(node);
}
else{
this->error();
}
// current token ist bei elseKleinState1
this->checkTokenType(StateTypes::elseKleinState4);
this->addLeaf(node, StateTypes::elseKleinState4 ,this->currentToken);
if(this->isReachableTerminal(this->currentToken, STATEMENT)) {
this->statement(node);
}
else{
this->error();
}
} else if(this->currentToken->getName() == StateTypes::WHILEkleinState5) {
TreeNode* node = this->addNode(parent, STATEMENT6);
this->addLeaf(node, StateTypes::WHILEkleinState5 ,this->currentToken);
this->checkTokenType(StateTypes::klammerAufState);
this->addLeaf(node, StateTypes::klammerAufState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, EXP)) {
this->exp(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::klammerZuState);
this->addLeaf(node, StateTypes::klammerZuState, this->currentToken);
if(this->isReachableTerminal(this->currentToken, STATEMENT)) {
this->statement(node);
}
else{
this->error();
}
}
else{
this->error();
}
}
/*
* EXP := EXP2 OP_EXP
*/
void ParseTree::exp(TreeNode* parent){
TreeNode* node = this->addNode(parent, EXP);
// theoretisch muss in EXP2 was drin sein
// if(this->isReachableTerminal(this->currentToken, EXP2) || this->isReachableTerminal(this->currentToken, OPEXP)) {
// this->exp2(node);
// this->op_exp(node);
// }
// else{
// this->error();
// }
if(this->isReachableTerminal(this->currentToken, EXP2)) {
this->exp2(node);
} else {
this->error();
}
if(this->isReachableTerminal(this->currentToken, OPEXP)) {
this->op_exp(node);
} else {
TreeNode* node = this->addNode(parent, OPEXP);
this->addNode(node, EPSILON);
}
}
/*
* EXP2 := ( EXP ) | identifier INDEX | integer | - EXP2 | ! EXP2
*/
void ParseTree::exp2(TreeNode* parent){
if(this->currentToken->getName() == StateTypes::klammerAufState){
TreeNode* node = this->addNode(parent, EXP2);
this->addLeaf(node, StateTypes::klammerAufState, this->currentToken);
if(isReachableTerminal(this->currentToken, EXP)){
this->exp(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::klammerZuState);
this->addLeaf(node, StateTypes::klammerZuState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::identifierState){
TreeNode* node = this->addNode(parent, EXP2_2);
this->addLeaf(node, StateTypes::identifierState, this->currentToken);
// macht ja dann gar kein epsilon weil es nicht reachable ist-> anfügen??
if(isReachableTerminal(this->currentToken, INDEX)){
this->index(node);
}
// kein error da index epsilaon sein kann
// else{
// this->error();
// }
}
else if(this->currentToken->getName() == StateTypes::integerState){
TreeNode* node = this->addNode(parent, EXP2_3);
this->addLeaf(node, StateTypes::integerState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::minusState){
TreeNode* node = this->addNode(parent, EXP2_4);
this->addLeaf(node, StateTypes::minusState, this->currentToken);
if(isReachableTerminal(this->currentToken, EXP2)){
this->exp2(node);
}
else{
this->error();
}
}
else if(this->currentToken->getName() == StateTypes::ausrufezeichenState){
TreeNode* node = this->addNode(parent, EXP2_5);
this->addLeaf(node, StateTypes::ausrufezeichenState, this->currentToken);
if(isReachableTerminal(this->currentToken, EXP2)){
this->exp2(node);
}
else{
this->error();
}
}
else{
this->error();
}
}
/*
* INDEX := [ EXP ] | ep
*/
void ParseTree::index(TreeNode* parent){
if(this->currentToken->getName() == StateTypes::eckigeKlammerAufState){
TreeNode* node = this->addNode(parent, INDEX);
this->addLeaf(node, StateTypes::eckigeKlammerAufState, this->currentToken);
if(isReachableTerminal(this->currentToken, EXP)){
this->exp(node);
}
else{
this->error();
}
this->checkTokenType(StateTypes::eckigeKlammerZuState);
this->addLeaf(node, StateTypes::eckigeKlammerZuState, this->currentToken);
} else {
TreeNode* node = this->addNode(parent, INDEX);
this->addNode(node, EPSILON);
}
//kein error() da index epsilon sein kann
}
/*
* OP_EXP := OP EXP | ep
*/
void ParseTree::op_exp(TreeNode* parent){
//if(isReachableTerminal(t, OP) || isReachableTerminal(t, EXP)){
if(isReachableTerminal(this->currentToken, OP) ){
TreeNode* node = this->addNode(parent, OPEXP);
this->op(node);
this->exp(node);
} else {
TreeNode* node = this->addNode(parent, OPEXP);
this->addNode(node, EPSILON);
}
//kein error() da index epsilon sein kann
}
/*
* OP := + | - | * | : | < | > | = | =:= | &&
*/
void ParseTree::op(TreeNode* parent){
if(this->currentToken->getName() == StateTypes::plusState){
TreeNode* node = this->addNode(parent, OP);
this->addLeaf(node, StateTypes::plusState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::minusState)
{
TreeNode* node = this->addNode(parent, OP2);
this->addLeaf(node, StateTypes::minusState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::sternState)
{
TreeNode* node = this->addNode(parent, OP3);
this->addLeaf(node, StateTypes::sternState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::doppelpunktState)
{
TreeNode* node = this->addNode(parent, OP4);
this->addLeaf(node, StateTypes::doppelpunktState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::kleinerState)
{
TreeNode* node = this->addNode(parent, OP5);
this->addLeaf(node, StateTypes::kleinerState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::groesserState)
{
TreeNode* node = this->addNode(parent, OP6);
this->addLeaf(node, StateTypes::groesserState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::gleichState)
{
TreeNode* node = this->addNode(parent, OP7);
this->addLeaf(node, StateTypes::gleichState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::gleichDoppelpunktGleichState)
{
TreeNode* node = this->addNode(parent, OP8);
this->addLeaf(node, StateTypes::gleichDoppelpunktGleichState, this->currentToken);
}
else if(this->currentToken->getName() == StateTypes::undUndState)
{
TreeNode* node = this->addNode(parent, OP9);
this->addLeaf(node, StateTypes::undUndState, this->currentToken);
}
else{
this->error();
}
}
| true |
9e69fe70ca166f659898d17a353e7db61abc7f7d | C++ | Tako-San/ILab | /MAP/node.cpp | UTF-8 | 5,842 | 3.609375 | 4 | [] | no_license | #include "node.h"
Node::Node() : data(),
parent(nullptr),
left(nullptr),
right(nullptr)
{
//std::cout<<"Node constructor without arguments. "<<this<<"\n\n";
}
Node::Node(Data_t &n_data) : data(n_data),
parent(nullptr),
left(nullptr),
right(nullptr)
{
//std::cout<<"Node constructor with n_data. "<<this<<"\n\n";
}
Node::Node(key_t key, val_t val) : data(key, val),
parent(nullptr),
left(nullptr),
right(nullptr)
{
//std::cout<<"Node constructor with key, val. "<<this<<"\n\n";
}
std::ostream& operator<< (std::ostream &out, const Node &node)
{
//out<<"Data: ("<<node.data<<"), this: "<<&node<<", parent: "<<node.parent<<", lt: "<<node.left<<", rt: "<<node.right<<endl;
out << node.data;
return out;
}
void Node::set(key_t key, val_t val, Node * n_parent)
{
data = Map_t(key, val);
parent = n_parent;
}
void Node::set(Data_t &n_data, Node * n_parent)
{
data = n_data;
parent = n_parent;
}
void Node::print()
{
if(left != nullptr)
left->print();
if(parent == nullptr)
cout << *this << " - ROOT" << endl;
else if(left == nullptr && right == nullptr)
cout << *this << " - leaf" << endl;
else
cout << *this << endl;
if(right != nullptr)
right->print();
}
void Node::print_leafs()
{
if(this == nullptr)
return;
if(left == nullptr && right == nullptr)
std::cout << data <<"\n";
else
{
left->print_leafs();
right->print_leafs();
}
}
void Node::print_lvl(int lvl)
{
if(this == nullptr)
return;
else if(lvl == 0)
std::cout << *this;
else if(lvl > 0)
{
left->print_lvl(lvl - 1);
right->print_lvl(lvl - 1);
}
else
return;
}
void Node::clear()
{
if(this == nullptr)
return;
if(left != nullptr)
left->clear();
if(right != nullptr)
right->clear();
delete this;
}
Node * Node::add(Data_t &n_data)
{
#define DIRTY_JOB(side) \
if(side != nullptr) \
return side->add(n_data); \
else \
{ \
side = new Node; \
side->set(n_data, this); \
return side; \
} \
std::cout<<"\nADD FUNC\n";
if(n_data < data)
{
DIRTY_JOB(left)
}
else if(n_data > data)
{
DIRTY_JOB(right)
}
return nullptr;
#undef DIRTY_JOB
}
/*Node * Node::add(key_t key, val_t val)
{
Map_t tmp(key, val);
return add(tmp);
}*/
Node * Node::add(key_t key, val_t val)
{
#define DIRTY_JOB(side) \
if(side != nullptr) \
return side->add(key, val); \
else \
{ \
std::cout << "\nDYNAMYC MEMORY: NEW\n"; \
side = new Node; \
side->set(key, val, this); \
return side; \
} \
//std::cout<<"\nADD FUNC\n";
if(key < data)
{
DIRTY_JOB(left)
}
else if(key > data)
{
DIRTY_JOB(right)
}
return nullptr;
#undef DIRTY_JOB
}
Node * Node::find(Data_t &n_data)
{
if((n_data > data) && (right != nullptr))
return right->find(n_data);
else if((n_data < data) && (left != nullptr))
return left->find(n_data);
else if(n_data == data)
return this;
return nullptr;
}
Node * Node::find(key_t key)
{
if((key > data) && (right != nullptr))
return right->find(key);
else if((key < data) && (left != nullptr))
return left->find(key);
else if(key == data)
return this;
return nullptr;
}
int Node::depth()
{
if(this == nullptr)
return 0;
int depth = 1;
int depth_l = left->depth();
int depth_r = right->depth();
int subtr_max = (depth_l > depth_r)? depth_l : depth_r;
depth += subtr_max;
return depth;
}
bool Node::is_balanced()
{
int res = abs(left->depth() - right->depth()) <= 1 ? 1 : 0;
return res;
}
void Node::del(key_t key)
{
if (this == nullptr)
return;
if (key < data)
left->del(key);
else if (key > data)
right->del(key);
else if (left != nullptr && right != nullptr)
{
Node *tmp;
for(tmp = right; tmp->left != nullptr; tmp = tmp->left);
data = tmp->data;
right->del(data.key);
}
else if (left != nullptr)
{
Node * tmp = left;
if (left->left != nullptr)
left->left->parent = this;
if (left->right != nullptr)
left->right->parent = this;
data = left->data;
right = left->right;
left = left->left;
delete tmp;
}
else if (right != nullptr)
{
Node * tmp = right;
if (right->right != nullptr)
right->right->parent = this;
if (right->left != nullptr)
right->left->parent = this;
data = right->data;
left = right->left;
right = right->right;
delete tmp;
}
else
{
if(parent->left == this)
parent->left = nullptr;
else
parent->right = nullptr;
delete this;
}
}
void Node::del(Data_t &to_del)
{
del(to_del.key);
} | true |
1cbff9bf21d558c4ae301c7eacba7a64f42a5ea8 | C++ | script0Brand/cis202-examples | /book-source/cccfiles/ccc_wxw.cpp | UTF-8 | 13,550 | 2.53125 | 3 | [] | no_license | /*
CCC Graphics Library
COPYRIGHT (C) 1994 - 2011 Cay S. Horstmann. All Rights Reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <wx/wx.h>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <csetjmp>
#include <cstdio>
#include <iostream>
#include "ccc_wxw.h"
/*-------------------------------------------------------------------------*/
const double DEFAULT_XMIN = -10;
const double DEFAULT_YMIN = 10;
const double DEFAULT_XMAX = 10;
const double DEFAULT_YMAX = -10;
const int ID_TEXT = 1000;
/*-------------------------------------------------------------------------*/
/**
A window onto which the graphics output is painted.
*/
class GraphicCanvas : public wxWindow
{
public:
/**
Initializes the base class.
@param parent the parent window
*/
GraphicCanvas(wxWindow* parent);
void OnPaint(wxPaintEvent& event);
void OnSize(wxSizeEvent& event);
void OnMouseEvent(wxMouseEvent& event);
/**
Clears the window.
*/
void clear();
/**
Sets the coordinate system.
@param x1 the minimum x-value
@param y1 the minimum y-value
@param x2 the maximum x-value
@param y2 the maximum y-value
*/
void coord(double xmin, double ymin, double xmax, double ymax);
/**
Adds a point to the set of shapes that need to be displayed.
@param s the point to add
*/
void add(Point s);
/**
Adds a circle to the set of shapes that need to be displayed.
@param s the circle to add
*/
void add(Circle s);
/**
Adds a line to the set of shapes that need to be displayed.
@param s the line to add
*/
void add(Line s);
/**
Adds a message to the set of shapes that need to be displayed.
@param s the message to add
*/
void add(Message s);
private:
/**
Scales an x-coordinate from user to display coordinates.
@param x a coordinate position in user coordinates
@return the scaled coordinate
*/
int user_to_disp_x(double x) const;
/**
Scales a y-coordinate from user to display coordinates.
@param y a coordinate position in user coordinates
@return the scaled coordinate
*/
int user_to_disp_y(double y) const;
/**
Scales an x-coordinate from display to user coordinates.
@param x a coordinate position in display coordinates
@return the scaled coordinate
*/
double disp_to_user_x(int x) const;
/**
Scales an y-coordinate from display to user coordinates.
@param y a coordinate position in display coordinates
@return the scaled coordinate
*/
double disp_to_user_y(int y) const;
/**
Draws a point
@param dc the device context
@param s the point to draw
*/
void draw(wxDC& dc, Point s);
/**
Draws a circle
@param dc the device context
@param s the circle to draw
*/
void draw(wxDC& dc, Circle s);
/**
Draws a line
@param dc the device context
@param s the line to draw
*/
void draw(wxDC& dc, Line s);
/**
Draws a message
@param dc the device context
@param s the message to draw
*/
void draw(wxDC& dc, Message s);
double _user_xmin; // the user's window's logical window coords
double _user_xmax;
double _user_ymin;
double _user_ymax;
int _disp_xmax; // the physical window dimension (in pixels)
int _disp_ymax;
int _disp_xoff;
int _disp_yoff;
vector<Point> points;
vector<Line> lines;
vector<Circle> circles;
vector<Message> messages;
DECLARE_EVENT_TABLE()
};
/**
A frame with a window that shows the graphical output.
*/
class GraphicFrame : public wxFrame
{
public:
/**
Constructs the window.
*/
GraphicFrame(const wxString& appName);
/**
Runs the ccc_win_main function.
*/
void run();
void set_text_focus(bool b);
void OnEnter(wxCommandEvent& event);
private:
wxTextCtrl* text;
GraphicCanvas* window;
DECLARE_EVENT_TABLE()
};
/**
An application that generates a simple painting.
*/
class GraphicApp : public wxApp
{
public:
/**
Constructs the frame.
*/
GraphicApp();
virtual bool OnInit();
private:
GraphicFrame* frame;
};
DECLARE_APP(GraphicApp)
GraphicWindow cwin;
IMPLEMENT_APP(GraphicApp)
BEGIN_EVENT_TABLE(GraphicCanvas, wxWindow)
EVT_PAINT(GraphicCanvas::OnPaint)
EVT_SIZE(GraphicCanvas::OnSize)
EVT_MOUSE_EVENTS(GraphicCanvas::OnMouseEvent)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(GraphicFrame, wxFrame)
EVT_TEXT_ENTER(ID_TEXT, GraphicFrame::OnEnter)
END_EVENT_TABLE()
/*-------------------------------------------------------------------------*/
GraphicCanvas::GraphicCanvas(wxWindow* parent)
: wxWindow(parent, -1)
{
_user_xmin = DEFAULT_XMIN;
_user_xmax = DEFAULT_XMAX;
_user_ymin = DEFAULT_YMIN;
_user_ymax = DEFAULT_YMAX;
}
void GraphicCanvas::clear()
{
points.clear();
lines.clear();
circles.clear();
messages.clear();
}
void GraphicCanvas::add(Point s)
{
points.push_back(s);
}
void GraphicCanvas::add(Circle s)
{
circles.push_back(s);
}
void GraphicCanvas::add(Line s)
{
lines.push_back(s);
}
void GraphicCanvas::add(Message s)
{
messages.push_back(s);
}
void GraphicCanvas::OnSize(wxSizeEvent& event)
{
wxSize size = GetSize();
int width = size.GetWidth();
int height= size.GetHeight();
int sz = width < height ? width : height;
_disp_xmax = sz;
_disp_ymax = sz;
_disp_xoff = (width - sz) / 2;
_disp_yoff = (height - sz) / 2;
}
void GraphicCanvas::OnPaint(wxPaintEvent& event)
{
wxPaintDC dc(this);
dc.SetBrush(*wxTRANSPARENT_BRUSH);
for (int i = 0; i < points.size(); i++)
draw(dc, points[i]);
for (int i = 0; i < lines.size(); i++)
draw(dc, lines[i]);
for (int i = 0; i < circles.size(); i++)
draw(dc, circles[i]);
for (int i = 0; i < messages.size(); i++)
draw(dc, messages[i]);
}
void GraphicCanvas::OnMouseEvent(wxMouseEvent& event)
{
if (event.ButtonDown())
cwin.mouse_input(Point(disp_to_user_x(event.GetX()),
disp_to_user_y(event.GetY())));
}
int GraphicCanvas::user_to_disp_x(double x) const
{
return (int) (_disp_xoff + (x - _user_xmin) * _disp_xmax / (_user_xmax - _user_xmin));
}
int GraphicCanvas::user_to_disp_y(double y) const
{
return (int) (_disp_yoff + (y - _user_ymin) * _disp_ymax / (_user_ymax - _user_ymin));
}
double GraphicCanvas::disp_to_user_x(int x) const
{
return (double)(x - _disp_xoff) * (_user_xmax - _user_xmin) / _disp_xmax + _user_xmin;
}
double GraphicCanvas::disp_to_user_y(int y) const
{
return (double)(y - _disp_yoff) * (_user_ymax - _user_ymin) / _disp_ymax + _user_ymin;
}
void GraphicCanvas::draw(wxDC& dc, Point s)
{
const int POINT_RADIUS = 3;
int disp_x = user_to_disp_x(s.get_x());
int disp_y = user_to_disp_y(s.get_y());
dc.DrawEllipse(disp_x - POINT_RADIUS, disp_y - POINT_RADIUS,
2 * POINT_RADIUS, 2 * POINT_RADIUS);
}
void GraphicCanvas::draw(wxDC& dc, Circle s)
{
int disp_x1 = user_to_disp_x(s.get_center().get_x() - s.get_radius());
int disp_y1 = user_to_disp_y(s.get_center().get_y() - s.get_radius());
int disp_x2 = user_to_disp_x(s.get_center().get_x() + s.get_radius());
int disp_y2 = user_to_disp_y(s.get_center().get_y() + s.get_radius());
dc.DrawEllipse(disp_x1, disp_y1, disp_x2 - disp_x1, disp_y2 - disp_y1);
}
void GraphicCanvas::draw(wxDC& dc, Line s)
{
int disp_x1 = user_to_disp_x(s.get_start().get_x());
int disp_y1 = user_to_disp_y(s.get_start().get_y());
int disp_x2 = user_to_disp_x(s.get_end().get_x());
int disp_y2 = user_to_disp_y(s.get_end().get_y());
dc.DrawLine(disp_x1, disp_y1, disp_x2, disp_y2);
}
void GraphicCanvas::draw(wxDC& dc, Message s)
{
int disp_x = user_to_disp_x(s.get_start().get_x());
int disp_y = user_to_disp_y(s.get_start().get_y());
string text = s.get_text();
wxString msg(text.c_str(), wxConvLocal);
dc.DrawText(msg, disp_x, disp_y);
}
void GraphicCanvas::coord(double xmin, double ymin,
double xmax, double ymax)
{
_user_xmin = xmin;
_user_xmax = xmax;
_user_ymin = ymin;
_user_ymax = ymax;
}
/*-------------------------------------------------------------------------*/
GraphicWindow::GraphicWindow()
{
canvas = NULL;
frame = NULL;
waiting_for_mouse_input = false;
waiting_for_string_input = false;
}
void GraphicWindow::open(GraphicFrame* f, GraphicCanvas* c)
{
frame = f;
canvas = c;
canvas->clear();
string_input_count = 0;
mouse_input_count = 0;
}
void GraphicWindow::coord(double xmin, double ymin,
double xmax, double ymax)
{
canvas->coord(xmin, ymin, xmax, ymax);
}
GraphicWindow& GraphicWindow::operator<<(Point p)
{
canvas->add(p);
return *this;
}
GraphicWindow& GraphicWindow::operator<<(Circle c)
{
canvas->add(c);
return *this;
}
GraphicWindow& GraphicWindow::operator<<(Line s)
{
canvas->add(s);
return *this;
}
GraphicWindow& GraphicWindow::operator<<(Message t)
{
canvas->add(t);
return *this;
}
int GraphicWindow::get_int(const string& out_string)
{
return atoi(get_string(out_string).c_str());
}
double GraphicWindow::get_double(const string& out_string)
{
return atof(get_string(out_string).c_str());
}
jmp_buf buf;
string GraphicWindow::get_string(string outstr)
{
string_input_count++;
if (string_input_count <= string_inputs.size())
return string_inputs[string_input_count - 1];
else
{
waiting_for_string_input = true;
frame->SetStatusText(wxString(outstr.c_str(), wxConvLocal));
frame->set_text_focus(true);
longjmp(buf, 1);
return "";
}
}
Point GraphicWindow::get_mouse(string outstr)
{
mouse_input_count++;
if (mouse_input_count <= mouse_inputs.size())
return mouse_inputs[mouse_input_count - 1];
else
{
waiting_for_mouse_input = true;
frame->SetStatusText(wxString(outstr.c_str(), wxConvLocal));
longjmp(buf, 1);
return Point();
}
}
void GraphicWindow::mouse_input(Point p)
{
if (waiting_for_mouse_input)
{
mouse_inputs.push_back(p);
frame->SetStatusText(wxT(""));
waiting_for_mouse_input = false;
frame->run();
}
}
void GraphicWindow::string_input(string s)
{
if (waiting_for_string_input)
{
string_inputs.push_back(s);
frame->SetStatusText(wxT(""));
frame->set_text_focus(false);
waiting_for_string_input = false;
frame->run();
}
}
/*-------------------------------------------------------------------------*/
extern int ccc_win_main();
GraphicFrame::GraphicFrame(const wxString& appName)
: wxFrame(NULL, -1, appName)
{
window = new GraphicCanvas(this);
CreateStatusBar();
text = new wxTextCtrl(this, ID_TEXT, wxT(""),
wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER);
wxBoxSizer* frame_sizer = new wxBoxSizer(wxVERTICAL);
frame_sizer->Add(window, 1, wxGROW);
frame_sizer->Add(text, 0, wxGROW);
SetAutoLayout(true);
SetSizer(frame_sizer);
Layout();
run();
}
void GraphicFrame::run()
{
if (setjmp(buf) == 0)
{
cwin.open(this, window);
ccc_win_main();
}
window->Refresh();
}
void GraphicFrame::set_text_focus(bool b)
{
if (b) text->SetFocus(); else window->SetFocus();
}
void GraphicFrame::OnEnter(wxCommandEvent& event)
{
string input(text->GetValue().mb_str());
text->SetValue(wxT(""));
cwin.string_input(input);
}
/*-------------------------------------------------------------------------*/
#ifdef __WXMAC__
struct ProcessSerialNumber
{
int highLongOfPSN;
int lowLongOfPSN;
};
extern "C"
{
void CPSEnableForegroundOperation(ProcessSerialNumber* psn);
void GetCurrentProcess(ProcessSerialNumber* psn);
void SetFrontProcess(ProcessSerialNumber* psn);
}
#endif
GraphicApp::GraphicApp()
{
/*
http://www.miscdebris.net/blog/2010/03/30/solution-for-my-mac-os-x-gui-program-doesnt-get-focus-if-its-outside-an-application-bundle/
this hack enables to have a GUI on Mac OSX even if the
* program was called from the command line (and isn't a bundle) */
#ifdef __WXMAC__
ProcessSerialNumber psn;
GetCurrentProcess( &psn );
CPSEnableForegroundOperation( &psn );
SetFrontProcess( &psn );
#endif
}
bool GraphicApp::OnInit()
{
frame = new GraphicFrame(GetAppName());
frame->Show(true);
return true;
}
| true |
98240f1479852f97c97f47865cc3a1894a5d3030 | C++ | boranyldrm/Bilkent-Courses | /CS315/CS315/adsız klasör/Yacc/manual_calculator/Numeric.cpp | UTF-8 | 1,893 | 3.5625 | 4 | [] | no_license | #include "Numeric.h"
using namespace std;
Numeric operator+(Numeric lhs, Numeric rhs)
{
if (lhs.isInteger()) {
if (rhs.isInteger())
return Numeric(lhs.getIntegerValue()+rhs.getIntegerValue());
else
return Numeric(lhs.getIntegerValue()+rhs.getFloatValue());
} else {
if (rhs.isInteger())
return Numeric(lhs.getFloatValue()+rhs.getIntegerValue());
else
return Numeric(lhs.getFloatValue()+rhs.getFloatValue());
}
}
Numeric operator-(Numeric lhs, Numeric rhs)
{
if (lhs.isInteger()) {
if (rhs.isInteger())
return Numeric(lhs.getIntegerValue()-rhs.getIntegerValue());
else
return Numeric(lhs.getIntegerValue()-rhs.getFloatValue());
} else {
if (rhs.isInteger())
return Numeric(lhs.getFloatValue()-rhs.getIntegerValue());
else
return Numeric(lhs.getFloatValue()-rhs.getFloatValue());
}
}
Numeric operator*(Numeric lhs, Numeric rhs)
{
if (lhs.isInteger()) {
if (rhs.isInteger())
return Numeric(lhs.getIntegerValue()*rhs.getIntegerValue());
else
return Numeric(lhs.getIntegerValue()*rhs.getFloatValue());
} else {
if (rhs.isInteger())
return Numeric(lhs.getFloatValue()*rhs.getIntegerValue());
else
return Numeric(lhs.getFloatValue()*rhs.getFloatValue());
}
}
Numeric operator/(Numeric lhs, Numeric rhs)
{
if (lhs.isInteger()) {
if (rhs.isInteger())
return Numeric(lhs.getIntegerValue()/rhs.getIntegerValue());
else
return Numeric(lhs.getIntegerValue()/rhs.getFloatValue());
} else {
if (rhs.isInteger())
return Numeric(lhs.getFloatValue()/rhs.getIntegerValue());
else
return Numeric(lhs.getFloatValue()/rhs.getFloatValue());
}
}
ostream & operator<<(ostream & ostr, Numeric num)
{
if (num.isInteger())
ostr << num.getIntegerValue();
else
ostr << num.getFloatValue();
return ostr;
}
| true |
a71dbfec8a297eefae93152ca5960ff0ee896be0 | C++ | MenglaiWang/Leetcode | /61. Rotate List.cpp | UTF-8 | 714 | 3.3125 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
int size = 0;
ListNode* p1 = head,*p2 =head;
while(p2){
p2 = p2->next;
size++;
}
p2 =head;
if(k%size==0) return head;
k = k%size;
for(int i = 0; i <k;i++){
p1 = p1->next;
}
while(p1->next){
p1= p1->next;
p2 =p2->next;
}
ListNode* new_head = p2->next;
p1->next = head;
p2->next = NULL;
return new_head;
}
}; | true |
3472ea1e0de8cade8163fa3cd265473ec0740005 | C++ | dw5450/win | /WinAPI Project/Player.cpp | UHC | 3,805 | 2.921875 | 3 | [] | no_license | #include "stdafx.h"
// 100 κ ϴ° ٲ۴. ҳ ũ. -> ʴ ϳ .
// ǵ ٲܰŸ ؾ߰. ٵ //Ѵ ֳĸ ϰͱ ̴!
Player::Player(const long x, const long y, const SIZE size){ //int -> long ȯ Ͼ ʿ long
p.x = x; p.y = y;
ObjectSize = size;
ObjectRect.left = x - size.cx / 2;
ObjectRect.top = y - size.cy / 2;
ObjectRect.right = x + size.cx / 2;
ObjectRect.bottom = y + size.cy / 2;
};
Player::~Player(){};
void Player::crash(Monster * MonsterPt){ //浹 üũ ( ) // ڵ
RECT rcTemp; //ε //߰
if (IntersectRect(&rcTemp, &ObjectRect, &(MonsterPt->GetObjectRect())))
{
Ellipse(hdc, rcTemp.left, rcTemp.top, rcTemp.right, rcTemp.bottom);
}
}
void Player::crash(Item * Item){ //浹 üũ ( ) // ڵ
}
void Player::crash(HWND hWnd)
{
RECT rectView;
GetClientRect(hWnd, &rectView);
if (rectView.left > p.x - ObjectSize.cx / 2 && SpeedXpos <= 0)
{
SpeedXpos = -SpeedXpos;
p.x = rectView.left + ObjectSize.cx / 2;
ObjectRect.left = p.x - ObjectSize.cx / 2;
ObjectRect.right = p.x + ObjectSize.cx / 2;
}
else if (rectView.right < p.x + ObjectSize.cx / 2 && SpeedXpos >= 0)
{
SpeedXpos = -SpeedXpos;
p.x = rectView.right - ObjectSize.cx / 2;
ObjectRect.left = p.x - ObjectSize.cx / 2;
ObjectRect.right = p.x + ObjectSize.cx / 2;
}
if (rectView.top > p.y - ObjectSize.cy / 2 && SpeedYpos <= 0)
{
SpeedYpos = -SpeedYpos;
p.y = rectView.top + ObjectSize.cy / 2;
ObjectRect.top = p.y - ObjectSize.cy / 2;
ObjectRect.bottom = p.y + ObjectSize.cy / 2;
}
else if (rectView.bottom < p.y + ObjectSize.cy / 2 && SpeedYpos >= 0)
{
SpeedYpos = -SpeedYpos;
p.y = rectView.bottom - ObjectSize.cy / 2;
ObjectRect.top = p.y - ObjectSize.cy / 2;
ObjectRect.bottom = p.y + ObjectSize.cy / 2;
}
}
void Player::draw(){ //װ ġ
// κ
Rectangle(hdc, ObjectRect.left, ObjectRect.top,
ObjectRect.right, ObjectRect.bottom);
/*else if (MoveToYpos < 0)
MoveToYpos = 0;*/
// Ʈ
};
//-----------ǥ accessϱ Լ--------------
const POINT Player::getPlayer(){
POINT tp;
tp.x = p.x; tp.y = p.y;
return tp;
};
void Player::putPlayer(const int x, const int y){
p.x = x; p.y = y;
};
//----------------------------------------------------------
//----------------------------------------------------------
void Player::SetResistance(long RESISTANCEXPOS, long RESISTANCEYPOS){ //װ ; //߰ ڵ
resistanceXpos = RESISTANCEXPOS;
resistanceYpos = RESISTANCEYPOS;
}
void Player::MoveTo(const long x, const long y){ //̵ x , y //߰ ڵ
SpeedXpos += x;
SpeedYpos += y;
}
void Player::Move(){ //̵ //߰ ڵ
double ResistanceXpos = 0; //X //߰ ڵ
double ResistanceYpos = 0; //Y //߰ ڵ
//
if (SpeedXpos != 0)
ResistanceXpos = SpeedXpos * (resistanceXpos / MAXRESISTANCE);
if (SpeedYpos != 0)
ResistanceYpos = SpeedYpos * (resistanceYpos / MAXRESISTANCE);
//װ = ǵ * ;
SpeedXpos -= ResistanceXpos;
SpeedYpos -= ResistanceYpos;
//̵
p.x += (long)SpeedXpos;
p.y += (long)SpeedYpos;
ObjectRect.left = p.x - ObjectSize.cx / 2;
ObjectRect.top = p.y - ObjectSize.cy / 2;
ObjectRect.right = p.x + ObjectSize.cx / 2;
ObjectRect.bottom = p.y + ObjectSize.cy / 2;
}
| true |
aa5232cd43fc3ccd877d43a80c2b109bd67ac28f | C++ | danieldugas/Vitrified-Code | /C++/High Performance Computing Examples/Roofline/computepower.cpp | UTF-8 | 4,977 | 2.59375 | 3 | [] | no_license | /*
* computepower.cpp
*
* Created by Christian Conti on 9/21/11.
* Extended by Panagiotis Hadjidoukas on 11/1/14
* Copyright 2015 ETH Zurich. All rights reserved.
*
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <vector>
#include <string>
#include <cassert>
#include <algorithm>
#include <sys/time.h>
#if defined(_OPENMP)
#include <omp.h>
#endif
#include "ArgumentParser.h"
#define MULADD(b, x, a) (b*(x+a))
#define SUM8(x0, x1, x2, x3, x4, x5, x6, x7) (((x0 + x1) + (x2 + x3)) + ((x4 + x5) + (x6 + x7)))
//========================================================================================
//
// Helper Functions
//
//========================================================================================
// timer method
double mysecond()
{
#if defined(_OPENMP)
return omp_get_wtime();
#else
struct timeval tp;
struct timezone tzp;
int i;
i = gettimeofday(&tp,&tzp);
return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 );
#endif
}
void ComputePower(double * s, int iSize)
{
const int static N = iSize;
{
// store coefficients in registers
const double a0 = 0.01f;
const double a1 = 0.035f;
const double a2 = 0.001f;
const double a3 = 0.15f;
const double b0 = 0.012f;
const double b1 = 0.067f;
const double b2 = 0.02f;
const double b3 = 0.21f;
// 8 independent streams of computations
// this helps filling the processing pipeline
// 8 data reads
double x0 = s[0];
double y0 = s[0];
double z0 = s[0];
double w0 = s[0];
double r0 = s[0];
double t0 = s[0];
double u0 = s[0];
double v0 = s[0];
// compute independently 8 polynomial evaluations with horner's scheme of degree 4N
// 4*8*2*N FLOP
for (int i=0; i<N; i++)
{
double gx0 = MULADD(b0, x0, a0);
double gy0 = MULADD(b0, y0, a0);
double gz0 = MULADD(b0, z0, a0);
double gw0 = MULADD(b0, w0, a0);
double gr0 = MULADD(b0, r0, a0);
double gt0 = MULADD(b0, t0, a0);
double gu0 = MULADD(b0, u0, a0);
double gv0 = MULADD(b0, v0, a0);
double tx0 = MULADD(b1, gx0, a1);
double ty0 = MULADD(b1, gy0, a1);
double tz0 = MULADD(b1, gz0, a1);
double tw0 = MULADD(b1, gw0, a1);
double tr0 = MULADD(b1, gr0, a1);
double tt0 = MULADD(b1, gt0, a1);
double tu0 = MULADD(b1, gu0, a1);
double tv0 = MULADD(b1, gv0, a1);
double ux0 = MULADD(b2, tx0, a2);
double uy0 = MULADD(b2, ty0, a2);
double uz0 = MULADD(b2, tz0, a2);
double uw0 = MULADD(b2, tw0, a2);
double ur0 = MULADD(b2, tr0, a2);
double ut0 = MULADD(b2, tt0, a2);
double uu0 = MULADD(b2, tu0, a2);
double uv0 = MULADD(b2, tv0, a2);
x0 = MULADD(b3, ux0, a3);
y0 = MULADD(b3, uy0, a3);
z0 = MULADD(b3, uz0, a3);
w0 = MULADD(b3, uw0, a3);
r0 = MULADD(b3, ur0, a3);
t0 = MULADD(b3, ut0, a3);
u0 = MULADD(b3, uu0, a3);
v0 = MULADD(b3, uv0, a3);
}
// sum the results of the 8 polynomial evaluations
// and store in the output array
// without this step, the compiler might simplify the code by discarding unused computation and data
// 1 data write, 7 FLOP (irrelevant if N is large enough)
s[0] = SUM8(x0, y0, z0, w0, r0, t0, u0, v0);
}
}
//========================================================================================
//
// main
//
//========================================================================================
int main(int argc, const char ** argv)
{
ArgumentParser parser(argc,argv);
// get the number of threads
int nthreads = 0;
#pragma omp parallel
{
#pragma omp atomic
nthreads += 1;
}
// getting parameters
int iSize = (int)parser("-size").asDouble(1.e8);
int iIteration = (int)parser("-iterations").asDouble(10.);
// running benchmarks
double * timeHOI = new double[iIteration];
map<string, vector<double> > peakPerformance;
double * s = new double;
// initialize value for the polynomial evaluation
s[0] = 1e-6;
// run the benchmark iIteration times
for (int i=0; i<iIteration; i++)
{
#pragma omp parallel
{
ComputePower(s,iSize);
}
}
for (int i=0; i<iIteration; i++)
{
//double * s = new double;
//double s;
timeHOI[i] = mysecond();
#pragma omp parallel
{
ComputePower(s,iSize);
}
timeHOI[i] = mysecond() - timeHOI[i];
}
cout << "\nSummary\n";
// compute performance of each benchmark run
for (int i=0; i<iIteration; i++)
peakPerformance["HOI"].push_back(1.e-9*(double)iSize*4*2*8*nthreads / timeHOI[i]);
sort(peakPerformance["HOI"].begin(), peakPerformance["HOI"].end());
// percentiles to be selected
const int I1 = iIteration*.1;
const int I2 = iIteration*.5;
const int I3 = iIteration*.9;
// output 10th, 50th, 90th percentiles
cout << I1 << " Ranked Peak Performance\t" << I2 << " Ranked Peak Performance (median)\t" << I3 << " Ranked Peak Performance\n";
cout << peakPerformance["HOI"][I1] << " GFLOP/s\t" << peakPerformance["HOI"][I2] << " GFLOP/s\t" << peakPerformance["HOI"][I3] << " GFLOP/s\n";
}
| true |
f91f781bca16226fcc64b7bbee49db0eab414b7b | C++ | WaerjakSC/Oblig1 | /stack.cpp | UTF-8 | 1,532 | 3.640625 | 4 | [] | no_license | #include "stack.h"
#include <iostream>
#include <memory>
namespace ADS101 {
stack::stack(char ch) { head = new CharNode(ch); }
/**
* @brief stack::push
* @param ch
* Add a new item to the stack
*/
void stack::push(char ch) {
auto *tmp = new CharNode(ch, head);
head = tmp;
}
/**
* @brief stack::top
* @return
* Returns the last item entered into the stack
*/
char stack::top() {
if (head != nullptr) {
return head->hentData();
}
// Else...
std::cout << "Stack is empty.\n";
return 0;
}
/**
* @brief stack::pop
* @return
* Removes the last item entered into the stack and reads its contents into a
* variable if needed
*/
char stack::pop() {
if (head != nullptr) {
CharNode *tmp = head;
head = head->hentNeste();
char ch = tmp->hentData();
delete tmp;
return ch; // Return the char in case you want to know what you just deleted
}
// Else...
std::cout << "Stack is empty, nothing to pop.\n";
return 0;
}
/**
* @brief stack::empty
* Empties the stack (in hindsight should probably have been just a bool to
* check if stack is empty, but I'm leaving it as it is)
*/
void stack::empty() {
CharNode *tmp = head;
while (tmp != nullptr) {
head = head->hentNeste();
delete tmp;
tmp = head;
}
}
/**
* @brief stack::size
* @return Returns the total size of the stack
*/
int stack::size() { return head->hentAntall(); }
/**
* @brief stack::getHead
* @return Getter for top of stack
*/
CharNode *stack::getHead() { return head; }
} // namespace ADS101
| true |
e04ae98ba4a1bd2e9000f22cc2226539c5c010ca | C++ | dntowers/Squeak | /StateChange.cpp | UTF-8 | 2,619 | 2.625 | 3 | [] | no_license | #include "StdAfx.h"
#include "MouseLL.h"
#include "StateChange.h"
StateChange::StateChange(void)
{
_InitRequired();
_DefaultAll();
}
StateChange::StateChange(int new_StateID)
{
_InitRequired();
_DefaultAll();
StateID = new_StateID;
}
#pragma region Initialization
// initialize required values, e.g. arrays
System::Void StateChange::_InitRequired(void)
{
// create arrays
scEvents = gcnew array<scEvent^>(SC_INDEX_MAX);
scTimes = gcnew array<double>(SC_INDEX_MAX);
// init arrays
for(int iIndex = 0; iIndex < SC_INDEX_MAX; iIndex++)
{
scEvents[iIndex] = gcnew scEvent();
scTimes[iIndex] = -1;
}
return System::Void();
}
// set all defaults
System::Void StateChange::_DefaultAll(void)
{
directionX= SC_DIR::SCD_NONE;
stateX = SC_STATE::SCS_NONE;
seqX = SC_SEQ::SCQ_NONE;
eventX = SC_EVENT::SCE_NONE;
reasonX = SC_REASON::SCR_NONE;
return System::Void();
}
#pragma endregion
#pragma region Initialization
// set event
System::Void StateChange::set_scEvent(int index, EV_TYPE new_x_type, MouseLLEvent^ new_x_event, double new_x_time)
{
scEvents[index]->x_type = new_x_type;
scEvents[index]->x_event = new_x_event;
scEvents[index]->x_time = new_x_time;
scEvents[index]->x_EventID = new_x_event->getEventID();
}
#pragma endregion
//public enum class SC_DIR {
// SCD_FORWARD, // move forward in moviw
// SCD_BACK, // move back in movie
// SCD_NONE // no change
//};
//
//public enum class SC_STATE {
// SCS_PLAY_REC, // playing & recording
// SCS_PLAY_NOREC, // playing & no recording
// SCS_NOPLAY_REC, // no playing & recording
// SCS_NOPLAY_NOREC, // no playing & no recording
// SCS_NONE, // no playing & no recording
//};
//
//public enum class SC_SEQ {
// SCQ_ADDED, // added an event
// SCQ_REMOVED, // removed an event
// SCQ_CHANGED, // changed an event
// SCQ_NONE, // no event change
//};
//
//public enum class SC_EVENT {
// SCE_MOVED_AFTER, // just moved past an event (should be given)
// SCE_MOVED_BEFORE, // just moved before an event (should be given)
// SCE_PAST_LAST, // moved past last existing event
// SCE_BEFORE_FIRST, // moved before first event
// SCE_NONE, // no event move change
//};
//
//public enum class SC_REASON {
// SCR_PLAYING, // changed because of playing movie
// SCR_SCROLLING, // changed because of scrolling movie
// SCR_STEP, // changed because of stepping (button)
// SCR_GRID, // changed because of selecting on grid
// SCR_NONE, // none (should not happen??)
//};
| true |
9f7a6af7bd6d3d39f1b3e0d035d1ebc88a19d0d4 | C++ | xuebai5/StaticNFrame | /Server/Dependencies/common/ctlib/include/CTServerUtils.h | UTF-8 | 4,027 | 2.515625 | 3 | [] | no_license | /**
* Server开发的一些常用函数
*/
#ifndef __CTLIB_SERVERUTILS_H__
#define __CTLIB_SERVERUTILS_H__
#include <signal.h>
#include "CTFileUtils.h"
namespace CTLib
{
/**
* 封装了Server开发的一些常用函数
*/
class CTServerUtils
{
public:
#ifndef WIN32
static void Ignore(int signum)
{
struct sigaction sig;
sig.sa_handler = SIG_IGN;
sig.sa_flags = 0;
sigemptyset(&sig.sa_mask);
sigaction(signum, &sig, 0);
}
#endif
/**
* 转为守护进程
*/
static void InitDaemon(void)
{
#ifndef WIN32
pid_t pid;
if ((pid = fork()) != 0)
{
exit(0);
}
setsid();
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
signal(SIGTERM, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
Ignore(SIGPIPE);
Ignore(SIGHUP);
if ((pid = fork()) != 0)
{
exit(0);
}
umask(0);
#endif
}
/**
* 避免运行多个实例
*/
#ifndef WIN32
static bool CheckSingleRun(const char* pszAppName)
{
bool bRet = false;
string s;
string sPidFile;
do
{
// 只要文件名,去掉前面的路径
s = pszAppName;
size_t iPos = s.find_last_of('/');
if (iPos != string::npos)
{
s = s.substr(iPos + 1);
}
// 读取进程ID
sPidFile = "./" + s + ".pid";
CTFileUtils::ReadFile(sPidFile.c_str(), s);
CTStringUtils::TrimLeft(s, " \r\n\t");
CTStringUtils::TrimRight(s, " \r\n\t");
int iPid = CTStringUtils::StrToInt<int>(s.c_str());
if (iPid <= 0)
{
bRet = true;
break;
}
// 看看pid文件中保存的进程是否存在
s.assign(pszAppName);
iPos = s.find_last_of('/');
if (iPos != string::npos)
{
s = s.substr(iPos + 1);
}
string sCmd;
CTStringUtils::Format(sCmd, "ps -p %d | grep %s -c", iPid, s.c_str());
FILE* pstPipe = popen(sCmd.c_str(), "r");
if (pstPipe == NULL)
{
printf("popen(%s) fail\n", sCmd.c_str());
bRet = false;
break;
}
char szBuf[32];
fgets(szBuf, sizeof(szBuf) - 1, pstPipe);
pclose(pstPipe);
int iCount = atoi(szBuf);
// 进程已经存在了
if (iCount > 0)
{
printf("%s already running!\n", pszAppName);
bRet = false;
break;
}
bRet = true;
}
while(0);
if (bRet)
{
CTStringUtils::Format(s, "%d\n", getpid());
int iRet = CTFileUtils::WriteFile(sPidFile.c_str(), s);
if (iRet)
{
printf("cannot write pid: ret=%d errno=%d\n", iRet, CT_ERRNO);
return false;
}
return true;
}
return bRet;
}
#else
static bool CheckSingleRun(const char* pszAppName)
{
return true;
}
#endif
/**
* 删除pid文件.
*/
static void RemovePidFile(const char* pszAppName)
{
// 只要文件名,去掉前面的路径
string s(pszAppName);
size_t iPos = s.find_last_of('/');
if (iPos != string::npos)
{
s = s.substr(iPos + 1);
}
// 读取进程ID
string sPidFile = "./" + s + ".pid";
unlink(sPidFile.c_str());
}
};
} //namespace CTLib
#endif //__CTLIB_SERVERUTILS_H__
| true |
c18984d394ab02583b2c176c61db028838814bb6 | C++ | justin-harper/cs122 | /Assignment 4/Assingnment 4/Assingnment 4/RemoveGreenEffect.cpp | UTF-8 | 556 | 2.75 | 3 | [
"MIT"
] | permissive | /*
Assignment: 4
Description: Paycheck Calculator
Author: Justin Harper
WSU ID: 10696738 Completion Time: 4hrs
In completing this program, I received help from the following people:
myself
version 1.0 (major relese) I am happy with this version!
*/
#include "RemoveGreenEffect.h"
using namespace std;
//class to remove green from the image
void RemoveGreenEffect::processImage(vector<Point>& points)
{
//pretty stright forward just set the green value of each pixle to 0
for (int i = 0; i < points.size(); i++)
{
points[i].setGreen(0);
}
return;
} | true |
a16c03457f0791f21f2a54cea602ddd96308c64c | C++ | taidangit/lap-trinh-c-tran-duy-thanh | /HocKieuDuLieuVaKhaiBaoBien/main.cpp | UTF-8 | 361 | 2.609375 | 3 | [] | no_license | #include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int age;
float f=1.5f;
cout<<f<<endl;
bool b=true;
char c='c';
int x, y, z=7, k=0;
double dtb;
cout<<"Nhap diem trung binh:";
cin>>dtb;
cout<<"DTB="<<dtb;
return 0;
}
| true |
e870f4831bf2bf94b41d9ae634aa53df9992d07b | C++ | RFlor14/GameEngine | /GameEngine/Engine/Rendering/3D/Model.h | UTF-8 | 1,869 | 2.9375 | 3 | [] | no_license | #ifndef MODEL_H
#define MODEL_H
#include <glm/gtc/matrix_transform.hpp>
#include <string>
#include "LoadOBJModel.h"
class Model
{
public:
/*
Give all params default value so when it's needed to be updated,
there's no errors because it assumes you're using a default value.
[shaderProgram_] makes sure each model has the ability to specify what
shader program to use to render itself.
*/
Model(const std::string& objPath_, const std::string& matPath_, GLuint shaderProgram_);
~Model();
void Render(Camera* camera_);
// Adds a mesh to this model.
void AddMesh(Mesh* mesh_);
// Takes in pos, ang, rot, sca and creates a model matrix.
unsigned int CreateInstance(glm::vec3 position_, float angle_, glm::vec3 rotation_, glm::vec3 scale_);
/*
Takes in a specific index of an instance (pos, ang...) then it goes to
the vector of modelInstances and update that specific instances model matrix.
*/
void UpdateInstance(unsigned int index_, glm::vec3 position_, float angle_, glm::vec3 rotation_, glm::vec3 scale_);
/*
You pass it the specific index of the instance, then it returns
the instances model matrix.
*/
glm::mat4 GetTransform(unsigned int index_) const;
GLuint GetShaderProgram() const;
BoundingBox GetBoundingBox() const;
private:
// creates the transformation matrix, takes in (pos, ang...)'s values to create that matrix.
glm::mat4 CreateTransform(glm::vec3 position_, float angle_, glm::vec3 rotation_, glm::vec3 scale_) const;
void LoadModel();
// Holds a collection of mesh pointers.
std::vector<Mesh*> meshes;
// Saves the shader program
GLuint shaderProgram;
/*
Holds a vector for all of the model's instances, and returns
the number of the current or newly created instances.
*/
std::vector<glm::mat4> modelInstances;
LoadOBJModel* obj;
BoundingBox boundingBox;
};
#endif // !MODEL_H
| true |
e2831d2d9f1cffa6cf2ea4c3c5d314582e7b16c5 | C++ | AshwathVS/Programming | /codeforces/codeforces_rating_less_than_1300/elephant.cpp | UTF-8 | 348 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n,sum = 0,k;
cin >> n;
k = n/5;
sum += k;
n -= (k * 5);
k = n/4;
sum += k;
n -= (k * 4);
k = n/3;
sum += k;
n -= (k * 3);
k = n/2;
sum += k;
n -= (k * 2);
k = n/1;
sum += k;
n -= (k * 1);
cout << sum << endl;
}
int main () {
solve();
return 0;
}
| true |
aa8ce17b6ccd03334c5a5363d092597068e1f68c | C++ | daria-grebneva/OOD | /composite/composite/CGroupShape.cpp | UTF-8 | 3,772 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include "CGroupShape.h"
#include <algorithm>
#include <functional>
CGroupShape::CGroupShape()
{
m_shapes = std::make_shared<CShapes>();
m_groupLineStyle = std::make_shared<CGroupLineStyle>(m_shapes);
m_groupFillStyle = std::make_shared<CGroupFillStyle>(m_shapes);
}
RectD CGroupShape::GetFrame()
{
auto rect = RectD{ 0, 0, 0, 0 };
if (m_shapes->GetShapesCount() != 0)
{
auto firstFrame = m_shapes->GetShapeAtIndex(0)->GetFrame();
double minX = firstFrame.left;
double minY = firstFrame.top;
double maxX = firstFrame.left + firstFrame.width;
double maxY = firstFrame.top + firstFrame.height;
for (size_t i = 1; i < GetShapesCount(); ++i)
{
auto frame = m_shapes->GetShapeAtIndex(i)->GetFrame();
if (!IsNullFrame(frame))
{
minX = (IsNullFrame(firstFrame)) ? frame.left : std::min(minX, frame.left);
minY = (IsNullFrame(firstFrame)) ? frame.top : std::min(minX, frame.top);
maxX = std::max(maxX, frame.left + frame.width);
maxY = std::max(maxY, frame.top + frame.height);
}
}
rect = RectD{ minX, minY, maxX - minX, maxY - minY };
}
return rect;
}
bool CGroupShape::IsNullFrame(const RectD& frame)
{
return ((frame.height == 0) && (frame.width == 0) && (frame.top == 0) && (frame.left == 0));
}
void CGroupShape::SetFrame(const RectD& rect)
{
auto oldFrame = GetFrame();
for (size_t i = 0; i < m_shapes->GetShapesCount(); i++)
{
auto shape = m_shapes->GetShapeAtIndex(i);
auto oldShapeFrame = shape->GetFrame();
shape->SetFrame({ GetNewLeftCoord(rect, oldShapeFrame, oldFrame),
GetNewTopCoord(rect, oldShapeFrame, oldFrame),
GetNewWidth(rect, oldShapeFrame, oldFrame),
GetNewHeight(rect, oldShapeFrame, oldFrame) });
}
}
double CGroupShape::GetNewLeftCoord(const RectD& rect, const RectD& oldShapeFrame, const RectD& oldFrame)
{
return (rect.left + ((oldShapeFrame.left - oldFrame.left) * (rect.width / oldFrame.width)));
}
double CGroupShape::GetNewTopCoord(const RectD& rect, const RectD& oldShapeFrame, const RectD& oldFrame)
{
return (rect.top + ((oldShapeFrame.top - oldFrame.top) * (rect.height / oldFrame.height)));
}
double CGroupShape::GetNewWidth(const RectD& rect, const RectD& oldShapeFrame, const RectD& oldFrame)
{
return (oldShapeFrame.width * rect.width / oldFrame.width);
}
double CGroupShape::GetNewHeight(const RectD& rect, const RectD& oldShapeFrame, const RectD& oldFrame)
{
return (oldShapeFrame.height * rect.height / oldFrame.height);
}
std::shared_ptr<ILineStyle> CGroupShape::GetLineStyle()
{
return m_groupLineStyle;
}
std::shared_ptr<const ILineStyle> CGroupShape::GetLineStyle() const
{
return m_groupLineStyle;
}
std::shared_ptr<IStyle> CGroupShape::GetFillStyle()
{
return m_groupFillStyle;
}
std::shared_ptr<const IStyle> CGroupShape::GetFillStyle() const
{
return m_groupFillStyle;
}
std::shared_ptr<IGroupShape> CGroupShape::GetGroup()
{
return shared_from_this();
}
std::shared_ptr<const IGroupShape> CGroupShape::GetGroup() const
{
return shared_from_this();
}
size_t CGroupShape::GetShapesCount() const
{
return m_shapes->GetShapesCount();
}
void CGroupShape::InsertShape(const std::shared_ptr<IShape>& shape, size_t position)
{
m_shapes->InsertShape(shape, position);
}
std::shared_ptr<IShape> CGroupShape::GetShapeAtIndex(size_t index) const
{
return m_shapes->GetShapeAtIndex(index);
}
void CGroupShape::RemoveShapeAtIndex(size_t index)
{
m_shapes->RemoveShapeAtIndex(index);
}
void CGroupShape::Draw(ICanvas& canvas) const
{
for (size_t i = 0; i < m_shapes->GetShapesCount(); i++)
{
auto shape = m_shapes->GetShapeAtIndex(i);
shape->Draw(canvas);
}
}
| true |
2d81384666dda0c6b6d3ad3cb30d9aeff5699571 | C++ | aidanmcalaine/USC-CSCI103 | /PA5 (Arbitrary Precision Integers)/decipher.cpp | UTF-8 | 1,283 | 3.125 | 3 | [] | no_license | #include "bigint.h"
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout<<"\033[1;41m----Missing an argument----\033[0m"<<endl;
cout << "Usage: ./decipher <file>"<<endl;
cout << "Examples:" << endl;
cout << "\t./decipher secret/message1.txt \033[1;90m//to decipher message 1\033[0m" << endl;
cout << "\t./decipher secret/message2.txt \033[1;90m//to decipher message 2\033[0m"<<endl;
return -1;
}
/************* You complete *************/
//read the file pass in from the command line argument
//argv[...]
try {
ifstream ifile (argv[1]);
int base;
string d;
string n;
string secretcode;
ifile >> base >> d >> n;
BigInt one(d, base);
BigInt two(n, base);
string x = "";
while (!ifile.fail()) {
ifile >> secretcode;
BigInt secretMessage(secretcode, base);
secretMessage.modulusExp(one, two);
x += (char) secretMessage.to_int();
}
x.pop_back();
cout << x << endl;
}
catch (const exception& e) {
cout << e.what() << endl;
return -1;
}
return 0;
}
| true |
d7c86414247f9ddfe8880f6126220eedbb42879b | C++ | JHYOOOOON/Collection | /baekjoon/18429.cpp | UTF-8 | 665 | 2.75 | 3 | [] | no_license | #include <iostream>
using namespace std;
int n, k;
int kit[9];
bool isused[9];
int cnt = 0;
void select(int count, int weight) {
if (weight < 500) return;
if (count == n) {
cnt++;
return;
}
for (int i = 0; i < n; i++) {
if (!isused[i]) {
isused[i] = 1;
select(count + 1, weight - k + kit[i]);
isused[i] = 0;
}
}
return;
}
int main() {
cin >> n >> k;
for (int i = 0; i < n; i++) cin >> kit[i];
for (int i = 0; i < n; i++) {
isused[i] = 1;
select(1, 500 - k + kit[i]);
isused[i] = 0;
}
cout << cnt << "\n";
return 0;
}
| true |
d9dadf33456039d884d1edac0d3b7bdda6a56e5b | C++ | zjin-lcf/HeCBench | /merkle-sycl/ff_p.cpp | UTF-8 | 2,641 | 2.890625 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | #include "ff_p.hpp"
#include <climits>
uint64_t
ff_p_add(uint64_t a, uint64_t b)
{
if (b >= MOD) {
b -= MOD;
}
uint64_t res_0 = a + b;
bool over_0 = a > UINT64_MAX - b;
uint32_t zero = 0;
uint64_t tmp_0 = (uint64_t)(zero - (uint32_t)(over_0 ? 1 : 0));
uint64_t res_1 = res_0 + tmp_0;
bool over_1 = res_0 > UINT64_MAX - tmp_0;
uint64_t tmp_1 = (uint64_t)(zero - (uint32_t)(over_1 ? 1 : 0));
uint64_t res = res_1 + tmp_1;
return res;
}
uint64_t
ff_p_sub(uint64_t a, uint64_t b)
{
if (b >= MOD) {
b -= MOD;
}
uint64_t res_0 = a - b;
bool under_0 = a < b;
uint32_t zero = 0;
uint64_t tmp_0 = (uint64_t)(zero - (uint32_t)(under_0 ? 1 : 0));
uint64_t res_1 = res_0 - tmp_0;
bool under_1 = res_0 < tmp_0;
uint64_t tmp_1 = (uint64_t)(zero - (uint32_t)(under_1 ? 1 : 0));
uint64_t res = res_1 + tmp_1;
return res;
}
uint64_t
ff_p_mult(uint64_t a, uint64_t b)
{
if (b >= MOD) {
b -= MOD;
}
uint64_t ab = a * b;
uint64_t cd = sycl::mul_hi(a, b);
uint64_t c = cd & 0x00000000ffffffff;
uint64_t d = cd >> 32;
uint64_t res_0 = ab - d;
bool under_0 = ab < d;
uint32_t zero = 0;
uint64_t tmp_0 = (uint64_t)(zero - (uint32_t)(under_0 ? 1 : 0));
res_0 -= tmp_0;
uint64_t tmp_1 = (c << 32) - c;
uint64_t res_1 = res_0 + tmp_1;
bool over_0 = res_0 > UINT64_MAX - tmp_1;
uint64_t tmp_2 = (uint64_t)(zero - (uint32_t)(over_0 ? 1 : 0));
uint64_t res = res_1 + tmp_2;
return res;
}
uint64_t
ff_p_pow(uint64_t a, const uint64_t b)
{
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
if (a == 0) {
return 0;
}
uint64_t r = b & 0b1 ? a : 1;
for (uint8_t i = 1; i < 64 - sycl::clz(b); i++) {
a = ff_p_mult(a, a);
if ((b >> i) & 0b1) {
r = ff_p_mult(r, a);
}
}
return r;
}
uint64_t
ff_p_inv(uint64_t a)
{
if (a >= MOD) {
a -= MOD;
}
if (a == 0) {
// ** no multiplicative inverse of additive identity **
//
// I'm not throwing an exception from here, because
// this function is supposed to be invoked from
// kernel body, where exception throwing is not (yet) allowed !
return 0;
}
const uint64_t exp = MOD - 2;
return ff_p_pow(a, exp);
}
uint64_t
ff_p_div(uint64_t a, uint64_t b)
{
if (b == 0) {
// ** no multiplicative inverse of additive identity **
//
// I'm not throwing an exception from here, because
// this function is supposed to be invoked from
// kernel body, where exception throwing is not (yet) allowed !
return 0;
}
if (a == 0) {
return 0;
}
uint64_t b_inv = ff_p_inv(b);
return ff_p_mult(a, b_inv);
}
| true |
8d030327b681ea0cbc26901c0bc9b74636359edf | C++ | stephenosullivan/Guide-to-Scientific-Computing-in-cpp | /Guide_to_Scientific_Computing/Exercise5_2.cpp | UTF-8 | 405 | 3.34375 | 3 | [] | no_license | //
// Exercise5_2.cpp
// Guide to Scientific Computing
//
// Created by Stephen O'Sullivan on 10/14/15.
// Copyright (c) 2015 Stephen O'Sullivan. All rights reserved.
//
// Send the address of an int to a func that changes the value of the int
#include <iostream>
void times2(int* i){
*i = 2 * (*i);
}
int main(){
int i = 5;
std::cout << i << "\n";
times2(&i);
std::cout << i << "\n";
return 0;
}
| true |
ec9b0544eead6fdde1d2387186f8fa4c1a0d96ed | C++ | MohammadAlhourani/AI-In-Games | /Ai Labs/AI Lab/AI Lab/Player.cpp | UTF-8 | 2,247 | 3.03125 | 3 | [] | no_license | #include "Player.h"
Player::Player()
{
setUpPlayer();
}
Player::~Player()
{
}
void Player::update(sf::Time t_deltaTime)
{
m_behaviours.boundary(m_position , m_playerSprite);
movement();
}
/// <summary>
/// the draw function simply draws the player
/// </summary>
/// <param name="t_renderWindow"></param>
void Player::draw(sf::RenderWindow &t_renderWindow)
{
t_renderWindow.draw(m_playerSprite);
}
/// <summary>
/// sets up the players sprite, loading the texture and setting the origin to the centre of the sprite
/// giving the player a random starting rotation
/// </summary>
void Player::setUpPlayer()
{
if (m_playerText.loadFromFile("ASSETS/IMAGES/playerShip.png"))
{
m_playerSprite.setTexture(m_playerText);
}
m_position = sf::Vector2f(750, 650);
m_playerSprite.setOrigin(m_playerSprite.getGlobalBounds().width / 2, m_playerSprite.getGlobalBounds().height / 2);
m_playerSprite.setScale(2, 2);
m_speed = 0;
m_orientation = 0;
m_velocity = sf::Vector2f(rand() % WINDOW_WIDTH, rand() % WINDOW_HEIGHT) - m_position;
m_orientation = m_behaviours.getNewOrientation(m_orientation, m_velocity);
m_playerSprite.setPosition(m_position);
m_playerSprite.setRotation(m_orientation);
}
void Player::movement()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && m_speed < m_maxSpeed ||
sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && m_speed < m_maxSpeed)
{
m_speed++;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && m_speed > 0 ||
sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && m_speed > 0)
{
m_speed--;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
m_velocity = m_behaviours.rotate(rotationDeg, m_velocity);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) || sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
m_velocity = m_behaviours.rotate(-rotationDeg, m_velocity);
}
m_position += m_behaviours.unitVec(m_velocity) * m_speed;
m_orientation = m_behaviours.getNewOrientation(m_orientation, m_velocity);
m_playerSprite.setPosition(m_position);
m_playerSprite.setRotation(m_orientation);
}
sf::Vector2f Player::getPos()
{
return m_position;
}
sf::Vector2f Player::getVelocity()
{
return m_velocity;
}
| true |
2912106ff73971c5dc50bc5280a9514e6c6c2260 | C++ | NGPGeeks/CPP | /AssignmentOOP/025Overload_new_delete_operators_in_a_class.cpp | UTF-8 | 2,106 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<new>
#include<stdlib.h>
using namespace std;
const int MAX = 5;
const int FREE = 0;
const int OCCUPIED = 1;
void memwarning( )
{
cout << endl <<"Free store has now gone empty";
exit( 1 );
}
class employee
{
private:
char name[20];
int age;
float sal;
public:
void *operator new(size_t bytes);
void operator delete( void * q );
void setdata( char * n, int a, float s );
void showdata();
~employee();
};
struct pool
{
employee obj;
int status;
};
int flag=0;
struct pool *p = NULL;
void * employee::operator new( size_t sz )
{
int i;
if( flag == 0 )
{
p = ( pool * )malloc( sz * MAX );
if( p == NULL )
memwarning( );
for( i = 0; i < MAX; i++ )
p[ i ].status = FREE;
flag = 1;
p[ 0 ].status = OCCUPIED;
return &p[ 0 ].obj;
}
else
{
for( i = 0; i < MAX; i++ )
{
if( p[ i ].status = FREE )
{
p[ i ].status = OCCUPIED;
return &p[ i ].obj;
}
}
memwarning( );
}
}
void employee::operator delete( void * q )
{
if(q == NULL)
return;
for(int i = 0; i < MAX; i++)
{
if(q == &p[ i ].obj)
{
p[i].status = FREE;
strcpy(p[i].obj.name, "" );
p[i].obj.age = 0;
p[i].obj.sal = 0.0;
}
}
}
void employee::setdata( char * n, int a, float s )
{
strcpy(name, n);
age = a;
sal = s;
}
void employee::showdata()
{
cout << endl << name << "\t" << age << "\t" << sal;
}
employee::~employee()
{
cout << endl << "reached destructor";
free(p);
}
int main()
{
void memwarning();
set_new_handler(memwarning);
employee * e1,*e2,*e3,*e4,*e5,*e6;
e1 = new employee;
e1->setdata("ajay", 23, 4500.50 );
e2 = new employee;
e2->setdata("amol", 25, 5500.50 );
e3 = new employee;
e3->setdata("anil", 26, 3500.50 );
e4 = new employee;
e4->setdata("anuj", 30, 6500.50 );
e5 = new employee;
e5->setdata("atul", 23, 4200.50 );
e1->showdata();
e2->showdata();
e3->showdata();
e4->showdata();
e5->showdata();
delete e4;
delete e5;
e4->showdata( );
e5->showdata( );
e4 = new employee;
e5 = new employee;
e6 = new employee;
cout << endl << "Done!!";
return 0;
}
| true |
dfa3de56a9963ec867b32a8c32e556e537700270 | C++ | nvnnv/Leetcode | /1376. Time Needed to Inform All Employees.cpp | UTF-8 | 807 | 2.625 | 3 | [] | no_license | void findMinR(unordered_map<int, vector<pair<int, int>>>& g, int i, int r, int& minR)
{
for (int j = 0; j < g[i].size(); ++j)
{
if (g[i][j].second > 0)
{
findMinR(g, g[i][j].first, r + g[i][j].second, minR);
}
}
minR = max(r, minR);
}
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
unordered_map<int, vector<pair<int, int>>> gg;
for (int i = 0; i < manager.size(); ++i)
{
if (manager[i] != -1)
{
if (!gg.count(manager[i]))
{
vector<pair<int, int>> x;
gg[manager[i]] = x;
}
gg[manager[i]].push_back({ i, informTime[manager[i]] });
}
}
int a = 0;
findMinR(gg, headID, 0, a);
return a;
}
| true |
c93b392f5fb566cfb28553caf0f1418ceddaec25 | C++ | tangya3158613488/Practice | /TCP/tcpServer.cc | UTF-8 | 780 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<unordered_map>
#include"tcp_server.hpp"
std::unordered_map<std::string,std::string> dict;
void Translate(const std::string& req,std::string& resp)
{
auto it=dict.find(req);
if(it==dict.end())
{
*resp="未找到";
return;
}
*resp=it->second;
return;
}
int main(int argc,char* argv[])
{
if(argc!=3)
{
printf("Usage:\n");
return 1;
}
dict.insert(std::make_pair("hello","你好"));
dict.insert(std::make_pair("apple","苹果"));
dict.insert(std::make_pair("world","世界"));
dict.insert(std::make_pair("happy","快乐"));
dict.insert(std::make_pair("future","未来"));
TcpServer server(argv[1],atoi(argv[2]));
server.Start(Translate);
return 0;
}
| true |
0050b4f85666028bccabf0ced15b67db7ca42aaf | C++ | jaybroker/dstore | /dstore/test/simple_packet_client_test.cpp | UTF-8 | 2,867 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <list>
#include <memory>
#include "tcp_client.h"
#include "connection.h"
#include "message.h"
#include "errno_define.h"
#include "log.h"
using namespace dstore::common;
using namespace dstore::network;
struct simple_packet
{
int32_t data_len;
char *data;
};
int decode_message(std::shared_ptr<Connection> conn)
{
int ret = DSTORE_SUCCESS;
const size_t header_len = sizeof(int32_t);
Buffer &read_buffer = conn->get_read_buffer();
size_t readable_bytes = read_buffer.get_read_bytes();
if (readable_bytes < header_len) {
ret = DSTORE_EAGAIN;
return ret;
}
LOG_INFO("header enough, readable_bytes = %d", readable_bytes);
char *data = read_buffer.get_data();
int32_t data_len = read_buffer.peek_int32();
LOG_INFO("data len=%d\n", data_len);
if (readable_bytes < data_len + header_len) {
ret = DSTORE_EAGAIN;
return ret;
}
simple_packet *packet = new simple_packet();
packet->data_len = data_len;
packet->data = data + header_len;
Message *message = new Message(static_cast<void *>(packet));
conn->add_message(message);
read_buffer.consume(data_len + header_len);
return ret;
}
int process_message(std::shared_ptr<Connection> conn)
{
int ret = DSTORE_SUCCESS;
LOG_INFO("start processing message");
std::list<Message *> &message_list = conn->get_message_list();
for (auto iter = message_list.begin(); iter != message_list.end();) {
LOG_INFO("start dealing with message");
simple_packet *packet = static_cast<simple_packet *>((*iter)->get_request());
LOG_INFO("data_len=%d, data=%s", packet->data_len, packet->data);
delete packet;
delete *iter;
iter = message_list.erase(iter);
}
return ret;
}
int connected(std::shared_ptr<Connection> conn)
{
int ret = DSTORE_SUCCESS;
char buffer[1024];
snprintf(buffer, sizeof(buffer), "hello world from client");
Buffer &write_buffer = conn->get_write_buffer();
write_buffer.append_int32(static_cast<int32_t>(strlen(buffer)));
write_buffer.append(buffer, strlen(buffer));
LOG_INFO("writetable_bytes=%d", write_buffer.get_need_write_bytes());
if (DSTORE_SUCCESS != (ret = conn->add_write())) {
LOG_INFO("add write event failed, ret=%d", ret);
return ret;
}
return ret;
}
int main(int argc, char **argv)
{
int ret = DSTORE_SUCCESS;
TCPClient client;
client.set_message_decode_callback(decode_message);
client.set_new_message_callback(process_message);
client.set_connect_complete_callback(connected);
if (DSTORE_SUCCESS != (ret = client.start())) {
LOG_WARN("client start failed, ret=%d", ret);
return ret;
}
if (DSTORE_SUCCESS != (ret = client.connect("127.0.0.1", "8900", false))) {
LOG_WARN("connect failed, ret=%d", ret);
return ret;
}
if (DSTORE_SUCCESS != (ret = client.loop())) {
LOG_WARN("loop failed, ret=%d", ret);
return ret;
}
return ret;
}
| true |
8c3a108c7c56decbf7bcccbc8481857c06d15650 | C++ | anhstudios/swganh | /src/swganh_core/object/slot_exclusive.cc | UTF-8 | 1,023 | 2.640625 | 3 | [
"MIT"
] | permissive | // This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "slot_exclusive.h"
#include "object.h"
using namespace swganh::object;
std::shared_ptr<swganh::object::Object> SlotExclusive::insert_object(const std::shared_ptr<swganh::object::Object> insertObject)
{
std::shared_ptr<swganh::object::Object> result = held_object_;
held_object_ = insertObject;
return result;
}
void SlotExclusive::remove_object(const std::shared_ptr<swganh::object::Object> removeObject)
{
if(held_object_ == removeObject)
{
held_object_ = nullptr;
}
}
void SlotExclusive::view_objects(std::function<void(const std::shared_ptr<swganh::object::Object>&)> walkerFunction)
{
if (held_object_ != nullptr)
walkerFunction(held_object_);
}
void SlotExclusive::view_objects_if(std::function<bool(std::shared_ptr<swganh::object::Object>)> walkerFunction)
{
if (held_object_ != nullptr)
walkerFunction(held_object_);
} | true |
41d9b61bef4e449a46c20f4f0dbd3fd2e195a132 | C++ | jacobgus/Speed-Detector | /SpeedDetector.ino | UTF-8 | 3,119 | 2.84375 | 3 | [] | no_license | // The sensor send and recieve code is based off David Mellis and Tom Igoe's code PING)))
// Created by Jacob Gus June 9th 2017
// this constant won't change. It's the pin number
// of the sensor's output:
const int pingPin = 7;
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// establish variables for duration of the ping,
// and the distance result in inches:
float duration1, duration2, inches1, inches2, differencePost, differencePreABS, distanceA, distanceB, startTime, elapsedTime, elapsedSeconds, FPS, IPS, MPH;
if (1){
//Value 1 starts here
//Start the timmer
startTime = millis();
// PING triggered
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(20000);
digitalWrite(pingPin, HIGH);
delayMicroseconds(20000);
digitalWrite(pingPin, LOW);
//Listen for PING back on same pin
pinMode(pingPin, INPUT);
duration1 = pulseIn(pingPin, HIGH);
//End of Value 1
delay(100);
//Value 2 Starts here
// PING triggered
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(20000);
digitalWrite(pingPin, HIGH);
delayMicroseconds(20000);
digitalWrite(pingPin, LOW);
//Listen for PING back on same pin
pinMode(pingPin, INPUT);
duration2 = pulseIn(pingPin, HIGH);
//End of Value 2
//Take the elapsed time between millis started and stopped and subtract it
elapsedTime = millis() - startTime;
//Divide by 1000 to change milliseconds into seconds
elapsedSeconds = (elapsedTime / 1000);
}
// convert the first time into a distance
inches1 = microsecondsToInches(duration1);
//set our distance of Value 1
distanceA = inches1;
//convert the second time into a distance
inches2 = microsecondsToInches(duration2);
//set our distance of Value 2
distanceB = inches2;
//Find difference in distance A and B
differencePreABS = distanceA - distanceB;
//Find absolute value of distance incase the object is moving in a direction that would produce a negative number
if (differencePreABS < 0){
differencePost = differencePreABS * -1;
}
else{
differencePost = differencePreABS * 1;
}
//IPS = Inches Per Second, FPS = Feet Per Second, MPH = Miles Per Hour
//Find our Inches Per Second
IPS = (differencePost / elapsedSeconds);
//Divide by Inches Per Second by 12 to get Feet Per second
FPS = (IPS / 12);
//Multiple Feet Per Second by .6818 to get Miles Per Hour
MPH = (FPS * .6818);
//Print all the data
Serial.print("Speed in MPH: ");
Serial.print(MPH);
Serial.println();
Serial.print("________________________________________________");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds) {
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
| true |
083d369f9b7100263182336bb27e722bf70bd976 | C++ | KentoNishi/JOI-Solutions | /2019-2020/competitions/joi2020-yo2/digits/main.cpp | UTF-8 | 991 | 2.65625 | 3 | [] | no_license | // Test case path: [path]
// url
#include <bits/stdc++.h>
using namespace std;
vector<bool> seen;
vector<bool> dp;
int N;
bool possible(int i, int h) {
//cout << i << " " << h << endl;
if (i == N) {
return true;
}
if (i > N) {
return false;
}
if (seen[i]) {
return dp[i];
}
seen[i] = true;
int num = i;
int sum = 0;
while (num > 0) {
int a = num % 10;
num /= 10;
sum += a;
}
dp[i] = possible(sum + i, i);
return dp[i];
}
int main() {
cin >> N;
seen = vector<bool>(N);
dp = vector<bool>(N);
int ans = 1;
for (int i = 1; i < N; i++) {
if (!seen[i]) {
if (possible(i, i)) {
//cout << i << " works " << endl;
ans++;
}
} else {
if (dp[i]) {
//cout << i << " works " << endl;
ans++;
}
}
}
cout << ans << endl;
return 0;
} | true |
b14b4fb3afe90f6a687211092a162bc5f41239ff | C++ | Grayer123/Algorithm-Design | /Rule_of_Three/Rule_of_Three/GCharacter.h | UTF-8 | 881 | 3.171875 | 3 | [] | no_license | /*
* GCharacter.h
*
* Created on Dec 26, 2015
* Author: Hongmin
*/
#ifndef GCHARACTER_H
#define GCHARACTER_H
#include"Header.h"
class GCharacter{
//Overload the insertion operator to output a GCharacter object
friend std::ostream& operator<<(std::ostream& os, const GCharacter& gc);
public:
static const int DEFAULT_CAPACITY = 5;
//Constructor
GCharacter(string = "Grayer", int = DEFAULT_CAPACITY);
//Copy Constructor
GCharacter(const GCharacter&);
//Overloaded Assignment Operator(returning a GCharacter&, because we could chain like gc1 = gc2 = gc3)
GCharacter& operator=(const GCharacter&);
//Destructor
~GCharacter();
//Insert a new tool into the toolHolder
void insert(const string&);
private:
//data members
string name;
int capacity;
int used;
string *toolHolder;
};
#endif /* GCHARACTER_H */
| true |
4cfa924298750967f3af5ca9ef4cc0ff0592e245 | C++ | username13459/URL-Distributor | /src/log.h | UTF-8 | 310 | 2.734375 | 3 | [] | no_license | #pragma once
#include<string>
using std::string;
namespace progLog
{
//Prepares for logging, opening the log file and etc.
void startLog();
//Writes a message to the log, with the timestamp appended to the front
void write(string message);
//Closes the current log
void closeLog();
}
| true |
b582e1453c62318c4448743c22ae99ec248ffa54 | C++ | martinpiper/ReplicaNetPublic | /ExampleMarmalade1/source/Enemy.cpp | UTF-8 | 3,910 | 2.53125 | 3 | [] | no_license | #include "s3e.h"
#include <math.h>
#include "main.h"
#include "Enemy.h"
#include "RNReplicaNet/Inc/ReplicaNet.h"
Enemy::Enemy()
{
int32 width = s3eSurfaceGetInt(S3E_SURFACE_WIDTH);
int32 height = s3eSurfaceGetInt(S3E_SURFACE_HEIGHT);
if (IsMaster())
{
mSeed = rand();
mPosX = (float)(rand() % width);
mPosY = (float)(rand() % height);
mVelX = -32.0f + ((float)(rand() & 63) / 2.0f);
mVelY = -32.0f + ((float)(rand() & 63) / 2.0f);
}
}
Enemy::~Enemy()
{
}
void Enemy::PostObjectCreate(void)
{
}
void Enemy::Tick(float timeDelta)
{
if (IsMaster())
{
float width = (float)s3eSurfaceGetInt(S3E_SURFACE_WIDTH);
float height = (float)s3eSurfaceGetInt(S3E_SURFACE_HEIGHT);
if ( ((mPosX < 0) && (mVelX < 0)) || ((mPosX > width) && (mVelX > 0)) )
{
ContinuityBreak(mPosX,RNReplicaNet::DataBlock::kSuddenChange); // Flag a change for the position since the velocity has changed direction
mVelX = -mVelX;
}
if ( ((mPosY < 0) && (mVelY < 0)) || ((mPosY > height) && (mVelY > 0)) )
{
ContinuityBreak(mPosY,RNReplicaNet::DataBlock::kSuddenChange); // Flag a change for the position since the velocity has changed direction
mVelY = -mVelY;
}
mPosX += mVelX * timeDelta;
GiveDeltaHint(mPosX,mVelX);
mPosY += mVelY * timeDelta;
GiveDeltaHint(mPosY,mVelY);
}
}
// Random number generation
#define N 624
#define M 397
#define MATRIX_A 0x9908b0df
#define UPPER_MASK 0x80000000
#define LOWER_MASK 0x7fffffff
/* Tempering parameters */
#define TEMPERING_MASK_B 0x9d2c5680
#define TEMPERING_MASK_C 0xefc60000
#define TEMPERING_SHIFT_U(y) (y >> 11)
#define TEMPERING_SHIFT_S(y) (y << 7)
#define TEMPERING_SHIFT_T(y) (y << 15)
#define TEMPERING_SHIFT_L(y) (y >> 18)
static unsigned long mt[N];
static int mti=N+1;
void sgenrand(unsigned long seed)
{
// [KNUTH 1981, The Art of Computer Programming Vol. 2 (2nd Ed.), pp102]
mt[0]= seed & 0xffffffff;
for (mti=1; mti<N; mti++)
{
mt[mti] = (69069 * mt[mti-1]) & 0xffffffff;
}
}
unsigned long genrand()
{
unsigned long y;
static unsigned long mag01[2]={0x0, MATRIX_A};
if (mti >= N)
{
int kk;
if (mti == N+1)
{
sgenrand(4357);
}
for (kk=0;kk<N-M;kk++)
{
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
}
for (;kk<N-1;kk++)
{
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
mti = 0;
}
y = mt[mti++];
y ^= TEMPERING_SHIFT_U(y);
y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
y ^= TEMPERING_SHIFT_L(y);
return y;
}
void Enemy::Render(void)
{
float dx,dy;
float newX,newY;
float startX,startY;
float newRot;
float len;
// MPi: TODO: This means all random numbers will be seeded for each render. If random numbers are needed during the game update loop
// this can cause issues, so consider using a different random number generator, or using some kind of tracked seed for the game
// update loop.
// rand() is not consistent across platforms given the same seed. So this is using a local version of rand() for rendering.
sgenrand(mSeed);
newRot = (float) ((mSeed & 31)-16) * (float) GetBoundReplicaNet()->GetTime();
int segments = (mSeed & 7) + 5;
len = (float)5.0f + (genrand() & 31);
startX = mPosX + (sinf(DEG2RAD(newRot)) * len);
startY = mPosY + (cosf(DEG2RAD(newRot)) * len);
dx = startX;
dy = startY;
int i;
for (i=0;i<segments;i++)
{
len = (float)5.0f + (genrand() & 31);
newX = mPosX + (sinf(DEG2RAD(newRot)) * len);
newY = mPosY + (cosf(DEG2RAD(newRot)) * len);
DrawLineRGB((int) dx,(int) dy,(int) newX,(int) newY, 255,255,255);
dx = newX;
dy = newY;
newRot += 300.0f / float(segments);
}
DrawLineRGB((int) dx,(int) dy,(int) startX,(int) startY, 255,255,255);
}
| true |
ab87a038429ea00d5fab7f1da8c95c8461220a07 | C++ | riven521/CLU18 | /Slu_CluVNS2/src/CluVRPinst.cpp | GB18030 | 2,757 | 3.046875 | 3 | [] | no_license | #include "CluVRPinst.h"
#include <iostream>
//**********************************************************************************************//
CluVRPinst::CluVRPinst(std::vector<Cluster> vClusters, int nVehicles)
{
this->nVehicles_ = nVehicles; //ijΪó
this->vehicleCapacity_ = Globals::vehicleCapacity; //ͬ
this->vClusters_ = vClusters;
this->nClusters_ = vClusters.size();
}
CluVRPinst::~CluVRPinst(){}
// ȡųDepotľ
std::vector<Cluster*> CluVRPinst::getClientClusters(void)
{
std::vector<Cluster*> v;
for (int i = 0; i < nClusters_; i++)
{
if(!vClusters_.at(i).isDepot) v.push_back(&vClusters_.at(i));
}
return v;
}
// жdepot,ѡһ
Cluster* CluVRPinst::getRandomDepot(void)
{
std::vector<Cluster*> v;
for (int i = 0; i < nClusters_; i++)
{
if (vClusters_.at(i).isDepot) v.push_back(&vClusters_.at(i));
}
return v.at(rand() % v.size());//ѡһ
}
// жǷ
bool CluVRPinst::isFeasible(void)
{
int totalDemand = 0;
for (int i = 0; i < nClusters_; i++)
{
totalDemand += vClusters_.at(i).getDemand();
}
return totalDemand <= (nVehicles_ * vehicleCapacity_);
}
// <<
template <typename TElem>
ostream& operator<<(ostream& os, const vector<TElem>& vec) {
typedef vector<TElem>::const_iterator iter_t;
const iter_t iter_begin = vec.begin();
const iter_t iter_end = vec.end();
os << "[";
for (iter_t iter = iter_begin; iter != iter_end; ++iter) {
cout << ((iter != iter_begin) ? "," : "") << *iter;
}
os << "]" << endl;
return os;
}
ostream& operator<<(ostream& os, const CluVRPinst* cluVRPinst)
{
cout << "£" << endl;
cout << "" << cluVRPinst->nClusters_ << " ";
cout << ":" << cluVRPinst->vehicleCapacity_ << " ";
//cout << "㹻?:" << cluVRPinst->isFeasible << " ";
cout << ":" << cluVRPinst->nClusters_ << endl << endl;
cout << "ڵΪ:" << endl;
cout << cluVRPinst->distNodes_ << endl;
cout << "HandoffΪ:" << endl;
cout << cluVRPinst->distClusters_ << endl;
cout << "ʵ:ÿ:" << endl;
//cout << (cluVRPinst->vClusters_) << endl;
vector<Cluster>::const_iterator it = cluVRPinst->vClusters_.begin();
for (; it != cluVRPinst->vClusters_.end(); ++it)
{
//cout << "ID" << it->show() << endl;
cout << "ID" << it->getId() << " ";
cout << "ڽڵ:" << it->getnNodes() << " ";
cout << "Demand:" << it->getDemand() << " ";
cout << "Ƿdepot:" << it->isDepot << " ";
cout << "ڽڵϢδ" << endl;
}
return os;
}
| true |
027a35808ef6ffad024948df328173c4e9b738a2 | C++ | ScorpionMLG/cpp1 | /7..cpp | UTF-8 | 196 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main(){
float a, b;
cout<<"vvedite kateti treugolnika: ";
cin>>a>>b;
cout<<"gipotenuza: "<< sqrt(a*a + b*b);
return 0;
} | true |
2f3bf60f27d80d8352738c2f94b2111585657b2a | C++ | Mitza23/Video_Player_CPP | /Domain/Commands/User/AddCommandUser.h | UTF-8 | 564 | 2.609375 | 3 | [] | no_license | //
// Created by mitza on 31-May-21.
//
#ifndef A10_MITZA23_1_ADDCOMMANDUSER_H
#define A10_MITZA23_1_ADDCOMMANDUSER_H
#include <Commands/Command.h>
#include <string>
#include <Repository.h>
class AddCommandUser : public Command{
private:
Repository& repository, dataBase;
std::string title;
public:
AddCommandUser(Repository &repository, const Repository &dataBase, const std::string &title) : repository(
repository), dataBase(dataBase), title(title) {}
void undo();
void redo();
};
#endif //A10_MITZA23_1_ADDCOMMANDUSER_H
| true |
787b917e45658b08563e283785331dd540b53d77 | C++ | BlastTNG/flight | /stars/code/tools/stats.h | UTF-8 | 1,802 | 2.6875 | 3 | [] | no_license | /*
* © 2013 Columbia University. All Rights Reserved.
* This file is part of STARS, the Star Tracking Attitude Reconstruction
* Software package, originally created for EBEX by Daniel Chapman.
*/
#pragma once
#ifndef TOOLS__STATS_H
#define TOOLS__STATS_H
#include <cmath>
#include <vector>
template <typename T>
double get_mean(std::vector<T>& values)
{
if (values.size() < 1) {
return 0.0;
}
double total = 0;
for (unsigned int i=0; i<values.size(); i++) {
total += values[i];
}
return total/double(values.size());
}
template <typename T>
double get_mean(T values[], int num_values)
{
if (num_values < 1) {
return 0.0;
}
double total = 0;
for (int i=0; i<num_values; i++) {
total += values[i];
}
return total/double(num_values);
}
template <typename T>
double get_sample_stdev(std::vector<T>& values, double& mean)
{
if (values.size() < 2) {
return 1.0;
}
double s = 0;
for (unsigned int i=0; i<values.size(); i++) {
s += pow(double(values[i])-mean, 2);
}
s = s / (double(values.size()) - 1.0);
return sqrt(s);
}
template <typename T>
double get_sample_stdev(T values[], int num_values, double& mean)
{
if (num_values < 2) {
return 1.0;
}
double s = 0;
for (int i=0; i<num_values; i++) {
s += pow(double(values[i])-mean, 2);
}
s = s / (double(num_values) - 1.0);
return sqrt(s);
}
template <typename T>
double get_sample_stdev(std::vector<T>& values)
{
double mean = get_mean(values);
return get_sample_stdev(values, mean);
}
template <typename T>
double get_sample_stdev(T values[], int num_values)
{
double mean = get_mean(values, num_values);
return get_sample_stdev(values, num_values, mean);
}
#endif
| true |
a4ca0a02a0695b1ead1d677d72c5690f671019ce | C++ | xinyuyao22/BattleShip | /MVC/View.h | UTF-8 | 1,085 | 2.5625 | 3 | [] | no_license | //
// Created by mfbut on 3/9/2019.
//
#ifndef BATTLESHIP_VIEW_H
#define BATTLESHIP_VIEW_H
#include <unordered_map>
#include "PlayerConfiguration.h"
#include "ShipPlacement.h"
#include "Player.h"
#include "AttackResult.h"
namespace BattleShip {
class Player; //forward declaration
class Model;
class Move;
class View {
public:
virtual PlayerConfiguration getPlayerConfiguration() = 0;
virtual std::string getPlayerName(int i) = 0;
virtual ShipPlacement getShipPlacement(const Player& player, char shipChar, int shipLen) = 0;
virtual void updateShipPlacementView(const Player& player) = 0;
virtual std::pair<int, int> getFiringCoordinate(const BattleShip::Player& attacker) = 0;
virtual void showWinner(const Player& winner) = 0;
virtual void showResultOfAttack(const BattleShip::Player& attacker,
const BattleShip::AttackResult& attackResult) = 0;
virtual void showPlayersBoard(const Player& player) = 0;
virtual void showPlacementBoard(const Player& player) = 0;
virtual int getAiChoice() = 0;
};
}
#endif //BATTLESHIP_VIEW_H
| true |
355cf350b10ef211b6079680345fcf15900b8d8f | C++ | gshovkoplyas/ITMO | /Discrete Math/Sort/antiqs/main.cpp | UTF-8 | 590 | 2.640625 | 3 | [] | no_license | /*Grigory Shovkoplyas in the house*/
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<cstdlib>
#include<ctime>
using namespace std;
#define taskname "antiqs"
int main()
{
freopen(taskname".in", "r", stdin);
freopen(taskname".out", "w", stdout);
int n;
cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++)
a[i] = i + 1;
for(int i = 2; i < n; i++)
swap(a[i], a[i / 2]);
for(int i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
} | true |
e4cbbc984e6343aac8798f26670c9fcfbd3e98c0 | C++ | rcallan/csv_tools | /tools/statistics/statistics.cpp | UTF-8 | 983 | 2.859375 | 3 | [] | no_license | //
// csvstatistics.cpp
//
#include "CsvOperations.h"
#include "StringOperations.h"
#include "parameters.h"
void showHelp()
{
std::cout << "usage- csvstatistics [--path <path>] [--columns COLUMNS] [--other_stat OTHERSTATISTIC]\n"
"optional arguments\n--other_stat - provides desired information about the columns instead of"
" default statistics. available arguments are standard_deviation, correlation_coefficient, "
"and none (default)\n\n"
"The csvstatistics tool shows some statistics about specified columns of a csv file.\n";
}
int main(int argc, char** argv)
{
parameters::ParameterSet pset = parameters::parse_arguments(argc, argv);
if (pset.showHelp == true)
{
showHelp();
return 0;
}
parameters::verify_parameters(pset);
CsvFile::Ptr csvFile(CsvFile::read_data(pset.filePath));
csvFile->printSize("input data");
csv_operations::show_multiple_column_stats(*csvFile, pset.colsToUse, pset.otherStat);
return 0;
}
| true |
aedab97f211f94fd13a54b307b861b8b88be3b7a | C++ | lukeulrich/alignshop-qt | /src/app/gui/models/AbstractBaseTreeModel.h | UTF-8 | 6,885 | 2.890625 | 3 | [] | no_license | /****************************************************************************
**
** Copyright (C) 2011 Agile Genomics, LLC
** All rights reserved.
** Author: Luke Ulrich
**
****************************************************************************/
#ifndef ABSTRACTBASETREEMODEL_H
#define ABSTRACTBASETREEMODEL_H
#include <QtCore/QAbstractItemModel>
#include "../../core/global.h"
#include "../../core/macros.h"
#include <QtDebug>
/**
* AbstractBaseTreeModel provides a basic implementation of some of the key methods required for modeling tree
* structures composed of TreeNode.
*
* Specifically, this includes the following:
* -- Reimplemented public methods
* o index
* o parent
* o removeRows
* o rowCount
*
* -- Helper public methods
* o indexFromNode
* o nodeFromIndex
*
* While the root_ data member is defined and initialized (to null) in this class, allocation and deallocation is the
* responsibility of subclasses.
*/
template<typename TreeNodeT>
class AbstractBaseTreeModel : public QAbstractItemModel
{
public:
// ------------------------------------------------------------------------------------------------
// Constructor
AbstractBaseTreeModel(QObject *parent = nullptr);
// ------------------------------------------------------------------------------------------------
// Reimplmented public methods
virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
virtual QModelIndex parent(const QModelIndex &child) const;
virtual bool removeRows(int row, int count, const QModelIndex &parent);
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
// ------------------------------------------------------------------------------------------------
// Helper methods
QModelIndex indexFromNode(TreeNodeT *treeNode, int column = 0) const;
QModelIndex indexFromNode(const TreeNodeT *treeNode, int column = 0) const;
TreeNodeT *nodeFromIndex(const QModelIndex &index) const;
protected:
TreeNodeT *root_;
};
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// Constructor
/**
* @param parent [QObject *]
*/
template<typename TreeNodeT>
inline
AbstractBaseTreeModel<TreeNodeT>::AbstractBaseTreeModel(QObject *parent)
: QAbstractItemModel(parent),
root_(nullptr)
{
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// Public methods
/**
* @param row [int]
* @param column [int]
* @param parent [const QModelIndex &]
* @returns QModelIndex
*/
template<typename TreeNodeT>
inline
QModelIndex AbstractBaseTreeModel<TreeNodeT>::index(int row, int column, const QModelIndex &parent) const
{
TreeNodeT *parentTreeNode = nodeFromIndex(parent);
if (parentTreeNode == nullptr)
return QModelIndex();
// Check for valid row and column values
if (row < 0 ||
row >= parentTreeNode->childCount() ||
column < 0 ||
column >= columnCount(parent))
{
return QModelIndex();
}
return createIndex(row, column, parentTreeNode->childAt(row));
}
/**
* @param child [const QModelIndex &]
* @returns QModelIndex
*/
template<typename TreeNodeT>
inline
QModelIndex AbstractBaseTreeModel<TreeNodeT>::parent(const QModelIndex &child) const
{
TreeNodeT *childNode = nodeFromIndex(child);
if (childNode == nullptr)
return QModelIndex();
TreeNodeT *parentNode = childNode->parent();
if (parentNode == root_ || parentNode == nullptr)
return QModelIndex();
if (parentNode->parent() == nullptr)
return QModelIndex();
return createIndex(parentNode->row(), 0, parentNode);
}
/**
* @param row [int]
* @param count [int]
* @param parent [const QModelIndex &]
* @returns bool
*/
template<typename TreeNodeT>
inline
bool AbstractBaseTreeModel<TreeNodeT>::removeRows(int row, int count, const QModelIndex &parent)
{
if (count < 0)
return false;
TreeNodeT *parentNode = nodeFromIndex(parent);
if (parentNode == nullptr)
return false;
ASSERT(row >= 0 && row < parentNode->childCount());
ASSERT(row + count <= parentNode->childCount());
if (count == 0)
return true;
beginRemoveRows(parent, row, row + count - 1);
parentNode->removeChildren(row, count);
endRemoveRows();
return true;
}
/**
* @param parent [const QModelIndex &]
* @returns int
*/
template<typename TreeNodeT>
inline
int AbstractBaseTreeModel<TreeNodeT>::rowCount(const QModelIndex &parent) const
{
TreeNodeT *parentNode = nodeFromIndex(parent);
if (parentNode != nullptr)
return parentNode->childCount();
return 0;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// Helper methods
/**
* @param treeNode [TreeNode<TreeNodeT> *]
* @param column [int]
* @returns QModelIndex
*/
template<typename TreeNodeT>
inline
QModelIndex AbstractBaseTreeModel<TreeNodeT>::indexFromNode(TreeNodeT *treeNode, int column) const
{
// Good debug check, although invalid index is returned in release mode
ASSERT(treeNode == nullptr || treeNode == root_ || treeNode->isDescendantOf(root_));
if (treeNode == nullptr || treeNode == root_ || !treeNode->isDescendantOf(root_))
return QModelIndex();
if (column != 0)
{
// Check the column
QModelIndex parentIndex = createIndex(treeNode->parent()->row(), 0, treeNode->parent());
if (column < 0 || column >= columnCount(parentIndex))
return QModelIndex();
}
return createIndex(treeNode->row(), column, treeNode);
}
/**
* @param treeNode [const TreeNode<TreeNodeT> *]
* @param column [int]
* @returns QModelIndex
*/
template<typename TreeNodeT>
inline
QModelIndex AbstractBaseTreeModel<TreeNodeT>::indexFromNode(const TreeNodeT *treeNode, int column) const
{
return indexFromNode(const_cast<TreeNodeT *>(treeNode), column);
}
/**
* @param index [const QModelIndex &]
* @returns AdocTreeNode *
*/
template<typename TreeNodeT>
inline
TreeNodeT *AbstractBaseTreeModel<TreeNodeT>::nodeFromIndex(const QModelIndex &index) const
{
if (index.isValid())
{
if (index.model() != this)
{
qDebug() << Q_FUNC_INFO << "Wrong index passed to model";
return nullptr;
}
return static_cast<TreeNodeT *>(index.internalPointer());
}
return root_;
}
#endif // ABSTRACTBASETREEMODEL_H
| true |
4354dba8e23e93b6f15e29d68b9f5ce919b20415 | C++ | dragon-web/review_cpp | /leetcode_9_14/leetcode_9_14/day_9_14.cpp | GB18030 | 1,523 | 3.3125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<math.h>
using namespace std;
/*
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if (rotateArray.size() == 0) return 0;
int first = 0, last = rotateArray.size() - 1;
while (first < last) { // ʣһԪأΪ
if (rotateArray[first] < rotateArray[last]) { // ǰ˳
return rotateArray[first];
}
int mid = first + ((last - first) >> 1);
if (rotateArray[mid] > rotateArray[last]) { // 1
first = mid + 1;
}
else if (rotateArray[mid] < rotateArray[last]) { //2
last = mid;
}
else { // 3
--last;
}
}
return rotateArray[first];
}
};
*/
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> array, int sum) {
vector<int> res(0);
int mul = array[0] *array[0];
if (array.size())
{
for (int i = 0; i < array.size(); ++i)
{
for (int j = 0; j < array.size(); ++j)
{
if (i != j && array[i] + array[j] == sum)
{
if (array[i] * array[j] < mul)
{
mul = array[i] * array[j];
res.resize(2);
res[0] = array[i] > array[j] ? array[j] : array[i];
res[1] = array[i] < array[j] ? array[j] : array[i];
}
}
}
}
if (res.size() == 2)
return res;
}
return res;
}
};
int main()
{
vector<int>dp = { 1,2,4,7,11,15 };
int sz = 15;
Solution a;
a.FindNumbersWithSum(dp, sz);
system("pause");
return 0;
} | true |
e7543c80734ae9e20b3857b92f12251bed0109ff | C++ | melnikos/navilation | /Util/include/math_util.h | UTF-8 | 929 | 2.8125 | 3 | [] | no_license | //
// Created by sigi on 12.06.19.
//
#ifndef EPIPHANY_UMATH_H
#define EPIPHANY_UMATH_H
namespace U {
namespace Math{
/**
* converts degrees to radiant
* @param degrees unit as degrees
* @return converted value
*/
double d2r(double degrees);
double r2d(double radiant);
/**
* sinus as a function of degrees
* @param degrees
* @return sinus value of the given parameter
*/
double sind(double degrees);
/**
* cosinus as a function of degrees
* @param degrees
* @return cosinus value of the given parameter
*/
double cosd(double degrees);
double tand(double degrees);
double atand(double relation);
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
}
}
#endif //EPIPHANY_UMATH_H
| true |
4d27f9a54e69a5553d2a5e935b1804023a4fb152 | C++ | Ashe/4D-Geometry-Viewer | /src/Viewer.h | UTF-8 | 2,456 | 2.71875 | 3 | [
"MIT"
] | permissive | // Viewer.h
// A scene used to view geometry
#ifndef EDITOR_H
#define EDITOR_H
#include <math.h>
#include <memory>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <glm/matrix.hpp>
#include "Scene.h"
#include "Camera.h"
#include "Camera4D.h"
#include "Shader.h"
#include "shaders/Vertex.h"
#include "shaders/Fragment.h"
#include "polytopes/Simplex.h"
#include "polytopes/Hypercube.h"
#include "polytopes/Hyperoctahedron.h"
namespace App {
// A scene with the ability to view geomery
class Viewer : public Scene {
public:
// Constructor
Viewer(Engine& e);
// Alter the speed of the camera
void handleMouseScrollInput(double x, double y) override;
// Handle keyboard input for keybindings
void handleKeyboardInput(
int key, int scan, int action, int mods) override;
// Update the viewer
void update(double dt) override;
// Render geometry
void render() override;
// Grant the viewer access to imgui
void handleImgui() override;
private:
// Shader to use
Shader shader;
// Current object to render
Polytope* polytope;
// Polytopes to choose from
Simplex simplex;
Hypercube hypercube;
Hyperoctahedron hyperoctahedron;
// The camera for viewing the world
Camera camera;
Camera4D camera4D;
float standardCameraSpeed = Camera::SPEED;
float alternateCameraSpeed = Camera::SPEED * 5;
float* cameraSpeed = &standardCameraSpeed;
float fieldOfVision = 45.f;
float viewDistance = 150.f;
// Toggleable editor windows and features
bool showWireframe = false;
bool show3DCameraWindow = true;
bool show4DCameraWindow = true;
bool showTransformWindow = true;
bool showPolytopeInfoWindow = true;
bool showDemoWindow = false;
// Rotation helpers
bool spinFirstRotation = false;
float firstRotationAngle = 0.f;
float firstRotationSpeed = 1.f;
float firstRotationOffset = 0.f;
bool spinSecondRotation = false;
float secondRotationAngle = 0.f;
float secondRotationSpeed = 1.f;
float secondRotationOffset = 0.f;
// Create rotation widget for imgui
static void tweakRotation(float& angle, bool& spin, float& base,
float& offset, float& speed);
// Place camera back into a normal position
void resetCameraPosition();
};
}
#endif
| true |
12b8b4672a1d8bf0d1b2262e978db43453e58621 | C++ | Jason-Addison/MicBoard | /Soundboard/Texture.h | UTF-8 | 300 | 2.546875 | 3 | [] | no_license | #pragma once
#include "GL\glew.h"
#include "GLFW\glfw3.h"
#include <string>
class Texture
{
public:
Texture();
Texture(GLuint texture, int width, int height);
~Texture();
GLuint texture;
int width;
int height;
std::string name;
GLuint getTexture();
int getWidth();
int getHeight();
};
| true |
0a6f9892476415bd0120478bb76b60400645486c | C++ | ddolzhenko/training_algos_2016_05 | /akozoriz/components/include/search.h | UTF-8 | 1,414 | 2.6875 | 3 | [] | no_license | #include <vector>
typedef std::vector<int> IntVector;
namespace components {
namespace search {
namespace linear {
int linear_search_1(IntVector& Array, const int key);
int linear_search_2(IntVector& Array, const int key);
int linear_search_3(IntVector& Array, const int key);
int linear_search_4(IntVector& Array, const int key);
} // namespace linear
namespace binary {
IntVector::iterator binary_search_1(IntVector::iterator begin_itt,
IntVector::iterator end_itt,
const int key);
IntVector::iterator binary_search_2(IntVector::iterator begin_itt,
IntVector::iterator end_itt,
const int key);
IntVector::iterator binary_search_3(IntVector::iterator begin_itt,
IntVector::iterator end_itt,
const int key);
IntVector::iterator upper_bound(IntVector::iterator begin_itt,
IntVector::iterator end_itt,
const int key);
IntVector::iterator lower_bound(IntVector::iterator begin_itt,
IntVector::iterator end_itt,
const int key);
int binary_to_linear_adaptor(IntVector& vec, const int find_key);
} // namespace binary
} // namespace search
} // namespace components
| true |
99006b0e7ddb2bce342e86124ffa08cdf0f50e2f | C++ | Mortano/PnDC | /PnDC/main.cpp | UTF-8 | 3,715 | 2.96875 | 3 | [] | no_license |
#include "Sorting.h"
#include "ParallelUtil.h"
#include <vector>
#include <random>
#include <numeric>
#include <iostream>
#include <numeric>
#include <chrono>
#include "RuntimeMeasurement.h"
auto RandomNumbers(size_t count)
{
static std::random_device s_rnd;
static std::uniform_int_distribution<size_t> s_distr(0, 1000);
std::vector<size_t> ret(count, 0);
std::generate(ret.begin(), ret.end(), [&]() { return s_distr(s_rnd); });
return ret;
}
template<typename T>
std::ostream& operator<<(std::ostream& stream, const std::vector<T>& vec)
{
stream << "[";
for(size_t idx = 0; idx < vec.size(); idx++)
{
if(idx != vec.size() - 1)
{
stream << vec[idx] << ", ";
}
else
{
stream << vec[idx];
}
}
stream << "]";
stream.flush();
return stream;
}
std::ostream& operator<<(std::ostream& stream, const rt::RuntimeStats& stats)
{
stream << "\tAvg.: [" << std::chrono::duration_cast<std::chrono::milliseconds>(stats._average).count() << " ms]\n";
stream << "\tWorst: [" << std::chrono::duration_cast<std::chrono::milliseconds>(stats._worst).count() << " ms]\n";
stream << "\tBest: [" << std::chrono::duration_cast<std::chrono::milliseconds>(stats._best).count() << " ms]\n";
stream << "\tCold cache time: [" << std::chrono::duration_cast<std::chrono::milliseconds>(stats._coldCacheTime).count() << " ms]\n";
stream.flush();
return stream;
}
size_t ParallelSum(const std::vector<size_t>& numbers)
{
return ParallelDivideAndConquer(
numbers, 8,
[](const std::vector<size_t>& vec, size_t chunks)
{
using Iter_t = decltype(vec.begin());
_ASSERT(chunks > 1);
auto elementsPerChunk = vec.size() / chunks;
std::vector<std::pair<Iter_t, Iter_t>> ret;
ret.reserve(chunks);
for(size_t idx = 0; idx < chunks - 1; idx++)
{
ret.push_back(std::make_pair(vec.begin() + (idx*elementsPerChunk), vec.begin() + ((idx + 1) * elementsPerChunk)));
}
ret.push_back(std::make_pair(vec.begin() + (chunks - 1)*elementsPerChunk, vec.end()));
return ret;
},
[](auto l, auto r) { return l + r; },
[](auto elem) { return std::accumulate(elem.first, elem.second, size_t{ 0 }); });
}
int main(int argc, char** argv)
{
constexpr size_t NumberCount = 1'000'000;
constexpr size_t Iterations = 500;
std::vector<std::vector<size_t>> rndNumbers;
std::generate_n(std::back_inserter(rndNumbers), Iterations, [=]() { return RandomNumbers(NumberCount); });
task::Initialize();
//auto sequentialSortStas = rt::CollectRuntimeStats([](auto& numbers)
// {
// SequentialSort(numbers.begin(), numbers.end());
// },
// [=]() { return RandomNumbers(NumberCount); },
// Iterations);
//auto parallelSortStats = rt::CollectRuntimeStats([&](auto& numbers)
// {
// ParallelSort<8>(numbers.begin(), numbers.end());
// },
// [=]() { return RandomNumbers(NumberCount); },
// Iterations);
auto taskSystemParallelSortStats = rt::CollectRuntimeStats([&](auto& numbers)
{
TaskSystemParallelSort(numbers.begin(), numbers.end());
},
[&]() mutable { auto ret = std::move(rndNumbers.back()); rndNumbers.pop_back(); return ret; },
Iterations);
//std::cout << "######## Sequential sort stats ########\n";
//std::cout << sequentialSortStas;
//std::cout << "######## Parallel sort stats ########\n";
//std::cout << parallelSortStats;
std::cout << "######## Parallel sort with task system stats ########\n";
std::cout << taskSystemParallelSortStats;
task::Shutdown();
getchar();
return 0;
} | true |
a66b0a22bd3bbc34c7486301769ec98f910ca9df | C++ | PPTGamer/cs171-project | /gameobj/AnimatedSprite.h | UTF-8 | 487 | 2.59375 | 3 | [] | no_license | #ifndef ANIMATEDSPRITE_H
#define ANIMATEDSPRITE_H
#include <SFML/Graphics.hpp>
class AnimatedSprite : public sf::Sprite
{
int animationFrame;
int animationNumber;
int maxFrame;
int width;
int height;
void refreshFrame();
public:
AnimatedSprite(int width=64, int height=64);
void setAnimationLength(int frames);
void setAnimationNumber(int number);
void setSize(int width, int height);
void setFrame(int frameNumber);
void advanceFrame(int offset);
int getFrame();
};
#endif | true |
315f4b8d6e8da3f7ad6621885fe0a2c63ff5e0f5 | C++ | Ckiddo/ACMproblemsove | /ThePreliminaryContestForICPCAsiaShenYang2019/F.cpp | UTF-8 | 4,837 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
int n,k;
int a[500002];
int maxa[500002];
int mina[500002];
int _range[22][2];
int _rangeLength;
void solve();
void input(){
while(scanf("%d %d",&n, &k) != -1){
for(int i = 0;i < n;i++){
scanf("%d", &a[i]);
}
std::fill(maxa,maxa+n,-1);
std::fill(mina,mina+n,1000000001);
solve();
}
}
void updateMin(int i){
int left = 0;
int range = n;
int pos = i;
int posFather;
int upbound = 2 * n + 1;
int sonNum = a[i/2*2];
int sonNum2;
if(i/2*2 + 1 < n){
sonNum2 = a[i/2*2 + 1];
}else{
sonNum2 = 1000000001;
}
while(range > 1){
// printf("min:%d %d %d\n", pos, sonNum, sonNum2);
posFather = (pos - left) / 2 + left + range;
mina[posFather - n] = std::min(sonNum, sonNum2);
pos = posFather;
left = left + range;
if(range == 1){
range = 0;
}
range = (range + 1) / 2;
sonNum = mina[(pos - left) / 2 * 2 + left - n];
if((pos - left) / 2 * 2 + 1 + left < left + range){
sonNum2 = mina[(pos - left) / 2 * 2 + 1 + left - n];
}else{
sonNum2 = 1000000001;
}
}
}
void updateMax(int i){
int left = 0;
int range = n;
int pos = i;
int posFather;
int upbound = 2 * n + 1;
int sonNum = a[i/2*2];
int sonNum2;
if(i/2*2 + 1 < n){
sonNum2 = a[i/2*2 + 1];
}else{
sonNum2 = -1;
}
while(range > 1){
// printf("max:%d %d %d\n", pos, sonNum, sonNum2);
posFather = (pos - left) / 2 + left + range;
maxa[posFather - n] = std::max(sonNum, sonNum2);
pos = posFather;
left = left + range;
if(range == 1){
range = 0;
}
range = (range + 1) / 2;
sonNum = maxa[(pos - left) / 2 * 2 + left - n];
if((pos - left) / 2 * 2 + 1 + left < left + range){
sonNum2 = maxa[(pos - left) / 2 * 2 + 1 + left - n];
}else{
sonNum2 = -1;
}
}
}
void showmin(){
printf("min:\n");
for(int i = 0;i < n;i++){
printf("%d\t", a[i]);
}
printf("\n");
int left = n;
int range = (n+1)/2;
int upbound = 2 * n + 1;
while(range > 0){
for(int i = 0;i < range;i++){
printf("%d\t", mina[left + i - n]);
}
printf("\n");
left = left + range;
if(range == 1){
range = 0;
}
range = (range + 1) / 2;
}
}
void showmax(){
printf("max:\n");
for(int i = 0;i < n;i++){
printf("%d\t", a[i]);
}
printf("\n");
int left = n;
int range = (n+1)/2;
int upbound = 2 * n + 1;
while(range > 0){
for(int i = 0;i < range;i++){
printf("%d\t", maxa[left + i - n]);
}
printf("\n");
left = left + range;
if(range == 1){
range = 0;
}
range = (range + 1) / 2;
}
}
void recordRange(){
int left = 0;
int range = n;
int upbound = 2 * n + 1;
_rangeLength = 0;
while(range > 0){
_range[_rangeLength][0] = left;
_range[_rangeLength][1] = range;
_rangeLength++;
left = left + range;
if(range == 1){
range = 0;
}
range = (range + 1) / 2;
}
}
int findMinPos(){
int posFather = _range[_rangeLength-1][0];
int leftSon, rightSon;
int minner;
int i;
for(i = _rangeLength-1;i >= 2;i--){
leftSon = (posFather - _range[i][0]) * 2 + _range[i-1][0];
minner = leftSon;
rightSon = (posFather - _range[i][0]) * 2 + 1 + _range[i-1][0];
if(rightSon < _range[i-1][0] + _range[i-1][1] && mina[rightSon - n] < mina[leftSon - n]){
minner = rightSon;
}
posFather = minner;
}
leftSon = (posFather - _range[i][0]) * 2 + _range[i-1][0];
minner = leftSon;
rightSon = (posFather - _range[i][0]) * 2 + 1 + _range[i-1][0];
if(rightSon < _range[i-1][0] + _range[i-1][1] && a[rightSon] < a[leftSon]){
minner = rightSon;
}
return minner;
}
int findMaxPos(){
int posFather = _range[_rangeLength-1][0];
int leftSon, rightSon;
int maxer;
int i;
for(i = _rangeLength-1;i >= 2;i--){
leftSon = (posFather - _range[i][0]) * 2 + _range[i-1][0];
maxer = leftSon;
rightSon = (posFather - _range[i][0]) * 2 + 1 + _range[i-1][0];
if(rightSon < _range[i-1][0] + _range[i-1][1] && maxa[rightSon - n] > maxa[leftSon - n]){
maxer = rightSon;
}
posFather = maxer;
}
leftSon = (posFather - _range[i][0]) * 2 + _range[i-1][0];
maxer = leftSon;
rightSon = (posFather - _range[i][0]) * 2 + 1 + _range[i-1][0];
if(rightSon < _range[i-1][0] + _range[i-1][1] && a[rightSon] > a[leftSon]){
maxer = rightSon;
}
return maxer;
}
void showa(){
printf("a:\n");
for(int i = 0;i < n;i++){
printf("%d\t", a[i]);
}
printf("\n");
}
void solve(){
for(int i = 0;i < n;i++){
updateMin(i);
updateMax(i);
}
int pos;
recordRange();
for(int i = 0;i < k;i++){
pos = findMaxPos();
// printf("maxpos: %d\n", pos);
a[pos]--;
updateMax(pos);
updateMin(pos);
pos = findMinPos();
// printf("minpos: %d\n", pos);
a[pos]++;
updateMax(pos);
updateMin(pos);
// showmin();
// showmax();
}
// showmin();
// showmax();
printf("%d\n", maxa[_range[_rangeLength-1][0] - n] - mina[_range[_rangeLength-1][0] - n]);
}
int main(){
input();
// solve();
} | true |
2f032d5909ff907e756d7524b73b44acfd5e2d1a | C++ | TzashiNorpu/Algorithm | /Clion/ZeroTrac/1500_1600/validTicTacToe_794.cpp | UTF-8 | 1,080 | 2.734375 | 3 | [
"MIT"
] | permissive | //
// Created by TzashiNorpu on 7/13/2022.
//
#include "../header/1500_1600.h"
using namespace ZeroTrac;
bool validTicTacToe_794::validTicTacToe(vector<string> &board) {
int turns = 0;
bool xwin = false, owin = false;
vector<int> rows(3, 0), cols(3, 0);
int pie = 0, na = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == 'X') {
turns++;
rows[i]++;
cols[j]++;
if (i == j) na++;
if (i + j == 2) pie++;
} else if (board[i][j] == 'O') {
turns--;
rows[i]--;
cols[j]--;
if (i == j) na--;
if (i + j == 2) pie--;
}
}
}
xwin = rows[0] == 3 || rows[1] == 3 || rows[2] == 3 ||
cols[0] == 3 || cols[1] == 3 || cols[2] == 3 ||
pie == 3 || na == 3;
owin = rows[0] == -3 || rows[1] == -3 || rows[2] == -3 ||
cols[0] == -3 || cols[1] == -3 || cols[2] == -3 ||
pie == -3 || na == -3;
if (xwin && turns == 0 || owin && turns == 1) return false;
return (turns == 0 || turns == 1) && (!xwin || !owin);
} | true |
42ff4002e72c2f55a4b32b2b2be957caca34a26b | C++ | Skuaka/BackpackManager | /ItemBar.cpp | UTF-8 | 3,692 | 2.875 | 3 | [] | no_license | //
// Created by 苏嘉凯 on 2019-04-29.
//
#include "ItemBar.h"
std::mutex ItemBar::__m_instance_mutex;
ItemBar* ItemBar::__m_pInstance;
ItemBar &ItemBar::GetInstance() {
if(!__m_pInstance)
{
std::unique_lock<std::mutex> lk(__m_instance_mutex);
if (!__m_pInstance) {
__m_pInstance = new ItemBar;
}
}
return *__m_pInstance;
}
ItemBar::ItemBar() :
StorageRoom(BAR_CAPACITY)
{
__m_order_vec.resize(_m_capacity);
for(int i=0; i<_m_capacity; ++i){
__m_order_vec[i] = i;
}
}
std::pair<Item, uint16_t>
ItemBar::SqueezeItem(const Item &item, uint16_t num) {
return SqueezeItem(std::move(Item(item)), num);
}
// todo: 移动未优化
std::pair<Item, uint16_t>
ItemBar::SqueezeItem(Item &&item, uint16_t num) {
// 为了偷懒和方便调试,直接调用父类函数,但是
// 因为下面还需要用到item,所以不能移动item。
int ret = StorageRoom::_AddItem(item, num);
// 物品栏满了,需要置换
if( ret == E_ROOM_FULL){
int i_to_chg = __m_order_vec[_m_capacity-1];
std::pair<Item, uint16_t> ret_info(std::move(GetItemInfo(i_to_chg)));
_m_cell_vec[i_to_chg].m_item = std::move(item);
_m_cell_vec[i_to_chg].m_num = num;
for(int i=_m_capacity-1; i>=1; --i){
__m_order_vec[i] = __m_order_vec[i-1];
}
__m_order_vec[0] = i_to_chg;
return std::move(ret_info);
}
return std::move(
std::pair<Item, uint16_t >(
Item(ret, std::string{}, Item::Property{}, nullptr),
0 ));
}
int ItemBar::AddItem(const Item &item, uint16_t num) {
return AddItem(std::move(Item(item)), num);
}
int ItemBar::AddItem(Item &&item, uint16_t num) {
int pos = StorageRoom::_AddItem(std::move(item), num);
if(pos >= 0) {
__ToFirst(pos);
}
return pos;
}
int
ItemBar::AddItem(int pos, const Item &item, uint16_t num) {
return AddItem(pos, std::move(Item(item)), num);
}
int
ItemBar::AddItem(int pos, Item &&item, uint16_t num) {
int ret = StorageRoom::_AddItem(pos, std::move(item), num);
if(ret >= 0) {
__ToFirst(pos);
}
return ret;
}
int
ItemBar::DelItem(int pos, uint16_t num) {
return StorageRoom::_DelItem(pos, num);
}
Item
ItemBar::GetItem(int pos) const {
return StorageRoom::_GetItem(pos);
}
uint16_t
ItemBar::GetItemNum(int pos) const {
return StorageRoom::_GetItemNum(pos);
}
std::pair<Item, uint16_t>
ItemBar::GetItemInfo(int pos) const {
return std::move(StorageRoom::_GetItemInfo(pos));
}
int
ItemBar::UseItem(int pos) {
int ret = StorageRoom::_DelItem(pos, 1);
if(ret == 0) {
_m_cell_vec[pos].m_item.Use();
if(_m_cell_vec[pos].m_num > 0) {
__ToFirst(pos);
}
}
return ret;
}
void
ItemBar::__ToFirst(int pos) {
for (int i = _m_capacity - 1; i >= 0; --i) {
if (__m_order_vec[i] == pos) {
for (int j = i; j >= 1; --j) {
__m_order_vec[j] = __m_order_vec[j - 1];
}
__m_order_vec[0] = pos;
break;
}
}
}
void
ItemBar::ExchangeItems(int pos1, int pos2)
{
if(pos1 < 0 || pos1 > BAR_CAPACITY || pos2 < 0 || pos2 > BAR_CAPACITY)
throw std::domain_error("illegal position");
if(pos1 == pos2)
throw std::invalid_argument("The two positions must be different");
auto t = GetItemInfo(pos1);
_m_cell_vec[pos1].m_num = _m_cell_vec[pos2].m_num;
_m_cell_vec[pos1].m_item = std::move(_m_cell_vec[pos2].m_item);
_m_cell_vec[pos2].m_num = t.second;
_m_cell_vec[pos2].m_item = std::move(t.first);
}
| true |
3672606390b19b42f8805448c43d0e48235934ad | C++ | amirreza-art/Golkhone_Buali | /Golkhone/person.cpp | UTF-8 | 15,738 | 3.03125 | 3 | [] | no_license | #include "person.h"
#include <cstring>
#include <stdexcept>
Person::Person()
{
}
void Person::set_flower(Flower *ptr)
{
flowers.push_back(ptr);
}
void Person::pick_Tulip()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Tulip")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::pick_Dahlia()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Dahlia")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::pick_Tuberose()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Tuberose")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::pick_Amaryllis()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Amaryllis")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::pick_Hyacinth()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Hyacinth")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::pick_Magnolia()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Magnolia")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::pick_Lilium()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Lilium")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::pick_Orchid()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Orchid")
{
flowers.at(i)->picking();
break;
}
}
}
void Person::sel_Tulip(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Tulip")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
void Person::sel_Dahlia(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Dahlia")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
void Person::sel_Tuberose(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Tuberose")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
void Person::sel_Amaryllis(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Amaryllis")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
void Person::sel_Hyacinth(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Hyacinth")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
void Person::sel_Magnolia(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Magnolia")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
void Person::sel_Lilium(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Lilium")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
void Person::sel_Orchid(unsigned int count)
{
for (size_t i = 0; i < count; i++)
{
for (size_t j = 0; j < flowers.size(); j++)
{
if (flowers.at(j)->get_name() == "Orchid")
{
delete flowers.at(j);
flowers.erase(flowers.begin() + j);
break;
}
}
}
}
OrdinaryFlowers * Person::get_OrdinaryFlower()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Ordinary Flower")
{
OrdinaryFlowers *ptr = dynamic_cast<OrdinaryFlowers *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
OrdinaryFlowerBuds * Person::get_OrdinaryFlowerBud()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Ordinary Flower Bud")
{
OrdinaryFlowerBuds *ptr = dynamic_cast<OrdinaryFlowerBuds *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
RareFlower * Person::get_RareFlower()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Rare Flower")
{
RareFlower *ptr = dynamic_cast<RareFlower *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
RareFlowerbuds * Person::get_RareFlowerbud()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Rare Flower Bud")
{
RareFlowerbuds *ptr = dynamic_cast<RareFlowerbuds *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
OrnamentalFlower * Person::get_OrnamentalFlower()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Ornamental Flower")
{
OrnamentalFlower *ptr = dynamic_cast<OrnamentalFlower *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
OrnamentalBud * Person::get_OrnamentalBud()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Ornamental Bud")
{
OrnamentalBud *ptr = dynamic_cast<OrnamentalBud *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
OrnamentalFlowerBud * Person::get_OrnamentalFlowerBud()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Ornamental Flower Bud")
{
OrnamentalFlowerBud *ptr = dynamic_cast<OrnamentalFlowerBud *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
Dahlia * Person::get_Dahlia()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Dahlia")
{
if (Dahlia::get_dahlia_count() == 0)
{
throw std::runtime_error("you should picking Dahlia first");
}
Dahlia::dec_dahlia_count();
Dahlia *ptr = dynamic_cast<Dahlia *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Dahlia");
}
Tulip * Person::get_Tulip()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Tulip")
{
if (Dahlia::get_dahlia_count() == 0)
{
throw std::runtime_error("you should picking Tulip first");
}
Tulip::dec_tulip_count();
Tulip *ptr = dynamic_cast<Tulip *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Tulip");
}
Amaryllis * Person::get_Amaryllis()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Amaryllis")
{
if (Dahlia::get_dahlia_count() == 0)
{
throw std::runtime_error("you should picking Amaryllis first");
}
Amaryllis::dec_Amaryllis_count();
Amaryllis *ptr = dynamic_cast<Amaryllis *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Amaryllis");
}
Tuberose * Person::get_Tuberose()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Tuberose")
{
if (Dahlia::get_dahlia_count() == 0)
{
throw std::runtime_error("you should picking Tuberose first");
}
Tuberose::dec_tuberose_count();
Tuberose *ptr = dynamic_cast<Tuberose *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Tuberose");
}
Hyacinth * Person::get_Hyacinth()
{
for (size_t i = 0; i < flowers.size(); i++)
{
if (flowers.at(i)->get_name() == "Hyacinth")
{
if (Dahlia::get_dahlia_count() == 0)
{
throw std::runtime_error("you should picking Hyacinth first");
}
Hyacinth::dec_hyacinth_count();
Hyacinth *ptr = dynamic_cast<Hyacinth *>(flowers.at(i));
flowers.erase(flowers.begin() + i);
return ptr;
}
}
throw std::runtime_error("you dont have any Hyacinth");
}
MagnoliaExtract * Person::get_MagnoliaExtract()
{
if (magnoliExtracts.empty())
{
throw std::runtime_error("you dont have enough Magnolia Extract!!");
}
MagnoliaExtract *ptr = magnoliExtracts.back();
magnoliExtracts.erase(magnoliExtracts.end() - 1);
return ptr;
}
LiliumExtract * Person::get_LiliumExtract()
{
if (liliumExtracts.empty())
{
throw std::runtime_error("you dont have enough Lilium Extract!!");
}
LiliumExtract *ptr = liliumExtracts.back();
liliumExtracts.erase(liliumExtracts.end() - 1);
return ptr;
}
OrchisExtract * Person::get_OrchidExtract()
{
if (orchidExtracts.empty())
{
throw std::runtime_error("you dont have enough Orchid Extract!!");
}
OrchisExtract *ptr = orchidExtracts.back();
orchidExtracts.erase(orchidExtracts.end() - 1);
return ptr;
}
void Person::set_name(std::string s)
{
strcpy(name, s.c_str());
}
std::string Person::get_name() const
{
return std::string(name);
}
unsigned int Person::get_MagnoliaExtract_count() const
{
unsigned int temp = magnoliExtracts.size();
return temp;
}
unsigned int Person::get_LiliumExtract_count() const
{
unsigned int temp = liliumExtracts.size();
return temp;
}
unsigned int Person::get_OrchidExtract_count() const
{
unsigned int temp = orchidExtracts.size();
return temp;
}
void Person::add_MagnoliaExtract(MagnoliaExtract *exptr)
{
magnoliExtracts.push_back(exptr);
}
void Person::add_LiliumExtract(LiliumExtract *exptr)
{
liliumExtracts.push_back(exptr);
}
void Person::add_OrchidExtract(OrchisExtract *exptr)
{
orchidExtracts.push_back(exptr);
}
Soil * Person::get_Soil()
{
if (soils.empty())
{
throw std::runtime_error("you dont have enough Soil!!");
}
Soil *ptr = soils.back();
soils.erase(soils.end() - 1);
return ptr;
}
unsigned int Person::get_Soil_count() const
{
unsigned int temp = soils.size();
return temp;
}
void Person::add_Soil(Soil *sptr)
{
soils.push_back(sptr);
}
Water * Person::get_Water()
{
if (waters.empty())
{
throw std::runtime_error("you dont have enough Water!!");
}
Water *ptr = waters.back();
waters.erase(waters.end() - 1);
return ptr;
}
unsigned int Person::get_Water_count() const
{
unsigned int temp = waters.size();
return temp;
}
void Person::add_Water(Water *wptr)
{
waters.push_back(wptr);
}
SprayingMaterial * Person::get_SprayingMaterial()
{
if (sprayingMaterials.empty())
{
throw std::runtime_error("you dont have enough SprayingMaterial!!");
}
SprayingMaterial *ptr = sprayingMaterials.back();
sprayingMaterials.erase(sprayingMaterials.end() - 1);
return ptr;
}
unsigned int Person::get_SprayingMaterial_count() const
{
unsigned int temp = sprayingMaterials.size();
return temp;
}
void Person::add_SprayingMaterial(SprayingMaterial *smptr)
{
sprayingMaterials.push_back(smptr);
}
OrdinaryUnion * Person::get_OrdinaryUnion()
{
if (ordinaryUnions.empty())
{
throw std::runtime_error("you dont have enough OrdinaryUnion!!");
}
OrdinaryUnion *ptr = ordinaryUnions.back();
ordinaryUnions.erase(ordinaryUnions.end() - 1);
return ptr;
}
unsigned int Person::get_OrdinaryUnion_count() const
{
unsigned int temp = ordinaryUnions.size();
return temp;
}
void Person::add_OrdinaryUnion(OrdinaryUnion *ooptr)
{
ordinaryUnions.push_back(ooptr);
}
OrnamentalOnion * Person::get_OrnamentalOnion()
{
if (ornamentalOnions.empty())
{
throw std::runtime_error("you dont have enough OrnamentalOnion!!");
}
OrnamentalOnion *ptr = ornamentalOnions.back();
ornamentalOnions.erase(ornamentalOnions.end() - 1);
return ptr;
}
unsigned int Person::get_OrnamentalOnion_count() const
{
unsigned int temp = ornamentalOnions.size();
return temp;
}
void Person::add_OrnamentalOnion(OrnamentalOnion *ooptr)
{
ornamentalOnions.push_back(ooptr);
}
RareOnion * Person::get_RareOnion()
{
if (rareOnions.empty())
{
throw std::runtime_error("you dont have enough RareOnion!!");
}
RareOnion *ptr = rareOnions.back();
rareOnions.erase(rareOnions.end() - 1);
return ptr;
}
unsigned int Person::get_RareOnion_count() const
{
unsigned int temp = rareOnions.size();
return temp;
}
void Person::add_RareOnion(RareOnion *roptr)
{
rareOnions.push_back(roptr);
}
Person::~Person()
{
for (auto item : flowers)
{
delete item;
}
for (auto item : liliumExtracts)
{
delete item;
}
for (auto item : magnoliExtracts)
{
delete item;
}
for (auto item : orchidExtracts)
{
delete item;
}
for (auto item : soils)
{
delete item;
}
for (auto item : waters)
{
delete item;
}
for (auto item : sprayingMaterials)
{
delete item;
}
for (auto item : ordinaryUnions)
{
delete item;
}
for (auto item : ornamentalOnions)
{
delete item;
}
for (auto item : rareOnions)
{
delete item;
}
}
| true |
6f1af5ff293f6a8e210e70fbf1dd9cfed7e8fc3e | C++ | c3coding100/koi_ba | /8주차/C/8.cpp | UTF-8 | 412 | 2.890625 | 3 | [] | no_license | #include <cstdio>
void gugudan(int a,int b)
{
int i=0,j=0;
if(a > b){
i=a;
a=b;
b=i;
}
for(j=a;j <= b;j++){
printf("== %ddan ==\n",j);
for(i=1;i<=9;i++){
printf("%d * %d = %2d\n",j,i,j*i);
}
printf("\n");
}
}
int main()
{
int i=0,j=0;
scanf("%d%d",&i,&j);
gugudan(i,j);
return 0;
}
| true |
aa292b7d4dc5967e7aaab7dd91f134fd21910cd5 | C++ | 00mjk/Ventilator | /software/controller/lib/non_volatile/nv_vars.h | UTF-8 | 3,338 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | /* Copyright 2021, RespiraWorks
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.
*/
#pragma once
#include "nvparams.h"
#include "vars.h"
namespace Debug::Variable {
class NonVolatile {
public:
NonVolatile() = default;
NonVolatile(NVParams::Handler *nv_params, const uint16_t offset)
: nv_params_(nv_params), offset_(offset){};
bool linked() const { return nv_params_ != nullptr; };
void write(const void *write_buff, uint16_t len) const {
if (linked()) nv_params_->Set(offset_, write_buff, len);
};
void read(void *read_buff, uint16_t len) const {
if (linked()) nv_params_->Get(offset_, read_buff, len);
};
void link(NVParams::Handler *nv_params, const uint16_t offset) {
nv_params_ = nv_params;
offset_ = offset;
};
protected:
NVParams::Handler *nv_params_{nullptr};
uint16_t offset_{0};
};
template <size_t N>
class NVFloatArray : public FloatArray<N>, public NonVolatile {
public:
NVFloatArray(const char *name, Access access, NVParams::Handler *nv_params, const uint16_t offset,
const char *units = "", const char *help = "", const char *fmt = "%.3f")
: FloatArray<N>(name, access, units, help, fmt), NonVolatile(nv_params, offset) {
float nv_data[N] = {0.0f};
read(&nv_data, 4 * N);
FloatArray<N>::deserialize_value(&nv_data);
}
NVFloatArray(const char *name, Access access, const char *units = "", const char *help = "",
const char *fmt = "%.3f")
: FloatArray<N>(name, access, units, help, fmt){};
NVFloatArray(const char *name, Access access, float initial_fill, const char *units = "",
const char *help = "", const char *fmt = "%.3f")
: FloatArray<N>(name, access, initial_fill, units, help, fmt){};
NVFloatArray(const char *name, Access access, std::array<float, N> initial,
const char *units = "", const char *help = "", const char *fmt = "%.3f")
: FloatArray<N>(name, access, initial, units, help, fmt){};
void deserialize_value(const void *write_buff) override {
FloatArray<N>::deserialize_value(write_buff);
// write checks that the var is linked, no need to check it here as well
write(write_buff, 4 * N);
}
void set_data(const size_t index, const float value) override {
FloatArray<N>::set_data(index, value);
if (linked()) {
nv_params_->Set(static_cast<uint16_t>(offset_ + index * 4), &value, 4);
}
}
void fill(float value) override {
FloatArray<N>::fill(value);
uint8_t write_buff[4 * N];
FloatArray<N>::serialize_value(&write_buff);
write(write_buff, 4 * N);
}
void link(NVParams::Handler *nv_params, const uint16_t offset) {
NonVolatile::link(nv_params, offset);
float nv_data[N] = {0.0f};
read(&nv_data, 4 * N);
FloatArray<N>::deserialize_value(&nv_data);
};
};
}; // namespace Debug::Variable
| true |
fba8769a21ffcb0f35f1bd830cd63002ceb9140f | C++ | riddhi2000/Competitive-programming | /interviewbit/substring-concatenation.cpp | UTF-8 | 1,082 | 2.953125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<int> findSubstring(string A, const vector<string> &B) {
vector<int> ans;
int n=B.size();
int count=0;
for(int i=0;i<A.length();i++){
vector<int> index(n,0);
count=0;
int j=0;
int e,s=i;
int f=0;
while(count < n && f<=n){
e=B[j].length();
if(A.substr(s,e) == B[j]){
if(index[j] == 0){
count++;
s=s+e;
index[j]=1;
f=0;
}
else{
break;
}
}
f++;
j=(j+1)%n;
}
if(count == n){
ans.push_back(i);
}
}
return ans;
}
int main(int argc, char const *argv[])
{
vector<string> s;
s.push_back("foo");
s.push_back("bar");
vector<int> v=findSubstring("barfoothefoobarman",s);
for(int i=0;i<v.size();i++)
cout << v[i] << " ";
cout << endl;
return 0;
}
| true |
70845bda2ca5f471e513b3d917f3a216fa09d29e | C++ | atulRanaa/problem-solving-directory | /Problem Solving/Tries_maxXor.cpp | UTF-8 | 1,287 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll long long
using namespace std;
struct Node{
int value;
Node *ar[2];
Node(){value=0, ar[0]=ar[1]= NULL;}
};
ll pow2[33];
void powof2(){
pow2[0]=1;
for(int i=0;i<33;i++) pow2[i] = (pow2[i-1]+pow2[i-1]);
}
void insert(Node *head, int n){
Node *t = head;
for(int i=20; i>=0; i--){
bool val = n&pow2[i];
if(t->ar[val] == NULL) t->ar[val]= new Node;
t = t->ar[val];
}
t->value = n;
}
int query(Node *head, int n){
Node *t = head;
for(int i=20; i>=0; i--){
bool val = n&pow2[i];
if(t->ar[1-val] != NULL) t= t->ar[1-val];
else if(t->ar[val] != NULL) t=t->ar[val];
}
return n^(t->value);
}
long long dp[902];
int main(){
powof2();
int n, ans=0;
cin>>n;
int ar[n];
for(int i=0; i<n; i++) cin>>ar[i];
dp[0] = 0;
for(int i=1; i<=n; i++) dp[i] = dp[i-1]+ar[i-1];
Node* root = new Node();
insert(root, 0);
for(int i=1; i<n; i++){
insert(root, dp[i]);
for(int j=i+1; j<=n; j++){
ans = max(ans, query(root, dp[j]-dp[i]));
}
for(int j=n; j>i; j--){
ans = max(ans, query(root, dp[n]-dp[j-1]));
}
}
cout<<ans<<endl;
return 0;
}
| true |
ae4b9d8ea063971be8db10dc3b0a3d54d0024e1d | C++ | mantoniogr/imgproc_cpp | /src/morphology.cpp | UTF-8 | 14,586 | 2.984375 | 3 | [] | no_license | //
// morphology.cpp
// image_processing
//
// Created by Marco Garduño on 24/07/17.
// Copyright © 2017 Marco Garduño. All rights reserved.
//
#include <iostream>
#include <vector>
#include <opencv2/highgui/highgui.hpp>
#include "morphology.h"
#include "functions.h"
#include <queue>
cv::Mat dilation(cv::Mat image, int lambda){
cv::Mat img = image.clone();
std::vector<std::vector<int>> matrix = mat2vector(img);
for(int k = 0; k < lambda; k++){
// B1
for(int j = 0; j < image.rows; j++){
for(int i = 0; i < image.cols-1; i++){
if(matrix[j][i] < matrix[j][i+1]){
matrix[j][i] = matrix[j][i+1];
}
}
}
// B2
for(int j = 0; j < image.rows-1; j++){
for(int i = 0; i < image.cols; i++){
if(matrix[j][i] < matrix[j+1][i]){
matrix[j][i] = matrix[j+1][i];
}
}
}
// B3
for(int j = 0; j < image.rows; j++){
for(int i = image.cols - 1; i > 0; i--){
if(matrix[j][i] < matrix[j][i-1]){
matrix[j][i] = matrix[j][i-1];
}
}
}
// B4
for(int j = image.rows - 1; j > 0; j--){
for(int i = 0; i < image.cols; i++){
if(matrix[j][i] < matrix[j-1][i]){
matrix[j][i] = matrix[j-1][i];
}
}
}
}
img = vector2mat(matrix);
return img;
}
cv::Mat erosion(cv::Mat image, int lambda){
cv::Mat img = image.clone();
img = negative_gray(img);
img = dilation(img, lambda);
img = negative_gray(img);
return img;
}
cv::Mat opening(cv::Mat image, int lambda){
cv::Mat img = image.clone();
img = erosion(img, lambda);
img = dilation(img, lambda);
return img;
}
cv::Mat closing(cv::Mat image, int lambda){
cv::Mat img = image.clone();
img = dilation(img, lambda);
img = erosion(img, lambda);
return img;
}
cv::Mat sequential_1(cv::Mat image, int lambda){
cv::Mat img = image.clone();
for(int i = 0; i < lambda; i++){
img = opening(img, i+1);
img = closing(img, i+1);
}
return img;
}
cv::Mat sequential_2(cv::Mat image, int lambda){
cv::Mat img = image.clone();
for(int i = 0; i < lambda; i++){
img = closing(img, i+1);
img = opening(img, i+1);
}
return img;
}
cv::Mat white_top_hat(cv::Mat image, int lambda){
cv::Mat img_original = image.clone();
cv::Mat img = image.clone();
img = opening(img, lambda);
img = difference(img_original, img);
return img;
}
cv::Mat black_top_hat(cv::Mat image, int lambda){
cv::Mat img_original = image.clone();
cv::Mat img = image.clone();
img = closing(img, lambda);
img = difference(img, img_original);
return img;
}
cv::Mat gradient(cv::Mat image, int lambda){
cv::Mat img = image.clone();
cv::Mat img2 = image.clone();
img = dilation(img, lambda);
img2 = erosion(img2, lambda);
img = difference(img, img2);
return img;
}
cv::Mat external_gradient(cv::Mat image, int lambda){
cv::Mat img = image.clone();
cv::Mat img2 = image.clone();
img = dilation(img, lambda);
img = difference(img, img2);
return img;
}
cv::Mat internal_gradient(cv::Mat image, int lambda){
cv::Mat img = image.clone();
cv::Mat img2 = image.clone();
img = erosion(img, lambda);
img = difference(img2, img);
return img;
}
cv::Mat geodesic_dilation(cv::Mat I, cv::Mat J){
std::vector<std::vector<int>> matrix_I = mat2vector(I);
std::vector<std::vector<int>> matrix_J = mat2vector(J);
std::vector<std::vector<int>> matrix_aux = matrix_I;
std::vector <int> list_1, list_2;
cv::Mat mat_aux;
cv::Mat dif;
bool flag = true;
double maxVal;
while(flag){
matrix_aux = matrix_J;
for(int j = 1; j < I.rows; j++){
for(int i = 1; i < I.cols-1; i++){
list_1 = { matrix_J[j-1][i-1], matrix_J[j-1][i], matrix_J[j-1][i+1],
matrix_J[j][i-1], matrix_J[j][i]};
auto max_ptr_1 = std::max_element(std::begin(list_1), std::end(list_1));
matrix_J[j][i] = std::min(*max_ptr_1, matrix_I[j][i]);
}
}
for(int j = I.rows-2; j >= 0 ; j--){
for(int i = I.cols-2; i >= 1; i--){
list_2 = { matrix_J[j][i], matrix_J[j][i+1],
matrix_J[j+1][i-1], matrix_J[j+1][i], matrix_J[j+1][i+1]};
auto max_ptr_2 = std::max_element(std::begin(list_2), std::end(list_2));
matrix_J[j][i] = std::min(*max_ptr_2, matrix_I[j][i]);
}
}
J = vector2mat(matrix_J);
mat_aux = vector2mat(matrix_aux);
dif = difference(mat_aux, J);
double min, max;
cv::minMaxLoc(dif, &min, &max);
if(max == 0){
flag = false;
}
}
return J;
}
cv::Mat geodesic_erosion(cv::Mat I, cv::Mat J){
I = negative_gray(I);
J = negative_gray(J);
J = geodesic_dilation(I, J);
I = negative_gray(I);
J = negative_gray(J);
return J;
}
cv::Mat opening_by_reconstruction(cv::Mat image, int lambda){
cv::Mat mat_aux = image.clone();
cv::Mat Y = image.clone();
cv::Mat eroded = image.clone();
cv::Mat J;
Y = erosion(image, lambda);
J = geodesic_dilation(mat_aux, Y);
return J;
}
cv::Mat closing_by_reconstruction(cv::Mat image, int lambda){
cv::Mat mat_aux = image.clone();
cv::Mat Y = image.clone();
cv::Mat dilated = image.clone();
cv::Mat J;
Y = dilation(image, lambda);
J = geodesic_erosion(mat_aux, Y);
return J;
}
cv::Mat sequential_reconstruction1(cv::Mat image, int lambda){
cv::Mat mat_aux = image.clone();
for(int i = 0; i < lambda+1; i++){
mat_aux = opening_by_reconstruction(mat_aux, i);
mat_aux = closing_by_reconstruction(mat_aux, i);
}
return mat_aux;
}
cv::Mat sequential_reconstruction2(cv::Mat image, int lambda){
cv::Mat mat_aux = image.clone();
for(int i = 0; i < lambda+1; i++){
mat_aux = closing_by_reconstruction(mat_aux, i);
mat_aux = opening_by_reconstruction(mat_aux, i);
}
return mat_aux;
}
cv::Mat maxima(cv::Mat image){
cv::Mat img = image.clone();
cv::Mat mat_aux;
std::vector<std::vector<int>> matrix_aux = mat2vector(image);
for(int j = 1; j < image.rows-1; j++){
for(int i = 1; i < image.cols-1; i++){
if(matrix_aux[j][i] > 0){
matrix_aux[j][i] = matrix_aux[j][i] - 1;
}
}
}
mat_aux = vector2mat(matrix_aux);
cv::Mat geo_dil = geodesic_dilation(image, mat_aux);
cv::Mat dif = difference(image, geo_dil);
//img = threshold(dif, 1, 255);
img = threshold(dif, 1);
return img;
}
cv::Mat minima(cv::Mat image){
cv::Mat img = image.clone();
img = negative_gray(img);
img = maxima(img);
return img;
}
cv::Mat labeling(cv::Mat image, int increment){
std::vector<std::vector<int>> matrix = mat2vector(image);
cv::Mat mat_aux = image.clone();
mat_aux = borders_change(mat_aux, 0);
std::vector<std::vector<int>> matrix_aux = mat2vector(mat_aux);
std::vector<int> coords = {0,0}; // j,i
std::vector<int> primas = {0,0}; // j,i
int k = 0;
std::queue <std::vector<int>> fifo;
for(int j = 0; j < image.rows; j++){
for(int i = 0; i < image.cols; i++){
if(matrix_aux[j][i] != 0){
k += increment;
coords[0] = j;
coords[1] = i;
fifo.push(coords);
matrix_aux[j][i] = 0;
matrix[j][i] = k;
while(!fifo.empty()){
primas = fifo.front();
fifo.pop();
for(int n = primas[0]-1; n < primas[0]+2; n++){
for(int m = primas[1]-1; m < primas[1]+2; m++){
if(matrix_aux[n][m] != 0){
coords[0] = n;
coords[1] = m;
fifo.push(coords);
matrix_aux[n][m] = 0;
matrix[n][m] = k;
}
}
}
}
}
}
}
mat_aux = vector2mat(matrix);
return mat_aux;
}
cv::Mat watershed(cv::Mat image){
cv::Mat mat_aux;
cv::Mat mask = minima(image); // minimos de image
cv::Mat imwl = labeling(mask, 1); // vertientes
imwl = borders_change(imwl, 1000000);
std::vector<std::vector<int>> matrix_imwl = mat2vector(imwl); // vertientes matrix
std::vector<std::vector<int>> ime = mat2vector(image); // vertientes matrix
std::vector<std::vector<int>> ims = mat2vector(image); // watershed matrix
std::vector<std::queue<std::vector<int>>> fifoj (256);
std::vector<int> coords = {0,0}; // j,i
for(int j = 1; j < image.rows-1; j++){
for(int i = 1; i < image.cols-1; i++){
if(matrix_imwl[j][i] != 0){
int ban_ = 255;
for(int k = j-1; k < j+2; k++){
for(int l = i-1; l < i+2; l++){
ban_ = ban_ & matrix_imwl[k][l];
}
}
if(ban_ == 0){
fifoj[ime[j][i]].push({j,i});
}
}
}
}
int i = 0;
while(i != 256){
while(!fifoj[i].empty()){
coords = fifoj[i].front();
fifoj[i].pop();
for(int k = coords[0]-1; k < coords[0]+2; k++){
for(int l = coords[1]-1; l < coords[1]+2; l++){
if(matrix_imwl[k][l] == 0){
for(int n = k-1; n < k+2; n++){
for(int m = l-1; m < l+2; m++){
if( matrix_imwl[n][m] != matrix_imwl[coords[0]][coords[1]] && matrix_imwl[n][m] != 0 && matrix_imwl[n][m] != 1000000){
ims[k][l] = 255;
}
matrix_imwl[k][l] = matrix_imwl[coords[0]][coords[1]];
fifoj[ime[k][l]].push({k,l});
}
}
}
}
}
}
i++;
}
mat_aux = vector2mat(matrix_imwl);
return mat_aux;
}
cv::Mat watershed(cv::Mat image, cv::Mat marker){
cv::Mat mat_aux;
//cv::Mat mask = minima(image); // minimos de image
cv::Mat imwl = labeling(marker, 1); // vertientes
imwl = borders_change(imwl, 1000000);
std::vector<std::vector<int>> matrix_imwl = mat2vector(imwl); // vertientes matrix
std::vector<std::vector<int>> ime = mat2vector(image); // vertientes matrix
std::vector<std::vector<int>> ims = mat2vector(image); // watershed matrix
std::vector<std::queue<std::vector<int>>> fifoj (256);
std::vector<int> coords = {0,0}; // j,i
for(int j = 1; j < image.rows-1; j++){
for(int i = 1; i < image.cols-1; i++){
if(matrix_imwl[j][i] != 0){
int ban_ = 255;
for(int k = j-1; k < j+2; k++){
for(int l = i-1; l < i+2; l++){
ban_ = ban_ & matrix_imwl[k][l];
}
}
if(ban_ == 0){
fifoj[ime[j][i]].push({j,i});
}
}
}
}
int i = 0;
while(i != 256){
while(!fifoj[i].empty()){
coords = fifoj[i].front();
fifoj[i].pop();
for(int k = coords[0]-1; k < coords[0]+2; k++){
for(int l = coords[1]-1; l < coords[1]+2; l++){
if(matrix_imwl[k][l] == 0){
for(int n = k-1; n < k+2; n++){
for(int m = l-1; m < l+2; m++){
if( matrix_imwl[n][m] != matrix_imwl[coords[0]][coords[1]] && matrix_imwl[n][m] != 0 && matrix_imwl[n][m] != 1000000){
ims[k][l] = 255;
}
matrix_imwl[k][l] = matrix_imwl[coords[0]][coords[1]];
fifoj[ime[k][l]].push({k,l});
}
}
}
}
}
}
i++;
}
mat_aux = vector2mat(ims);
return mat_aux;
}
std::vector<cv::Mat> watershed(cv::Mat image, cv::Mat marker, cv::Mat dst){
std::vector<cv::Mat> w_vector;
cv::Mat mat_aux, mat_aux2;
//cv::Mat mask = minima(image); // minimos de image
cv::Mat imwl = labeling(marker, 1); // vertientes
imwl = borders_change(imwl, 0);
std::vector<std::vector<int>> matrix_imwl = mat2vector(imwl); // vertientes matrix
std::vector<std::vector<int>> ime = mat2vector(image); // vertientes matrix
std::vector<std::vector<int>> ims = mat2vector(dst); // watershed matrix
std::vector<std::queue<std::vector<int>>> fifoj (256);
std::vector<int> coords = {0,0}; // j,i
for(int j = 1; j < image.rows-1; j++){
for(int i = 1; i < image.cols-1; i++){
if(matrix_imwl[j][i] != 0){
int ban_ = 255;
for(int k = j-1; k < j+2; k++){
for(int l = i-1; l < i+2; l++){
ban_ = ban_ & matrix_imwl[k][l];
}
}
if(ban_ == 0){
fifoj[ime[j][i]].push({j,i});
}
}
}
}
int i = 0;
while(i != 256){
while(!fifoj[i].empty()){
coords = fifoj[i].front();
fifoj[i].pop();
for(int k = coords[0]-1; k < coords[0]+2; k++){
for(int l = coords[1]-1; l < coords[1]+2; l++){
if(l < image.cols && k < image.rows && l > -1 && k > -1 && matrix_imwl[k][l] == 0){
for(int n = k-1; n < k+2; n++){
for(int m = l-1; m < l+2; m++){
if(m < image.cols && n < image.rows && m > -1 && n > -1 && (matrix_imwl[n][m] != matrix_imwl[coords[0]][coords[1]]) && (matrix_imwl[n][m] != 0) && (matrix_imwl[n][m] != 1000000)){
ims[k][l] = 255;
}
matrix_imwl[k][l] = matrix_imwl[coords[0]][coords[1]];
fifoj[ime[k][l]].push({k,l});
}
}
}
}
}
}
i++;
}
mat_aux = vector2mat(ims);
mat_aux2 = vector2mat(matrix_imwl);
w_vector.push_back(mat_aux);
w_vector.push_back(mat_aux2);
return w_vector;
}
| true |
3c2185907299c37646be3fe7d5b452022988a1fa | C++ | nerds-odd-e/mahjong | /tst/DataCreationHelpers.h | UTF-8 | 2,313 | 3.234375 | 3 | [
"MIT"
] | permissive | #ifndef DATA_CREATION_HELPERS
#define DATA_CREATION_HELPERS
#include "Hand.h"
#include "Perspective.h"
class DummyUIEvent: public UIEvent {
public:
virtual ~DummyUIEvent() {
}
virtual std::string toString() {
return "";
}
};
const Tile WINNING_TILE = 10;
const Tile ANY_TILE = 8;
const Tile defaultTilesPongTheWinningTileAndChowWinningTilePlusOne[] = { WINNING_TILE, WINNING_TILE, WINNING_TILE+2, WINNING_TILE+2 };
constexpr unsigned int max_holding_count = 13;
class HandBuilder {
public:
HandBuilder(): numberOfTiles_(0){}
Hand * please() {
return createHand(tiles_, numberOfTiles_);
}
Player * dealToPlease(Player *player, int distance) {
player->deal(tiles_, numberOfTiles_, distance);
return player;
}
HandBuilder& withTiles(Tile tile) {
tiles_[numberOfTiles_++] = tile;
return *this;
}
template<typename T, typename... Args>
HandBuilder& withTiles(T tile, Args... args) {
withTiles(tile);
return withTiles(args...);
}
HandBuilder& withAPairOf(Tile tile) {
return withTiles(tile, tile);
}
HandBuilder& withPongOf(Tile tile) {
return withTiles(tile, tile, tile);
}
HandBuilder& withChowFrom(Tile tile) {
return withTiles(tile, tile+1, tile+2);
}
private:
Hand * createHand(Tile * tiles, int count) {
Hand * hand = new Hand();
hand->deal(tiles, count);
return hand;
}
private:
Tile tiles_[max_holding_count];
int numberOfTiles_;
};
class HandDataMother {
public:
Hand *createAllIrrelevantHand() {
Tile tiles[] = { 1, 4, 7, 11 };
return createHand(tiles, 4);
}
Hand * createHandWinWithTheWinningTile() {
Tile tiles[] = {WINNING_TILE};
return createHand(tiles, 1);
}
Hand *createHandPongTheWinningTile() {
Tile tiles[] = {WINNING_TILE, WINNING_TILE, WINNING_TILE + 3, WINNING_TILE + 6};
return createHand(tiles, 4);
}
Hand * createHandChowTheWinningTile() {
Tile tiles[] = {WINNING_TILE+1, WINNING_TILE+2, WINNING_TILE + 3, WINNING_TILE + 6};
return createHand(tiles, 4);
}
Hand * createHandPongAndWinTheWinningTile() {
Tile tiles[] = {WINNING_TILE, WINNING_TILE, WINNING_TILE + 2, WINNING_TILE + 2};
return createHand(tiles, 4);
}
private:
Hand * createHand(Tile * tiles, int count) {
Hand * hand = new Hand();
hand->deal(tiles, count);
return hand;
}
};
#endif | true |
f377fd6a7a0917d032d3fa1c9552d9622d586909 | C++ | codingbycoding/codingbycoding.github.io | /cpp/effective_cpp/effective.h | UTF-8 | 7,226 | 3.328125 | 3 | [] | no_license | #ifndef ADAM_EFFECTIVE_CPP_EFFECTIVE_H_
#define ADAM_EFFECTIVE_CPP_EFFECTIVE_H_
#include <iostream>
#include <cassert>
#include <new>
class AgainstDefaultCompilerGen {
private:
AgainstDefaultCompilerGen(const AgainstDefaultCompilerGen&);//on purpose only declare this to against compiler default gen ctor.
AgainstDefaultCompilerGen& operator= (const AgainstDefaultCompilerGen&);//the same as above.
};
class AbstractClass {
public:
virtual ~AbstractClass() = 0;
};
class CarSpecification {
public:
CarSpecification(float speed, float price, float weight, float length, float width, float height) :
speed_(speed),
price_(price),
weight_(weight),
length_(length),
width_(width),
height_(height) {
}
CarSpecification() :
speed_(0),
price_(0),
weight_(0),
length_(0),
width_(0),
height_(0) {
}
private:
float speed_;//the declaration order will be the init order no matter what the order it will be appreance in the inialis list.
float price_;
float weight_;
float length_;
float width_;
float height_;
};
class Car {
public:
Car() : carSpecification_() {
}
virtual ~Car() {
inner_log(); // test ctor and dtor should not call a virtual function.
}
virtual void inner_log() {
std::cout << __func__ << ":" << __LINE__ << std::endl;
}
private:
CarSpecification carSpecification_;
std::string brand_;
};
class AudiCar : public Car {
public:
~AudiCar() {
inner_log();
}
virtual void inner_log() {
std::cout << __func__ << ":" << __LINE__ << std::endl;
}
};
class BWMCar : public Car {
public:
~BWMCar() {
inner_log();
}
virtual void inner_log() {
std::cout << __func__ << ":" << __LINE__ << std::endl;
}
};
class Timeline {
public:
Timeline() {
pTag_ = new char[100];
/* pTag_ = {'T', 'i', 'm', 'e', 'l', 'i', 'n', 'e'}; */
}
~Timeline() {
delete pTag_;
pTag_ = NULL;
}
static const int innerVal = 1;//This is only a declare. class integral type(ints, bools, chars) only declare is OK. but the others are not.
static const float innerF; // = 1.1f;//This is only a declare. class integral type(ints, bools, chars) only declare is OK. but the others are not.
void print() const {
std::cout << "Timeline:" << pTag_ << std::endl;
}
char* getTag() const {
//bitFlag_ = 0;//would make compiler failed
mut_bitFlag_ = 0;//wouldn't make compiler failed
return pTag_;
}
private:
enum {EVENT_SIZE = 5};//enum hack more like #define than const because access a const's address is legal, however access a #define address is noramlly illegal. And "enmu hack" is techni base of metaprogramming.
int max_event_per_day[EVENT_SIZE];
char* pTag_;
int bitFlag_;
mutable int mut_bitFlag_;//can be modified in a const member function
};
//overuse #define example
template <typename T>
bool fun_test(const T& arg) {
std::cout << "arg:" << arg << std::endl;
}
template <typename T>
inline void callWithMax(const T& lhs, const T& rhs) {
fun_test(lhs > rhs ? lhs : rhs);
}
class Month {
private:
static Month Jan() {
Month(1);
}
static Month Feb() {
Month(2);
}
private:
explicit Month(int mon) {
}
};
class Rational {
public:
Rational(int numerator=0, int denominator=1)
: numerator_(numerator), denominator_(denominator) {
}
const Rational operator*(const Rational& rhs) const {
return Rational(numerator_ * rhs.numerator(), denominator_ * rhs.denominator());
}
const int numerator() const {
return numerator_;
}
const int denominator() const {
return denominator_;
}
private:
int numerator_;
int denominator_;
};
//if you need convert all the parameters you should make the function non-member
const Rational operator*(const Rational& lhs, const Rational& rhs);
int doSomething() throw();
class Base {
public:
explicit Base();
virtual void mf1();
virtual void mf2();
void mf3();
void mf4();
virtual void mfB();//derived class derived this interface and default behavior.
private:
};
class Derived : public Base {
public:
using Base::mf2;//make Base::mf2 available here
explicit Derived();
virtual void mf1();
virtual void mf2(int x);
void mf3();
void mf4();
private:
};
class Airport {
public:
Airport() : name_("Airport") {
}
const std::string name() const {
return name_;
}
private:
std::string name_;
};
class Airplane {
public:
virtual void fly(const Airport& dst_airport) = 0;//pure virtual method but still has its definition and it must be redefine in its derived class.
protected:
void defaultFly(const Airport& dst_airport);
};
class ModeA_Airplane : public Airplane {
public:
void fly(const Airport& dst_airport);
};
class ModeB_Airplane : public Airplane {
public:
void fly(const Airport& dst_airport);
};
class ModeC_Airplane : public Airplane {
public:
void fly(const Airport& dst_airport);
};
class Person {
public:
void sleep();
};
class Student : private Person { //what is private derived means ?
public:
void snap();
//error: ‘Person’ is an inaccessible base of ‘Student’
};
void eat(const Person& person);
void study(const Student& student);
class MultiBase {
private:
std::string name_;// must make all the direct derived class inharit virtually to avoid multi data member copy
};
class MultiA : virtual public MultiBase { //virtual derived to avoid multi data member copy of MultiBase
};
class MultiB : virtual public MultiBase { //virtual derived to avoid multi data member copy of MultiBase
};
class MultiAB {
};
template <typename C>
void printSomething(const C& c) {
typename C::const_iterator cit = c.cbegin();// if no typename keyword C::const_iterator the compiler will compilent
//typename C::const_iterator cit = c.cbegin();// if no typename keyword C::const_iterator the compiler
std::cout << "*cit:" << *cit << std::endl;
}
template<typename T>
class Calculator {
public:
template<typename Y>//use member function template to accept "all compatible types"
Calculator(const Y& rhs);
};
struct t_trait_A {
};
struct t_trait_B {
};
template<typename T>
void test_trait(const T& t, t_trait_A) {
std::cout << "t_trait_A test_trait t:" << t << std::endl;
}
template<typename T>
void test_trait(const T& t, t_trait_B) {
std::cout << "t_trait_B test_trait t:" << t << std::endl;
}
class NewHandlerHolder {
public:
NewHandlerHolder(std::new_handler nh);
~NewHandlerHolder();
private:
std::new_handler handler_;
};
class Alloc_T {
public:
void* operator new(std::size_t size) throw (std::bad_alloc);
/* void* operator new(std::size_t size); */
void* operator new(std::size_t size, std::ostream& os);
void* operator new(std::size_t size, const std::nothrow_t&) throw ();
void operator delete(void*);
static std::new_handler set_new_handler(std::new_handler p);
private:
static std::new_handler currentHandler_;
};
#endif
| true |
f964dbdb82cde5fa9172d609c05441a2500080d6 | C++ | ajayguna-96/LeetCode | /Keyboard Row.cpp | UTF-8 | 985 | 3.109375 | 3 | [] | no_license | class Solution {
public:
int FindRow (char letter , vector<string> dict){
for(int i = 0; i < dict.size() ; i++){
for( int j = 0 ; j < dict[i].length() ; j++){
if( tolower(letter) == dict[i][j]){
return i + 1;
}
}
}
return -1;
}
vector<string> findWords(vector<string>& words) {
vector<string> dict = {"qwertyuiop" , "asdfghjkl" ,"zxcvbnm"};
int num = -1;
int it = -1;
vector<string> res;
for(int i = 0 ; i < words.size() ; i++){
num = FindRow( words[i][0] , dict );
for(int j = 1 ; j < words[i].length() ; j++){
it = FindRow( words[i][j] , dict );
if(num != it){
break;
}
}
if(num == it || it == -1){
res.push_back(words[i]);
}
it = -1;
}
return res;
}
};
| true |
9b9f543aaea5da0454263dba4138b4df30c16f58 | C++ | aryabhatta22/CompetitiveCoding | /Sudo Placement GFG/Array/2_LeaderInArray/main.cpp | UTF-8 | 1,186 | 3.09375 | 3 | [] | no_license | /**************************
Description : https://practice.geeksforgeeks.org/problems/leaders-in-an-array/0/?track=sp-arrays-and-searching&batchId=152
Date : 13 Aug, 2019
**************************/
#include<iostream>
using namespace std;
int main()
{
//code
int test{0};
long int size{0}, resSize{0};
long int* arr;
long int* result;
int max{0};
cin>>test;
while(test--){
cin>>size;
arr=new long int[size];
result=new long int[size];
for(int i=0;i<size;i++)
cin>>arr[i];
max=arr[size-1];
result[resSize]=max;
resSize++;
for(int i=size-2;i>=0;i--){
if(arr[i]>=max){
max=arr[i];
result[resSize]=max;
resSize++;
}else continue;
}
for(int i=resSize-1;i>=0;i--)
cout<<result[i]<<" ";
cout<<"\n";
resSize=0;
}
return 0;
}
/* Hint: approach from left of array and store a max value, whenever left value is geater than max value
print the max value and set left value as max value. Repeat till the index 0.
*/ | true |
fa54f8b81c285c8756fff501b55366b4d6e80715 | C++ | sunbinbin1991/myfirstcode | /example/leetCode/739_daliyTemperatures.h | UTF-8 | 601 | 3.140625 | 3 | [] | no_license | #pragma once
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> dailyTemperatures(vector<int>& temperatures)
{
int n = temperatures.size();
vector<int> ans;
int len = temperatures.size();
for (int i = 0; i < len; ++i) {
int count = 0;
for (int j = i; j < len; j++) {
if (temperatures[j] > temperatures[i]) {
count++;
ans.push_back(count);
break;
}
if (j = len - 1) {
ans.push_back(0);
}
}
}
return ans;
} | true |
50a2b03c6ac14470f6356e555b77d3fae94f41ad | C++ | templeblock/Portfolio | /ASpaceGame/GameSolution/Engine/Randomness.cpp | UTF-8 | 387 | 2.90625 | 3 | [] | no_license | #include "Randomness.h"
Randomness::Randomness()
{
srand ((unsigned int)time(NULL));
}
float Randomness::randomFloat()
{
return (float) rand()/RAND_MAX;
}
Vector2D Randomness::randomUnitVector()
{
float angle = TWO_PI * randomFloat();
return Vector2D(cos(angle), sin(angle));
}
float Randomness::randomInRange(float min, float max)
{
return (randomFloat()*(max-min+1)+min);
} | true |
3122b44f277d533006ba5f2dcea3c128c7beffeb | C++ | rishav2416/ProjectEuler | /problem33-DigitCancelingFractions.cpp | UTF-8 | 680 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <set>
using namespace std;
bool checkDigitCanceling(int nom, int den){
if(nom%10==0 || den%10==0){return 0;} //trivial example;
if((nom/10) == (den/10) && (nom*(den%10)== den*(nom%10)) ){return 1;}
if((nom/10) == (den%10) && (nom*(den/10)== den*(nom%10)) ){return 1;}
if((nom%10) == (den/10) && (nom*(den%10)== den*(nom/10)) ){return 1;}
if((nom%10) == (den%10) && (nom*(den/10)== den*(nom/10)) ){return 1;}
return 0;
}
int main (int argc, char * const argv[]) {
for(int a=11;a<99;++a){for(int b=a+1;b<=99;++b){if(checkDigitCanceling(a,b)){cout<<a<<" "<<b<<endl;}}}
return 0;
}
| true |
b30e67fb2cea9b81d0062e00496b8d71ea28e530 | C++ | Ramnirmal0/Audrino-codes | /Arduino/soil classisfication/SOIL_CLASSIFICATION.ino | UTF-8 | 1,283 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | /*
MQ A4 D7
MQ3 A0 D8
SOIL A5
*/
/* MQ-3 Alcohol Sensor Circuit with Arduino */
int analog_IN = A4; // This is our input pin
const int AOUTpin = 0; //the AOUT pin of the alcohol sensor goes into analog pin A0 of the arduino
const int DOUTpin = 8; //the DOUT pin of the alcohol sensor goes into digital pin D8 of the arduino
int sensor_pin = A5;
int output_value ;
int limit;
int value;
void setup() {
Serial.begin(9600);//sets the baud rate
pinMode(DOUTpin, INPUT);//sets the pin as an input to the arduino
pinMode(analog_IN, INPUT);
}
void loop()
{
value = analogRead(AOUTpin); //reads the analaog value from the alcohol sensor's AOUT pin
limit = digitalRead(DOUTpin); //reads the digital value from the alcohol sensor's DOUT pin
Serial.print("methane contents : ");
Serial.println(value);//prints the alcohol value
delay(1000);
Serial.println("======================================");
output_value = analogRead(sensor_pin);
output_value = map(output_value, 550, 0, 0, 100);
Serial.print("soil Moisture : ");
Serial.print(output_value);
Serial.println("%");
delay(1000);
int Value1 = analogRead(analog_IN);
Serial.print("Nitrogen Gas reading : ");
Serial.println(Value1);
}
| true |
761d72db88425ae6c5718d33ea1f6e6cdea3be6a | C++ | chinagdlex/yggdrasil | /developing/yggdrasil/test/charset/const_strings_test.cpp | UTF-8 | 1,711 | 2.53125 | 3 | [] | no_license | //const_strings_test.cpp
#ifndef _MSC_VER
# error "this file test msvc only !!!!"
#endif // _MSC_VER
#include <iostream>
#include <yggr/charset/string.hpp>
#include <yggr/ppex/pp_debug.hpp>
#include <yggr/charset/const_strings.hpp>
//#define YGGR_USE_STL_STRING
#define YGGR_USE_BOOST_STRING
#ifdef _MSC_VER
#include <vld.h>
#endif // _MSC_VER
YGGR_PP_CONST_STRING_GLOBAL_DEF(g_test_string, "ab,\\c2")
template<typename Char>
const Char* foo(const Char* ptr, const Char* ptr2 = YGGR_PP_CONST_STRING_GLOBAL_GET(g_test_string, Char))
{
return ptr2;
}
int main(int arc, char* argv[])
{
#ifdef _DEBUG
std::cout << YGGR_PP_DEBUG(YGGR_PP_CONST_STRING_LOCAL_DEF(test_string, "ab,\\c")) << std::endl;
std::cout << YGGR_PP_DEBUG( YGGR_PP_CONST_CHAR_LOCAL_DEF(test_char, '/') ) << std::endl;
#endif // _DEBUG
YGGR_PP_CONST_STRING_LOCAL_DEF(test_string, "ab,\\c");
yggr::string str = YGGR_PP_CONST_STRING_LOCAL_GET(test_string, std::string::value_type);
yggr::string str2 = YGGR_PP_CONST_STRING_GLOBAL_GET(g_test_string, std::string::value_type);
std::cout << str << std::endl;
std::cout << str2 << std::endl;
#ifndef __MINGW32__
yggr::wstring wstr = YGGR_PP_CONST_STRING_LOCAL_GET(test_string, std::wstring::value_type);
yggr::wstring wstr2 = YGGR_PP_CONST_STRING_GLOBAL_GET(g_test_string, std::wstring::value_type);
std::wcout.imbue(std::locale("chs"));
std::wcout << wstr << std::endl;
std::wcout << wstr2 << std::endl;
#endif //
YGGR_PP_CONST_CHAR_LOCAL_DEF(test_char, '/')
std::cout << YGGR_PP_CONST_CHAR_LOCAL_GET(test_char, char) << std::endl;
#ifndef __MINGW32__
wchar_t wchar = YGGR_PP_CONST_CHAR_LOCAL_GET(test_char, wchar_t);
#endif // __MINGW32__
char cc = 0;
std::cin >> cc;
} | true |
861951ae136fcd8e605ba7d4f4626e47c054eee8 | C++ | Lin6797/Lin6797-stu-warehouse | /数据结构实验/实验7/minHeap_detail.cpp | GB18030 | 2,354 | 3.6875 | 4 | [] | no_license | //Сѵľʵ
#include "minHeap_class.h"
#include <iostream>
using namespace std;
template<class T>
minHeap<T>::minHeap(int n){ //캯
Num=0; Capacity=n; //ʼ
tHeap=new T[n]; //ٿռ
eHeap=new int[n];
}
template<class T>
bool minHeap<T>::IsEmpty(){//ж϶ǷΪ
if(Num==0) return true;
else return false;
}
template<class T>
bool minHeap<T>::IsFull(){//ж϶ǷΪ
if(Num==Capacity) return true;
else return false;
}
template<class T>
bool minHeap<T>::SiftUp(int start){//ϻѣĬstart=Num-1
int j=start, i=(j-1)/2; //jΪʼ㣬iΪʼĸĸ
T ttemp=tHeap[start]; int etemp=eHeap[start]; //͵м
while(j>0){
if(eHeap[i]<=etemp) break; //ӽڵȨֵȸĸڵĴ()
else{ //ӽڵȨֵȸĸڵС
eHeap[j]=eHeap[i]; tHeap[j]=tHeap[i];
j=i; i=(j-1)/2;
}
}
eHeap[j]=etemp; tHeap[j]=ttemp;
return true;
}
template<class T>
bool minHeap<T>::SiftDown(int start, int end){//»ѣĬstart=0,end=Num-1
int i=start, j=(2*i)+1; //iΪ,jΪ½ǵĽ
T ttemp=tHeap[i]; int etemp=eHeap[i]; //͵ʼ
while(j<=end){
if ( j<end && eHeap[j]>eHeap[j+1] ) j++; //ѡСŮ
if(eHeap[j]>=etemp) break; //ĸȨֵŮȨֵС
else{ //ĸȨֵŮȨֵ
tHeap[i]=tHeap[j]; eHeap[i]=eHeap[j];
i=j; j=2*i+1;
}
}
eHeap[i]=etemp; tHeap[i]=ttemp;
return true;
}
template<class T>
bool minHeap<T>::Insert(T t_data, int e_data){ //
if(IsFull()){
cout<<"ɲ"<<endl;
return false;
}
Num++;
tHeap[Num-1]=t_data;
eHeap[Num-1]=e_data;
SiftUp(Num-1);
return true;
}
template<class T>
bool minHeap<T>::Build(T t_data, int e_data){ //
Insert(t_data, e_data);
return false;
}
template<class T>
T minHeap<T>::Delete(){//ɾ
if(IsEmpty()){
cout<<"Ϊ,ɽɾ"<<endl;
}
else{
T ttemp=tHeap[0]; int etemp=eHeap[0];
tHeap[0]=tHeap[Num-1];
eHeap[0]=eHeap[Num-1];
Num--;
SiftDown(0,Num-1);
return ttemp;
}
}
template<class T>
T minHeap<T>::Out(){
T temp=Delete();
return temp;
}
template<class T>
T minHeap<T>::Get(){
return tHeap[0];
}
| true |