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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e0673aca541e31f054f8658a0889bd8f790b074c | C++ | NerdBeebe/BeebeChristian_CSC5_Spring2017 | /hmwrk/Assignment_1/Gaddis_8th_Edition_Chapter2_Problem3_SalesTax/main.cpp | UTF-8 | 778 | 3.796875 | 4 | [] | no_license | /*
* File: Sales Tax
* Author: Christian Beebe
* Created on 20170216
* Purpose: Compute the total sales tax on a purchase
*/
//System Libraries
#include <iostream> //Input - Output Library
using namespace std; //Name-space under which system libraries exist
//User Libraries
//Global Constants
//Function Prototypes
//Execution begins here
int main(int argc, char** argv) {
//Declare Variables
float tax,//Sales tax
purchase,//Item purchased
tltax;//Total sales tax in $'s
//Initialize variables
tax=0.06;
purchase=95;
//Map inputs to outputs or process the data
tltax=tax*purchase;
//Output the transformed data
cout<<"The sales tax on the $95 product is $"<<tltax<<endl;
//Exit stage right!
return 0;
}
| true |
9e44d6270910270128ddb5e5b9ffaa5038a48ace | C++ | hakobast/GLPractice | /src/lib/core/mat/Vector2.h | UTF-8 | 368 | 2.75 | 3 | [] | no_license | //
// Created by Hakob Astvatsatryan on 5/11/16.
//
#ifndef VECTOR2_H
#define VECTOR2_H
class Vector2 {
public:
Vector2(): x_(0), y_(0){};
Vector2(float x, float y): x_(x), y_(y){};
float getX() const;
float getY() const;
void set(float x, float y);
void setX(float x);
void setY(float y);
private:
float x_;
float y_;
};
#endif //VECTOR2_H | true |
466d97b18811f5978dbb2294d516c358ae20ccf4 | C++ | Elencrak/HeartStorm | /src/Player.h | UTF-8 | 609 | 2.59375 | 3 | [] | no_license | #pragma once
#include "Card.h"
#include "Deck.h"
#include "Hand.h"
#include "Board.h"
#include <memory>
namespace JojoBen
{
class Player
{
public:
int ID;
int LifePoint;
void Initialize(std::shared_ptr<Board> board, int seed);
void Draw();
void PlayCard(int index);
void SetNetworkID(std::string netID);
std::string GetNetworkID();
shared_ptr<Board> GetBoard();
Hand* GetHand();
int GetHash();
void TakeDamage(int amount);
Player(int ID);
~Player();
private:
std::string netID;
Deck* playerDeck;
Hand* playerHand;
std::shared_ptr<Board> playerBoard;
};
}
| true |
e92448e8a2667844aeffc07734a98585976690f4 | C++ | satyampandey9811/competitive-programming | /2. Leetcode/medium level/064. total hamming distance.cpp | UTF-8 | 452 | 3.046875 | 3 | [] | no_license | // link to question - https://leetcode.com/problems/total-hamming-distance/
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int ans = 0, n = nums.size();
for(int i = 0; i < 32; i++){
int bitone = 0;
for(auto x: nums){
if(x & (1 << i))
bitone++;
}
ans += bitone * (n - bitone);
}
return ans;
}
}; | true |
fc103ce1e098b2be308307a65577ec81b22a1267 | C++ | wlhe/cvlearn | /ch9/calchist/main.cpp | UTF-8 | 4,583 | 2.5625 | 3 | [] | no_license | #include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <vector>
using namespace cv;
static void hueSaturationHist(const std::string &imgname)
{
Mat src = imread(imgname);
if (src.empty()) {
std::cout << imgname << " Image empty\n";
}
imshow("Origin", src);
Mat hsv;
cvtColor(src, hsv, COLOR_BGR2HSV);
int hbins = 30;
int sbins = 32;
int histSize[] = {hbins, sbins};
float hranges[] = {0, 180};
float sranges[] = {0, 255};
const float *ranges[] = {hranges, sranges};
MatND hist;
int channels[] = {0, 1};
calcHist(&hsv, 1, channels, Mat(), hist, 2, histSize, ranges, true, false);
double maxVal = 0;
minMaxLoc(hist, 0, &maxVal, 0, 0);
int scale = 20;
Mat histImg = Mat::zeros(sbins * scale, hbins * scale, CV_8UC3);
for (int h = 0; h < hbins; h++) {
for (int s = 0; s < sbins; s++) {
float binVal = hist.at<float>(h, s);
int intensity = cvRound(binVal * 255 / maxVal);
rectangle(histImg, Point(h * scale, s * scale),
Point((h + 1) * scale - 1, (s + 1) * scale - 1),
Scalar::all(intensity), cv::FILLED);
}
}
imshow("H-S Histogram", histImg);
}
static void sample1Dhist(const std::string &imgname)
{
Mat src = imread(imgname, IMREAD_GRAYSCALE);
if (src.empty()) {
std::cout << imgname << " Image empty\n";
}
imshow("Origin", src);
MatND hist;
int dims = 1;
float hranges[] = {0, 255};
const float *ranges[] = {hranges};
int channels[] = {0};
int size = 256;
calcHist(&src, 1, channels, Mat(), hist, dims, &size, ranges);
double minVal = 0, maxVal = 0;
minMaxLoc(hist, &minVal, &maxVal, 0, 0);
int scale = 1;
Mat histImg = Mat::zeros(size * scale, size * scale, CV_8UC3);
int hpt = size * 0.9;
for (int i = 0; i < size; i++) {
float binVal = hist.at<float>(i);
int realValue = saturate_cast<int>(binVal * hpt / maxVal);
rectangle(histImg, Point(i * scale, size * scale - 1),
Point((i + 1) * scale - 1, (size - realValue) * scale - 1),
Scalar::all(255));
}
imshow("1D Hist", histImg);
}
static void sampleRGBHist(const std::string &imgname)
{
Mat src = imread(imgname);
if (src.empty()) {
std::cout << imgname << " Image empty\n";
}
imshow("Origin", src);
int bins = 256;
int histSize[] = {bins};
float range[] = {0, 256};
const float *ranges[] = {range};
MatND histRed, histGreen, histBlue;
int channelsBlue[] = {0};
calcHist(&src, 1, channelsBlue, Mat(), histBlue, 1, histSize, ranges);
int channelsGreen[] = {1};
calcHist(&src, 1, channelsGreen, Mat(), histGreen, 1, histSize, ranges);
int channelsRed[] = {2};
calcHist(&src, 1, channelsRed, Mat(), histRed, 1, histSize, ranges);
double maxRed, maxGreen, maxBlue;
minMaxLoc(histBlue, 0, &maxBlue, 0, 0);
minMaxLoc(histGreen, 0, &maxGreen, 0, 0);
minMaxLoc(histRed, 0, &maxRed, 0, 0);
int scale = 1;
Mat histImg = Mat::zeros(bins * scale, bins * 3, CV_8UC3);
for (int i = 0; i < bins; i++) {
float binRed = histRed.at<float>(i);
float binGreen = histGreen.at<float>(i);
float binBlue = histBlue.at<float>(i);
int intensityRed = cvRound(binRed * bins / maxRed);
int intensityGreen = cvRound(binGreen * bins / maxGreen);
int intensityBlue = cvRound(binBlue * bins / maxBlue);
rectangle(histImg, Point(i * scale, bins - 1),
Point((i + 1) * scale - 1, bins - intensityBlue - 1),
Scalar(255, 0, 0));
rectangle(histImg, Point((i + bins) * scale, bins - 1),
Point((i + bins + 1) * scale - 1, bins - intensityGreen - 1),
Scalar(0, 255, 0));
rectangle(histImg, Point((i + 2 * bins) * scale, bins - 1),
Point((i + 2 * bins + 1) * scale - 1, bins - intensityRed - 1),
Scalar(0, 0, 255));
}
imshow("RGB Hist", histImg);
}
int main(int argc, char **argv)
{
std::string imgname = "../../images/3.jpg";
if (argc == 2) {
imgname = argv[1];
}
// hueSaturationHist(imgname);
// sample1Dhist(imgname);
sampleRGBHist(imgname);
waitKey(0);
return 0;
} | true |
89e2a5970791d0526a01886dfa11ae40326e1dca | C++ | marekpetrik/CRAAM | /include/rm/test.cpp | UTF-8 | 778 | 3.140625 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | #include <iostream>
#include <vector>
#include "range.hpp"
using std::cout;
using util::lang::range;
using util::lang::indices;
int main() {
for (auto i : range(1, 5))
cout << i << "\n";
for (auto u : range(0u))
if (u == 3u) break;
else cout << u << "\n";
for (auto c : range('a', 'd'))
cout << c << "\n";
for (auto u : range(20u, 29u).step(2u))
cout << u << "\n";
for (auto i : range(100).step(-3))
if (i < 90) break;
else cout << i << "\n";
std::vector<int> x{1, 2, 3};
for (auto i : indices(x))
cout << i << '\n';
for (auto i : indices({"foo", "bar"}))
cout << i << '\n';
for (auto i : indices("foobar").step(2))
cout << i << '\n';
}
| true |
82f4bd0c00ecaee3e2539b95da80a8256ed11898 | C++ | DylanCurran/vertexBufferCube | /Dylan'sVBCube/SFMLOpenGL/MyMatrix3.h | UTF-8 | 1,419 | 3 | 3 | [] | no_license | #ifndef MY_MATRIX3
#define MY_MATRIX3
#include "MyVector3D.h"
#include "math.h"
class MyMatrix3
{
public:
MyMatrix3();
MyMatrix3(
double a11, double a12, double a13,
double a21, double a22, double a23,
double a31, double a32, double a33);
MyMatrix3(MyVector3D row1, MyVector3D row2, MyVector3D row3);
~MyMatrix3();
std::string toString();
MyMatrix3 operator +(const MyMatrix3 otherOne) const;
MyMatrix3 operator -(const MyMatrix3 otherOne) const;
MyMatrix3 operator *(const MyMatrix3 otherOne) const;
MyVector3D operator *(const MyVector3D otherOne) const;
MyMatrix3 operator *(const double scalar) const;
MyMatrix3 transpose() const;
double determinant() const;
MyMatrix3 inverse() const;
MyVector3D row(int row) const;
MyVector3D column(int column) const;
bool operator ==(const MyMatrix3 otherOne) const;
bool operator !=(const MyMatrix3 otherOne) const;
static MyMatrix3 rotationX(double radNess);
static MyMatrix3 rotationY(double radNess);
static MyMatrix3 rotationZ(double radNess);
static MyMatrix3 translation(MyMatrix3 displacement); // since 2D translation z == 1
static MyVector3D translation2(MyVector3D displacement);
static MyMatrix3 scale(double scaleFactor);
private:
double m11;
double m12;
double m13;
double m21;
double m22;
double m23;
double m31;
double m32;
double m33;
};
#endif // !MY_MATRIX3
| true |
d25fd26e52cdda0f2f805a35c83391831714412c | C++ | JudsonSS/Compiladores | /Labs/Lab05/parser.cpp | UTF-8 | 890 | 3.375 | 3 | [
"MIT"
] | permissive | #include "parser.h"
#include <iostream>
#include <cctype>
using std::cin;
using std::cout;
using std::endl;
void Parser::Expr()
{
// expr -> term oper
Term();
while (true)
{
// oper -> + term { print(+) } oper
if (lookahead == '+')
{
Match('+');
Term();
cout << '+';
}
// oper -> - term { print(-) } oper
else if (lookahead == '-')
{
Match('-');
Term();
cout << '-';
}
// produção vazia
else return;
}
}
void Parser::Term()
{
if (isdigit(lookahead))
{
cout << lookahead;
Match(lookahead);
}
else
throw SyntaxError{};
}
void Parser::Match(char t)
{
if (t == lookahead)
lookahead = cin.get();
else
throw SyntaxError{};
}
Parser::Parser()
{
lookahead = 0;
}
void Parser::Start()
{
lookahead = cin.get();
Expr();
if (lookahead != '\n')
throw SyntaxError{};
} | true |
d579185f1e6e660ec46529bf3f4ea1b867af8152 | C++ | tomgrove/ToyProlog | /PrologToy/Machine.h | UTF-8 | 2,188 | 2.96875 | 3 | [] | no_license | #pragma once
#include <vector>
#include "term.h"
namespace Toy {
class Machine
{
public:
Machine()
: mHeapIndex(0)
, mH(new Term[ MaxHeapSize ])
, mMode( eRead )
, mFail( false )
, mS( nullptr )
, mP( nullptr )
{}
Term* AllocVariable();
Term* AllocStructure(FunctorType functor, uint32_t arity);
static const uint32_t NumTempRegisters = 256;
static const uint32_t MaxHeapSize = 1024 * 1024;
typedef enum {
eRead,
eWrite
} Mode;
typedef enum {
eNop,
ePut_Structure,
eSet_Variable,
eSet_Value,
eGet_Structure,
eUnify_Variable,
eUnify_Value,
eCall,
eProceed
} Opcode;
struct Instruction
{
Opcode mOp;
union {
uint32_t mArgs[3];
Instruction* mTarget;
};
Instruction()
: mOp(eNop)
{}
Instruction(Instruction* target)
: mOp(eCall)
, mTarget(target)
{}
Instruction(Opcode op)
: mOp(op)
{}
Instruction(Opcode op, uint32_t arg0)
: mOp(op)
{
mArgs[0] = arg0;
}
Instruction(Opcode op, uint32_t arg0, uint32_t arg1)
: mOp(op)
{
mArgs[0] = arg0;
mArgs[1] = arg1;
}
Instruction(Opcode op, uint32_t arg0, uint32_t arg1, uint32_t arg2)
: mOp(op)
{
mArgs[0] = arg0;
mArgs[1] = arg1;
mArgs[2] = arg2;
}
};
Term* mH;
uint32_t mHeapIndex;
Term mXs[ NumTempRegisters ];
Term* mS;
Instruction* mP;
Mode mMode;
bool mFail;
Term* DeRef(Term* term);
void Bind(Term* term, Term* ref);
void Unify(Term* t0, Term* t1);
// opcodes
void put_structure(FunctorType functor, uint32_t arity, uint32_t reg);
void set_variable(uint32_t reg );
void set_value(uint32_t reg);
void get_structure(FunctorType functor, uint32_t arity, uint32_t reg);
void unify_variable(uint32_t reg);
void unify_value(uint32_t reg);
void Execute(Instruction* instructions);
void Disassemble(Instruction* instructions, uint32_t count, std::stringstream& ss);
void DumpHeap(std::stringstream& ss);
void SerializeTerm(Term* term, std::stringstream& ss);
bool CheckHeap();
private:
Term* AllocCells( uint32_t numCells );
};
//__declspec(dllexport) void TestMachine();
} | true |
14921f1560a208195bbab7889fe421a2e3e9e730 | C++ | MagiaGroz/Algorithms | /graphs/lcm.cpp | UTF-8 | 835 | 3.03125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int gcd (int a, int b) {
return b ? gcd (b, a % b) : a;
}
int lcm (int a, int b) {
return a / gcd (a, b) * b;
}
// Utility function to find
// GCD of 'a' and 'b'
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Returns LCM of array elements
ll findlcm(int arr[], int n)
{
// Initialize result
ll ans = arr[0];
// ans contains LCM of arr[0], ..arr[i]
// after i'th iteration,
for (int i = 1; i < n; i++)
ans = (((arr[i] * ans)) /
(gcd(arr[i], ans)));
return ans;
}
// Driver Code
int main()
{
int arr[] = { 2, 7, 3, 9, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%lld", findlcm(arr, n));
return 0;
} | true |
18e3a06bbaf37f785c77934b32450d87e8c30fa6 | C++ | Yuanfeng-Wang/CSM_Cantera | /include/cantera/thermo/FixedChemPotSSTP.h | UTF-8 | 22,650 | 2.578125 | 3 | [] | no_license | /**
* @file FixedChemPotSSTP.h
* Header file for the FixedChemPotSSTP class, which represents a fixed-composition
* incompressible substance with a constant chemical potential (see \ref thermoprops and
* class \link Cantera::FixedChemPotSSTP FixedChemPotSSTP\endlink)
*/
/*
* Copyright (2005) Sandia Corporation. Under the terms of
* Contract DE-AC04-94AL85000 with Sandia Corporation, the
* U.S. Government retains certain rights in this software.
*/
#ifndef CT_FIXEDCHEMPOTSSTP_H
#define CT_FIXEDCHEMPOTSSTP_H
#include "mix_defs.h"
#include "SingleSpeciesTP.h"
#include "SpeciesThermo.h"
namespace Cantera
{
//! Class %FixedChemPotSSTP represents a stoichiometric (fixed
//! composition) incompressible substance.
/*!
* This class internally changes the independent degree of freedom from
* density to pressure. This is necessary because the phase is
* incompressible. It uses a zero volume approximation.
*
*
* <b> Specification of Species Standard %State Properties </b>
*
* This class inherits from SingleSpeciesTP.
* It uses a single value for the chemical potential which is assumed to be constant
* with respect to temperature and pressure.
*
* The reference state thermodynamics is inherited from SingleSpeciesTP. However,
* it's only used to set the initial chemical potential to the value
* of the chemical potential at the starting conditions. Thereafter,
* it is ignored.
*
* For a zero volume material, the internal energy and the enthalpy are
* equal to the chemical potential. The entropy, the heat capacity, and the molar volume
* are equal to zero.
*
*
* <b> Specification of Solution Thermodynamic Properties </b>
*
* All solution properties are obtained from the standard state
* species functions, since there is only one species in the phase.
*
* <b> Application within %Kinetics Managers </b>
*
* The standard concentration is equal to 1.0. This means that the
* kinetics operator works on an (activities basis). Since this
* is a stoichiometric substance, this means that the concentration
* of this phase drops out of kinetics expressions.
*
* An example of a reaction using this is a sticking coefficient
* reaction of a substance in an ideal gas phase on a surface with a bulk phase
* species in this phase. In this case, the rate of progress for this
* reaction, \f$ R_s \f$, may be expressed via the following equation:
* \f[
* R_s = k_s C_{gas}
* \f]
* where the units for \f$ R_s \f$ are kmol m-2 s-1. \f$ C_{gas} \f$ has units
* of kmol m-3. Therefore, the kinetic rate constant, \f$ k_s \f$, has
* units of m s-1. Nowhere does the concentration of the bulk phase
* appear in the rate constant expression, since it's a stoichiometric
* phase, and the activity is always equal to 1.0.
*
* <b> Instantiation of the Class </b>
*
* This phase may be instantiated by calling the default ThermoFactory routine
* for %Cantera. This new %FixedChemPotSSTP object must then have a standalone xml file
* description an example of which is given below.
*
*
*
* It may also be created by the following code snippets. The code
* includes the special member function setChemicalPotential( chempot), which
* sets the chemical potential to a specific value in J / kmol.
*
* @code
* sprintf(file_ID,"%s#Li(Fixed)", iFile);
* XML_Node *xm = get_XML_NameID("phase", file_ID, 0);
* FixedChemPotSSTP *LiFixed = new FixedChemPotSSTP(*xm);
// Set the chemical potential to -2.3E7 J/kmol
* LiFixed->setChemicalPotential(-2.3E7.)
* @endcode
*
* or by the following call to importPhase():
*
* @code
* sprintf(file_ID,"%s#NaCl(S)", iFile);
* XML_Node *xm = get_XML_NameID("phase", file_ID, 0);
* FixedChemPotSSTP solid;
* importPhase(*xm, &solid);
* @endcode
*
* The phase may also be created by a special constructor so that element
* potentials may be set. The constructor takes the name of the element and
* the value of the element chemical potential. An example is given below.
*
* @code
* FixedChemPotSSTP *LiFixed = new FixedChemPotSSTP("Li", -2.3E7);
* @endcode
*
* <b> XML Example </b>
*
* The phase model name for this is called FixedChemPot. It must be supplied
* as the model attribute of the thermo XML element entry.
*
*
* @verbatim
<?xml version="1.0"?>
<ctml>
<validate reactions="yes" species="yes"/>
<!-- phase NaCl(S) -->
<phase dim="3" id="LiFixed">
<elementArray datasrc="elements.xml">
Li
</elementArray>
<speciesArray datasrc="#species_Li(Fixed)">
LiFixed
</speciesArray>
<thermo model="FixedChemPot">
<chemicalPotential units="J/kmol"> -2.3E7 </chemicalPotential>
</thermo>
<transport model="None"/>
<kinetics model="none"/>
</phase>
<!-- species definitions -->
<speciesData id="species_Li(Fixed)">
<species name="LiFixed">
<atomArray> Li:1 </atomArray>
<thermo>
<Shomate Pref="1 bar" Tmax="1075.0" Tmin="250.0">
<floatArray size="7">
50.72389, 6.672267, -2.517167,
10.15934, -0.200675, -427.2115,
130.3973
</floatArray>
</Shomate>
</thermo>
</species>
</speciesData>
</ctml>
@endverbatim
*
* The model attribute, "FixedChemPot", on the thermo element
* identifies the phase as being a FixedChemPotSSTP object.
*
* @ingroup thermoprops
*/
class FixedChemPotSSTP : public SingleSpeciesTP
{
public:
//! Default constructor for the FixedChemPotSSTP class
FixedChemPotSSTP();
//! Construct and initialize a FixedChemPotSSTP ThermoPhase object
//! directly from an ASCII input file
/*!
* @param infile name of the input file
* @param id name of the phase id in the file.
* If this is blank, the first phase in the file is used.
*/
FixedChemPotSSTP(std::string infile, std::string id = "");
//! Construct and initialize a FixedChemPotSSTP ThermoPhase object
//! directly from an XML database
/*!
* @param phaseRef XML node pointing to a FixedChemPotSSTP description
* @param id Id of the phase.
*/
FixedChemPotSSTP(XML_Node& phaseRef, std::string id = "");
//! Copy constructor
/*!
* @param right Object to be copied
*/
FixedChemPotSSTP(const FixedChemPotSSTP& right);
//! Special constructor for the FixecChemPotSSTP class setting an element chemical
//! potential directly
/*!
* This will create a %FixedChemPotSSTP consisting of a single species with the
* stoichiometry of one of the specified atom. It will have a chemical potential
* that is given by the second argument.
*
* @param Ename String name of the element
* @param chemPot Value of the chemical potential of that element (J/kmol)
*/
FixedChemPotSSTP(std::string Ename, doublereal chemPot);
//! Assignment operator
/*!
* @param right Object to be copied
*/
FixedChemPotSSTP& operator=(const FixedChemPotSSTP& right);
//! Destructor for the routine (virtual)
virtual ~FixedChemPotSSTP();
//! Duplication function
/*!
* This virtual function is used to create a duplicate of the
* current phase. It's used to duplicate the phase when given
* a ThermoPhase pointer to the phase.
*
* @return It returns a ThermoPhase pointer.
*/
ThermoPhase* duplMyselfAsThermoPhase() const;
/**
*
* @name Utilities
* @{
*/
/**
* Equation of state flag.
*
* Returns the value cStoichSubstance, defined in mix_defs.h.
*/
virtual int eosType() const;
/**
* @}
* @name Molar Thermodynamic Properties of the Solution
* @{
*/
/**
* @}
* @name Mechanical Equation of State
* @{
*/
//! Report the Pressure. Units: Pa.
/*!
* For an incompressible substance, the density is independent
* of pressure. This method simply returns the stored
* pressure value.
*/
virtual doublereal pressure() const;
//! Set the pressure at constant temperature. Units: Pa.
/*!
* For an incompressible substance, the density is
* independent of pressure. Therefore, this method only
* stores the specified pressure value. It does not
* modify the density.
*
* @param p Pressure (units - Pa)
*/
virtual void setPressure(doublereal p);
//! Returns the isothermal compressibility. Units: 1/Pa.
/*!
* The isothermal compressibility is defined as
* \f[
* \kappa_T = -\frac{1}{v}\left(\frac{\partial v}{\partial P}\right)_T
* \f]
*/
virtual doublereal isothermalCompressibility() const;
//! Return the volumetric thermal expansion coefficient. Units: 1/K.
/*!
* The thermal expansion coefficient is defined as
* \f[
* \beta = \frac{1}{v}\left(\frac{\partial v}{\partial T}\right)_P
* \f]
*/
virtual doublereal thermalExpansionCoeff() const ;
/**
* @}
* @name Activities, Standard States, and Activity Concentrations
*
* This section is largely handled by parent classes, since there
* is only one species. Therefore, the activity is equal to one.
* @{
*/
//! This method returns an array of generalized concentrations
/*!
* \f$ C^a_k\f$ are defined such that \f$ a_k = C^a_k /
* C^0_k, \f$ where \f$ C^0_k \f$ is a standard concentration
* defined below and \f$ a_k \f$ are activities used in the
* thermodynamic functions. These activity (or generalized)
* concentrations are used
* by kinetics manager classes to compute the forward and
* reverse rates of elementary reactions.
*
* For a stoichiometric substance, there is
* only one species, and the generalized concentration is 1.0.
*
* @param c Output array of generalized concentrations. The
* units depend upon the implementation of the
* reaction rate expressions within the phase.
*/
virtual void getActivityConcentrations(doublereal* c) const;
//! Return the standard concentration for the kth species
/*!
* The standard concentration \f$ C^0_k \f$ used to normalize
* the activity (i.e., generalized) concentration.
* This phase assumes that the kinetics operator works on an
* dimensionless basis. Thus, the standard concentration is
* equal to 1.0.
*
* @param k Optional parameter indicating the species. The default
* is to assume this refers to species 0.
* @return
* Returns The standard Concentration as 1.0
*/
virtual doublereal standardConcentration(size_t k=0) const;
//! Natural logarithm of the standard concentration of the kth species.
/*!
* @param k index of the species (defaults to zero)
*/
virtual doublereal logStandardConc(size_t k=0) const;
//! Get the array of chemical potentials at unit activity for the species
//! at their standard states at the current <I>T</I> and <I>P</I> of the solution.
/*!
* For a stoichiometric substance, there is no activity term in
* the chemical potential expression, and therefore the
* standard chemical potential and the chemical potential
* are both equal to the molar Gibbs function.
*
* These are the standard state chemical potentials \f$ \mu^0_k(T,P)
* \f$. The values are evaluated at the current
* temperature and pressure of the solution
*
* @param mu0 Output vector of chemical potentials.
* Length: m_kk.
*/
virtual void getStandardChemPotentials(doublereal* mu0) const;
//! Returns the units of the standard and generalized concentrations.
/*!
* Note they have the same units, as their
* ratio is defined to be equal to the activity of the kth
* species in the solution, which is unitless.
*
* This routine is used in print out applications where the
* units are needed. Usually, MKS units are assumed throughout
* the program and in the XML input files.
*
* The base %ThermoPhase class assigns the default quantities
* of (kmol/m3) for all species.
* Inherited classes are responsible for overriding the default
* values if necessary.
*
* @param uA Output vector containing the units
* uA[0] = kmol units - default = 1
* uA[1] = m units - default = -nDim(), the number of spatial
* dimensions in the Phase class.
* uA[2] = kg units - default = 0;
* uA[3] = Pa(pressure) units - default = 0;
* uA[4] = Temperature units - default = 0;
* uA[5] = time units - default = 0
* @param k species index. Defaults to 0.
* @param sizeUA output int containing the size of the vector.
* Currently, this is equal to 6.
*/
virtual void getUnitsStandardConc(doublereal* uA, int k = 0,
int sizeUA = 6) const;
//@}
/// @name Partial Molar Properties of the Solution
///
/// These properties are handled by the parent class,
/// SingleSpeciesTP
//@{
//! Get the species partial molar volumes. Units: m^3/kmol.
/*!
* This is the phase molar volume. \f$ V(T,P) = V_o(T,P) \f$.
*
* set to zero.
*
* @param vbar On return, contains the molar volume of the single species
* and the phase. Units are m^3 / kmol. Length = 1
*/
void getPartialMolarVolumes(doublereal* vbar) const;
//@}
/// @name Properties of the Standard State of the Species in the Solution
//@{
//! Get the nondimensional Enthalpy functions for the species
//! at their standard states at the current <I>T</I> and <I>P</I> of the solution.
/*!
* @param hrt Output vector of nondimensional standard state enthalpies.
* Length: m_kk.
*/
virtual void getEnthalpy_RT(doublereal* hrt) const;
//! Get the array of nondimensional Entropy functions for the
//! standard state species at the current <I>T</I> and <I>P</I> of the solution.
/*!
* @param sr Output vector of nondimensional standard state entropies.
* Length: m_kk.
*/
virtual void getEntropy_R(doublereal* sr) const;
//! Get the nondimensional Gibbs functions for the species
//! in their standard states at the current <I>T</I> and <I>P</I> of the solution.
/*!
* @param grt Output vector of nondimensional standard state gibbs free energies
* Length: m_kk.
*/
virtual void getGibbs_RT(doublereal* grt) const;
//! Get the nondimensional Heat Capacities at constant
//! pressure for the species standard states
//! at the current <I>T</I> and <I>P</I> of the solution
/*!
* @param cpr Output vector of nondimensional standard state heat capacities
* Length: m_kk.
*/
virtual void getCp_R(doublereal* cpr) const;
//! Returns the vector of nondimensional Internal Energies of the standard
//! state species at the current <I>T</I> and <I>P</I> of the solution
/*!
* For an incompressible,
* stoichiometric substance, the molar internal energy is
* independent of pressure. Since the thermodynamic properties
* are specified by giving the standard-state enthalpy, the
* term \f$ P_{ref} \hat v\f$ is subtracted from the specified reference molar
* enthalpy to compute the standard state molar internal energy.
*
* @param urt output vector of nondimensional standard state
* internal energies of the species. Length: m_kk.
*/
virtual void getIntEnergy_RT(doublereal* urt) const;
//! Get the molar volumes of each species in their standard
//! states at the current <I>T</I> and <I>P</I> of the solution.
/*
* units = m^3 / kmol
*
* We set this to zero
*
* @param vbar On output this contains the standard volume of the species
* and phase (m^3/kmol). Vector of length 1
*/
virtual void getStandardVolumes(doublereal* vbar) const;
//@}
/// @name Thermodynamic Values for the Species Reference States
//@{
//! Returns the vector of nondimensional
//! internal Energies of the reference state at the current temperature
//! of the solution and the reference pressure for each species.
/*!
* @param urt Output vector of nondimensional reference state
* internal energies of the species.
* Length: m_kk
*/
virtual void getIntEnergy_RT_ref(doublereal* urt) const;
//@}
/// @name Thermodynamic Values for the Species Reference State
///
/*!
* Returns the vector of nondimensional
* enthalpies of the reference state at the current temperature
* of the solution and the reference pressure for the species.
*
* This function is resolved in this class. It is assumed that the m_spthermo species thermo
* pointer is populated and yields the reference state.
*
* @param hrt Output vector containing the nondimensional reference state enthalpies
* Length: m_kk.
*/
virtual void getEnthalpy_RT_ref(doublereal* hrt) const;
/*!
* Returns the vector of nondimensional
* enthalpies of the reference state at the current temperature
* of the solution and the reference pressure for the species.
*
* This function is resolved in this class. It is assumed that the m_spthermo species thermo
* pointer is populated and yields the reference state.
*
* @param grt Output vector containing the nondimensional reference state
* Gibbs Free energies. Length: m_kk.
*/
virtual void getGibbs_RT_ref(doublereal* grt) const;
/*!
* Returns the vector of the
* gibbs function of the reference state at the current temperature
* of the solution and the reference pressure for the species.
* units = J/kmol
*
* This function is resolved in this class. It is assumed that the m_spthermo species thermo
* pointer is populated and yields the reference state.
*
* @param g Output vector containing the reference state
* Gibbs Free energies. Length: m_kk. Units: J/kmol.
*/
virtual void getGibbs_ref(doublereal* g) const;
/*!
* Returns the vector of nondimensional
* entropies of the reference state at the current temperature
* of the solution and the reference pressure for each species.
*
* This function is resolved in this class. It is assumed that the m_spthermo species thermo
* pointer is populated and yields the reference state.
*
* @param er Output vector containing the nondimensional reference state
* entropies. Length: m_kk.
*/
virtual void getEntropy_R_ref(doublereal* er) const;
/*!
* Returns the vector of nondimensional
* constant pressure heat capacities of the reference state
* at the current temperature of the solution
* and reference pressure for each species.
*
* This function is resolved in this class. It is assumed that the m_spthermo species thermo
* pointer is populated and yields the reference state.
*
* @param cprt Output vector of nondimensional reference state
* heat capacities at constant pressure for the species.
* Length: m_kk
*/
virtual void getCp_R_ref(doublereal* cprt) const;
/*
* ---- Critical State Properties
*/
/*
* ---- Saturation Properties
*/
/*
* @internal Initialize. This method is provided to allow
* subclasses to perform any initialization required after all
* species have been added. For example, it might be used to
* resize internal work arrays that must have an entry for
* each species. The base class implementation does nothing,
* and subclasses that do not require initialization do not
* need to overload this method. When importing a CTML phase
* description, this method is called just prior to returning
* from function importPhase.
*
* @see importCTML.cpp
*/
virtual void initThermo();
virtual void initThermoXML(XML_Node& phaseNode, std::string id);
//! Set the equation of state parameters
/*!
* @internal
* The number and meaning of these depends on the subclass.
*
* @param n number of parameters
* @param c array of \a n coefficients
* c[0] = density of phase [ kg/m3 ]
*/
virtual void setParameters(int n, doublereal* const c);
//! Get the equation of state parameters in a vector
/*!
* @internal
*
* @param n number of parameters
* @param c array of \a n coefficients
*
* For this phase:
* - n = 1
* - c[0] = density of phase [ kg/m3 ]
*/
virtual void getParameters(int& n, doublereal* const c) const;
//! Set equation of state parameter values from XML entries.
/*!
* This method is called by function importPhase() in
* file importCTML.cpp when processing a phase definition in
* an input file. It should be overloaded in subclasses to set
* any parameters that are specific to that particular phase
* model. Note, this method is called before the phase is
* initialized with elements and/or species.
*
* For this phase, the chemical potential is set
*
* @param eosdata An XML_Node object corresponding to
* the "thermo" entry for this phase in the input file.
*
* eosdata points to the thermo block, and looks like this:
*
* @verbatim
<phase id="stoichsolid" >
<thermo model="FixedChemPot">
<chemicalPotential units="J/kmol"> -2.7E7 </chemicalPotential>
</thermo>
</phase> @endverbatim
*
*/
virtual void setParametersFromXML(const XML_Node& eosdata);
//! Function to set the chemical potential directly
/*!
* @param chemPot Value of the chemical potential (units J/kmol)
*/
void setChemicalPotential(doublereal chemPot);
protected:
//! Value of the chemical potential of the bath species
/*!
* units are J/kmol
*/
doublereal chemPot_;
};
}
#endif
| true |
3f8b24973f707bb147ac9c51ffdedc68c328b86d | C++ | febin-micheal/oot | /4.1.cpp | UTF-8 | 739 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Student
{
public:
int rollno;
// Student();
// ~Student();
void read()
{
cout<<"enter rollno: ";
cin>>rollno;
}
};
class Test: public virtual Student
{
public:
int m1,m2;
// Test();
// ~Test();
void read1()
{
cout<<"enter marks of 2 subjects: ";
cin>>m1>>m2;
}
};
class Sports: public virtual Student
{
public:
int w;
// Sports();
// ~Sports();
void read2()
{
cout<<"enter score in sports: ";
cin>>w;
}
};
class Result: public Test, public Sports
{
public:
float sum;
// Result();
// ~Result();
void display()
{
sum = m1 + m2 + w;
cout<<"Result: "<<sum;
}
};
int main()
{
Result s;
s.read();
s.read1();
s.read2();
s.display();
return 0;
} | true |
64933bbbd016a59cb8ebe9c61530666973d3b0ff | C++ | vgvgvvv/3d-math | /Plane.h | UTF-8 | 3,071 | 3.375 | 3 | [] | no_license | #pragma once
#include "Ray.h"
#include "Vector3.h"
#include "MathLibAPI.h"
class MATHLIB_API Plane
{
Vector3 m_Normal;
float m_Distance;
public:
// Normal vector of the plane.
Vector3 GetNormal() { return m_Normal; }
void SetNormal(Vector3 value) { m_Normal = value; }
// Distance from the origin to the plane.
float GetDistance() { return m_Distance; }
void SetDistance(float value) { m_Distance = value; }
// Creates a plane.
Plane(Vector3 inNormal, Vector3 inPoint)
{
m_Normal = Vector3::Normalize(inNormal);
m_Distance = -Vector3::Dot(m_Normal, inPoint);
}
// Creates a plane.
Plane(Vector3 inNormal, float d)
{
m_Normal = Vector3::Normalize(inNormal);
m_Distance = d;
}
// Creates a plane.
Plane(Vector3 a, Vector3 b, Vector3 c)
{
m_Normal = Vector3::Normalize(Vector3::Cross(b - a, c - a));
m_Distance = -Vector3::Dot(m_Normal, a);
}
// Sets a plane using a point that lies within it plus a normal to orient it (note that the normal must be a normalized vector).
void SetNormalAndPosition(Vector3 inNormal, Vector3 inPoint)
{
m_Normal = Vector3::Normalize(inNormal);
m_Distance = -Vector3::Dot(inNormal, inPoint);
}
// Sets a plane using three points that lie within it. The points go around clockwise as you look down on the top surface of the plane.
void Set3Points(Vector3 a, Vector3 b, Vector3 c);
// Make the plane face the opposite direction
void Flip();
// Return a version of the plane that faces the opposite direction
Plane flipped() const;
// Translates the plane into a given direction
void Translate(Vector3 translation);
// Creates a plane that's translated into a given direction
static Plane Translate(Plane plane, Vector3 translation) { return {plane.m_Normal, plane.m_Distance += Vector3::Dot(plane.m_Normal, translation)
}; }
// Calculates the closest point on the plane.
Vector3 ClosestPointOnPlane(Vector3 point) const;
// Returns a signed distance from plane to point.
float GetDistanceToPoint(Vector3 point) const;
// Is a point on the positive side of the plane?
bool GetSide(Vector3 point) const;
// Are two points on the same side of the plane?
bool SameSide(Vector3 inPt0, Vector3 inPt1) const;
// Intersects a ray with the plane.
bool Raycast(Ray ray, float& enter) const;
// override string ToString()
// {
// return ToString(null, CultureInfo.InvariantCulture.NumberFormat);
// }
//
// string ToString(string format)
// {
// return ToString(format, CultureInfo.InvariantCulture.NumberFormat);
// }
//
// string ToString(string format, IFormatProvider formatProvider)
// {
// if (string.IsNullOrEmpty(format))
// format = "F1";
// return String.Format("(normal:{0}, distance:{1})", m_Normal.ToString(format, formatProvider), m_Distance.ToString(format, formatProvider));
// }
};
| true |
8712ac7e13baf58f86108047f3f2837c6f0cfbd5 | C++ | krzysztofdabkowski1/cereal_json_example | /Car.h | UTF-8 | 1,519 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <memory>
#include <cereal/types/vector.hpp>
#include <cereal/types/polymorphic.hpp>
#include <cereal/archives/json.hpp>
class Tire
{
private:
int typeOfRubber;
public:
Tire(int typeOfRubber)
{
Tire::typeOfRubber = typeOfRubber;
}
Tire()
{
typeOfRubber = 0;
}
int getRubberType()
{
return typeOfRubber;
}
template <class Archive>
void serialize( Archive & ar )
{
ar(CEREAL_NVP(typeOfRubber));
}
};
class Car
{
public:
std::vector<Tire> tires;
std::string name;
Car(std::string name)
{
//tires.reset(new std::shared_ptr<Tire>[4]);
Car::name = name;
tires.push_back(Tire(1));
tires.push_back(Tire(1));
tires.push_back(Tire(2));
tires.push_back(Tire(2));
}
Car() = default;
void getSound()
{
std::cout<<"wrooom wroom "<<name<<std::endl;
}
void getTiresRubberType()
{
std::cout<<tires[0].getRubberType()
<<tires[1].getRubberType()
<<tires[2].getRubberType()
<<tires[3].getRubberType();
}
template <class Archive>
void serialize( Archive & ar )
{
ar(CEREAL_NVP(name), CEREAL_NVP(tires));
}
};
| true |
6ae0c6c32e58034e246299eb9594a33dd380ab34 | C++ | TanDongXu/TextCheck | /Trie.cpp | UTF-8 | 2,243 | 3.3125 | 3 | [] | no_license | #include"Trie.h"
//Trie constructor
Trie::Trie()
{
pRoot = new TrieNode();
//vQueue.clear();
}//end of Trie
//destructor
Trie::~Trie()
{
delete pRoot;
}//end of ~Trie
//Tire insert
void Trie::trie_insert(std::string inputStr)
{
int length = inputStr.size();
//if inputStr is NULL or the length is more than md5's length
if( length <= 0 || length > 32)
{
std::cout<<"trie_insert: inuputStr Error!"<< std::endl;
return;
}
int index;
TrieNode* pNode = pRoot, *pNew;
for(int i = 0; i < length; i++)
{
/*char A~Z put in 0~25 and char 0~9 put in 26~35*/
if(inputStr[i] >= 'A' && inputStr[i] <='Z')
{
index = inputStr[i] - 'A';
}else if(inputStr[i] >= '0' && inputStr[i] <= '9')
{
index = inputStr[i] - '0' + 26;
}else
{
std::cout<<"trie_insert:Md5 input Error!"<<std::endl;
exit(0);
}
if(NULL == pNode->nextBranch[index])
{
pNew = (TrieNode*) malloc(sizeof(TrieNode));
pNew->word = inputStr[i];
for(int j = 0; j < MaxBranchNum; j++)
{
pNew->nextBranch[j] = NULL;
}
pNode->nextBranch[index] = pNew;
pNode = pNode->nextBranch[index];
}else
{
pNode = pNode->nextBranch[index];
}
}//end for
}// end of Trie insert
//Trie search
bool Trie::trie_search(std::string inputStr)
{
int length = inputStr.size();
if(length <= 0 || length > 32)
{
std::cout<<"trie_search: inputStr Error!"<< std::endl;
return false;
}
int index;
TrieNode*pNode = pRoot;
for(int i = 0; i < length; i++)
{
/*char A~Z put in 0~25 and char 0~9 put in 26~35*/
if(inputStr[i] >= 'A' && inputStr[i] <='Z')
{
index = inputStr[i] - 'A';
}else if(inputStr[i] >= '0' && inputStr[i] <= '9')
{
index = inputStr[i] - '0' + 26;
}else
{
std::cout<<"trie_search:Md5 input Error!"<<std::endl;
exit(0);
}
if(NULL == pNode->nextBranch[index])
return false;
else if(inputStr[i] == pNode->nextBranch[index]->word)
{
pNode = pNode->nextBranch[index];
}else
{
return false;
}
}//end for
return true;
}// end of Trie search
//printf Trie
//void Trie::dfs_printTrie(TrieNode* pNode)
//{
// if(NULL == pNode)
// {
// std::cout<<"dfs_printTrie: Trie input Error!"<< std::endl;
// return;
// }
//
// vQueue.push_back(pNode);
// //if(pNode->){}
//}
| true |
d7df9235f1f1202e98bf417c9c3a3e0b9e5aebbf | C++ | BomNk/HwRunAuto | /AnalogInput/AnalogInput.ino | UTF-8 | 3,938 | 2.859375 | 3 | [] | no_license | /*
Analog Input
Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED) connected to digital pin 13.
The amount of time the LED will be on and off depends on the value obtained
by analogRead().
The circuit:
- potentiometer
center pin of the potentiometer to the analog input 0
one side pin (either one) to ground
the other side pin to +5V
- LED
anode (long leg) attached to digital output 13
cathode (short leg) attached to ground
- Note: because most Arduinos have a built-in LED attached to pin 13 on the
board, the LED is optional.
created by David Cuartielles
modified 30 Aug 2011
By Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/AnalogInput
*/
#define USE_ARDUINO_INTERRUPTS true
//define PulseWire A0 // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h> // Includes the PulseSensorPlayground Library.
const byte interruptPin = 2;
volatile byte state = LOW;
//int PulseWire = 0; // select the input pin for the potentiometer
const int PulseWire = 0; // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13; // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;
PulseSensorPlayground pulseSensor;
// select the pin for the LED
int Motor1_INT1 = 4;// variable to storethe value coming from the sensor
int Motor1_INT2 = 5;
int Motor1_Enable = 3;
char speedMotor;
int count;
int myBPM;
//char ch;
void setup() {
// declare the ledPin as an OUTPUT:
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink,FALLING);
pinMode(Motor1_INT1,OUTPUT);
pinMode(Motor1_INT2,OUTPUT);
pinMode(Motor1_Enable,OUTPUT);
//pinMode(PulseWire,INPUT);
digitalWrite(Motor1_INT1,LOW);
digitalWrite(Motor1_INT2,LOW);
//digitalWrite(Motor1_Enable,50);
//pinMode(ledPin, OUTPUT);
Serial.begin(9600);
pulseSensor.analogInput(PulseWire);
pulseSensor.blinkOnPulse(LED13); //auto-magically blink Arduino's LED with heartbeat.
pulseSensor.setThreshold(Threshold);
// Double-check the "pulseSensor" object was created and "began" seeing a signal.
if (pulseSensor.begin()) {
//Serial.println("We created a pulseSensor Object !"); //This prints one time at Arduino power-up, or on Arduino reset.
}
speedMotor = 'S';
count = 0;
myBPM =0;
}
void loop() {
speedMotor = Serial.read();
myBPM = pulseSensor.getBeatsPerMinute();
if (pulseSensor.sawStartOfBeat()) { // Constantly test to see if "a beat happened".
//Serial.println("♥ A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
//Serial.print("BPM: "); // Print phrase "BPM: "
Serial.print(myBPM); // Print the value inside of myBPM.
}
else{
Serial.print(myBPM);
}
Serial.print("/");
if(state == 1){
state = 0;
count = count + 1;
delay(20);
}
Serial.println(count);
//ch = Serial.read();
//data_input = digitalRead(Pro_input);
//sensorValue = analogRead(sensorPin);
//Serial.println(data_input);
//Serial.println(sensorValue,DEC);
motorA(speedMotor);
//analogWrite(Motor1_Enable,sensorValue);
delay(40);
}
void motorA(char ch){
digitalWrite(Motor1_INT1,HIGH);
digitalWrite(Motor1_INT2,LOW);
if(ch == '0'){
analogWrite(Motor1_Enable,0);
}
if(ch == '1'){
analogWrite(Motor1_Enable,50);
}
if(ch == '2'){
analogWrite(Motor1_Enable,100);
}
if(ch == '3'){
analogWrite(Motor1_Enable,150);
}
if(ch == '4'){
analogWrite(Motor1_Enable,200);
}
if(ch == '5'){
analogWrite(Motor1_Enable,250);
}
if(ch == 'S'){
analogWrite(Motor1_Enable,0);
count = 0;
myBPM = 0;
}
}
void blink() {
state = !state;
}
| true |
c278486a13be96064a64faaef2810dd96586df76 | C++ | toolbox-and-snippets/breakout-board-libraries | /sensors/xbee-and-temperature/tempOverXBee.ino | UTF-8 | 1,619 | 3.0625 | 3 | [] | no_license |
#include <SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial xbee(2, 3); // RX, TX
char c = 'A';
int pingPong = 1;
int sensorAddress = 0x91 >> 1; // From datasheet sensor address is 0x91
// shift the address 1 bit right, the Wire library only needs the 7
// most significant bits for the address
byte msb;
byte lsb;
int temperature;
void setup() {
Serial.begin(9600);
Wire.begin();
Serial.println( "Arduino started sending bytes via XBee" );
// set the data rate for the SoftwareSerial port
xbee.begin( 9600 );
}
void loop() {
Wire.requestFrom(sensorAddress,2);
if (2 <= Wire.available()) // if two bytes were received
{
msb = Wire.read(); // receive high byte (full degrees)
lsb = Wire.read(); // receive low byte (fraction degrees)
temperature = ((msb) << 4); // MSB
temperature |= (lsb >> 4); // LSB
Serial.print("Temperature: ");
xbee.print( temperature*0.0625 );
xbee.print( '\t');
Serial.println(temperature*0.0625);
}
delay(500); // wait for half a s
// send character via XBee to other XBee connected to Mac
// via USB cable
//--- display the character just sent on console ---
Serial.println( c );
//--- get the next letter in the alphabet, and reset to ---
//--- 'A' once we have reached 'Z'.
c = c + 1;
if ( c>'Z' )
c = 'A';
//--- switch LED on Arduino board every character sent---
if ( pingPong == 0 )
digitalWrite(13, LOW);
else
digitalWrite(13, HIGH);
pingPong = 1 - pingPong;
delay( 1000 );
}
| true |
2120579600cd6ec13d1ba226600bf55433a12c23 | C++ | liaobnb/Byteme | /leetcode/p31.cpp | UTF-8 | 1,581 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define mst(x, y) memset(x, y, sizeof(x))
#define fora(e, c) for (auto &e : c)
#define fori(i, a, b) for (int i=(a); i<(b); ++i)
#define ford(i, a, b) for (int i=(a); i>(b); --i)
#define pvi(x) fora(a, x) cout << a << " "; cout << endl
#define par(x, n) fori(a, 0, n) cout << x[a] << " "; cout << endl
#define output(ix, val) cout << "Case #" << (ix) << ": " << (val) << endl
#define trace(...) _f(#__VA_ARGS__, __VA_ARGS__)
template <typename T>
void _f(const char* name, T&& arg) {
cout << name << ": " << arg << endl;
}
template <typename T, typename... Args>
void _f(const char* names, T&& arg, Args&&... args) {
const char* split = strchr(names + 1, ',');
cout.write(names, split - names) << ": " << arg << " |";
_f(split, args...);
}
#define vi vector<int>
class Solution {
public:
void nextPermutation(vector<int>& aa) {
int n = aa.size();
int mi;
for (int i = n - 2; i >= 0; --i) {
if (aa[i] < aa[i + 1]) {
int mi = i + 1;
for (int j = i + 2; j < n; ++j)
if (aa[i] < aa[j] && aa[j] < aa[mi])
mi = j;
swap(aa[i], aa[mi]);
sort(aa.begin() + i + 1, aa.end());
return;
}
}
sort(aa.begin(), aa.end());
}
};
void test(vi aa) {
Solution go;
go.nextPermutation(aa);
pvi(aa);
}
int main() {
test({1, 2, 3});
test({3, 2, 1});
test({1, 1, 5});
return 0;
}
| true |
a3e403ea1e1d895104d9be90ee9b4bef8fb7abac | C++ | djpeach/DIY-Arcade-Cabinet | /menu/menu/State_Alert.cpp | UTF-8 | 2,904 | 2.8125 | 3 | [] | no_license | #include "State_Alert.hpp"
#include "SharedContext.hpp"
#include <string>
#include "stdlib.h"
State_Alert::State_Alert(SharedContext * ctx) : State_Base(ctx) {
setTransparent(true);
}
State_Alert::~State_Alert() {}
void State_Alert::onCreate() {
sf::Vector2u windowSize = ctx->window->getRenderWindow()->getSize();
alertBox.setSize(sf::Vector2f(windowSize.x * .8 , windowSize.y * .8 ));
alertBox.setFillColor(sf::Color(50, 50, 50));
alertBox.setOutlineColor(sf::Color(240, 20, 20));
alertBox.setOutlineThickness(10);
sf::Vector2f alertBoxSize = alertBox.getSize();
alertBox.setOrigin(alertBoxSize.x / 2, alertBoxSize.y / 2);
alertBox.setPosition(windowSize.x / 2, windowSize.y / 2);
ctx->eventManager->addCallback(StateType::Alert, "player1Go", &State_Alert::backToMenu, this);
ctx->eventManager->addCallback(StateType::Alert, "player2Go", &State_Alert::backToMenu, this);
ctx->eventManager->addCallback(StateType::Alert, "slashClose", &State_Alert::backToMenu, this);
}
void State_Alert::onDestroy() {
ctx->eventManager->removeCallback(StateType::Alert, "player1Go");
ctx->eventManager->removeCallback(StateType::Alert, "player2Go");
ctx->eventManager->removeCallback(StateType::Alert, "slashClose");
}
void State_Alert::activate() {
}
void State_Alert::deactivate() {}
void State_Alert::update(const sf::Time & delta) {}
void State_Alert::draw() {
sf::Vector2u windowSize = ctx->window->getRenderWindow()->getSize();
sf::RectangleShape rect(sf::Vector2f(windowSize.x, windowSize.y));
rect.setFillColor(sf::Color(0, 0, 0, 200));
ctx->window->getRenderWindow()->draw(rect);
ctx->window->getRenderWindow()->draw(alertBox);
sf::Font font;
if (!font.loadFromFile("assets/fonts/arial.ttf")) {
std::cerr << "Could not load font from assets/fonts/arial.ttf" << std::endl;
exit(1);
}
sf::Text text;
text.setString(this->string);
text.setFont(font);
text.setCharacterSize(35);
text.setOrigin(text.getGlobalBounds().width / 2, text.getGlobalBounds().height / 2);
text.setPosition(alertBox.getPosition().x, alertBox.getPosition().y - (50 * this->showBack));
ctx->window->getRenderWindow()->draw(text);
if (this->showBack) {
text.setString("Press the Control Button to go back to the menu");
text.setFont(font);
text.setCharacterSize(35);
text.setOrigin(text.getGlobalBounds().width / 2, text.getGlobalBounds().height / 2);
text.setPosition(alertBox.getPosition().x, alertBox.getPosition().y + 50);
ctx->window->getRenderWindow()->draw(text);
}
}
void State_Alert::setString(std::string string) {
this->string = string;
}
void State_Alert::setShowBack(bool showBack) {
this->showBack = showBack;
}
void State_Alert::backToMenu(BindingDetails * details) {
ctx->stateMachine->changeState(StateType::DIYACMenu);
}
| true |
a682229ce7f1ff3acda4e5a9966f6cb80fd25c9d | C++ | rlt3/Evolving | /Segment.hpp | UTF-8 | 4,796 | 2.953125 | 3 | [] | no_license | #pragma once
#include <cstdlib>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <assert.h>
#include <unistd.h>
#include <ucontext.h>
#include <stdint.h>
/* entry function into the assembly */
typedef void (*assembly) (void *addr);
typedef void (*segment_sig_handler) (int, siginfo_t*, void*);
/*
* Create and manage a memory segment that is both executable and writable with
* signal handlers to prevent the segment from crashing the program.
*/
class Segment {
public:
/*
* Starting and ending addresses of currently executing segment. This allow
* for signal handling multiple executable segment objects, but only in a
* single-threaded environment. Would need to upgrade this data-structure
* to allow for multiple threads with signal handling.
*/
static uint64_t addr_beg;
static uint64_t addr_end;
/*
* By default, the length of a segment is the length of a page size because
* executable memory must be page aligned. Next step (if needed) is to have
* a constructor which defines multiples of the pagesize as the length.
*/
Segment ()
: seg_len(getpagesize())
{
seg = mmap(NULL, seg_len,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_ANONYMOUS | MAP_PRIVATE,
0, 0);
if (!seg) {
perror(strerror(errno));
exit(1);
}
Segment::set_signal_handler((void*) Segment::signal_handler);
}
/* Reset the signal handler to its default actions */
~Segment ()
{
Segment::set_signal_handler((void*) SIG_DFL);
}
/* Set memory segment to WRITE and write to it, clearing it first */
void
write (uint8_t *bytes, uint32_t length)
{
Segment::set_prot(seg, seg_len, PROT_WRITE);
memset(seg, 0, seg_len);
memcpy(seg, bytes, length);
}
/* Set memory segment to EXEC and execute */
void
exec (void *data)
{
Segment::set_prot(seg, seg_len, PROT_EXEC);
Segment::addr_beg = (uint64_t) seg;
Segment::addr_end = addr_beg + seg_len;
assembly func = (assembly) seg;
func(data);
Segment::addr_beg = 0;
Segment::addr_end = 0;
}
/* Write a nop slide to safely exit the malformed assembly section */
static void
signal_handler (int sig, siginfo_t *info, void *u)
{
ucontext_t *context = (ucontext_t*) u;
/*
* struct mcontext_t is machine dependent and opaque on purpose. It is
* used for restoring the context and we could increment the REG_RIP
* value and that would skip to the next instruction (but that could be
* bad). We instead use it to know if the faulting instruction is in
* the expected location.
*/
uint64_t fault_addr = context->uc_mcontext.gregs[REG_RIP];
uint32_t len = Segment::addr_end - Segment::addr_beg;
uint8_t *seg = (uint8_t *) Segment::addr_beg;
assert((sig == SIGSEGV || sig == SIGILL));
/*
* If the signal is a real one (not caused by our mutation memory
* segment) then remove the handler and return, letting the program's
* instruction raise the signal again naturally.
*/
if (fault_addr < Segment::addr_beg || fault_addr > Segment::addr_end) {
Segment::set_signal_handler((void*) SIG_DFL);
return;
}
printf("caught signal %d at %p. bad memory address %p. virt %p\n",
sig, (void*) fault_addr, info->si_call_addr, (void*) Segment::addr_beg);
assert(seg && len > 0);
Segment::set_prot(seg, len, PROT_WRITE);
/* write nops for the entire buffer */
memset(seg, 0x90, len);
/* ret instruction for last byte */
seg[len - 1] = 0xc3;
Segment::set_prot(seg, len, PROT_EXEC);
}
protected:
static void
set_prot (void* seg, const uint32_t len, const uint32_t protections)
{
if (mprotect(seg, len, protections | PROT_READ) < 0) {
perror(strerror(errno));
exit(1);
}
}
static void
set_signal_handler (void *handler)
{
/* Catch segfault and sigill signals */
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = (segment_sig_handler) handler;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGILL, &sa, NULL);
}
/* number of bytes allocated for the executable memory */
uint32_t seg_len;
/* location of executable memory */
void *seg;
};
uint64_t Segment::addr_beg = 0;
uint64_t Segment::addr_end = 0;
| true |
241f65e19812281218f6d0d6f639efabdc1d5863 | C++ | yisenFangW/leetcode | /1011. 在 D 天内送达包裹的能力.cpp | UTF-8 | 1,997 | 3.609375 | 4 | [] | no_license | 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
示例 1:
输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
输出:15
解释:
船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
第 1 天:1, 2, 3, 4, 5
第 2 天:6, 7
第 3 天:8
第 4 天:9
第 5 天:10
请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
示例 2:
输入:weights = [3,2,2,4,1,4], D = 3
输出:6
解释:
船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示:
第 1 天:3, 2
第 2 天:2, 4
第 3 天:1, 4
示例 3:
输入:weights = [1,2,3,1,1], D = 4
输出:3
解释:
第 1 天:1
第 2 天:2
第 3 天:3
第 4 天:1, 1
提示:
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500
//题目开始没思路,看了题解才有些思路:
//最低承运能力,肯定是在max和accumulate之间的,二分取值,用贪心法试,找出天数<=D,切承运量最低的数值;
int shipWithinDays(vector<int> &weights, int D) {
int left = *max_element(weights.begin(), weights.end());
int right = accumulate(weights.begin(), weights.end(), 0);
while (left < right) {
int mid = left + ((right - left) >> 1);
int day = 1, count = 0;
for (int i = 0; i < weights.size(); ++i) {
count += weights[i];
if(count > mid){
day++;
count = weights[i];
}
}
if(day > D)
left = mid +1;
else
right = mid;
}
return right;
}
| true |
6e4b54965d62fa6493e6dbb4ee482287581847ad | C++ | richrosenthal/CPlusPlus-Exercises | /exercise4/main.cpp | UTF-8 | 1,237 | 3.265625 | 3 | [
"MIT"
] | permissive | /*
Author Richard Rosenthal
Date 1-6-21 */
#include <iostream>
using namespace std;
const int amountOfDaysValid = 30;
const double salesTax = 0.06;
const int smallRoom = 50;
const int largeRoom = 75;
double totalAmount;
int amountOfSmallRooms;
int amountOfLargeRooms;
int main() {
cout << "Welcome to Ricky's Carpet Cleaning Business" << endl;
cout << endl;
cout << "How many small rooms do you want cleaned?" << endl;
cin >> amountOfSmallRooms;
cout << "How many large rooms do you want cleaned?" << endl;
cin >> amountOfLargeRooms;
cout << "Charges: " << endl;
cout << "Amount of Small Rooms :" << amountOfSmallRooms << endl;
cout << "Amount of Large Rooms :" << amountOfLargeRooms << endl;
cout << "Price per Small Room $" << smallRoom << endl;
cout << "Price per Large Room $" << largeRoom << endl;
totalAmount = (smallRoom * amountOfSmallRooms) + (largeRoom * amountOfLargeRooms);
cout << "Cost $" << totalAmount << endl;
cout << "Tax $" << salesTax << endl;
cout << "==============================" << endl;
cout << "Total Estimate: $" << (totalAmount * salesTax) + totalAmount << endl;
cout << "Valid for " << amountOfDaysValid << "days" << endl;
return 0;
}
| true |
14381c5e02cfc897a3ca9cc2357ac66e28e6e588 | C++ | santospandey/CLRS_Implement | /DataStructure/Stack/stack.cpp | UTF-8 | 1,212 | 4 | 4 | [] | no_license | #include <iostream>
template <typename T>
class Stack
{
private:
int limit;
T *arr;
int top;
public:
Stack()
{
top = -1;
limit = 10;
arr = new T[limit];
};
Stack(int limit)
{
top = -1;
this->limit = limit;
arr = new T[limit];
};
bool isEmpty() const
{
return (top == -1);
};
bool isFull() const
{
return (top == limit - 1);
};
void push(T elem)
{
if (!isFull())
{
arr[++top] = elem;
}
else
{
std::cout << "Array is full" << std::endl;
}
};
T pop()
{
if (!isEmpty())
{
int elem = arr[top];
top = top - 1;
return elem;
}
else
{
std::cout << "Array is empty" << std::endl;
return -1;
}
};
void printElements() const
{
std::cout << "Elements are :" << std::endl;
for (int i = 0; i <= top; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
};
~Stack()
{
delete[] arr;
};
}; | true |
ac9912bacc815763ef07cd11ea391fcf2b1bf39a | C++ | Team846/code-2014 | /ScrubMonkey/Brain/Events/JoystickHeldEvent.h | UTF-8 | 560 | 2.59375 | 3 | [] | no_license | #ifndef JOYSTICK_HELD_EVENT_H_
#define JOYSTICK_HELD_EVENT_H_
#include "DelayedEvent.h"
#include "../../DriverStation/DebouncedJoystick.h"
#include "JoystickPressedEvent.h"
/*!
* @brief Event that fires when a joystick button is held.
*/
class JoystickHeldEvent : public DelayedEvent
{
public:
JoystickHeldEvent(DebouncedJoystick* joystick, int button, int cycles);
virtual ~JoystickHeldEvent();
int GetButton();
DebouncedJoystick* GetJoystick();
private:
DebouncedJoystick* m_joystick;
int m_lastFiredButton;
};
#endif
| true |
0c56c626a53dd8d39dbaa278db7478bd2461802f | C++ | ZJUZWT/CGProject | /old_ver/demo/Water.h | UTF-8 | 5,925 | 3 | 3 | [] | no_license | #pragma once
#include "ViewObject.h"
class WaterPlane : public ViewObject{
public:
enum { WaterVAO, WaterMeshVAO, WaterNumVAO };
enum { WaterArrayBuffer, WaterElementBuffer, WaterMeshElementBuffer, WaterNumBuffer };
GLuint VAOs[WaterNumVAO];
GLuint Buffers[WaterNumBuffer];
GLuint Program;
GLuint ProgramMesh;
GLuint gBufferProgram;
GLuint numTri;
public:
WaterPlane() {}
WaterPlane(GLfloat x1, GLfloat z1, GLfloat x2, GLfloat z2, GLfloat y, GLuint xDivNum, GLuint zDivNum) : numTri(xDivNum* zDivNum * 2) {
GLfloat* point = new GLfloat[(xDivNum + 1) * (zDivNum + 1) * 3];
GLuint* index = new GLuint[3 * 2 * xDivNum * zDivNum];
GLuint* indexLine = new GLuint[3 * 2 * xDivNum * zDivNum];
for (int i = 0; i <= xDivNum; i++)
for (int j = 0; j <= zDivNum; j++) {
point[(i + j * (xDivNum + 1)) * 3 + 0] = (x2 - x1) * i / xDivNum + x1;
point[(i + j * (xDivNum + 1)) * 3 + 1] = y;
point[(i + j * (xDivNum + 1)) * 3 + 2] = (z2 - z1) * j / zDivNum + z1;
}
for (int i = 0; i < xDivNum; i++)
for (int j = 0; j < zDivNum; j++) {
index[(i + j * xDivNum) * 6 + 0] = i + j * (xDivNum + 1);
index[(i + j * xDivNum) * 6 + 1] = i + (j + 1) * (xDivNum + 1);
index[(i + j * xDivNum) * 6 + 2] = i + 1 + j * (xDivNum + 1);
index[(i + j * xDivNum) * 6 + 3] = i + 1 + j * (xDivNum + 1);
index[(i + j * xDivNum) * 6 + 4] = i + (j + 1) * (xDivNum + 1);
index[(i + j * xDivNum) * 6 + 5] = i + 1 + (j + 1) * (xDivNum + 1);
}
for (int i = 0; i < xDivNum; i++)
for (int j = 0; j < zDivNum; j++) {
indexLine[(i + j * xDivNum) * 6 + 0] = i + 1 + (j + 1) * (xDivNum + 1);
indexLine[(i + j * xDivNum) * 6 + 1] = i + 1 + j * (xDivNum + 1);
indexLine[(i + j * xDivNum) * 6 + 2] = i + 1 + (j + 1) * (xDivNum + 1);
indexLine[(i + j * xDivNum) * 6 + 3] = i + (j + 1) * (xDivNum + 1);
indexLine[(i + j * xDivNum) * 6 + 4] = i + 1 + (j + 1) * (xDivNum + 1);
indexLine[(i + j * xDivNum) * 6 + 5] = i + j * (xDivNum + 1);
}
glGenVertexArrays(WaterNumVAO, VAOs);
glCreateBuffers(WaterNumBuffer, Buffers);
glNamedBufferStorage(Buffers[WaterArrayBuffer], (xDivNum + 1) * (zDivNum + 1) * 3 * sizeof(GLfloat), point, 0);
glNamedBufferStorage(Buffers[WaterElementBuffer], 3 * 2 * xDivNum * zDivNum * sizeof(GLuint), index, 0);
glNamedBufferStorage(Buffers[WaterMeshElementBuffer], 3 * 2 * xDivNum * zDivNum * sizeof(GLuint), indexLine, 0);
glBindVertexArray(VAOs[WaterVAO]);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[WaterArrayBuffer]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[WaterElementBuffer]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GL_FLOAT), 0);
glEnableVertexAttribArray(0);
Program = glCreateProgram();
ShaderInfo shaders[] = {
{GL_VERTEX_SHADER,"waterV.shader"} ,
{GL_FRAGMENT_SHADER,"waterF.shader"} ,
{GL_NONE,""} };
for (int i = 0; shaders[i].mode != GL_NONE; i++) {
GLuint shader = LoadShader(shaders[i]);
glAttachShader(Program, shader);
}
glLinkProgram(Program);
glBindVertexArray(VAOs[WaterMeshVAO]);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[WaterArrayBuffer]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[WaterMeshElementBuffer]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GL_FLOAT), 0);
glEnableVertexAttribArray(0);
ProgramMesh = glCreateProgram();
ShaderInfo shadersMesh[] = {
{GL_VERTEX_SHADER,"gBufferWaterV.shader"} ,
{GL_FRAGMENT_SHADER,"WaterMeshF.shader"} ,
{GL_NONE,""} };
for (int i = 0; shadersMesh[i].mode != GL_NONE; i++) {
GLuint shader = LoadShader(shadersMesh[i]);
glAttachShader(ProgramMesh, shader);
}
glLinkProgram(ProgramMesh);
gBufferProgram = glCreateProgram();
ShaderInfo shadersGBuffer[] = {
{GL_VERTEX_SHADER,"gBufferWaterV.shader"} ,
{GL_FRAGMENT_SHADER,"gBufferWaterF.shader"} ,
{GL_NONE,""} };
for (int i = 0; shadersGBuffer[i].mode != GL_NONE; i++) {
GLuint shader = LoadShader(shadersGBuffer[i]);
glAttachShader(gBufferProgram, shader);
}
glLinkProgram(gBufferProgram);
}
void gBufferRender(glm::mat4 uniV, glm::mat4 uniP, float uniTime) {
glUseProgram(gBufferProgram);
GLint location;
location = glGetUniformLocation(gBufferProgram, "uniV");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(uniV));
location = glGetUniformLocation(gBufferProgram, "uniP");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(uniP));
location = glGetUniformLocation(gBufferProgram, "uniTime");
glUniform1f(location, uniTime);
glBindVertexArray(this->VAOs[WaterVAO]);
glDrawElements(GL_TRIANGLES, numTri * 3, GL_UNSIGNED_INT, 0);
glUseProgram(0);
}
void shadowBufferRender(GLuint program, glm::mat4 uniV, glm::mat4 uniP, float uniTime) {
GLint location;
glUseProgram(program);
location = glGetUniformLocation(program, "uniM");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(this->modelMat));
location = glGetUniformLocation(program, "uniV");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(uniV));
location = glGetUniformLocation(program, "uniP");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(uniP));
location = glGetUniformLocation(program, "uniTime");
glUniform1f(location, uniTime);
glBindVertexArray(this->VAOs[WaterVAO]);
glDrawElements(GL_TRIANGLES, numTri * 3, GL_UNSIGNED_INT, 0);
glUseProgram(0);
}
void oitRender(GLuint program, glm::mat4 uniV, glm::mat4 uniP, float uniTime) {
glUseProgram(program);
GLint location;
location = glGetUniformLocation(program, "uniV");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(uniV));
location = glGetUniformLocation(program, "uniP");
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(uniP));
location = glGetUniformLocation(program, "uniTime");
glUniform1f(location, uniTime);
glBindVertexArray(this->VAOs[WaterVAO]);
glDrawElements(GL_TRIANGLES, numTri * 3, GL_UNSIGNED_INT, 0);
glUseProgram(0);
}
}; | true |
6855829c792666cbcf2ee97e236253a148ffcfe6 | C++ | GoGitThat/algorithmns | /stack.cpp | UTF-8 | 1,070 | 3.953125 | 4 | [] | no_license | #include "structs.h"
#include <iostream>
using namespace std;
class Stack{
private:
node *head, *tail;
int size;
public:
Stack(){ // constructor
head=NULL;
tail=NULL;
size=0;
}
int Peek(){
if(head!=NULL){
return head->num;
}
return 0;
}
void Push(int x){
//create a temp node
node *temp = new node;
temp->num = x;
temp->next = NULL;
//first node in the stack
if(head==NULL){
head=temp;
tail=temp;
temp=NULL;
}else{
//nodes already exist in the stack
temp->next=head;
head=temp;
temp=NULL;
}
//increment size counter of stack
size++;
}
int Pop(){
//get head node
node *temp = new node;
temp = head;
//set new head node as next node of the previous head node
head = head->next;
//decrement size
size--;
return temp->num;
}
int getSize(){
return size;
}
void print(){
node* temp = head;
while(temp!=NULL){
cout << temp->num << "\n";
temp = temp->next;
}
}
};
| true |
d9b173d8d2b7d63339b42ee21e1112722cbe2653 | C++ | zhenyatos/OS_Labs_SPBPU_2020 | /Samutichev.Evgenii/lab2/core/sys_exception.h | UTF-8 | 330 | 2.65625 | 3 | [] | no_license | #ifndef MY_EXCEPTION_H_INCLUDED
#define MY_EXCEPTION_H_INCLUDED
#include <exception>
#include <string>
class SysException : public std::exception {
public:
SysException(const std::string& msg, int errnum);
const char* what() const noexcept override;
private:
std::string _msg;
};
#endif // MY_EXCEPTION_H_INCLUDED
| true |
a4f4074ae99a83c60022c4a178f508e38848f796 | C++ | WhiZTiM/coliru | /Archive2/f9/2eaa8eb327a97d/main.cpp | UTF-8 | 379 | 3.140625 | 3 | [] | no_license | #include<stdio.h>
int main(void)
{
int i;
int n;
int k;
int sum1;
int sum2;
do
{
printf("Zahl eingeben (0 fuer Ende): ");
scanf("%i\n",&k);
for(i>0; i=0; i++)
sum1=+i;
{
for(n<0; n=0; n++)
sum2=+n;
}
}while(k!=0);
printf("Anzahl positiver Zahlen: %i \n",i);
printf("Anzahl ngativer Zahlen: %i \n",n);
return 0;
} | true |
c9e7c1b58be6bce4f335be25b737bc02433064dd | C++ | Aaryan03/oop_lab2 | /problem statement 1.cpp | UTF-8 | 1,851 | 3.296875 | 3 | [] | no_license | /******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <iostream>
using namespace std;
int addition(int x, int y)
{
int s;
s = x +y;
cout << "The sum is: "<< s;
return s;
}
float addition(float x, float y)
{
float s;
s = x +y;
cout << "The sum is: "<< s;
return s;
}
double addition(double x, double y)
{
double s;
s = x +y;
cout << "The sum is: "<< s;
return s;
}
long double addition(long double x, long double y)
{
long double s;
s = x +y;
cout << "The sum is: "<< s;
return s;
}
long int addition(long int x,long int y)
{
long int s;
s = x +y;
cout << "The sum is: "<< s;
return s;
}
char addition(char x, char y)
{
char s;
s = x +y;
cout << "The sum is: "<< s;
return s;
}
int main() {
int a,b;
float c,d;
double e,f;
long double g,h;
long int i,j;
char k,l;
cout << "Enter first int: ";
cin >> a;
cout << "Enter second int: ";
cin >> b;
addition(a,b);
cout << "\n\nEnter first float: ";
cin >> c;
cout << "Enter second float: ";
cin >> d;
addition(c,d);
cout << "\n\nEnter first double: ";
cin >> e;
cout << "Enter second double: ";
cin >> f;
addition(e,f);
cout << "\n\nEnter first long double: ";
cin >> g;
cout << "Enter second long double: ";
cin >> h;
addition(g,h);
cout << "\n\nEnter first long int: ";
cin >> i;
cout << "Enter second long int: ";
cin >> j;
addition(i,j);
cout << "\n\nEnter first char: ";
cin >> k;
cout << "Enter second char: ";
cin >> l;
addition(k,l);
}
| true |
4ce73348a3936a1087be68ca617b3f47f7603c8b | C++ | lchristenson2/word-search | /lab_7/inc/BST.h | UTF-8 | 835 | 3.890625 | 4 | [] | no_license | #pragma once
#include <iostream>
struct BST {
long data;
BST* left;
BST* right;
};
void traverse(BST* root){
if (root != NULL){
traverse(root->left);
std::cout << root->data << std::endl;
traverse(root->right);
}
}
BST* insert(BST* root, long value){
if (root == NULL){
root = new BST();
root->data = value;
root->left = NULL;
root->right = NULL;
}
else{
if (value >= root->data){
// go right
root->right = insert(root->right, value);
}
else{
// go left
root->left = insert(root->left, value);
}
}
return root;
}
bool search (BST* root, long value){
if (root == NULL){
return false;
}
else{
if (root->data == value){
return true;
}
else{
if (value < root->data){
return search(root->left, value);
}
else{
return search(root->right, value);
}
}
}
}
| true |
84d1682f8805d171ad02bbabb0fa1df6bab874bb | C++ | larmel/JSmith | /src/generate/Expression/CallExpression.h | UTF-8 | 487 | 2.59375 | 3 | [] | no_license | #ifndef CALL_EXPRESSION_H
#define CALL_EXPRESSION_H
#include <iostream>
#include <cstdlib>
#include "Expression.h"
class FunctionVariable;
class Scope;
class CallExpression : public Expression {
private:
std::vector<Expression*> parameters;
public:
FunctionVariable *function;
CallExpression(Scope* parent_scope, int depth);
void print(std::ostream& out) const;
friend std::ostream& operator<<(std::ostream& out, const CallExpression& e);
};
#endif
| true |
4b9df6de73077688af30cfb53ed57f9aaa576d91 | C++ | amanat361/COMSC-110 | /Programs/averageHeight.cpp | UTF-8 | 2,577 | 3.671875 | 4 | [] | no_license | //Objective: Find the average height of everyone in the room.
//Name: Samin Amanat
//Course: COMSC-110-1021
//Compiler: TDM MinGW
//Editor: MS NotePad
//libraries
#include <iostream>
using namespace std;
//Programmer defined data types
//NONE
//Special compiler dependent definitions
//NONE
//global constants/variables
//NONE
//Programmer defined functions
//NONE
//main program
int main()
{
//Data
double height; //each person's height in inches (21.5 inches - 99 inches are valid values)
int count = 0; //number of people in the room
double sum = 0; //sum of all heights
int averageHeight; //average height of all the people in the room
int feet; //when converting average height to feet, this holds the whole number of feet
int inches; //when converting average height to feet, this holds the remainder of inches
char peopleLeft; //either Y or N to see if any people are left in the room
//Introduction
cout << "Objective: This program will serve as a template for all programs\n written in this course.\n";
cout << "Programmer: Samin Amanat\n";
cout << "Editor(s) used: Notepad\n";
cout << "Compiler(s) used: TDM MinGW\n";
cout << "File: " << __FILE__ << endl;
cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl;
cout << "Instructions: Please answer the prompts about each person's height." << endl << endl;
//Start loop asking for people's height, do until there are no more people
do
{
//Ask again if value is not between 21.5 inches and 99 inches
do
{
//Ask for people's height
cout << "What is a height in inches [21.5 - 99]: ";
cin >> height;
cin.ignore(1000, 10);
//Error message
if (!(height >= 21.5 && height <= 99))
{
cout << "That is an invalid height. Height must be in inches and between 21.5 inches and 99 inches." << endl;
}
} while (!(height >= 21.5 && height <= 99)); //Input validation
//Add height to sum
sum = sum + height;
//Add one to count
count = count + 1;
//Ask of there are any people left in the room
cout << "Are there more people to count? [Y/N]: ";
cin >> peopleLeft;
cin.ignore(1000, 10);
} while (peopleLeft == 'Y' || peopleLeft == 'y'); //loop as long as there are people left in room
//Calculate average height of all the people
averageHeight = sum / count;
//Convert average height to feet
feet = averageHeight / 12;
inches = averageHeight % 12;
//Output the average height
cout << "The average height is " << feet << "'" << inches << "\"" << endl;
}//main | true |
2d78d22b29ecb241e974ea20fb73a95786b5b715 | C++ | raghuveersagar/Hackathonhelpers | /C++/Priority_Queue.cpp | UTF-8 | 2,573 | 3.46875 | 3 | [] | no_license | #include<vector>
#include<string>
#include<memory>
#include<fstream>
#include<iostream>
#include<map>
#include<algorithm>
#include <stdlib.h>
using namespace std;
/*
Data type representing the heap
*/
template<class T>
struct heap
{
vector<T> arr;
int heapsize;
int length;
heap(vector<T> v) :
arr(v), heapsize(0), length(v.size()) {
}
};
/*
Data type representing each vertex in the graph
*/
struct vertex
{
vertex(int d, vertex * p, string v, int pos) :distance(d), parent(p), value(v), heap_position(pos){
}
int distance;
vertex* parent;
string value;
int heap_position;
bool operator>(const vertex& v1)
{
return this->distance > v1.distance;
}
};
ostream& operator<<(ostream& os, heap<vertex*>& h)
{
vector<vertex*>& arr = h.arr;
for (int i = 0; i < h.heapsize; i++)
os << arr[i]->value << "(" << arr[i]->distance << "," << arr[i]->heap_position << ") ";
return os;
}
class priority_q
{
public:
heap<vertex*> h;
priority_q(vector<vertex*> v) :h(v){
h.heapsize = h.length;
buildMinHeap();
}
vertex* pop()
{
return extract_min();
}
vertex* top()
{
return h.arr[0];
}
bool empty()
{
return h.heapsize == 0;
}
void buildMinHeap() {
int length = h.length;
h.heapsize = h.length;
for (int i = (h.length - 1) / 2; i >= 0; i--)
minHeapify(i);
}
void minHeapify(int i) {
int right = 2 * i + 1;
int left = 2 * i + 2;
vector<vertex*> &arr = h.arr;
int smallest = -1;
if (left <= h.heapsize - 1 && (arr[i])->distance > (arr[left])->distance) {
smallest = left;
}
else {
smallest = i;
}
if (right <= h.heapsize - 1 && (arr[smallest])->distance > (arr[right])->distance) {
smallest = right;
}
if (smallest != i) {
exchange(arr, i, smallest);
minHeapify(smallest);
}
}
vertex* extract_min()
{
vertex* temp = h.arr[0];
vector<vertex*>& temp_arr = h.arr;
temp_arr[0] = temp_arr[h.heapsize - 1];
temp_arr[0]->heap_position = 0;
h.heapsize = h.heapsize - 1;
minHeapify(0);
return temp;
}
void print_heap()
{
cout << h << endl;
}
void exchange(vector<vertex*> &v, int a, int b) {
vertex* temp = v[a];
v[a] = v[b];
v[b] = temp;
int temp_pos = v[a]->heap_position;
v[a]->heap_position = v[b]->heap_position;
v[b]->heap_position = temp_pos;
}
void update_key(vertex* v)
{
int pos = v->heap_position;
vector<vertex*> &temp = (h.arr);
while (pos > 0 && temp[pos]->distance < temp[(pos - 1) / 2]->distance)
{
exchange(temp, pos, ((pos - 1) / 2));
pos = ((pos - 1) / 2);
}
}
}; | true |
92f74d14265b5058837eadb9fec9377a921d76eb | C++ | anudeepreddy/OS-Lab | /memorymanagement/MFT.cpp | UTF-8 | 2,173 | 3.09375 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct block{
int processId;
int spaceUsed;
int isNext;
};
int findBlocks(struct block memory[],int n,int noOfBlocks){
int count=0;
for(int i=0;i<noOfBlocks;i++){
if(memory[i].processId==0){
count++;
}
else{
count=0;
}
if(count==n){
return i-(n-1);
}
}
return -1;
}
int main(){
int noOfProcesses,TOTALDISKSPACE,AVAILABLEDISKSPACE,blockSize,noOfBlocks,processId,sizeOfProcess,requiredBlocks;
int internalFragmentation=0,externalFragmentation=0;
cout<<"Enter the Total Disk space:";
cin>>TOTALDISKSPACE;
AVAILABLEDISKSPACE = TOTALDISKSPACE;
cout<<"Enter the number of Blocks:";
cin>>noOfBlocks;
cout<<"Enter the number of Processes:";
cin>>noOfProcesses;
blockSize = TOTALDISKSPACE/noOfBlocks;
struct block memory[noOfBlocks];
for(int i=0;i<noOfBlocks;i++){
memory[i].processId=0;
memory[i].spaceUsed=0;
memory[i].isNext=0;
}
for(int i=0;i<noOfProcesses;i++){
cout<<"Enter the process Id and size of the process:";
cin>>processId>>sizeOfProcess;
if(sizeOfProcess%blockSize==0){
requiredBlocks=sizeOfProcess/blockSize;
}
else{
requiredBlocks=(sizeOfProcess/blockSize)+1;
}
int blockIndex;
blockIndex = findBlocks(memory,requiredBlocks,noOfBlocks);
if(blockIndex==-1 || sizeOfProcess>AVAILABLEDISKSPACE){
cout<<"Process cannot be allocated memory!!!\n";
}
else{
AVAILABLEDISKSPACE -= (blockSize*requiredBlocks);
if(sizeOfProcess%blockSize!=0)
internalFragmentation += blockSize-(sizeOfProcess%blockSize);
for(int j=blockIndex;j<blockIndex+requiredBlocks;j++){
if(j!=blockIndex+requiredBlocks-1){
memory[i].isNext=1;
memory[i].spaceUsed=blockSize;
}
else {
memory[i].spaceUsed=sizeOfProcess%blockSize;
}
memory[i].processId=processId;
}
}
}
cout<<"Total Disk space:"<<TOTALDISKSPACE;
cout<<"\nInternal Fragmentation:"<<internalFragmentation;
cout<<"\nExternal Fragmentation:"<<AVAILABLEDISKSPACE;
} | true |
0229903a5195b9c7253b92de1832d72676242746 | C++ | kambliambar25/SA | /C++/greater no using inline function.cpp | UTF-8 | 242 | 3.03125 | 3 | [] | no_license | #include<iostream>
using namespace std;
inline int max(int x,int y,int z)
{
return(x>y)?x:(y>z)?y:(x>z)?:z;
}
int main()
{
int a,b,c;
cout<<"Enter the no."<<endl;
cin>>a>>b>>c;
cout<<"Greater no:"<<max(a,b,c);
return 0;
}
| true |
90997338219c925489d1a825c82d726ff94c06de | C++ | aurodev/GPlay3D | /samples/examples/src/DynamicMesh.cpp | UTF-8 | 7,847 | 2.765625 | 3 | [] | no_license | #include "DynamicMesh.h"
#include "SamplesGame.h"
#if defined(ADD_SAMPLE)
ADD_SAMPLE("Graphics", "Dyanmic Mesh", DynamicMeshUpdate, 2);
#endif
struct PosColorVertex
{
Vector3 m_pos;
Vector3 m_normal;
Vector2 m_uv;
};
PosColorVertex vertices[] =
{
// position // normal // texcoord
{ Vector3(-1, -1, 1), Vector3( 0.0, 0.0, 1.0), Vector2(0.0, 0.0) },
{ Vector3( 1, -1, 1), Vector3( 0.0, 0.0, 1.0), Vector2(1.0, 0.0) },
{ Vector3(-1, 1, 1), Vector3( 0.0, 0.0, 1.0), Vector2(0.0, 1.0) },
{ Vector3( 1, 1, 1), Vector3( 0.0, 0.0, 1.0), Vector2(1.0, 1.0) },
{ Vector3(-1, 1, 1), Vector3( 0.0, 1.0, 0.0), Vector2(0.0, 0.0) },
{ Vector3( 1, 1, 1), Vector3( 0.0, 1.0, 0.0), Vector2(1.0, 0.0) },
{ Vector3(-1, 1, -1), Vector3( 0.0, 1.0, 0.0), Vector2(0.0, 1.0) },
{ Vector3( 1, 1, -1), Vector3( 0.0, 1.0, 0.0), Vector2(1.0, 1.0) },
{ Vector3(-1, 1, -1), Vector3( 0.0, 0.0, -1.0), Vector2(0.0, 0.0) },
{ Vector3( 1, 1, -1), Vector3( 0.0, 0.0, -1.0), Vector2(1.0, 0.0) },
{ Vector3(-1, -1, -1), Vector3( 0.0, 0.0, -1.0), Vector2(0.0, 1.0) },
{ Vector3( 1, -1, -1), Vector3( 0.0, 0.0, -1.0), Vector2(1.0, 1.0) },
{ Vector3(-1, -1, -1), Vector3( 0.0, -1.0, 0.0), Vector2(0.0, 0.0) },
{ Vector3( 1, -1, -1), Vector3( 0.0, -1.0, 0.0), Vector2(1.0, 0.0) },
{ Vector3(-1, -1, 1), Vector3( 0.0, -1.0, 0.0), Vector2(0.0, 1.0) },
{ Vector3( 1, -1, 1), Vector3( 0.0, -1.0, 0.0), Vector2(1.0, 1.0) },
{ Vector3( 1, -1, 1), Vector3( 1.0, 0.0, 0.0), Vector2(0.0, 0.0) },
{ Vector3( 1, -1, -1), Vector3( 1.0, 0.0, 0.0), Vector2(1.0, 0.0) },
{ Vector3( 1, 1, 1), Vector3( 1.0, 0.0, 0.0), Vector2(0.0, 1.0) },
{ Vector3( 1, 1, -1), Vector3( 1.0, 0.0, 0.0), Vector2(1.0, 1.0) },
{ Vector3(-1, -1, -1), Vector3( -1.0, 0.0, 0.0), Vector2(0.0, 0.0) },
{ Vector3(-1, -1, 1), Vector3( -1.0, 0.0, 0.0), Vector2(1.0, 0.0) },
{ Vector3(-1, 1, -1), Vector3( -1.0, 0.0, 0.0), Vector2(0.0, 1.0) },
{ Vector3(-1, 1, 1), Vector3( -1.0, 0.0, 0.0), Vector2(1.0, 1.0) }
};
static Mesh* createTexturedCube(float size = 1.0f)
{
/*short indices[] =
{
0, 1, 2,
2, 1, 3,
4, 5, 6,
6, 5, 7,
8, 9, 10,
10, 9, 11,
12, 13, 14,
14, 13, 15,
16, 17, 18,
18, 17, 19,
20, 21, 22,
22, 21, 23
};*/
unsigned int vertexCount = 24;
unsigned int indexCount = 36;
VertexFormat::Element elements[] =
{
VertexFormat::Element(VertexFormat::POSITION, 3),
VertexFormat::Element(VertexFormat::NORMAL, 3),
VertexFormat::Element(VertexFormat::TEXCOORD0, 2)
};
Mesh* mesh = Mesh::createMesh(VertexFormat(elements, 3), vertexCount, true);
if (mesh == NULL)
{
GP_ERROR("Failed to create mesh.");
return NULL;
}
mesh->setVertexData(0, 0, vertexCount);
MeshPart* meshPart = mesh->addPart(Mesh::TRIANGLES, Mesh::INDEX16, indexCount, true);
meshPart->setIndexData(0, 0, indexCount);
return mesh;
}
DynamicMeshUpdate::DynamicMeshUpdate()
: _font(NULL)
, _triangleModel(NULL)
, _cubeModel(NULL)
, _spinDirection(-1.0f)
{
}
void DynamicMeshUpdate::initialize()
{
// Create the font for drawing the framerate.
_font = Font::create("res/coredata/ui/arial.gpb");
// Create a perspective projection matrix.
Matrix projMatrix;
Matrix::createPerspective(45.0f, getWidth() / (float)getHeight(), 1.0f, 100.0f, &projMatrix);
// Create a lookat view matrix.
Matrix viewMatrix;
Matrix::createLookAt(Vector3(3,2,-5), Vector3::zero(), Vector3::unitY(), &viewMatrix);
// set mvp matrix
_worldViewProjectionMatrix = projMatrix * viewMatrix;
// Create a material
Material* material = Material::create("res/coredata/shaders/textured.vert", "res/coredata/shaders/textured.frag");
Texture::Sampler * sampler = Texture::Sampler::create("res/data/textures/brick.png");
material->getParameter("u_diffuseTexture")->setValue(sampler);
material->getParameter("u_worldViewProjectionMatrix")->setValue(_worldViewProjectionMatrix);
material->getStateBlock()->setCullFace(true);
material->getStateBlock()->setDepthTest(true);
material->getStateBlock()->setDepthWrite(true);
// Create a cube.
Mesh* meshQuad = createTexturedCube();
_cubeModel = Model::create(meshQuad);
_cubeModel->setMaterial(material);
SAFE_RELEASE(meshQuad);
}
void DynamicMeshUpdate::finalize()
{
SAFE_RELEASE(_cubeModel);
SAFE_RELEASE(_triangleModel);
SAFE_RELEASE(_font);
}
void DynamicMeshUpdate::update(float elapsedTime)
{
// Update the rotation of the cube.
float dt = elapsedTime * 0.001f;
float dx = _spinDirection * MATH_PI * 1.5f;
float dy = _spinDirection * MATH_PI * 1.2f;
float dz = _spinDirection * MATH_PI * 1.3f;
Quaternion rot = Quaternion(Vector3(dx, dy, dz), dt);
_worldViewProjectionMatrix.rotate(rot);
// Update vertex buffer.
float t = Game::getAbsoluteTime() * 0.001f;
float phase = t * 10.0f;
PosColorVertex * vbPtr = (PosColorVertex*)_cubeModel->getMesh()->mapVertexBuffer();
//VertexBuffer * vb = (VertexBuffer *)_cubeModel->getMesh()->getVertexBuffer();
//PosColorVertex * vbPtr = (PosColorVertex*)vb->lock(0, vb->getElementCount());
if(vbPtr)
{
unsigned int vertexCount = _cubeModel->getMesh()->getVertexCount();
for(int i=0; i<vertexCount; i++)
{
Vector3& src = vertices[i].m_pos;
Vector3& dest = vbPtr->m_pos;
dest.x = src.x * (1.0f + 0.12f * sin(phase));
dest.y = src.y * (1.0f + 0.15f * sin(phase + 60.0f));
dest.z = src.z * (1.0f + 0.08f * sin(phase + 120.0f));
vbPtr->m_normal = vertices[i].m_normal;
vbPtr->m_uv = vertices[i].m_uv;
vbPtr++;
}
}
//vb->unLock();
_cubeModel->getMesh()->unmapVertexBuffer();
// Update index buffer.
// Rewrite always the same, no interest, but only for testing
unsigned short * ibPtr = (unsigned short *)_cubeModel->getMesh()->getPart(0)->mapIndexBuffer();
//IndexBuffer * ib = (IndexBuffer *)_cubeModel->getMesh()->getPart(0)->getIndexBuffer();
//unsigned short * ibPtr = (unsigned short *)ib->lock(0, ib->getElementCount());
if(ibPtr)
{
unsigned short indices[36] =
{
0, 1, 2,
2, 1, 3,
4, 5, 6,
6, 5, 7,
8, 9, 10,
10, 9, 11,
12, 13, 14,
14, 13, 15,
16, 17, 18,
18, 17, 19,
20, 21, 22,
22, 21, 23
};
memcpy(ibPtr, indices, sizeof(unsigned short) * 36);
}
//ib->unLock();
_cubeModel->getMesh()->getPart(0)->unmapIndexBuffer();
}
void DynamicMeshUpdate::render(float elapsedTime)
{
// draw the cube
_cubeModel->getMaterial()->getParameter("u_worldViewProjectionMatrix")->setValue(_worldViewProjectionMatrix);
_cubeModel->draw();
// draw frame rate
drawFrameRate(_font, Vector4(0, 0.5f, 1, 1), 5, 1, getFrameRate());
}
void DynamicMeshUpdate::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
switch (evt)
{
case Touch::TOUCH_PRESS:
// Reverse the spin direction if the user touches the screen.
_spinDirection *= -1.0f;
break;
case Touch::TOUCH_RELEASE:
break;
case Touch::TOUCH_MOVE:
break;
};
}
| true |
0b136c4d24b577e74a92b89050c2f9f01ba1ec01 | C++ | maz0005/inventory_project | /src/inventory.cpp | UTF-8 | 10,497 | 3.015625 | 3 | [] | no_license | #include "../include/inventory.h"
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
bool FULL = 0; /*Set to 1 when inventory full*/
void Startup_Handler(const std::string &file_name_In, std::string &user_name_In, std::string &password_In, std::string &title_In, Dynamic_Array &inventory_numbers_In, std::vector<User_Item> &user_items_In, std::vector<Electronic> &electronic_items_In, std::vector<Furniture> &furniture_items_In,
std::vector<Clothing> &clothing_items_In, std::vector<Book> &book_items_In) {
std::string data[14]; /*Where data will be stored to instantiate objects*/
std::vector<std::string> misc_names;
std::vector<std::string> misc_values;
std::vector<std::string> materials;
std::vector<std::string> material_percentages;
std::string temp;
std::string temp2;
std::ifstream input_file;
input_file.open(file_name_In);
if(input_file.fail()) {
std::cout << "Error with file: inventory_file\n" << std::endl;
exit(1);
}
getline(input_file, temp);
if(!temp.compare("no_saved_data\0")) return; /*First boot up. No previously saved data.*/
if(temp.compare("end_username_password\0")) { /*Will return 0 if both equal. Means no username or password at this point in text file so won't enter*/
user_name_In = temp;
getline(input_file, password_In);
getline(input_file, temp); /*Remove 'end_username_password' from stream*/
}
getline(input_file, temp);
if(temp.compare("end_title\0")) { /*Will return 0 if no title at this point.*/
title_In = temp;
getline(input_file, temp); /*Remove 'end_title from stream'*/
}
/*Allocate memory for index numbers*/
getline(input_file, temp);
inventory_numbers_In.size = std::stod(temp, NULL);
if (inventory_numbers_In.size < 9999) { inventory_numbers_In.pointer = (bool *) malloc(sizeof(bool) * 10000); }
else { inventory_numbers_In.pointer = (bool *) malloc (sizeof(bool) * inventory_numbers_In.size); }
std::cout << "Loading system...\n" << std::endl;
getline(input_file, temp); /*Get inventory type*/
while(temp.compare("end_all_items\0")) { /*Check if there are any more items*/
if (!temp.compare("User Item\0")) { /*Check if user created a specific item*/
getline(input_file, data[0]); /*Get inventory number*/
inventory_numbers_In.pointer[std::stoul(data[0], NULL)] = true;
getline(input_file, temp2);
do {
misc_names.push_back(temp2);
getline(input_file, temp2); /*Get corresponding value*/
misc_values.push_back(temp2);
getline(input_file, temp2);
} while(temp2.compare("end_user_item\0"));
User_Item item = User_Item(temp, misc_names, misc_values);
user_items_In.push_back(item);
misc_names.clear();
misc_values.clear();
}
else { /*Check if item is one of the hardcoded items*/
data[0] = temp;
for (int i = 1; i < 7; i++) getline(input_file, data[i]); /*Get common members amongst all objects*/
inventory_numbers_In.pointer[stoul(data[1], NULL)] = true; /*Set index as taken*/
if (!temp.compare("Electronic\0")) {
for (int i = 7; i < 10; i++) getline(input_file, data[i]);
Electronic item = Electronic(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9]);
electronic_items_In.push_back(item);
}
else if (!temp.compare("Book\0")) {
for (int i = 7; i < 12; i++) getline(input_file, data[i]);
Book item = Book(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11]);
book_items_In.push_back(item);
}
else if (!temp.compare("Furniture\0")) {
for (int i = 7; i < 14; i++) getline(input_file, data[i]);
Furniture item = Furniture(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13]);
furniture_items_In.push_back(item);
}
else if (!temp.compare("Clothing\0")) {
for (int i = 7; i < 12; i++) getline(input_file, data[i]);
getline(input_file, temp);
while(temp.compare("end_materials\0")) {
materials.push_back(temp);
getline(input_file, temp);
material_percentages.push_back(temp);
getline(input_file, temp);
}
Clothing item = Clothing(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], materials, material_percentages);
clothing_items_In.push_back(item);
materials.clear();
material_percentages.clear();
}
}
getline(input_file, temp);
}
input_file.close();
std::cout << "Bootup successful\n" << std::endl;
for (int i = 0; i < 10000; i++); /*Make sure file closes before returning*/
}
void Display_Menu(DISPLAY_OPTION option_In) {
switch (option_In) {
case MAIN_MENU:
std::cout << "*****************************************************************************************************************\n"
<< "* Main Menu *\n"
<< "*****************************************************************************************************************\n"
<< "(1) View/Edit Inventory\n"
<< "(2) Manage Acceptable Items\n"
<< "(3) Change Username/Password\n"
<< "(4) Change Company Name\n"
<< "(5) Exit" << std::endl;
break;
case INVENTORY:
std::cout << "*****************************************************************************************************************\n"
<< "* Inventory Page *\n"
<< "*****************************************************************************************************************\n"
<< "(1) Display Entire Inventor\n"
<< "(2) Display by Option\n"
<< "(3) Manage Prices\n"
<< "(4) Add to Inventory\n"
<< "(5) Remove from Inventory\n"
<< "(6) Return to Main Menu\n" << std::endl;
break;
case INV_OPTION:
std::cout << "*****************************************************************************************************************\n"
<< "* Inventory Page *\n"
<< "***************************************************************************************************************\n"
<< "(1) Keyword\n"
<< "(2) Category\n"
<< "(3) Brand\n"
<< "(4) Inventory Number\n"
<< "(5) Go Back\n" << std::endl;
break;
case ACCEPTABLE:
std::cout << "*****************************************************************************************************************\n"
<< "* Acceptable Items Page *\n"
<< "*****************************************************************************************************************\n"
<< "(1) Display Acceptable Items"
<< "(2) Add Acceptable Items"
<< "(3) Remove Acceptable Items"
<< "(4) Return to Main Menu" << std::endl;
break;
default:
break;
}
}
void Display_Inventory(DISPLAY_FILTER filter_In) {
}
void Manage_Inventory(void) {
}
void Change_User_Password(void) {
}
void Manage_Acc_Items(void) {
}
unsigned long int New_Inv_Number(Dynamic_Array array_In) {
unsigned long int previous_size = array_In.size; /*More space now available. Hold next available number to return*/
for(unsigned long int i = 0; i < (array_In.size - 1); i++) { /*Find next available inventory number*/
if (!array_In.pointer[i]) {
array_In.pointer[i] = true;
return i; /*Return inventory number*/
}
}
/*No number available. Allocate more memory*/
try {
array_In.pointer = (bool *) realloc(array_In.pointer, (sizeof(bool) * (array_In.size * 2))); /*Double the size*/
array_In.size = array_In.size * 2;
}
catch (...) {
std::cout << "Error allocating more memory for inventory numbers. Program terminating" << std::endl;
exit(0);
}
return previous_size;
}
void Save_System(void){
}
int getch() {
int ch;
struct termios t_old, t_new;
tcgetattr(STDIN_FILENO, &t_old);
t_new = t_old;
t_new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &t_new);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &t_old);
return ch;
}
std::string getpass(const char *prompt, bool show_asterisk=true)
{
const char BACKSPACE = 127;
const char RETURN = 10;
std::string password;
unsigned char ch = 0;
std::cout << prompt;
while((ch=getch())!=RETURN)
{
if(ch == BACKSPACE)
{
if(password.length()!=0)
{
if(show_asterisk)
std::cout <<"\b \b";
password.resize(password.length()-1);
}
}
else
{
password += ch;
if(show_asterisk)
std::cout <<'*';
}
}
std::cout << std::endl;
return password;
}
void Login_Handler(const std::string &file_name_In) {
std::ifstream input_file;
input_file.open(file_name_In);
if(input_file.fail()) {
std::cout << "Error with file: inventory_file\n" << std::endl;
exit(1);
}
std::string user_name;
std::string password;
std::getline(input_file, user_name);
if(!user_name.compare("end_username_password")) return; /*No login required. Else continue*/
std::getline(input_file, password);
std::string user_name_2;
std::string password_2;
while(1) {
user_name_2.clear();
password_2.clear();
std::cout << "Username: ";
std::getline(std::cin, user_name_2);
password_2 = getpass("Password: ", true);
if ((user_name_2.compare(user_name)) | (password_2.compare(password))) std::cout << "Invalid user name or password" << std::endl;
else break;
}
input_file.close();
for (int i = 0; i < 10000; i++); /*Make sure file closes before returning*/
}
| true |
50354b65dd0b3243d327dcd11fdc2489e9dbdcec | C++ | nouveau-riche/DSA-450-Love-Babbar | /EXAMPLES/reverse level order.cpp | UTF-8 | 1,232 | 3.96875 | 4 | [
"MIT"
] | permissive | #include<iostream>
#include<queue>
#include<stack>
using namespace std;
// structure of the node
struct Node{
int data;
struct Node *left;
struct Node *right;
};
// function to create the new Node
struct Node * newNode(int data){
struct Node *temp;
temp = new Node();
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// change according to simple bfs: at place of printing the node push the node in stack
void reverse_bfs(struct Node *node){
queue<struct Node *> q;
stack<int> s;
q.push(node);
while(!q.empty()){
struct Node *front = q.front();
q.pop();
s.push(front->data);
if(front->right != NULL){
q.push(front->right);
}
if(front->left != NULL){
q.push(front->left);
}
}
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
}
int main(){
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
reverse_bfs(root);
} | true |
5899c71293f7eb661fa2e87d91b59ed081d70597 | C++ | natiiix/demo_fr025remix | /fr025remix/obj_VertexSet.cpp | UTF-8 | 579 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "obj_VertexSet.hpp"
namespace obj
{
VertexSet::VertexSet(const std::string & strVertexSet)
{
std::vector<std::string> elements;
str::split(strVertexSet, elements, '/');
// Indexes in .obj files are counted from 1, however the C++ ones start at 0
m_vertex = str::toInt(elements[0]) - 1;
m_texture = str::toInt(elements[1]) - 1;
m_normal = str::toInt(elements[2]) - 1;
}
int VertexSet::getVertex() const
{
return m_vertex;
}
int VertexSet::getTexture() const
{
return m_texture;
}
int VertexSet::getNormal() const
{
return m_normal;
}
}
| true |
88e723e271ef64bc649811ebbead4bd42b94f1c5 | C++ | mathiasf0/calories-burnt | /Calories Burned Program FINAL.cpp | UTF-8 | 1,937 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
double PerWeight;
double PerHeight;
int PerAge;
double activFactor;
double BMR;
cout << "Hi! Today we will calculate how many calories you burned today. To proceed, we will need information on your weight, height, age, and daily activity! All your information is private, and solely used for calculation purposes. " << '\n';
cout << "Please enter your weight in pounds and then press enter key: ";
cin >> PerWeight;
cout << "Please enter your height in feet and then press enter key: ";
cin >> PerHeight;
cout << "Please enter your age in years and press enter key: ";
cin >> PerAge;
cout << "These are the activity numbers for the most common lifestyles. Please read each one carefully and choose only one." << '\n'
<< "If you spend most of your day at your desk job and do not exercise, enter 1.2. " << '\n'
<< "If you do some exercise 1 to 3 days per week, then enter 1.375. " << '\n'
<< "If you do moderate exercises 3 to 5 times a week then enter 1.55. " << '\n'
<< "If you do high - intensity exercises 6 to 7 times a week, enter 1.725. " << '\n'
<< "If you train and play sports at least twice a day enter 1.9. " << '\n' ;
cin >> activFactor;
BMR = 66 + (6.2 * PerWeight) + (152.4 * PerHeight) - (6.8 * PerAge); //BMR Formula
cout << "You burn about " << BMR << " calories each day! If you eat more calories than that per day, then you could definitely do more exercises if you wish to!" << '\n'
<< "On the other hand, you may wish to cut down on certain foods to lower your caloric intake. "
<< "Here are some of the most popular high-calorie foods : " << '\n'
<< "One Avocado has about 322 calories!" << '\n'
<< "Four Tablespoons of Peanut Butter has 400 calories!" << '\n'
<< "One Cup of Nuts has 400 calories!" << '\n'
<< "One Small Box of Raisins has 200 calories!" << '\n';
system("pause");
}
| true |
555aa795c54713f165de96d67fc8cad21c30d591 | C++ | Ming-J/LeetCode | /CodeForces/0476A_Dreamoon_And_Stairs.cpp | UTF-8 | 282 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int stairs;
int multiple;
cin>>stairs>>multiple;
int minSteps = stairs/2 + stairs%2;
for(int i = minSteps; i <= stairs; ++i){
if(i%multiple == 0){
cout<<i<<endl;
return 0;
}
}
cout<<-1<<endl;
}
| true |
b1a471621941edf8266f197c806b08e466d53a1f | C++ | ailuoxz/BadPrincess-Game | /Src/AI/Actions/TimerAction.cpp | UTF-8 | 1,514 | 2.84375 | 3 | [] | no_license | /**
@file TimerAction.cpp
Action that set if certain ability of some type of unit is enabled or disabled
@see TimerAction
@author Ivan Leon
@date May 2015
*/
#include "TimerAction.h"
#include "GUI/Server.h"
#include "GUI/StatisticsController.h"
namespace AI {
IActionStatus CTimerAction::onStart(){
_lastTimeWritten = convertTimeToString(_maxTime);
GUI::CServer::getSingletonPtr()->getStatisticsController()->setTimerTextColor(_color);
GUI::CServer::getSingletonPtr()->getStatisticsController()->setTimerText(_lastTimeWritten);
GUI::CServer::getSingletonPtr()->getStatisticsController()->setTimerVisibility(true);
return IActionStatus::OnStart;
}
bool CTimerAction::onCheck(unsigned int msecs)
{
_maxTime-=msecs;
if(_maxTime>0)
{
std::string currentTime = convertTimeToString(_maxTime);
if(_lastTimeWritten.compare(currentTime)!=0)
{
_lastTimeWritten = currentTime;
GUI::CServer::getSingletonPtr()->getStatisticsController()->setTimerText(_lastTimeWritten);
}
return false;
}else
return true;
}
std::string CTimerAction::convertTimeToString(int millisecond)
{
unsigned int secs = (unsigned int) millisecond/1000;
unsigned int min = (unsigned int) secs / 60;
secs -= min*60;
std::string zero = secs >= 10 ? "" : "0";
return std::to_string(min)+" : " + zero + std::to_string(secs);
}
IActionStatus CTimerAction::onEnd(){
GUI::CServer::getSingletonPtr()->getStatisticsController()->setTimerVisibility(false);
return IActionStatus::Ended;
};
} | true |
65c6fc2529b1746a03169d3442b8282e75880c99 | C++ | mhackampari/OpenCL | /Knapsack OpenCL/knapsack_main.cpp | UTF-8 | 2,549 | 2.578125 | 3 | [] | no_license | /*
* File: knapsack_main.cpp
* Author: terminator
*TODO: write to the file the results and add timer function
* Created on February 21, 2015, 10:07 PM
*/
#include <CL/cl.h>
#include "Knapsack.h"
#include "Chrono.h"
#include "Timer.h"
#include "TestData.h"
int main(int argc, char** argv) {
Chrono ch;
Timer tm;
ch.startChrono();
fstream logfile;
logfile.open("results_knapsack.txt", ios::out);
//remember the limit of the 4gb allocated space
int dim[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
int local_threads[] = {0, 64, 128, 256, 512, 1024};
for (int k = 5; k < sizeof (local_threads) / sizeof (int); k++) {//local_threads
for (int j = 9; j < sizeof (dim) / sizeof (int); j++) {
TestData* test = new TestData(dim[j]);
Knapsack *ksack = new Knapsack(*test);
//1.Query the host system for OpenCL platform info
ksack->queryOclPlatformInfo(&logfile);
//2. Query the host for OpenCL devices
ksack->queryOclDevice(&logfile);
for (int i = 0; i < ksack->getNumDevices(); i++) {
ksack->queryOclDeviceInfo(i, &logfile);
//3. Create a context and a queue to associate the OpenCL devices.
ksack->createContextQueue(i, &logfile);
//4. Create programs that will run on one or more associated devices.
ksack->createProgramBuild(i, &logfile);
//5. Create memory objects on the host or on the device.
//6. Copy memory data to the device as needed. Create memory objects on the host or on the device.
ksack->createMemObjects(&logfile);
//7. Create Kernels
ksack->createKernel();
//8. Provide arguments for the kernels.
// ksack.createKernel();
//9. Submit the kernels to the command queue for execution.
//10. Copy the results from the device to the host
//ksack.executeMemObjects();
ksack->executeComputation(i, &logfile, local_threads[k]);
ksack->printResults(&logfile);
}
delete ksack;
delete test;
}
}
logfile.close();
//http://stackoverflow.com/questions/14063791/double-free-or-corruption-but-why
ch.stopChrono();
tm.stop();
cout << "CHRONO TIME: " << ch.getTimeChrono() << endl;
cout << "TIMER TIME: " << tm.getTime();
return 0;
}
| true |
8d4cc220a435b1fae0d849742f20e6555740388d | C++ | leejuy1140/Algorithm | /Algorithm/Algorithm/거듭제곱 구하기L.cpp | UTF-8 | 526 | 2.953125 | 3 | [] | no_license | #include <stdio.h>
#include <cstdint>
const int QUOTIENT = 10007;
int n;
uint64_t m;
uint64_t power(uint64_t curM)
{
if (curM == 1) return n;
uint64_t answer;
if (curM % 2)
{
answer = n * power(curM - 1);
return answer % QUOTIENT;
}
else
{
answer = power(curM / 2);
return (answer * answer) % QUOTIENT;
}
}
int main()
{
scanf("%d %llu", &n, &m);
uint64_t answer;
if (m != 1 && m % 2) answer = n * power(m - 1);
else answer = power(m);
printf("%d\n", answer % QUOTIENT);
return 0;
} | true |
2eb52fda1213d066459086695030c57834c38dbf | C++ | Arctem/bake | /include/ir/basic_block.h | UTF-8 | 1,502 | 3.078125 | 3 | [] | no_license | #pragma once
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "ir/op.h"
#include "ir/ir_visitor.h"
#include "ast/ast.h"
namespace ir {
class BasicBlock {
public:
virtual ~BasicBlock();
BasicBlock* getBrOnTrue() { return brOnTrue; }
BasicBlock* getBrOnFalse() { return brOnFalse; }
std::vector<Op*> getOps() { return ops; }
string* getLabel();
void setBrOnTrue(BasicBlock* block) { brOnTrue = block; }
void setBrOnFalse(BasicBlock* block) { brOnFalse = block; }
void addOp(Op* op, int pos = -1);
virtual void accept(IrVisitor* v) { v->visit(this); }
private:
BasicBlock* brOnTrue = nullptr;
BasicBlock* brOnFalse = nullptr;
std::vector<Op*> ops;
string* label;
};
class Method : public BasicBlock {
public:
Method(std::string name) : name(name) { }
virtual ~Method() {};
void setAst(bake_ast::Feature* n) { ast = n; } // Set the AST node corresponding to this class
void addStackVar(int);
std::vector<int> getStackVars() { return stack_vars; }
bake_ast::Feature* getAst() { return ast; } // Return the AST node corresponding to this class
std::string getName() { return name; }
virtual void accept(IrVisitor* v) { v->visit(this); }
private:
std::string name;
std::vector<int> stack_vars; // Vector containing the size of each parameter that this method takes
bake_ast::Feature* ast; // Reference to the AST node defining this class
};
}
| true |
b853f796e76cbcdef18042c2d50878ad5d634129 | C++ | team116/ed2017 | /src/Intake.cpp | UTF-8 | 550 | 2.578125 | 3 | [] | no_license | /*
* Intake.cpp
*
* Created on: Jan 15, 2017
* Author: Will
*/
#include <Intake.h>
#include "Ports.h"
Intake* Intake::INSTANCE = nullptr;
Intake::Intake() {
// TODO Auto-generated constructor stub
intake_motor = Utils::constructMotor(RobotPorts::MOTOR_INTAKE);
}
void Intake::process() {
}
float Intake::getSpeed() {
return intake_motor->Get();
}
void Intake::setSpeedIntake(float speed) {
intake_motor->Set(-speed);
}
Intake* Intake::getInstance()
{
if(INSTANCE == nullptr) {
INSTANCE = new Intake();
}
return INSTANCE;
}
| true |
ae20e7a9b46898401940c5b0a57dad142d2d3b33 | C++ | InbalEl/cpp_projects | /factory/gilad/2/factory.hpp | UTF-8 | 1,864 | 3.046875 | 3 | [] | no_license | // ###################################################################
// #file Name : function.hpp
// #Description : function class decleration and definition
// #Create Date : 5.1.2020
// #last update : 10.1.2020 (Change to smart pointers)
// #Developer : Gilad Barak
// ###################################################################
#include <functional>
#include <unordered_map>
#include <memory>
namespace ilrd{
namespace rd90{
/*----------------------------------------------------------------------------*/
template <typename T, typename KEY, typename ARG>
class Factory
{
public:
explicit Factory() = default;
template<typename R>
void Register(KEY key);
std::shared_ptr<T> Create(KEY key, const ARG& arg);
private:
template<typename R>
static std::shared_ptr<T> CreateInstance(const ARG& arg);
typedef std::shared_ptr<T>(*func_ptr)(const ARG& arg);
std::unordered_map<KEY,func_ptr> m_creators;
};
/*----------------------------------------------------------------------------*/
template <typename T, typename KEY, typename ARG>
template<typename R>
void Factory<T,KEY,ARG>::Register(KEY key)
{
m_creators.insert(std::make_pair(key,&Factory<T,KEY,ARG>::CreateInstance<R>));
}
/*----------------------------------------------------------------------------*/
template <typename T, typename KEY, typename ARG>
template<typename R>
std::shared_ptr<T> Factory<T,KEY,ARG>::CreateInstance(const ARG& arg)
{
std::shared_ptr<T> ret(new R(arg));
return (ret);
}
/*----------------------------------------------------------------------------*/
template <typename T, typename KEY, typename ARG>
std::shared_ptr<T> Factory<T,KEY,ARG>::Create(KEY key,const ARG& arg)
{
return (m_creators[key](arg));
}
/*----------------------------------------------------------------------------*/
}
} | true |
859899fa933b4585b8f26459a57ec48432952562 | C++ | lheckemann/namic-sandbox | /pstAtlasSeg/src/atlasSegMIExe_outputPr.cxx | UTF-8 | 1,683 | 2.546875 | 3 | [] | no_license | /**
* Atlas based segmentation
*
* 20100521
* Yi Gao
*/
//std
#include <vector>
#include <string>
//newProstate
#include "cArrayOp.h"
#include "txtIO.h"
// itk
#include "itkImage.h"
// local
#include "atlasSegMI.h"
int main(int argc, char** argv)
{
if (argc < 5)
{
std::cerr<<"args: rawImageName trainingImageListName labelImageListName outputLabelName\n";
exit(-1);
}
std::string rawImageName(argv[1]);
std::string trainingImageListName(argv[2]);
std::string labelImageListName(argv[3]);
std::string outputLabelName(argv[4]);
typedef float pixel_t;
typedef itk::Image<pixel_t, 3> image_t;
/**
* Read in raw image
*/
image_t::Pointer img = newProstate::readImage3<image_t::PixelType>(rawImageName.c_str());
/**
* Read in training images' names
*/
std::vector< std::string > trainingImageList = newProstate::readTextLineToListOfString<char>(trainingImageListName.c_str());
/**
* Read in label images' names
*/
std::vector< std::string > labelImageList = newProstate::readTextLineToListOfString<char>(labelImageListName.c_str());
typedef unsigned char labelPixel_t;
typedef itk::Image<labelPixel_t, 3> labelImage_t;
// atlas based seg
std::cout<<"Segmenting "<<rawImageName<<"...\n"<<std::flush;
//labelImage_t::Pointer resultLabel = atlasSegMI<image_t, labelImage_t>(img, trainingImageList, labelImageList);
itk::Image<float, 3>::Pointer resultLabel \
= newProstate::atlasSegMI_outputPr<image_t>(img, trainingImageList, labelImageList);
// write result
newProstate::writeImage3<float>(resultLabel, outputLabelName.c_str());
return 0;
}
| true |
f8a781f651df511f4d1be4009955ee741d950687 | C++ | Andresmag/U-TAD_AudioProgramming | /Practice2/src/text.cpp | UTF-8 | 1,111 | 3.25 | 3 | [] | no_license | #include "vec2.h"
#include "text.h"
#include "font.h"
#include <cstring>
// Constructors
Text::Text()
: m_sText(nullptr)
, m_pFont(nullptr)
, m_uSpeed(0)
{
m_pColor[0] = 0;
m_pColor[1] = 0;
m_pColor[2] = 0;
}
Text::Text(const char* _sText, const Font* _pFont, const Vec2& _vPos, const unsigned int& _uSpeed, const float* _pColor)
{
m_sText = new char[strlen(_sText) + 1]; // +1 para el \0 y evitar heap corruption al eliminar
strcpy(const_cast<char*>(m_sText), _sText);
m_pFont = _pFont;
m_vPos = _vPos;
m_uSpeed = _uSpeed;
m_pColor[0] = _pColor[0];
m_pColor[1] = _pColor[1];
m_pColor[2] = _pColor[2];
}
// Destructor
Text::~Text()
{
if (m_sText != nullptr)
{
delete[] m_sText;
}
}
// Getters
const char* Text::getText()
{
return m_sText;
}
const Font* Text::getFont()
{
return m_pFont;
}
const Vec2 Text::getPos()
{
return m_vPos;
}
float* Text::getColor()
{
return m_pColor;
}
// Update position
void Text::UpdatePosition(float _fSeconds)
{
m_vPos.SetXCoor(m_vPos.GetXCoor() - m_uSpeed * _fSeconds);
}
// Draw text
void Text::Draw()
{
m_pFont->Draw(m_sText, m_vPos);
} | true |
0193e2b55a3170f24267a0271d2e9890fff72afa | C++ | jarenbraza/ICPC-2018 | /ICPC/TheNaviComputerIsDown.cpp | UTF-8 | 715 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#include <stdio.h>
#include <string>
using namespace std;
double getDistance(double x1, double x2, double y1, double y2, double z1, double z2) {
return (double)((int)(pow(pow(x2 - x1, 2) + pow(y2 - y1, 2) + pow(z2 - z1, 2), 0.5) * 100 + 0.5)) / 100.0;
}
int main() {
int n;
double x1, y1, z1, x2, y2, z2;
string s1, s2;
cin >> n;
while (n--) {
getchar();
getline(cin, s1);
cin >> x1 >> y1 >> z1;
getchar();
getline(cin, s2);
cin >> x2 >> y2 >> z2;
printf("%s to %s: %.2f\n", s1.c_str(), s2.c_str(), getDistance(x1, x2, y1, y2, z1, z2));
}
return 0;
} | true |
8b8623817d70c9c096865f8ac42e33aa80609472 | C++ | istvankurucz/bookshop-inventory-system | /book.h | UTF-8 | 863 | 2.96875 | 3 | [] | no_license | #ifndef __BOOK_H
#define __BOOK_H
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
static int book_count, income;
string id, author, title;
int price, count;
public:
Book();
Book(string id, string author, string title, int price, int count);
static int getBooks();
static void setBooks(int new_count);
static int getIncome();
static void setIncome(int new_income);
string getId() const;
void setId(string new_id);
string getAuthor() const;
void setAuthor(string new_author);
string getTitle() const;
void setTitle(string new_title);
int getPrice() const;
void setPrice(int new_price);
int getCount() const;
void setCount(int new_count);
void setAll(string new_id, string new_author, string new_title, int new_price, int new_count);
~Book();
};
#endif | true |
11d960f4a56b4b650aa1b6dcbd3bda9c50a2efb6 | C++ | quantum109678/IT_4 | /daa/lab9/edit_dist.cpp | UTF-8 | 638 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int min_cost(int x,int y,int z){
int min=(x<y)?(x<z)?x:z:(y<z)?y:z;
return min;
}
int edit_dist(string s1,string s2,int m,int n){
int memo[m+1][n+1];
for(int i=0;i<=m;i++){
for(int j=0;j<=m;j++){
if(i==0) memo[i][j]=j;
else if(j==0) memo[i][j]=i;
else if(s1[i-1]==s2[j-1]) memo[i][j]=memo[i-1][j-1];
else memo[i][j]=1+min_cost(memo[i][j-1],memo[i-1][j],memo[i-1][j-1]);
}
}
return memo[m][n];
}
int main(){
string s1,s2;
cout<<"Enter the two strings:";
cin>>s1>>s2;
cout<<edit_dist(s1,s2,s1.length(),s2.length())<<endl;
return 0;
} | true |
bb299e59603e1724e490945cba652743ed7632bc | C++ | zhanglongjian/ds-c | /IPOrder2.h | GB18030 | 374 | 2.75 | 3 | [] | no_license | template<class ElemType>
void InOrder(BTree<ElemType> *bt)//,btΪָ
{if(bt){
InOrder(bt->LChild);cout<<ElemType(*bt)<<',';InOrder(bt->RChild);}
}
template<class ElemType>
void PostOrder(BTree<ElemType> *bt)//,btΪָ
{if(bt){
PostOrder(bt->LChild);PostOrder(bt->RChild);cout<<ElemType(*bt)<<',';}
} | true |
a02ba44d29820ecbff0e38847d57ad6cdcd4b63b | C++ | johnpyle6/music.johnpyle.net-node | /250/Lab1/Lab1b.cpp | UTF-8 | 2,600 | 3.734375 | 4 | [] | no_license | /** Programs to demonstrate knowledge of C++
* @author John Pyle
* @file Lab1b.cpp
*/
#include <iostream> // Library that defines cout and cin
#include <cstdlib> // Library that EXIT_SUCCESS constant
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
bool isVowel(char character);
void getStatus(string word, int &vow, int &con, int &oth);
bool processLine(string lineOfWords, int &vow, int &con, int &oth);
/*
int main(void)
{
string input;
int con = 0;
int oth = 0;
int vow = 0;
const string INPUT_FILE = "myFile.txt"; //name of input file
ifstream inFile(INPUT_FILE.c_str()); // open the input file
string inputString; // stores lines of data input from the file
bool quit = false;
if (!inFile)
cout << "Error opening file for input: " << INPUT_FILE << endl;
else
{
getline (inFile, inputString); // the prime read
while (inFile) // while no errors have been encountered
{
cout << "The line is: " << inputString << endl;
quit = processLine(inputString, vow, con, oth);
if (quit)
{ cout << "Vowels: " << vow << endl;
cout << "Consonants: " << con << endl;
cout << "Other: " << oth << endl << endl;
con = 0;
oth = 0;
vow = 0;
}
getline (inFile, inputString);
}
inFile.close();
}
return EXIT_SUCCESS;
}
*/
bool isVowel(char character)
{
char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
bool vowel = false;
for( unsigned int i = 0; i < sizeof(vowels); i = i + 1 )
{
if (character == vowels[i])
vowel = true;
}
return vowel;
}
void getStatus(string word, int &vow, int &con, int &oth)
{
char ch = word[0];
if ( !isalpha(ch) )
oth++;
else if ( isVowel(ch) )
vow++;
else
con++;
}
bool processLine(string lineOfWords, int &vow, int &con, int &oth){
bool quit = false;
char *cstr = const_cast<char*>( lineOfWords.c_str() );
char *pch;
pch = strtok (cstr," ");
while (pch != NULL)
{
//cout << ":" << pch << endl;
if ( strcmp(pch, "quit") == 0){
//cout << "is quit" << endl;
quit = true;
}else{
//cout << ":" << pch << endl;
getStatus(pch, vow, con, oth);
}
pch = strtok (NULL, " ");
}
return quit;
} | true |
42ec09ea3a4279a7b5dadb2ebf9afa999999872b | C++ | jonnyvegas/CIS-202 | /ch 16/checkedarray.cpp | UTF-8 | 2,410 | 4.25 | 4 | [] | no_license | //Name: Jonathan Villegas
//Description: Define a class named CheckedArray. The objects of this
//class are like regular arrays but have range checking. If a is an object
//of the class CheckedArray
//and i is an illegal index then use of a[i]will cause your program to throw
//an exception (an object) of the class ArrayOutOfRangeError.
//Date: 5/18/14
//Email: jonathan.e.villegas@gmail.com
//File: checkedarray.cpp
#include <iostream>
using namespace std;
class ArrayOutOfRangeError
{};
template <class T>
class CheckedArray
{
public:
//Constructor
CheckedArray(int the_size);
//Operator overload
T& operator[](int index);
//Returns the value at the index.
T get_value(int index);
//Adds the value to the array.
void add_value(T the_val, int the_value);
private:
int *value;
int size;
};
template <class T>
CheckedArray<T>::CheckedArray(int the_size)
{
value = new T[the_size];
size = the_size;
}
template <class T>
T& CheckedArray<T>::operator[](int index)
{
//If the index is out of range
if(index < 0 || index >= size)
{
throw ArrayOutOfRangeError();
}
//else return the value at the index.
return value[index];
}
template <class T>
T CheckedArray<T>::get_value(int index)
{
//If the value accessed is not in the range
if(index < 0 || index >= size)
{
throw ArrayOutOfRangeError();
}
return value[index];
}
template <class T>
void CheckedArray<T>::add_value(T the_val, int index)
{
if(index < 0 || index >= size)
{
throw ArrayOutOfRangeError();
}
value[index] = the_val;
}
int main()
{
int num, input;
//Construct an array of 10 numbers.
CheckedArray<int> a(10);
try
{
for(int i = 0; i < 10; i++)
{
cout << "Please enter value " << i + 1 << ": ";
cin >> num;
a[i] = num;
}
cout << "Enter value 11: ";
cin >> num;
a[10] = num;
}
catch(ArrayOutOfRangeError)
{
int num2;
cout << "You tried to access an illegal index!!!" << endl;
cout << "Which index did you want to access?: ";
cin >> num;
cout << "What did you want to store in there?: ";
cin >> num2;
a.add_value(num2,num);
}
cout << "You entered: " << endl;
for (int j = 0; j < 10; j++)
{
cout << a[j] << " ";
}
cout << endl;
return 0;
}
| true |
ecf2f4cf6917fd64a7a9484639a1c695c9b24b4e | C++ | mosteo/ekfvloc | /transf.cc | UTF-8 | 7,622 | 2.65625 | 3 | [] | no_license | /*
* Copyright (C) 2010
* Mayte Lázaro, Alejandro R. Mosteo
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_matrix.h>
#include "transf.hh"
Transf::Transf() :
Matrix(3, 1)
{
}
Transf::Transf(double x, double y, double phi) :
Matrix(3, 1)
{
operator()(0, 0) = x;
operator()(1, 0) = y;
operator()(2, 0) = phi;
}
Transf::Transf(Matrix &m) :
Matrix(3, 1)
{
if ((m.RowNo() != 3) or(m.ColNo() != 1))
{
throw range_error("Impossible conversion from Matrix to Transf\n");
}
else
{
operator()(0, 0) = m(0, 0);
operator()(1, 0) = m(1, 0);
operator()(2, 0) = m(2, 0);
}
}
Transf::~Transf()
{
}
double Transf::tX() const
{
return operator()(0, 0);
}
double Transf::tY() const
{
return operator()(1, 0);
}
double Transf::tPhi() const
{
return operator()(2, 0);
}
double Normalize(double p)
// Normalize the angle p to (-M_PI, PI].
{
double result = p;
int i = 0;
while (result > M_PI)
{
result -= 2.0 * M_PI;
if (++i > 50)
{
printf("ERROR: normalize, result:%f\n", result);
break;
}
}
i = 0;
while (result <= -M_PI)
{
result += 2.0 * M_PI;
if (++i > 50)
{
printf("ERROR: normalize, result:%f\n", result);
break;
}
}
return result;
}
Transf Compose(Transf Tab, Transf Tbc)
{
Transf Tac;
Tac.x() = Tbc.tX() * cos(Tab.tPhi()) -
Tbc.tY() * sin(Tab.tPhi()) +
Tab.tX();
Tac.y() = Tbc.tX() * sin(Tab.tPhi()) +
Tbc.tY() * cos(Tab.tPhi()) +
Tab.tY();
Tac.phi() = Normalize(Tab.tPhi() + Tbc.tPhi());
return Tac;
}
Transf Inv(Transf Tab)
{
Transf Tba;
Tba.x() = -Tab.tY() * sin(Tab.tPhi()) -
Tab.tX() * cos(Tab.tPhi());
Tba.y() = Tab.tX() * sin(Tab.tPhi()) -
Tab.tY() * cos(Tab.tPhi());
Tba.phi() = -Tab.tPhi();
return Tba;
}
Transf TRel(Transf Twa, Transf Twb)
{
return Compose(Inv(Twa), Twb);
}
Matrix Jacobian(Transf Tab)
{
Matrix Jab(3, 3);
Jab(0, 0) = cos(Tab.tPhi());
Jab(0, 1) = -sin(Tab.tPhi());
Jab(0, 2) = Tab.tY();
Jab(1, 0) = sin(Tab.tPhi());
Jab(1, 1) = cos(Tab.tPhi());
Jab(1, 2) = -Tab.tX();
Jab(2, 0) = 0;
Jab(2, 1) = 0;
Jab(2, 2) = 1;
return Jab;
}
Matrix InvJacobian(Transf Tab)
{
Matrix Jba(3, 3);
Jba(0, 0) = cos(Tab.tPhi());
Jba(0, 1) = sin(Tab.tPhi());
Jba(0, 2) = Tab.tX() * sin(Tab.tPhi()) - Tab.tY() * cos(Tab.tPhi());
Jba(1, 0) = -sin(Tab.tPhi());
Jba(1, 1) = cos(Tab.tPhi());
Jba(1, 2) = Tab.tX() * cos(Tab.tPhi()) + Tab.tY() * sin(Tab.tPhi());
Jba(2, 0) = 0;
Jba(2, 1) = 0;
Jba(2, 2) = 1;
return Jba;
}
Matrix J1(Transf Ta, Transf Tb)
{
Matrix J1(3, 3);
J1(0, 0) = 1;
J1(0, 1) = 0;
J1(0, 2) = -Tb.tX() * sin(Ta.tPhi()) - Tb.tY() * cos(Ta.tPhi());
J1(1, 0) = 0;
J1(1, 1) = 1;
J1(1, 2) = Tb.tX() * cos(Ta.tPhi()) - Tb.tY() * sin(Ta.tPhi());
J1(2, 0) = 0;
J1(2, 1) = 0;
J1(2, 2) = 1;
return J1;
}
Matrix InvJ1(Transf Ta, Transf Tb)
{
Matrix InvJ1(3, 3);
InvJ1(0, 0) = 1;
InvJ1(0, 1) = 0;
InvJ1(0, 2) = Tb.tX() * sin(Ta.tPhi()) + Tb.tY() * cos(Ta.tPhi());
InvJ1(1, 0) = 0;
InvJ1(1, 1) = 1;
InvJ1(1, 2) = -Tb.tX() * cos(Ta.tPhi()) + Tb.tY() * sin(Ta.tPhi());
InvJ1(2, 0) = 0;
InvJ1(2, 1) = 0;
InvJ1(2, 2) = 1;
return InvJ1;
}
Matrix J1zero(Transf Ta)
{
Matrix J1z(3, 3);
J1z(0, 0) = 1;
J1z(0, 1) = 0;
J1z(0, 2) = -Ta.tY();
J1z(1, 0) = 0;
J1z(1, 1) = 1;
J1z(1, 2) = Ta.tX();
J1z(2, 0) = 0;
J1z(2, 1) = 0;
J1z(2, 2) = 1;
return J1z;
}
Matrix InvJ1zero(Transf Ta)
{
Matrix InvJ1z(3, 3);
InvJ1z(0, 0) = 1;
InvJ1z(0, 1) = 0;
InvJ1z(0, 2) = Ta.tY();
InvJ1z(1, 0) = 0;
InvJ1z(1, 1) = 1;
InvJ1z(1, 2) = -Ta.tX();
InvJ1z(2, 0) = 0;
InvJ1z(2, 1) = 0;
InvJ1z(2, 2) = 1;
return InvJ1z;
}
Matrix J2(Transf Ta, Transf Tb)
{
Matrix J2(3, 3);
J2(0, 0) = cos(Ta.tPhi());
J2(0, 1) = -sin(Ta.tPhi());
J2(0, 2) = 0;
J2(1, 0) = sin(Ta.tPhi());
J2(1, 1) = cos(Ta.tPhi());
J2(1, 2) = 0;
J2(2, 0) = 0;
J2(2, 1) = 0;
J2(2, 2) = 1;
return J2;
}
Matrix InvJ2(Transf Ta, Transf Tb)
{
Matrix InvJ2(3, 3);
InvJ2(0, 0) = cos(Ta.tPhi());
InvJ2(0, 1) = sin(Ta.tPhi());
InvJ2(0, 2) = 0;
InvJ2(1, 0) = -sin(Ta.tPhi());
InvJ2(1, 1) = cos(Ta.tPhi());
InvJ2(1, 2) = 0;
InvJ2(2, 0) = 0;
InvJ2(2, 1) = 0;
InvJ2(2, 2) = 1;
return InvJ2;
}
Matrix J2zero(Transf Ta)
{
Matrix J2z(3, 3);
J2z(0, 0) = cos(Ta.tPhi());
J2z(0, 1) = -sin(Ta.tPhi());
J2z(0, 2) = 0;
J2z(1, 0) = sin(Ta.tPhi());
;
J2z(1, 1) = cos(Ta.tPhi());
;
J2z(1, 2) = 0;
J2z(2, 0) = 0;
J2z(2, 1) = 0;
J2z(2, 2) = 1;
return J2z;
}
Matrix InvJ2zero(Transf Ta)
{
Matrix InvJ2z(3, 3);
InvJ2z(0, 0) = cos(Ta.tPhi());
InvJ2z(0, 1) = sin(Ta.tPhi());
InvJ2z(0, 2) = 0;
InvJ2z(1, 0) = -sin(Ta.tPhi());
;
InvJ2z(1, 1) = cos(Ta.tPhi());
;
InvJ2z(1, 2) = 0;
InvJ2z(2, 0) = 0;
InvJ2z(2, 1) = 0;
InvJ2z(2, 2) = 1;
return InvJ2z;
}
double spAtan2(double y, double x)
// Computes atan2(y, x) and expresses the result anticlockwise
{
double phi;
phi = atan2(y, x);
if (phi > M_PI_2)
return (phi - 2 * M_PI);
return phi;
}
double Transf::Distance(const Transf &b) const
{
return sqrt(pow(tX() - b.tX(), 2.0) + pow(tY() - b.tY(), 2.0));
}
void Eigenv(Matrix M, Matrix *vectors, Matrix *values)
{
if (!M.IsSquare())
throw range_error("Matrix isn't square");
gsl_matrix *m = gsl_matrix_alloc(M.RowNo(), M.ColNo());
for (uint r = 0; r < M.RowNo(); r++)
for (uint c = 0; c < M.ColNo(); c++)
gsl_matrix_set(m, r, c, M(r, c));
gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(M.RowNo());
gsl_vector *d = gsl_vector_alloc(M.RowNo());
gsl_matrix *v = gsl_matrix_alloc(M.RowNo(), M.ColNo());
const int err = gsl_eigen_symmv(m, d, v, w);
if (err == 0)
{
*values = Matrix(M.RowNo(), M.ColNo());
(*values) *= 0;
for (uint r = 0; r < M.RowNo(); r++)
(*values)(r, r) = gsl_vector_get(d, r);
*vectors = Matrix(M.RowNo(), M.ColNo());
for (uint r = 0; r < M.RowNo(); r++)
for (uint c = 0; c < M.ColNo(); c++)
(*vectors)(r, c) = gsl_matrix_get(v, r, c);
}
gsl_eigen_symmv_free(w);
gsl_vector_free(d);
gsl_matrix_free(v);
gsl_matrix_free(m);
if (err != 0)
throw std::runtime_error(gsl_strerror(err));
} | true |
2cb7d01eb74e6c472c3f8d219a32d36d6f6f942c | C++ | hakumai-iida/IllustLogicAnalyzer | /Prj_Android/app/src/main/jni/shared/sys/util/util_encrypt.cpp | UTF-8 | 2,348 | 3.09375 | 3 | [] | no_license | /*+----------------------------------------------------------------+
| Title: util_encrypt.cpp [共通環境]
| Comment: 暗号化(※生データを見せない程度のシンプルなもの)
| Author: K.Takayanagi
+----------------------------------------------------------------+*/
/*+----------------------------------------------------------------+
| Header Define ヘッダ定義
+----------------------------------------------------------------+*/
#include "env.hpp"
#include "util_encrypt.hpp"
/*+----------------------------------------------------------------+
| Define 定義
+----------------------------------------------------------------+*/
// 鍵
#define ENC_KEY_L 0x59
#define ENC_KEY_R 0xD3
/*+----------------------------------------------------------------+
| Struct 構造体型宣言
+----------------------------------------------------------------+*/
/*+----------------------------------------------------------------+
| Global グローバルデータ型定義
+----------------------------------------------------------------+*/
/*+----------------------------------------------------------------+
| Prototype プロトタイプ宣言
+----------------------------------------------------------------+*/
/*+----------------------------------------------------------------+
| Program プログラム領域
+----------------------------------------------------------------+*/
//----------------------------------
// 暗号化
//----------------------------------
bool util_encrypt_encode( void* pBuf, uint32 len ){
BYTE* pArr = (BYTE*)pBuf;
uint32 num = len/2;
// 左右を並び替えてXORをかけておく(※奇数の真ん中は無加工となるが気にしない)
for( uint32 i=0; i<num; i++ ){
BYTE temp = pArr[i];
pArr[i] = (BYTE)(pArr[len-(i+1)] ^ ENC_KEY_L);
pArr[len-(i+1)] = (BYTE)(temp ^ ENC_KEY_R);
}
return( true );
}
//----------------------------------
// 復号化
//----------------------------------
bool util_encrypt_decode( void* pBuf, uint32 len ){
BYTE* pArr = (BYTE*)pBuf;
uint32 num = len/2;
// 並びを戻してXOR
for( uint32 i=0; i<num; i++ ){
BYTE temp = pArr[i];
pArr[i] = (BYTE)(pArr[len-(i+1)] ^ ENC_KEY_R);
pArr[len-(i+1)] = (BYTE)(temp ^ ENC_KEY_L);
}
return( true );
}
| true |
587968491194f16fd21220ac1ccc28fb0b95ee2d | C++ | yazilimperver/SnakeGame | /ConsoleUtil.cpp | UTF-8 | 5,627 | 3.1875 | 3 | [] | no_license | #include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <random>
#include <ctime>
#include <iostream>
#include "ConsoleUtil.h"
void displayConsoleInfo()
{
int width;
int height;
getConsoleInformation(width, height);
std::cout << "Current console width and height are: " << width << " ," << height << '\n';
}
void setColor(Color colorBack, Color colorFore)
{
int back = 0;
int colorBackInt = static_cast<int>(colorBack);
if (colorBackInt & 1) back |= BACKGROUND_BLUE;
if (colorBackInt & 2) back |= BACKGROUND_GREEN;
if (colorBackInt & 4) back |= BACKGROUND_RED;
if (colorBackInt & 8) back |= BACKGROUND_INTENSITY;
int fore = 0;
int colorForeInt = static_cast<int>(colorFore);
if (colorForeInt & 1) fore |= FOREGROUND_BLUE;
if (colorForeInt & 2) fore |= FOREGROUND_GREEN;
if (colorForeInt & 4) fore |= FOREGROUND_RED;
if (colorForeInt & 8) fore |= FOREGROUND_INTENSITY;
// Get the Win32 handle representing standard output.
// This generally only has to be done once, so we make it static.
static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut, back | fore);
}
void clearConsole()
{
setColor(Color::eColor_black, Color::eColor_black);
// Get the Win32 handle representing standard output.
// This generally only has to be done once, so we make it static.
static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
COORD topLeft = { 0, 0 };
// std::cout uses a buffer to batch writes to the underlying console.
// We need to flush that to the console because we@re circumventing
// std::cout entirely; after we clear the console, we don@t want
// stale buffered text to randomly be written out.
std::cout.flush();
// Figure out the current width and height of the console window
if (!GetConsoleScreenBufferInfo(hOut, &csbi))
{
// TODO: Handle failure!
abort();
}
DWORD length = csbi.dwSize.X * csbi.dwSize.Y;
DWORD written;
// Flood-fill the console with spaces to clear it
FillConsoleOutputCharacter(hOut, TEXT(' '), length, topLeft, &written);
// Reset the attributes of every character to the default.
// This clears all background color formatting, if any.
FillConsoleOutputAttribute(hOut, csbi.wAttributes, length, topLeft, &written);
// Move the cursor back to the top left for the next sequence of writes
SetConsoleCursorPosition(hOut, topLeft);
}
void moveCursor(const COORD& pos)
{
// Get the Win32 handle representing standard output.
// This generally only has to be done once, so we make it static.
static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOut, pos);
}
void moveCursor(int x, int y)
{
COORD point;
point.X = x;
point.Y = y;
static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOut, point);
}
void displayCenteredText(const char *message, int consoleWidth, int ypos)
{
size_t len = strlen(message);
if (len > 0)
{
size_t xpos = (consoleWidth - len) / 2;
moveCursor(static_cast<int>(xpos), static_cast<int>(ypos));
printf(message);
}
}
void cursorHide()
{
HANDLE hwnd;
hwnd = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.bVisible = 0;
info.dwSize = 1;
SetConsoleCursorInfo(hwnd, &info);
}
void keyboardHandle()
{
bool exit = false;
int key = _getch();
switch (key)
{
case KEY_LEFT: ; break;
case KEY_RIGHT: ; break;
case KEY_UP: ; break;
case KEY_DOWN: ; break;
case KEY_RETURN: ; break;
}
if (key == KEY_ESCAPE)
exit = true;
}
void getConsoleInformation(int& width, int& height)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD consoleInfo = GetLargestConsoleWindowSize(hConsole);
width = consoleInfo.X;
height = consoleInfo.Y;
}
void displayTable(const COORD& topLeft, int width, int height, Color colorBack, Color colorFront, int theme)
{
setColor(colorBack, colorFront);
moveCursor(topLeft);
// top left corner
std::cout << static_cast<char>(218);
// top side
for (int i = 1; i < width - 1; i++)
{
std::cout << static_cast<char>(196);
}
// top right corner
std::cout << static_cast<char>(191);
COORD cursor = topLeft;
cursor.Y++;
for (int i = 1; i < height - 1; i++)
{
moveCursor(cursor);
std::cout << static_cast<char>(179);
cursor.X = topLeft.X + width - 1;
moveCursor(cursor);
std::cout << static_cast<char>(179);
cursor.X = topLeft.X;
cursor.Y++;
}
cursor = topLeft;
cursor.Y = topLeft.Y + height-1;
moveCursor(cursor);
// bottom left corner
std::cout << static_cast<char>(192);
// bottom side
for (int i = 1; i < width - 1; i++)
{
std::cout << static_cast<char>(196);
}
// bottom right corner
std::cout << static_cast<char>(217);
}
void setWindowSize(int Width, int Height)
{
_COORD coord;
coord.X = Width;
coord.Y = Height;
_SMALL_RECT Rect;
Rect.Top = 0;
Rect.Left = 0;
Rect.Bottom = Height - 1;
Rect.Right = Width - 1;
HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);// Get Handle
SetConsoleScreenBufferSize(Handle, coord);// Set Buffer Size
SetConsoleWindowInfo(Handle, TRUE, &Rect);// Set Window Size
}
void setConsoleInformation(short left, short top, short width, short height)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_RECT rect = { left, top, width, height};
BOOL result = SetConsoleWindowInfo(hConsole, TRUE, &rect);
}
int getNonBlockingChar()
{
if (_kbhit())
return _getch();
else
return -1;
}
int generateRandromNumber(int low, int high)
{
static std::mt19937 u_mt(std::time(nullptr));
std::uniform_int_distribution<unsigned int> u_distrib(low, high);
return u_distrib(u_mt);
}
| true |
549ec6a1d4b08bc8db2028733c13eb6892219e03 | C++ | HarounH/thesecondone | /helloworld/glutMovingCircle.cpp | UTF-8 | 1,180 | 3 | 3 | [] | no_license | //glut moving circle
#include <GL/glut.h> //should include everything
#define P_HEIGHT 400
#define P_WIDTH 400
//Usual C++ includes
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <vector>
using namespace std;
class Circle{
public:
float xCentre , yCentre;
float radius;
float color[] = { 1.0 , 1.0 , 1.0 , 1.0};
}myCircle;
//Header file kinda thing
void eventHandler(); //The function that handles events/interrupts(keyboard/mouse)
void display(); //The display function that is required by openGL
void init(); //Takes care of initialization
//Main loop.
int main(int argc, char** argv) {
myCircle.xCentre = 0.0;
myCircle.yCentre = 0.0;
myCircle.radius = 2.0;
glutInit(&argc , char** argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(P_HEIGHT , P_WIDTH); //Window sizes defined earlier.
glutInitWindowPosition(50,50); //ARbit values.
int window1 = glutCreateWindow("Moving Cirlce");
init(); //Dfined below
glutDisplayFunc(display);
glutSpecialFunc(eventHandler);
glutMainLoop();
return 0;
}
void init() {
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFLush();
} | true |
1175bb1cfcb84fcdea6e2761411e8ff354612f1b | C++ | kk-katayama/com_pro | /contest/library/Graph/EulerTour.cpp | UTF-8 | 2,492 | 3.140625 | 3 | [] | no_license | //*******************************************************
// Tree
//*******************************************************
// status of edge
template <typename X>
struct Edge{
int from;
int to;
X cost;
Edge() = default;
Edge(int from, int to, X cost) : from(from), to(to), cost(cost) {}
};
//status of node
template <typename X>
struct Node{
int idx;
vector<Edge<X>> edge;
Node() = default;
explicit Node(int idx) : idx(idx) {
}
};
// tree
template <typename X>
class Tree{
public:
int n; // number of node
vector<Node<X>> node;
vector<vector<int>> par; // par[v][i] := 頂点vから2^i回親をたどった頂点
vector<X> depth; // depth[v] := 根から見たときの頂点vの深さ
vector<int> size; // size[v] := 頂点vを根とする部分木の大きさ
const int M = 20;
void Init_Node() {
rep(i,n) node.emplace_back(i);
par.resize(n, vector<int>(M));
depth.resize(n);
size.resize(n);
}
Tree() = default;
explicit Tree(int n) : n(n) {
Init_Node();
}
// no-weight
Tree(int n, vector<int> a, vector<int> b) : n(n) {
Init_Node();
rep(i,n-1) {
add_edge(a[i], b[i]);
add_edge(b[i], a[i]); // indirected edge
}
}
Tree(int n, vector<int> a, vector<int> b, vector<X> c) : n(n) {
Init_Node();
rep(i,n-1) {
add_edge(a[i], b[i], c[i]);
add_edge(b[i], a[i], c[i]); // indirected edge
}
}
void add_edge(int from, int to, X cost = 1) {
node[from].edge.emplace_back(from, to, cost);
}
int DFS_Init(int v, int p, int d) {
par[v][0] = p;
depth[v] = d;
int siz = 1;
for(auto next: node[v].edge) {
int w = next.to;
X cost = next.cost;
if(w == p) continue;
siz += DFS_Init(w, v, d + cost);
}
return size[v] = siz;
}
// make rooted tree
void Make_root(int root) {
DFS_Init(root, -1, 0);
}
//-------------------------------------------
// 辺に対するオイラーツアー.
// de[v] := vに降りていく辺のインデックス
// ue[v] := vから昇る辺のインデックス
//------------------------------------------
vector<int> de, ue;
void EulerTour(int root) {
de.resize(n);
ue.resize(n);
int idx = 0;
auto dfs = [&](auto self, int v, int p) ->void{
de[v] = idx++;
for(auto next: node[v].edge) {
int w = next.to;
if(w == p) continue;
self(self, w, v);
}
ue[v] = idx++;
};
dfs(dfs, root, -1);
}
};
| true |
d6aecfc7c6e5db3aa4e1d09b6753272bd7b0e52f | C++ | dowmq/HelloGameWorld | /TextFileParser.h | UTF-8 | 2,162 | 3.015625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include <exception>
#include <stdexcept>
#include <fstream>
#include <memory>
#include <map>
class StringParseException : public std::exception
{
public:
StringParseException(const char* msg_) : std::exception{ msg_ } {}
};
class OpenFailException : public StringParseException
{
public:
OpenFailException(const char* msg) : StringParseException(msg) {}
};
class TextFileParser
{
public:
public:
// The TextFileParser will parse line at once.
// two expected value in one line will result in undefined behavior.
explicit TextFileParser(std::string filename);
~TextFileParser();
// If the Parser encounter the pass_char in the frist of the line,
// then Parser will not parse and go to the next line.
// the basic pass_char is '/'
void Register_pass_char(char some_char);
// You can set equals sign char list. basic equals sign = '='
void Set_equals_sign(char sign);
// You can register the "expected word"
// if the parse completed, you can get the result
// example) Register_word_to_be_expected("ip") and
// the file has "ip = 127.0.0.1", you will get "127.0.0.1"
// basically '=' is the equals sign, and you don't wish, call Set_equals_sign()
void Register_expected_string(std::string word);
void Parse();
// the string you are expecting isn't in the container, the method will throw std::out_of_range exception.
std::string GetString(std::string registered_word);
private:
bool is_comment_line(char data_0);
std::ifstream target_file;
bool is_parsed;
size_t number_of_parsed_line;
size_t number_of_elements;
std::vector<char> pass_char;
char equals_sign;
std::vector<std::string> wishlist;
std::map<std::string, std::string> expected_result_list;
public:
// Use when you need Serial String in Text File
// if comment word is 0, the result is undefined.
// if file open is failed, then throws OpenFailException
static std::unique_ptr<std::vector<std::vector<std::string>>> GetSerialString
(std::string filename, char comment_word);
};
| true |
500cb431d23659f1dc143f2f9c8e39e4b0f5fd17 | C++ | Username-AnubhavKhanal/GraphingCalc | /include/MatrixException.hpp | UTF-8 | 592 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <sstream>
class ORDEREXCEPTION
{
private:
int order1[2];
int order2[2];
public:
ORDEREXCEPTION() = default;
ORDEREXCEPTION(int a, int b, int c, int d);
std::string message();
};
class SINGULAREXCEPTION
{
private:
std::string message_str;
public:
SINGULAREXCEPTION();
std::string message();
};
class DIVIDEBYZERO
{
public:
std::string message();
};
class OUTOFRANGE
{
private:
std::string errorMsg;
public:
OUTOFRANGE() = default;
OUTOFRANGE(int m, int n, int row, int col);
std::string message();
};
| true |
03f06ec7be91f11e231512a652e6d626b5b4394b | C++ | ravindra281298/Leetcode-solutions | /Symmetric tree.cpp | UTF-8 | 551 | 3.625 | 4 | [] | no_license | //Problem Link: https://leetcode.com/problems/symmetric-tree/
class Solution {
public:
bool check(TreeNode* ptr1, TreeNode* ptr2){
if(!ptr1 && !ptr2)
return true;
if((!ptr1 && ptr2) || (ptr1 && !ptr2) || (ptr1->val!=ptr2->val))
return false;
return check(ptr1->left,ptr2->right) && check(ptr2->left,ptr1->right);
}
bool isSymmetric(TreeNode* root) {
if(!root || (!root->left && !root->right))
return true;
return check(root->left,root->right);
}
}; | true |
3f6e05da884a8f298894d97636e8e0c8aceaf1a2 | C++ | sckimynwa/ProblemSolving | /C++/BOJ_10464.cpp | UTF-8 | 290 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int i=0;i<n;i++){
long a, b;
cin >> a >> b;
long c = a;
for(long j=a+1;j<=b;j++){
c = c ^ j;
}
cout << c << endl;
}
return 0;
}
| true |
fa2c8a6eb5ec95e6c300649e19917942583c8e9c | C++ | alexandraback/datacollection | /solutions_1673486_1/C++/vsb/program.cpp | UTF-8 | 2,229 | 2.8125 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <queue>
#include <string>
#include <set>
#include <map>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <numeric>
using namespace std;
int nextInt() {
int x;
scanf("%d", &x);
return x;
}
long long nextLong() {
long long x;
scanf("%I64d", &x);
return x;
}
double nextDouble() {
double x;
scanf("%lf", &x);
return x;
}
const int BUFSIZE = 1000000;
char buf[BUFSIZE + 1];
string nextString() {
scanf("%s", buf);
return buf;
}
string nextLine() {
gets(buf);
return buf;
}
int stringToInt(string s) {
stringstream in(s);
int x;
in >> x;
return x;
}
struct Point {
typedef double T;
T x, y;
Point () : x(0), y(0) {}
Point (T x, T y) : x(x), y(y) {}
Point operator - (Point op) const { return Point(x - op.x, y - op.y); }
Point operator + (Point op) const { return Point(x + op.x, y + op.y); }
Point operator * (T op) const { return Point(x * op, y * op); }
T operator * (Point op) const { return x * op.x + y * op.y; }
T operator % (Point op) const { return x * op.y - y * op.x; }
T length2() { return x * x + y * y; }
double length() { return sqrt(length2()); }
};
Point nextPoint() {
double x = nextDouble();
double y = nextDouble();
return Point(x, y);
}
typedef vector<vector<int> > Adj;
int main() {
int T = nextInt();
for (int cas = 1; cas <= T; ++cas) {
int A = nextInt();
int B = nextInt();
vector<double> p(A);
for (int i = 0; i < p.size(); ++i) {
p[i] = nextDouble();
}
vector<double> prob(A + 1, 0);
prob[0] = 1;
for (int i = 1; i <= A; ++i) {
prob[i] = prob[i - 1] * p[i - 1];
if (prob[i] < 1e-20) {
prob[i] = 0;
}
}
double keystrokes = 1 + B + 1;
for (int backspaces = 0; backspaces <= A; ++backspaces) {
double curKeystrokes = prob[A - backspaces] * (backspaces + backspaces + (B - A) + 1)
+ (1 - prob[A - backspaces]) * (backspaces + backspaces + (B - A) + 1 + B + 1);
if (keystrokes > curKeystrokes) {
keystrokes = curKeystrokes;
}
}
printf("Case #%d: %.10lf\n", cas, keystrokes);
}
return 0;
} | true |
8aff931f098b28de43841af44d1529e5b1e4c333 | C++ | hemmerling/cpp-3dogs | /src/modell/general/Coordinates.cpp | UTF-8 | 244 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include "coordinates.h"
Coordinates::~Coordinates(){}
Coordinates::Coordinates(){
// Basisklassen-Variablen werden vom Basisklassen-Konstruktor initialisiert
}
Coordinates::Coordinates(GLfloat x, GLfloat y, GLfloat z){
init(x, y, z);
}
| true |
7156aba4b7037305651c4ecc7550b9c0fb24c447 | C++ | SudoRTan/StudioProject1 | /SP1Framework/Stage.cpp | UTF-8 | 1,877 | 2.875 | 3 | [] | no_license | #include "Stage.h"
#include <sstream>
Stage::Stage(Player* player) : entityManager(player) {
this->player = player;
map = nullptr;
numOfEnemies = 0;
stageNumber = 1; // player starts game at stage1_1
levelNumber = 1;
type = "Stage";
}
Stage::~Stage() {
cleanUp();
}
void Stage::cleanUp(void) {
if (map != nullptr) {
delete map;
map = nullptr;
}
entityManager.cleanUp();
}
void Stage::loadMap(int stageToLoad, int levelToLoad) {
cleanUp();
stageNumber = stageToLoad;
levelNumber = levelToLoad;
map = new Map(stageNumber, levelNumber);
EntityTemplate** enemyPositions = map->getEnemyTemplate();
EntityTemplate** collectiblePositions = map->getCollectibleTemplate();
numOfEnemies = map->getNumberOfEnemies();
int numOfCollectibles = map->getNumberOfCollectibles();
entityManager.loadCollectible(numOfCollectibles, collectiblePositions);
entityManager.loadEnemy(numOfEnemies, enemyPositions);
player->setPosition(map->getPlayerPosition().X, map->getPlayerPosition().Y);
entityManager.init(*map);
}
void Stage::update(SKeyEvent KeyEvent[K_COUNT], double g_dElapsedTime, int& gameState) {
entityManager.update(*map, KeyEvent, g_dElapsedTime, gameState);
/*
if (enemy != nullptr) {
for (int i = 0; i < numOfEnemies; i++) {
if (enemy[i] != nullptr) {
if (enemy[i]->getHealth() <= 0) {
enemy[i]->death(*map);
delete enemy[i];
enemy[i] = nullptr;
}
else {
int enemyReturnValue = 0;
enemyReturnValue = enemy[i]->update(*map, g_dElapsedTime, *player);
}
}
}
}
*/
}
void Stage::render(Console& console) {
ui.render(console, *player, stageNumber, levelNumber);
map->renderMap(console, player->getPositionX(), player->getPositionY());
}
std::string Stage::getType() {
return type;
}
| true |
0c0ccfdaba773153416ef58f8e5302615824bac1 | C++ | firewood/topcoder | /yukicoder_1xx/104.cpp | UTF-8 | 323 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <sstream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string s;
getline(cin, s);
int pos = 0;
for (int i = 0; i < (int)s.length(); ++i) {
pos *= 2;
pos += s[i] == 'R';
}
pos += (1 << s.length());
cout << pos << endl;
return 0;
}
| true |
66abc516e2d6f3c96b2132ea7806d64b98526da7 | C++ | mwerlberger/imp | /deprecated/imageutilities/src/iuio/opencvsource.cpp | UTF-8 | 1,107 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "opencvsource.h"
OpenCVSource::OpenCVSource(unsigned int camId)
{
videocapture_ = new cv::VideoCapture(0);
if (!videocapture_->isOpened())
{
width_ = 0;
height_ = 0;
std::cerr << "OpenCVSource: Error opening camera " << camId << std::endl;
}
videocapture_->release();
videocapture_->set(CV_CAP_PROP_FRAME_WIDTH, 1024);
videocapture_->set(CV_CAP_PROP_FRAME_HEIGHT, 768);
videocapture_->set(CV_CAP_PROP_FPS, 30);
videocapture_->open(0);
width_ = videocapture_->get(CV_CAP_PROP_FRAME_WIDTH);
height_ = videocapture_->get(CV_CAP_PROP_FRAME_HEIGHT);
fps_ = videocapture_->get(CV_CAP_PROP_FPS);
frameNr_ = 0;
}
OpenCVSource::~OpenCVSource()
{
videocapture_->release();
delete videocapture_;
}
cv::Mat OpenCVSource::getImage()
{
if (!videocapture_->read(imageBGR_))
{
std::cerr << "OpenCVSource::getImage(): Error reading from camera" << std::endl;
return cv::Mat::zeros(width_, height_, CV_8UC3);
}
frameNr_++;
cv::cvtColor(imageBGR_, imageRGB_, CV_BGR2RGB);
return imageRGB_;
}
| true |
bddf9ab3c55175c0d0bd3f0a80953e987535d5b9 | C++ | ong-wei-hong/USACO-Guide | /Silver/Prefix Sums/Introduction to Prefix Sums/Subarray Divisibility.cpp | UTF-8 | 406 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define ll long long
const int MxN = 2e5;
int n, sum, m[MxN];
ll ans;
int main(){
cin >> n;
int a;
m[0] = 1;
for(int i=0; i<n; ++i){
cin >> a;
sum = (sum + a % n + n) % n; // +n to account for -ve a
ans += m[sum]; //if the sum of the first j elements mod n = sum mod n, the last i - j elements is divisible by n
++m[sum];
}
cout << ans << "\n";
}
| true |
7a0e8107de6b9518b0a63feedf94d232ccb81bf4 | C++ | ficfiriic/Realization-of-a-multithreaded-operating-system | /src/KernelEv.cpp | UTF-8 | 1,293 | 2.546875 | 3 | [] | no_license | /*
* KernelEv.cpp
*
* Created on: Jun 21, 2019
* Author: OS1
*/
#include "KernelEv.h"
#include "Schedule.h"
#include "System.h"
KernelEv::KernelEv(IVTNo ivtNo) {
// TODO Auto-generated constructor stub
entryForMe = IVTEntry::entries[ivtNo];
this->myOwner = (PCB*) System::running;
this->blocking=0;
this->value=0;
IVTEntry::entries[ivtNo]->setEvent(this);
}
void KernelEv::wait(){
//printf("Usao u wait eventa\n");
if (this->myOwner != System::running) return; //da ne moze da pozove neko ko nije napravio ovaj dogadjaj
//printf("Kernel Event\n");
if (this->value==1)
{this->value = 0;
//printf("Bla bla u pogresnu grana wait eventa\n");
return;}
if (this->value == 0) {
this->value=-1;
this->blocking = 1;
//printf("Usao sam u pravu grana wait eventa\n");
//this->value = 0;
myOwner->status = BLOCKED;
//printf("Blokirao sam vlasnika eventa\n");
dispatch();
}
}
void KernelEv::signal(){
//printf("Usao u signal eventa\n");
if (this->value != -1)
{this->value = 1; /*printf("Signal ne radim nista\n");*/ return;}
this->blocking = 0;
this->value=0;
myOwner->status = READY;
//printf("Odblokirao sam vlasnika eventa\n");
Scheduler::put(this->myOwner);
}
KernelEv::~KernelEv() {
//delete myOwner;
delete entryForMe;
}
| true |
21909a6c36d2313207bf9d2b2587c709671b7eb2 | C++ | uilianries/BeagleBoneBlackGPIO | /include/bbbgpio/file_descriptor.hpp | UTF-8 | 2,720 | 3.34375 | 3 | [
"MIT"
] | permissive | /**
* \file
* \brief Open some file and write/read on start
*
* \author Uilian Ries <uilianries@gmail.com>
*/
#ifndef BBB_GPIO_FILE_DESCRIPTOR_HPP_
#define BBB_GPIO_FILE_DESCRIPTOR_HPP_
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include "stream_operation.hpp"
namespace bbb {
namespace gpio {
/**
* \brief Open some stream (out/in) and check
*/
template <typename F>
class file_descriptor {
protected:
F fs_; /**< Stream to be treated */
public:
/**
* \brief Open file path and check if is valid
* \param file_path file path to be opened
*/
explicit file_descriptor(const boost::filesystem::path& file_path)
{
fs_.open(file_path.string());
if (!fs_) {
std::ostringstream oss;
oss << "Could not open file path: " << file_path;
throw std::runtime_error(file_path.string());
}
}
};
/**
* \brief Open a file as stream output and write some data
*/
template <typename T>
class ofile_descriptor : public file_descriptor<std::ofstream> {
public:
/**
* \brief Open file path, as ostream, and write T data
* \param file_path regular file path to be write
* \param t data to be write in ostream
*/
ofile_descriptor(const boost::filesystem::path& file_path, T t)
: file_descriptor(file_path)
{
push(t);
}
protected:
/**
* \brief Write some data in file and sync
* \param t data to be write
*/
void push(T t)
{
if (!fs_) {
throw std::runtime_error("Could not write in file");
}
fs_ << t;
fs_.flush();
}
};
/**
* \brief Open a stream file to input mode
*/
template <typename T>
class ifile_descriptor : public file_descriptor<std::ifstream> {
public:
/**
* \brief Wrapper to ifstream
* \param file_path Path to be read
*/
explicit ifile_descriptor(const boost::filesystem::path& file_path)
: file_descriptor(file_path)
{
}
protected:
/**
* \brief Sync and read t from file stream
* \param t variable to receive file stream
*/
void pull(T& t)
{
fs_.seekg(0, fs_.beg);
if (!fs_) {
throw std::runtime_error("Could not read file");
}
fs_ >> t;
}
};
} // namespace gpio
} // namespace bbb
#endif // BBB_GPIO_FILE_DESCRIPTOR_HPP_
| true |
d2ae197d044dd13865c051649e9c93af0459fd2b | C++ | SuperABC/Editor | /Editor/Editor/operation.cpp | UTF-8 | 2,465 | 2.671875 | 3 | [] | no_license | #include "operation.h"
#include "editor.h"
extern Editor *editor;
Operation::Operation() {
}
Operation::~Operation() {
}
void Operation::add(int file, int preBlock, int postBlock,
int preLine, int postLine,int preOffset, int postOffset, char ch) {
Step tmp;
tmp.type = OP_INSERT;
tmp.file = file;
tmp.preBlock = preBlock;
tmp.postBlock = postBlock;
tmp.preLine = preLine;
tmp.postLine = postLine;
tmp.prePos = preOffset;
tmp.postPos = postOffset;
tmp.content.push_back(std::string() + ch);
over.clear();
past.push_front(tmp);
if (past.size() > MAX_QUEUE_LENGTH)past.pop_back();
}
void Operation::add(int file, int preBlock, int postBlock,
int preLine, int postLine, int preOffset, int postOffset, std::vector<std::string> str) {
Step tmp;
tmp.type = OP_PASTE;
tmp.file = file;
tmp.preBlock = preBlock;
tmp.postBlock = postBlock;
tmp.preLine = preLine;
tmp.postLine = postLine;
tmp.prePos = preOffset;
tmp.postPos = postOffset;
tmp.content = str;
over.clear();
past.push_front(tmp);
if (past.size() > MAX_QUEUE_LENGTH)past.pop_back();
}
void Operation::del(int file, int preBlock, int postBlock,
int preLine, int postLine, int preOffset, int postOffset, char ch) {
Step tmp;
tmp.type = OP_DELETE;
tmp.file = file;
tmp.preBlock = preBlock;
tmp.postBlock = postBlock;
tmp.preLine = preLine;
tmp.postLine = postLine;
tmp.prePos = preOffset;
tmp.postPos = postOffset;
tmp.content.push_back(std::string() + ch);
over.clear();
past.push_front(tmp);
if (past.size() > MAX_QUEUE_LENGTH)past.pop_back();
}
void Operation::del(int file, int preBlock, int postBlock,
int preLine, int postLine, int preOffset, int postOffset, std::vector<std::string> str) {
Step tmp;
tmp.type = OP_CUT;
tmp.file = file;
tmp.preBlock = preBlock;
tmp.postBlock = postBlock;
tmp.preLine = preLine;
tmp.postLine = postLine;
tmp.prePos = preOffset;
tmp.postPos = postOffset;
tmp.content = str;
over.clear();
past.push_front(tmp);
if (past.size() > MAX_QUEUE_LENGTH)past.pop_back();
}
Step Operation::regret() {
if (past.empty())return Step();
Step tmp = past.front();
over.push_back(tmp);
past.pop_front();
return tmp;
}
Step Operation::ahead() {
if (over.empty())return Step();
Step tmp = over.back();
over.pop_back();
past.push_front(tmp);
return tmp;
}
void Operation::setCutPre(int preBlock, int preLine, int preOffset) {
over.back().preBlock = preBlock;
over.back().preLine = preLine;
over.back().prePos = preOffset;
} | true |
0d22b085c13098efdb1f2414d0af9cfbea498f2f | C++ | fjnkt98/gazoushori | /7th/p07-1-1.cpp | SHIFT_JIS | 6,716 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#include <opencv/highgui.h>
const char useChar[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()+,-;=@[]^_`{}~";
const char charImgPath[] = "C:/Users/Kohta.AKIRA-PC/Documents/Visual Studio 2013/Projects/ConsoleApplication1/ConsoleApplication1/char";
typedef struct {
double mean; // ϖ邳
} Param;
// --------------------------- Function prototype declaration --------------------------
void subImage(IplImage* subImg, IplImage* img, int x, int y, int w, int h);
void calcParam(Param *param, IplImage* img);
double calcDistance(Param* a, Param* b);
Param* calcCharParam(CvSize* size);
Param* calcImgparam(CvSize* outSize, IplImage* img1, CvSize size);
char* genString(Param* paramChar, Param* paramImg, CvSize outSize);
void writeFile(char *outStr, Param* paramImg, CvSize outSize, char* imgFilename);
// --------------------------------------------------------------------------------------
void main(int argc, char* argv[])
{
IplImage* img1;
// NIvṼ`FbN
printf("argc = %d\n", argc);
for (int k = 0; k < argc; k++) {
printf("argv[%d] = %s\n", k, argv[k]);
}
printf("\n\n");
if (argc < 2) {
printf("t@Cw肵ĂB\n");
return;
}
// 摜f[^̓ǂݍ
if ((img1 = cvLoadImage(argv[1], CV_LOAD_IMAGE_COLOR)) == NULL) { // (OCXP[łĂ)J[摜Ƃēǂݍ
printf("摜t@C̓ǂݍ݂Ɏs܂B\n");
return;
}
// ǂݍ摜̕\
cvNamedWindow("Original");
cvShowImage("Original", img1);
// -------------------------------------------------------------
Param* paramChar = NULL;
Param* paramImg = NULL;
char *outStr = NULL;
CvSize outSize;
CvSize size;
paramChar = calcCharParam(&size);
paramImg = calcImgparam(&outSize, img1, size);
outStr = genString(paramChar, paramImg, outSize);
printf("%s\n", outStr);
writeFile(outStr, paramImg, outSize, argv[1]);
cvWaitKey(0);
cvDestroyAllWindows();
}
// 摜̈ꕔ(摜ubN)o
void subImage(IplImage* subImg, IplImage* img, int x, int y, int w, int h) {
// 0ŏ(img̕⍂ꍇ̑)
cvSetZero(subImg);
for (int i = y; i < y + h && i < img->height; i++) {
for (int j = x; j < x + w && j < img->width; j++) {
subImg->imageData[(i - y) * subImg->widthStep + (j - x) * 3 + 2] = img->imageData[img->widthStep * i + j * 3 + 2];
subImg->imageData[(i - y) * subImg->widthStep + (j - x) * 3 + 1] = img->imageData[img->widthStep * i + j * 3 + 1];
subImg->imageData[(i - y) * subImg->widthStep + (j - x) * 3 + 0] = img->imageData[img->widthStep * i + j * 3 + 0];
}
}
}
// 摜p[^(邳̕ϒl)vZ
void calcParam(Param *param, IplImage* img) {
long sum = 0;
long npixel = img->width * img->height;
double brightness = 0.0;
for (int y = 0; y < img->height; y++){
for (int x = 0; x < img->width; x++){
sum += (unsigned char)img->imageData[img->widthStep * y + x * 3 + 0] * 0.114478
+ (unsigned char)img->imageData[img->widthStep * y + x * 3 + 1] * 0.586611
+ (unsigned char)img->imageData[img->widthStep * y + x * 3 + 2] * 0.298912;
}
}
brightness = (double)sum / npixel;
param->mean = brightness;
}
double calcDistance(Param* a, Param* b){
double r;
r = fabsf(a->mean - b->mean);
return r;
}
Param* calcCharParam(CvSize* size){
IplImage* img = NULL;
char fn[256];
Param* param = (Param *)malloc(sizeof(Param) * strlen(useChar));
for (int i = 0; i < strlen(useChar); i++) {
sprintf_s(fn, "%s/%c.bmp", charImgPath, useChar[i]);
if ((img = cvLoadImage(fn, CV_LOAD_IMAGE_COLOR)) == NULL) { // (OCXP[łĂ)J[摜Ƃēǂݍ
printf("摜t@C̓ǂݍ݂Ɏs܂B\n");
return NULL;
}
calcParam(¶m[i], img);
printf("%s : %f\n", fn, param[i].mean);
}
size->width = img->width;
size->height = img->height;
// ------------------ l0-255Ɋg(͖Ă܂)
double maxV = param[0].mean;
double minV = param[0].mean;
for (int i = 0; i < strlen(useChar); i++) {
minV = (minV < param[i].mean) ? minV : param[i].mean;
maxV = (maxV > param[i].mean) ? maxV : param[i].mean;
}
for (int i = 0; i < strlen(useChar); i++) {
param[i].mean = (param[i].mean - minV) / (maxV - minV) * 255;
}
return param;
}
Param* calcImgparam(CvSize* outSize, IplImage* img1, CvSize size){
outSize->width = img1->width / size.width + 1;
outSize->height = img1->height / size.height + 1;
Param* paramImg = (Param *)malloc(sizeof(Param) * outSize->width * outSize->height);
IplImage* subImg = cvCreateImage(size, img1->depth, img1->nChannels);
for (int i = 0; i < outSize->height; i++) {
for (int j = 0; j < outSize->width; j++) {
subImage(subImg, img1, j * size.width, i * size.height, size.width, size.height);
calcParam(¶mImg[i * outSize->width + j], subImg);
}
}
return paramImg;
}
char* genString(Param* paramChar, Param* paramImg, CvSize outSize) {
char* outStr = (char *)malloc(sizeof(char) * ((outSize.width + 1) * outSize.height + 1)); // outSize.width u+1v ͉sAṒu+1v '\0'
double min;
int minInd;
int x, y;
for (y = 0; y < outSize.height; y++) {
for (x = 0; x < outSize.width; x++) {
min = calcDistance(¶mChar[0], ¶mImg[y * outSize.width + x]);
minInd = 0;
for (int i = 1; i < strlen(useChar); i++) {
if (min > calcDistance(¶mChar[i], ¶mImg[y * outSize.width + x])){
min = calcDistance(¶mChar[i], ¶mImg[y * outSize.width + x]);
minInd = i;
}
}
outStr[y * (outSize.width + 1) + x] = useChar[minInd];
}
outStr[y * (outSize.width + 1) + outSize.width] = '\n';
}
outStr[outSize.height * (outSize.width + 1)] = '\0';
return outStr;
}
// t@Cւ̌ʏo
void writeFile(char *outStr, Param* paramImg, CvSize outSize, char* imgFilename) {
FILE *fp;
char filename[256];
char *ext_p;
strcpy_s(filename, 256, imgFilename); // ǂݍ摜̃t@CRs[
ext_p = strrchr(filename, '.');
*ext_p = '\0'; // t@Cgq
strcat_s(filename, ".txt");
if (fopen_s(&fp, filename, "w") == 0) { // fopen()Ɠ{̂ fopen_s()ɁBԂl̎dlႤ̂ŒӁB
fprintf_s(fp, "%s", outStr);
fclose(fp);
}
} | true |
a51a75eba9c364bb561284fadcc4b710996f8a6d | C++ | dev-jelly/algorithm | /boj/1085/main.cpp | UTF-8 | 296 | 2.984375 | 3 | [] | no_license | //
// Created by jelly on 03/12/2019.
//
#include <iostream>
using namespace std;
int main() {
int x, y, w, h;
cin >> x >> y >> w >> h;
int min = x;
if (min > y) min = y;
if (min > (w - x)) min = w - x;
if (min > (h - y)) min = h - y;
cout << min;
return 0;
}
| true |
c9813e7cff52ce012d3cd2aa331d956b6a4dfff8 | C++ | ParkGY94/My-Project-Game- | /My RPG ver1.0.cpp | UHC | 7,037 | 3 | 3 | [] | no_license | #include <iostream>
#include <time.h>
using namespace std;
class Monster;
class Player {
public:
Player();
void Attack(Monster *A);
void DefeatMonster(Monster *A);
void Skill(Monster *A);
void LevelUp();
void ViewPlayerStats() const;
int GetPlayerHP() { return HP; }
int GetPlayerHPMax() { return HPMax; }
int GetPlayerMP() { return MP; }
int GetPlayerMPMax() { return MPMax; }
int GetPlayerAtt() { return Att; }
int GetPlayerDef() { return Def; }
int GetPlayerLv() { return Lv; }
int GetPlayerExp() { return Exp; }
void SetPlayerHP(int num) {HP = num;}
void ChangePlayerHP(int HP_) { HP -= HP_; }
void SetPlayerMP(int num) { MP = num; }
void ChangePlayerMP(int MP_) { MP -= MP_; }
void SetPlayerAtt(int num) { Att = num; }
void SetPlayerDef(int num) { Def = num; }
void ChangePlayerLv(int Lv_) { Lv += Lv_; }
void ChangePlayerExp(int Exp_) { Exp += Exp_; }
private:
int HP, HPMax, MP, MPMax, Att, Def;
int Lv, Exp, Explim;
};
class Monster {
public:
Monster();
Monster(int Lv);
virtual void Attack(Player *player_);
virtual void MonsterHP();
virtual int GetMonsterHP() { return HP; }
virtual int GetMonsterAtt() { return Att; }
virtual int GetMonsterDef() { return Def; }
virtual int GetMonsterLv() { return Lv; }
virtual void SetMonsterHP(int num) { HP = num; }
virtual void ChangeMonsterHP(int HP_) { HP -= HP_; }
protected:
int HP, Att, Def;
int Lv;
};
class Rat : public Monster { //Level 1 Rat
public:
Rat() { Monster(1); }
private:
};
class Rabbit : public Monster { //Level 2 Rabbit
public:
Rabbit() { Monster(2); }
private:
};
class Snake : public Monster { //Level 3 Rat
public:
Snake() { Monster(3); }
private:
};
void MainScreen();
void ShowMonster();
void Resting(Player *p);
void HuntingRat(Player *p);
void HuntingRabbit(Player *p);
void HuntingSnake(Player *p);
int main() {
Player *My= new Player();
int a,b;
int c = 0;
while (c!=1) {
MainScreen();
cin >> a;
switch (a) {
case 1: {
ShowMonster();
cin >> b;
switch (b) {
case 1:
HuntingRat(My);
break;
case 2:
HuntingRabbit(My);
break;
case 3:
HuntingSnake(My);
break;
}
break;
}
case 2: {
My->ViewPlayerStats();
break;
}
case 3:
Resting(My);
break;
case 4:
c = 1;
break;
}
}
}
Player::Player() : Lv(1), Exp(0), Explim(50), HP(300), HPMax(300),
MP(50), MPMax(50), Att(50), Def(30) {}
void Player::Attack(Monster *A) { //÷̾ ϴ Լ
cout << " մϴ." << endl;
if (Att - (A->GetMonsterDef() / 2) <= 1) { A->ChangeMonsterHP(1); } // Att - Def 1/2 1 1 ظ ش
else { A->ChangeMonsterHP(Att - (A->GetMonsterDef() / 2)); }
if (A->GetMonsterHP() > 0) { A->MonsterHP(); }
else { DefeatMonster(A); }
}
void Player::DefeatMonster(Monster *A) { // Լ
cout << "Ϳ ¸Ͽϴ. " << (A->GetMonsterLv() * 10)
<< " ġ ȹϿϴ. " << endl;
ChangePlayerExp(A->GetMonsterLv() * 10);
if (Exp >= Explim) { LevelUp(); }
}
void Player::Skill(Monster *A) { //ųԼ
cout << "Ϳ ų մϴ." << endl;
if ((Att * 2) - (A->GetMonsterDef() / 2) <= 1) { A->ChangeMonsterHP(1); }
else { A->ChangeMonsterHP((Att * 2) - (A->GetMonsterDef() / 2)); }
MP -= 15;
if (A->GetMonsterHP() > 0) { A->MonsterHP(); }
else { DefeatMonster(A); }
}
void Player::LevelUp() { // Լ
Lv++; Exp = Exp - Explim;
Explim = (Explim * 2) + 10; HPMax += 50; HP = HPMax;
MPMax += 10; MP = MPMax; Att += 25; Def += 15;
cout << "մϴ " << Lv << " Ǿϴ." << endl;
}
void Player::ViewPlayerStats() const {
cout << "÷̾ " << Lv << "Դϴ." << endl;
cout << "÷̾ HP " << HP << "/" << HPMax << "Դϴ." << endl;
cout << "÷̾ MP " << MP << "/" << MPMax << "Դϴ." << endl;
cout << "÷̾ Att " << Att << "Դϴ." << endl;
cout << "÷̾ Def " << Def << "Դϴ." << endl;
cout << "÷̾ ġ " << Exp << "/" << Explim << " Դϴ." << endl;
}
Monster::Monster() : Lv(1), HP(150), Att(20), Def(20) {}
Monster::Monster(int Lv) {
HP = (Lv * 75) + 75; Att = Lv * 20; Def = Lv * 20;
}
void Monster::Attack(Player *player_) {
cout << "Ͱ մϴ." << endl;
if (Att - (player_->GetPlayerDef() / 2) <= 1) { player_->ChangePlayerHP(1); }
else { player_->ChangePlayerHP(Att - (player_->GetPlayerDef() / 2)); }
}
void Monster::MonsterHP() { // Hp Ÿ Լ
cout << " HP " << HP << "ҽϴ. " << endl;
}
void MainScreen() {
cout << endl;
cout << " ȭ" << endl;
cout << "ϴ ȣ Էϼ" << endl;
cout << "1. Ѵ." << endl;
cout << "2. ¸ ." << endl;
cout << "3. Ѵ" << endl;
cout << "4. " << endl;
}
void ShowMonster() {
cout << "ϴ ȣ Էϼ" << endl;
cout << "1. Lv1 Rat" << endl;
cout << "2. Lv2 Rabbit" << endl;
cout << "3. Lv3 Snake" << endl;
}
void Resting(Player *p) {
p->ChangePlayerHP(-50);
if (p->GetPlayerHP() >= p->GetPlayerHPMax()) { p->SetPlayerHP(p->GetPlayerHPMax()); }
p->ChangePlayerMP(-20);
if (p->GetPlayerMP() >= p->GetPlayerMPMax()) { p->SetPlayerMP(p->GetPlayerMPMax()); }
cout << " HP MP ȸϿϴ." << endl;
}
void HuntingRat(Player *p) {
Monster* R = new Rat();
int* choice = new int (0);
while (true) {
cout << "1. ⺻" << endl;
cout << "2. ų(Ŀ)" << endl;
cin >> *choice;
switch (*choice) {
case 1:
p->Attack(R);
break;
case 2:
p->Skill(R);
break;
}
if (R->GetMonsterHP() <= 0) { break; }
R->Attack(p);
}
delete choice;
delete R;
}
void HuntingRabbit(Player* p) {
Monster* R = new Rabbit();
int* choice = new int(0);
while (true) {
cout << "1. ⺻" << endl;
cout << "2. ų(Ŀ)" << endl;
cin >> *choice;
switch (*choice) {
case 1:
p->Attack(R);
break;
case 2:
p->Skill(R);
break;
}
if (R->GetMonsterHP() <= 0) { break; }
R->Attack(p);
}
delete choice;
delete R;;
}
void HuntingSnake(Player* p) {
Monster* R = new Snake();
int* choice = new int(0);
while (true) {
cout << "1. ⺻" << endl;
cout << "2. ų(Ŀ)" << endl;
cin >> *choice;
switch (*choice) {
case 1:
p->Attack(R);
break;
case 2:
p->Skill(R);
break;
}
if (R->GetMonsterHP() <= 0) { break; }
R->Attack(p);
}
delete choice;
delete R;
} | true |
6e58859c38ef1d7c2d7e6fe167dd1b958daff621 | C++ | SeungHoons/algorithm_Hoons | /algorithm_Hoons/algorithm_Hoons/BackJoon/2581.cpp | UTF-8 | 801 | 2.984375 | 3 | [] | no_license |
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int inputNum1;
int inputNum2;
int min = 10000;
int max = 0;
bool bol = false;
scanf("%d", &inputNum1);
scanf("%d", &inputNum2);
for (int j = inputNum1; j <= inputNum2; j++)
{
int num = sqrt(j) + 1;
bol = false;
for (int i = 2; i <num; i++)
{
if (j%i == 0)
{
bol = true;
break;
}
}
if (j == 1 || j==0)
continue;
if (!bol || j == 2)
{
max += j;
if (min>j)
{
min = j;
}
}
}
if (max == 0)
{
printf("-1");
}
else
printf("%d\n%d", max, min);
} | true |
13aae5b20750afd8ede4168891bdeda36b77d6a3 | C++ | veer11997/DSA | /Linear-search/sorting-comparetor.cpp | UTF-8 | 820 | 3.3125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
bool mycompare(pair<string,int> p1,pair<string,int> p2)
{
// first name ,second sal sal>name pref
//alice 86 bob 86 lexicographicall to s1<s2
if(p1.second==p2.second)
return p1.first<p2.first;
return p1.second>p2.second;// alice 90 bob 86 pic forward whose sal big
}
int main()
{
// stl sorting and generic compareter sorting
int min_sal;
int n;
pair<string,int> emp[100];
cin>>min_sal;
cin>>n;
string name;
int salary;
for(int i=0;i<n;i++)
{
cin>>name>>salary;
emp[i].first=name;
emp[i].second=salary;
}
sort(emp,emp+n,mycompare);
for(int i=0;i<n;i++){
if(emp[i].second>=min_sal)
cout<<emp[i].first<<" "<<emp[i].second<<endl;
}
return 0;
}
| true |
240e3e705135d585542a1a820a8784f31587b970 | C++ | vsuu/elib | /unittest/BerTLVTest.cpp | UTF-8 | 1,563 | 2.546875 | 3 | [] | no_license | #include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
#include "BerTLV.h"
#include "strop.h"
using namespace std;
using namespace elib;
void TestBerTLV()
{
try
{
TagType tag;
char * tagstr = "\x70\x80";
char * tagstr1 = "\x1F\x70";
BerTLV::ParseTag(tagstr, tagstr + 2, tag);
assert(tag == 0x70);
BerTLV::ParseTag(tagstr1, tagstr1 + 2, tag);
assert(tag == 0x1F70);
uint32_t len;
char *lenstr = "\x81\x10";
char *lenstr2 = "\x79\x10";
char *lenstr3 = "\x82\x10\x10";
BerTLV::ParseLen(lenstr, lenstr + 2, len);
assert(len == 0x10);
BerTLV::ParseLen(lenstr2, lenstr2 + 2, len);
assert(len == 0x79);
BerTLV::ParseLen(lenstr3, lenstr3 + 3, len);
assert(len == 0x1010);
BerTLV tlv(0x70);
tlv.SetValue(Hex2Bin("5F340101"));
tlv.AppendChild(BerTLV(0x5A, Hex2Bin("123456")));
tlv.AppendChild(BerTLV(0xBF0C));
auto ptr = tlv.Find(0xBF0C);
ptr->AppendChild(BerTLV(0x9F4D, Hex2Bin("0B0A")));
tlv.InsertChild(0x9F4D, BerTLV(Hex2Bin("95051122334455")));
BinData out_buf;
BerTLV::EncapTLV(tlv, back_inserter(out_buf));
cout << out_buf.ToHex().c_str() << endl;
BerTLV tlv2;
BerTLV::ParseTLV(begin(out_buf), end(out_buf), tlv2);
stringstream ss(ios_base::in | ios_base::out | ios_base::binary);
BerTLV::EncapTLV(tlv, ss);
tlv2.Clear();
BerTLV::ParseTLV(ss, tlv2);
out_buf.clear();
tlv2.EncapTLV(back_inserter(out_buf));
cout << out_buf.ToHex().c_str() << endl;
}
catch (const exception &e)
{
cout << "error:" << endl;
cout << e.what() << endl;
}
} | true |
bbcf4b9c0a5047ae6e377ee361ef849ac65925fb | C++ | yatharth17/Hactoberfest2019 | /kadane's algo(for maximum subarray).cpp | UTF-8 | 342 | 2.921875 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
int main()
{
int a[100];
for(int i=0;i<5;i++)
{
cin>>a[i];
}
int cs=0;
int ms=0;
for(int i=0;i<5;i++)
{
cs=cs+a[i];
if(cs<0)
{
cs=0;
}
ms=max(cs,ms); ///inbuilt function for maximum sum
}
cout<<ms;
}
| true |
d68400de71eeccc412db3987504071716566f656 | C++ | sitekwb/wut-studies | /Semester_3/AISDI/Linear/tests/LinkedListTests.cpp | UTF-8 | 27,749 | 2.890625 | 3 | [] | no_license | #include "../src/LinkedList.h"
#include <initializer_list>
#include <complex>
#include <cstdint>
#include <cstddef>
#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/mpl/list.hpp>
#define SENTINELS_NUMBER 1
namespace
{
class OperationCountingObject
{
public:
OperationCountingObject(int value_ = 0)
: value(value_)
{
++constructedObjects;
}
OperationCountingObject(const OperationCountingObject& other)
: value(std::move(other.value))
{
++constructedObjects;
++copiedObjects;
}
OperationCountingObject(OperationCountingObject&& other)
: value(other.value)
{
++constructedObjects;
++movedObjects;
}
~OperationCountingObject()
{
++destroyedObjects;
}
OperationCountingObject& operator=(const OperationCountingObject& other)
{
++assignedObjects;
value = other.value;
return *this;
}
OperationCountingObject& operator=(OperationCountingObject&& other)
{
++assignedObjects;
++movedObjects;
value = std::move(other.value);
return *this;
}
operator int() const
{
return value;
}
static void resetCounters()
{
constructedObjects = 0;
destroyedObjects = 0;
copiedObjects = 0;
movedObjects = 0;
assignedObjects = 0;
}
static std::size_t constructedObjectsCount()
{
return constructedObjects;
}
static std::size_t destroyedObjectsCount()
{
return destroyedObjects;
}
static std::size_t copiedObjectsCount()
{
return copiedObjects;
}
static std::size_t movedObjectsCount()
{
return movedObjects;
}
static std::size_t assignedObjectsCount()
{
return assignedObjects;
}
private:
int value;
static std::size_t constructedObjects;
static std::size_t destroyedObjects;
static std::size_t copiedObjects;
static std::size_t movedObjects;
static std::size_t assignedObjects;
};
std::size_t OperationCountingObject::constructedObjects = 0;
std::size_t OperationCountingObject::destroyedObjects = 0;
std::size_t OperationCountingObject::copiedObjects = 0;
std::size_t OperationCountingObject::movedObjects = 0;
std::size_t OperationCountingObject::assignedObjects = 0 ;
std::ostream& operator<<(std::ostream& out, const OperationCountingObject& obj)
{
return out << '<' << static_cast<int>(obj) << '>';
}
struct Fixture
{
Fixture()
{
OperationCountingObject::resetCounters();
}
};
} // namespace
template <typename T>
using LinearCollection = aisdi::LinkedList<T>;
using TestedTypes = boost::mpl::list<std::int32_t,
std::uint64_t,
std::complex<std::int32_t>,
OperationCountingObject>;
using std::begin;
using std::end;
BOOST_FIXTURE_TEST_SUITE(VectorTests, Fixture)
template <typename T>
void thenCollectionContainsValues(const LinearCollection<T>& collection,
std::initializer_list<int> expected)
{
BOOST_CHECK_EQUAL_COLLECTIONS(begin(collection), end(collection),
begin(expected), end(expected));
}
template <typename T>
void thenConstructedObjectsCountWas(std::size_t count)
{
(void) count;
// unable to check it (in a simple way) for all objects, hence template specialization.
}
template <typename T>
void thenDestroyedObjectsCountWas(std::size_t count)
{
(void) count;
// unable to check it (in a simple way) for all objects, hence template specialization.
}
template <typename T>
void thenCopiedObjectsCountWas(std::size_t count)
{
(void) count;
// unable to check it (in a simple way) for all objects, hence template specialization.
}
template <typename T>
void thenMovedObjectsCountWas(std::size_t count)
{
(void) count;
// unable to check it (in a simple way) for all objects, hence template specialization.
}
template <typename T>
void thenAssignedObjectsCountWas(std::size_t count)
{
(void) count;
// unable to check it (in a simple way) for all objects, hence template specialization.
}
template <>
void thenConstructedObjectsCountWas<OperationCountingObject>(std::size_t count)
{
BOOST_CHECK_EQUAL(OperationCountingObject::constructedObjectsCount(), count);
}
template <>
void thenDestroyedObjectsCountWas<OperationCountingObject>(std::size_t count)
{
BOOST_CHECK_EQUAL(OperationCountingObject::destroyedObjectsCount(), count);
}
template <>
void thenCopiedObjectsCountWas<OperationCountingObject>(std::size_t count)
{
BOOST_CHECK_EQUAL(OperationCountingObject::copiedObjectsCount(), count);
}
template <>
void thenMovedObjectsCountWas<OperationCountingObject>(std::size_t count)
{
BOOST_CHECK_EQUAL(OperationCountingObject::movedObjectsCount(), count);
}
template <>
void thenAssignedObjectsCountWas<OperationCountingObject>(std::size_t count)
{
BOOST_CHECK_EQUAL(OperationCountingObject::assignedObjectsCount(), count);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollection_WhenCreatedWithDefaultConstructor_ThenItIsEmpty,
T,
TestedTypes)
{
const LinearCollection<T> collection;
BOOST_CHECK(collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenAddingItem_ThenItIsNoLongerEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(T{});
BOOST_CHECK(!collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenGettingIterators_ThenBeginEqualsEnd,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK(begin(collection) == end(collection));
BOOST_CHECK(const_cast<const LinearCollection<T>&>(collection).begin() == collection.end());
BOOST_CHECK(collection.cbegin() == collection.cend());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenGettingIterator_ThenBeginIsNotEnd,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(T{});
BOOST_CHECK(collection.begin() != collection.end());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollectionWithOneElement_WhenIterating_ThenElementIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(753);
auto it = collection.begin();
BOOST_CHECK_EQUAL(*it, 753);
BOOST_CHECK(++it == collection.end());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenIterator_WhenPostIncrementing_ThenPreviousPositionIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(T{});
auto it = collection.begin();
auto postIncrementedIt = it++;
BOOST_CHECK(postIncrementedIt == collection.begin());
BOOST_CHECK(it == collection.end());
BOOST_CHECK(postIncrementedIt == collection.cbegin());
BOOST_CHECK(it == collection.cend());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenIterator_WhenPreIncrementing_ThenNewPositionIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(T{});
auto it = collection.begin();
auto preIncrementedIt = ++it;
BOOST_CHECK(preIncrementedIt == it);
BOOST_CHECK(it == collection.end());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEndIterator_WhenIncrementing_ThenOperationThrows,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK_THROW(collection.end()++, std::out_of_range);
BOOST_CHECK_THROW(++(collection.end()), std::out_of_range);
BOOST_CHECK_THROW(collection.cend()++, std::out_of_range);
BOOST_CHECK_THROW(++(collection.cend()), std::out_of_range);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEndIterator_WhenDecrementing_ThenIteratorPointsToLastItem,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(1);
collection.append(2);
auto it = collection.end();
--it;
BOOST_CHECK_EQUAL(*it, 2);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenIterator_WhenPreDecrementing_ThenNewIteratorValueIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(1);
auto it = collection.end();
auto preDecremented = --it;
BOOST_CHECK(it == preDecremented);
BOOST_CHECK_EQUAL(*it, 1);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenIterator_WhenPostDecrementing_ThenOldIteratorValueIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(1);
auto it = collection.end();
auto postDecremented = it--;
BOOST_CHECK(postDecremented == collection.end());
BOOST_CHECK_EQUAL(*it, 1);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenBeginIterator_WhenDecrementing_ThenOperationThrows,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK_THROW(collection.begin()--, std::out_of_range);
BOOST_CHECK_THROW(--(collection.begin()), std::out_of_range);
BOOST_CHECK_THROW(collection.cbegin()--, std::out_of_range);
BOOST_CHECK_THROW(--(collection.cbegin()), std::out_of_range);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEndIterator_WhenDereferencing_ThenOperationThrows,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK_THROW(*collection.end(), std::out_of_range);
BOOST_CHECK_THROW(*collection.cend(), std::out_of_range);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenConstIterator_WhenDereferencing_ThenItemIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection = { 10, 20, 30 };
//auto it = ++collection.cbegin();
//BOOST_CHECK_EQUAL(*it, 20);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenIterator_WhenDereferencing_ThenItemCanBeChanged,
T,
TestedTypes)
{
LinearCollection<T> collection = { 10, 20, 30 };
auto it = ++begin(collection);
*it = 500;
thenCollectionContainsValues(collection, { 10, 500, 30 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenIterator_WhenAddingInteger_ThenAdvancedIteratorIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection = { 2001, 2010, 2051 };
auto it = begin(collection);
BOOST_CHECK(it + 3 == end(collection));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenIterator_WhenSubstractingInteger_ThenChangedIteratorIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection = { 2001, 2010, 2051 };
auto it = end(collection);
BOOST_CHECK(it - 2 == ++begin(collection));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenAddingItem_ThenItemIsInCollection,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.append(42);
thenCollectionContainsValues(collection, { 42 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollection_WhenInitializingFromList_ThenAllItemsAreInCollection,
T,
TestedTypes)
{
const LinearCollection<T> collection = { 1410, 753, 1789 };
thenCollectionContainsValues(collection, { 1410, 753, 1789 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenCreatingCopy_ThenAllItemsAreCopied,
T,
TestedTypes)
{
LinearCollection<T> collection = { 1410, 753, 1789 };
LinearCollection<T> other{collection};
collection.append(1024);
thenCollectionContainsValues(collection, { 1410, 753, 1789, 1024 });
thenCollectionContainsValues(other, { 1410, 753, 1789 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenCreatingCopy_ThenBothCollectionsAreEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection;
LinearCollection<T> other{collection};
BOOST_CHECK(other.isEmpty());
BOOST_CHECK(collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenMovingToOther_ThenAllItemsAreMoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 1410, 753, 1789 };
OperationCountingObject::resetCounters();
LinearCollection<T> other{std::move(collection)};
thenCollectionContainsValues(other, { 1410, 753, 1789 });
thenConstructedObjectsCountWas<T>(SENTINELS_NUMBER);
thenCopiedObjectsCountWas<T>(0);
thenAssignedObjectsCountWas<T>(0);
thenMovedObjectsCountWas<T>(0);
thenDestroyedObjectsCountWas<T>(0);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenMovingToOther_ThenSecondCollectionsIsEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection;
LinearCollection<T> other{std::move(collection)};
BOOST_CHECK(other.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenAssigningToOther_ThenAllElementsAreCopied,
T,
TestedTypes)
{
const LinearCollection<T> collection = { 1, 2, 3, 4 };
LinearCollection<T> other = { 100, 200, 300, 400 };
other = collection;
thenCollectionContainsValues(other, { 1, 2, 3, 4 });
thenCollectionContainsValues(collection, { 1, 2, 3, 4 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenAssigningToOther_ThenOtherCollectionIsEmpty,
T,
TestedTypes)
{
const LinearCollection<T> collection;
LinearCollection<T> other = { 100, 200, 300, 400 };
other = collection;
BOOST_CHECK(other.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenSelfAssigning_ThenNothingHappens,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection = collection;
BOOST_CHECK(collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNotEmptyCollection_WhenSelfAssigning_ThenNothingHappens,
T,
TestedTypes)
{
LinearCollection<T> collection = { 100, 200, 300, 400 };
collection = collection;
thenCollectionContainsValues(collection, { 100, 200, 300, 400 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenMoveAssigning_ThenAllElementsAreMoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 1, 2, 3, 4 };
LinearCollection<T> other = { 100, 200, 300, 400 };
OperationCountingObject::resetCounters();
other = std::move(collection);
thenCollectionContainsValues(other, { 1, 2, 3, 4 });
thenConstructedObjectsCountWas<T>(0);
thenCopiedObjectsCountWas<T>(0);
thenAssignedObjectsCountWas<T>(0);
thenMovedObjectsCountWas<T>(0);
thenDestroyedObjectsCountWas<T>(4);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenMoveAssigning_ThenNewCollectionIsEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection;
LinearCollection<T> other = { 100, 200, 300, 400 };
other = std::move(collection);
BOOST_CHECK(other.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollection_WhenAppendingItem_ThenItemIsLast,
T,
TestedTypes)
{
LinearCollection<T> collection = { 1, 2, 3 };
collection.append(42);
thenCollectionContainsValues(collection, { 1, 2, 3, 42 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenPrependingItem_ThenItemIsAdded,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.prepend(300);
thenCollectionContainsValues(collection, { 300 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPrependingItem_ThenItemIsFirst,
T,
TestedTypes)
{
LinearCollection<T> collection = { 1, 2 };
collection.prepend(300);
thenCollectionContainsValues(collection, { 300, 1, 2 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenGettingSize_ThenZeroIsReturned,
T,
TestedTypes)
{
const LinearCollection<T> collection;
BOOST_CHECK_EQUAL(collection.getSize(), 0);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenGettingSize_ThenElementCountIsReturned,
T,
TestedTypes)
{
const LinearCollection<T> collection = { 12, 100, 500 };
BOOST_CHECK_EQUAL(collection.getSize(), 3);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollection_WhenChangingIt_ThenItsSizeAlsoChanges,
T,
TestedTypes)
{
LinearCollection<T> collection = { 72, 27, 77 };
collection.append(99);
BOOST_CHECK_EQUAL(collection.getSize(), 4);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPrependingItem_ThenSizeIsUpdated,
T,
TestedTypes)
{
LinearCollection<T> collection = { 72, 27, 77 };
collection.prepend(99);
BOOST_CHECK_EQUAL(collection.getSize(), 4);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenInsertingItem_ThenItemIsAdded,
T,
TestedTypes)
{
LinearCollection<T> collection;
collection.insert(begin(collection), 42);
thenCollectionContainsValues(collection, { 42 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenInsertingAtBegin_ThenItemIsPrepended,
T,
TestedTypes)
{
LinearCollection<T> collection = { 11, 12, 13 };
collection.insert(begin(collection), 42);
thenCollectionContainsValues(collection, { 42, 11, 12, 13 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenInsertingAtEnd_ThenItemIsAppended,
T,
TestedTypes)
{
LinearCollection<T> collection = { 11, 12, 13 };
collection.insert(end(collection), 42);
thenCollectionContainsValues(collection, { 11, 12, 13, 42 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenInsertingInMiddle_ThenItemInserted,
T,
TestedTypes)
{
LinearCollection<T> collection = { 11, 12, 13 };
collection.insert(++begin(collection), 42);
thenCollectionContainsValues(collection, { 11, 42, 12, 13 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenInserting_ThenSizeIsUpdated,
T,
TestedTypes)
{
LinearCollection<T> collection = { 101, 102, 103 };
collection.insert(begin(collection), 27);
BOOST_CHECK_EQUAL(collection.getSize(), 4);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenPoppingFirst_ThenOperationThrows,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK_THROW(collection.popFirst(), std::logic_error);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenPoppingLast_ThenOperationThrows,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK_THROW(collection.popLast(), std::logic_error);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollectionWithSingleItem_WhenPoppingFirst_ThenCollectionIsEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection = { 420 };
collection.popFirst();
BOOST_CHECK(collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollectionWithSingleItem_WhenPoppingLast_ThenCollectionIsEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection = { 420 };
collection.popLast();
BOOST_CHECK(collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPoppingFirst_ThenCollectionSizeIsReduced,
T,
TestedTypes)
{
LinearCollection<T> collection = { 14, 10 };
collection.popFirst();
BOOST_CHECK_EQUAL(collection.getSize(), 1);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPoppingLast_ThenCollectionSizeIsReduced,
T,
TestedTypes)
{
LinearCollection<T> collection = { 14, 10 };
collection.popLast();
BOOST_CHECK_EQUAL(collection.getSize(), 1);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPoppingFirst_ThenItemIsRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 300, 8, 480 };
collection.popFirst();
thenCollectionContainsValues(collection, { 8, 480 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPoppingLast_ThenItemIsRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 300, 8, 480 };
collection.popLast();
thenCollectionContainsValues(collection, { 300, 8 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPoppingFirst_ThenItemsIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection = { 101, 202, 303 };
BOOST_CHECK_EQUAL(collection.popFirst(), 101);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPoppingLast_ThenItemsIsReturned,
T,
TestedTypes)
{
LinearCollection<T> collection = { 101, 202, 303 };
BOOST_CHECK_EQUAL(collection.popLast(), 303);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenEmptyCollection_WhenErasing_ThenOperationThrows,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK_THROW(collection.erase(collection.begin()), std::out_of_range);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingEnd_ThenOperationThrows,
T,
TestedTypes)
{
LinearCollection<T> collection = { 20, 16 };
BOOST_CHECK_THROW(collection.erase(end(collection)), std::out_of_range);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingBegin_ThenItemIsRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 22, 41, 31 };
collection.erase(begin(collection));
thenCollectionContainsValues(collection, { 41, 31 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingLastItem_ThemItemIsRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 22, 45, 33 };
collection.erase(--end(collection));
thenCollectionContainsValues(collection, { 22, 45 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingMiddleItem_ThenItemIsRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 22, 51, 48 };
collection.erase(++begin(collection));
thenCollectionContainsValues(collection, { 22, 48 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasing_ThenSizeIsReduced,
T,
TestedTypes)
{
LinearCollection<T> collection = { 1000, 500, 2, 900 };
collection.erase(begin(collection) + 2);
BOOST_CHECK_EQUAL(collection.getSize(), 3);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenCollectionWithSingleItem_WhenErasing_ThenCollectionIsEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection = { 1529 };
collection.erase(begin(collection));
BOOST_CHECK(collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingEmptyRange_ThenNothingHappens,
T,
TestedTypes)
{
LinearCollection<T> collection = { 19, 42, 11 };
collection.erase(begin(collection), begin(collection));
thenCollectionContainsValues(collection, { 19, 42, 11 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingRangeFromBegin_ThenItemsAreRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 19, 42, 11 };
collection.erase(begin(collection), begin(collection) + 2);
thenCollectionContainsValues(collection, { 11 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_whenErasingRangeToEnd_ThenItemsAreRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 20, 1, 45 };
collection.erase(begin(collection) + 1, end(collection));
thenCollectionContainsValues(collection, { 20 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingSingleItemRange_ThenItemIsRemoved,
T,
TestedTypes)
{
LinearCollection<T> collection = { 2001, 2010, 2051, 3001 };
collection.erase(begin(collection) + 1, begin(collection) + 2);
thenCollectionContainsValues(collection, { 2001, 2051, 3001 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingWholeRange_ThenCollectinIsEmpty,
T,
TestedTypes)
{
LinearCollection<T> collection = { 400, 403, 404 };
collection.erase(begin(collection), end(collection));
BOOST_CHECK(collection.isEmpty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingRange_ThenSizeIsUpdated,
T,
TestedTypes)
{
LinearCollection<T> collection = { 23, 10, 20, 16 };
collection.erase(begin(collection) + 1, end(collection) - 1);
BOOST_CHECK_EQUAL(collection.getSize(), 2);
}
//own tests
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenPrependingElement_ThenItIsBegin,
T,
TestedTypes)
{
LinearCollection<T> collection = { 18, 15, 9, 200 };
collection.prepend(1200);
BOOST_CHECK_EQUAL(*collection.begin(), 1200);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingManyElements_ThenItDeletsThem,
T,
TestedTypes)
{
LinearCollection<T> collection = { 20, 80, 100, 130, 2, 8, 0 };
collection.erase(collection.begin()+2, collection.begin()+5);
thenCollectionContainsValues(collection, { 20, 80, 8, 0 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenInsertingElement_ThenItContainsIt,
T,
TestedTypes)
{
LinearCollection<T> collection = { 20, 80, 100, 130, 2, 8, 0 };
collection.insert(collection.begin()+2, 44);
thenCollectionContainsValues(collection, { 20, 80, 44, 100, 130, 2, 8, 0 });
}
BOOST_AUTO_TEST_CASE_TEMPLATE(LGivenNonEmptyCollection_WhenErasingEnd_ThenItThrows,
T,
TestedTypes)
{
LinearCollection<T> collection;
BOOST_CHECK_THROW(collection.erase(collection.end()), std::out_of_range);
}
// ConstIterator is tested via Iterator methods.
// If Iterator methods are to be changed, then new ConstIterator tests are required.
BOOST_AUTO_TEST_SUITE_END()
| true |
75ee0ba9e6915aa38538bb14a3cd21c17fe8eb72 | C++ | JSzulwinski/GP3-Submission-2019 | /Scene.h | UTF-8 | 2,425 | 2.828125 | 3 | [] | no_license | #pragma once
#include <vector>
#include "Vector3f.h"
#include "Vector4f.h"
#include "Object.h"
#include "Light.h"
#include "Camera.h"
using namespace std;
class Scene
{
public:
Scene(const char* windowCaption, int windowPosX, int windowPosY, int windowWidth, int windowHeight);
~Scene();
void setFullScreen(bool fullScreen);
void setKeyboardFunction(void (*keyboardFunction)(Scene* scene, unsigned char key, int mouseX, int mouseY));
void setSpecialFunction(void (*specialFunction)(Scene* scene, int key, int mouseX, int mouseY));
void setMouseButtonFunction(void (*mouseButtonFunction)(Scene* scene, int button, int state, int mouseX, int mouseY));
void setMouseMoveActiveFunction(void (*mouseMoveActiveFunction)(Scene* scene, int mouseX, int mouseY));
void setMouseMovePassiveFunction(void (*mouseMovePassiveFunction)(Scene* scene, int mouseX, int mouseY));
void setFrameRate(int fps);
int getWidth();
int getHeight();
bool isFullScreen();
GLuint addTexture(char* fileName);
void addObject(Object* object);
void start();
bool fullScreen;
Camera camera;
Vector3f backgroundColor;
Vector4f lightAmbient;
Light light[8];
vector<Object*> objects;
vector<GLuint> textures;
GLUquadricObj* quadric; // Quadric variable (gluSphere itp)
GLint quadricParts;
private:
static Scene* instance;
int windowHandle;
int windowPosX, windowPosY;
int windowWidth, windowHeight;
int renderInterval;
void (*keyboardFunction)(Scene* scene, unsigned char key, int mouseX, int mouseY);
void (*specialFunction)(Scene* scene, int _cChar, int mouseX, int mouseY);
static void glutKeyboardFunction(unsigned char key, int mouseX, int mouseY);
static void glutSpecialFunction(int key, int mouseX, int mouseY);
void (*mouseButtonFunction)(Scene* scene, int button, int state, int mouseX, int mouseY);
void (*mouseMoveActiveFunction)(Scene* scene, int mouseX, int mouseY);
void (*mouseMovePassiveFunction)(Scene* scene, int mouseX, int mouseY);
static void glutMouseButtonFunction(int button, int state, int mouseX, int mouseY);
static void glutMouseMoveActiveFunction(int mouseX, int mouseY);
static void glutMouseMovePassiveFunction(int mouseX, int mouseY);
static void glutRenderFunction();
static void glutReshapeFunction(int width, int height);
static void glutTimerFunction(int sceneCallback);
void resize(int width, int height);
void render();
bool checkCollision(Object* a, Object* b);
};
| true |
1c2d963f95d4ee7dc723720d9bb7461aa90c7363 | C++ | LeLxkas/Marx | /Marx/src/Marx/Renderer/Camera.cpp | UTF-8 | 667 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include "mxpch.h"
#include "Camera.h"
namespace Marx
{
OrthographicCamera::OrthographicCamera(float left, float right, float bottom, float top)
: m_projectionMatrix(DX::XMMatrixOrthographicOffCenterLH(left, right, bottom, top, -1.0f, 1.0f))
{}
void OrthographicCamera::recalculateViewMatrix()
{
DX::XMMATRIX transform = DX::XMMatrixTranslation(m_position.x, m_position.y, m_position.z) *
DX::XMMatrixRotationZ(DX::XMConvertToRadians(m_rotation));
m_viewMatrix = DX::XMMatrixInverse(NULL, transform);
m_viewProjectionMatrix = m_viewMatrix * m_projectionMatrix;
m_viewProjectionMatrixTransposed = DX::XMMatrixTranspose(m_viewProjectionMatrix);
}
} | true |
fc4834d2d088924d6aa8814e191cf7add84e0efb | C++ | sundsx/RevBayes | /src/core/dag/DagNode.h | UTF-8 | 11,224 | 2.84375 | 3 | [] | no_license | /**
* @file
* This file contains the declaration of the DAG node class, which is our base class for all DAG node is in the model graph.
* It is merely used as a common base class to connect the entire graph.
*
* @brief Declaration of the base class DagNode.
*
* (c) Copyright 2009- under GPL version 3
* @date Last modified: $Date$
* @author The RevBayes Development Core Team
* @license GPL version 3
* @version 1.0
* @since 2012-06-17, version 1.0
* @interface DagNode
*
* $Id$
*/
#ifndef DagNode_H
#define DagNode_H
#include <map>
#include <set>
#include <string>
#include <vector>
namespace RevBayesCore {
class DagNode {
public:
enum DagNodeTypes { CONSTANT, DETERMINISTIC, STOCHASTIC };
virtual ~DagNode(void); //!< Virtual destructor
// pure virtual methods
virtual DagNode* clone(void) const = 0;
virtual DagNode* cloneDAG(std::map<const DagNode*, DagNode*> &nodesMap) const = 0; //!< Clone the entire DAG which is connected to this node
virtual double getLnProbability(void) = 0;
virtual double getLnProbabilityRatio(void) = 0;
virtual void printName(std::ostream &o, const std::string &sep) const = 0; //!< Monitor/Print this variable
virtual void printStructureInfo(std::ostream &o) const = 0; //!< Print the structural information (e.g. name, value-type, distribution/function, children, parents, etc.)
virtual void printValue(std::ostream &o, const std::string &sep) const = 0; //!< Monitor/Print this variable
virtual void printValue(std::ostream &o,size_t i) const = 0; //!< Monitor/Print the i-th element of this variable
virtual void redraw(void) = 0; //!< Redraw the current value of the node (applies only to stochastic nodes)
// public member functions
void addChild(DagNode *child) const; //!< Add a new child node
void addTouchedElementIndex(size_t i); //!< Add the index of an element that has been touch (usually for vector-like values)
void clearTouchedElementIndices(void);
DagNode* cloneDownstreamDag(std::map<const DagNode*, DagNode*> &nodesMap) const; //!< Clone the DAG which is downstream to this node (all children)
void collectDownstreamGraph(std::set<DagNode*> &nodes); //!< Collect all nodes downstream from this node (incl the node)
size_t decrementReferenceCount(void) const; //!< Decrement the reference count for reference counting in smart pointers
void getAffectedNodes(std::set<DagNode *>& affected); //!< get affected nodes
// DagNode* getChild(size_t index); //!< Get the child at the index
const std::set<DagNode*>& getChildren(void) const; //!< Get the set of parents
std::string getDagNodeType(void) const;
DagNode* getFirstChild(void) const; //!< Get the first child from a our set
const std::string& getName(void) const; //!< Get the of the node
size_t getNumberOfChildren(void) const; //!< Get the number of children for this node
size_t getReferenceCount(void) const; //!< Get the reference count for reference counting in smart pointers
const std::set<size_t>& getTouchedElementIndices(void) const; //!< Get the indices of the touches elements. If the set is empty, then all elements might have changed.
void incrementReferenceCount(void) const; //!< Increment the reference count for reference counting in smart pointers
virtual bool isClamped(void) const; //!< Is this node clamped? Only stochastic nodes might be clamped.
virtual bool isConstant(void) const; //!< Is this DAG node constant?
virtual bool isSimpleNumeric(void) const; //!< Is this variable a simple numeric variable? Currently only integer and real number are.
virtual bool isStochastic(void) const; //!< Is this DAG node stochastic?
void keep(void);
virtual void keepAffected(void); //!< Keep value of affected nodes
virtual void reInitialized(void); //!< The DAG was re-initialized so maybe you want to reset some stuff
virtual void reInitializeAffected(void); //!< The DAG was re-initialized so maybe you want to reset some stuff
virtual void reInitializeMe(void); //!< The DAG was re-initialized so maybe you want to reset some stuff
void removeChild(DagNode *child) const;
void replace(DagNode *n); //!< Replace this node with node p.
void restore(void);
virtual void restoreAffected(void); //!< Restore value of affected nodes recursively
virtual void setName(const std::string &n); //!< Set the name of this variable for identification purposes.
void touch(void);
virtual void touchAffected(void); //!< Touch affected nodes (flag for recalculation)
// Parent management functions that nodes with parents need to override. Here we just return an empty set or throw an error.
virtual std::set<const DagNode*> getParents(void) const; //!< Get the set of parents (empty set here)
virtual void swapParent(const DagNode *oldP, const DagNode *newP); //!< Exchange the parent node which includes setting myself as a child of the new parent and removing myself from my old parents children list
protected:
DagNode(const std::string &n); //!< Constructor
DagNode(const DagNode &n); //!< Constructor
DagNode& operator=(const DagNode &d); //!< Overloaded assignment operator
virtual void getAffected(std::set<DagNode *>& affected, DagNode* affecter) = 0; //!< get affected nodes
virtual void keepMe(DagNode* affecter) = 0; //!< Keep value of myself
virtual void restoreMe(DagNode *restorer) = 0; //!< Restore value of this nodes
virtual void touchMe(DagNode *toucher) = 0; //!< Touch myself (flag for recalculation)
// helper functions
void printChildren(std::ostream& o, size_t indent, size_t lineLen) const; //!< Print children DAG nodes
void printParents(std::ostream& o, size_t indent, size_t lineLen) const; //!< Print children DAG nodes
// members
mutable std::set<DagNode*> children; //!< The children in the model graph of this node
std::string name;
std::set<size_t> touchedElements;
DagNodeTypes type;
private:
mutable size_t refCount;
};
}
#endif
| true |
c8ce2520bed778166313e250e5d5010f9437fb07 | C++ | hgs3896/ITE1015_Creative_Programming | /HW3/binary_search/binary_search.cc | UTF-8 | 725 | 3.21875 | 3 | [] | no_license | #include "binary_search.h"
#include <algorithm>
using namespace std;
inline void BinarySearch::sortArray() {
sort(mArray, mArray+mArrayCount);
}
BinarySearch::BinarySearch(): mArray(NULL), mArrayCount(0){}
BinarySearch::BinarySearch(int *_array, int _arrayCount) : mArrayCount(_arrayCount){
if (mArrayCount <= 0) return;
mArray = new int[mArrayCount];
for (int i = 0; i < mArrayCount; ++i)
mArray[i] = _array[i];
sortArray();
}
BinarySearch::~BinarySearch() {
delete[] mArray;
}
int BinarySearch::getIndex(int _element) {
int m, l = 0, r = mArrayCount - 1;
while (l <= r) {
m = (l + r) / 2;
if (mArray[m] == _element)
return m;
else if (mArray[m] < _element)
l = m+1;
else
r = m-1;
}
return -1;
} | true |
671b9f1f81863223eb3e05043ac05ca1c32d946e | C++ | LambdaRan/book | /EfficientC++/ch06/MemoryChunk.h | UTF-8 | 1,518 | 3.390625 | 3 | [] | no_license |
// 把不同大小的内存块连接起来形成块序列
#ifndef MEMORYCHUNK_H
#define MEMORYCHUNK_H
class MemoryChunk
{
public:
MemoryChunk(MemoryChunk *nextChunk, size_t chunkSize);
~MemoryChunk();
inline void *alloc(size_t size);
inline void free(void *doomed);
// 指向列表下一内存块的指针
MemoryChunk *nextMemChunk()
{
return next;
}
// 当前内存块剩余空间大小
size_t spaceAvailable()
{
return chunkSize - bytesAlreadAllocated;
}
// 这是一个内存块的默认大小
enum { DEFAULT_CHUNK_SIZE = 4096 };
//const size_t DEFAULT_CHUNK_SIZE = 4096;
private:
MemoryChunk *next;
void *mem;
// 一个内存块的默认大小
size_t chunkSize;
// 当前内存块中已分配的字节数
size_t bytesAlreadAllocated;
};
MemoryChunk::MemoryChunk(MemoryChunk *nextChunk, size_t reqSize)
{
chunkSize = (reqSize > DEFAULT_CHUNK_SIZE) ? reqSize : DEFAULT_CHUNK_SIZE;
next = nextChunk;
bytesAlreadAllocated = 0;
mem = new char[chunkSize];
}
MemoryChunk::~MemoryChunk()
{
delete mem;
}
void *MemoryChunk::alloc(size_t requestSize)
{
void *addr = reinterpret_cast<void *>(reinterpret_cast<size_t>(mem) + bytesAlreadAllocated);
bytesAlreadAllocated += requestSize;
return addr;
}
inline
void MemoryChunk::free(void *doomed)
{
(void)doomed;
// 无操作
}
#endif // !MEMORYCHUNK_H
| true |
3895795c6e75cc65f808fe5b0c836156d0294e91 | C++ | peaceless/SimpleSortAlgorithm | /InsertSort.cpp | UTF-8 | 1,292 | 3.984375 | 4 | [] | no_license | /*
* 插入排序认为已存在一个已经排序好的序列,将一系列元素插入到这个已排序序列中去
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
typedef int ElemType;
void InsertSort(ElemType A[], int n) {
int i,j = 1;
int temp;
for(i = 2; i < n; i++) { //依次将A【2】~A【n】插入到前面已排序序列
if(A[i] < A[i-1]) { //若A【i】的关键码小于其前驱,需将A【i】插入有序表
temp = A[i] ; //复制为哨兵,A【0】不存放元素
for(j = i-1; temp < A[j]; --j) //从后往前查找带插入位置
A[j+1] = A[j]; //向后挪位置
}
A[j+1] = temp; //复制到插入位置
}
}
int main()
{
srand(static_cast<unsigned>(time(0)));
int test[10];
std::cout << "get a queue:\n";
for (int i = 0; i < 10; ++i)
{
test[i] = rand()%10;
std::cout << test[i] << " ";
}
std::cout << "\nafter sort\n";
InsertSort(test,10);
for (int i = 0; i < 10; ++i)
{
std::cout << test[i] << " ";
}
return 0;
}
/*
空间效率:使用常数单元,空间复杂度为O(1)
时间效率:最好情况下,即表中元素已有序,时间复杂度为O(n)
最坏情况下,即表中元素逆序,总的移动次数为Σ(i = 2~n)(i+1)
平均比较次数和总的移动次数为n²/4
*/ | true |
2afe7b79532e4588785b632c5a713d1cebb84b4b | C++ | ultram4rine/ssu | /numerical/optimization/regular_simplex.cpp | UTF-8 | 2,401 | 3.21875 | 3 | [] | no_license | #define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <array>
#include <utility>
#include "regular_simplex.hpp"
// Build regular simplex;
array<array<double, 2>, 3> build_simplex(array<double, 2> x_0, double l)
{
int n = x_0.size();
array<array<double, 2>, 3> nodes;
nodes[0] = x_0;
for (auto i = 1; i < n + 1; i++)
{
for (auto j = 0; j < n; j++)
{
nodes[i][j] = i == j + 1 ? nodes[0][j] + ((sqrt(n + 1) - 1) / (n * sqrt(2))) * l : nodes[0][j] + ((sqrt(n + 1) + n - 1) / (n * sqrt(2))) * l;
}
}
return nodes;
}
// Reflect given node relatively to canter of mass.
array<double, 2> reflect_node(array<double, 2> x, array<array<double, 2>, 3> nodes)
{
int n = x.size();
array<double, 2> sum = {0, 0};
for (auto i = 0; i < n; i++)
{
sum[0] += nodes[i][0];
sum[1] += nodes[i][1];
}
sum[0] = sum[0] * 2 / n;
sum[1] = sum[1] * 2 / n;
sum[0] -= x[0];
sum[1] -= x[1];
return {sum[0], sum[1]};
}
// Regular simplex method.
array<double, 2> regular_simplex(array<double, 2> x_0, double eps, twoDFunc f)
{
// step counter;
int k = 0;
// node counter;
int d = 0;
int n = x_0.size();
// length of simplex edge.
double l = 0.5;
array<double, 2> x_1 = x_0;
double f_2 = f(x_1);
// build simplex.
array<array<double, 2>, x_0.size() + 1> nodes = build_simplex(x_1, l);
do
{
// sort.
for (auto i = 0; i < n; i++)
{
int smallestIndex = i;
for (int j = i + 1; j < n + 1; j++)
{
if (f(nodes[j]) < f(nodes[i]))
smallestIndex = j;
}
swap(nodes[i], nodes[smallestIndex]);
}
array<double, 2> x_2 = reflect_node(nodes[n], nodes);
f_2 = f(x_2);
if (f_2 < f(nodes[n]))
{
nodes[n] = x_2;
d = 0;
}
else
{
if (1 + d > n)
{
break;
}
x_1 = nodes[n - (1 + d)];
d++;
}
k++;
} while (k < 1000);
double sum_x1 = 0, sum_x2 = 0;
for (auto i = 0; i < n + 1; i++)
{
sum_x1 += nodes[i][0];
sum_x2 += nodes[i][1];
}
array<double, 2> center = {sum_x1 / 3, sum_x2 / 3};
return center;
}
| true |
a71ff3ad3b3551717a292b025df3576b82ea4f12 | C++ | Qzhenlong/LeetCode | /LongestPalindromicSubstring.cpp | GB18030 | 1,128 | 3.4375 | 3 | [] | no_license | #include<iostream>
#include<map>
using namespace std;
/*
أظӴ
˼·
̬滮
һT¼i-j֮DzǻĴT[i][j] = true;
i~jǻĴôi+1~j-1ȻǻĴT[i][j] = (T[i+1][j-1] s[i] == s[j])
1T[i][j] = true; i = j;
2) T[i][j] = s[i]== s[j]; j = i+1;
2) T[i][j] = (s[i] == s[j]) && T[i+1][j-1];
㷨O(n) KMP㷨ı
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
*/
class Solution {
public:
string longestPalindrome(string s)
{
int n = s.size(), maxlen = 1, max_index = 0;
bool T[n][n];
if(s.size() == 0) return s;
for(int j = 0; j < n; j++)
{
T[j][j] = true;
for(int i = 0; i < j; i++)
{
if(s[i] == s[j])
{
T[i][j] = (j-i<2) || T[i+1][j-1];
if(maxlen < j-i+1 && T[i][j])
{
maxlen = j-i+1;
max_index = i;
}
}
else
T[i][j] = false;
}
}
return s.substr(max_index, maxlen);
}
};
int main()
{
Solution c;
string s = "a";
cout << c.longestPalindrome(s) << endl;
while(1);
return 0;
}
| true |
680b908f573b5a8e055dcd2816cb8daf9d7f57c2 | C++ | semi10/AClock | /RTClib.h | UTF-8 | 1,520 | 2.6875 | 3 | [] | no_license | /* RTClib.h
* defintions for DS1307 RTC
*/
#ifndef RTClib_h
#define RTClib_h
#include <avr/pgmspace.h>
#include <Arduino.h>
#define DS1307_ADDRESS 0x68
#define SECONDS_PER_DAY 86400
#define SECONDS_FROM_1970_TO_2000 946684800
static const uint8_t daysInMonth [] PROGMEM = {31,28,31,30,31,30,31,31,30,31,30,31};
class RTClib{
public:
RTClib();
void setTime(String _serIn);
String getDate();
String getTime();
void getTime(String &hour, String &minute);
uint8_t getSec() {return ss;}
uint8_t getMinute() {return mm;}
uint8_t getHour() {return hh;}
uint8_t getDay() {return d;}
uint8_t getMonth() {return m;}
uint8_t getYear() {return y;}
boolean timeChanged(); //True if pmm != mm
int date2days(uint8_t d, uint8_t m, uint8_t y);
uint16_t dateDiff(uint8_t day, uint8_t month, uint8_t year);
uint16_t timeDiff(uint8_t minutes, uint8_t hours);
private:
String serIn; //Serial data input
String tempStr; //temp string from serIn
char cArray[5]; //char Array for string to integer convertion
byte lastData; //to keep track of my current position in serIn String.
uint8_t y;
uint8_t m, d, hh, mm, ss;
uint8_t pmm; //pmm = prevous minute
uint8_t bcd2dec(uint8_t val);
uint8_t dec2bcd(uint8_t val);
String formatNumber(uint8_t number);
void now();
void writeTime(uint16_t y, uint8_t m, uint8_t d, uint8_t hh, uint8_t mm, uint8_t ss); //write time to RTC chip
};
#endif
| true |
9247dbbd12401c484d409597086fa13b24519dfb | C++ | YaYanush/software-engineering | /wstep-do-programowania/zajecia-4/GCD.cpp | UTF-8 | 505 | 3.734375 | 4 | [
"MIT"
] | permissive | #include <iostream>
int main() {
// input
std::cout << "Please provide two integers.\n";
int a1, b1;
int previous;
std::cin >> a1 >> b1;
std::cout << "GCD of " << a1 << " and " << b1 << " is: ";
int a, b;
if (a1 > b1) {
a = a1;
b = b1;
} else {
a = b1;
b = a1;
}
// calculations
while (b != 0) {
previous = a;
a = b;
b = previous % b;
}
// output
std::cout << a;
return 0;
} | true |
f632c5ee55faf691be7f47623c0cdb1dd76c6b58 | C++ | amirhadi3/modern-cpp | /15.189/constexpr lambda/constexpr lambda/Source.cpp | UTF-8 | 1,414 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
template<typename T, int size, typename callback>
void forEach(T(&arr)[size], callback operation) {
for (int i = 0; i < size - 1; ++i) {
operation(arr[i]);
}
}
class product {
std::string name;
float price;
public:
product(const std::string& n, float p) : name(n), price(p) {
}
void assignFinalPrice() {
float taxes[]{ 12,5,5 };
float basePrice{ price };
forEach(taxes, [basePrice, this](float tax) {
price += basePrice * tax / 100;
});
}
float getPrice() const {
return price;
}
auto getDescription() {
// in c++17 pass by value of the object parameters is an option
// it creates a copy and prevents the risk of dangling pointers
return [*this](const std::string& header) {
std::ostringstream ost;
ost << header << std::endl;
ost << "name: " << name << std::endl; //no need to use this->name
ost << "price: " << price << std::endl; // no need to use this->price
return ost.str();
};
}
};
int main() {
product *p = new product{ "watch",500 };
p->assignFinalPrice();
auto desc = p->getDescription();
delete p;
std::cout << desc("The header");
auto f = [](int x, int y) {
return x + y;
}; // without using the constexpr on the function definition, it is considered as a constexpr
// so it can be used in a constexp itself.
constexpr auto sum = f(3, 4);
std::cout << sum << std::endl;
} | true |
b40080bb218f13edad4abefec2a044becb071e81 | C++ | larrystd/simple_epoll_server | /webserver/HttpServer.cpp | UTF-8 | 3,233 | 2.90625 | 3 | [] | no_license | /*
* @Author: your name
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /epoll_server-master/webserver/HttpServer.cpp
*/
#include "HttpServer.h"
void HttpServer::start(int port) {
if((listen_fd=socket(AF_INET, SOCK_STREAM, 0)) < 0) // return fd of socket
{
cout << "socket error\n" << endl;
exit(-1);
}
bzero(&serverSocketaddr, sizeof(struct sockaddr_in));
serverSocketaddr.sin_family = AF_INET;
serverSocketaddr.sin_port = htons(port);
serverSocketaddr.sin_addr.s_addr = htonl(0);
if (::bind(listen_fd, (sockaddr*)&serverSocketaddr, sizeof(serverSocketaddr)) != 0)
{
cerr << "Error: failed to bind port (" << port << ")!" << endl;
exit(-1);
}
if (listen(listen_fd, 5) < 0)
{
cerr << "Error: failed to listen!!!" << endl;
exit(-1);
}
epoll_fd = epoll_create(MAXEVENT); // create epoll
struct epoll_event event;
event.events = EPOLLIN|EPOLLET;
event.data.fd = listen_fd;
if(epoll_ctl(epoll_fd,EPOLL_CTL_ADD,listen_fd,&event)<0) // 注册listen_fd
{
printf("epoll 加入失败 fd:%d\n",listen_fd);
exit(-1);
}
//ret会返回在规定的时间内获取到IO数据的个数,并把获取到的event保存在eventList中,注意在每次执行该函数时eventList都会清空,由epoll_wait函数填写。
for (;;) {
ret = epoll_wait(epoll_fd, eventList, MAXEVENT, -1); // Returns the number of triggered events returned in "events" buffer
for (int n = 0; n < ret; ++n) { //
if (eventList[n].data.fd == listen_fd) { // 如果文件描述符是socket对应的,需要处理socket
bzero(&clientSocketaddr, sizeof(struct sockaddr_in)); // 置零
socklen_t len = sizeof(clientSocketaddr);
int connd = accept(listen_fd,(struct sockaddr *) &clientSocketaddr, &len); //接受连接
if (connd== -1) {
perror("accept");
exit(-1);
}
if ((fcntl(connd, F_SETFL, fcntl(connd, F_GETFD, 0) | O_NONBLOCK))>0) // 给文件设置标志,不阻塞,也就是没可读数据返回-1
{
perror("set blocking fail");
exit(-1);
}
event.events = EPOLLIN | EPOLLET;
event.data.fd = connd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, connd,&event) == -1) { // 注册connd到epoll_ctl
perror("epoll_ctl: conn_sock");
exit(EXIT_FAILURE);
}
} else {
handle(eventList[n].data.fd); // 处理读写文件fd,也就是connd
}
}
}
}
void HttpServer::handle(int clientfd)
{
int recvLen=0;
char recvBuf[MAX_DATA_SIZE];
memset(recvBuf,0,sizeof(recvBuf));
recvLen=recv(clientfd,(char *)recvBuf,MAX_DATA_SIZE,0); // 向connd内写消息
if(recvLen==0)
return;
else if(recvLen<0)
{
perror("recv Error");
exit(-1);
}
//各种处理
printf("接收到的数据:%s \n",recvBuf);
return;
} | true |
7746dee1cf2269f83ada0a3cf50a594820a91644 | C++ | doum1004/code_assessment | /leetcode/leetcode_cpp/longest-substring-with-at-most-two-distinct-characters.cpp | UTF-8 | 1,849 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <cassert>
#include <vector>
#include <unordered_map>
using namespace std;
/**
https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
- solution1. slinding window (l,r)
- time: o(n) 2n
- space: o(n)
1. iterate by r to count on map
2. if it hits more than target, iterate by l to decrease count on map till erase
3. otherwise save res
- solution2. move
- time: o(n)
- space: o(1)
*/
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct_slindingwindow(string& s) {
int n = s.size();
int l = 0, r = 0, res = 0, d = 2;
unordered_map<char, int> h;
while (r<n) {
h[s[r]]++;
if (h.size() > d) {
while (h.size() > d) {
h[s[l]]--;
if (h[s[l]] == 0) h.erase(s[l]);
l++;
}
}
else {
res = max(res, r-l+1);
}
r++;
}
return res == 0 ? n : res;
}
/**
abbbbaddddddddd
l
r
c
*/
int lengthOfLongestSubstringTwoDistinct_nospace(string& s) {
int l=0,c=0,res=0;
for (auto r=0; r<s.size(); ++r) {
if (s[r] != s[c]) {
if (c != 0 && s[r] != s[c-1]) l = c;
c = r;
}
res = max(res, r-l+1);
}
return res;
}
int lengthOfLongestSubstringTwoDistinct(string s) {
//return lengthOfLongestSubstringTwoDistinct_slindingwindow(s);
return lengthOfLongestSubstringTwoDistinct_nospace(s);
}
};
int main()
{
assert(Solution().lengthOfLongestSubstringTwoDistinct("eceba") == (3));
assert(Solution().lengthOfLongestSubstringTwoDistinct("ccaabbb") == (5));
return 0;
} | true |
04e4fff75005e426562df22714565a061795f991 | C++ | dimitrijejankov/simsql-old | /src/main/java/simsql/functions/vg/WeightedInputChunk.vg.cc | UTF-8 | 4,818 | 2.75 | 3 | [] | no_license | /*****************************************************************************
* *
* Copyright 2014 Rice University *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this of 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. *
* *
*****************************************************************************/
#include <stdio.h>
#include "VGFunction.h"
struct RecordIn {
Vector *x;
long *row_id;
Matrix *w;
long *data_id;
};
struct RecordOut {
Vector *chunk;
long *data_id;
long *column_id;
};
/** VG Function class */
class WeightedInputChunk : public VGFunction {
public:
/** Constructor. Use this to declare your RNG and other
* important structures .
*/
WeightedInputChunk() {}
/** Destructor. Deallocate everything from the constructor. */
~WeightedInputChunk() {}
/** Initializes the RNG seed for a given call. */
void initializeSeed(long seedValue) {}
/**
* Clears the set of parameters for the first call to takeParams.
* If possible, uses the default parameter set.
*/
void clearParams() {
printf("---DATA START---\n");
fflush(stdout);
}
/** Finalizes the current trial and prepares the structures for
* another fresh call to outputVals(). */
void finalizeTrial() {
printf("---DATA END---\n");
fflush(stdout);
}
void printVector(Vector* v){
if(v->value == NULL)
return;
printf("[");
for(int i = 0; i < (size_t)v->length; i++){
if (i != ((size_t)v->length) - 1) {
printf("%lf ", v->value[i]);
}
else {
printf("%lf", v->value[i]);
}
}
printf("] ");
}
void printMatrix(Matrix* m){
if(m->value == NULL)
return;
printf("[");
for(int i = 0; i < (size_t)m->numRow; i++){
printf("[");
for(int j = 0; j < (size_t)m->numCol; j++) {
if (j != ((size_t)m->numCol) - 1) {
printf("%lf ", m->value[i * (size_t)m->numCol + j]);
}
else {
printf("%lf", m->value[i * (size_t)m->numCol + j]);
}
}
printf("]");
}
printf("] ");
}
/**
* Passes the parameter values. Might be called several times
* for each group.
*/
void takeParams(RecordIn &input) {
if (input.x != NULL) {
printVector(input.x);
}
else {
printf("null ");
}
if (input.row_id != NULL) {
printf("%ld ", *input.row_id);
}
else
printf("null ");
if (input.w != NULL) {
printMatrix(input.w);
}
else
printf("null ");
if (input.data_id != NULL) {
printf("%ld ", *input.data_id);
}
else
printf("null ");
printf("\n");
}
/**
* Produces the sample values. Returns 1 if there are more
* records to be produced for the current sample, 0 otherwise.
*/
int outputVals(RecordOut &output) {
return 0;
}
/** Schema information methods -- DO NOT MODIFY */
VGSchema inputSchema() {
return (VGSchema){4, {"vector[a]", "integer", "matrix[a][a]", "integer"}, {"x", "row_id", "w", "data_id"}};
}
VGSchema outputSchema() {
return (VGSchema){3, {"vector[a]", "integer", "integer"}, {"chunk", "data_id", "column_id"}};
}
const char *getName() {
return "WeightedInputChunk";
}
};
/** External creation/destruction methods -- DO NOT MODIFY */
VGFunction *create() {
return(new WeightedInputChunk());
}
void destroy(VGFunction *vgFunction) {
delete (WeightedInputChunk *)vgFunction;
} | true |
8c6ed45ef730dc922cc5222b8dd29eda5f977fbb | C++ | VoidReck/Halo-Generic-Multiclient | /src/HaloMultiClient/Common.cpp | UTF-8 | 2,527 | 2.65625 | 3 | [] | no_license | #include "Common.h"
// Gets the directory of the process
std::string GetWorkingDirectory()
{
char szOutput[1024] = {0};
std::string path = "";
// Get the plugins directory (GetCurrentDirectory() won't always give what we want)
GetModuleFileName(GetModuleHandle(0), szOutput, sizeof(szOutput)-1);
char* szExeDelim = strrchr(szOutput, '\\');
if (szExeDelim)
{
szExeDelim[0] = '\0';
path = szOutput;
}
return path;
}
BOOL WriteBytes(HANDLE hProcess, DWORD destAddress, LPVOID patch, DWORD numBytes)
{
DWORD oldProtect = 0, dwWritten = 0;
LPVOID srcAddress = (LPVOID)PtrToUlong(destAddress);
BOOL result = TRUE;
result = result && VirtualProtectEx(hProcess, srcAddress, numBytes, PAGE_EXECUTE_READWRITE, &oldProtect);
result = result && WriteProcessMemory(hProcess, srcAddress, patch, numBytes, &dwWritten);
result = result && numBytes == dwWritten;
result = result && VirtualProtectEx(hProcess, srcAddress, numBytes, oldProtect, &oldProtect);
result = result && FlushInstructionCache(hProcess, srcAddress, numBytes);
return result;
}
// Reads bytes in the current process (Made by Drew_Benton).
BOOL ReadBytes(HANDLE hProcess, DWORD sourceAddress, LPVOID buffer, DWORD numBytes)
{
DWORD oldProtect = 0, dwRead = 0;
LPVOID srcAddress = (LPVOID)PtrToUlong(sourceAddress);
BOOL result = TRUE;
result = result && VirtualProtectEx(hProcess, srcAddress, numBytes, PAGE_EXECUTE_READWRITE, &oldProtect);
result = result && ReadProcessMemory(hProcess, srcAddress, buffer, numBytes, &dwRead);
result = result && numBytes == dwRead;
result = result && VirtualProtectEx(hProcess, srcAddress, numBytes, oldProtect, &oldProtect);
result = result && FlushInstructionCache(hProcess, srcAddress, numBytes);
return result;
}
std::vector<DWORD> FindSignature(LPBYTE sigBuffer, LPBYTE sigWildCard, DWORD sigSize, LPBYTE pBuffer, DWORD size)
{
std::vector<DWORD> results;
for(DWORD index = 0; index < size; ++index)
{
bool found = true;
for(DWORD sindex = 0; sindex < sigSize; ++sindex)
{
// Make sure we don't overrun the buffer!
if(sindex + index >= size)
{
found = false;
break;
}
if(sigWildCard != 0)
{
if(pBuffer[index + sindex] != sigBuffer[sindex] && sigWildCard[sindex] == 0)
{
found = false;
break;
}
}
else
{
if(pBuffer[index + sindex] != sigBuffer[sindex])
{
found = false;
break;
}
}
}
if(found)
{
results.push_back(index);
}
}
return results;
} | true |
5abc8d19f74b2a8ea857dd48c6c74827cbefefe4 | C++ | tylerwolverton/SD2-MP2Notes | /sd2/c29/assignments/a04_perspective/clientToWorld.cpp | UTF-8 | 2,291 | 2.765625 | 3 | [] | no_license | //------------------------------------------------------------------------
vec3 Camera::ClientToWorld( vec2 client, float ndcZ = 0 )
{
// map client to ndc
vec3 ndc = RangeMap( Vec3(client, ndcZ),
Vec3(0,0,0), Vec3(1,1,1),
Vec3(-1,-1,0), Vec3(1,1,1) );
// get this to world
// view : world -> camera
// projection : camera -> clip (homogeneous ndc)
// clip -> world
Mat44 proj = GetProjectionMatrix();
Mat44 worldToClip = proj;
worldToClip.PushMatrix( GetViewMatrix() );
Mat44 clipToWorld = Invert( worldToClip );
Vec4 worldHomogeneous = clipToWorld.Transform( Vec4( ndc, 1 ) );
Vec3 worldPos = worldHomogenous.XYZ() / worldHomogeneous.w;
reutrn worldPos;
}
//------------------------------------------------------------------------
vec2 Camera::GetOrthoMin()
{
return ClientToWorld( Vec2(0,0), 0).XY();
}
//------------------------------------------------------------------------
vec2 Camera::GetOrthoMax()
{
return ClientToWorld( Vec2(1,1), 0).XY();
}
//------------------------------------------------------------------------
// Inferring Aspect to Set Projections
//------------------------------------------------------------------------
//------------------------------------------------------------------------
vec2 Camera::SetOrthographicProjection( float height, float nz, float fz )
{
float aspect = GetOutputSize(); // my colorTarget size
Vec2 extents = Vec2( aspect * height * 0.5f, height * 0.5f );
m_projection = MakeOrthographicProjection( -extents, extents, nz, fz );
}
//------------------------------------------------------------------------
vec2 Camera::SetPerspectiveProjection( float fov, float nz, float fz )
{
float aspect = GetColorTargetSize();
m_projection = MakeProjectionMatrix( fov, aspect, nz, fz );
}
//------------------------------------------------------------------------
float Camera::GetOutputAspectRatio()
{
return GetColorTargetSize().GetRatio();
}
//------------------------------------------------------------------------
Vec2 Camera::GetColorTargetSize() const // is needed for depth buffers
{
if (m_colorTarget != nullptr) {
return m_colorTarget.GetSize();
} else {
m_renderContext->GetBackbuffer().GetSize();
}
}
| true |
76b895f617b9e755e342a682a74a9c29d887cb1b | C++ | Ceruninco/TPcpp | /MenuCatalogue.cpp | UTF-8 | 3,129 | 3.109375 | 3 | [] | no_license |
//coucou mec
#include <iostream>
#include <cstring>
#include "TrajetComp.h"
#include "TrajetSimple.h"
#include "Catalogue.h"
using namespace std;
Catalogue monCatalogue;
int main(void)
{
int requete;
int sousrequete;
do
{
cout<<"1 pour ajouter un trajet simple"<<endl;
cout<<"2 pour ajouter un trajet composé"<<endl;
cout<<"3 pour afficher les trajets"<<endl;
cout<<"4 pour rechercher un trajet"<<endl;
cout<<"5 pour faire une recherche avancée d'un trajet"<<endl;
cout<<"6 pour sauvegarder"<<endl;
cout<<"7 pour load la DB"<<endl;
cout<<"0 pour quitter"<<endl;
scanf("%d", &requete);
switch(requete)
{
case 1:
monCatalogue.insertionSimple();
break;
case 2 :
monCatalogue.insertionCompose();
break;
case 3 :
monCatalogue.afficherTrajets();
break;
case 4 :
{
char* buffer=new char[1000];
char* villeD;
char* villeA;
cout<<"ville de départ ?"<<endl;
cin >> buffer;
villeD=new char[strlen(buffer)+1];
strcpy(villeD,buffer);
cout<<"ville d'arrivée ?"<<endl;
cin >> buffer;
villeA=new char[strlen(buffer)+1];
strcpy(villeA,buffer);
delete [] buffer;
monCatalogue.rechercherTrajet(villeD, villeA);
delete [] villeD;
delete [] villeA;
}
break;
case 5 :
{
char* buffer=new char[1000];
char* villeD;
char* villeA;
cout<<"ville de départ ?"<<endl;
cin >> buffer;
villeD=new char[strlen(buffer)+1];
strcpy(villeD,buffer);
cout<<"ville d'arrivée ?"<<endl;
cin >> buffer;
villeA=new char[strlen(buffer)+1];
strcpy(villeA,buffer);
delete [] buffer;
monCatalogue.Dijsktra(villeD,villeA);
delete [] villeD;
delete [] villeA;
}
break;
case 6 :
{
monCatalogue.enregistrer();
}
break;
case 7 :
{
cout<<" 1 pour charger tout"<<endl;
cout<<" 2 pour charger uniquement les trajet simples"<<endl;
cout<<" 3 pour charger uniquement les trajet composés"<<endl;
cout<<" 4 pour charger les trajets en fonction de villes particulières"<<endl;
cout<<" 5 pour charger un intervalle de trajets "<<endl;
scanf("%d", &sousrequete);
switch(sousrequete)
{
case 1:
{
monCatalogue.load_savedAll();
}
break;
case 2:
{
monCatalogue.load_savedSimple();
}
break;
case 3:
{
monCatalogue.load_savedComp();
}
break;
case 4:
{
monCatalogue.load_savedDepArr();
}
break;
case 5:
{
monCatalogue.load_savedSelec();
}
break;
}
}
break;
}
}while(requete!=0);
return 0;
}
| true |
b9a5c666e1fb21989ddfb4fad57ea74b999c414f | C++ | AugustRush/2017demo | /ARPhysics-master/Engine/World.h | UTF-8 | 10,532 | 2.640625 | 3 | [
"MIT"
] | permissive | //
// World.h
//
// Created by Adrian Russell on 10/9/13.
// Copyright (c) 2014 Adrian Russell. All rights reserved.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software. Permission is granted to anyone to
// use this software for any purpose, including commercial applications, and to
// alter it and redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source
// distribution.
//
#ifndef __ARPhysics__World_H__
#define __ARPhysics__World_H__
#include "types.h"
#include "Body.h"
#include "Array.h"
#include "Constraint.h"
#include "SpatialIndexing.h"
#include "ForceGenerator.h"
#include <unordered_map>
/*!
The World class is the base class representing an area where simulation can take place.
*/
class World : public Object {
public:
/*!
Constructor for World object.
@param width
The width of the world.
@param height
The height of the world.
@param indexing
The spatial indexing system to use for the world.
@param numberOfIterations
The number of times to solve the collisions and constraints each step.
The larger this number the more accurate the simulation will be but the slower it will run.
The default is 5.
@discussion Note that bodies can go beyond the bounds of the world making the world size arbitrary.
*/
World(float width, float height, SpatialIndexing *indexing, unsigned int numberOfIterations = 5);
/*! World destructor. */
~World();
/*! Advances the physics simulation by a specified time.
@param dt (Delta Time) The time to advance the simulation by in seconds. I.e. if 0.0166 is specfied then all bodies and forces will be advanced in their states by 0.0166 seconds.
*/
virtual void step(float dt);
/*!
Returns the width of the world.
@return The width of the world.
*/
float getWidth() { return _width; };
/*!
Returns the height of the world.
@return The height of the world.
*/
float getHeight() { return _height; };
//---------------------------------------------------------------------------------------//
#pragma mark Indexing
/*!
Returns the spatial indexing system used by the world.
@return The spatial indexing system used by the world.
*/
SpatialIndexing *indexing() { return this->_indexing; };
//---------------------------------------------------------------------------------------//
#pragma mark Bodies
/*!
Adds a body to the world that allows it to be simulated.
@param body
The body to add to the world.
@discussion If the body has already been added to the world then it will not be added again.
*/
virtual void addBody(Body *body);
/*!
Returns an array of all of the bodies in the world.
@return An array of Body* objects representing all bodies.
*/
virtual Array* getBodies() { return this->_indexing->bodies(); };
virtual void removeBody(Body *body);
//---------------------------------------------------------------------------------------//
#pragma mark Constraints
/*!
Returns an array of all of the contraints registered in the world.
@return An Array of all of the contraints registered in the world.
*/
virtual Array *getConstraints() { return this->_constraints; };
/*!
Adds a constraint to the world, if it hasn't alreadt been added.
@param constraint
The constraint to add to the world
*/
virtual void addConstraint(Constraint *constraint);
/*!
Removes a specified constraint from the world.
@param constraint
The constraint to remove.
*/
virtual void removeConstraint(Constraint *constraint);
//---------------------------------------------------------------------------------------//
#pragma mark Force Generators
/*!
Returns an array of all of the contraints registered in the world.
@return An Array of all of the contraints registered in the world.
*/
virtual Array *getForceGenerators() { return this->_forceGenerators; };
/*!
Adds a force generator to the world, if it hasn't already been added.
@param generator
The force generator to add to the world
*/
virtual void addForceGenerator(ForceGenerator *generator);
/*!
Removes a specified force generator from the world.
@param generator
The force generator to remove.
*/
virtual void removeForceGenerator(ForceGenerator *generator);
//---------------------------------------------------------------------------------------//
#pragma mark Collision Handlers
// collision handling
typedef uintptr_t CollisionKey;
typedef std::function<bool(Arbiter *)> CollisionBeginFunc;
typedef std::function<bool(Arbiter *)> CollisionPreSolveFunc;
typedef std::function<void(Arbiter *)> CollisionPostSolveFunc;
typedef std::function<void(Arbiter *)> CollisionEndFunc;
typedef std::function<void(World *, void *)> CollisionPostStepCallBack;
struct CollisionHandler
{
CollisionLevel a; // the type of the first collision body
CollisionLevel b; // the type of the second collision body
CollisionBeginFunc begin; // called when start touching
CollisionPreSolveFunc presolve; // called before solving
CollisionPostSolveFunc postsolve; // collision been processed
CollisionEndFunc end; // stopped touching
};
typedef struct CollisionHandler CollisionHandler;
/*!
Returns the default collision handler.
@return The default collision handler.
*/
CollisionHandler defaultCollisionHander() { return _defaultHandler; }
/*!
Set the collision handler methods that will be used by default.
@param begin
The method to call when bodies collide.
@param preSolve
The method to call before the collision is resolved.
@param postSolve
The method to call after the collision is resolved.
@param seperate
The method to call when the bodies separate.
@discussion If any value is set to NULL then the current value will be retained.
*/
void setDefaultCollisionHandler(CollisionBeginFunc begin, CollisionPreSolveFunc preSolve, CollisionPostSolveFunc postSolve, CollisionEndFunc seperate);
/*!
Adds new collisions handler methods for two specified collision levels.
@param a
The collision level for one body that will use the specified collision callbacks.
@param b
The collision level for the other body that will use the specified collision callbacks.
@param begin
The method to call when bodies collide.
@param preSolve
The method to call before the collision is resolved.
@param postSolve
The method to call after the collision is resolved.
@param seperate
The method to call when the bodies separate.
@return A bool indicating if the if the new collision handler has been added.
*/
bool addCollisionHandler(CollisionLevel a, CollisionLevel b, CollisionBeginFunc begin, CollisionPreSolveFunc preSolve, CollisionPostSolveFunc postSolve, CollisionEndFunc seperate);
/*!
Remove the collision handler.
@param a
The collision level for one body.
@param b
The collision level for the other body.
@return A bool inducating if the removal was successful. If no collision handler existed then it will return false.
@discussion *Note:* You can not remove the default handler.
*/
bool removeCollisionHandler(CollisionLevel a, CollisionLevel b);
/*!
Removes all collision handlers, except the default handler.
@return A bool inducating whether or not all collision handelrs were removed.
*/
bool removeAllCollisionHandlers();
/*!
Adds a method that will be called at the end of the current step with a specified key that will be passed back.
@param func
The method to call and the end of the current step.
@param key
The key to be used that will be passed back when the callback is called.
@return A bool indicating whether or not the poststep callback was added.
*/
bool addPostStepCallback(CollisionPostStepCallBack func, void *key);
/*!
Returns the collision handler for the two speicfied bodies.
@param a
The first body.
@param b
The second body.
@return The collision handler that will be used for the two bodies.
@discussion If a specific collision handler has not been specified for the two bodies the defauly collision handler will be returned.
*/
CollisionHandler collisionHandlerForBodies(Body *a, Body *b);
private:
float _damping; // the damping applied to forces in each step. (default 1.0).
unsigned int _numberOfIterations; // the number of times to apply impulses & solve constraints in each step.
SpatialIndexing *_indexing; // the spatial indexing system to use.
float _width; // the width of the world
float _height; // the height of the world
Array *_forceGenerators; // array of force generators
Array *_constraints; // array of constraints
CollisionHandler _defaultHandler; // the defuault collision handler
std::unordered_map<CollisionKey, CollisionHandler> _collisionHandlers;
std::unordered_map<void *, CollisionPostStepCallBack> _postStepCallbacks;
};
#endif
| true |
ab6f76ff9691c9a648b6acfccbf1b7531dd8b77e | C++ | qw12345ab/ZadaniaCpp22-09-16 | /EgzaminCPP/EgzOb/1/EgzOb1.1.cpp | WINDOWS-1250 | 250 | 3.453125 | 3 | [] | no_license | // a.)
class Wektor {
float x, y;
// wskanik do elementu klasy wektor typu float
float *wskX;
public:
Wektor() {
wskX = &x;
}
};
// b.)
//siedmioelementowa tablica wskaznikow do funkcji int* fun(int)
// int (*wsk [7]) (int) = &fun;
| true |