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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6d7af5d4c8aeb39bd1d8c8041b73f35f209231a5 | C++ | marek-cel/mscsim | /tests/models/test_fdm_atmospheretest.cpp | UTF-8 | 5,714 | 2.59375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #include <QString>
#include <QtTest>
#include <iostream>
#include <fdm/models/fdm_Atmosphere.h>
////////////////////////////////////////////////////////////////////////////////
#define NUM 9
////////////////////////////////////////////////////////////////////////////////
using namespace std;
////////////////////////////////////////////////////////////////////////////////
class AtmosphereTest : public QObject
{
Q_OBJECT
public:
static const double _h [ NUM ]; // [m] altitude
static const double _t [ NUM ]; // [K] temperature
static const double _p [ NUM ]; // [Pa] pressure
static const double _rho [ NUM ]; // [kg/m^3] density
static const double _c [ NUM ]; // [m/s] speed of sound
static const double _mu [ NUM ]; // [Pa*s] dynamic viscosity
AtmosphereTest();
private:
fdm::Atmosphere *_atmosphere;
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void stdConditions();
void modifiedSeaLevelConditions();
};
////////////////////////////////////////////////////////////////////////////////
const double AtmosphereTest::_h[] = {
0.0,
5000.0,
11000.0,
15000.0,
20000.0,
32000.0,
47000.0,
51000.0,
71000.0
};
// from Table I
const double AtmosphereTest::_t[] = {
288.15,
255.65,
216.65,
216.65,
216.65,
228.65,
270.65,
270.65,
214.65
};
// from Table I
const double AtmosphereTest::_p[] = {
101325.0,
54019.0,
22632.0,
12044.0,
5474.8,
868.01,
110.9,
66.938,
3.9564
};
// from Table I
const double AtmosphereTest::_rho[] = {
1.225,
0.73612,
0.36392,
0.19367,
0.088035,
0.013225,
0.0014275,
0.0008616,
0.000064211
};
// from Table III
const double AtmosphereTest::_c[] = {
340.29,
320.53,
295.07,
295.07,
295.07,
303.13,
329.8,
329.8,
293.7
};
// from Table III
const double AtmosphereTest::_mu[] = {
1.7894e-5,
1.6281e-5,
1.4216e-5,
1.4216e-5,
1.4216e-5,
1.4868e-5,
1.7037e-5,
1.7037e-5,
1.4106e-5
};
////////////////////////////////////////////////////////////////////////////////
AtmosphereTest::AtmosphereTest() : _atmosphere ( 0 ) {}
////////////////////////////////////////////////////////////////////////////////
void AtmosphereTest::initTestCase()
{
_atmosphere = new fdm::Atmosphere();
// double h = 0.0;
// _atmosphere->update( h );
// double t = _atmosphere->getTemperature();
// double p = _atmosphere->getPressure();
// double rho = _atmosphere->getDensity();
// double c = _atmosphere->getSpeedOfSound();
// double mu = _atmosphere->getDynViscosity();
// double nu = _atmosphere->getKinViscosity();
// std::cout << "h: " << h << std::endl;
// std::cout << "t: " << t << std::endl;
// std::cout << "p: " << p << std::endl;
// std::cout << "rho: " << rho << std::endl;
// std::cout << "c: " << c << std::endl;
// std::cout << "mu: " << mu << std::endl;
// std::cout << "nu: " << nu << std::endl;
}
////////////////////////////////////////////////////////////////////////////////
void AtmosphereTest::cleanupTestCase()
{
if ( _atmosphere ) delete _atmosphere;
_atmosphere = 0;
}
////////////////////////////////////////////////////////////////////////////////
void AtmosphereTest::stdConditions()
{
_atmosphere->setPressureSL( fdm::Atmosphere::_std_sl_p );
_atmosphere->setTemperatureSL( fdm::Atmosphere::_std_sl_t );
for ( int i = 0; i < NUM; i++ )
{
_atmosphere->update( _h[ i ] );
double h = _h[ i ];
double t = _atmosphere->getTemperature();
double p = _atmosphere->getPressure();
double rho = _atmosphere->getDensity();
double c = _atmosphere->getSpeedOfSound();
double mu = _atmosphere->getDynViscosity();
QVERIFY2( fabs( t - _t [ i ] ) < 1.0e-2 * fabs( _t [ i ] ) , "Failure" );
QVERIFY2( fabs( p - _p [ i ] ) < 1.0e-2 * fabs( _p [ i ] ) , "Failure" );
QVERIFY2( fabs( rho - _rho [ i ] ) < 1.0e-2 * fabs( _rho [ i ] ) , "Failure" );
QVERIFY2( fabs( c - _c [ i ] ) < 1.0e-2 * fabs( _c [ i ] ) , "Failure" );
QVERIFY2( fabs( mu - _mu [ i ] ) < 1.0e-2 * fabs( _mu [ i ] ) , "Failure" );
}
}
////////////////////////////////////////////////////////////////////////////////
void AtmosphereTest::modifiedSeaLevelConditions()
{
_atmosphere->setPressureSL( fdm::Atmosphere::_std_sl_p + 1000.0 );
_atmosphere->setTemperatureSL( fdm::Atmosphere::_std_sl_t + 10.0 );
for ( int i = 2; i < NUM; i++ )
{
_atmosphere->update( _h[ i ] );
double t = _atmosphere->getTemperature();
double p = _atmosphere->getPressure();
double rho = _atmosphere->getDensity();
double c = _atmosphere->getSpeedOfSound();
double mu = _atmosphere->getDynViscosity();
QVERIFY2( fabs( t - _t [ i ] ) < 1.0e-2 * fabs( _t [ i ] ) , "Failure" );
QVERIFY2( fabs( p - _p [ i ] ) < 1.0e-2 * fabs( _p [ i ] ) , "Failure" );
QVERIFY2( fabs( rho - _rho [ i ] ) < 1.0e-2 * fabs( _rho [ i ] ) , "Failure" );
QVERIFY2( fabs( c - _c [ i ] ) < 1.0e-2 * fabs( _c [ i ] ) , "Failure" );
QVERIFY2( fabs( mu - _mu [ i ] ) < 1.0e-2 * fabs( _mu [ i ] ) , "Failure" );
}
}
////////////////////////////////////////////////////////////////////////////////
QTEST_APPLESS_MAIN(AtmosphereTest)
////////////////////////////////////////////////////////////////////////////////
#include "test_fdm_atmospheretest.moc"
| true |
55f9f7265a6b45ae1091592f0cddbc475f99f319 | C++ | lvningyuan/pdlbox | /名字相似度判断.cpp | UTF-8 | 494 | 2.6875 | 3 | [] | no_license | class Solution {
public:
bool isLongPressedName(string name, string typed) {
int len = typed.size();
int j =0;
for(int i =0; i < len; ++i)
{
if(typed[i] == name[j])
++j;
else if(typed[i] != name[j] &&
typed[i] == typed[i-1])
continue;
else
return false;
}
if(j != name.size() )
return false;
return true;
}
}; | true |
162cbe381179ddf4f7f33f1372eb8cb93b245cb0 | C++ | Top0201/RayTracer | /raytrace_hw/light.cpp | GB18030 | 2,655 | 2.984375 | 3 | [] | no_license | #include"light.h"
#include<sstream>
#include<string>
#include<cmath>
#include<cstdlib>
#define ran() ( double( rand() % 32768 ) / 32768 )
Light::Light() {
sample = rand();
next = NULL;
lightPrimitive = NULL;
}
void Light::Input( std::string var , std::stringstream& fin ) {
if ( var == "color=" ) color.Input( fin );
}
void PointLight::Input( std::string var , std::stringstream& fin ) {
if ( var == "O=" ) O.Input( fin );
Light::Input( var , fin );
}
double PointLight::CalnShade( Vector3 C , Primitive* primitive_head , int shade_quality ) {
Vector3 V = O - C;
double dist = V.Module();
//ޱڵshadowϵ
for ( Primitive* now = primitive_head ; now != NULL ; now = now->GetNext() )
{
CollidePrimitive tmp = now->Collide(C, V);
if ( EPS < (dist - tmp.dist) )
//ڵshadow=0
return 0;
}
//δڵshadow=1
return 1;
}
void SquareLight::Input( std::string var , std::stringstream& fin ) {
if ( var == "O=" ) O.Input( fin );
if ( var == "Dx=" ) Dx.Input( fin );
if ( var == "Dy=" ) Dy.Input( fin );
Light::Input( var , fin );
}
//?ʵarea light
double SquareLight::CalnShade( Vector3 C , Primitive* primitive_head , int shade_quality ) {
return 1;
}
Primitive* SquareLight::CreateLightPrimitive()
{
//OΪƽĵƽ
PlaneAreaLightPrimitive* res = new PlaneAreaLightPrimitive(O, Dx, Dy, color);
lightPrimitive = res;
return res;
}
void SphereLight::Input( std::string var , std::stringstream& fin ) {
if ( var == "O=" ) O.Input( fin );
if ( var == "R=" ) fin>>R;
Light::Input( var , fin );
}
//㷨θĽ
double SphereLight::CalnShade( Vector3 C , Primitive* primitive_head , int shade_quality ) {
long long shade = 0;
//NEED TO IMPLEMENT
double stackAngle = PI / 3;
double sectorAngle = 2 * PI / 3;
long long lightCount = 0;
long long shadowCount = 0;
//
for (int i = 0; i <= PI; i += stackAngle)
{
for (int j = 0; j <= 2 * PI; j += sectorAngle)
{
double x = R * sin(i) * sin(j);
double y = R * sin(i) * cos(j);
double z = R * cos(i);
Vector3 P = Vector3(x, y, z);
Vector3 V = P - C;
double dist = V.Module();
for (Primitive* now = primitive_head; now != NULL; now = now->GetNext())
{
CollidePrimitive tmp = now->Collide(C, V);
if (EPS < (dist - tmp.dist))
shadowCount += 1;
else
lightCount += 1;
}
}
}
shade = lightCount / (lightCount + shadowCount);
return shade;
}
Primitive* SphereLight::CreateLightPrimitive()
{
SphereLightPrimitive* res = new SphereLightPrimitive(O, R, color);
lightPrimitive = res;
return res;
}
| true |
e94fb3a6cc5305eb78021a3b16dd1c68c0b97694 | C++ | SherlockThang/sidecar | /Algorithms/ncintegrate/NCIntegrate.cc | UTF-8 | 12,651 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <cmath>
#include <iterator>
#include "Utils/VsipVector.h"
#include <vsip/math.hpp>
#include "boost/bind.hpp"
#include "Logger/Log.h"
#include "NCIntegrate.h"
#include "NCIntegrate_defaults.h"
#include "QtCore/QString"
using namespace SideCar;
using namespace SideCar::Messages;
using namespace SideCar::Algorithms;
NCIntegrate::NCIntegrate(Controller& controller, Logger::Log& log) :
Algorithm(controller, log), enabled_(Parameter::BoolValue::Make("enabled", "Enabled", kDefaultEnabled)),
numPulses_(Parameter::PositiveIntValue::Make("numPRIs", "Num PRIs", kDefaultNumPRIs)),
iqValues_(Parameter::BoolValue::Make("iqValues", "IQ Values", kDefaultIqValues)), in_(kDefaultNumPRIs),
runningAverage_()
{
numPulses_->connectChangedSignalTo(boost::bind(&NCIntegrate::numPulsesChanged, this, _1));
iqValues_->connectChangedSignalTo(boost::bind(&NCIntegrate::iqValuesChanged, this, _1));
}
bool
NCIntegrate::startup()
{
registerProcessor<NCIntegrate, Video>(&NCIntegrate::process);
return registerParameter(enabled_) && registerParameter(iqValues_) && registerParameter(numPulses_) &&
Algorithm::startup();
}
bool
NCIntegrate::reset()
{
in_.clear();
runningAverage_.clear();
return true;
}
/** Text Stream insertion operator for a RunningAverageVector. Prints out the values of the vector.
*/
inline std::ostream&
operator<<(std::ostream& os, const NCIntegrate::RunningAverageVector& rav)
{
Traits::GenericPrinter<NCIntegrate::RunningAverageVector::value_type, 10>(os, rav);
return os;
}
/** Base class for the averaging functors used to update the running average vector.
*/
struct AverageBase {
using DataType = NCIntegrate::RunningAverageVector::value_type;
int32_t size;
int32_t halfSize;
Video::const_iterator in;
Video::Container& out;
/** Constructor
\param s number of messages being integrated
\param i input iterator of the message being added
\param o outputiterator of the message being built
*/
AverageBase(int32_t s, Video::const_iterator i, Video::Container& o) : size(s), halfSize(s / 2), in(i), out(o) {}
/** Convenience function for IQ processing. Returns the square of the given value.
\param x value to work with
\return squared value
*/
static DataType squared(DataType x) { return x * x; }
/** Convenience function for IQ processing. Returns the square root of the given value, rounded to the
nearest integer.
\param x value to work with
\return rounded squared-root value
*/
static DataType root(DataType x) { return ::round(::sqrt(x)); }
};
/** Functor used to update runningAverage_ by adding new message data and removing the oldest message, and as a
side-effect add running average values to an output message.
*/
struct Average3 : public AverageBase {
Video::const_iterator gone;
Average3(int32_t s, Video::const_iterator i, Video::const_iterator g, Video::Container& o) :
AverageBase(s, i, o), gone(g)
{
}
DataType operator()(DataType x)
{
DataType v = x + *in++ - *gone++;
out.push_back((v + halfSize) / size);
return v;
}
};
/** Functor used to update runningAverage_ by adding new IQ message data and removing the oldest message, and as
a side-effect add running average values to an output message.
*/
struct Average3IQ : public AverageBase {
Video::const_iterator gone;
Average3IQ(int32_t s, Video::const_iterator i, Video::const_iterator g, Video::Container& o) :
AverageBase(s, i, o), gone(g)
{
}
DataType operator()(DataType x)
{
DataType newI = *in++;
DataType newQ = *in++;
DataType oldI = *gone++;
DataType oldQ = *gone++;
DataType v = x + (squared(newI) + squared(newQ)) - (squared(oldI) + squared(oldQ));
out.push_back(root((v + halfSize) / size));
return v;
}
};
/** Functor used to update runningAverage_ by adding new message data, and as a side-effect add running average
values to an output message.
*/
struct Average2 : public AverageBase {
Average2(int32_t s, Video::const_iterator i, Video::Container& o) : AverageBase(s, i, o) {}
DataType operator()(DataType x)
{
DataType v = x + *in++;
out.push_back((v + halfSize) / size);
return v;
}
};
/** Functor used to update runningAverage_ by adding new IQ message data, and as a side-effect add running
average values to an output message.
*/
struct Average2IQ : public AverageBase {
Average2IQ(int32_t s, Video::const_iterator i, Video::Container& o) : AverageBase(s, i, o) {}
DataType operator()(DataType x)
{
DataType newI = *in++;
DataType newQ = *in++;
DataType v = x + squared(newI) + squared(newQ);
out.push_back(root((v + halfSize) / size));
return v;
}
};
bool
NCIntegrate::process(Video::Ref msg)
{
static Logger::ProcLog log("process", getLog());
LOGINFO << std::endl;
LOGDEBUG << *msg.get() << std::endl;
if (!enabled_->getValue() || numPulses_->getValue() == 1) {
bool rc = send(msg);
LOGDEBUG << "rc: " << rc << std::endl;
return rc;
}
Video::Ref gone;
if (in_.full()) { gone = in_.back(); }
in_.add(msg);
if (in_.size() == 1) {
// This is the first message, just copy over its sample values into our running average buffer.
//
LOGDEBUG << "first time" << std::endl;
if (iqValues_->getValue()) {
Video::const_iterator pos = msg->begin();
Video::const_iterator end = msg->end();
while (pos < end) {
RunningAverageVector::value_type newI = *pos++;
RunningAverageVector::value_type newQ = *pos++;
runningAverage_.push_back(newI * newI + newQ * newQ);
}
} else {
std::copy(msg->begin(), msg->end(), std::back_inserter<>(runningAverage_));
}
LOGDEBUG << runningAverage_ << std::endl;
return true;
}
// Make sure we don't address out-of-bounds values.
//
size_t limit = runningAverage_.size();
if (msg->size() < limit) {
limit = msg->size();
if (iqValues_->getValue()) { limit /= 2; }
} else if (msg->size() > limit) {
// Expand our runningAverage_ to the largest message ever seen.
//
limit = msg->size();
if (iqValues_->getValue()) { limit /= 2; }
runningAverage_.resize(limit, 0);
}
if (!in_.full()) {
// Just update runningAverage_ by adding the new message to it.
//
if (iqValues_->getValue()) {
RunningAverageVector::iterator pos = runningAverage_.begin();
RunningAverageVector::iterator end = runningAverage_.begin() + limit;
Video::const_iterator vit = msg->begin();
while (pos != end) {
RunningAverageVector::value_type i = *vit++;
RunningAverageVector::value_type q = *vit++;
*pos++ += i * i + q * q;
}
} else {
std::transform(runningAverage_.begin(), runningAverage_.begin() + limit, msg->begin(),
runningAverage_.begin(), std::plus<int32_t>());
}
LOGDEBUG << runningAverage_ << std::endl;
return true;
}
// Base our outgoing message on the middle message in our retention queue.
//
Video::Ref midPoint(*(in_.begin() + in_.size() / 2));
Video::Ref out(Video::Make(getName(), midPoint));
// Make sure we only allocate once for the samples we are about to generate.
//
out->reserve(runningAverage_.size());
if (gone) {
// Update runningAverage by adding to it the newest input message and subtracting the oldest input message, and
// fill the output message with the calculated running average.
//
if (iqValues_->getValue()) {
std::transform(runningAverage_.begin(), runningAverage_.end(), runningAverage_.begin(),
Average3IQ(in_.size(), msg->begin(), gone->begin(), out->getData()));
} else {
std::transform(runningAverage_.begin(), runningAverage_.end(), runningAverage_.begin(),
Average3(in_.size(), msg->begin(), gone->begin(), out->getData()));
}
} else {
// Update runningAverage by adding to it the newest input message, and fill the output message with the
// calculated running average.
//
if (iqValues_->getValue()) {
std::transform(runningAverage_.begin(), runningAverage_.end(), runningAverage_.begin(),
Average2IQ(in_.size(), msg->begin(), out->getData()));
} else {
std::transform(runningAverage_.begin(), runningAverage_.end(), runningAverage_.begin(),
Average2(in_.size(), msg->begin(), out->getData()));
}
}
bool rc = send(out);
LOGDEBUG << "rc: " << rc << std::endl;
return rc;
}
#if 0
bool
NCIntegrate::process(Video::Ref msg)
{
static Logger::ProcLog log("process", getLog());
LOGINFO << std::endl;
LOGDEBUG << *msg.get() << std::endl;
if (! enabled_->getValue() || numPulses_->getValue() == 1) {
bool rc = send(msg);
LOGDEBUG << "rc: " << rc << std::endl;
return rc;
}
Video::Ref gone;
if (in_.full()) {
gone = in_.back();
}
in_.add(msg);
if (in_.size() == 1) {
// This is the first message, just copy over its sample values into our running average buffer.
//
LOGDEBUG << "first time" << std::endl;
std::copy(msg->begin(), msg->end(),
std::back_inserter<>(runningAverage_));
LOGDEBUG << runningAverage_ << std::endl;
return true;
}
VsipVector<Video> vMsg(*msg);
VsipVector<RunningAverageVector> vAve(runningAverage_);
vMsg.admit(true); // Bring in values from msg vector
vAve.admit(true); // Bring in values from runningAverage vector
vAve.v += vMsg.v;
vMsg.release(false); // Don't need these values from vsip
if (! in_.full()) {
// Not enough PRIs to send out a message, so just add to the running average vector.
//
vAve.release(true); // Bring back values to runningAverage
LOGDEBUG << runningAverage_ << std::endl;
return true;
}
// Base our outgoing message on the middle message in our retention queue.
//
Video::Ref midPoint(*(in_.begin() + in_.size() / 2));
Video::Ref out(Video::Make(getName(), midPoint));
out->resize(in_.getMaxMsgSize(), 0);
VsipVector<Video> vOut(*out);
vOut.admit(false); // Don't bring in values from out vector
if (gone) {
// We have to remove the effect of the oldest message sample data while calculating the new average.
//
VsipVector<Video> vOld(*gone);
vOld.admit(true);
vAve.v -= vOld.v;
vOld.release(false);
}
// Add in half buffer size before dividing to handle rounding up.
//
int half = in_.size() / 2;
vOut.v = (vAve.v + half) / in_.size();
// Advise VSIPL to flush internal buffers to external vector. Only necessary for runningAverage_ and out
// vectors.
//
vAve.release(true);
LOGDEBUG << runningAverage_ << ' ' << in_.size() << std::endl;
vOut.release(true);
bool rc = send(out);
LOGDEBUG << "rc: " << rc << std::endl;
return rc;
}
#endif
void
NCIntegrate::numPulsesChanged(const Parameter::PositiveIntValue& value)
{
static Logger::ProcLog log("numPulsesChanged", getLog());
size_t newSize = value.getValue();
LOGINFO << "new value: " << newSize << std::endl;
in_.setCapacity(newSize);
in_.clear();
runningAverage_.clear();
}
void
NCIntegrate::iqValuesChanged(const Parameter::BoolValue& value)
{
static Logger::ProcLog log("iqValuesChanged", getLog());
in_.clear();
runningAverage_.clear();
}
void
NCIntegrate::setInfoSlots(IO::StatusBase& status)
{
status.setSlot(kNumPRIs, int(in_.getCapacity()));
status.setSlot(kIQValues, iqValues_->getValue());
}
extern "C" ACE_Svc_Export void*
FormatInfo(const IO::StatusBase& status, int role)
{
if (role != Qt::DisplayRole) return NULL;
int numPRIs = status[NCIntegrate::kNumPRIs];
bool iqValues = status[NCIntegrate::kIQValues];
QString out = QString("Num PRIs: %1").arg(numPRIs);
if (iqValues) out += " *IQ*";
return Algorithm::FormatInfoValue(out);
}
extern "C" ACE_Svc_Export Algorithm*
NCIntegrateMake(Controller& controller, Logger::Log& log)
{
return new NCIntegrate(controller, log);
}
| true |
978cb5544dbe2401f051ca108ff5e158502983c8 | C++ | jebouin/Infected-Pipes | /gui/Skill.cpp | UTF-8 | 853 | 2.734375 | 3 | [] | no_license | #include "Skill.h"
#include "IP.h"
#include "SkillIcon.h"
Skill::Skill(IP& ip, sf::Vector2i skillPos, sf::Vector2f iconPos, string name, string description, int maxLevel) {
_icon = new SkillIcon(ip, skillPos, name, description, *this);
_icon->setPosition(iconPos);
_maxLevel = maxLevel;
_level = 0;
}
Skill::~Skill() {
delete _icon;
_icon = 0;
}
void Skill::Update(IP& ip, float eTime) {
_icon->Update(ip, eTime);
}
void Skill::DrawBack(IP& ip) {
_icon->DrawBack(ip);
}
void Skill::DrawTop(IP& ip) {
_icon->DrawTop(ip);
}
int Skill::GetLevel() {
return _level;
}
int Skill::GetLevelMax() {
return _maxLevel;
}
void Skill::LevelUp() {
if(_level == _maxLevel) {
return;
}
_level++;
}
SkillIcon& Skill::GetIcon() {
return *_icon;
}
void Skill::Unhide() {
_icon->Unhide();
}
| true |
53b35350b74dad0fe17b6390aca9b526c7739c01 | C++ | arcreane/c-game-errorphp | /Adventure/Adventure/Sources/Potion.cpp | UTF-8 | 738 | 3.03125 | 3 | [] | no_license | #include "Potion.h"
#include <random>
#include <stdio.h>
#include <iostream>
using namespace std;
void Potions::setPotionType() {
std::random_device rd;
std::mt19937 mt(rd());
auto dist = std::uniform_int_distribution<int>(0, 2);
ePotionType rPotionType = ePotionType(dist(mt));
mPotionType = rPotionType;
}
void Potions::getPotionType() {
switch (mPotionType)
{
case POTION_RES:
cout << "C'est une potion de resistance magique " << endl;
break;
case POTION_HEAL:
cout << "C'est une potion de soin" << endl;
break;
case POTION_ARMOR:
cout << "C'est une potion d'armure !" << endl;
break;
default:
break;
}
}
void Potions::createPotion() {
Potions::setPotionType();
Potions::getPotionType();
}
| true |
4f857ef0298d64d10255f901b35068843515b32f | C++ | sb565/Algorithms_Implementation | /Codes/GraphColoring.cpp | UTF-8 | 1,138 | 3.109375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int x[50],g[50][50],n,i,j,m;
void next_value(int k)
{
while(1)
{
x[k]=(x[k]+1)%(m+1);
if(x[k]==0)
return;
for(j=1;j<=n;j++)
{
if(g[k][j]!=0&&(x[k]==x[j]))
break;
}
if(j==n+1)
return;
}
}
int coloring(int k)
{
int c=0;
do
{
next_value(k);
if(x[k]==0)
return c;
if(k==n)
{
for(i=1;i<=n;i++)
cout<<"v:"<<i<<" = c:"<<x[i]<<" ";
cout<<endl;
c++;
}
else
c+=coloring(k+1);
}while(k<n+1);
}
int main()
{
int e,k,l;
cout<<"Enter no. of vertices : ";
cin>>n;
cout<<"Enter the number of colours :";
cin>>m;
cout<<"Enter no. of edges : ";
cin>>e;
cout<<"\nThe maximum possible colours that can be assigned are: "<<m<<endl;
for(i=0;i<=n;i++)
for(j=0;j<=n;j++)
g[i][j]=0;
cout<<"Enter u and v of an edge\n";
for(i=1;i<=e;i++)
{
cout<<"for egde "<<i<<endl;
cin>>k>>l;
g[k][l]=1;
g[l][k]=1;
}
for(i=0;i<=n;i++)
x[i]=0;
cout<<"\nThe colouring possibilities are:\n";
k=coloring(1);
if(k==0)
cout<<"Colouring not possible \n";
else
cout<<"Total number of possible ways of colouring are :"<<k<<endl;
return 0;
}
| true |
52e72ca52dc6f01ac410a35e0901b6202a24f481 | C++ | chiumax/CMSC-140 | /Hw4/Hw4_part1.cpp | UTF-8 | 1,349 | 3.734375 | 4 | [
"MIT"
] | permissive | /*
Hw4_part1.cpp
CMSC 140, CRN 24381, Dr. Kuijt
Max C.
A software company sells a package that retails for $99. Quantity discounts are given according to the following table.
Quantity discount
------------------------------
10-19 20%
20-49 30%
50-99 40%
100 or more 50%
Write a program that asks for the number of units sold and computes the total cost of the purchase.
Input validation: Make sure the number of units is greater than 0.
*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int input;
float discount;
cout << "How many units were sold? ";
cin >> input;
if (0 < input && input < 10)
{
discount = 0;
}
else if (10 <= input && input <= 19)
{
discount = .20;
}
else if (20 <= input && input <= 49)
{
discount = .30;
}
else if (50 <= input && input <= 99)
{
discount = .40;
}
else if (100 <= input)
{
discount = .50;
}
else
{
cout << "Units sold must be greater than zero";
return 0;
}
// 2 decimal points
cout << "The total cost of the purchase is $" << fixed << setprecision(2) << ((input * 99) - (input * 99 * discount));
return 0;
} | true |
b2926031731aa2c4cb2ff356d82e8a1698a6e4d0 | C++ | xxning/Algorithm | /PRO4/ex1/source/EdgeGen.cpp | UTF-8 | 1,202 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
int main(){
FILE *input;
srand((unsigned)time(NULL));
int i,j,k;
int n,e,v1,v2;
char Filename[6][28]={"./ex1/input/size1/input.txt",
"./ex1/input/size2/input.txt",
"./ex1/input/size3/input.txt",
"./ex1/input/size4/input.txt",
"./ex1/input/size5/input.txt",
"./ex1/input/size6/input.txt"
};
char Edge[256][256];
for(i=0;i<256;i++)
for(j=0;j<256;j++)
Edge[i][j]=0;
//******************************************
//******************************************
for(i=0;i<6;i++){
n=pow(2,i+3);
e=n*(i+3);
input=fopen(Filename[i],"w");
if(!input){
printf("error:can't open objcct file.\n");
exit(1);
}
for(j=0;j<e;j++){
v1=rand()%n;
v2=rand()%n;
if(v1==v2||Edge[v1][v2]==1)
j--;
else{
Edge[v1][v2]=1;
fprintf(input,"%d %d\n",v1,v2);
}
}
for(j=0;j<n;j++)
for(k=0;k<n;k++)
Edge[j][k]=0;
fclose(input);
}
//******************************************
//******************************************
printf("Complete the generate of edge(ex2).\n");
return 0;
}
| true |
a8cf084981779b4b0550aa24c55898ab5e08f604 | C++ | izzyreal/vmpc-unreal-plugin | /VmpcPlugin/Source/ThirdParty/include/mpc/src/ui/NameGui.cpp | UTF-8 | 1,559 | 2.59375 | 3 | [] | no_license | #include <ui/NameGui.hpp>
#include <lang/StrUtil.hpp>
#include <Mpc.hpp>
#include <Util.hpp>
using namespace mpc::ui;
using namespace std;
NameGui::NameGui()
{
}
void NameGui::setName(string name)
{
this->name = moduru::lang::StrUtil::padRight(name, " ", 16);
nameLimit = 16;
}
void NameGui::setNameLimit(int i)
{
name = name.substr(0, i);
nameLimit = i;
}
int NameGui::getNameLimit()
{
return nameLimit;
}
void NameGui::setName(string str, int i)
{
name[i] = str[0];
}
string NameGui::getName()
{
string s = name;
while (!s.empty() && isspace(s.back())) s.pop_back();
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ') s[i] = '_';
}
return moduru::lang::StrUtil::padRight(s, " ", nameLimit);
}
void NameGui::changeNameCharacter(int i, bool up)
{
char schar = name[i];
string s{ schar };
auto stringCounter = 0;
for (auto str : mpc::Mpc::akaiAscii) {
if (str.compare(s) == 0) {
break;
}
stringCounter++;
}
if (stringCounter == 0 && !up) return;
if (stringCounter == 75 && up) return;
auto change = -1;
if (up) change = 1;
if (stringCounter > 75) {
s = " ";
}
else {
s = mpc::Mpc::akaiAscii[stringCounter + change];
}
name = name.substr(0, i).append(s).append(name.substr(i + 1, name.length()));
setChanged();
notifyObservers(string("name"));
}
void NameGui::setNameBeingEdited(bool b)
{
editing = b;
}
void NameGui::setParameterName(string s)
{
parameterName = s;
}
string NameGui::getParameterName()
{
return parameterName;
}
bool NameGui::isNameBeingEdited()
{
return editing;
}
| true |
e75af1d2068b7f3b901c87c6ef526e66679bd3fd | C++ | rizky-bagus/Tsunemori-Akane | /CQU/CQU Monthly May 2016/G.cpp | UTF-8 | 1,572 | 2.53125 | 3 | [] | no_license | #include <set>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int T;
int n, f[100005], rk[100005];
set<int> s[100005];
int find(int x) {
if (f[x] == x) return x;
s[f[x]].erase(x);
f[x] = find(f[x]);
s[f[x]].insert(x);
return f[x];
}
void merge(int x, int y) {
int fx = find(x), fy = find(y);
if (fx == fy) return;
if (rk[fx] >= rk[fy]) {
rk[fx] += rk[fy];
s[f[fy]].erase(fy);
f[fy] = fx;
s[fx].insert(fy);
} else {
rk[fy] += rk[fx];
s[f[fx]].erase(fx);
f[fx] = fy;
s[fy].insert(fx);
}
}
int g[100005], pg;
void gao(int a) {
for (set<int>::iterator it = s[a].begin(); it != s[a].end(); ++it) {
g[pg++] = *it;
if (*it == a) continue;
gao(*it);
}
s[a].clear();
}
char o[5];
int main() {
freopen("in", "r", stdin);
scanf("%d", &T);
for (int _ = 1; _ <= T; ++_) {
int n, m; scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
s[i].insert(i);
f[i] = i;
rk[i] = 1;
}
while (m--) {
scanf("%s", o);
if (o[0] == 'U') {
int x, y; scanf("%d%d", &x, &y);
merge(x, y);
}
if (o[0] == 'D') {
int x; scanf("%d", &x);
int fx = find(x);
pg = 0;
gao(fx);
for (int i = 0; i < pg; ++i) {
s[g[i]].insert(g[i]);
f[g[i]] = g[i];
rk[g[i]] = 1;
}
}
if (o[0] == 'S') {
int x; scanf("%d", &x);
int fx = find(x);
printf("%d\n", rk[fx]);
}
if (o[0] == 'F') {
int x, y; scanf("%d%d", &x, &y);
int fx = find(x), fy = find(y);
puts(fx == fy ? "Yes" : "No");
}
}
}
return 0;
}
| true |
cdc81e82c2524a5adfb2124e545ec4f94b269335 | C++ | saderholm/SeniorDesign19 | /motortest/motortest.ino | UTF-8 | 3,411 | 2.90625 | 3 | [] | no_license | #include <Wire.h>
#include <Adafruit_MotorShield.h>
// Create the motor shield object with default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *m0 = AFMS.getMotor(1); // connect DC motor to port 0
Adafruit_DCMotor *m1 = AFMS.getMotor(2); // connect DC motor to port 1
Adafruit_DCMotor *m2 = AFMS.getMotor(3); // connect DC motor to port 2
Adafruit_DCMotor *m3 = AFMS.getMotor(4); // connect DC motor to port 3
// m1 m2 m1: front left (BR)
// 0-----0 m2: front right (BR)
// m3: back left (RB)
// 0-----0 m4: back right (RB)
// m3 m4
int s = 150;
void setup() {
AFMS.begin(); // default frequency = 1.6 kHz
// Turn on motors
m0->setSpeed(200);
m1->setSpeed(200);
m2->setSpeed(200);
m3->setSpeed(200);
m0->run(RELEASE);
m1->run(RELEASE);
m2->run(RELEASE);
m3->run(RELEASE);
Serial.begin(9600);
}
void loop() {
spiralling();
}
void test(){
// Test forward, pause, and backward
forward(s);
delay(1000);
pause();
delay(500);
backward(s);
delay(1000);
pause();
// Test left turn & circling function
for(int i = 0; i < 3; i++){
leftTurn();
delay(500);
forward(s);
delay(500);
}
}
void spiral() {
m0->setSpeed(45);
m1->setSpeed(255);
m2->setSpeed(45);
m3->setSpeed(255);
m0->run(FORWARD);
m1->run(FORWARD);
m2->run(FORWARD);
m3->run(FORWARD);
}
void spiralling() {
// digitalWrite(m0,LOW);
// digitalWrite(m1,HIGH);
// digitalWrite(m2,LOW);
// digitalWrite(m3,HIGH);
int tourtime=10000; // circle tourtime. it is about intersection areas between each spiral. it should be less than circle time
int decreasetime=10; // time for next tour, larger spiral needs more time
int numberofspiral=8; // number of circle
int minspeed=137; // initial speed for spiral.
int maxspeed=255;// max speed
for(int i=0;i<=numberofspiral;i++) {
m0->setSpeed(minspeed);
m1->setSpeed(maxspeed);
m2->setSpeed(minspeed);
m3->setSpeed(maxspeed);
m0->run(FORWARD);
m1->run(FORWARD);
m2->run(FORWARD);
m3->run(FORWARD);
minspeed=minspeed-8;// increase the speed to increase radius
delay(tourtime);
tourtime=tourtime-decreasetime;// increase the time for scan optimum area
}
delay(150);
}
void circle() {
m0->setSpeed(255);
m1->setSpeed(137);
m2->setSpeed(255);
m3->setSpeed(137);
m0->run(FORWARD);
m1->run(FORWARD);
m2->run(FORWARD);
m3->run(FORWARD);
}
void pause() {
m0->run(RELEASE);
m1->run(RELEASE);
m2->run(RELEASE);
m3->run(RELEASE);
}
void forward(int speed) {
m0->setSpeed(speed);
m1->setSpeed(speed);
m2->setSpeed(speed);
m3->setSpeed(speed);
m0->run(FORWARD);
m1->run(FORWARD);
m2->run(FORWARD);
m3->run(FORWARD);
}
void backward(int speed) {
m0->setSpeed(speed);
m1->setSpeed(speed);
m2->setSpeed(speed);
m3->setSpeed(speed);
m0->run(BACKWARD);
m1->run(BACKWARD);
m2->run(BACKWARD);
m3->run(BACKWARD);
}
void leftTurn() {
// outside wheels
m0->setSpeed(255);
m2->setSpeed(255);
// inside wheels
m1->setSpeed(0); // example values, can be changed
m3->setSpeed(0);
m0->run(FORWARD);
m1->run(FORWARD);
m2->run(FORWARD);
m3->run(FORWARD);
}
| true |
31c0251293708211b9c19f26034fa301f8647076 | C++ | Xangis/magma | /editors/de310/source/obj/objhere.cpp | UTF-8 | 13,430 | 2.640625 | 3 | [] | no_license | //
// File: objhere.cpp originally part of dikuEdit
//
// Usage: functions related to objectHere structures in general
//
// Copyright 1995-98 (C) Michael Glosenger
//
#include <iostream>
#include "../fh.h"
#include "../types.h"
#include "objhere.h"
#include "../room/room.h"
#include "object.h"
using namespace std;
extern ulong numbObjs;
extern dikuRoom *roomHead;
extern dikuMob *mobHead;
extern editableListNode *inventory;
//
// checkAllObjInsideForVnum : checks object pointed to by objHere as well
// as objects inside for matching vnum
//
char checkAllObjInsideForVnum(objectHere *objHere, const long vnum)
{
objectHere *obj = objHere;
while (obj)
{
if (obj->objectNumb == vnum) return TRUE;
if (checkAllObjInsideForVnum(obj->objInside, vnum)) return TRUE;
obj = obj->Next;
}
return FALSE;
}
//
// findObjHere : Returns the address of the objectHere node that has the
// requested objNumber (if any) - scans through every objHere
// in the room list
//
// objNumber : object number to look for in all objectHere nodes
// everywhere
// *roomListHead : head of rooms to search through
// *roomNumb : pointer to ulong to set to roomNumb
// checkOnlyThisRoom : if TRUE, checks only room pointer passed
// checkOnlyVisible : if TRUE, doesn't check objs in containers or on mobs
//
objectHere *findObjHere(const ulong objNumber, dikuRoom *roomNode,
ulong *roomNumb,
const char checkOnlyThisRoom /* = FALSE*/,
const char checkOnlyVisible /* = FALSE*/)
{
objectHere *obj;
mobHere *mob;
long i;
while (roomNode)
{
obj = roomNode->objectHead;
while (obj)
{
if (obj->objectNumb == objNumber)
{
*roomNumb = roomNode->roomNumber;
return obj;
}
if (obj->objInside && !checkOnlyVisible)
{
if (checkAllObjInsideForVnum(obj->objInside, objNumber))
{
*roomNumb = roomNode->roomNumber;
return obj;
}
}
obj = obj->Next;
}
mob = roomNode->mobHead;
while (mob && !checkOnlyVisible)
{
if (mob->objectHead)
{
obj = mob->objectHead;
while (obj)
{
if (obj->objectNumb == objNumber)
{
*roomNumb = roomNode->roomNumber;
return obj;
}
if ((obj->objInside) &&
(checkAllObjInsideForVnum(obj->objInside, objNumber)))
{
*roomNumb = roomNode->roomNumber;
return obj;
}
obj = obj->Next;
}
}
for (i = WEAR_LOW; i <= WEAR_TRUEHIGH; i++)
{
obj = mob->equipment[i];
if (obj)
{
if (obj->objectNumb == objNumber)
{
*roomNumb = roomNode->roomNumber;
return obj;
}
if ((obj->objInside) &&
(checkAllObjInsideForVnum(obj->objInside, objNumber)))
{
*roomNumb = roomNode->roomNumber;
return obj;
}
}
}
mob = mob->Next;
}
if (!checkOnlyThisRoom) roomNode = roomNode->Next;
else return NULL;
}
return NULL;
}
//
// getNumbObjectHereNodes : Returns the number of nodes in a specific
// objectHere list
//
// *objNode : take a wild guess, bucko
//
ulong getNumbObjectHereNodes(objectHere *objNode)
{
ulong i = 0;
while (objNode)
{
i++;
objNode = objNode->Next;
}
return i;
}
//
// copyObjHere : Copies just one objectHere
//
// *srcObjHere : take a wild guess, bucko
// incLoaded : if true, increments appropriate vars (in funcs called)
//
objectHere *copyObjHere(objectHere *srcObjHere, const char incLoaded)
{
objectHere *newObjHere;
if (!srcObjHere) return NULL;
newObjHere = new objectHere;
if (!newObjHere)
{
cout << "\n\nERROR: copyObjHere() - ran out of mem alloc'ing new "
<< " objectHere node. Aborting..\n\n";
return NULL;
}
// first, the easy stuff
memcpy(newObjHere, srcObjHere, sizeof(objectHere));
newObjHere->Next = NULL;
// now, the not quite as easy but still relatively simple stuff
newObjHere->objInside = copyObjHereList(srcObjHere->objInside, incLoaded);
return newObjHere;
}
//
// copyObjHereList : Copies an objectHere list, returning the address of the
// new list
//
// *srcObjHere : take a wild guess, bucko
// incLoaded : specifies what you might expect
//
objectHere *copyObjHereList(objectHere *srcObjHere, const char incLoaded)
{
objectHere *newObjHere, *prevObjHere = NULL, *headObjHere = NULL;
if (!srcObjHere) return NULL;
while (srcObjHere)
{
newObjHere = new objectHere;
if (!newObjHere)
{
cout << "\n\nERROR: copyObjHereList() - ran out of mem alloc'ing new "
<< " objectHere node. Aborting..\n\n";
return NULL;
}
newObjHere->Next = NULL;
if (!headObjHere) headObjHere = newObjHere;
if (prevObjHere) prevObjHere->Next = newObjHere;
prevObjHere = newObjHere;
// first, the easy stuff
memcpy(newObjHere, srcObjHere, sizeof(objectHere));
// now, the not quite as easy but still relatively simple stuff
newObjHere->objInside = copyObjHereList(srcObjHere->objInside, incLoaded);
if (incLoaded)
{
addEntity(ENTITY_OBJECT, newObjHere->objectNumb);
numbObjs++;
}
srcObjHere = srcObjHere->Next;
}
if (incLoaded) createPrompt(); // more efficient..
return headObjHere;
}
//
// checkEntireObjHereListForType :
// checks entire objectHere list for an objHere of type *objType
//
char checkEntireObjHereListForType(objectHere *objHereHead,
const dikuObject *objType)
{
objectHere *objHere = objHereHead;
while (objHere)
{
if (objHere->objectPtr == objType) return TRUE;
if (objHere->objInside)
{
if (checkEntireObjHereListForType(objHere->objInside, objType))
{
return TRUE;
}
}
objHere = objHere->Next;
}
return FALSE;
}
//
// checkForObjHeresofType : Checks for any objectHere nodes whereever they may
// show up (of a certain type..) TRUE if found..
//
char checkForObjHeresofType(const dikuObject *objType)
{
dikuRoom *room = roomHead;
editableListNode *edit = inventory;
objectHere *objHere;//, *objHere2;
mobHere *mobHere;
long i;
while (room)
{
objHere = room->objectHead;
while (objHere)
{
if (objHere->objectPtr == objType) return TRUE;
if (checkEntireObjHereListForType(objHere->objInside, objType))
return TRUE;
objHere = objHere->Next;
}
mobHere = room->mobHead;
while (mobHere)
{
if (checkEntireObjHereListForType(mobHere->objectHead, objType))
return TRUE;
/*
if (checkEntireObjHereListForType(mobHere->equipHead, objType))
return TRUE;
*/
for (i = WEAR_LOW; i <= WEAR_TRUEHIGH; i++)
if (checkEntireObjHereListForType(mobHere->equipment[i], objType))
return TRUE;
mobHere = mobHere->Next;
}
room = room->Next;
}
// check inventory
while (edit)
{
if ((edit->entityType == ENTITY_OBJECT) &&
(((objectHere *)(edit->entityPtr))->objectPtr == objType))
return TRUE;
edit = edit->Next;
}
return FALSE;
}
//
// scanObjHereListForLoadedContainer :
// Scans through a list of objectHeres and their objInside pointers
// for "loaded" containers (shit in them) of a certain vnum
//
char scanObjHereListForLoadedContainer(objectHere *objHere,
const ulong containNumb)
{
objectHere *obj = objHere;
while (obj)
{
if ((obj->objectNumb == containNumb) && obj->objInside) return TRUE;
if (scanObjHereListForLoadedContainer(obj->objInside, containNumb))
return TRUE;
obj = obj->Next;
}
return FALSE;
}
//
// checkForObjHeresWithLoadedContainer :
// Checks for any objectHere nodes with "loaded" containers of a
// certain object number - that is, containers with shit in them -
// returns TRUE if any are found
//
// containNumb : vnum of container to check for
//
char checkForObjHeresWithLoadedContainer(const ulong containNumb)
{
dikuRoom *room = roomHead;
objectHere *objHere;
mobHere *mobHere;
long i;
while (room)
{
objHere = room->objectHead;
while (objHere)
{
if (scanObjHereListForLoadedContainer(objHere, containNumb))
return TRUE;
objHere = objHere->Next;
}
mobHere = room->mobHead;
while (mobHere)
{
if (scanObjHereListForLoadedContainer(mobHere->objectHead, containNumb))
return TRUE;
for (i = WEAR_LOW; i <= WEAR_TRUEHIGH; i++)
if (scanObjHereListForLoadedContainer(mobHere->equipment[i],
containNumb))
return TRUE;
mobHere = mobHere->Next;
}
room = room->Next;
}
return FALSE;
}
//
// resetObjHereList : resets (renumbers) all obj heres in a list
//
void resetObjHereList(const long oldNumb, const long newNumb,
objectHere *objHead)
{
objectHere *objHere = objHead;
while (objHere)
{
if (objHere->objectNumb == oldNumb) objHere->objectNumb = newNumb;
if (objHere->objInside)
resetObjHereList(oldNumb, newNumb, objHere->objInside);
objHere = objHere->Next;
}
}
//
// resetAllObjHere : "Resets" (renumbers) all objectHere nodes in all dikuRoom nodes
// nodes in the list pointed to by *room
//
// oldNumb : see above
// newNumb : ditto
// *room : yep
//
void resetAllObjHere(const long oldNumb, const long newNumb, dikuRoom *room)
{
mobHere *mob;
long i;
if (oldNumb == newNumb) return;
while (room)
{
resetObjHereList(oldNumb, newNumb, room->objectHead);
mob = room->mobHead;
while (mob)
{
resetObjHereList(oldNumb, newNumb, mob->objectHead);
for (i = WEAR_LOW; i <= WEAR_TRUEHIGH; i++)
resetObjHereList(oldNumb, newNumb, mob->equipment[i]);
mob = mob->Next;
}
room = room->Next;
}
}
//
// addObjHeretoList
//
void addObjHeretoList(objectHere **objListHead, objectHere *objToAdd)
{
objectHere *obj;
if (!objToAdd)
{
_outtext("\nError in addObjHeretoList() - objToAdd is NULL.\n");
return;
}
if (!*objListHead) *objListHead = objToAdd;
else
{
obj = *objListHead;
while (obj && obj->Next)
{
obj = obj->Next;
}
obj->Next = objToAdd;
}
objToAdd->Next = NULL;
}
//
// objinInv : checks mob's carried list for a particular object type (by ptr)
//
objectHere *objinInv(mobHere *mob, const dikuObject *obj)
{
objectHere *objH;
if (!mob || !obj) return NULL;
objH = mob->objectHead;
while (objH)
{
if (objH->objectPtr == obj) return objH;
objH = objH->Next;
}
return NULL;
}
//
// objinInv : check's mob's carried list for a particular object type (by vnum)
//
objectHere *objinInv(mobHere *mob, const ulong objNumb)
{
objectHere *objH;
if (!mob) return NULL;
objH = mob->objectHead;
while (objH)
{
if (objH->objectNumb == objNumb) return objH;
objH = objH->Next;
}
return NULL;
}
//
// isObjTypeUsed : is a particular object type used? (in other words,
// is it loaded or used by a shop or quest)
//
char isObjTypeUsed(ulong numb)
{
dikuMob *mob = mobHead;
questQuest *qstq;
questItem *qsti;
ulong i;
if (getNumbEntities(ENTITY_OBJECT, numb, FALSE)) return TRUE;
// check quests and shops
while (mob)
{
if (mob->questPtr)
{
qstq = mob->questPtr->questHead;
while (qstq)
{
qsti = qstq->questPlayRecvHead;
while (qsti)
{
if ((qsti->itemType == QUEST_RITEM_OBJ) && (qsti->itemVal == numb))
{
return TRUE;
}
qsti = qsti->Next;
}
qstq = qstq->Next;
}
}
if (mob->shopPtr) // this code is semi-pointless, since it sets mobs' inv
{ // appropriately anyway when saving improperly set shops
for (i = 0; mob->shopPtr->producedItemList[i]; i++)
{
if (mob->shopPtr->producedItemList[i] == numb) return TRUE;
}
}
mob = mob->Next;
}
return FALSE;
}
//
// resetObjHEntityPointersByNumb
//
void resetObjHEntityPointersByNumb(objectHere *objH)
{
while (objH)
{
resetObjHEntityPointersByNumb(objH->objInside);
objH->objectPtr = findObj(objH->objectNumb);
objH = objH->Next;
}
}
| true |
13635bcba6eba9571d3c244f2198376d5553b440 | C++ | MIMFaisal/Codeforces | /266B.cpp | UTF-8 | 439 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
int i,n,t,j,l;
scanf("%d %d ",&n,&t);
char q[n+1];
gets(q);
l=strlen(q);
for(i=1;i<=t;i++)
{
for(j=1;j<l;j++)
{
if(q[j-1]=='B'&&q[j]=='G')
{
q[j-1]='G';
q[j]='B';
j++;
}
}
}
puts(q);
return 0;
}
| true |
ac14f95fcddf7e4fb7ccb70ccd2396db08012ca0 | C++ | EdwardDeaver/ControlMyLights | /OLD/Arduino/ArduinoColor/ArduinoColor.ino | UTF-8 | 3,301 | 3.328125 | 3 | [] | no_license | //https://learn.adafruit.com/rgb-led-strips/arduino-code
int Red,Green,Blue; // Red, Green, Blue value from the hex conversion
String color;
int FADESPEED = 30;
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3
void setup() {
pinMode(REDPIN, OUTPUT);
pinMode(GREENPIN, OUTPUT);
pinMode(BLUEPIN, OUTPUT);
// start serial port at 9600 bps:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
establishContact(); // send a byte to establish contact until receiver responds
}
void loop() {
/*
if (Serial.available() > 0) {
String Mdata = Serial.readString();
Serial.println(Mdata);
Serial.println(Mdata[0]);
}
*/
// if we get a valid byte, read analog ins:
if (Serial.available() > 0) {
String Message = Serial.readString();
// Serial.println(Message[0]);
// Serial.println(Message[1]);
// Serial.println(Message[2]);
// Serial.println(Message[3]);
if(Message[0] == '#'){
// Serial.println("red is ");
// Serial.println(Message);
color = Message.substring(1);
bool resultant = convertStringHextoRGB(color);
// Serial.println("green is ");
//Serial.println(Green);
//Serial.println("blue is ");
//Serial.println(Blue);
writeToRGB(Red, Green,Blue);
}
}
}
// Conversion from https://stackoverflow.com/questions/23576827/arduino-convert-a-string-hex-ffffff-into-3-int
bool convertStringHextoRGB(String HexString){
long number = (long) strtol( &color[0], NULL, 16);
Red = number >> 16;
Green = number >> 8 & 0xFF;
Blue = number & 0xFF;
// Serial.println("red is ");
// Serial.println(Red);
return true;
}
// Writes string data to serial port.
void writeToScreen (String data){
// get incoming byte:
int str_len = data.length() + 1;
char char_array[str_len];
data.toCharArray(char_array, str_len);
//for (int i = 0; i<str_len; i++){
// Serial.write(char_array[i]);
// }
//Serial.write("\n");
}
//
void establishContact() {
while (Serial.available() <= 0) {
Serial.println('1'); // send a capital 1
delay(300);
}
}
// Write data to the desired pin
void writeToRGB(int red, int green, int blue){
Serial.println(red);
Serial.println(green);
Serial.println(blue);
analogWrite(REDPIN, red);
analogWrite(GREENPIN, green);
analogWrite(BLUEPIN, blue);
}
void colorchangeexample(){
int r, g, b;
// fade from blue to violet
for (r = 0; r < 256; r++) {
analogWrite(REDPIN, r);
delay(FADESPEED);
}
// fade from violet to red
for (b = 255; b > 0; b--) {
analogWrite(BLUEPIN, b);
delay(FADESPEED);
}
// fade from red to yellow
for (g = 0; g < 256; g++) {
analogWrite(GREENPIN, g);
delay(FADESPEED);
}
// fade from yellow to green
for (r = 255; r > 0; r--) {
analogWrite(REDPIN, r);
delay(FADESPEED);
}
// fade from green to teal
for (b = 0; b < 256; b++) {
analogWrite(BLUEPIN, b);
delay(FADESPEED);
}
// fade from teal to blue
for (g = 255; g > 0; g--) {
analogWrite(GREENPIN, g);
delay(FADESPEED);
}
}
| true |
11d34ac332b0c25ba023c9e81278c864b91c7964 | C++ | dinhtuyen3011/cpp | /OOP Concepts/Resources/31_5_Applications_of_Pointers/Practice09.cpp | UTF-8 | 319 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void) {
char *str= "IMIC Technology";
char *pc = str;
cout<<str<<endl;
cout << str[0] <<' '<< *pc <<' '<<pc[3]<<"\n";
pc = pc + 3;
cout<<*pc<<endl;
cout <<*pc<<' '<< pc[2] <<' '<< pc[5];
return 0;
}
/* Output *//*
I I C
C Technology
C T h
*/
| true |
d1364e199eda82ce99665575b42f3866ffb159e6 | C++ | jayparekhjp/openCV-Facial-Recognition | /openCV/sources/samples/cpp/connected_components.cpp | UTF-8 | 2,102 | 2.859375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Mat img;
int threshval = 100;
static void on_trackbar(int, void*)
{
Mat bw = threshval < 128 ? (img < threshval) : (img > threshval);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( bw, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
Mat dst = Mat::zeros(img.size(), CV_8UC3);
if( !contours.empty() && !hierarchy.empty() )
{
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
Scalar color( (rand()&255), (rand()&255), (rand()&255) );
drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
}
}
imshow( "Connected Components", dst );
}
static void help()
{
cout << "\n This program demonstrates connected components and use of the trackbar\n"
"Usage: \n"
" ./connected_components <image(stuff.jpg as default)>\n"
"The image is converted to grayscale and displayed, another image has a trackbar\n"
"that controls thresholding and thereby the extracted contours which are drawn in color\n";
}
const char* keys =
{
"{1| |stuff.jpg|image for converting to a grayscale}"
};
int main( int argc, const char** argv )
{
help();
CommandLineParser parser(argc, argv, keys);
string inputImage = parser.get<string>("1");
img = imread(inputImage.c_str(), 0);
if(img.empty())
{
cout << "Could not read input image file: " << inputImage << endl;
return -1;
}
namedWindow( "Image", 1 );
imshow( "Image", img );
namedWindow( "Connected Components", 1 );
createTrackbar( "Threshold", "Connected Components", &threshval, 255, on_trackbar );
on_trackbar(threshval, 0);
waitKey(0);
return 0;
}
| true |
9c136f0b97d895e7b8ed6f229f0f08ed40ff91b0 | C++ | fredfeng/PDB | /branches/v0.1.3-scons/DBServerBackEnd/headers/BackEndNewStorageLocationWork.h | UTF-8 | 698 | 2.625 | 3 | [] | no_license |
#ifndef BACKEND_NEW_STORAGE_WORK_H
#define BACKEND_NEW_STORAGE_WORK_H
#include "PDBCommWork.h"
#include "PDBBuzzer.h"
#include "PDBWork.h"
#include "SimplePDB.h"
#include <string>
using namespace std;
// tells the database to use a new storage location
class BackEndNewStorageLocationWork : public PDBCommWork {
public:
// specify the database object and the file to open
BackEndNewStorageLocationWork (SimplePDBPtr openMeIn);
// do the actual work
void execute (PDBBuzzerPtr callerBuzzer) override;
// clone this guy
PDBCommWorkPtr clone () override;
private:
// the database that we are tasked with opening
SimplePDBPtr openMe;
// the file to open
string fName;
};
#endif
| true |
761638fbc11c53ee162dac8e8ad289cf8885ca5c | C++ | Cowerling/CRESTInCPP | /Base/Cell.h | UTF-8 | 2,119 | 3.03125 | 3 | [] | no_license | //
// Created by cowerling on 17-4-18.
//
#ifndef CREST_CELL_H
#define CREST_CELL_H
#include "Tier.h"
#include "StatusResultType.h"
namespace CREST {
class Cell {
public:
Cell();
virtual ~Cell();
void RunoffGenerationProcess(float precipitation, float potential_evaporation, float max_water_capacity, float evaporation_multiplier, float impervious_ratio,
float exponent, float hydra_conductivity);
inline int GetX() const;
void SetX(int x);
inline int GetY() const;
void SetY(int y);
inline float GetFlowTime() const;
void SetFlowTime(float flow_time);
inline const Cell* GetNextCell() const;
inline Cell* GetNextCell();
void SetNextCell(Cell *next_cell);
inline Tier& GetSurfaceTier();
inline Tier& GetGroundTier();
inline float GetSoilWater() const;
void SetSoilWater(float soil_water);
inline float GetRunoff() const;
void SetRunoff(float runoff);
float GetStatusResult(StatusResultType type) const;
protected:
Tier m_surface_tier, m_ground_tier;
float m_actual_evaporation;
float m_soil_water; //refers to the initial value of soil water.
int m_x, m_y;
float m_flow_time;
float m_runoff;
Cell *m_next_cell;
};
inline int Cell::GetX() const
{
return m_x;
}
inline int Cell::GetY() const
{
return m_y;
}
inline float Cell::GetFlowTime() const
{
return m_flow_time;
}
inline const Cell* Cell::GetNextCell() const
{
return m_next_cell;
}
inline Cell* Cell::GetNextCell()
{
return m_next_cell;
}
inline Tier& Cell::GetSurfaceTier()
{
return m_surface_tier;
}
inline Tier& Cell::GetGroundTier()
{
return m_ground_tier;
}
inline float Cell::GetSoilWater() const {
return m_soil_water;
}
inline float Cell::GetRunoff() const
{
return m_runoff;
}
}
#endif //CREST_CELL_H
| true |
a23fb2a69fe8caaebb697512d1eda89ed551c521 | C++ | green-fox-academy/Amberhaart | /week-03/day-04/printParams/main.cpp | UTF-8 | 1,197 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <string>
void printParams (std:: string x);
void printParams (std:: string x, std:: string y);
void printParams (std:: string x, std:: string y, std:: string z);
void printParams (std:: string x, std:: string y, std:: string z, std:: string w);
int main(int argc, char* args[]) {
// - Create a function called `printParams`
// which prints the input String parameters
// - It can have any number of parameters
// Examples
// printParams("first")
// printParams("first", "second")
// printParams("first", "second", "third", "fourh")
// ...
std::string a;
std::string b;
std::string c;
std::string d;
printParams(a);
printParams(a, b);
printParams(a, b, c);
printParams(a, b, c, d);
return 0;
}
void printParams (std:: string x){
std::cout << "I" << std::endl;
}
void printParams (std:: string x, std:: string y){
std::cout << "will" << std::endl;
}
void printParams (std:: string x, std:: string y, std:: string z){
std::cout << "not" << std::endl;
}
void printParams (std:: string x, std:: string y, std:: string z, std:: string w){
std::cout << "break" << std::endl;
} | true |
a49e221d702866a2ba5312d77c5690033d1d502d | C++ | MregXN/Leetcode | /Array/849.cpp | UTF-8 | 2,394 | 3.671875 | 4 | [] | no_license | // 在一排座位( seats)中,1 代表有人坐在座位上,0 代表座位上是空的。
// 至少有一个空座位,且至少有一人坐在座位上。
// 亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。
// 返回他到离他最近的人的最大距离。
// 示例 1:
// 输入:[1,0,0,0,1,0,1]
// 输出:2
// 解释:
// 如果亚历克斯坐在第二个空位(seats[2])上,他到离他最近的人的距离为 2 。
// 如果亚历克斯坐在其它任何一个空位上,他到离他最近的人的距离为 1 。
// 因此,他到离他最近的人的最大距离是 2 。
// 示例 2:
// 输入:[1,0,0,0]
// 输出:3
// 解释:
// 如果亚历克斯坐在最后一个座位上,他离最近的人有 3 个座位远。
// 这是可能的最大距离,所以答案是 3 。
// 提示:
// 1 <= seats.length <= 20000
// seats 中只含有 0 和 1,至少有一个 0,且至少有一个 1。
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#define max(a, b) (((a) > (b)) ? (a) : (b))
using namespace std;
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int left = 0 ;
int right = 0 ;
int last1 = -1 ;
int distance = 0;
int n = seats.size();
for(int i = 0 ; i < n;i++)
{
if(seats[i])
{
if( last1 == -1) left = i;
else if((i - last1) > distance ) distance = i - last1;
last1 = i;
}
}
right = n-1 - last1;
distance = floor(distance/2);
int max = (left > right) ? (left):(right) ;
max = (max > distance) ? (max):(distance) ;
return max;
}
};
int main(){
string input;
Solution solution;
vector<int> seats;
cout << "please input " << endl;
getline(cin, input ,'\n');
// cout << input << endl;
for(int i = input.find('['); i < input.find(']') ;i++ )
{
if(input[i] <= '9' && input[i] >= '0' )
{
seats.push_back(input[i] - 48);
}
}
//for(int i =0 ; i < seats.size();i++) cout << seats[i];
cout << solution.maxDistToClosest(seats) << endl;
return 0 ;
} | true |
c49fc531a03da7234c5ef2e3303896ed07e30a9a | C++ | priyanto14/tugas-dasar-pemrograman | /Latihan 1.CPP | UTF-8 | 348 | 2.625 | 3 | [] | no_license | #include <stdio.h>
#include <conio.h>
main() {
int nilai,tugas;
printf("Masukan Sebuah Nilai:"); scanf("%d",&nilai);
printf("Masukan Nilai Tugas:"); scanf("%d",&tugas);
if(nilai>80)
printf("Anak Baik \n");
else if(nilai>70)
printf("Bagus \n");
else if(nilai>60)
printf("Cemen \n");
else
printf("Dodol \n");
getch();
}
| true |
951a2e8ac2e920507199d3de03c8f15fa90f4896 | C++ | andrefmrocha/MIEIC_18_19_AEDA | /src/Company.h | UTF-8 | 7,006 | 3.3125 | 3 | [] | no_license | /*
* Company.h
*
* Created on: 30/10/2018
* Author: joaomartins
*/
#ifndef SRC_COMPANY_H_
#define SRC_COMPANY_H_
#include "Calendar.h"
#include "Court.h"
#include "Date.h"
/**
* The company itself, operation all of the rest
*/
class Company
{
private:
std::vector<Court> tennisCourts; /**< vector with all the Courts */
std::vector<User> users; /**< vector with all the Users */
std::vector<Teacher> teachers; /**< vector with all the Users */
double cardValue;
int year; /**< current Year */
Date date; /**< Current date*/
public:
/**
*
* @brief Class Constructor
*/
Company() {};
/**
* @brief Class constructor
* @param d - current date
*/
Company(double cardValue, Date d);
/**
* @brief getter of Maximum of users in all courts
* @return maximum of users in all courts
*/
int getMaxUser()const;
/**
* @brief Creating a new Court
*/
void createCourt();
//tested
/**
* @brief Getter of the current Courts.
* @return vector of Courts
*/
std::vector<Court> getCourts();
//tested
/**
* @brief Getter of the current Users.
* @return vector of Users
*/
std::vector <User> getUsers();
//tested
/**
* @brief Getter of the current Teachers.
* @return vector of Teachers
*/
std::vector<Teacher> getTeachers();
/**
* @brief Getter of a specific User
* @param userName - name of the User
* @return a reference to the user
*/
User& getUser(std::string userName);
/**
* @brief Getter of a specific User
* @param userName - name of the User
* @return a reference to the user
*/
Teacher& getTeacher(std::string teacherName);
/**
* Reserving the Court, User and Teacher for a new Lesson.
* @param month - the month of the lesson
* @param day - the day of the lesson
* @param startingHour - the starting Hour for it
* @param userName - the name of the User
* @param teacherName - the name of the Teacher
* @return if it was successful created
*/
bool makeLesson(int month,int day,double startingHour,std::string userName,std::string teacherName);
//tested
/**
* @brief Reserving the Court, User and Teacher for a new Reservation.
* @param month - the month of the lesson
* @param day - the day of the lesson
* @param startingHour - the starting Hour for it
* @param duration - the duration it
* @param username - the name of the User
* @return if it was successful created
*/
bool makeFree(int month,int day, double startingHour,int duration, std::string username);
//tested
/**
* @brief Register a new User to the system.
* @param name - the name of the user
* @param age - the age of the user
* @param isGold - if he wants to have the Gold card or not
* @param gender - the gender of the User
* @return if the user was succesfully created
*/
bool registerUser(std::string name, int age,bool isGold,std::string gender);
//tested
/**
* @brief - Register a new Teacher to the system.
* @param teacherName - the name of the Teacher
* @param age - the age of the Teacher
* @param gender - the gender of the Teacher
* @return if the Teacher was succesfully created
*/
bool registerTeacher(std::string teacherName,int age,std::string gender);
/**
* @brief Make a Report for a specific user.
* @param month - month it relates to
* @param userName - the name of the user
* @param teacherName - the name of the teacher
* @return if if was made sucessfuly
*/
bool makeUserReport(int month,std::string userName,std::string teacherName);
//partially tested, needs to verify that invoice is saved properly
/**
* @brief Make an Invoice for a specific user.
* @param userName - month it relates to
* @param month - the name of the user
* @return if if was made sucessfuly
*/
//partially tested, needs to verify that invoice is saved properly
bool makeUserInvoice(std::string userName, int month);
/**
* @brief Method to show a specific Report.
* @param name - name of the User
* @param month - month they want
* @return if it was properly shown
*/
//needs reports to be properly saved to be tested
bool showReport(std::string name, int month);
/**
* @brief Method to show a specific Invoice.
* @param name - name of the User
* @param month - month they want
* @return if it was properly shown
*/
//needs invoices to be prpperly saved to be tested
bool showInvoice(std::string name,int month);
//to implement
/**
* @brief Store in the information of the Company to a file.
* @param outfile - the file to write information
* @param identation - current indentation
*/
void storeInfo(std::ofstream &outfile,int identation);
/**
* @brief To indent the file
* @param outfile - where to write
* @param indentation - current indentation
*/
void indentation(std::ofstream &outfile,int indentation);
/**
* @brief Reads the company information of a file
* @param infile
*/
void readInfo(std::ifstream &infile);
/**
* @brief The operator to go through a day and all its necessary situations
* @return the company itself
*/
Company operator++();
/**
* @brief shows all Users
*/
void showUsers();
/**
* @brief shows all Teachers
*/
void showTeachers();
/**
* @brief shows all Courts
*/
void showCourts();
/**
* @brief show a specific User
* @param name - name of the User
*/
void showUser(std::string name);
/**
* @brief show a specific User
* @param name - name of the User
*/
void showTeacher(std::string teacher);
/**
* @brief Show the Reservations of a specific user
* @param name - Name of the User
*/
void showUserReservations (std::string name);
/**
* @brief Shows the lessons of the Teacher
* @param teacher - name of the Teacher
*/
void showTeacherLessons (std::string teacher);
void showDate();
};
/**
* When a user does not exist
*/
class NoUserRegistered
{
private:
std::string name;
public:
NoUserRegistered(std::string name) { this->name=name;}
std::string what()const;
};
/**
* When a Teacher does not exist
*/
class NoTeacherRegistered
{
private:
std::string name;
public:
NoTeacherRegistered(std::string name) {this->name = name;}
std::string what()const;
};
/**
* When the age is not valid
*/
class InvalidAge
{
private:
int age;
public:
InvalidAge(int age) { this->age=age;}
std::string what()const;
};
/**
* When that name is already in the system
*/
class AlreadyRegisteredUser
{
private:
std::string name;
public:
AlreadyRegisteredUser(std::string name) { this->name=name;}
std::string what()const;
};
/**
* When that name is already in the system
*/
class AlreadyRegisteredTeacher
{
private:
std::string name;
public:
AlreadyRegisteredTeacher(std::string name) { this->name=name;}
std::string what()const;
};
class InvalidDate
{
int month;
int day;
public:
InvalidDate(int day, int month) { this->day = day, this->month = month;}
std::string what() const;
};
#endif /* SRC_COMPANY_H_ */
| true |
91a10b631f719959e2d582d267d6a91222210b8e | C++ | derekniess/3D-Physics-Engine-Framework | /ResourceManager.h | UTF-8 | 1,536 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include <utility>
#include <vector>
#include <memory>
#include "Observer.h"
#include "Resource.h"
#include "DebugVertex.h"
#include "Reflection.h"
#include "Texture.h"
class Renderer;
class Mesh;
class Engine;
class GameObject;
enum AccessType
{
READ,
WRITE,
APPEND,
AccessTypeEnd
};
struct TextFileData
{
char * pData;
unsigned int Size;
TextFileData() :
pData(nullptr),
Size(0)
{}
};
class ResourceManager : public Observer
{
private:
std::vector<std::unique_ptr<Texture>> TextureList;
/*------------------------------- ENGINE REFERENCE -------------------------------*/
Engine & EngineHandle;
// Map to all types that are registered with the reflection system
TypeDataBase TypeDB;
public:
ResourceManager(Engine & aEngine) :EngineHandle(aEngine) {};
virtual ~ResourceManager() {};
inline Texture * GetTexture(int aTextureID) const { return TextureList[aTextureID].get(); }
TextFileData & LoadTextFile(const char* aFileName, AccessType aAccessType) const;
Texture * LoadTexture(int aWidth, int aHeight, char * aFilename);
// Uses Assimp importer to read mesh data from file and returns it in a Mesh component
Mesh * ImportMesh(const char * aFilename);
// Uses Assimp importer to get mesh positions from file and returns it in a DebugVertex array
std::vector<DebugVertex> ImportColliderData(std::string & aFilename);
void CreateArchteypeFromGameObject(GameObject * aGameObject, const char * aArchetypeName);
virtual void OnNotify(Event * aEvent) override;
}; | true |
87cf00e776af66f5e32f4c3cf8a8c755d36e4a2f | C++ | r00nster/sclx_c7042 | /sclx_in.h | UTF-8 | 1,424 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef SCLX_IN_H_
#define SCLX_IN_H_
#include <tasks/serial/term.h>
#include <cstring>
#include "crc.h"
class sclx_in {
public:
struct __attribute__((__packed__)) packet_t {
std::uint8_t status;
std::uint8_t handset[6];
std::uint8_t aux_current;
std::uint8_t carid_sf;
std::uint32_t game_time_sf;
std::uint8_t button_status;
std::uint8_t crc;
};
sclx_in() {
m_data_p = reinterpret_cast<char*>(&m_packet.status);
m_size = sizeof(m_packet);
std::memset(m_data_p, 0, m_size);
}
inline void read(tasks::serial::term& term) {
std::streamsize bytes = term.read(m_data_p + m_read, m_size - m_read);
if (bytes >= 0) {
m_read += bytes;
} else {
throw tasks::tasks_exception(tasks::tasks_error::UNSET, "read failed: " + std::string(std::strerror(errno)),
errno);
}
}
inline bool done() { return m_read == m_size; }
inline bool valid() const { return m_packet.crc == crc8(&m_packet.status, m_size - 1); }
inline void reset() { m_read = 0; }
inline packet_t& packet() { return m_packet; }
inline std::streamsize size() const { return m_size; }
private:
packet_t m_packet;
char* m_data_p;
std::streamsize m_size = sizeof(m_packet);
std::streamsize m_read = 0;
};
#endif // SCLX_IN_H_
| true |
7128bc60f7869ce4ec537a2c7e93d8260eca2fee | C++ | alanrpfeil/Computer-Graphics | /sig program/include/sigkin/kn_joint_st.h | UTF-8 | 4,669 | 2.515625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | /*=======================================================================
Copyright (c) 2018-2019 Marcelo Kallmann.
This software is distributed under the Apache License, Version 2.0.
All copies must contain the full copyright notice licence.txt located
at the base folder of the distribution.
=======================================================================*/
# ifndef KN_JOINT_ST
# define KN_JOINT_ST
# include <sig/gs_quat.h>
class KnJointRot;
/*! Implements the swing and twist decomposition of a rotation, which is
suitable to define meaningfull swing limits with the use of an ellipse.
The swing is parameterized in the axis-angle format, in the XY plane.
The twist is then defined as a rotation around Z axis. */
class KnJointST
{ private :
float _sx, _sy; // swing values X Y in axis-angle format
float _ex, _ey; // ellipse radius to limit swing
float _twist; // twist is a rotation around Z
float _lolim, _uplim; // twist min/max limits
gscbool _limit_twist; // if twist limits are active or not
KnJointRot* _jq;
public :
/*! Constructor calls init() */
KnJointST ( KnJointRot* jq );
/*! Init swing to (0,0), limits to (PI,PI), and twist frozen to 0. */
void init ();
/*! Init parameters with same values as in st; only _jq pointer is not chnaged. */
void init ( const KnJointST* st );
/*! Returns true if swing (x,y) is inside the limits, and false otherwise.
(if (x/ellipsex)^2 + (y/ellipsey)^2 - 1 <=0 then true is returned) */
bool swing_inlimits ( float x, float y );
/*! Set swing values, which are bounded to the ellipse limits before inserted.
The local matrix of the associated joint will be set as changed only
if a different value than the actual one is set.
Note: (x,y) represents the rotation axis, and ||(x,y)|| is the rotation angle */
void swing ( float x, float y );
/*! Change the swing x value and calls swing(x,y) method to enforce limits */
void swingx ( float x ) { swing(x,_sy); }
/*! Change the swing y value and calls swing(x,y) method to enforce limits */
void swingy ( float y ) { swing(_sx,y); }
/*! Returns the x component of the current swing */
float swingx ();
/*! Returns the y component of the current swing */
float swingy ();
/*! Change the x/y radius of the limiting ellipse, ensuring swing remains valid.
Given parameters are automatically bounded into (0,pi] */
void ellipse ( float rx, float ry );
/*! Get the x radius of the limiting ellipse, which is in (0,pi] */
float ellipsex () const { return _ex; }
/*! Get the y radius of the limiting ellipse, which is in (0,pi] */
float ellipsey () const { return _ey; }
/*! Set the twist value. In case twist limits are activated, the value is
bounded to the limits before inserted. Changes only if a new value is set. */
void twist ( float t );
/*! Returns the current twist value */
float twist ();
/*! Set twist limits and ensures twist value remains valid if limits are active */
void twist_limits ( float min, float max );
/*! Returns the min twist limit value */
float twist_lolim () const { return _lolim; }
/*! Returns the min twist limit value */
float twist_uplim () const { return _uplim; }
/*! Activates or deactivates twist limits */
void twist_limits ( bool b ) { _limit_twist = b? 1:0; }
/*! Returns the activation state of twist limits */
bool twist_limits () { return _limit_twist==1; }
/*! Returns true if the given value respects current twist limits and false otherwise */
bool twist_inlimits ( float t ) const
{ return _lolim<=t && t<=_uplim; }
/*! Activates limits and set min and max equal to the current twist value */
void twist_freeze ();
/*! Returns true if the twist value is frozen, i.e if it cannot receive new values.
If the minimum limit is equal to the maximum limit, and limits are activated,
then the twist is considered frozen. */
bool twist_frozen () const;
/*! Returns random swing values, limited by the current ellipse radius */
void get_random_swing ( float& x, float& y ) const;
/*! Returns random twist values, limited if twist limits are activated */
float get_random_twist () const;
/*! Convert and put in the given quaternion the rotation equal to: R=Rtwist*Rswing */
void get ( GsQuat& q ) const;
/*! Convert the given quaternion into the correct swing-twist values and set
this KnJointST with the converted values */
void set ( const GsQuat& q );
};
//==================================== End of File ===========================================
# endif // KN_JOINT_ST
| true |
53f6867fcf0b1c6788f989c8c82b4a337a26eb7d | C++ | longlongwaytogo/Learning.test | /C++/c11/thread.cpp | UTF-8 | 329 | 2.84375 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include <atomic>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
int g_int = 1;
void thread_task()
{
std::cout<< "hello thread :" << g_int++ << std::endl;
}
int main ()
{
for(int i = 0; i < 10; ++i)
{
std::thread t(thread_task);
t.join();
}
return 0;
} | true |
9e95ae3fdb8f370b2bdb644ed65a1db30d3ef754 | C++ | amartin11/robot-code-public | /muan/wpilib/pcm_wrapper.h | UTF-8 | 1,577 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef MUAN_WPILIB_PCM_WRAPPER_H_
#define MUAN_WPILIB_PCM_WRAPPER_H_
#include <array>
#include <atomic>
#include <cstdint>
#include "WPILib.h"
namespace muan {
namespace wpilib {
class PcmWrapper {
public:
explicit PcmWrapper(int32_t module);
PcmWrapper();
~PcmWrapper();
// Create a solenoid on the specified channel.
bool CreateSolenoid(uint8_t port);
void CreateDoubleSolenoid(uint8_t channel_forward, uint8_t channel_reverse);
// Writes to the specified solenoid port. This is realtime and just sets
// values that will be written in the CAN thread. These functions will die if
// the corresponding channel is not initialized.
void WriteSolenoid(uint8_t channel, bool on);
void WriteDoubleSolenoid(uint8_t channel_forward, uint8_t channel_reverse,
DoubleSolenoid::Value value);
private:
friend class CanWrapper;
// Flushes the current values to the CAN bus. This function is not realtime
// and should only be called from the CAN thread. It's private so it can only
// be called by friend classes, like CanWrapper.
void Flush();
// Make sure the port is initialized, and die if it is not
void CheckPortInitialized(uint8_t port);
void SetChannel(uint8_t channel, bool on);
// Bitmasks of the initialized channels as well as the current values of each
// solenoid
std::atomic<uint8_t> current_values_{0};
// Handles to the solenoids
std::array<HAL_SolenoidHandle, 8> handles_;
int32_t module_;
};
} // namespace wpilib
} // namespace muan
#endif // MUAN_WPILIB_PCM_WRAPPER_H_
| true |
dc5dd8d0226cc4a83989b1c3f32ac3c2de43d02e | C++ | dwmkFD/AtCoderSubmit | /ProconLibrary/SuccinctBitVector.cpp | SHIFT_JIS | 5,576 | 2.6875 | 3 | [] | no_license | template<typename T = uint64_t> constexpr T NOTFOUND = 0xffffffffffffffffLLU;
template<typename T = uint64_t> struct SuccinctBitVector {
public:
explicit SuccinctBitVector(const T n) : size(n) {
const T s = (n + blockBitNum - 1) / blockBitNum + 1; // ceil(n, blockSize)
this->B.assign(s, 0);
this->L.assign(n / LEVEL_L + 1, 0);
this->S.assign(n / LEVEL_S + 1, 0);
}
// B[pos] = bit
void setBit(const T bit, const T pos){
const T blockPos = pos / blockBitNum;
const T offset = pos % blockBitNum;
if (bit == 1) { B.at(blockPos) |= (1LLU << offset); }
else { B.at(blockPos) &= (~(1LLU << offset)); }
}
// B[pos]
T access(const T pos) {
const T blockPos = pos / blockBitNum;
const T offset = pos % blockBitNum;
return ((B.at(blockPos) >> offset) & 1);
}
void build() {
T num = 0;
for (T i = 0; i <= size; i++){
if (i % LEVEL_L == 0) {
L.at(i / LEVEL_L) = num;
}
if (i % LEVEL_S == 0) {
S.at(i / LEVEL_S) = num - L.at(i / LEVEL_L);
}
if (i != size and i % blockBitNum == 0) {
num += popcnt(this->B.at(i / blockBitNum));
}
}
this-> numOne = num;
}
// B[0, pos)bit̐
T rank(const T bit, const T pos) {
if (bit) {
return L[pos / LEVEL_L] + S[pos / LEVEL_S] + popCount(B[pos / blockBitNum] & ((1 << (pos % blockBitNum)) - 1));
}
else {
return pos - rank(1, pos);
}
}
// rankԖڂbiẗʒu + 1(rank1-origin)
T select(const T bit, const T rank) {
if (bit == 0 and rank > this->size - this-> numOne) { return NOTFOUND<T>; }
if (bit == 1 and rank > this-> numOne) { return NOTFOUND<T>; }
// ubNL
T large_idx = 0;
{
T left = 0;
T right = L.size();
while (right - left > 1) {
T mid = (left + right) / 2;
T r = L.at(mid);
r = (bit) ? r : mid * LEVEL_L - L.at(mid);
if (r < rank) {
left = mid;
large_idx = mid;
} else {
right = mid;
}
}
}
// ubNS
T small_idx = (large_idx * LEVEL_L) / LEVEL_S;
{
T left = (large_idx * LEVEL_L) / LEVEL_S;
T right = std::min(((large_idx + 1) * LEVEL_L) / LEVEL_S, (T)S.size());
while (right - left > 1) {
T mid = (left + right) / 2;
T r = L.at(large_idx) + S.at(mid);
r = (bit) ? r :mid * LEVEL_S - r;
if (r < rank) {
left = mid;
small_idx = mid;
} else {
right = mid;
}
}
}
// BubNPʂŏԂɒT
T rank_pos = 0;
{
const T begin_block_idx = (small_idx * LEVEL_S) / blockBitNum;
T total_bit = L.at(large_idx) + S.at(small_idx);
if (bit == 0) {
total_bit = small_idx * LEVEL_S - total_bit;
}
for (T i = 0;; ++i) {
T b = popCount(B.at(begin_block_idx + i));
if (bit == 0) {
b = blockBitNum - b;
}
if (total_bit + b >= rank) {
T block = (bit) ? B.at(begin_block_idx + i) : ~B.at(begin_block_idx + i);
rank_pos = (begin_block_idx + i) * blockBitNum + selectInBlock(block, rank - total_bit);
break;
}
total_bit += b;
}
}
return rank_pos + 1;
}
T getNumOne() const {
return numOne;
}
void debug() {
std::cout << "LEVEL_L(" << L.size() << ")" << std::endl;
for (T i = 0 ; i < L.size(); ++i) {
std::cout << L.at(i) << ", ";
}
std::cout << std::endl;
std::cout << "LEVEL_S(" << S.size() << ")" << std::endl;
for (T i = 0 ; i < S.size(); ++i) {
std::cout << S.at(i) << ", ";
}
std::cout << std::endl;
}
private:
// popcnt __builtin_popcountll gp
T selectInBlock( T x, T rank ) {
T x1 = x - ( ( x & 0xAAAAAAAAAAAAAAAALLU ) >> 1 );
T x2 = ( x1 & 0x3333333333333333LLU ) + ( ( x1 >> 2 ) & 0x3333333333333333LLU );
T x3 = ( x2 + ( x2 >> 4 ) ) & 0x0F0F0F0F0F0F0F0FLLU;
T pos = 0;
for ( ;; pos += 8 ) {
T rank_next = ( x3 >> pos ) & 0xFFLLU;
if ( rank <= rank_next ) break;
rank -= rank_next;
}
T v2 = ( x2 >> pos ) & 0xFLLU;
if ( rank > v2 ) {
rank -= v2;
pos += 4;
}
T v1 = ( x1 >> pos ) & 0x3LLU;
if ( rank > v1 ) {
rank -= v1;
pos += 2;
}
T v0 = ( x >> pos ) & 0x1LLU;
if ( v0 < rank ) {
rank -= v0;
pos += 1;
}
return pos;
}
const T size; // rbgxNg̃TCY
static const T blockBitNum = 16;
static const T LEVEL_L = 512;
static const T LEVEL_S = 16;
vector<T> L; // ubN
vector<T> S; // ubN
vector<T> B; // rbgxNg
T numOne = 0; // 1bit̐
};
| true |
8fd829ff00e1fe91343ad9c7b6d4f389cf7f0ec3 | C++ | Tmliu06/libdex | /src/insttype.cpp | UTF-8 | 38,953 | 2.5625 | 3 | [] | no_license | #include "insttype.h"
namespace {
enum Format {
op00,
opAA,
opBA,
op00AAAA,
opAABBBB,
opAACCBB,
opBACCCC,
op00AAAAAAAA,
op00AAAABBBB,
opAABBBBBBBB,
opAABBBBCCCC,
opAGBBBBDCFE,
opAABBBBCCCCHHHH,
opAGBBBBDCFEHHHH,
opAABBBBBBBBBBBBBBBB,
_10t,
_20t,
_21t,
_22t,
_30t,
};
uint64_t _b(const uint8_t * d, int n) { return (uint64_t) d[n] << (n * 8); }
uint64_t read_l(const uint8_t * d) { return d[0] & 0x0f; }
uint64_t read_h(const uint8_t * d) { return d[0] >> 4; }
uint16_t read_2(const uint8_t * d) { return d[0] + _b(d, 1); }
uint32_t read_4(const uint8_t * d) { return d[0] + _b(d, 1) + _b(d, 2) + _b(d, 3); }
uint64_t read_8(const uint8_t * d) { return d[0] + _b(d, 1) + _b(d, 2) + _b(d, 3) + _b(d, 4) + _b(d, 5) + _b(d, 6) + _b(d, 7); }
struct Getter_op00 : public InstType::Getter {
virtual int length() const override { return 2; }
};
struct Getter_opAA : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual int length() const override { return 2; }
};
struct Getter_10t : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return (int8_t) data[1]; }
virtual int length() const override { return 2; }
};
struct Getter_opBA : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_l(data + 1); }
virtual uint64_t b(const uint8_t * data) const override { return read_h(data + 1); }
virtual int length() const override { return 2; }
};
struct Getter_op00AAAA : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_2(data + 2); }
virtual int length() const override { return 4; }
};
struct Getter_20t : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return (int16_t) read_2(data + 2); }
virtual int length() const override { return 4; }
};
struct Getter_opAABBBB : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual uint64_t b(const uint8_t * data) const override { return read_2(data + 2); }
virtual int length() const override { return 4; }
};
struct Getter_21t : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual uint64_t b(const uint8_t * data) const override { return (int16_t) read_2(data + 2); }
virtual int length() const override { return 4; }
};
struct Getter_opAACCBB : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual uint64_t b(const uint8_t * data) const override { return data[3]; }
virtual uint64_t c(const uint8_t * data) const override { return data[2]; }
virtual int length() const override { return 4; }
};
struct Getter_opBACCCC : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_l(data + 1); }
virtual uint64_t b(const uint8_t * data) const override { return read_h(data + 1); }
virtual uint64_t c(const uint8_t * data) const override { return read_2(data + 2); }
virtual int length() const override { return 4; }
};
struct Getter_22t : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_l(data + 1); }
virtual uint64_t b(const uint8_t * data) const override { return read_h(data + 1); }
virtual uint64_t c(const uint8_t * data) const override { return (int16_t) read_2(data + 2); }
virtual int length() const override { return 4; }
};
struct Getter_op00AAAAAAAA : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_4(data + 2); }
virtual int length() const override { return 6; }
};
struct Getter_30t : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return (int32_t) read_4(data + 2); }
virtual int length() const override { return 6; }
};
struct Getter_op00AAAABBBB : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_2(data + 2); }
virtual uint64_t b(const uint8_t * data) const override { return read_2(data + 4); }
virtual int length() const override { return 6; }
};
struct Getter_opAABBBBBBBB : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual uint64_t b(const uint8_t * data) const override { return read_4(data + 2); }
virtual int length() const override { return 6; }
};
struct Getter_opAABBBBCCCC : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual uint64_t b(const uint8_t * data) const override { return read_2(data + 2); }
virtual uint64_t c(const uint8_t * data) const override { return read_2(data + 4); }
virtual int length() const override { return 6; }
};
struct Getter_opAGBBBBDCFE : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_h(data + 1); }
virtual uint64_t b(const uint8_t * data) const override { return read_2(data + 2); }
virtual uint64_t c(const uint8_t * data) const override { return read_l(data + 4); }
virtual uint64_t d(const uint8_t * data) const override { return read_h(data + 4); }
virtual uint64_t e(const uint8_t * data) const override { return read_l(data + 5); }
virtual uint64_t f(const uint8_t * data) const override { return read_h(data + 5); }
virtual uint64_t g(const uint8_t * data) const override { return read_l(data + 1); }
virtual int length() const override { return 6; }
};
struct Getter_opAABBBBCCCCHHHH : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual uint64_t b(const uint8_t * data) const override { return read_2(data + 2); }
virtual uint64_t c(const uint8_t * data) const override { return read_2(data + 4); }
virtual uint64_t h(const uint8_t * data) const override { return read_2(data + 6); }
virtual int length() const override { return 8; }
};
struct Getter_opAGBBBBDCFEHHHH : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return read_h(data + 1); }
virtual uint64_t b(const uint8_t * data) const override { return read_2(data + 2); }
virtual uint64_t c(const uint8_t * data) const override { return read_l(data + 4); }
virtual uint64_t d(const uint8_t * data) const override { return read_h(data + 4); }
virtual uint64_t e(const uint8_t * data) const override { return read_l(data + 5); }
virtual uint64_t f(const uint8_t * data) const override { return read_h(data + 5); }
virtual uint64_t g(const uint8_t * data) const override { return read_l(data + 1); }
virtual uint64_t h(const uint8_t * data) const override { return read_2(data + 6); }
virtual int length() const override { return 8; }
};
struct Getter_opAABBBBBBBBBBBBBBBB : public InstType::Getter {
virtual uint64_t a(const uint8_t * data) const override { return data[1]; }
virtual uint64_t b(const uint8_t * data) const override { return read_8(data + 2); }
virtual int length() const override { return 10; }
};
}
const InstType::Getter * InstType::getters[] = {
[op00] = new Getter_op00(),
[opAA] = new Getter_opAA(),
[opBA] = new Getter_opBA(),
[op00AAAA] = new Getter_op00AAAA(),
[opAABBBB] = new Getter_opAABBBB(),
[opAACCBB] = new Getter_opAACCBB(),
[opBACCCC] = new Getter_opBACCCC(),
[op00AAAAAAAA] = new Getter_op00AAAAAAAA(),
[op00AAAABBBB] = new Getter_op00AAAABBBB(),
[opAABBBBBBBB] = new Getter_opAABBBBBBBB(),
[opAABBBBCCCC] = new Getter_opAABBBBCCCC(),
[opAGBBBBDCFE] = new Getter_opAGBBBBDCFE(),
[opAABBBBCCCCHHHH] = new Getter_opAABBBBCCCCHHHH(),
[opAGBBBBDCFEHHHH] = new Getter_opAGBBBBDCFEHHHH(),
[opAABBBBBBBBBBBBBBBB] = new Getter_opAABBBBBBBBBBBBBBBB(),
[_10t] = new Getter_10t(),
[_20t] = new Getter_20t(),
[_21t] = new Getter_21t(),
[_22t] = new Getter_22t(),
[_30t] = new Getter_30t(),
};
const InstType inst_types[256] = {
[0x00] = InstType("nop", op00 ),
[0x01] = InstType("move", opBA, "vA, vB" ),
[0x02] = InstType("move/from16", opAABBBB, "vA, vB" ),
[0x03] = InstType("move/16", op00AAAABBBB, "vA, vB" ),
[0x04] = InstType("move_wide", opBA, "vA, vB" ),
[0x05] = InstType("move_wide/from16", opAABBBB, "vA, vB" ),
[0x06] = InstType("move_wide/16", op00AAAABBBB, "vA, vB" ),
[0x07] = InstType("move_object", opBA, "vA, vB" ),
[0x08] = InstType("move_object/from16", opAABBBB, "vA, vB" ),
[0x09] = InstType("move_object/16", op00AAAABBBB, "vA, vB" ),
[0x0a] = InstType("move_result", opAA, "vA" ),
[0x0b] = InstType("move_result_wide", opAA, "vA" ),
[0x0c] = InstType("move_result_object", opAA, "vA" ),
[0x0d] = InstType("move_exception", opAA, "vA" ),
[0x0e] = InstType("return_void", op00 ),
[0x0f] = InstType("return", opAA, "vA" ),
[0x10] = InstType("return_wide", opAA, "VA" ),
[0x11] = InstType("return_object", opAA, "vA" ),
[0x12] = InstType("const/4", opBA, "vA, #+B" ),
[0x13] = InstType("const/16", opAABBBB, "vA, #+B" ),
[0x14] = InstType("const", opAABBBBBBBB, "vA, #+B" ),
[0x15] = InstType("const/high16", opAABBBB, "vA, #+B0000" ),
[0x16] = InstType("const_wide/16", opAABBBB, "vA, #+B" ),
[0x17] = InstType("const_wide/32", opAABBBBBBBB, "vA, #+B" ),
[0x18] = InstType("const_wide", opAABBBBBBBBBBBBBBBB, "vA, #+B" ),
[0x19] = InstType("const_wide/high16", opAABBBB, "vA, #+B000000000000" ),
[0x1a] = InstType("const_string", opAABBBB, "vA, string@B" ),
[0x1b] = InstType("const_string/jumbo", opAABBBBBBBB, "vA, string@B" ),
[0x1c] = InstType("const_class", opAABBBB, "vA, type@B" ),
[0x1d] = InstType("monitor_enter", opAA, "vA" ),
[0x1e] = InstType("monitor_exit", opAA, "vA" ),
[0x1f] = InstType("check_cast", opAABBBB, "vA, type@B" ),
[0x20] = InstType("instance_of", opBACCCC, "vA, vB, type@C" ),
[0x21] = InstType("array_length", opBA, "vA, vB" ),
[0x22] = InstType("new_instance", opAABBBB, "vA, type@B" ),
[0x23] = InstType("new_array", opBACCCC, "vA, vB, type@C" ),
[0x24] = InstType("filled_new_array", opAGBBBBDCFE, "{vC, vD, vE, vF, vG}, type@B" ),
[0x25] = InstType("filled_new_array/range", opAABBBBCCCC, "{vC .. vN}, type@B" ),
[0x26] = InstType("fill_array_data", opAABBBBBBBB, "{vA, +B}" ),
[0x27] = InstType("throw", opAA, "vA" ),
[0x28] = InstType("goto", _10t, "+A" ),
[0x29] = InstType("goto/16", _20t, "+A" ),
[0x2a] = InstType("goto/32", _30t, "+A" ),
[0x2b] = InstType("packed_switch", opAABBBBBBBB, "vA, +B" ),
[0x2c] = InstType("sparse_switch", opAABBBBBBBB, "vA, +B" ),
[0x2d] = InstType("cmpl_float", opAACCBB, "vA, vB, vC" ),
[0x2e] = InstType("cmpg_float", opAACCBB, "vA, vB, vC" ),
[0x2f] = InstType("cmpl_double", opAACCBB, "vA, vB, vC" ),
[0x30] = InstType("cmpg_double", opAACCBB, "vA, vB, vC" ),
[0x31] = InstType("cmp_long", opAACCBB, "vA, vB, vC" ),
[0x32] = InstType("if_eq", _22t, "vA, vB, +C" ),
[0x33] = InstType("if_ne", _22t, "vA, vB, +C" ),
[0x34] = InstType("if_lt", _22t, "vA, vB, +C" ),
[0x35] = InstType("if_ge", _22t, "vA, vB, +C" ),
[0x36] = InstType("if_gt", _22t, "vA, vB, +C" ),
[0x37] = InstType("if_le", _22t, "vA, vB, +C" ),
[0x38] = InstType("if_eqz", _21t, "vA, +B" ),
[0x39] = InstType("if_nez", _21t, "vA, +B" ),
[0x3a] = InstType("if_ltz", _21t, "vA, +B" ),
[0x3b] = InstType("if_gez", _21t, "vA, +B" ),
[0x3c] = InstType("if_gtz", _21t, "vA, +B" ),
[0x3d] = InstType("if_lez", _21t, "vA, +B" ),
[0x3e] = InstType("UNUSED", op00 ),
[0x3f] = InstType("UNUSED", op00 ),
[0x40] = InstType("UNUSED", op00 ),
[0x41] = InstType("UNUSED", op00 ),
[0x42] = InstType("UNUSED", op00 ),
[0x43] = InstType("UNUSED", op00 ),
[0x44] = InstType("aget", opAACCBB, "vA, vB, vC" ),
[0x45] = InstType("aget_wide", opAACCBB, "vA, vB, vC" ),
[0x46] = InstType("aget_object", opAACCBB, "vA, vB, vC" ),
[0x47] = InstType("aget_boolean", opAACCBB, "vA, vB, vC" ),
[0x48] = InstType("aget_byte", opAACCBB, "vA, vB, vC" ),
[0x49] = InstType("aget_char", opAACCBB, "vA, vB, vC" ),
[0x4a] = InstType("aget_short", opAACCBB, "vA, vB, vC" ),
[0x4b] = InstType("aput", opAACCBB, "vA, vB, vC" ),
[0x4c] = InstType("aput_wide", opAACCBB, "vA, vB, vC" ),
[0x4d] = InstType("aput_object", opAACCBB, "vA, vB, vC" ),
[0x4e] = InstType("aput_boolean", opAACCBB, "vA, vB, vC" ),
[0x4f] = InstType("aput_byte", opAACCBB, "vA, vB, vC" ),
[0x50] = InstType("aput_char", opAACCBB, "vA, vB, vC" ),
[0x51] = InstType("aput_short", opAACCBB, "vA, vB, vC" ),
[0x52] = InstType("iget", opBACCCC, "vA, vB, field@C" ),
[0x53] = InstType("iget_wide", opBACCCC, "vA, vB, field@C" ),
[0x54] = InstType("iget_object", opBACCCC, "vA, vB, field@C" ),
[0x55] = InstType("iget_boolean", opBACCCC, "vA, vB, field@C" ),
[0x56] = InstType("iget_byte", opBACCCC, "vA, vB, field@C" ),
[0x57] = InstType("iget_char", opBACCCC, "vA, vB, field@C" ),
[0x58] = InstType("iget_short", opBACCCC, "vA, vB, field@C" ),
[0x59] = InstType("iput", opBACCCC, "vA, vB, field@C" ),
[0x5a] = InstType("iput_wide", opBACCCC, "vA, vB, field@C" ),
[0x5b] = InstType("iput_object", opBACCCC, "vA, vB, field@C" ),
[0x5c] = InstType("iput_boolean", opBACCCC, "vA, vB, field@C" ),
[0x5d] = InstType("iput_byte", opBACCCC, "vA, vB, field@C" ),
[0x5e] = InstType("iput_char", opBACCCC, "vA, vB, field@C" ),
[0x5f] = InstType("iput_short", opBACCCC, "vA, vB, field@C" ),
[0x60] = InstType("sget", opAABBBB, "vA, field@B" ),
[0x61] = InstType("sget_wide", opAABBBB, "vA, field@B" ),
[0x62] = InstType("sget_object", opAABBBB, "vA, field@B" ),
[0x63] = InstType("sget_boolean", opAABBBB, "vA, field@B" ),
[0x64] = InstType("sget_byte", opAABBBB, "vA, field@B" ),
[0x65] = InstType("sget_char", opAABBBB, "vA, field@B" ),
[0x66] = InstType("sget_short", opAABBBB, "vA, field@B" ),
[0x67] = InstType("sput", opAABBBB, "vA, field@B" ),
[0x68] = InstType("sput_wide", opAABBBB, "vA, field@B" ),
[0x69] = InstType("sput_object", opAABBBB, "vA, field@B" ),
[0x6a] = InstType("sput_boolean", opAABBBB, "vA, field@B" ),
[0x6b] = InstType("sput_byte", opAABBBB, "vA, field@B" ),
[0x6c] = InstType("sput_char", opAABBBB, "vA, field@B" ),
[0x6d] = InstType("sput_short", opAABBBB, "vA, field@B" ),
[0x6e] = InstType("invoke_virtual", opAGBBBBDCFE, "{vC vD, vE, vF, vG}, meth@B" ),
[0x6f] = InstType("invoke_super", opAGBBBBDCFE, "{vC vD, vE, vF, vG}, meth@B" ),
[0x70] = InstType("invoke_direct", opAGBBBBDCFE, "{vC vD, vE, vF, vG}, meth@B" ),
[0x71] = InstType("invoke_static", opAGBBBBDCFE, "{vC vD, vE, vF, vG}, meth@B" ),
[0x72] = InstType("invoke_interface", opAGBBBBDCFE, "{vC vD, vE, vF, vG}, meth@B" ),
[0x73] = InstType("UNUSED", op00 ),
[0x74] = InstType("invoke_virtual/range", opAABBBBCCCC, "{vC .. vN}, meth@B" ),
[0x75] = InstType("invoke_super/range", opAABBBBCCCC, "{vC .. vN}, meth@B" ),
[0x76] = InstType("invoke_direct/range", opAABBBBCCCC, "{vC .. vN}, meth@B" ),
[0x77] = InstType("invoke_static/range", opAABBBBCCCC, "{vC .. vN}, meth@B" ),
[0x78] = InstType("invoke_interface/range", opAABBBBCCCC, "{vC .. vN}, meth@B" ),
[0x79] = InstType("UNUSED", op00 ),
[0x7a] = InstType("UNUSED", op00 ),
[0x7b] = InstType("neg_int", opBA, "vA, vB" ),
[0x7c] = InstType("not_int", opBA, "vA, vB" ),
[0x7d] = InstType("neg_long", opBA, "vA, vB" ),
[0x7e] = InstType("not_long", opBA, "vA, vB" ),
[0x7f] = InstType("neg_float", opBA, "vA, vB" ),
[0x80] = InstType("neg_double", opBA, "vA, vB" ),
[0x81] = InstType("int_to_long", opBA, "vA, vB" ),
[0x82] = InstType("int_to_float", opBA, "vA, vB" ),
[0x83] = InstType("int_to_double", opBA, "vA, vB" ),
[0x84] = InstType("long_to_int", opBA, "vA, vB" ),
[0x85] = InstType("long_to_float", opBA, "vA, vB" ),
[0x86] = InstType("long_to_double", opBA, "vA, vB" ),
[0x87] = InstType("float_to_int", opBA, "vA, vB" ),
[0x88] = InstType("float_to_long", opBA, "vA, vB" ),
[0x89] = InstType("float_to_double", opBA, "vA, vB" ),
[0x8a] = InstType("double_to_int", opBA, "vA, vB" ),
[0x8b] = InstType("double_to_long", opBA, "vA, vB" ),
[0x8c] = InstType("double_to_float", opBA, "vA, vB" ),
[0x8d] = InstType("int_to_byte", opBA, "vA, vB" ),
[0x8e] = InstType("int_to_char", opBA, "vA, vB" ),
[0x8f] = InstType("int_to_short", opBA, "vA, vB" ),
[0x90] = InstType("add_int", opAACCBB, "vA, vB, vC" ),
[0x91] = InstType("sub_int", opAACCBB, "vA, vB, vC" ),
[0x92] = InstType("mul_int", opAACCBB, "vA, vB, vC" ),
[0x93] = InstType("div_int", opAACCBB, "vA, vB, vC" ),
[0x94] = InstType("rem_int", opAACCBB, "vA, vB, vC" ),
[0x95] = InstType("and_int", opAACCBB, "vA, vB, vC" ),
[0x96] = InstType("or_int", opAACCBB, "vA, vB, vC" ),
[0x97] = InstType("xor_int", opAACCBB, "vA, vB, vC" ),
[0x98] = InstType("shl_int", opAACCBB, "vA, vB, vC" ),
[0x99] = InstType("shr_int", opAACCBB, "vA, vB, vC" ),
[0x9a] = InstType("ushr_int", opAACCBB, "vA, vB, vC" ),
[0x9b] = InstType("add_long", opAACCBB, "vA, vB, vC" ),
[0x9c] = InstType("sub_long", opAACCBB, "vA, vB, vC" ),
[0x9d] = InstType("mul_long", opAACCBB, "vA, vB, vC" ),
[0x9e] = InstType("div_long", opAACCBB, "vA, vB, vC" ),
[0x9f] = InstType("rem_long", opAACCBB, "vA, vB, vC" ),
[0xa0] = InstType("and_long", opAACCBB, "vA, vB, vC" ),
[0xa1] = InstType("or_long", opAACCBB, "vA, vB, vC" ),
[0xa2] = InstType("xor_long", opAACCBB, "vA, vB, vC" ),
[0xa3] = InstType("shl_long", opAACCBB, "vA, vB, vC" ),
[0xa4] = InstType("shr_long", opAACCBB, "vA, vB, vC" ),
[0xa5] = InstType("ushr_long", opAACCBB, "vA, vB, vC" ),
[0xa6] = InstType("add_float", opAACCBB, "vA, vB, vC" ),
[0xa7] = InstType("sub_float", opAACCBB, "vA, vB, vC" ),
[0xa8] = InstType("mul_float", opAACCBB, "vA, vB, vC" ),
[0xa9] = InstType("div_float", opAACCBB, "vA, vB, vC" ),
[0xaa] = InstType("rem_float", opAACCBB, "vA, vB, vC" ),
[0xab] = InstType("add_double", opAACCBB, "vA, vB, vC" ),
[0xac] = InstType("sub_double", opAACCBB, "vA, vB, vC" ),
[0xad] = InstType("mul_double", opAACCBB, "vA, vB, vC" ),
[0xae] = InstType("div_double", opAACCBB, "vA, vB, vC" ),
[0xaf] = InstType("rem_double", opAACCBB, "vA, vB, vC" ),
[0xb0] = InstType("add_int/2addr", opBA, "vA, vB" ),
[0xb1] = InstType("sub_int/2addr", opBA, "vA, vB" ),
[0xb2] = InstType("mul_int/2addr", opBA, "vA, vB" ),
[0xb3] = InstType("div_int/2addr", opBA, "vA, vB" ),
[0xb4] = InstType("rem_int/2addr", opBA, "vA, vB" ),
[0xb5] = InstType("and_int/2addr", opBA, "vA, vB" ),
[0xb6] = InstType("or_int/2addr", opBA, "vA, vB" ),
[0xb7] = InstType("xor_int/2addr", opBA, "vA, vB" ),
[0xb8] = InstType("shl_int/2addr", opBA, "vA, vB" ),
[0xb9] = InstType("shr_int/2addr", opBA, "vA, vB" ),
[0xba] = InstType("ushr_int/2addr", opBA, "vA, vB" ),
[0xbb] = InstType("add_long/2addr", opBA, "vA, vB" ),
[0xbc] = InstType("sub_long/2addr", opBA, "vA, vB" ),
[0xbd] = InstType("mul_long/2addr", opBA, "vA, vB" ),
[0xbe] = InstType("div_long/2addr", opBA, "vA, vB" ),
[0xbf] = InstType("rem_long/2addr", opBA, "vA, vB" ),
[0xc0] = InstType("and_long/2addr", opBA, "vA, vB" ),
[0xc1] = InstType("or_long/2addr", opBA, "vA, vB" ),
[0xc2] = InstType("xor_long/2addr", opBA, "vA, vB" ),
[0xc3] = InstType("shl_long/2addr", opBA, "vA, vB" ),
[0xc4] = InstType("shr_long/2addr", opBA, "vA, vB" ),
[0xc5] = InstType("ushr_long/2addr", opBA, "vA, vB" ),
[0xc6] = InstType("add_float/2addr", opBA, "vA, vB" ),
[0xc7] = InstType("sub_float/2addr", opBA, "vA, vB" ),
[0xc8] = InstType("mul_float/2addr", opBA, "vA, vB" ),
[0xc9] = InstType("div_float/2addr", opBA, "vA, vB" ),
[0xca] = InstType("rem_float/2addr", opBA, "vA, vB" ),
[0xcb] = InstType("add_double/2addr", opBA, "vA, vB" ),
[0xcc] = InstType("sub_double/2addr", opBA, "vA, vB" ),
[0xcd] = InstType("mul_double/2addr", opBA, "vA, vB" ),
[0xce] = InstType("div_double/2addr", opBA, "vA, vB" ),
[0xcf] = InstType("rem_double/2addr", opBA, "vA, vB" ),
[0xd0] = InstType("add_int/lit16", opBACCCC, "vA, vB, #+C" ),
[0xd1] = InstType("rsub_int", opBACCCC, "vA, vB, #+C" ),
[0xd2] = InstType("mul_int/lit16", opBACCCC, "vA, vB, #+C" ),
[0xd3] = InstType("div_int/lit16", opBACCCC, "vA, vB, #+C" ),
[0xd4] = InstType("rem_int/lit16", opBACCCC, "vA, vB, #+C" ),
[0xd5] = InstType("and_int/lit16", opBACCCC, "vA, vB, #+C" ),
[0xd6] = InstType("or_int/lit16", opBACCCC, "vA, vB, #+C" ),
[0xd7] = InstType("xor_int/lit16", opBACCCC, "vA, vB, #+C" ),
[0xd8] = InstType("add_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xd9] = InstType("rsub_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xda] = InstType("mul_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xdb] = InstType("div_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xdc] = InstType("rem_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xdd] = InstType("and_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xde] = InstType("or_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xdf] = InstType("xor_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xe0] = InstType("shl_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xe1] = InstType("shr_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xe2] = InstType("ushr_int/lit8", opAACCBB, "vA, vB, #+C" ),
[0xe3] = InstType("UNUSED", op00 ),
[0xe4] = InstType("UNUSED", op00 ),
[0xe5] = InstType("UNUSED", op00 ),
[0xe6] = InstType("UNUSED", op00 ),
[0xe7] = InstType("UNUSED", op00 ),
[0xe8] = InstType("UNUSED", op00 ),
[0xe9] = InstType("UNUSED", op00 ),
[0xea] = InstType("UNUSED", op00 ),
[0xeb] = InstType("UNUSED", op00 ),
[0xec] = InstType("UNUSED", op00 ),
[0xed] = InstType("UNUSED", op00 ),
[0xee] = InstType("UNUSED", op00 ),
[0xef] = InstType("UNUSED", op00 ),
[0xf0] = InstType("UNUSED", op00 ),
[0xf1] = InstType("UNUSED", op00 ),
[0xf2] = InstType("UNUSED", op00 ),
[0xf3] = InstType("UNUSED", op00 ),
[0xf4] = InstType("UNUSED", op00 ),
[0xf5] = InstType("UNUSED", op00 ),
[0xf6] = InstType("UNUSED", op00 ),
[0xf7] = InstType("UNUSED", op00 ),
[0xf8] = InstType("UNUSED", op00 ),
[0xf9] = InstType("UNUSED", op00 ),
[0xfa] = InstType("invoke_polymorphic", opAGBBBBDCFEHHHH, "{vC, vD, vE, vF, vG}, meth@B, proto@H" ),
[0xfb] = InstType("invoke_polymorphic/range", opAABBBBCCCCHHHH, "{vC .. vN}, meth@B, proto@H" ),
[0xfc] = InstType("invoke_custom", opAGBBBBDCFE, "{vC, vD, vE, vF, vG}, call_site@B" ),
[0xfd] = InstType("invoke_custom/range", opAABBBBCCCC, "{vC .. vN}, call_site@B" ),
[0xfe] = InstType("const_method_handle", opAABBBB, "vA, method_handle@B" ),
[0xff] = InstType("const_method_type", opAABBBB, "vA, proto@B" ),
};
| true |
6bfd98a7e4a779a052446fb4b2771e184b2f1275 | C++ | Ars-eniy-Cheis/ProgramLanguages | /Figures/Rectangle.cpp | UTF-8 | 315 | 3.078125 | 3 | [] | no_license |
#include "Rectangle.h"
Rectangle::Rectangle()
{
a = 0;
b = 0;
}
Rectangle::Rectangle(float new_a, float new_b)
{
a = new_a;
b = new_b;
}
Rectangle::Rectangle(float new_a)
{
a = new_a;
b = new_a;
}
float Rectangle::Area()
{
return a * b;
}
Figure* Rectangle::Clone()
{
return new Rectangle(a, b);
}
| true |
5fc973fc8590f4c8b69c4cdc1dbc8ea5bda27654 | C++ | learn-it/system | /snippets/negcache/neg_cache.cc | UTF-8 | 3,017 | 2.65625 | 3 | [] | no_license | #include <map>
#include <algorithm>
#include <string>
#include <time.h>
#include <pthread.h>
#include <errno.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <string.h>
#include <iostream>
using namespace std;
// items are stored until this count of seconds
static size_t cache_ttl = 2;
struct data_byname
{
data_byname(int err): time_it(0), error(err) {}
void * time_it;
int error;
};
typedef map<string, data_byname> map_byname;
typedef map_byname::iterator it_byname;
typedef multimap<time_t, it_byname> map_bytime;
typedef map_bytime::iterator it_bytime;
map_byname by_name;
map_bytime by_time;
struct delete_name
{
void operator() (map_bytime::value_type& n)
{
by_name.erase(n.second);
}
} name_deleter;
class RWLock
{
public:
RWLock() { pthread_rwlock_init(&lock_, 0); }
~RWLock() { pthread_rwlock_destroy(&lock_); }
operator pthread_rwlock_t&() { return lock_; }
private:
pthread_rwlock_t lock_;
};
class RGuard
{
public:
RGuard(pthread_rwlock_t& l): lock_(l) { pthread_rwlock_rdlock(&lock_); }
~RGuard() { pthread_rwlock_unlock(&lock_); }
private:
pthread_rwlock_t& lock_;
};
class WGuard
{
public:
WGuard(pthread_rwlock_t& l): lock_(l) { pthread_rwlock_wrlock(&lock_); }
~WGuard() { pthread_rwlock_unlock(&lock_); }
private:
pthread_rwlock_t& lock_;
};
static RWLock lock;
// performance ~1.1m ops/sec
int check_negcache(const char *url)
{
if (*url != '/')
return 0; /* (won't cache unknown stuff) */
++url; // skip leading '/'
if (*url == 0)
return 0; /* (something evil is happening) */
RGuard guard(lock);
if (by_time.size() == 0)
return 0;
string host(url, strchrnul(url, '/'));
time_t expiry;
time(&expiry);
expiry -= cache_ttl;
it_bytime t = by_time.end();
it_bytime p = t--;
while (true)
{
if (t->first <= expiry) {
for_each(by_time.begin(), p, name_deleter);
by_time.erase(by_time.begin(), p);
break;
}
if (t == by_time.begin())
break;
p = t--;
}
it_byname name_it = by_name.find(host);
if (name_it == by_name.end())
return 0;
return name_it->second.error;
}
// performance ~850k ops/sec
void set_negcache(const char *url, int error)
{
if (*url != '/')
return; /* (won't cache unknown stuff) */
if (error != ECONNREFUSED && error != ETIMEDOUT)
return;
++url; // skip leading '/'
if (*url == 0)
return; /* (something evil is happening) */
string host(url, strchrnul(url, '/'));
WGuard guard(lock);
it_byname name_it = by_name.find(host);
it_bytime time_it;
if (name_it != by_name.end()) {
*(void **)&time_it = name_it->second.time_it;
by_time.erase(time_it);
name_it->second.error = error;
} else {
pair<it_byname, bool> res = by_name.insert(
map_byname::value_type(host, error)
);
name_it = res.first;
}
time_it = by_time.insert(map_bytime::value_type(time(0), name_it));
name_it->second.time_it = *(void **)&time_it;
}
| true |
b3cee51c98f87ed392a077fd62efd5274440bf11 | C++ | Algomorph/surfelwarp | /apps/hash_app/check_compact_probe_table.cpp | UTF-8 | 1,789 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "check_compact_probe_table.h"
#include "common/common_types.h"
#include "common/sanity_check.h"
#include "hashing/CompactProbeTable.h"
#include <iostream>
void surfelwarp::check_probe_compaction(const unsigned test_size, const unsigned test_iters)
{
for(auto i = 0; i < test_iters; i++) {
check_probe_compaction(test_size);
if(i % 10 == 0)
std::cout << "Checking of " << i << std::endl;
}
}
void surfelwarp::check_probe_compaction(const unsigned test_size)
{
using namespace hashing;
using namespace surfelwarp;
//Prepare data at host
std::vector<unsigned> h_keys;
const unsigned duplicate = 32;
fillMultiKeyValuePairs(h_keys, test_size, 2 * test_size, duplicate);
//Upload it
DeviceArray<unsigned> d_keys;
d_keys.upload(h_keys);
//Create the table
CompactProbeTable table;
table.AllocateBuffer(2 * (h_keys.size() / duplicate));
table.ResetTable();
const bool success = table.Insert(d_keys.ptr(), d_keys.size());
if(!success) {
std::cout << "Insertation failed!" << std::endl;
}
//Check the table
std::vector<unsigned> h_entires;
h_entires.resize(table.TableSize());
cudaSafeCall(cudaMemcpy(h_entires.data(), table.TableEntry(), sizeof(unsigned) * h_entires.size(), cudaMemcpyDeviceToHost));
//Check the duplicate
bool unique = isElementUnique(h_entires, 0xffffffff);
assert(unique);
//Retrieve of the index
DeviceArray<unsigned> d_index;
d_index.create(d_keys.size());
table.RetrieveIndex(d_keys.ptr(), d_keys.size(), d_index.ptr());
//Check the retrieved index
std::vector<unsigned> h_index;
d_index.download(h_index);
for(auto i = 0; i < h_index.size(); i++) {
const auto key_in = h_keys[i];
assert(h_index[i] < h_entires.size());
const auto key_retrieved = h_entires[h_index[i]];
assert(key_in == key_retrieved);
}
} | true |
c590c7a8b681e6916a83bd3fd48359939123a9d0 | C++ | zlvb/zcelib | /src/commlib/zcelib/zce_socket_addr_in6.h | GB18030 | 5,214 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef ZCE_LIB_SOCKET_ADDR_IN6_
#define ZCE_LIB_SOCKET_ADDR_IN6_
//IPV6һ
//IPv6ṹ
class ZCE_Sockaddr_In6 : public ZCE_Sockaddr
{
public:
//ĬϹ캯
ZCE_Sockaddr_In6 (void);
//sockaddr_in죬
ZCE_Sockaddr_In6 (const sockaddr_in6 *addr);
//ݶ˿ںţIPַַ,ipv6_addr_strӦ<40ֽڵij
ZCE_Sockaddr_In6 (const char *ipv6_addr_str,
uint16_t port_number);
//ݶ˿ںţIPַϢ
ZCE_Sockaddr_In6 (uint16_t port_number,
const char ipv6_addr_val[16]);
//죬һҪдĻָָԼһַģ
ZCE_Sockaddr_In6 (const ZCE_Sockaddr_In6 &others);
virtual ~ZCE_Sockaddr_In6();
public:
//õַϢ
virtual void set_sockaddr (sockaddr *addr, socklen_t len);
/*!
* @brief ַȡIPַϢԼ˿ںϢ,
* @return int == 0ʾóɹ
* @param ip_addr_str
* @note ַ#,ᱻΪж˿ںţûУ˿ںΪ0
*/
int set(const char *ip_addr_str);
//ݵַ֣˿ں
int set(const char ip_addr_str[],
uint16_t port_number);
//ݵַIP˿ں
int set(uint16_t port_number,
const char ipv6_addr_val[16]);
///ö˿ںã
inline void set_port_number (uint16_t);
///ȡö˿ں
inline uint16_t get_port_number (void) const;
///˿ںǷһȫ˿
bool check_safeport();
//ɳķǰȫ
inline const char *get_host_name (void) const;
//ȡ:ðŵIPַϢSTRING
inline const char *get_host_addr (char *addr, int addr_size) const;
//ɳķǰȫ
inline const char *get_host_addr (void) const;
//ȡԣŵIPַ#˿ںSTRING
inline const char *get_host_addr_port(char *addr, int addr_size) const;
//ȡIPַ,Ҫ֤ipv6_addr_val16ֽ
const char *get_ip_address (char *ipv6_addr_val) const;
//ȽַǷ
bool operator == (const ZCE_Sockaddr_In6 &others) const;
//ȽַǷ
bool operator != (const ZCE_Sockaddr_In6 &others) const;
//IPַǷ,Ӷ˿
bool is_ip_equal (const ZCE_Sockaddr_In6 &others) const;
//IPV6ĵַǷIPV4ĵַӳ
bool is_v4mapped() const;
//һIPV4ĵַõӦӳIPV6ĵַ
int map_from_inaddr(const ZCE_Sockaddr_In &from);
//IPV6ĵַIPV4ӳģ仹ԭΪIPV4ĵַ
int mapped_to_inaddr(ZCE_Sockaddr_In &to) const;
//DNSغ
//ȡIPַصϢ,õgetnameinfo
int get_name_info(char *host_name, size_t name_len) const;
//ȡصIPַϢõgetaddrinfo
int get_addr_info(const char *hostname, uint16_t service_port = 0);
//ֲתʹãZCE_Sockaddr_In6Ϊsockaddr_in6һ
//sockaddr_in6
operator sockaddr_in6 () const;
//ڲconst sockaddr_in6ָ룬Աģ
operator const sockaddr_in6 *() const;
//ڲ sockaddr_in6ָ룬Աģ
operator sockaddr_in6 *();
protected:
//IPV6ĵַ
sockaddr_in6 in6_addr_;
};
//ȡIPַҪ֤ipv6_addr_valij16ֽ
inline const char *ZCE_Sockaddr_In6::get_ip_address (char *ipv6_addr_val) const
{
memcpy(ipv6_addr_val, &(in6_addr_.sin6_addr), sizeof(in6_addr));
return ipv6_addr_val;
}
//ö˿ںã
inline void ZCE_Sockaddr_In6::set_port_number (uint16_t port_number)
{
in6_addr_.sin6_port = ntohs(port_number);
}
//ȡö˿ں
inline uint16_t ZCE_Sockaddr_In6::get_port_number (void) const
{
return ntohs(in6_addr_.sin6_port);
}
//ȡ.ŵIPַϢSTRING
inline const char *ZCE_Sockaddr_In6::get_host_addr (char *addr_buf, int addr_size) const
{
return ZCE_LIB::socketaddr_ntop(reinterpret_cast<const sockaddr *>(&in6_addr_),
addr_buf,
addr_size);
}
//ɳķǰȫ
inline const char *ZCE_Sockaddr_In6::get_host_addr (void) const
{
const size_t BUF_LEN = 64;
static char in4_buf[BUF_LEN + 1];
in4_buf[BUF_LEN] = '\0';
return ZCE_LIB::socketaddr_ntop(reinterpret_cast<const sockaddr *>(&in6_addr_),
in4_buf,
BUF_LEN);
}
//ȡ.ŵIPַ#˿ںSTRING
inline const char *ZCE_Sockaddr_In6::get_host_addr_port(char *addr_buf, int addr_size) const
{
return ZCE_LIB::socketaddr_ntop_ex(reinterpret_cast<const sockaddr *>(&in6_addr_),
addr_buf,
addr_size);
}
#endif //ZCE_LIB_SOCKET_ADDR_IN6_
| true |
1d6e0e05b712229c82228cd7aae6b6e04c455c50 | C++ | liqiang311/oj | /offer2017/2017_09_21_xiecheng_1.cpp | UTF-8 | 1,887 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <stack>
using namespace std;
#define max(a,b) (a>b?a:b)
int fun1(vector< vector<int> > &arr, int ii, int jj)
{
vector< vector<int> > f;
f.resize(arr.size());
for (int i = 0; i < f.size(); i++)
{
f[i].resize(arr[i].size());
for (int j = 0; j < arr[i].size(); j++)
{
f[i][j] = 0;
}
}
f[ii][jj] = 1;
stack<pair<int, int>> s;
s.push(pair<int, int>(ii, jj));
while (!s.empty())
{
pair<int, int> p = s.top();
s.pop();
int ff = p.first, ss = p.second, newv = f[p.first][p.second] + 1;
if (ff - 1 >= 0 && arr[ff][ss] > arr[ff - 1][ss] && newv > f[ff - 1][ss])
{
f[ff - 1][ss] = newv;
s.push(pair<int, int>(ff - 1, ss));
}
if (ff + 1 < arr.size() && arr[ff][ss] > arr[ff + 1][ss] && newv > f[ff + 1][ss])
{
f[ff + 1][ss] = newv;
s.push(pair<int, int>(p.first + 1, p.second));
}
if (ss - 1 >= 0 && arr[ff][ss] > arr[ff][ss - 1] && newv > f[ff][ss-1])
{
f[ff][ss - 1] = newv;
s.push(pair<int, int>(ff, ss - 1));
}
if (ss + 1 < arr.size() && arr[ff][ss] > arr[ff][ss + 1] && newv > f[ff][ss + 1])
{
f[ff][ss + 1] = newv;
s.push(pair<int, int>(p.first, p.second + 1));
}
}
int res = 0;
for (int i = 0; i < f.size(); i++)
{
for (int j = 0; j < arr[i].size(); j++)
{
if (f[i][j] > res) res = f[i][j];
}
}
return res;
}
int fun(vector< vector<int> > arr)
{
int res = 0;
for (int i = 0; i < arr.size(); i++)
{
for (int j = 0; j < arr[i].size(); j++)
{
int res1 = fun1(arr, i, j);
if (res1 > res) res = res1;
}
}
return res;
}
int main()
{
int X, Y;
while (cin >> X && cin >> Y)
{
vector<vector<int> > vec(X, vector<int>(Y, 0));
for (int i = 0; i < X; i++)
{
for (int j = 0; j < Y; j++)
{
cin >> vec[i][j];
}
}
cout << fun(vec) << endl;
}
return 0;
}
/*
2 2
3 2
1 3
4 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
*/
| true |
dde3aaa622a98bcd050e7919f17d064bc2ecb485 | C++ | socc-io/algostudy | /baekjoon/smilu/1557.cpp | UTF-8 | 867 | 2.625 | 3 | [] | no_license | #include <cstdio>
typedef long long ll;
const int MAX = 100010;
int mob[MAX];
ll f(ll x) {
ll ret = 0;
for (int i = 1; i*i <= x; i++)
ret += mob[i] * (x/(i*i));
return ret;
}
void set_mob() {
for (int i = 0; i < MAX; i++) mob[i] = 1;
for (int i = 2; i*i < MAX; i++) {
if (mob[i] != 1) continue;
for (int j = i; j < MAX; j += i) mob[j] *= -i;
for (int j = i*i; j < MAX; j += i*i) mob[j] = 0;
}
for (int i = 2; i < MAX; i++) {
if (mob[i] == i) mob[i] = 1;
else if (mob[i] == -i) mob[i] = -1;
else if (mob[i] < 0) mob[i] = 1;
else if (mob[i] > 0) mob[i] = -1;
}
}
int main(void)
{
ll k; scanf("%lld", &k);
set_mob();
ll s = 1, e = 2000000000;
while (s < e) {
ll m = (s+e)>>1;
ll v = f(m);
if (v > k) e = m-1;
else if (v < k) s = m+1;
else e = m;
}
printf("%lld\n", s);
}
| true |
050af52136dfcaca7548a14fcfcb2ade80605805 | C++ | fifilyu/zguide-examples-cpp-with-cmake | /src/mdcliapi2.hpp | UTF-8 | 4,111 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef __MDCLIAPI_HPP_INCLUDED__
#define __MDCLIAPI_HPP_INCLUDED__
#include "zmsg.hpp"
#include "mdp.h"
// Structure of our class
// We access these properties only via class methods
class mdcli {
public:
// ---------------------------------------------------------------------
// Constructor
mdcli (std::string broker, int verbose)
{
s_version_assert (4, 0);
m_broker = broker;
m_context = new zmq::context_t (1);
m_verbose = verbose;
m_timeout = 2500; // msecs
m_client = 0;
s_catch_signals ();
connect_to_broker ();
}
// ---------------------------------------------------------------------
// Destructor
virtual
~mdcli ()
{
delete m_client;
delete m_context;
}
// ---------------------------------------------------------------------
// Connect or reconnect to broker
void connect_to_broker ()
{
if (m_client) {
delete m_client;
}
m_client = new zmq::socket_t (*m_context, ZMQ_DEALER);
int linger = 0;
m_client->setsockopt (ZMQ_LINGER, &linger, sizeof (linger));
s_set_id(*m_client);
m_client->connect (m_broker.c_str());
if (m_verbose)
s_console ("I: connecting to broker at %s...", m_broker.c_str());
}
// ---------------------------------------------------------------------
// Set request timeout
void
set_timeout (int timeout)
{
m_timeout = timeout;
}
// ---------------------------------------------------------------------
// Send request to broker
// Takes ownership of request message and destroys it when sent.
int
send (std::string service, zmsg *&request_p)
{
assert (request_p);
zmsg *request = request_p;
// Prefix request with protocol frames
// Frame 0: empty (REQ emulation)
// Frame 1: "MDPCxy" (six bytes, MDP/Client x.y)
// Frame 2: Service name (printable string)
request->push_front ((char*)service.c_str());
request->push_front ((char*)MDPC_CLIENT);
request->push_front ((char*)"");
if (m_verbose) {
s_console ("I: send request to '%s' service:", service.c_str());
request->dump ();
}
request->send (*m_client);
return 0;
}
// ---------------------------------------------------------------------
// Returns the reply message or NULL if there was no reply. Does not
// attempt to recover from a broker failure, this is not possible
// without storing all unanswered requests and resending them all...
zmsg *
recv ()
{
// Poll socket for a reply, with timeout
zmq::pollitem_t items [] =
{ { static_cast<void *>(*m_client), 0, ZMQ_POLLIN, 0 } };
zmq::poll (items, 1, m_timeout);
// If we got a reply, process it
if (items [0].revents & ZMQ_POLLIN) {
zmsg *msg = new zmsg (*m_client);
if (m_verbose) {
s_console ("I: received reply:");
msg->dump ();
}
// Don't try to handle errors, just assert noisily
assert (msg->parts () >= 4);
assert (msg->pop_front ().length() == 0); // empty message
std::basic_string<unsigned char> header = msg->pop_front();
assert (header.compare((unsigned char *)MDPC_CLIENT) == 0);
std::basic_string<unsigned char> service = msg->pop_front();
assert (service.compare((unsigned char *)service.c_str()) == 0);
return msg; // Success
}
if (s_interrupted)
std::cout << "W: interrupt received, killing client..." << std::endl;
else
if (m_verbose)
s_console ("W: permanent error, abandoning request");
return 0;
}
private:
std::string m_broker;
zmq::context_t * m_context;
zmq::socket_t * m_client; // Socket to broker
int m_verbose; // Print activity to stdout
int m_timeout; // Request timeout
};
#endif
| true |
50592e6223c0a0b110d760e9568fe9d0c1935e8b | C++ | alriddoch/tardis | /SDL_and_opengles/SDL_and_opengles.cpp | UTF-8 | 8,770 | 2.5625 | 3 | [] | no_license | /*This source code copyrighted by Lazy Foo' Productions (2004-2014)
and may not be redistributed without written permission.*/
//Using SDL, SDL OpenGL, GLEW, standard IO, and strings
#include <SDL.h>
// #include <GL/glew.h>
#include <SDL_opengl.h>
#include <GLES2/gl2.h>
#include <stdio.h>
#include <string>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
//Starts up SDL, creates window, and initializes OpenGL
bool init();
//Initializes rendering program and clear color
bool initGL();
//Input handler
void handleKeys(unsigned char key, int x, int y);
//Per frame update
void update();
//Renders quad to the screen
void render();
//Frees media and shuts down SDL
void close();
//Shader loading utility programs
void printProgramLog(GLuint program);
void printShaderLog(GLuint shader);
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//OpenGL context
SDL_GLContext gContext;
//Render flag
bool gRenderQuad = true;
//Graphics program
GLuint gProgramID = 0;
GLint gVertexPos2DLocation = -1;
GLuint gVBO = 0;
GLuint gIBO = 0;
bool init()
{
//Initialize SDL
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
return false;
}
printf("SDL init ok\n");
//Use OpenGL 3.1 core
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
//Create window
gWindow = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if(gWindow == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
printf("Create window ok\n");
//Create context
gContext = SDL_GL_CreateContext(gWindow);
if(gContext == NULL)
{
printf("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError());
return false;
}
printf("Create context ok\n");
//Use Vsync
if(SDL_GL_SetSwapInterval(1) < 0)
{
printf("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError());
}
//Initialize OpenGL
if(!initGL())
{
printf("Unable to initialize OpenGL!\n");
return false;
}
return true;
}
bool initGL()
{
//Generate program
gProgramID = glCreateProgram();
//Create vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
//Get vertex source
const GLchar* vertexShaderSource[] =
{
"#version 100\n"
"attribute vec2 LVertexPos2D;"
"void main() {"
" gl_Position = vec4(LVertexPos2D.x, LVertexPos2D.y, 0, 1);"
"}"
};
//Set vertex source
glShaderSource(vertexShader, 1, vertexShaderSource, NULL);
//Compile vertex source
glCompileShader(vertexShader);
//Check vertex shader for errors
GLint vShaderCompiled = GL_FALSE;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &vShaderCompiled);
if(vShaderCompiled != GL_TRUE)
{
printf("Unable to compile vertex shader %d!\n", vertexShader);
printShaderLog(vertexShader);
return false;
}
//Attach vertex shader to program
glAttachShader(gProgramID, vertexShader);
//Create fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
//Get fragment source
const GLchar* fragmentShaderSource[] =
{
"#version 100\n"
"void main() {"
" gl_FragColor = vec4(1.0, 0.0, 1.0, 0.0);"
"}"
};
//Set fragment source
glShaderSource(fragmentShader, 1, fragmentShaderSource, NULL);
//Compile fragment source
glCompileShader(fragmentShader);
//Check fragment shader for errors
GLint fShaderCompiled = GL_FALSE;
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &fShaderCompiled);
if(fShaderCompiled != GL_TRUE)
{
printf("Unable to compile fragment shader %d!\n", fragmentShader);
printShaderLog(fragmentShader);
return false;
}
//Attach fragment shader to program
glAttachShader(gProgramID, fragmentShader);
//Link program
glLinkProgram(gProgramID);
//Check for errors
GLint programSuccess = GL_TRUE;
glGetProgramiv(gProgramID, GL_LINK_STATUS, &programSuccess);
if(programSuccess != GL_TRUE)
{
printf("Error linking program %d!\n", gProgramID);
printProgramLog(gProgramID);
return false;
}
//Get vertex attribute location
gVertexPos2DLocation = glGetAttribLocation(gProgramID, "LVertexPos2D");
if(gVertexPos2DLocation == -1)
{
printf("LVertexPos2D is not a valid glsl program variable!\n");
return false;
}
//Initialize clear color
glClearColor(0.f, 0.f, 0.f, 1.f);
//VBO data
GLfloat vertexData[] =
{
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f
};
//IBO data
GLuint indexData[] = { 0, 1, 2, 3 };
//Create VBO
glGenBuffers(1, &gVBO);
glBindBuffer(GL_ARRAY_BUFFER, gVBO);
glBufferData(GL_ARRAY_BUFFER, 2 * 4 * sizeof(GLfloat), vertexData, GL_STATIC_DRAW);
//Create IBO
glGenBuffers(1, &gIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 4 * sizeof(GLuint), indexData, GL_STATIC_DRAW);
// These calls don't exist in ES, but are required by at least some
// implementations in the 3.x core (3.1 Mesa/DRI specifically)
// glGenVertexArrays(1, &gVAO);
// glBindVertexArray(gVAO);
return true;
}
void handleKeys(unsigned char key, int x, int y)
{
//Toggle quad
if(key == 'q')
{
gRenderQuad = !gRenderQuad;
}
}
void update()
{
//No per frame update needed
}
void render()
{
//Clear color buffer
glClear(GL_COLOR_BUFFER_BIT);
//Render quad
if(gRenderQuad)
{
//Bind program
glUseProgram(gProgramID);
//Enable vertex position
glEnableVertexAttribArray(gVertexPos2DLocation);
//Set vertex data
glBindBuffer(GL_ARRAY_BUFFER, gVBO);
glVertexAttribPointer(gVertexPos2DLocation, 2, GL_FLOAT, GL_FALSE, 0, NULL);
//Set index data and render
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIBO);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, NULL);
//Disable vertex position
glDisableVertexAttribArray(gVertexPos2DLocation);
//Unbind program
glUseProgram(GL_ZERO);
}
}
void close()
{
//Deallocate program
glDeleteProgram(gProgramID);
//Destroy window
SDL_DestroyWindow(gWindow);
gWindow = NULL;
//Quit SDL subsystems
SDL_Quit();
}
void printProgramLog(GLuint program)
{
//Make sure name is shader
if(glIsProgram(program))
{
//Program log length
int infoLogLength = 0;
int maxLength = infoLogLength;
//Get info string length
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
//Allocate string
char* infoLog = new char[ maxLength ];
//Get info log
glGetProgramInfoLog(program, maxLength, &infoLogLength, infoLog);
if(infoLogLength > 0)
{
//Print Log
printf("%s\n", infoLog);
}
//Deallocate string
delete[] infoLog;
}
else
{
printf("Name %d is not a program\n", program);
}
}
void printShaderLog(GLuint shader)
{
//Make sure name is shader
if(glIsShader(shader))
{
//Shader log length
int infoLogLength = 0;
int maxLength = infoLogLength;
//Get info string length
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
//Allocate string
char* infoLog = new char[ maxLength ];
//Get info log
glGetShaderInfoLog(shader, maxLength, &infoLogLength, infoLog);
if(infoLogLength > 0)
{
//Print Log
printf("%s\n", infoLog);
}
//Deallocate string
delete[] infoLog;
}
else
{
printf("Name %d is not a shader\n", shader);
}
}
int main(int argc, char* args[])
{
//Start up SDL and create window
if(!init())
{
printf("Failed to initialize!\n");
}
else
{
printf("Init all ok\n");
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//Enable text input
SDL_StartTextInput();
//While application is running
while(!quit)
{
//Handle events on queue
while(SDL_PollEvent(&e) != 0)
{
//User requests quit
if(e.type == SDL_QUIT)
{
quit = true;
}
//Handle keypress with current mouse position
else if(e.type == SDL_TEXTINPUT)
{
int x = 0, y = 0;
SDL_GetMouseState(&x, &y);
handleKeys(e.text.text[ 0 ], x, y);
}
}
//Render quad
render();
//Update screen
SDL_GL_SwapWindow(gWindow);
}
//Disable text input
SDL_StopTextInput();
}
//Free resources and close SDL
close();
return 0;
}
| true |
06d8698ba4d965bdf1061cdb9b10ab24d1f6d653 | C++ | simjaemun2/uva | /ch6/6.4/uva10298.cpp | UTF-8 | 1,158 | 2.53125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <string>
#include <memory.h>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <utility>
#include <stack>
#include <sstream>
#include <math.h>
using namespace std;
string line;
vector<int> kmpPreprocess(string s)
{
int i = 0, j = -1;
vector<int> v(s.size() + 1, 0);
v[0] = -1;
while (i < s.size())
{
while (j >= 0 && s[i] != s[j])
j = v[j];
i++, j++;
v[i] = j;
}
return v;
}
vector<int> kmpSearch(string t, string p)
{
int i = 0, j = 0;
vector<int> v = kmpPreprocess(p);
vector<int> result;
while (i < t.size())
{
while (j >= 0 && t[i] != p[j])
j = v[j];
i++, j++;
if (j == p.size())
{
result.push_back(i - j);
j = v[j];
}
}
return result;
}
int main(int argc, char** argv)
{
std::ios::sync_with_stdio(false);
#ifdef _WIN32
freopen("Text.txt", "r", stdin);
#endif
while (cin >> line, line != ".")
{
string line2 = line + line;
cout << kmpSearch(line2, line).size() - 1<< '\n';
}
return 0;
}
| true |
3931c191030849748a1ba38c2014eb4a1ab166cc | C++ | linzhongkai/HowToLearnCPP | /LeetCode-Middle/multiplyString1.cpp | UTF-8 | 1,637 | 3.28125 | 3 | [] | no_license | class Solution {
public:
string multiply(string num1, string num2) {
string result1 = "", result2 = "";
int carry =0;
int count = 0;
for(int i = num2.size() - 1; i >= 0; i--, count++){
result1.clear();
int carry =0;
int y = num2[i] - '0';
for(int j = num1.size() - 1; j >= 0; j--){
int x = num1[j] - '0';
int multi = x * y + carry;
result1.push_back('0' + multi % 10);
carry = multi / 10;
}
if(carry != 0){ //处理最后一个进位
result1.push_back('0' + carry);
}
reverse(result1.begin(), result1.end());
for(int k = 0; k < count; k++){ //移位
result1.push_back('0');
}
result2 = addStrings(result2, result1);
}
if(result2[0] == '0'){ //处理结果为0的问题
result2.clear();
result2.push_back('0');
}
return result2;
}
string addStrings(string num1, string num2) {
int i = num1.size() - 1;
int j = num2.size() - 1;
int add = 0;
int carry = 0;
string result;
while(i >= 0 || j >= 0){
int x = i >= 0 ? num1[i] - '0' : 0;
int y = j >= 0 ? num2[j] - '0' : 0;
add = x + y + carry;
result.push_back('0' + add % 10);
carry = add / 10;
i--;
j--;
}
if(carry != 0){ //处理最后一个进位
result.push_back('0' + carry);
}
reverse(result.begin(), result.end()); //翻转
return result;
}
};
| true |
88e4d2404d57bcb26600323edfe3a3580da79c5f | C++ | bdumitriu/playground | /university-work/utcn/sisteme de operare/linux/so/include/driver/BlockMap.h | UTF-8 | 11,555 | 2.921875 | 3 | [] | no_license | /*
* Project: File System Simulator
* Author: Bogdan DUMITRIU
* E-mail: bdumitriu@bdumitriu.ro
* Date: Sat Nov 9 2002
* Description: This is the interface of the BlockMap class.
*/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef _BLOCK_MAP_H
#define _BLOCK_MAP_H
#include <stdlib.h>
#include <string.h>
#include <iostream.h>
#include "../defs.h"
#include "HDD.h"
#include "Inode.h"
#include "FileInputStream.h"
#include "FileOutputStream.h"
#include "../utils/Utils.h"
#include "../exceptions/ArrayIndexOutOfBoundsException.h"
#include "../exceptions/HardDiskNotInitializedException.h"
#include "../exceptions/InvalidBlockNumberException.h"
#include "../exceptions/IOException.h"
/**
* This class represents an interface to the structures on the hard
* disk containing the blocks bitmap. It allows easy manipulation of
* this bitmap (finding free blocks, allocating blocks, freeing blocks,
* etc.). Here's the configuration of the blocks bitmap file which
* this class assumes:
*
* <table border="1" align="center">
* <caption>Blocks bitmap file configuration</caption>
* <tr>
* <td align="center" bgcolor="cyan">16 bytes</td>
* <td align="center" bgcolor="cyan">4 bytes</td>
* <td align="center" bgcolor="cyan">nr. of non system blocks <u>bits</u></td>
* </tr>
* <tr>
* <td align="center" bgcolor="lightblue">checksum</td>
* <td align="center" bgcolor="lightblue">total number of non system blocks on hard disk</td>
* <td align="center" bgcolor="lightblue">blocks bitmap</td>
* </tr>
* </table>
*
* The blocks bitmap contains, say, n bits. Then the bitmap holds
* information regarding a exactly n blocks (one bit/block). If the bit
* is 1, then the block is allocated (i.e. is used by a file/directory);
* if the bit is 0, then the block is free for use. The actual number of
* bits which represent blocks is given by the second element in the block
* (the number of non system blocks).
*
* @short Represents an interface to the hard disk's structure containg the blocks bitmap.
* @author Bogdan DUMITRIU
* @version 0.1
*/
/*
* The blocks bitmap file configuration is:
*
* +----------+--------------------------+--------------------------------------+
* | 16 bytes | 4 bytes | nr. of non system blocks * 8 *bits* |
* +----------+--------------------------+--------------------------------------+
* | checksum | nr. of non system blocks | the blocks bitmap |
* +----------+--------------------------+--------------------------------------+
*
*/
class BlockMap
{
public:
/**
* Creates a new BlockMap. <code>hdd</code> will be used to perform
* read/write operations when the class' methods are called.
*
* @param hdd the hard disk which will be used for read/write operations.
*/
BlockMap(HDD* hdd);
/**
* The destructor of the class. This destructor does not free
* the <code>hdd</code>.
*/
~BlockMap();
/**
* Returns the value of the blocks bitmap file's checksum.
*
* The method throws:
* <ul>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*
* @return the value of the blocks bitmap file's checksum.
*/
unsigned char* getChecksum()
throw(HardDiskNotInitializedException*, IOException*, InvalidBlockNumberException*);
/**
* Returns the value of the blocks bitmap file's number of non system blocks.
*
* The method throws:
* <ul>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*
* @return the value of the blocks bitmap file's number of non system blocks.
*/
unsigned long getNrOfBlocks()
throw(HardDiskNotInitializedException*, IOException*, InvalidBlockNumberException*);
/**
* Changes the value of the blocks bitmap file's checksum to
* <code>checksum</code>.
*
* The method throws:
* <ul>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*
* @param checksum the new value of the checksum.
*/
void setChecksum(unsigned char* checksum)
throw(HardDiskNotInitializedException*, IOException*, InvalidBlockNumberException*);
/**
* Changes the value of the blocks bitmap file's number of non
* system blocks to <code>nrOfBlocks</code>.
*
* The method throws:
* <ul>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*
* @param nrOfBlocks the new value of the number of non system blocks.
*/
void setNrOfBlocks(unsigned long nrOfBlocks)
throw(HardDiskNotInitializedException*, IOException*, InvalidBlockNumberException*);
/**
* Returns true if the <code>index</code>th bit of the bitmap
* is 0 and false if it is 1.
*
* The method throws:
* <ul>
* <li> ArrayIndexOutOfBoundsException* if index is less than 0 (which
* is rather hard since it's an unsigned long) or greater than or
* equal to NR_OF_BLOCKS-FILEATTR_AREA_START_ADDR-MAX_NO_FILEATTR.</li>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*
* @return true if the <code>index</code>th bit is 0 and false
* if it is 1.
*/
bool isFree(unsigned long index) throw(
ArrayIndexOutOfBoundsException*,
HardDiskNotInitializedException*,
IOException*,
InvalidBlockNumberException*);
/**
* Sets the <code>index</code>th bit of the bitmap to 1.
*
* The method doesn't make any checks too see if the block isn't
* already allocated. You should make sure of that yourself.
*
* The method throws:
* <ul>
* <li> ArrayIndexOutOfBoundsException* if index is less than 0 (which
* is rather hard since it's an unsigned long) or greater than or
* equal to 8*include/defs.h::NR_OF_BLOCKS-FILEATTR_AREA_START_ADDR-MAX_NO_FILEATTR.</li>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*/
void allocBlock(unsigned long index) throw(
ArrayIndexOutOfBoundsException*,
HardDiskNotInitializedException*,
IOException*,
InvalidBlockNumberException*);
/**
* Allocates each of the blocks in the <code>blocks</code> array by
* setting its corresponding bit to 1. <code>nr</code> represents the
* number of blocks to allocated. Therefore, blocks should contain at
* least <code>nr</code> valid entries.
*
* The method doesn't make any checks too see if the blocks aren't
* already allocated. You should make sure of that yourself.
*
* The method throws:
* <ul>
* <li> ArrayIndexOutOfBoundsException* if any of the blocks is less
* than 0 (which is rather hard since they're unsigned longs) or greater
* than or equal to 8*include/defs.h::NR_OF_BLOCKS-FILEATTR_AREA_START_ADDR-MAX_NO_FILEATTR.</li>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*/
void allocBlocks(unsigned long* blocks, unsigned long nr) throw(
ArrayIndexOutOfBoundsException*,
HardDiskNotInitializedException*,
IOException*,
InvalidBlockNumberException*);
/**
* Sets the <code>index</code>th bit of the bitmap to 0.
*
* The method throws:
* <ul>
* <li> ArrayIndexOutOfBoundsException* if index is less than 0 (which
* is rather hard since it's an unsigned long) or greater than or
* equal to 8*include/defs.h::NR_OF_BLOCKS-FILEATTR_AREA_START_ADDR-MAX_NO_FILEATTR.</li>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*/
void freeBlock(unsigned long index) throw(
ArrayIndexOutOfBoundsException*,
HardDiskNotInitializedException*,
IOException*,
InvalidBlockNumberException*);
/**
* Returns the index of a free bitmap position (i.e. one whose value
* is 0). This method takes the nr. of non system blocks into account,
* meaning it only searches for a free bit up to (this number-1)th bit.
* If no free positions exist, the method returns the same value
* getNrOfBlocks() would return => you can check if you still have free
* bytes or not by comparing the return value received with the return
* value of getNrOfBlocks(). If they are identical, it means the hard
* disk is full (i.e. no more free non system blocks are available).
*
* The method throws:
* <ul>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*
* @return the index of a free bitmap position (i.e. one whose value is 0).
*/
unsigned long getFreeBlock()
throw(HardDiskNotInitializedException*, IOException*, InvalidBlockNumberException*);
/**
* Searches for a number of <code>nr</code> free blocks and writes their
* addresses in the <code>freeBlocks</code> array. Therefore, <code>freeBlocks</code>
* should have enough space to store at least a number of <code>nr</code>
* unsigned longs. This method takes the nr. of non system blocks into account,
* meaning it only searches for free bits up to (this number-1)th bit. The
* method returns the number of free blocks found. This means that the first
* that many entries in freeBlocks are addresses of actual free blocks.
*
* The method throws:
* <ul>
* <li> HardDiskNotInitializedException* forwarded from <code>hdd</code>.</li>
* <li> IOException* forwarded from <code>hdd</code>.</li>
* <li> InvalidBlockNumberException* forwarded from <code>hdd</code>.</li>
* </ul>
*
* @return the the number of free blocks found.
*/
unsigned long getFreeBlocks(unsigned long* freeBlocks, unsigned long nr)
throw(HardDiskNotInitializedException*, IOException*, InvalidBlockNumberException*);
private:
HDD* hdd; /* the hard disk used for read/write operations */
FileInputStream* fis; /* the file input stream used to read the file */
FileOutputStream* fos; /* the file output stream used to write the file */
Inode* fbInode; /* the inode holding information about the blocks bitmap file */
};
#endif
| true |
d84c0f1d23fae672b1f1b3efbbc6276c19859858 | C++ | sriharishekhar/Codeforces | /SinglePush.cpp | UTF-8 | 687 | 3.421875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void CheckEqual(int a[0], int b[0]) {
}
void SinglePush(int n) {
int size;
for (int i = 0; i < n; i++) {
cout << "Enter Size of array" << endl;
cin >> size;
int a[size];
int b[size];
for (int j = 0; j < size; j++) {
cin >> a[j];
}
for (int j = 0; j < size; j++) {
cin >> b[j];
}
for (int j = 0; j < size; j++) {
cout << a[j] << " ";
}
cout << endl;
for (int j = 0; j < size; j++) {
cout << b[j] << " ";
}
cout << endl;
CheckEqual(&a, &b);
}
}
int main() {
int n;
cout << "Enter # times" << endl;
cin >> n;
SinglePush(n);
return 0;
} | true |
133a56dc4dbef3fe04601e868f5f445ba34f97e0 | C++ | oha-yashi/cpplibs | /modpow.cpp | UTF-8 | 514 | 3.171875 | 3 | [] | no_license | /*
modpow(a, n, p) = a^n mod(p)
繰り返し2乗法
*/
#include <bits/stdc++.h>
using namespace std;
#define LIMIT 1000000007 //10^9+7
long long modpow(long long a, long long n, long long p){
if(n==1) return a % p;
if(n%2 == 1) return (a * modpow(a, n-1, p)) % p;
long long t = modpow(a, n/2, p);
return t * t % p;
}
/*
使える場面
Z = X/Y
Z mod(LIMIT) = X/Y mod(LIMIT)
Y * Y^LIMIT-2 mod(LIMIT) = 1 フェルマーの小定理
Y^LIMIT-2 mod(LIMIT) = 1/Y
>> Z mod(LIMIT) = X * Y^LIMIT-2 mod(LIMIT)
*/ | true |
0a9d6e3ced1120b722cd212a7f3b7b05e1b842d6 | C++ | bg1bgst333/Sample | /winapi/PathFindFileName/PathFindFileName/src/PathFindFileName/PathFindFileName/PathFindFileName.cpp | SHIFT_JIS | 953 | 2.8125 | 3 | [
"MIT"
] | permissive | // wb_t@C̃CN[h
#include <windows.h> // WWindowsAPI
#include <tchar.h> // TCHAR^
#include <stdio.h> // Wo
#include <shlwapi.h> // VFAPI
// _tmain̒`
int _tmain(int argc, TCHAR *argv[]){ // mainTCHAR.
// R}hC̐.
_tprintf(_T("argc = %d\n"), argc); // argco.
if (argc != 2){ // 2ȊO̓G[.
_tprintf(_T("error: argc != 2\n")); // "error: argc != 2"Əo.
return -1; // -1ԂĈُI.
}
// pXt@C𒊏o.
TCHAR *ptszFileName = NULL; // t@CwTCHAR^|C^ptszFileNameNULLŏ.
ptszFileName = PathFindFileName(argv[1]); // PathFindFileNameargv[1]̃t@C𒊏o.
_tprintf(_T("ptszFileName = %s\n"), ptszFileName); // ptszFileNameo.
// vȌI.
return 0; // 0ԂĐI.
} | true |
b79fce98086a0e9335b62d362511b1b601294bfe | C++ | Eddie02582/Leetcode | /C++/1779. Find Nearest Point That Has the Same X or Y Coordinate.cpp | UTF-8 | 613 | 2.875 | 3 | [] | no_license | class Solution {
public:
int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
ios::sync_with_stdio(false); cin.tie(nullptr);
int index = -1;
int distance = 9999;
for(int i = 0; i < points.size();i++){
if(x == points[i][0] || y == points[i][1]){
int temp = abs(y - points[i][1]) + abs(x - points[i][0]);
if(temp < distance){
index = i;
distance = temp;
}
}
}
return index;
}
}; | true |
542d486d978d48134cd3325ed531edc21495c13b | C++ | tarvainen/rodent | /src/EEPROMWriter.cpp | UTF-8 | 404 | 2.828125 | 3 | [] | no_license | #include "EEPROMWriter.h"
/*
Reads an Rodent status object from EEPROM memory.
*/
StatusObject EEPROMWriter::read() {
StatusObject status;
EEPROM.get(0, status);
return status;
}
/*
Writes the given Rodent status object to the EEPROM memory.
*/
void EEPROMWriter::write(StatusObject statusObject) {
EEPROM.put(0, statusObject);
}
/*
Dumps the EEPROM memory.
*/
void EEPROMWriter::dumpMemory() {
} | true |
44c7d3d3eac997d815b3d8ddf1c06e2b6dbaf175 | C++ | rheineke/cpp-iem | /test/iem/message_test.cpp | UTF-8 | 2,293 | 3.015625 | 3 | [
"MIT"
] | permissive | // Copyright 2016 Reece Heineke<reece.heineke@gmail.com>
#include "iem/message.hpp"
#include "gtest/gtest.h"
namespace iem {
TEST(TraderMessageTest, MessageType) {
// Serialization
EXPECT_EQ(to_string(MessageType::ORDER), "Order");
EXPECT_EQ(to_string(MessageType::ORDER_RESOLUTION), "Order Resolution");
// Deserialization
EXPECT_EQ(message_type_from_string("Order"), MessageType::ORDER);
EXPECT_EQ(message_type_from_string("Order Resolution"),
MessageType::ORDER_RESOLUTION);
EXPECT_THROW(message_type_from_string("foo"), std::invalid_argument);
}
TEST(TraderMessageTest, Action) {
// Serialization
EXPECT_EQ(to_string(Action::BUY), "Buy");
EXPECT_EQ(to_string(Action::SELL), "Sell");
EXPECT_EQ(to_string(Action::ASK_ENTERED), "Ask entered");
EXPECT_EQ(to_string(Action::BID_ENTERED), "Bid entered");
EXPECT_EQ(to_string(Action::FIXED_BUNDLE_PURCHASE_EXECUTED),
"Fixed bundle purchase executed");
EXPECT_EQ(to_string(Action::FIXED_BUNDLE_SALE_EXECUTED),
"Fixed bundle sale executed");
EXPECT_EQ(to_string(Action::MARKET_BUNDLE_PURCHASE_EXECUTED),
"Market bundle purchase executed");
EXPECT_EQ(to_string(Action::MARKET_BUNDLE_SALE_EXECUTED),
"Market bundle sale executed");
// Deserialization
EXPECT_EQ(action_from_string("Buy"), Action::BUY);
EXPECT_EQ(action_from_string("Sell"), Action::SELL);
EXPECT_EQ(action_from_string("Ask entered"), Action::ASK_ENTERED);
EXPECT_EQ(action_from_string("Bid entered"), Action::BID_ENTERED);
EXPECT_EQ(action_from_string("Fixed bundle purchase executed"),
Action::FIXED_BUNDLE_PURCHASE_EXECUTED);
EXPECT_EQ(action_from_string("Buy Fixed Price Bundle"),
Action::FIXED_BUNDLE_PURCHASE_EXECUTED);
EXPECT_EQ(action_from_string("Sell Fixed Price Bundle"),
Action::FIXED_BUNDLE_SALE_EXECUTED);
}
TEST(TraderMessageTest, TradeMessageDateFromString) {
const boost::gregorian::date d(2016, boost::gregorian::Nov, 28);
const boost::posix_time::time_duration t(19, 19, 30, 613000);
const boost::posix_time::ptime expected_dt(d, t);
const auto dt = date_from_string("2016-11-28 19:19:30.613");
EXPECT_EQ(dt, expected_dt);
}
TEST(TraderMessageTest, Quantity) {
EXPECT_NO_THROW(std::stoi("1.000000"));
}
} // namespace iem
| true |
96f71bc8b8f1a7dffbd15181e8c817968cd22a8b | C++ | ArnaudValensi/2d-game-engine-cpp-opengl | /src/Spritesheet.cpp | UTF-8 | 1,462 | 2.90625 | 3 | [] | no_license | #include "Spritesheet.h"
#include "debug.h"
#include <fstream>
#include <iostream>
#include <map>
#include <nlohmann/json.hpp>
void Spritesheet::Create(std::string file) {
std::string texture_path = file + ".png";
std::string json_path = file + ".json";
m_Texture = std::make_unique<Texture>("./assets/spritesheets/main.png", true);
// IMPROVEMENT: Check json validity.
LoadJsonInfo(json_path);
}
void Spritesheet::LoadJsonInfo(const std::string& json_path) {
glm::ivec2 texture_size = m_Texture->GetSize();
// Create the sprites base on the json.
std::ifstream i(json_path);
nlohmann::json j;
i >> j;
auto frames = j["frames"];
if (frames.empty()) {
PANIC("Spritesheet json is missing the 'frames' key");
}
for (auto& it : frames) {
auto frame = it;
auto filename = frame["filename"].get<std::string>();
auto position = frame["frame"];
int x = position["x"].get<int>();
int y = position["y"].get<int>();
int width = position["w"].get<int>();
int height = position["h"].get<int>();
if (x < 0 || x + width > texture_size.x || y < 0 || y + height > texture_size.y) {
PANIC("The sprite '%s' defined in the json spritesheet has a wrong positioning\n",
filename.c_str());
}
m_Sprites.insert({filename, Sprite(m_Texture.get(), x, y, width, height)});
}
}
const Sprite& Spritesheet::GetSprite(const std::string& sprite_name) {
return m_Sprites.at(sprite_name);
}
| true |
cc16854be42528aaf881fe7baf35762f3101e6cf | C++ | Honza0297/ETUAR | /src/release/University(VS)/Done/trilobot/display.h | UTF-8 | 2,516 | 2.828125 | 3 | [] | no_license | /************************************************ */
/* Educational tutorial for Arduino in robotics */
/* Vyukovy Tutorial pro pouziti Arduina v robotice*/
/* File: display.h */
/* Author: Jan Beran */
/* Date: March 2020 */
/* */
/* This file is a part of author´s bachelor thesis*/
/* */
/**************************************************/
#ifndef _DISPLAY16X2_H
#define _DISPLAY16X2_H 1
#include "LiquidCrystal_I2C.h"
#define DISPLAY_ENABLE true
/* Adresa displeje muze byt ruzna*/
#define DISPLAY_ADDRESS_PRIMARY 0x3F
#define DISPLAY_ADDRESS_FALLBACK 0x20 //nebo cokoli 0x20 az 0x27
#define DISPLAY_ADDRESS DISPLAY_ADDRESS_PRIMARY
/**
* @brief Trida/wrapper pro I2C displej.
* Cilem je maximalni zjedndueni prace s displejemi za cenu velmi omezeneho vyuziti.
* */
class Display
{
public:
/**
* @brief Inicializuje instanci LiquidCrystal_I2C displeje a pripravi ho k pouziti.
*/
Display();
/**
* @brief Smaze prvni radek a vytiskne pozadovanou promennou.
* Co je template? jednoducha pomucka z C++. Jelikoz chci tisknout X datovych typu, udelam si "sablonu",
* diky ktere mohu vytisknout libovolny datovy typ (ktery podporuje i obaleny displej).
* */
template <typename T> void print_first_line(const T to_print)
{
display->setCursor(0,0);
display->print(" "); //emuluje smazani jednoho radku
display->setCursor(0,0);
display->print(to_print);
}
/**
* @brief Smaze druhy radek a vytiskne pozadovanou promennou.
* Co je template? jednoducha pomucka z C++. Jelikoz chci tisknout X datovych typu, udelam si "sablonu",
* diky ktere mohu vytisknout libovolny datovy typ (ktery podporuje i obaleny displej).
* */
template <typename T> void print_second_line(const T to_print)
{
display->setCursor(0,1);
display->print(" "); //emuluje smazani jednoho radku
display->setCursor(0,1);
display->print(to_print);
}
/**
* @brief Vymaze cely displej.
* */
void clear();
private:
/** Displej, ktery je touto tridou obalovan */
LiquidCrystal_I2C *display;
};
#endif | true |
5f2d1b84f6c46d40883a7859847d4ffe1c88f511 | C++ | Bkohler93/hunt_the_wumpus | /adventurer.h | UTF-8 | 928 | 3.34375 | 3 | [] | no_license | #ifndef ADVENTURER_H
#define ADVENTURER_H
#include <iostream>
class Adventurer
{
private:
int map_size;
int num_arrows;
bool has_gold;
int x, y;
public:
/* constructors */
Adventurer(int map_size, int x, int y) :
map_size{map_size}, num_arrows{3}, has_gold{false}, x{x}, y{y} {}
Adventurer() : map_size{0}, num_arrows{3}, has_gold{false}, x{0}, y{0} {}
/* setters */
void set_map_size(int);
void set_num_arrows(int);
void set_has_gold(bool);
void set_x(int);
void set_y(int);
void set_x_y(int, int);
/* getters */
int get_map_size() const;
int get_num_arrows() const;
bool get_has_gold() const;
int get_x() const;
int get_y() const;
/* mutators */
void adventurer_shoots(); //decreases arrow count by 1
void pick_up_gold(); //sets has_gold to true;
void move_north();
void move_south();
void move_east();
void move_west();
void change_x(int);
void change_y(int);
void stay();
};
#endif | true |
28492ed4997e3ed426b73861934c3e1d74eeaeed | C++ | xoyowade/solutions | /leetcode/63_unique_paths2.cpp | UTF-8 | 1,276 | 2.8125 | 3 | [] | no_license | class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > &grid = obstacleGrid;
vector<vector<int> > count_grid;
int num_rows = grid.size();
int num_cols = grid[0].size();
for (int i = 0; i < num_rows; i++) {
vector<int> count_line(num_cols, 0);
count_grid.push_back(count_line);
}
for (int i = num_rows-1; i >= 0; i--) {
for (int j = num_cols-1; j >= 0; j--) {
if (grid[i][j] == 1) {
count_grid[i][j] = 0;
} else {
bool is_end = true;
int down = 0, right = 0;
if (j < num_cols-1) {
right = count_grid[i][j+1];
is_end = false;
}
if (i < num_rows-1) {
down = count_grid[i+1][j];
is_end = false;
}
count_grid[i][j] = is_end ? 1 : right + down;
}
}
}
return count_grid[0][0];
}
};
| true |
163808b0b155a717b67db37cade2e9ad9cdc52b8 | C++ | SammyEnigma/Soc-Performance-Evaluation | /mainwindow.cpp | UTF-8 | 19,254 | 2.546875 | 3 | [] | no_license | /*
* @Author: MRXY001
* @Date: 2019-11-27 18:00:02
* @LastEditors : MRXY001
* @LastEditTime : 2019-12-23 10:00:17
* @Description: 主窗口
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "xlsxdocument.h"
#include "xlsxworksheet.h"
#include "xlsxcellrange.h"
#include "xlsxsheetmodel.h"
#include <QScrollBar>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow), flow_control(nullptr)
{
log("初始化MainWindow");
ui->setupUi(this);
setWindowState(Qt::WindowMaximized);
initSystem();
initView();
initData();
log("初始化MainWindow结束");
}
MainWindow::~MainWindow()
{
delete ui;
}
/**
* 保存绘制的形状到文件,以便下次读取
* @param file_path 文件路径
*/
void MainWindow::saveToFile(QString file_path)
{
log("保存至文件:" + file_path);
QString full_string;
full_string += StringUtil::makeXml(ui->scrollArea->horizontalScrollBar()->sliderPosition(), "SCROLL_HORIZONTAL");
full_string += "\n" + StringUtil::makeXml(ui->scrollArea->verticalScrollBar()->sliderPosition(), "SCROLL_VERTICAL");
full_string += "\n" + StringUtil::makeXml(ui->scrollAreaWidgetContents_2->width(), "GRAPHIC_WIDTH");
full_string += "\n" + StringUtil::makeXml(ui->scrollAreaWidgetContents_2->height(), "GRAPHIC_HEIGHT");
full_string += "\n" + ui->scrollAreaWidgetContents_2->toString();
FileUtil::writeTextFile(file_path, full_string);
}
/**
* 从XML文件中读取形状实例,并且在绘图区域中绘制
* @param file_path 文件路径
*/
void MainWindow::readFromFile(QString file_path)
{
log("从文件读取:" + file_path);
QString full_string = FileUtil::readTextFileIfExist(file_path);
if (full_string.trimmed().isEmpty())
return;
ui->scrollAreaWidgetContents_2->clearAll();
int graphic_width = StringUtil::getXmlInt(full_string, "GRAPHIC_WIDTH");
int graphic_height = StringUtil::getXmlInt(full_string, "GRAPHIC_HEIGHT");
if (graphic_width != 0 && graphic_height != 0)
ui->scrollAreaWidgetContents_2->setFixedSize(graphic_width, graphic_height);
int scroll_h = StringUtil::getXmlInt(full_string, "SCROLL_HORIZONTAL");
int scroll_v = StringUtil::getXmlInt(full_string, "SCROLL_VERTICAL");
if (scroll_h != 0 || scroll_v != 0)
{
QTimer::singleShot(0, [=] { // 不知道为什么必须要延迟才可以滚动,不如不生效(可能是上限没有改过来?)
ui->scrollArea->horizontalScrollBar()->setSliderPosition(scroll_h);
ui->scrollArea->verticalScrollBar()->setSliderPosition(scroll_v);
});
}
// 从文件中恢复形状
QStringList shape_string_list = StringUtil::getXmls(full_string, "SHAPE");
foreach (QString shape_string, shape_string_list)
{
QString name = StringUtil::getXml(shape_string, "CLASS");
// 创建形状实例
ShapeBase *type = ui->listWidget->getShapeByName(name);
if (type == nullptr) // 没有找到这个类,可能后期被删掉了
{
log("无法找到形状类:" + name);
continue;
}
ShapeBase *shape = ui->scrollAreaWidgetContents_2->insertShapeByType(type, QPoint(0, 0));
shape->fromString(shape_string);
if (StringUtil::getXmlInt(shape_string, "SELECTED") != 0)
ui->scrollAreaWidgetContents_2->select(shape, true);
}
// 遍历连接(因为需要等port全部加载完成后)
QMap<QString, PortBase *> ports = ui->scrollAreaWidgetContents_2->ports_map;
foreach (ShapeBase *shape, ui->scrollAreaWidgetContents_2->shape_lists)
{
if (shape->getLargeType() == CableType) // 线的连接
{
CableBase *cable = static_cast<CableBase *>(shape);
QString portID1 = StringUtil::getXml(cable->readedText(), "FROM_PORT_ID");
QString portID2 = StringUtil::getXml(cable->readedText(), "TO_PORT_ID");
if (portID1.isEmpty() || portID2.isEmpty())
{
ERR("有线未进行连接:端口:" + portID1 + ", " + portID2)
continue;
}
if (!ports.contains(portID1) || !ports.contains(portID2))
{
ERR("不存在连接ID,两端口:" + portID1 + ", " + portID2)
continue;
}
cable->setPorts(ports.value(portID1), ports.value(portID2));
cable->adjustGeometryByPorts();
ui->scrollAreaWidgetContents_2->cable_lists.append(cable);
}
else if (shape->getClass() == "WatchModule") // 监视控件
{
// 恢复监视的端口
}
}
// 其他操作
// ui->scrollAreaWidgetContents_2->setMinimumSize(widthest, heightest);
}
void MainWindow::showEvent(QShowEvent *event)
{
restoreGeometry(us->getVar("window/geometry").toByteArray());
restoreState(us->getVar("window/state").toByteArray());
QMainWindow::showEvent(event);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
us->setVal("window/geometry", saveGeometry());
us->setVal("window/state", saveState());
QMainWindow::closeEvent(event);
}
/**
* 初始化整个系统
* 比如初始化目录结构
*/
void MainWindow::initSystem()
{
FileUtil::ensureDirExist(rt->DATA_PATH);
FileUtil::ensureDirExist(rt->SHAPE_PATH);
rt->log_filter = us->getStr("recent/log_filter", "");
}
/**
* 初始化布局
*/
void MainWindow::initView()
{
// 和数据挂钩的设置
ui->actionToken_Animation->setChecked(us->show_animation);
ui->actionAuto_Watch_Port->setChecked(us->port_auto_watch);
// 连接绘图区域信号槽
connect(ui->scrollAreaWidgetContents_2, &GraphicArea::signalScrollToPos, this, [=](int x, int y) {
if (x != -1)
ui->scrollArea->horizontalScrollBar()->setSliderPosition(x);
if (y != -1)
ui->scrollArea->verticalScrollBar()->setSliderPosition(y);
});
connect(ui->scrollAreaWidgetContents_2, &GraphicArea::signalEnsurePosVisible, this, [=](int x, int y) {
if (x < ui->scrollArea->horizontalScrollBar()->sliderPosition())
ui->scrollArea->horizontalScrollBar()->setSliderPosition(x);
else if (x > ui->scrollArea->horizontalScrollBar()->sliderPosition() + ui->scrollArea->width())
ui->scrollArea->horizontalScrollBar()->setSliderPosition(x - ui->scrollArea->width());
if (y < ui->scrollArea->verticalScrollBar()->sliderPosition())
ui->scrollArea->verticalScrollBar()->setSliderPosition(y);
else if (y > ui->scrollArea->verticalScrollBar()->sliderPosition() + ui->scrollArea->height())
ui->scrollArea->verticalScrollBar()->setSliderPosition(y - ui->scrollArea->height());
});
connect(ui->scrollAreaWidgetContents_2, &GraphicArea::signalScrollAreaScroll, this, [=](int h, int v) {
if (h)
ui->scrollArea->horizontalScrollBar()->setSliderPosition(ui->scrollArea->horizontalScrollBar()->sliderPosition() + h);
if (v)
ui->scrollArea->verticalScrollBar()->setSliderPosition(ui->scrollArea->verticalScrollBar()->sliderPosition() + v);
});
connect(ui->scrollAreaWidgetContents_2, SIGNAL(signalSave()), this, SLOT(on_actionSave_triggered()));
connect(ui->scrollAreaWidgetContents_2, &GraphicArea::signalAutoSave, this, [=] {
if (us->auto_save)
on_actionSave_triggered();
});
connect(ui->scrollAreaWidgetContents_2, &GraphicArea::signalTurnBackToPointer, this, [=] {
if (us->drag_shape_auto_return)
ui->listWidget->recoverDragPrevIndex(); // 实现绘制完一个模块后调色板上的选项回到先前位置
});
connect(ui->scrollAreaWidgetContents_2, SIGNAL(signalSelectedChanged(ShapeList)), ui->tab, SLOT(loadShapesDatas(ShapeList)));
}
/**
* 初始化数据
* (自动读取上次打开的文件)
*/
void MainWindow::initData()
{
// 读取形状
graphic_file_path = us->getStr("recent/open_path");
if (graphic_file_path.isEmpty())
graphic_file_path = rt->DATA_PATH + "graphic.xml";
readFromFile(graphic_file_path);
// 恢复额外数据
QString filePath = us->getStr("recent/csv_path");
QDir dir(filePath);
foreach (auto file, dir.entryInfoList())
{
if(file.isFile())
{
rt->current_package_rows.insert(file.baseName(), 0);
rt->package_tables.insert(file.baseName(), CSVTool::getCSV(FileUtil::readTextFile(file.absoluteFilePath())));
}
}
us->data_mode = static_cast<DataPattern>(us->getInt("us/data_mode"));
// 设置菜单
if(us->data_mode == Trace)
{
ui->actionTrace_T->setChecked(true);
}
else if(us->data_mode == Fix)
{
ui->actionFix_F->setChecked(true);
}
else if(us->data_mode == Random)
{
ui->actionRandom_R->setChecked(true);
}
// us->watchmodule_visible = us->getBool("us/watchmodule_visible");
us->watchmodule_visible = ui->scrollAreaWidgetContents_2->areIPsAndDRAMsAllWatched();
ui->actionWatchModule_Show_S->setChecked(us->watchmodule_visible);
}
void MainWindow::on_actionSave_triggered()
{
saveToFile(graphic_file_path);
}
/**
* 放大界面
*/
void MainWindow::on_actionZoom_In_I_triggered()
{
double prop = 1.25;
QRect geo = ui->scrollAreaWidgetContents_2->geometry(); // 保存旧的大小
ui->scrollAreaWidgetContents_2->zoomIn(prop);
// 调整滚动条的位置
ui->scrollArea->horizontalScrollBar()->setSliderPosition(ui->scrollArea->horizontalScrollBar()->sliderPosition() + static_cast<int>(geo.width() * (prop - 1) / 2));
ui->scrollArea->verticalScrollBar()->setSliderPosition(ui->scrollArea->verticalScrollBar()->sliderPosition() + static_cast<int>(geo.height() * (prop - 1) / 2));
}
/**
* 缩小界面
*/
void MainWindow::on_actionZoom_Out_O_triggered()
{
double prop = 0.8;
QRect geo = ui->scrollAreaWidgetContents_2->geometry(); // 保存旧的大小
ui->scrollAreaWidgetContents_2->zoomIn(prop);
// 调整滚动条的位置
ui->scrollArea->horizontalScrollBar()->setSliderPosition(ui->scrollArea->horizontalScrollBar()->sliderPosition() + static_cast<int>(geo.width() * (prop - 1) / 2));
ui->scrollArea->verticalScrollBar()->setSliderPosition(ui->scrollArea->verticalScrollBar()->sliderPosition() + static_cast<int>(geo.height() * (prop - 1) / 2));
}
void MainWindow::on_actionRun_triggered()
{
log("MainWindow::on_actionRun_triggered()");
if (flow_control != nullptr)
flow_control->deleteLater();
// flow_control = new FlowControl_Master1_Slave1(ui->scrollAreaWidgetContents_2, this);
// flow_control = new FlowControl_Master2_Switch_Slave2(ui->scrollAreaWidgetContents_2, this);
flow_control = new FlowControlAutomatic(ui->scrollAreaWidgetContents_2, this);
flow_control->startRun();
ui->actionRun->setVisible(false);
ui->actionStop->setVisible(true);
ui->actionStop->setEnabled(true);
ui->actionPause_P->setVisible(true);
ui->actionPause_P->setEnabled(true);
ui->actionResume_S->setVisible(false);
ui->actionStep->setEnabled(true);
ui->actionTen_Step_T->setEnabled(true);
ui->actionGo_To->setEnabled(true);
ui->actionFaster->setEnabled(true);
ui->actionSlower->setEnabled(true);
connect(flow_control, &FlowControlBase::signalOneClockPassed, this, [=] {
ui->plainTextEdit->setPlainText(rt->running_out.join("\n"));
ui->plainTextEdit->verticalScrollBar()->setSliderPosition(ui->plainTextEdit->verticalScrollBar()->maximum());
});
}
void MainWindow::on_actionPause_P_triggered()
{
flow_control->pauseRun();
ui->actionPause_P->setVisible(false);
ui->actionResume_S->setVisible(true);
}
void MainWindow::on_actionStep_triggered()
{
flow_control->nextStep();
}
void MainWindow::on_actionResume_S_triggered()
{
flow_control->resumeRun();
ui->actionResume_S->setVisible(false);
ui->actionPause_P->setVisible(true);
}
void MainWindow::on_actionDebug_triggered()
{
flow_control->printfAllData();
}
void MainWindow::on_actionStop_triggered()
{
flow_control->stopRun();
ui->actionRun->setVisible(true);
ui->actionStop->setVisible(false);
ui->actionPause_P->setVisible(true);
ui->actionPause_P->setEnabled(false);
ui->actionResume_S->setVisible(false);
ui->actionStep->setEnabled(false);
ui->actionTen_Step_T->setEnabled(false);
ui->actionGo_To->setEnabled(false);
ui->actionFaster->setEnabled(false);
ui->actionSlower->setEnabled(false);
flow_control->deleteLater();
flow_control = nullptr;
}
void MainWindow::on_actionSelect_All_triggered()
{
ui->scrollAreaWidgetContents_2->actionSelectAll();
}
void MainWindow::on_actionCopy_triggered()
{
ui->scrollAreaWidgetContents_2->actionCopy();
}
void MainWindow::on_actionPaste_triggered()
{
ui->scrollAreaWidgetContents_2->actionPaste();
}
void MainWindow::on_actionAbout_triggered()
{
QMessageBox::information(this, tr("芯片开发图形化"), tr("开发人员:王鑫益 蓝兴业\n指导老师:郑奇 张霞\n\nGithub:https://github.com/Graphical-SoC-Performance/Soc-Performance-Evaluation"));
}
void MainWindow::on_actionGithub_G_triggered()
{
QDesktopServices::openUrl(QUrl(QLatin1String("https://github.com/Graphical-SoC-Performance/Soc-Performance-Evaluation")));
}
void MainWindow::on_actionTen_Step_T_triggered()
{
for (int i = 0; i < 10; i++)
flow_control->nextStep();
}
void MainWindow::on_actionGo_To_triggered()
{
QString rst = QInputDialog::getText(this, "跳转", "请输入要跳转到的clock(int)\n若小于当前clock,将重新开始运行", QLineEdit::Normal, us->getStr("recent/go_to_clock"));
if (rst.trimmed().isEmpty())
return;
bool ok;
int i = rst.toInt(&ok);
if (!ok)
return;
us->setVal("recent/go_to_clock", rst);
// 跳转到这个clock
if (!flow_control)
on_actionRun_triggered();
flow_control->gotoClock(i);
}
void MainWindow::on_actionFaster_triggered()
{
flow_control->changeSpeed(0.8);
}
void MainWindow::on_actionSlower_triggered()
{
flow_control->changeSpeed(1.25);
}
void MainWindow::on_actionSet_Log_Filter_triggered()
{
bool ok;
QString text = QInputDialog::getText(this, "日志过滤器", "请输入过滤内容,支持正则表达式", QLineEdit::Normal, us->getStr("recent/log_filter", ""), &ok);
if (ok)
{
rt->log_filter = text;
us->setVal("recent/log_filter", text);
}
}
void MainWindow::on_lineEdit_editingFinished()
{
QString text = ui->lineEdit->text();
if (text.isEmpty())
return;
ui->lineEdit->clear();
system(text.toLocal8Bit());
}
void MainWindow::on_actionToken_Animation_triggered()
{
us->show_animation = !us->show_animation;
us->setVal("us/show_animation", us->show_animation);
ui->actionToken_Animation->setChecked(us->show_animation);
}
void MainWindow::on_actionShow_All_Dock_triggered()
{
ui->dockWidget->show();
ui->dockWidget_3->show();
ui->dockWidget_4->show();
}
void MainWindow::on_actionAuto_Watch_Port_triggered()
{
us->port_auto_watch = !us->port_auto_watch;
us->setVal("us/port_auto_watch", us->port_auto_watch);
ui->actionAuto_Watch_Port->setChecked(us->port_auto_watch);
}
void MainWindow::on_actionShow_Dock_Modules_triggered()
{
ui->dockWidget->show();
}
void MainWindow::on_actionShow_Dock_Properties_triggered()
{
ui->dockWidget_3->show();
}
void MainWindow::on_actionShow_Dock_Console_triggered()
{
ui->dockWidget_4->show();
}
void MainWindow::on_actionEdit_Database_E_triggered()
{
Xlsx_Edit::xlsx_edit();
}
void MainWindow::on_actionRead_CSV_C_triggered()
{
QString filePath = QFileDialog::getExistingDirectory(this, "Open Directory", QString("debug/data"));
if (filePath.isEmpty())
return ;
rt->current_package_rows.clear();
rt->package_tables.clear();
QDir dir(filePath);
foreach (auto file, dir.entryInfoList())
{
if(file.isFile())
{
rt->current_package_rows.insert(file.baseName(), 0);
rt->package_tables.insert(file.baseName(), CSVTool::getCSV(FileUtil::readTextFile(file.absoluteFilePath())));
}
}
us->setVal("recent/csv_path", filePath);
}
void MainWindow::on_actionTrace_T_triggered()
{
ui->actionTrace_T->setChecked(true);
ui->actionFix_F->setChecked(false);
ui->actionRandom_R->setChecked(false);
ui->actionNoneMode->setChecked(false);
us->data_mode = Trace;
us->setVal("us/data_mode", us->data_mode);
}
void MainWindow::on_actionFix_F_triggered()
{
ui->actionTrace_T->setChecked(false);
ui->actionFix_F->setChecked(true);
ui->actionRandom_R->setChecked(false);
ui->actionNoneMode->setChecked(false);
us->data_mode = Fix;
us->setVal("us/data_mode", us->data_mode);
}
void MainWindow::on_actionRandom_R_triggered()
{
ui->actionTrace_T->setChecked(false);
ui->actionFix_F->setChecked(false);
ui->actionRandom_R->setChecked(true);
ui->actionNoneMode->setChecked(false);
us->data_mode = Random;
us->setVal("us/data_mode", us->data_mode);
}
void MainWindow::on_actionWatchModule_Show_S_triggered()
{
us->watchmodule_visible = !us->watchmodule_visible;
ui->actionWatchModule_Show_S->setChecked(us->watchmodule_visible);
us->setVal("us/watchmodule_visible", us->watchmodule_visible);
if(us->watchmodule_visible)
{
ui->scrollAreaWidgetContents_2->slotWatchModuleShow();
}
else
{
ui->scrollAreaWidgetContents_2->slotWatchModuleHide();
}
}
void MainWindow::on_actionNew_triggered()
{
if (rt->running)
{
QMessageBox::critical(this, "警告", "正在运行中...\n\n请先停止正在运行的程序");
return ;
}
// 关闭原先文件
QString recent = us->getStr("recent/open_path", "");
QString path = QFileDialog::getSaveFileName(this, "选择打开的配置文件", recent, "*.xml");
if (path.isEmpty())
return ;
graphic_file_path = path;
us->setVal("recent/open_path", path);
// 清空
ui->scrollAreaWidgetContents_2->clearAll(); // 虽然读取时也会清空旧的但是……文件不存在的话,不会读取
readFromFile(path);
}
void MainWindow::on_actionOpen_triggered()
{
if (rt->running)
{
QMessageBox::critical(this, "警告", "正在运行中...\n\n请先停止正在运行的程序");
return ;
}
QString recent = us->getStr("recent/open_path", "");
QString path = QFileDialog::getOpenFileName(this, "选择打开的配置文件", recent, "*.xml");
if (path.isEmpty())
return ;
graphic_file_path = path;
us->setVal("recent/open_path", path);
// 打开这个配置文件
readFromFile(path);
}
void MainWindow::on_actionNoneMode_triggered()
{
ui->actionTrace_T->setChecked(false);
ui->actionFix_F->setChecked(false);
ui->actionRandom_R->setChecked(false);
ui->actionNoneMode->setChecked(true);
us->data_mode = NoneMode;
us->setVal("us/data_mode", us->data_mode);
}
| true |
d37091503656588af9b99d7f6ad24e4296dc16be | C++ | fieldkit/firmware | /fk/storage/memory_page_store.cpp | UTF-8 | 833 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "storage/memory_page_store.h"
namespace fk {
FK_DECLARE_LOGGER("pages");
MemoryPageStore::MemoryPageStore(DataMemory *target) : target_(target) {
}
int32_t MemoryPageStore::load_page(uint32_t address, uint8_t *ptr, size_t size) {
auto page_size = target_->geometry().page_size;
auto page_address = ((uint32_t)(address / page_size)) * page_size;
FK_ASSERT(page_size == size);
return target_->read(page_address, ptr, size, MemoryReadFlags::None);
}
int32_t MemoryPageStore::save_page(uint32_t address, uint8_t const *ptr, size_t size, uint16_t start, uint16_t end) {
auto page_size = target_->geometry().page_size;
auto page_address = ((uint32_t)(address / page_size)) * page_size;
FK_ASSERT(page_size == size);
return target_->write(page_address, ptr, size, MemoryWriteFlags::None);
}
}
| true |
770e3be8a3e0dfda3155496d3aa58ab84fade5da | C++ | TissueFluid/Algorithm | /LintCode/Copy Books.cc | UTF-8 | 1,517 | 3.484375 | 3 | [] | no_license | // Copy Books
// dp[i][j] : time of j books copied by i workers
// dp[i][j] = min{max(dp[i-1][k from 0 to j-1], sum(pages[k+1 to j]))}
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
class Solution {
public:
/**
* @param pages: a vector of integers
* @param k: an integer
* @return: an integer
*/
int copyBooks(vector<int> &pages, int k) {
const int size = pages.size();
if (k <= 0) {
return -1;
}
if (size == 0) {
return 0;
}
if (size <= k) {
int maximum = pages[0];
for (int i = 1; i < size; ++i) {
maximum = max(maximum, pages[i]);
}
return maximum;
}
vector<int> sum_end_with(size, 0);
sum_end_with[0] = pages[0];
for (int i = 1; i < size; ++i) {
sum_end_with[i] = sum_end_with[i - 1] + pages[i];
}
vector<vector<int> > dp(k + 1, vector<int>(size, numeric_limits<int>::max()));
for (int i = 0; i < size; ++i) {
dp[1][i] = sum_end_with[i];
}
for (int i = 2; i <= k; ++i) {
dp[i][0] = pages[i];
for (int j = 1; j < size; ++j) {
for (int t = 0; t < j; ++t) {
int sum = sum_end_with[j] - sum_end_with[t];
dp[i][j] = min(dp[i][j], max(dp[i-1][t], sum));
}
}
}
return dp[k][size - 1];
}
};
| true |
5de0950399b72048439b9abc5235b04d52071029 | C++ | emadar22/Project-2-OOP | /BeverageItem.h | UTF-8 | 1,068 | 3.4375 | 3 | [] | no_license | //
// Created by daraw on 20/04/2020.
//
#ifndef HW2_OOP_BEVERAGEITEM_H
#define HW2_OOP_BEVERAGEITEM_H
#include <iostream>
#include <string>
namespace OOP_Hw2 {
class BeverageItem {
std::string name; // string of the name of the item
double price; // the price of the item
bool Alcoholic; // boolean 1/0 if the item is alcoholic or not
BeverageItem(const std::string &name, double price, bool IsAlcoholic):name(name),price(price),Alcoholic(IsAlcoholic){}//default
public:
static BeverageItem CreateAlcoholic(const std::string &name, double price);// Alcoholic item constractor
static BeverageItem CreateNonAlcoholic(const std::string &name, double price);// nonAlcoholic item constractor
const std::string& GetName()const;// Return the name of the item
double GetPrice()const; // Return the price of the item
bool IsAlcoholic()const;// Return if the item is alcoholic or not
void SetPrice(double newPrice);// set a price for the item
};
}
#endif //HW2_OOP_BEVERAGEITEM_H
| true |
5dcb0db20d33d51d0d9ce5481da81843d49a9d8f | C++ | youbingchenyoubing/sort_algorithm | /src/quick_sort.h | UTF-8 | 1,713 | 3.296875 | 3 | [] | no_license | #ifndef QUICK_SORT_H
#define QUICK_SORT_H
# include <iostream>
# include <ctime>
using namespace std;
class quickSort
{
public:
quickSort( int data[], int dataSize ): length( dataSize )
{
this->data = new int[dataSize];
for ( int i = 0; i < length; ++i )
{
this->data[i] = data[i];
}
}
~quickSort()
{
if ( data )
{
delete [] data;
data = nullptr;
}
}
void sort()
{
srand( unsigned( time( 0 ) ) );
quick_sort( 0, length - 1 );
}
void test()
{
for ( int i = 0; i < length; ++i )
{
cout << data[i] << " ";
}
cout << endl;
}
private:
int* data;
int length;
void quick_sort( int begin, int end )
{
if ( begin < end )
{
int priv = partion( begin, end );
quick_sort( begin, priv - 1 );
quick_sort( priv + 1, end );
}
}
int partion( int begin, int end )
{
int index = ( rand() % ( end - begin ) ) + begin;
int temp = data[begin];
data[begin] = data[index];
data[index] = temp;
temp = data[begin];
while ( begin < end )
{
while ( begin < end && data[end] >= temp )
{
--end;
}
data[begin] = data[end];
while ( begin < end && data[begin] <= temp )
{
++begin;
}
data[end] = data[begin];
}
data[begin] = temp;
return begin;
}
};
#endif | true |
5cf5f218e918088bb31fef97f2bacb6ae62ed742 | C++ | KKtiandao/DataStructAndAlgorithm | /include/dataStruct/quene/quene.h | UTF-8 | 580 | 2.859375 | 3 | [] | no_license | #ifndef QUENE_H
#define QUENE_H
#include "../list/list.h"
template <class T> class Quene : public List<T> {
public:
Quene(): List<T>(){}
Quene(T a): List<T>(a) {}
bool Push(T a);
Node<T>* Pop();
// void Dump();
// int Size();
};
template <class T> bool Quene<T>::Push(T a) {
auto pNode = new Node<T>(a);
return List<T>::PushFront(pNode);
}
template <class T> Node<T>* Quene<T>::Pop() {
return List<T>::PopBack();
}
//template <class T> void Quene<T>::Dump(){
// List<T>::Dump();
//}
//
//template <class T> int Quene<T>::Size(){
// return List<T>::Size();
//}
#endif
| true |
42a5a4eeaff2dd69b70a35517e61afcc09f394b0 | C++ | aoibird/pc | /cpc/example36_lower_bound.cpp | UTF-8 | 587 | 3.046875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#define MAXN 10000
using namespace std;
int a[MAXN];
int n;
int x;
void input()
{
cin >> n >> x;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
}
void lower_bound()
{
int lb = -1, ub = n;
while (ub - lb > 1) {
int mid = (lb+ub)/2;
if (a[mid] >= x) ub = mid;
else lb = mid;
}
printf("%d\n", ub);
}
void upper_bound()
{
int lb = -1, ub = n;
while (ub - lb > 1) {
int mid = (lb+ub)/2;
if (a[mid] > x) ub = mid;
else lb = mid;
}
printf("%d\n", lb);
}
int main()
{
input();
lower_bound();
upper_bound();
}
| true |
73401d278b324fbe70759454d1f74adefd56eb96 | C++ | koha13/All-code | /C-Thay_Son/BT6/Cau6.1.cpp | UTF-8 | 1,178 | 3.171875 | 3 | [] | no_license | #include<stdio.h>
struct phanso{
int tu;
int mau;
};
int ucln(int a,int b){
while(b!=0){
a=a%b;
int tg=a;
a=b;
b=tg;
}
return a;
}
void rutgon(int &a,int &b){
int d=ucln(a,b);
a/=d;
b/=d;
}
void quydong(int &a,int &b,int &c,int &d){
long long uc=a*b/ucln(a,b);
c=c*uc/a;
d=d*uc/b;
a=uc;
b=uc;
}
void tong(int a,int b,int c){
struct phanso ps3;
ps3.tu=a+b;
ps3.mau=c;
rutgon(ps3.tu,ps3.mau);
printf("Tong = %lld/%lld\n",ps3.tu,ps3.mau);
}
void tich(int a,int b,int c,int d){
struct phanso pstich;
pstich.tu=a*c;
pstich.mau=b*d;
rutgon(pstich.tu,pstich.mau);
printf("Tich = %lld/%lld\n",pstich.tu,pstich.mau);
}
void thuong(int a,int b){
struct phanso psthuong;
psthuong.tu=a;
psthuong.mau=b;
rutgon(psthuong.tu,psthuong.mau);
printf("Thuong = %lld/%lld\n",psthuong.tu,psthuong.mau);
}
main(){
struct phanso ps1,ps2;
printf("Nhap phan so thu 1\n");
scanf("%lld%lld",&ps1.tu,&ps1.mau);
printf("Nhap phan so thu 2\n");
scanf("%lld%lld",&ps2.tu,&ps2.mau);
rutgon(ps1.tu,ps1.mau);
rutgon(ps2.tu,ps2.mau);
quydong(ps1.mau,ps2.mau,ps1.tu,ps2.tu);
tong(ps1.tu,ps2.tu,ps1.mau);
tich(ps1.tu,ps1.mau,ps2.tu,ps2.mau);
thuong(ps1.tu,ps2.tu);
}
| true |
6c402a41446af06f75b8032397e69b06e5b55a01 | C++ | tony-space/WingSimulator | /Simulation/libCpuSimulation/CLineSegment.cpp | UTF-8 | 1,394 | 2.9375 | 3 | [] | no_license | #include "pch.hpp"
#include "CLineSegment.hpp"
using namespace wing2d::simulation::cpu;
CLineSegment::CLineSegment(const glm::vec2& a, const glm::vec2& b) : m_ray()
{
auto delta = b - a;
m_length = glm::length(delta);
m_first = a;
m_second = b;
if (m_length > 1e-16f)
m_ray = delta / m_length;
else
m_length = 0.0f;
m_normal = glm::vec2(-m_ray.y, m_ray.x);
m_distance = glm::dot(a, m_normal);
}
const glm::vec2& wing2d::simulation::cpu::CLineSegment::First() const
{
return m_first;
}
const glm::vec2& wing2d::simulation::cpu::CLineSegment::Second() const
{
return m_second;
}
const glm::vec2& wing2d::simulation::cpu::CLineSegment::Ray() const
{
return m_ray;
}
const glm::vec2& CLineSegment::Normal() const
{
return m_normal;
}
float CLineSegment::DistanceToLine(const glm::vec2& pos) const
{
auto dirToCenter = pos - m_first;
auto centerProj = glm::dot(dirToCenter, m_ray);
auto isAbove = glm::sign(glm::dot(dirToCenter, m_normal));
return isAbove * glm::sqrt(glm::dot(dirToCenter, dirToCenter) - centerProj * centerProj);
}
glm::vec2 CLineSegment::ClosestPoint(const glm::vec2& pos) const
{
const auto toPos = pos - m_first;
const auto projection = glm::dot(m_ray, toPos);
if (projection < 0.0f)
{
return m_first;
}
else if (projection >= 0.0f && projection <= m_length)
{
return m_first + m_ray * projection;
}
else
{
return m_second;
}
}
| true |
4683cdeff0af3903e87ecb853f5aea20121dbc34 | C++ | LuminousLee/ECPlugin | /src/ECModel.cpp | UTF-8 | 1,819 | 2.734375 | 3 | [] | no_license | #include "ECModel.hpp"
using namespace std;
ECModel::ECModel(){
}
ECModel::~ECModel(){
}
vector<string> ECModel::event_list = vector<string>();
bool ECModel::init(){
ECModel::event_list.push_back("cycles");
ECModel::event_list.push_back("instructions");
ECModel::event_list.push_back("cache-misses");
//ECModel::event_list.push_back("llc-load-misses");
//ECModel::event_list.push_back("llc-store-misses");
//ECModel::event_list.push_back("llc-prefetch-misses");
return true;
}
double ECModel::energyCost(map<string, int> event_map, map<int, double> event_value){
if(checkArgs())
return calEnergyCost(event_map, event_value);
else
return -1;
}
bool ECModel::checkArgs(){
return true;
}
double ECModel::calEnergyCost(map<string, int> event_map, map<int, double> event_value){
double cycles = 0, ins = 0, cahmis = 0;
// llc_load = 0, llc_store = 0, llc_prefetch = 0;
try{
cycles = event_value[event_map["cycles"]];
}catch(exception e){
cycles = 0;
}
try{
ins = event_value[event_map["instructions"]];
}catch(exception e){
ins = 0;
}
try{
cahmis = event_value[event_map["cache-misses"]];
}catch(exception e){
cahmis = 0;
}
/*
try{
llc_load = event_value[event_map["llc-load-misses"]];
}catch(exception e){
llc_load = 0;
}
try{
llc_store = event_value[event_map["llc-store-misses"]];
}catch(exception e){
llc_store = 0;
}
try{
llc_prefetch = event_value[event_map["llc-prefetch-misses"]];
}catch(exception e){
llc_prefetch = 0;
}
if(llc_prefetch+llc_load+llc_store<0.1){
return 0;
}*/
return 47.675 + 23.834*cycles + 2.093*ins + 72.113*cahmis;
}
| true |
c31e77b4c43c25611ac1d7ad670208bd3261e290 | C++ | theperfectstorm/arduino_relay_timer | /relay2.ino | UTF-8 | 1,712 | 2.921875 | 3 | [] | no_license | #define OUT1 8 //set your pin numbers here
#define OUT2 9
#define OUT3 10
int to_blink=0;
unsigned long previousMillis = 0; // will store last time LED was updated
unsigned long delay1=1800000; //30min*60sec*1000ms=1800000ms
unsigned long delay2=900000; //15mins*60sec*1000ms=900000ms
unsigned long delay3=1800000; //30min*60sec*1000ms=1800000ms
unsigned long BLINK_FOR=900000; //15min*60sec*1000ms=900000 sec for testing.
void setup() {
int once_repeted=0; //flag
int to_blink=0; //flag
int interval=1000;
pinMode(OUT1,OUTPUT);
pinMode(OUT2,OUTPUT);
pinMode(OUT3,OUTPUT);
//initiall all relays off
digitalWrite(OUT1,HIGH);
digitalWrite(OUT2,HIGH);
digitalWrite(OUT3,HIGH);
//ASSUMING LOW LEVEL -----> RELAY ON
}
void relay1(void);
void relay2(void);
void relay3(void);
void blink_relay(void);
void relay1()
{
digitalWrite(OUT1,LOW); //turn on;
unsigned long startMillis = millis();
while (millis() - startMillis < delay1); //30mins
digitalWrite(OUT1,HIGH);//turn off
}
void relay2()
{
digitalWrite(OUT2,LOW); //turn on
unsigned long startMillis = millis();
while (millis() - startMillis < delay2); //15mins
digitalWrite(OUT2,HIGH); //turn off relay 2
}
void relay3()
{
digitalWrite(OUT3,LOW); //turn on;
unsigned long startMillis = millis();
while (millis() - startMillis < delay3); //15mins
digitalWrite(OUT3,HIGH);//turn off
}
void blink_relay()
{
unsigned long startMillis = millis();
while (millis() - startMillis < BLINK_FOR )//Blink for 30mins
{
digitalWrite(OUT2,LOW); //turn on
delay(1000);//delay
digitalWrite(OUT2,HIGH);//turn off
delay(1000);//wait a second
}
}
void loop()
{
relay1();
relay2();
relay3();
blink_relay();
}
| true |
980f20bdfdc91016440085e6acd414df8758e9d4 | C++ | jschueths/Evolutionary-Algorithm-Practice | /config.hpp | UTF-8 | 2,314 | 2.65625 | 3 | [] | no_license | /////////////////////////////////////////////////////////////////////
/// @file config.hpp
/// @author Joshua McCarville-Schueths CS348 Fall 2011
/// @brief Implementation for config data type, Assignment 1b.
/////////////////////////////////////////////////////////////////////
void config::init(ConfigFile &confile)
{
// Read the file names
m_input_file = confile.read<string>("data_file");
m_solution_file = confile.read<string>("solution_file");
m_log_file = confile.read<string>("log_file");
// Read the parameters
m_mu = confile.read<int>("mu");
m_lambda = confile.read<int>("lambda");
m_penalty = confile.read<int>("penalty");
m_random = confile.read<bool>("random");
m_runs = confile.read<int>("runs");
m_evals = confile.read<int>("evals");
m_parents = confile.read<int>("num_parents");
m_select_type = confile.read<string>("selection_type");
if(m_select_type == "tournament")
m_tourney_size = confile.read<int>("tournament_size");
m_recombination = confile.read<string>("recombination");
if(m_recombination == "n-point")
m_crossovers = confile.read<int>("num_crossovers");
m_term = confile.read<string>("termination_type");
m_probability = confile.read<float>("mutation_probability");
if(!m_random)
m_seed = confile.read<unsigned int>("seed");
else
m_seed = time(NULL);
}
const int& config::mu()
{
return m_mu;
}
const int& config::lambda()
{
return m_lambda;
}
const int& config::penalty()
{
return m_penalty;
}
const int& config::runs()
{
return m_runs;
}
const int& config::evals()
{
return m_evals;
}
const int& config::num_parents()
{
return m_parents;
}
const int& config::num_crossovers()
{
return m_crossovers;
}
const int& config::tourney_size()
{
return m_tourney_size;
}
const float& config::probability()
{
return m_probability;
}
const string& config::input_file()
{
return m_input_file;
}
const string& config::log_file()
{
return m_log_file;
}
const string& config::solution_file()
{
return m_solution_file;
}
const string& config::select_type()
{
return m_select_type;
}
const string& config::recombination()
{
return m_recombination;
}
const string& config::term()
{
return m_term;
}
const bool& config::random()
{
return m_random;
}
const unsigned int& config::seed()
{
return m_seed;
}
| true |
ed0d8e1d2bc1cd4a5bee85bc1ee236a8fb0ff2ef | C++ | TheDaleks/data | /include/data/queue/functional_queue.hpp | UTF-8 | 4,958 | 2.90625 | 3 | [] | no_license | // Copyright (c) 2019 Daniel Krawisz
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DATA_MAP_QUEUE
#define DATA_MAP_QUEUE
#include <data/list.hpp>
#include <data/tools/iterator_list.hpp>
#include <data/queue.hpp>
#include <data/fold.hpp>
namespace data {
// functional queue based on Milewski's implementation of Okasaki.
template <typename X, typename L>
class functional_queue {
L Left;
L Right;
functional_queue(L l, L r) : Left{l}, Right{r} {}
public:
using required = list::is_buildable<L, X>;
using returned = typename required::returned;
constexpr static required Satisfied{};
functional_queue() : Left{}, Right{} {}
functional_queue(L l) : Left{l}, Right{} {}
bool empty() const {
return container::empty(Left);
}
uint32 size() const {
return container::size(Left) + container::size(Right);
}
bool valid() const {
return Left.valid() && Right.valid();
}
const returned first() const {
return list::first(Left);
}
const returned operator[](uint32 i) {
if (i >= size()) throw std::out_of_range("queue index");
uint32 left = Left.size();
if (i >= left) return Right[Right.size() - (i - left) - 1];
return Left[i];
}
private:
static functional_queue check(const L& l, const L& r) {
if (l.empty()) {
if (!r.empty()) return functional_queue{list::reverse(r), L{}};
return functional_queue{};
} else return functional_queue(l, r);
}
public:
functional_queue rest() const {
return check(Left.rest(), Right);
}
returned last() const {
return check(Right, Left).Left.first();
}
functional_queue append(X e) const {
return check(Left, Right + e);
}
functional_queue prepend(X e) const {
return check(Left + e, Right);
}
functional_queue operator+(X e) const {
return append(e);
}
functional_queue append(L list) const {
if (list.empty()) return *this;
return append(list.first()).append(list.rest());
}
functional_queue operator+(L list) const {
return append(list);
}
functional_queue append(functional_queue q) const {
if (q.empty()) return *this;
return append(q.first()).append(q.rest());
}
functional_queue operator+(functional_queue q) const {
return append(q);
}
functional_queue reverse() const {
return check(list::reverse(Left), list::reverse(Right));
}
bool operator==(const functional_queue& q) const {
if (this == &q) return true;
if (size() != q.size()) return false;
if (first() != q.first()) return false;
return rest() == q.rest();
}
bool operator!=(const functional_queue& q) const {
return !operator=(q);
}
static functional_queue make() {
return functional_queue{};
}
template <typename A, typename ... M>
static functional_queue make(A x, M... m) {
return make(m...).prepend(x);
}
constexpr static data::queue::definition::queue<functional_queue, returned> require_is_queue{};
constexpr static data::list::definition::extendable<functional_queue, returned> require_is_buildable{};
};
template <typename X, typename L>
inline bool empty(functional_queue<X, L> q) {
return q.empty();
}
template <typename X, typename L>
inline uint32 size(functional_queue<X, L> q) {
return q.size();
}
template <typename X, typename L>
inline typename functional_queue<X, L>::returned first(functional_queue<X, L> q) {
return q.first();
}
template <typename X, typename L>
inline functional_queue<X, L> rest(functional_queue<X, L> q) {
return q.rest();
}
template <typename X, typename L>
inline functional_queue<X, L> append(functional_queue<X, L> q, X x) {
return q.append(x);
}
template <typename X, typename L>
inline functional_queue<X, L> reverse(functional_queue<X, L> q) {
return q.reverse();
}
}
template <typename X, typename L>
std::ostream& operator<<(std::ostream& o, const data::functional_queue<X, L> n) {
return data::list::write(o, n);
}
#endif
| true |
e4fe3d1d97e0f7584f2dc8317eb7b0a4c868275c | C++ | AGraber/ed7hook_switch | /source/skyline/logger/SdLogger.cpp | UTF-8 | 955 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "skyline/logger/SdLogger.hpp"
#include "nn/fs.h"
namespace skyline::logger {
nn::fs::FileHandle fileHandle;
s64 offset;
SdLogger::SdLogger(std::string path) {
/*nn::fs::DirectoryEntryType type;
Result rc = nn::fs::GetEntryType(&type, path.c_str());
if (rc == 0x202) { // Path does not exist
rc = nn::fs::CreateFile(path.c_str(), 0);
} else if (R_FAILED(rc))
return;
if (type == nn::fs::DirectoryEntryType_Directory) return;
R_ERRORONFAIL(nn::fs::OpenFile(&fileHandle, path.c_str(), nn::fs::OpenMode_ReadWrite | nn::fs::OpenMode_Append));*/
}
void SdLogger::Initialize() {
// nothing to do
}
void SdLogger::SendRaw(void* data, size_t size) {
nn::fs::SetFileSize(fileHandle, offset + size);
nn::fs::WriteFile(fileHandle, offset, data, size,
nn::fs::WriteOption::CreateOption(nn::fs::WriteOptionFlag_Flush));
offset += size;
};
}; // namespace skyline::logger | true |
1ce68541de917997933bb1fb0caeeb04e72e5a69 | C++ | Ourgaht/prog3d | /src/plane.cpp | UTF-8 | 767 | 2.734375 | 3 | [] | no_license | #include "plane.h"
#include <cmath>
Plane::Plane()
{
}
Plane::Plane(const PropertyList &propList)
{
m_position = propList.getPoint("position",Point3f(0,0,0));
m_normal = propList.getVector("normal",Point3f(0,0,1));
}
Plane::~Plane()
{
}
bool Plane::intersect(const Ray& ray, Hit& hit) const
{
float ddn = ray.direction.dot(m_normal);
if (fabs(ddn) < 1e-5) {
return false;
}
Point3f amo = m_position - ray.origin;
float amodn = amo.dot(m_normal);
float t = amodn / ddn;
if (t < 0) {
return false;
}
hit.setShape(this);
hit.setT(t);
float side = static_cast<float>( -sgn(m_normal.dot(ray.direction)) );
hit.setNormal(side * m_normal);
return true;
}
REGISTER_CLASS(Plane, "plane")
| true |
fa0d6977d8be32153d14a2b7acafc6587831a534 | C++ | glindsey/game-project-potential | /src/StageChunkCollection.cpp | UTF-8 | 8,704 | 2.8125 | 3 | [] | no_license | #include "StageChunkCollection.h"
#include "MathUtils.h"
#include "Stage.h"
#include "StageChunk.h"
#include "StageComponentVisitor.h"
struct StageChunkCollection::Impl
{
inline int calc_chunk_index(int chunk_x, int chunk_y, int chunk_z)
{
return (chunk_z * (int)num_of_chunks.x * (int)num_of_chunks.y) +
(chunk_y * (int)num_of_chunks.x) + chunk_x;
}
inline int calc_block_index(int block_x, int block_y, int block_z)
{
return (block_z * (int)num_of_blocks.x * (int)num_of_blocks.y) +
(block_y * (int)num_of_blocks.x) + block_x;
}
inline int calc_block_index_of_chunk(int chunk_x, int chunk_y, int chunk_z)
{
int block_x = (chunk_x * StageChunk::chunk_side_length);
int block_y = (chunk_y * StageChunk::chunk_side_length);
int block_z = chunk_z;
return calc_block_index(block_x, block_y, block_z);
}
inline StageChunk* get_chunk_location(int chunk_index)
{
StageChunk* chunks = reinterpret_cast<StageChunk*>(chunk_pool);
return &(chunks[chunk_index]);
}
inline StageChunk* get_chunk_location(int chunk_x, int chunk_y, int chunk_z)
{
int chunk_index = calc_chunk_index(chunk_x, chunk_y, chunk_z);
return get_chunk_location(chunk_index);
}
inline StageBlock* get_block_location_of_chunk(int chunk_x,
int chunk_y,
int chunk_z)
{
int block_index = calc_block_index_of_chunk(chunk_x, chunk_y, chunk_z);
return get_block_location(block_index);
}
inline StageBlock* get_block_location(int block_index)
{
StageBlock* blocks = reinterpret_cast<StageBlock*>(block_pool);
return &(blocks[block_index]);
}
inline StageBlock* get_block_location(int block_x, int block_y, int block_z)
{
int block_index = calc_block_index(block_x, block_y, block_z);
return get_block_location(block_index);
}
Impl(StageCoord3 total_block_size)
{
num_of_blocks = total_block_size;
std::cout << "Allocating a " << num_of_blocks.x << "x" <<
num_of_blocks.y << "x" <<
num_of_blocks.z <<
" memory pool for StageBlocks...";
unsigned int block_pool_size = num_of_blocks.x *
num_of_blocks.y *
num_of_blocks.z *
sizeof(StageBlock);
std::cout << " (" << (float)(block_pool_size / 1048576) << " MiB in size)" << std::endl;
block_pool = malloc(block_pool_size);
if (block_pool == nullptr)
{
throw new std::bad_alloc;
}
num_of_chunks.x = (num_of_blocks.x / StageChunk::chunk_side_length) +
((num_of_blocks.x % StageChunk::chunk_side_length == 0) ? 0 : 1);
num_of_chunks.y = (num_of_blocks.y / StageChunk::chunk_side_length) +
((num_of_blocks.y % StageChunk::chunk_side_length == 0) ? 0 : 1);
num_of_chunks.z = num_of_blocks.z;
std::cout << "Allocating a " << num_of_chunks.x << "x" <<
num_of_chunks.y << "x" <<
num_of_chunks.z <<
" memory pool for StageChunks...";
unsigned int chunk_pool_size = num_of_chunks.x *
num_of_chunks.y *
num_of_chunks.z *
sizeof(StageChunk);
std::cout << " (" << (float)(chunk_pool_size / 1024) << " kiB in size.)" << std::endl;
chunk_pool = malloc(chunk_pool_size);
if (chunk_pool == nullptr)
{
throw new std::bad_alloc;
}
}
~Impl()
{
#ifdef DEBUG_DESTROY_STAGECHUNK_INSTANCES
std::cout << "Destroying StageChunk instances..." << std::endl;
for (int idx = 0; idx < num_of_chunks_.z *
num_of_chunks_.y *
num_of_chunks_.x; ++idx)
{
chunks_[idx]->~StageChunk();
}
#endif
std::cout << "Deleting the memory pool for StageChunks..." << std::endl;
if (chunk_pool != nullptr)
{
free(chunk_pool);
}
std::cout << "Deleting the memory pool for StageBlocks..." << std::endl;
if (block_pool != nullptr)
{
free(block_pool);
}
}
/// Pointer to a big ol' memory pool for StageChunks.
void* chunk_pool;
/// Pointer to a big ol' memory pool for StageBlocks.
void* block_pool;
/// Size of the stage, in StageBlocks.
StageCoord3 num_of_blocks;
/// Size of the stage, in StageChunks.
StageCoord3 num_of_chunks;
};
StageChunkCollection::StageChunkCollection(StageCoord3 total_block_size)
: impl(new Impl(total_block_size))
{
std::cout << "Creating and initializing the StageBlock instances..." << std::endl;
for (int block_z = 0; block_z < impl->num_of_blocks.z; ++block_z)
{
for (int block_y = 0; block_y < impl->num_of_blocks.y; ++block_y)
{
for (int block_x = 0; block_x < impl->num_of_blocks.x; ++block_x)
{
int block_index = impl->calc_block_index(block_x, block_y, block_z);
// Figure out where in the block pool this block will go.
StageBlock* block_ptr = impl->get_block_location(block_index);
// Use placement new to construct the StageBlock.
(void) new (block_ptr) StageBlock(block_x, block_y, block_z);
}
}
}
std::cout << "Creating and initializing the StageChunk instances..." << std::endl;
for (int chunk_z = 0; chunk_z < impl->num_of_chunks.z; ++chunk_z)
{
for (int chunk_y = 0; chunk_y < impl->num_of_chunks.y; ++chunk_y)
{
for (int chunk_x = 0; chunk_x < impl->num_of_chunks.x; ++chunk_x)
{
int chunk_index = impl->calc_chunk_index(chunk_x, chunk_y, chunk_z);
StageChunk* chunk_ptr = impl->get_chunk_location(chunk_index);
StageCoord block_x = chunk_x * StageChunk::chunk_side_length;
StageCoord block_y = chunk_y * StageChunk::chunk_side_length;
StageCoord block_z = chunk_z;
// Placement new means we don't have to save the return value, which
// seems *really* weird, but that's how it is!
(void) new (chunk_ptr) StageChunk(this, chunk_index,
block_x, block_y, block_z);
}
}
}
}
StageChunkCollection::~StageChunkCollection()
{
std::cout << "Destroying StageChunkCollection..." << std::endl;
}
void StageChunkCollection::accept(StageComponentVisitor& visitor)
{
// Visit the collection. Note that this may not be strictly necessary.
bool visitChildren = visitor.visit(*this);
if (visitChildren)
{
// Visit the chunks existing in the collection.
for (int chunk_z = 0; chunk_z < impl->num_of_chunks.z; ++chunk_z)
{
for (int chunk_y = 0; chunk_y < impl->num_of_chunks.y; ++chunk_y)
{
for (int chunk_x = 0; chunk_x < impl->num_of_chunks.x; ++chunk_x)
{
int chunk_index = impl->calc_chunk_index(chunk_x, chunk_y, chunk_z);
StageChunk* chunk = impl->get_chunk_location(chunk_index);
chunk->accept(visitor);
}
}
}
}
}
StageChunk& StageChunkCollection::getChunk(int idx)
{
return *(impl->get_chunk_location(idx));
}
StageChunk& StageChunkCollection::get_chunk_containing(StageCoord block_x,
StageCoord block_y,
StageCoord block_z)
{
int chunk_x = block_x / StageChunk::chunk_side_length;
int chunk_y = block_y / StageChunk::chunk_side_length;
int chunk_z = block_z;
int chunk_index = impl->calc_chunk_index(chunk_x, chunk_y, chunk_z);
return *(impl->get_chunk_location(chunk_index));
}
StageBlock& StageChunkCollection::get_block(StageCoord block_x,
StageCoord block_y,
StageCoord block_z)
{
return *(getBlockPointer(block_x, block_y, block_z));
}
StageBlock* StageChunkCollection::getBlockPointer(StageCoord block_x,
StageCoord block_y,
StageCoord block_z)
{
if ((block_x < 0) || (block_y < 0) || (block_z < 0) ||
(block_x >= impl->num_of_blocks.x) ||
(block_y >= impl->num_of_blocks.y) ||
(block_z >= impl->num_of_blocks.z))
{
std::cout << "Attempt to get block (" <<
block_x << ", " <<
block_y << ", " <<
block_z << ")" << std::endl;
}
int block_index = impl->calc_block_index(block_x, block_y, block_z);
return impl->get_block_location(block_index);
}
| true |
8a32fd77207eabb050a259a69adcb6299640414e | C++ | qcoh/dmgb | /dmgb_test/cpu_test.cpp | UTF-8 | 36,955 | 2.796875 | 3 | [] | no_license | #include "test.h"
#include "cpu.h"
#include "mmu.h"
#include "rw_ref.h"
struct test_mmu : public read_writer {
u8& operator[](const u16 addr) noexcept { return m_mmu[addr]; }
u8 read(const u16 addr) const noexcept override { return m_mmu[addr]; }
void write(const u16 addr, const u8 v) noexcept override { m_mmu[addr] = v; }
u8 m_mmu[0x10000]{};
};
u8& reg(cpu::cpu& c, test_mmu& m, const u8 index) {
switch (index & 0x7) {
case 0:
return c.b;
case 1:
return c.c;
case 2:
return c.d;
case 3:
return c.e;
case 4:
return c.h;
case 5:
return c.l;
case 6:
return m[c.hl];
case 7:
return c.a;
}
// impossible
return c.a;
}
u16 reg16(const cpu::cpu& c, const u8 index) {
if (index == 0) {
return c.bc;
} else if (index == 1) {
return c.de;
} else if (index == 2) {
return c.hl;
} else {
return c.sp;
}
}
u16 regp(const cpu::cpu& c, const u8 index) {
if (index == 0) {
return c.bc;
} else if (index == 1) {
return c.de;
} else if (index == 2) {
return c.hl;
} else {
return c.af;
}
}
SCENARIO("basic lds", "[cpu]") {
GIVEN("cpu and mmu_ref with value at register d is 12") {
cpu::cpu c{};
test_mmu m{};
c.d = 12;
WHEN("loading d to c") {
m[0] = 0x4a;
c.pc = 0;
cpu::step(c, m);
THEN("the value at register c is 12") { REQUIRE(c.c == 12); }
THEN("pc increases by 1") { REQUIRE(c.pc == 1); }
THEN("instruction takes 4 cycle") { REQUIRE(c.cycles == 4); }
}
}
}
SCENARIO("add", "[cpu]") {
GIVEN("a cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("adding to a",
[&c, &m](const u8 randa, const u8 randv, const bool randcf) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.cf = randcf;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0x80, 0x87);
cpu::step(c, m);
RC_ASSERT(c.a == static_cast<u8>(randa + randv));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.zf == (c.a == 0));
RC_ASSERT(c.hf == ((randa & 0xf) + (randv & 0xf) > 0xf));
RC_ASSERT(c.cf == ((randa + randv) > 0xff));
});
WHEN("adding register to a") {
m[c.pc] = 0x80;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("adding memory to a") {
m[c.pc] = 0x86;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("adc", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY(
"adding to a with carry",
[&c, &m](const u8 randa, const u8 randv, const bool randcf) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.cf = randcf;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0x88, 0x8f);
cpu::step(c, m);
RC_ASSERT(c.a == static_cast<u8>(randa + randv + randcf));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.zf == (c.a == 0));
RC_ASSERT(c.hf == ((randa & 0xf) + (randv & 0xf) + randcf > 0xf));
RC_ASSERT(c.cf == ((randa + randv + randcf) > 0xff));
});
WHEN("adcing register to a") {
m[c.pc] = 0x88;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("adcing memory to a") {
m[c.pc] = 0x8e;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("sub", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("subtracting from a",
[&c, &m](const u8 randa, const u8 randv) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0x90, 0x97);
cpu::step(c, m);
RC_ASSERT(c.a == static_cast<u8>(randa - randv));
RC_ASSERT(c.nf == true);
RC_ASSERT(c.zf == (c.a == 0));
RC_ASSERT(c.hf == ((randa & 0xf) < (randv & 0xf)));
RC_ASSERT(c.cf == (randa < randv));
});
WHEN("subtracting register from a") {
m[c.pc] = 0x90;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("subtracting memory from a") {
m[c.pc] = 0x96;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("sbc", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("subtracting from a with carry",
[&c, &m](const u8 randa, const u8 randv, const bool randcf) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
c.cf = randcf;
m[c.hl] = randv;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0x98, 0x9f);
cpu::step(c, m);
RC_ASSERT(c.a == static_cast<u8>(randa - randv - randcf));
RC_ASSERT(c.nf == true);
RC_ASSERT(c.zf == (c.a == 0));
RC_ASSERT(c.hf == ((randa & 0xf) < (randv & 0xf) + randcf));
RC_ASSERT(c.cf == (randa < randv + randcf));
});
WHEN("sbctracting register from a") {
m[c.pc] = 0x98;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("sbctracting memory from a") {
m[c.pc] = 0x9e;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("and", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("bitwise and with a",
[&c, &m](const u8 randa, const u8 randv) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0xa0, 0xa7);
cpu::step(c, m);
RC_ASSERT(c.a == (randa & randv));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == true);
RC_ASSERT(c.zf == (c.a == 0));
RC_ASSERT(c.cf == false);
});
WHEN("anding register with a") {
m[c.pc] = 0xa0;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("anding memory with a") {
m[c.pc] = 0xa6;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("xor", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("bitwise xor with a",
[&c, &m](const u8 randa, const u8 randv) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0xa8, 0xaf);
cpu::step(c, m);
RC_ASSERT(c.a == (randa ^ randv));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(c.zf == (c.a == 0));
RC_ASSERT(c.cf == false);
});
WHEN("xoring register with a") {
m[c.pc] = 0xa8;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("xoring memory with a") {
m[c.pc] = 0xae;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("or", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("bitwise or with a", [&c, &m](const u8 randa, const u8 randv) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0xb0, 0xb7);
cpu::step(c, m);
RC_ASSERT(c.a == (randa | randv));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(c.zf == (c.a == 0));
RC_ASSERT(c.cf == false);
});
WHEN("oring register with a") {
m[c.pc] = 0xb0;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("oring memory with a") {
m[c.pc] = 0xb6;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("cp", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("comparing with a", [&c, &m](const u8 randa, const u8 randv) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0xb8, 0xbf);
cpu::step(c, m);
RC_ASSERT(c.a == randa);
RC_ASSERT(c.nf == true);
RC_ASSERT(c.zf == ((randa - randv) == 0));
RC_ASSERT(c.hf == ((randa & 0xf) < (randv & 0xf)));
RC_ASSERT(c.cf == (randa < randv));
});
rc::PROPERTY("cp is the same as sub without modifying a",
[&c, &m](const u8 randa, const u8 randv) {
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::distinctFrom(rc::gen::inRange(0, 10), c.hl);
m[c.pc] = *rc::gen::inRange(0xb8, 0xbf);
cpu::step(c, m);
const bool cf = c.cf;
const bool nf = c.nf;
const bool hf = c.hf;
const bool zf = c.zf;
c.a = randa;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
m[c.pc] = *rc::gen::inRange(0x90, 0x97);
cpu::step(c, m);
RC_ASSERT(c.nf == nf);
RC_ASSERT(c.zf == zf);
RC_ASSERT(c.hf == hf);
RC_ASSERT(c.cf == cf);
});
WHEN("comparing register with a") {
m[c.pc] = 0xb8;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 4") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 4);
}
}
WHEN("comparing memory with a") {
m[c.pc] = 0xbe;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("bit", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("test bit", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x40, 0x7f);
m[c.pc + 1] = cb;
cpu::step(c, m);
const u8 Index = (cb >> 3) & 0x7;
const u8 Mask = 1 << Index;
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == true);
RC_ASSERT(c.zf == !(randv & Mask));
});
WHEN("test bit of register") {
m[c.pc] = 0xcb;
m[c.pc + 1] = 0x40;
cpu::step(c, m);
THEN("pc increments by 2, cycles by 8") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 8);
}
}
WHEN("test bit of memory") {
m[c.pc] = 0xcb;
m[c.pc + 1] = 0x46;
cpu::step(c, m);
THEN("pc increments by 2, cycles by 16") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 16);
}
}
}
}
SCENARIO("res", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("reset bit", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x80, 0xbf);
m[c.pc + 1] = cb;
cpu::step(c, m);
const u8 Mask = 1 << ((cb >> 3) & 0x7);
RC_ASSERT((reg(c, m, cb & 0x7) & Mask) == 0);
});
}
}
SCENARIO("set", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("set bit", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0xc0, 0xff);
m[c.pc + 1] = cb;
cpu::step(c, m);
const u8 Mask = 1 << ((cb >> 3) & 0x7);
RC_ASSERT((reg(c, m, cb & 0x7) & Mask) != 0);
});
}
}
SCENARIO("rlc", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("rlc", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x0, 0x7);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == !!(randv & (1 << 7)));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) ==
static_cast<u8>((randv << 1) | (randv >> 7)));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("rrc", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("rrc", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x8, 0xf);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == !!(randv & 1));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) ==
static_cast<u8>((randv >> 1) | (randv << 7)));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("rl", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("rl", [&c, &m](const u8 randv, const bool randcf) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.cf = randcf;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x10, 0x17);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == !!(randv & (1 << 7)));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) == static_cast<u8>((randv << 1) | randcf));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("rr", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("rr", [&c, &m](const u8 randv, const bool randcf) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.cf = randcf;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x18, 0x1f);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == !!(randv & 1));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) ==
static_cast<u8>((randv >> 1) | (randcf << 7)));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("sla", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("sla", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x20, 0x27);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == !!(randv & (1 << 7)));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) == static_cast<u8>(randv << 1));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("sra", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("sra", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x28, 0x2f);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == !!(randv & 1));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) == static_cast<u8>(randv >> 1) |
(randv & (1 << 7)));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("swap", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("swap", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x30, 0x37);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == false);
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) ==
static_cast<u8>((randv >> 4) | (randv << 4)));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("srl", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("srl", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = 0xcb;
const u8 cb = *rc::gen::inRange(0x38, 0x3f);
m[c.pc + 1] = cb;
cpu::step(c, m);
RC_ASSERT(c.cf == !!(randv & 1));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == false);
RC_ASSERT(reg(c, m, cb & 0x7) == static_cast<u8>(randv >> 1));
RC_ASSERT(c.zf == (reg(c, m, cb & 0x7) == 0));
});
}
}
SCENARIO("ld_16", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ld_16", [&c, &m](const u16 randw) {
m[c.pc] = *rc::gen::element(0x1, 0x11, 0x21, 0x31);
const auto original_pc = c.pc;
m[c.pc + 1] = randw & 0xff;
m[c.pc + 2] = randw >> 8;
cpu::step(c, m);
RC_ASSERT(reg16(c, (m[original_pc] >> 4) & 0x3) == randw);
});
WHEN("calling ld_16") {
m[c.pc] = 0x1;
cpu::step(c, m);
THEN("pc increments by 3, cycles by 12") {
REQUIRE(c.pc == 3);
REQUIRE(c.cycles == 12);
}
}
}
}
SCENARIO("inc", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("inc", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = *rc::gen::element(0x4, 0xc, 0x14, 0x1c, 0x24, 0x2c, 0x34, 0x3c);
cpu::step(c, m);
RC_ASSERT(reg(c, m, (m[c.pc] >> 3) & 0x7) == static_cast<u8>(randv + 1));
RC_ASSERT(c.zf == (reg(c, m, (m[c.pc] >> 3) & 0x7) == 0));
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == ((randv & 0xf) == 0xf));
});
}
}
SCENARIO("dec", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("dec", [&c, &m](const u8 randv) {
c.a = randv;
c.b = randv;
c.c = randv;
c.d = randv;
c.e = randv;
c.h = randv;
c.l = randv;
m[c.hl] = randv;
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
m[c.pc] = *rc::gen::element(0x5, 0xd, 0x15, 0x1d, 0x25, 0x2d, 0x35, 0x3d);
cpu::step(c, m);
RC_ASSERT(reg(c, m, (m[c.pc] >> 3) & 0x7) == static_cast<u8>(randv - 1));
RC_ASSERT(c.zf == (reg(c, m, (m[c.pc] >> 3) & 0x7) == 0));
RC_ASSERT(c.nf == true);
RC_ASSERT(c.hf == ((randv & 0xf) == 0));
});
}
}
SCENARIO("inc16", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("inc16", [&c, &m](const u16 randw) {
c.bc = randw;
c.de = randw;
c.hl = randw;
c.sp = randw;
m[c.pc] = *rc::gen::element(0x3, 0x13, 0x23, 0x33);
cpu::step(c, m);
RC_ASSERT(reg16(c, (m[c.pc] >> 4) & 0x3) == static_cast<u16>(randw + 1));
});
}
}
SCENARIO("dec16", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("dec16", [&c, &m](const u16 randw) {
c.bc = randw;
c.de = randw;
c.hl = randw;
c.sp = randw;
m[c.pc] = *rc::gen::element(0xb, 0x1b, 0x2b, 0x3b);
cpu::step(c, m);
RC_ASSERT(reg16(c, (m[c.pc] >> 4) & 0x3) == static_cast<u16>(randw - 1));
});
}
}
SCENARIO("ld_d8", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ld_d8", [&c, &m](const u8 randv) {
c.pc = *rc::gen::suchThat(rc::gen::inRange(0, 10), [&c](int x) {
return x != c.hl && (x + 1) != c.hl;
});
const u16 original_pc = c.pc;
m[c.pc] = *rc::gen::element(0x6, 0xe, 0x16, 0x1e, 0x26, 0x2e, 0x36, 0x3e);
m[c.pc + 1] = randv;
cpu::step(c, m);
RC_ASSERT(reg(c, m, (m[original_pc] >> 3) & 0x7) == randv);
});
WHEN("loading immediate byte to a") {
m[c.pc] = 0x3e;
cpu::step(c, m);
THEN("pc increments by 2, cycles by 8") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 8);
}
}
WHEN("loading immediate byte to (hl)") {
m[c.pc] = 0x36;
cpu::step(c, m);
THEN("pc increments by 2, cycles by 12") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 12);
}
}
}
}
SCENARIO("pop", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY(
"pop", [&c, &m](const u8 randlo, const u8 randhi, const u16 randsp) {
c.sp = randsp;
m[randsp] = randlo;
m[randsp + 1] = randhi;
c.pc = *rc::gen::suchThat(rc::gen::inRange(10, 20), [&c](int x) {
return x != c.sp && x + 1 != c.sp;
});
m[c.pc] = *rc::gen::element(0xc1, 0xd1, 0xe1, 0xf1);
cpu::step(c, m);
RC_ASSERT(regp(c, (m[c.pc] >> 5)) ==
static_cast<u16>(randlo | (randhi >> 8)));
});
}
}
SCENARIO("add_hl", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("add_hl", [&c, &m](const u16 randhl, const u16 randw) {
c.bc = randw;
c.de = randw;
c.hl = randhl;
c.sp = randw;
m[c.pc] = *rc::gen::element(0x09, 0x19, 0x39);
cpu::step(c, m);
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == ((randhl & 0xfff) + (randw & 0xfff) > 0xfff));
RC_ASSERT(c.cf == ((randhl + randw) > 0xffff));
RC_ASSERT(c.hl == static_cast<u16>(randhl + randw));
});
rc::PROPERTY("add_hl_hl", [&c, &m](const u16 randhl) {
c.hl = randhl;
m[c.pc] = 0x29;
cpu::step(c, m);
RC_ASSERT(c.nf == false);
RC_ASSERT(c.hf == ((randhl & 0xfff) + (randhl & 0xfff) > 0xfff));
RC_ASSERT(c.cf == ((randhl + randhl) > 0xffff));
RC_ASSERT(c.hl == static_cast<u16>(randhl + randhl));
});
}
}
SCENARIO("ld_m16_a", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ld_m16_a", [&c, &m](const u16 randw, const u8 randa) {
c.bc = randw;
c.de = randw;
c.a = randa;
m[c.pc] = *rc::gen::element(0x02, 0x12);
cpu::step(c, m);
RC_ASSERT(m[randw] == randa);
});
}
}
SCENARIO("ld_a_m16", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ld_a_m16", [&c, &m](const u16 randw, const u8 randa) {
m[randw] = randa;
c.bc = randw;
c.de = randw;
c.pc = *rc::gen::suchThat(rc::gen::inRange(10, 20),
[&c](int x) { return x != c.bc && x != c.de; });
m[c.pc] = *rc::gen::element(0x0a, 0x1a);
cpu::step(c, m);
RC_ASSERT(c.a == randa);
});
}
}
SCENARIO("ldi_hl_a", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ldi_hl_a", [&c, &m](const u16 randhl, const u8 randa) {
c.hl = randhl;
c.a = randa;
m[c.pc] = 0x22;
cpu::step(c, m);
RC_ASSERT(m[randhl] == randa);
RC_ASSERT(c.hl == static_cast<u16>(randhl + 1));
});
}
}
SCENARIO("ldd_hl_a", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ldd_hl_a", [&c, &m](const u16 randhl, const u8 randa) {
c.hl = randhl;
c.a = randa;
m[c.pc] = 0x32;
cpu::step(c, m);
RC_ASSERT(m[randhl] == randa);
RC_ASSERT(c.hl == static_cast<u16>(randhl - 1));
});
WHEN("calling ldd_hl_a") {
m[c.pc] = 0x32;
cpu::step(c, m);
THEN("pc increments by 1, cycles by 8") {
REQUIRE(c.pc == 1);
REQUIRE(c.cycles == 8);
}
}
}
}
SCENARIO("ldi_a_hl", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ldi_a_hl", [&c, &m](const u16 randhl, const u8 randa) {
c.hl = randhl;
m[c.hl] = randa;
c.pc = *rc::gen::suchThat(rc::gen::inRange(10, 20),
[&c](int x) { return x != c.hl; });
m[c.pc] = 0x2a;
cpu::step(c, m);
RC_ASSERT(c.a == randa);
RC_ASSERT(c.hl == static_cast<u16>(randhl + 1));
});
}
}
SCENARIO("ldd_a_hl", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("ldd_a_hl", [&c, &m](const u16 randhl, const u8 randa) {
c.hl = randhl;
m[c.hl] = randa;
c.pc = *rc::gen::suchThat(rc::gen::inRange(10, 20),
[&c](int x) { return x != c.hl; });
m[c.pc] = 0x3a;
cpu::step(c, m);
RC_ASSERT(c.a == randa);
RC_ASSERT(c.hl == static_cast<u16>(randhl - 1));
});
}
}
SCENARIO("rst", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("rst 0x0", [&c, &m]() {
c.sp = *rc::gen::suchThat(rc::gen::arbitrary<u16>(),
[](u16 x) { return x > 2; });
const u16 oldpc = *rc::gen::arbitrary<u16>();
c.pc = oldpc;
m[c.pc] = 0xc7;
cpu::step(c, m);
RC_ASSERT(c.pc == 0x00);
RC_ASSERT(m[c.sp] == (oldpc & 0xff));
RC_ASSERT(m[c.sp + 1] == (oldpc >> 8));
});
rc::PROPERTY("rst 0x10", [&c, &m]() {
c.sp = *rc::gen::suchThat(rc::gen::arbitrary<u16>(),
[](u16 x) { return x > 2; });
const u16 oldpc = *rc::gen::arbitrary<u16>();
c.pc = oldpc;
m[c.pc] = 0xd7;
cpu::step(c, m);
RC_ASSERT(c.pc == 0x10);
RC_ASSERT(m[c.sp] == (oldpc & 0xff));
RC_ASSERT(m[c.sp + 1] == (oldpc >> 8));
});
rc::PROPERTY("rst 0x20", [&c, &m]() {
c.sp = *rc::gen::suchThat(rc::gen::arbitrary<u16>(),
[](u16 x) { return x > 2; });
const u16 oldpc = *rc::gen::arbitrary<u16>();
c.pc = oldpc;
m[c.pc] = 0xe7;
cpu::step(c, m);
RC_ASSERT(c.pc == 0x20);
RC_ASSERT(m[c.sp] == (oldpc & 0xff));
RC_ASSERT(m[c.sp + 1] == (oldpc >> 8));
});
rc::PROPERTY("rst 0x30", [&c, &m]() {
c.sp = *rc::gen::suchThat(rc::gen::arbitrary<u16>(),
[](u16 x) { return x > 2; });
const u16 oldpc = *rc::gen::arbitrary<u16>();
c.pc = oldpc;
m[c.pc] = 0xf7;
cpu::step(c, m);
RC_ASSERT(c.pc == 0x30);
RC_ASSERT(m[c.sp] == (oldpc & 0xff));
RC_ASSERT(m[c.sp + 1] == (oldpc >> 8));
});
}
}
SCENARIO("jr", "[cpu]") {
GIVEN("cpu and mmu") {
cpu::cpu c{};
test_mmu m{};
rc::PROPERTY("jr nz", [&c, &m](const bool randzero, const u8 randimb) {
c.zf = randzero;
c.pc = *rc::gen::suchThat(rc::gen::arbitrary<u16>(), [](u16 x) {
return (127 < x) && (x < 0xffff);
});
const u16 original_pc = c.pc;
m[c.pc] = 0x20;
m[c.pc + 1] = randimb;
cpu::step(c, m);
if (c.zf) {
RC_ASSERT(c.pc == (original_pc + 2));
} else {
RC_ASSERT(c.pc ==
(2 + original_pc + static_cast<signed char>(randimb)));
}
});
rc::PROPERTY("jr z", [&c, &m](const bool randzero, const u8 randimb) {
c.zf = randzero;
c.pc = *rc::gen::suchThat(rc::gen::arbitrary<u16>(), [](u16 x) {
return (127 < x) && (x < 0xffff);
});
const u16 original_pc = c.pc;
m[c.pc] = 0x28;
m[c.pc + 1] = randimb;
cpu::step(c, m);
if (!c.zf) {
RC_ASSERT(c.pc == (original_pc + 2));
} else {
RC_ASSERT(c.pc ==
(2 + original_pc + static_cast<signed char>(randimb)));
}
});
rc::PROPERTY("jr nc", [&c, &m](const bool randcarry, const u8 randimb) {
c.cf = randcarry;
c.pc = *rc::gen::suchThat(rc::gen::arbitrary<u16>(), [](u16 x) {
return (127 < x) && (x < 0xffff);
});
const u16 original_pc = c.pc;
m[c.pc] = 0x30;
m[c.pc + 1] = randimb;
cpu::step(c, m);
if (c.cf) {
RC_ASSERT(c.pc == (original_pc + 2));
} else {
RC_ASSERT(c.pc ==
(2 + original_pc + static_cast<signed char>(randimb)));
}
});
rc::PROPERTY("jr c", [&c, &m](const bool randcarry, const u8 randimb) {
c.cf = randcarry;
c.pc = *rc::gen::suchThat(rc::gen::arbitrary<u16>(), [](u16 x) {
return (127 < x) && (x < 0xffff);
});
const u16 original_pc = c.pc;
m[c.pc] = 0x38;
m[c.pc + 1] = randimb;
cpu::step(c, m);
if (!c.cf) {
RC_ASSERT(c.pc == (original_pc + 2));
} else {
RC_ASSERT(c.pc ==
(2 + original_pc + static_cast<signed char>(randimb)));
}
});
rc::PROPERTY("jr", [&c, &m](const u8 randimb) {
c.pc = *rc::gen::suchThat(rc::gen::arbitrary<u16>(), [](u16 x) {
return (127 < x) && (x < 0xffff);
});
const u16 original_pc = c.pc;
m[c.pc] = 0x18;
m[c.pc + 1] = randimb;
cpu::step(c, m);
RC_ASSERT(c.pc == (2 + original_pc + static_cast<signed char>(randimb)));
});
WHEN("jr nz true") {
m[c.pc] = 0x20;
m[c.pc + 1] = 0x10;
c.zf = false;
cpu::step(c, m);
THEN("jump, increment cycles by 12") {
REQUIRE(c.pc == 0x12);
REQUIRE(c.cycles == 12);
}
}
WHEN("jr nz false") {
m[c.pc] = 0x20;
m[c.pc + 1] = 0;
c.zf = true;
cpu::step(c, m);
THEN("no jump, pc increments by 2, cycles by 8") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 8);
}
}
WHEN("jr z true") {
m[c.pc] = 0x28;
m[c.pc + 1] = 0x10;
c.zf = true;
cpu::step(c, m);
THEN("jump, increment cycles by 12") {
REQUIRE(c.pc == 0x12);
REQUIRE(c.cycles == 12);
}
}
WHEN("jr z false") {
m[c.pc] = 0x28;
m[c.pc + 1] = 0;
c.zf = false;
cpu::step(c, m);
THEN("no jump, pc increments by 2, cycles by 8") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 8);
}
}
WHEN("jr nc true") {
m[c.pc] = 0x30;
m[c.pc + 1] = 0x10;
c.cf = false;
cpu::step(c, m);
THEN("jump, increment cycles by 12") {
REQUIRE(c.pc == 0x12);
REQUIRE(c.cycles == 12);
}
}
WHEN("jr nc false") {
m[c.pc] = 0x30;
m[c.pc + 1] = 0;
c.cf = true;
cpu::step(c, m);
THEN("no jump, pc increments by 2, cycles by 8") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 8);
}
}
WHEN("jr c true") {
m[c.pc] = 0x38;
m[c.pc + 1] = 0x10;
c.cf = true;
cpu::step(c, m);
THEN("jump, increment cycles by 12") {
REQUIRE(c.pc == 0x12);
REQUIRE(c.cycles == 12);
}
}
WHEN("jr z false") {
m[c.pc] = 0x38;
m[c.pc + 1] = 0;
c.cf = false;
cpu::step(c, m);
THEN("no jump, pc increments by 2, cycles by 8") {
REQUIRE(c.pc == 2);
REQUIRE(c.cycles == 8);
}
}
WHEN("jr") {
m[c.pc] = 0x18;
m[c.pc + 1] = 0x10;
cpu::step(c, m);
THEN("jump, increment cycles by 8") {
REQUIRE(c.pc == 0x12);
REQUIRE(c.cycles == 12);
}
}
}
}
| true |
090ebc9ca9ccaaf99f001f427c749f2cdc98ed29 | C++ | VZIKL/leetcode-test | /excel-sheet-column-title.cpp | UTF-8 | 371 | 3.046875 | 3 | [] | no_license | // File Name: excel-sheet-column-title.cpp
// Author:
// Mail:
// Created Time: 2016年12月19日 星期一 02时10分07秒
#include <iostream>
#include <string>
class Solution {
public:
std::string covertToTitle(int n) {
std::string result;
while (n) {
result = char((n - 1) % 26 + 'A') + result;
n = (n - 1) / 26;
}
return result;
}
};
| true |
1e23964caa54e71b82084efd9fe80fda92e75e5f | C++ | GDDXH/First-year-of-University | /hdu.cpp/杭电2060.cpp | UTF-8 | 582 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<string>
#include<cstring>
#include<cstdlib>
#include<vector>
using namespace std;
int main()
{
int amout,billiard,score1,score2,i,j;
cin>>amout;
while(amout--)
{
bool flag=false;
cin>>billiard>>score1>>score2;
if(billiard>6)
{
if(8*(billiard-6)+27+score1>=score2)
flag=true;
}
else
{
for(i=7,j=billiard;j>0;j--,i--)
{
score1+=i;
}
if(score1>=score2)
flag=true;
}
if(flag)
cout<<"Yes\n";
else
cout<<"No\n";
}
return 0;;
}
| true |
f70b1495d4679e3e723f2d1d50180ce07e1ed230 | C++ | li3939108/leetcode | /partitionList.cpp | UTF-8 | 932 | 3.484375 | 3 | [] | no_license | #include <iostream>
using namespace std ;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *partition(ListNode *head, int x) {
ListNode *lh = NULL, *gh = NULL, *ghead = NULL, *lhead = NULL;
while(head != NULL){
if(head->val < x){
ListNode *h = new ListNode(head->val);
if(lh == NULL){
lh = h ;
lhead = lh ;
}else{
lh->next = h;
lh = lh->next ;
}
}else{
ListNode *h = new ListNode(head->val) ;
if(gh == NULL){
gh = h ;
ghead = gh ;
}else{
gh->next = h;
gh = gh->next ;
}
}
head = head->next ;
}
if(lh != NULL){
lh->next = ghead ;
}else{
return ghead ;
}
return lhead ;
}
int main(){
ListNode in(1) ;
ListNode *r = partition(&in, 0);
cout << "haha\n" ;
while(r != NULL){
int val = r->val ;
cout << ' ' << '-' ;
cout << ' ' << val << '-' << endl;
r = r->next ;
}
cout << '\n' ;
return 0 ;
}
| true |
19fd19fab5cd7b714512c06f03ba7cc485ed846c | C++ | nancysolanki/hash-map.cpp | /highest freq.cpp | UTF-8 | 323 | 2.921875 | 3 | [] | no_license | #include<unordered_map>
int highestFrequency(int arr[], int n)
{
unordered_map<int,int>hm;
for(int i=0;i<n;i++)
{
hm[arr[i]]++;
}
int max=hm[arr[0]];
for(int i=0;i<n;i++)
{
if(hm[arr[i]]>hm[max])
{
max=arr[i];
return arr[i];
}
}
}
| true |
8a4b201fb0f63ebbbd4f4c5090fd2fabf3c74859 | C++ | 808wzrd/D4--Texted-Based-Game | /ProjectV2/player.hpp | UTF-8 | 549 | 2.796875 | 3 | [] | no_license | #include <string>
using namespace std;
class Player
{
public:
Player(string, int, string, string, int);
string showName();
string showWeapon();
string showGender();
void pickWeapon(string newWeapon);
int showHP();
void decreaseHP(int decrease);
void increaseHP(int increase);
int showAttack();
void setAttack(int newAttack);
vector<string> checkStatus();
void addToInventory(string weapon);
vector<string> showInventory();
void sortInventory();
private:
int hp, attack;
string name, weapon, gender;
vector<string> inventory;
}; | true |
833c72c733653871e6454a3e19b19383c589d711 | C++ | krre/qosg | /src/osg/ShapeDrawable.cpp | UTF-8 | 555 | 2.578125 | 3 | [] | no_license | #include "ShapeDrawable.h"
void ShapeDrawable::classBegin() {
if (osgObj == nullptr) {
osgObj = new osg::ShapeDrawable;
}
Drawable::classBegin();
}
void ShapeDrawable::setShape(Shape* shape) {
if (this->shape == shape) return;
this->shape = shape;
toOsg()->setShape(shape->toOsg());
emit shapeChanged(shape);
}
void ShapeDrawable::setColor(const QColor& color) {
osg::Vec4 vec4 = Converter::toVec4(color);
if (vec4 == toOsg()->getColor()) return;
toOsg()->setColor(vec4);
emit colorChanged(color);
}
| true |
05de24cbd7528d08a5cac69d602ed18b2ef28bee | C++ | ROHITKUCHERIA/Cpp_Programming_Basics | /C++/tut28.cpp | UTF-8 | 564 | 3.28125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Y; // forword diclaration
class X{
int data;
public:
void setValue(int value){
data= value;
}
friend void add(X,Y);
};
class Y{
int num;
public:
void setValue(int value){
num=value;
}
friend void add(X,Y);
};
void add(X o1, Y o2){
cout<<" Summing datas of X and Y Objects gives me : "<<o1.data+o2.num;
}
int main(){
X a;
a.setValue(3);
Y b;
b.setValue(5);
add(a,b);
return 0;
} | true |
0d277393691b6ce38b39b64b2ebc7e97c5d13ec6 | C++ | yogomi/tiny-examples | /thread/src/main.cc | UTF-8 | 2,301 | 3.015625 | 3 | [] | no_license | // Copyright 2015 Makoto Yano
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <list>
class HydraHead {
public:
HydraHead():counter_(0), beat_(false) {
hart_beats_.push_back(&beat_);
}
void Beat();
void HartBeat();
bool Continue() {return !finish_;}
void Finish() {finish_ = true;}
private:
int counter_;
bool beat_;
static bool finish_;
static std::list<bool *> hart_beats_;
static std::mutex m_;
static std::mutex hart_beat_mutex_;
static std::condition_variable cv_;
};
void HydraHead::Beat() {
std::unique_lock<std::mutex> uniq_lk(hart_beat_mutex_);
cv_.wait(uniq_lk, [&]{return beat_;});
std::cout << std::this_thread::get_id() << " : Wait Finish" << std::endl;
for (int i = 0; i < 20000; i++) {
int f;
}
// このmutexは文字列を整然と表記させるものなのでただのHartBeatには不要
std::lock_guard<std::mutex> lock(m_);
counter_++;
std::cout << std::this_thread::get_id() << " : " << counter_ << std::endl;
beat_ = false;
}
void HydraHead::HartBeat() {
{
std::unique_lock<std::mutex> uniq_lk(hart_beat_mutex_);
std::cout << std::this_thread::get_id() << " : Beat" << std::endl;
for_each(hart_beats_.begin(), hart_beats_.end(), [](bool *b){
*b = true;
});
cv_.notify_all();
}
while (std::any_of(hart_beats_.begin()
, hart_beats_.end()
, [](bool *b){return *b;})) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
bool HydraHead::finish_ = false;
std::mutex HydraHead::m_;
std::mutex HydraHead::hart_beat_mutex_;
std::condition_variable HydraHead::cv_;
std::list<bool *> HydraHead::hart_beats_;
void worker(HydraHead &h) {
while (h.Continue()) {
h.Beat();
}
}
int main() {
std::cout << "maaa" << std::endl;
HydraHead h1, h2, h3, h4, h5;
std::thread th(worker, std::ref(h1));
th.detach();
th = std::thread(worker, std::ref(h2));
th.detach();
th = std::thread(worker, std::ref(h3));
th.detach();
th = std::thread(worker, std::ref(h4));
th.detach();
th = std::thread(worker, std::ref(h5));
th.detach();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
for (int i = 0; i < 50000; i++) {
h1.HartBeat();
}
h1.Finish();
return 0;
}
| true |
d3c0ef85adb0bcff7a22a9a3933e0a1371138b5c | C++ | TarunSinghania/Prewritten-code | /Graphs/weightedgraph.cpp | UTF-8 | 1,343 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
//birdirectional weighted
using namespace std;
#define fr(i,a,b) for(int i =a ; i < b; i++)
#define mkp make_pair
#define pb push_back
#define pii pair<int,int>
#define speed ios::sync_with_stdio(false), cin.tie(0) , cout.tie(0)
//unidirected
//addedge
//veector array passed as refernce by default use structure wrapper for by value
int w[100001];
void ae(vector<int> v[] , int x ,int y){
v[x].push_back(y);
v[y].push_back(x);
}
void dfsu(int u ,vector<int> v[], vector<bool> &vis)
{
vis[u] = true;
cout<<u<<endl;
//can pass wiegth here directl global variable
for(int i = 0; i< v[u].size(); i++)
{
if(vis[v[u][i]]==false)
dfsu(v[u][i],v,vis);
}
}
//one node dfs
void dfs(vector<int> v[],int node,int size)
{
std::vector<bool> visited(size+1,false) ;
dfsu(node,v,visited);
}
//all node dfs
void dfscomp(vector<int> adj[],int size)
{
// std::vector<bool> (visited,false) ;
std::vector<int> tents;
//to contain the node id
std::vector<bool> visited(size+1,false) ;
fr(i,1,size+1){
if(visited[i]==false)
{
dfsu(i,adj,visited);
}
}//for
}
main()
{
int v, e;
cin>>v>>e;
//linked list
vector<int> adj[v+1];
fr(i,1,v+1)
cin>>w[i];
int u,b;
fr(i,0,e)
{
cin>>u>>b;
ae(adj,u,b);
}
dfscomp(adj,v);
} | true |
53a83a25639db29e11c88bf85b2732b5cf90a0f1 | C++ | gaohank/cxx-coding-project | /05_example/01_mystring/mystring.h | UTF-8 | 569 | 2.90625 | 3 | [] | no_license | #ifndef MYSTRING_H
#define MYSTRING_H
#include <stdio.h>
class mystring
{
public:
mystring(const char *str = "");
mystring(const mystring &another);
~mystring();
char *c_ptr();
void display();
mystring &operator=(const mystring &another);
mystring operator+(const mystring &another);
char& operator[](int pos);
bool operator>(const mystring &another);
bool operator<(const mystring &another);
bool operator==(const mystring &another);
char at(int pos);
private:
char *_str;
int size;
};
#endif // MYSTRING_H
| true |
541b7d60cbfe254591e35e6760c63b26f919974c | C++ | XavierFox12/CodingPortfolio | /Hocking College C++/Xavier_Fox_Chp_4_Exercise_4/Xavier_Fox_Chp_4_Exercise_4/Xavier_Fox_Chp_4_Exercise_4.cpp | UTF-8 | 1,702 | 3.640625 | 4 | [] | no_license | /* Program: Xavier_Fox_Chp_4_Exercise_4.cpp
Programmer: Xavier Fox
Date: 29 Sep. 2014
Purpose: To determine what shape the user entered
and determine its area, or circumference.
*/
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
const double PI = 3.1416;
int main()
{
string shape;
double height, length, width, radius;
cout << "Enter the shape type: (rectangle, circle, cylinder) ";
cin >> shape;
cout << endl;
cout << fixed << showpoint << setprecision(2);
if (shape == "rectangle")
{
cout << "Enter the length of the rectangle: ";
cin >> length;
cout << endl;
cout << "Enter the width of the rectangle: ";
cin >> width;
cout << endl;
cout << "Area of the rectangle = "
<< length * width << endl;
cout << "Perimeter of the rectangle = "
<< 2 * (length + width) << endl;
}
else if (shape == "circle")
{
cout << "Enter radius of the circle: ";
cin >> radius;
cout << endl;
cout << "Area of the circle = "
<< PI * pow(radius, 2.0) << endl;
cout << "Circumference of the circle: "
<< 2 * PI * radius << endl;
}
else if (shape == "cylinder")
{
cout << "Enter the height of the cylinder: ";
cin >> height;
cout << endl;
cout << "Enter the radius of the base of the cylinder: ";
cin >> radius;
cout << endl;
cout << "Volume of the cylinder = "
<< PI * pow(radius, 2.0)* height << endl;
cout << "Surface area of the cylinder: "
<< 2 * PI * radius * height + 2 * PI * pow(radius, 2.0)
<< endl;
}
else
cout << "The program does not handle " << shape << endl;
cout << endl << "Program by: Xavier Fox" << endl << endl;
return 0;
}
| true |
2e1b54c5aa6b4cd2508b7cbb25b538ba66cd5530 | C++ | andrewjianyoudai/Tutorial_Cpp | /Section4.1/CustmObjAsMapval/Source.cpp | UTF-8 | 1,103 | 4.09375 | 4 | [] | no_license | #include <iostream>
#include<map>
#include<string>
using namespace std;
class Person {
private:
string name;
int age;
public:
// Copy Constructor
Person(const Person &other) {
cout << "Copy constructor running !"<< endl;
name = other.name;
age = other.age;
}
// constructor with Nonparameter : default constructor with default parameters
Person() : name(""), age(0) { }
// constructor with parameter
Person(string name, int age) : name(name), age(age) { }
// print method
void print() {
cout << name << ": " << age << endl;
}
}; // class
/*
int main() {
// create the map
map<int, Person>people;
people[0] = Person("Mike", 40);
people[1] = Person("Vicky", 30);
people[2] = Person("William", 10);
people.insert(make_pair(55, Person("Bob", 38)));
people.insert(make_pair(88, Person("Emma", 24)));
// Iterator through the Map
for (map<int, Person>::iterator it = people.begin(); it != people.end(); it++) {
cout << it->first << ": " << flush; // sorted according to the key nr
it->second.print();
}
cin.get();
return 0;
}// main
*/ | true |
2e6e5083ef69ace68687812dbfa0a6151de3e75a | C++ | SebMenozzi/FPS | /client/src/gui/menu.h | UTF-8 | 737 | 2.59375 | 3 | [] | no_license | #ifndef MENU_H_INCLUDED
#define MENU_H_INCLUDED
#include <vector>
#include <string>
#include <SDL2/SDL.h>
#include "../types.h"
#include "widget.h"
#include "../texturesContainer.h"
class Menu
{
public:
Menu(SDL_Window* window, std::string backgroundImage);
~Menu();
void draw(bool8 force = FALSE);
void add(Widget* widget);
private:
bool8 change();
void animate();
void distributeEventToWidgets(SDL_Event evenement);
void focusToNext();
void drawBackground();
TexturesContainer texturesContainer;
std::vector<Widget*> widgetsList;
std::string backgroundImage;
bool8 stateChanged;
SDL_Window* window;
int windowWidth;
int windowHeight;
};
#endif // MENU_H_INCLUDED
| true |
594ae0c3d3a23fc527447a3e1f1d7a6ad7d929df | C++ | ttzztztz/leetcodeAlgorithms | /Lintcode/1504. Shortest Path to Get All Keys.cpp | UTF-8 | 2,109 | 2.578125 | 3 | [] | no_license | class Solution {
public:
/**
* @param grid:
* @return: The lowest number of moves to acquire all keys
*/
int N, M;
bool pointValid(int i, int j) {
return i >= 0 && j >= 0 && i < N && j < M;
}
int shortestPathAllKeys(vector<string> &grid) {
int startX = 0, startY = 0, keyCount = 0;
N = grid.size(), M = grid[0].size();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (grid[i][j] == '@') {
startX = i, startY = j;
} else if (grid[i][j] >= 'a' && grid[i][j] <= 'f') {
keyCount++;
}
}
}
const int mask = (1 << keyCount) - 1;
vector<vector<vector<bool>>> visited(mask + 5, vector<vector<bool>>(N + 5, vector<bool>(M + 5, false)));
deque<tuple<int, int, int>> q;
int answer = 0;
q.emplace_back(startX, startY, 0);
const int dx[] = {0, 0, -1, 1};
const int dy[] = {1, -1, 0, 0};
while (!q.empty()) {
const int Q = q.size();
for (int _ = 0; _ < Q; _++) {
int x, y, state;
tie(x, y, state) = q.front();
visited[state][x][y] = true;
q.pop_front();
for (int k = 0; k < 4; k++) {
const int nx = x + dx[k], ny = y + dy[k];
int ns = state;
if (!pointValid(nx, ny) || grid[nx][ny] == '#' || visited[ns][nx][ny]) continue;
if (grid[nx][ny] >= 'a' && grid[nx][ny] <= 'f') ns |= (1 << (grid[nx][ny] - 'a'));
if (grid[nx][ny] >= 'A' && grid[nx][ny] <= 'F' && !(state & (1 << (grid[nx][ny] - 'A')))) continue;
if (ns == mask) return answer + 1;
visited[ns][nx][ny] = true;
q.emplace_back(nx, ny, ns);
}
}
answer++;
}
return -1;
}
};
| true |
914320e7b9d8ede74197cf8a13f7b2f33d848501 | C++ | hhvyas/-365DaysOfCodes | /Day4(Heap).cpp | UTF-8 | 3,133 | 3.421875 | 3 | [] | no_license | /* Today I learnt about Heaps, and heap sort from https://www.youtube.com/watch?v=g9YK6sftDi0 it's very introductory video for learning about heap, and heap sort
After that to clear my doubts I refered to
https://www.youtube.com/watch?v=B7hVxCmfPtM&t=113s&ab_channel=MITOpenCourseWare (MIT) and https://www.geeksforgeeks.org/heap-data-structure/.
And further-more I solved some problems.. not many*
*/
/*A heap is one maximally efficient implementation of a priority queue.
We can have:
-) a min heap: min element can be peeked in constant time.
-) or a max heap: max element can be peeked in constant time.
The name of the heap indicates what we can peek in O(1) time.
We insert the item to the "end" of the complete binary tree (bottom right of the tree).
We "bubble up" the item to restore the heap. We keep bubbling up while there is a parent to compare against and that parent is greater than (in the case of a min heap) or less than (in the case of a max heap) the item. In those cases, the item we are bubbling up dominates its parent.
Removal from a binary heap:
We give the caller the item at the top of the heap and place the item at the "end" of the heap at the very "top".
We then "bubble the item down" to restore the heap property.
Min Heap: We keep swapping the value with the smallest child if the smallest child is less than the value we are bubbling down.
Max Heap: We keep swapping the value with the largest child if the largest child is greater than the value we are bubbling down.
In this manner, we restore the heap ordering property.
Insertion - O(log(n))
Deletion - O(log(n))
Peek - O(1).
-------------------------------------------
Heap Sort (O(n*log(n));
https://www.youtube.com/watch?v=B7hVxCmfPtM&t=113s&ab_channel=MITOpenCourseWare
Heap is tree representation of array..
root of tree:- first element of array.
parent(i) = i/2;
left(i) = 2*i
right = 2*i+1;
Max-Hip: If all parents node has value greater than or equal to all of his children..
used in priority queue --> take it, and delete it
if we continuesly take one by one element then, it will be in descending order.
Max-Heapify :-
Tree rooted at left(i) and right(i) are max-heaps.
Max_Heapify(2) -> both of it's child must be Max_Heap.
--> Will work bottom-up
Exchanege A
12
/ \
4 5
/ \ / \
10 8,9 11
Max_Heapify(1->index) call --> both of it's children's heapify property will be checked.. now
Max_Heapify(2-->(4)) isn't correct so, one of it's children will be on-place of parent.. so 4 and 8 will be leaf nodes.. same goes now for 5.. 11 will be in-place of 5. and recursive condition will end. (Stop when you reach at leaf nodes).
Psudo Code for max_heap->
for i = n/2 down to 1
do max_heapify(A, i) --> n/2 coz [n/2,..n] will be leaves.
1 4 5 10 8 9 11
n = 7;
n/2 = 3;
so max_heap(3) -> 12 10 5 4 8 9 11
Max_heap(2) -> 12 10 11 4 8 9 5 (Children value is more)
Max_heap(1) -> 12 10 11 4 8 9 5 -> Max_heap is built.
*/
https://atcoder.jp/contests/abc177/tasks/abc177_c
https://ideone.com/sRmhSj
https://codeforces.com/contest/27/problem/B
https://ideone.com/XKlXrR
| true |
bd5f3f02e4d18e36f9b5416dae12e565dae320e9 | C++ | j-jorge/tweenerspp | /include/tweeners/detail/slot_component.hpp | UTF-8 | 2,132 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef TWEENERS_DETAIL_SLOT_COMPONENT_HPP
#define TWEENERS_DETAIL_SLOT_COMPONENT_HPP
#include <vector>
namespace tweeners
{
namespace detail
{
/**
* \brief Associative container with fallback value for non existent keys.
*
* The intent of this container is to associate an optional value to a
* tweener slot in tweeners::system and store them in a cache-friendly way
* for efficient iteration.
*
* Instances of this container is supposed to contain as many entries
* (created with add_one_slot_at_end()) than there are slots in
* tweeners::system.
*
* The slots whose component are stored in slot_component are expected to
* be identified continuously from zero to n.
*/
template< typename T, typename Id >
class slot_component
{
public:
explicit slot_component( T default_value );
void reserve( std::size_t slot_count, std::size_t value_count );
void add_one_slot_at_end();
template< typename... Args >
void emplace( Id slot_id, Args&&... value );
bool has_value( Id slot_id ) const;
T& get_existing( Id slot_id );
const T& operator[]( Id i ) const;
template< typename Iterator >
void erase( Iterator first, Iterator last );
private:
void check_invariants() const;
private:
/**
* \brief The values asosciated with the slots.
*
* m_values[ 0 ] is the default value.
*/
std::vector< T > m_values;
/**
* \brief The index in m_values of the value associated with each slot.
*
* The slots having no associated value are assigned the index 0.
*/
std::vector< std::size_t > m_value_index_from_slot;
/**
* \brief Reverse lookup for m_value_index_from_slot.
*
* Given i, the entry m_slot_from_value_index[ i ] is the index in
* m_value_index_from_slot to which is associated the value m_values[ i ].
*/
std::vector< std::size_t > m_slot_from_value_index;
};
}
}
#include <tweeners/detail/slot_component.tpp>
#endif
| true |
77ad27d948cbbd827683d0636f785e395c566e90 | C++ | SneakerMa/CppLearning | /Chapter_2/Sample_3.cpp | UTF-8 | 712 | 3.28125 | 3 | [] | no_license | #include <iostream>
int main() {
int ival = 1024;
int &refVal = ival; // refVal refers to (is another name for) ival
//int &refVal2; // error: a reference must be initialized
refVal = 2; // assigns 2 to the object to which refVal refers, i.e., to ival
int ii = refVal; // same as ii = ival
// ok: refVal3 is bound to the object to which refVal is bound, i.e., to value_comp
int &refVal3 = refVal;
// initializes i from the value in the object to which refVal is bound
int i = refVal; // ok: initializes i to the same value as ival
int &refVal4 = 10; // error: initializer must be an object
double dval = 3.14;
int &refVal5 = dval; // error: initializer must be an int object
return 0;
} | true |
2056cdb1563664724865ac86cd4855b79c6bc223 | C++ | dcheng0/os-spring-2019 | /data_structures/queue/bound_buffer.h | UTF-8 | 1,026 | 2.734375 | 3 | [] | no_license | #ifndef DOCUMENTS_BOUND_BUFFER_H
#define DOCUMENTS_BOUND_BUFFER_H
#include <vector>
namespace data_structures {
template<typename ValueType>
class BoundBuffer {
public:
private:
const int max_size_;
int size_;
int nextIn_;
int nextOut_;
typedef std::vector<int> BufferList;
typedef std::unique_ptr<BufferList[]> storage_;
public:
explicit BoundBuffer(int max_size) : max_size_(max_size) {}
int nextIn() {
return (nextIn_);
}
int nextOut() {
return (nextOut_);
}
int size() {
return size_;
}
void addLast(const ValueType& value) {
//BufferList &list = storage_.begin(); //, storage_.end());
nextIn_ = value;
nextIn_ = (nextIn() + 1) % size();
}
ValueType removeFirst() {
return ValueType();
}
};
} // namespace data_structures
#endif //DOCUMENTS_BOUND_BUFFER_H
// used the following link for conceptual help
// https://github.com/uu-os-2018/module-4/blob/master/mandatory/src/bounded_buffer.c | true |
0b4ee4c71c0d772493d15712a4ffc727b2fb3c0a | C++ | Chaitanya142/Win32-COM | /Project/ChemDll/Source.cpp | UTF-8 | 7,029 | 2.625 | 3 | [] | no_license | #include "ChemDllHeader.h"
class CGayLussacsLawCalculator :public ICIP, ICIT, ICFP, ICFT {
private:
long m_cRef;
public:
CGayLussacsLawCalculator();
~CGayLussacsLawCalculator();
HRESULT __stdcall QueryInterface(REFIID, void **);
ULONG __stdcall AddRef(void);
ULONG __stdcall Release(void);
HRESULT __stdcall CalculateInitialPressure(double *, double, double, double );
HRESULT __stdcall CalculateInitialTemp(double, double *, double, double );
HRESULT __stdcall CalculateFinalPressure(double, double, double *, double);
HRESULT __stdcall CalculateFinalTemp(double, double, double, double *);
};
class CGayLussacsLawCalculatorClassFactory :public IClassFactory {
private:
long m_cRef;
public:
CGayLussacsLawCalculatorClassFactory(void);
~CGayLussacsLawCalculatorClassFactory(void);
HRESULT __stdcall QueryInterface(REFIID, void **);
ULONG __stdcall AddRef(void);
ULONG __stdcall Release(void);
HRESULT __stdcall CreateInstance(IUnknown *, REFIID, void **);
HRESULT __stdcall LockServer(BOOL);
};
long glNumberOfActiveComponents = 0;
long glNumberOfServerLocks = 0;
HMODULE ghModule;
BOOL WINAPI DllMain(HINSTANCE hDll, DWORD dwReason, LPVOID Reserved) {
switch (dwReason) {
case DLL_PROCESS_ATTACH:
ghModule = hDll;
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return(TRUE);
}
CGayLussacsLawCalculator::CGayLussacsLawCalculator()
{
m_cRef = 1;
InterlockedIncrement(&glNumberOfActiveComponents);
}
CGayLussacsLawCalculator::~CGayLussacsLawCalculator()
{
InterlockedDecrement(&glNumberOfActiveComponents);
}
HRESULT __stdcall CGayLussacsLawCalculator::QueryInterface(REFIID riid, void **ppv)
{
if (riid == IID_IUnknown)
*ppv = static_cast<ICIP*>(this);
else if (riid == IID_ICIP)
*ppv = static_cast<ICIP*>(this);
else if (riid == IID_ICIT)
*ppv = static_cast<ICIT*>(this);
else if (riid == IID_ICFP)
*ppv = static_cast<ICFP *>(this);
else if (riid == IID_ICFT)
*ppv = static_cast<ICFT *>(this);
else
{
*ppv = NULL;
return(E_NOINTERFACE);
}
reinterpret_cast<IUnknown *>(*ppv)->AddRef();
return(S_OK);
}
ULONG __stdcall CGayLussacsLawCalculator::AddRef(void)
{
InterlockedIncrement(&m_cRef);
return (m_cRef);
}
ULONG __stdcall CGayLussacsLawCalculator::Release(void)
{
InterlockedDecrement(&m_cRef);
if (m_cRef == 0) {
delete(this);
return(0);
}
return (m_cRef);
}
HRESULT __stdcall CGayLussacsLawCalculator::CalculateInitialPressure(double * Pi, double Ti, double Pf, double Tf)
{
*Pi = Pf * Ti / Tf;
return(S_OK);
}
HRESULT __stdcall CGayLussacsLawCalculator::CalculateInitialTemp(double Pi, double *Ti, double Pf, double Tf)
{
*Ti = Pi * Tf / Pf;
return (S_OK);
}
HRESULT __stdcall CGayLussacsLawCalculator::CalculateFinalPressure(double Pi, double Ti, double * Pf, double Tf)
{
*Pf = Pi *Tf/ Ti;
return (S_OK);
}
HRESULT __stdcall CGayLussacsLawCalculator::CalculateFinalTemp(double Pi, double Ti, double Pf, double *Tf)
{
*Tf=Pf * Ti / Pi;
return (S_OK);
}
CGayLussacsLawCalculatorClassFactory::CGayLussacsLawCalculatorClassFactory(void)
{
m_cRef = 1;
}
CGayLussacsLawCalculatorClassFactory::~CGayLussacsLawCalculatorClassFactory(void)
{
}
HRESULT __stdcall CGayLussacsLawCalculatorClassFactory::QueryInterface(REFIID riid, void ** ppv)
{
if (riid == IID_IUnknown)
*ppv = static_cast<IClassFactory *>(this);
else if(riid==IID_IClassFactory)
*ppv = static_cast<IClassFactory *>(this);
else {
*ppv = NULL;
return(E_NOINTERFACE);
}
reinterpret_cast<IUnknown *>(this)->AddRef();
return(S_OK);
}
ULONG __stdcall CGayLussacsLawCalculatorClassFactory::AddRef(void)
{
InterlockedIncrement(&m_cRef);
return (m_cRef);
}
ULONG __stdcall CGayLussacsLawCalculatorClassFactory::Release(void)
{
InterlockedDecrement(&m_cRef);
if (m_cRef == 0) {
delete(this);
return(0);
}
return m_cRef;
}
HRESULT __stdcall CGayLussacsLawCalculatorClassFactory::CreateInstance(IUnknown * pUnkOuter, REFIID riid, void **ppv)
{
CGayLussacsLawCalculator * pCGayLussacsLawCalculator;
HRESULT hr;
if (pUnkOuter != NULL)
return (CLASS_E_NOAGGREGATION);
pCGayLussacsLawCalculator = new CGayLussacsLawCalculator();
if (pCGayLussacsLawCalculator == NULL)
return(E_OUTOFMEMORY);
hr = pCGayLussacsLawCalculator->QueryInterface(riid, ppv);
pCGayLussacsLawCalculator->Release();
return(hr);
}
HRESULT __stdcall CGayLussacsLawCalculatorClassFactory::LockServer(BOOL fLock)
{
if (fLock)
InterlockedIncrement(&glNumberOfServerLocks);
else
InterlockedDecrement(&glNumberOfServerLocks);
return(S_OK);
}
HRESULT __stdcall DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppv) {
CGayLussacsLawCalculatorClassFactory *pCGayLussacsLawCalculatorClassFactory = NULL;
HRESULT hr;
if (rclsid != CLSID_GayLussacsLawCalculator)
return (CLASS_E_CLASSNOTAVAILABLE);
pCGayLussacsLawCalculatorClassFactory = new CGayLussacsLawCalculatorClassFactory();
if (pCGayLussacsLawCalculatorClassFactory == NULL)
return(E_OUTOFMEMORY);
hr = pCGayLussacsLawCalculatorClassFactory->QueryInterface(riid, ppv);
pCGayLussacsLawCalculatorClassFactory->Release();
return(hr);
}
HRESULT __stdcall DllCanUnloadNow(void) {
if ((glNumberOfActiveComponents == 0) && (glNumberOfServerLocks == 0))
return(S_OK);
else
return(S_FALSE);
}
STDAPI DllRegisterServer() {
//MessageBox(NULL, "1", "E", MB_OK);
HKEY hCLSIDKey = NULL,hInProcSvrKey=NULL;
LONG lRet;
TCHAR szModulePath[MAX_PATH];
TCHAR szClassDescription[] = TEXT("Chem COM Dll");
TCHAR szThreadingModel[] = TEXT("Apartment");
__try {
lRet = RegCreateKeyEx(HKEY_CLASSES_ROOT, TEXT("CLSID\\{B8A96FF5-94C9-43FD-911C-D2C5E582C1E6}"), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE | KEY_CREATE_SUB_KEY, NULL, &hCLSIDKey, NULL);
if (ERROR_SUCCESS != lRet)
return HRESULT_FROM_WIN32(lRet);
lRet = RegSetValueEx(hCLSIDKey,NULL,0,REG_SZ,(const BYTE *)szClassDescription,sizeof(szClassDescription));
if(ERROR_SUCCESS != lRet)
return HRESULT_FROM_WIN32(lRet);
lRet = RegCreateKeyEx(hCLSIDKey, TEXT("InProcServer32"), 0, NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE, NULL, &hInProcSvrKey, NULL);
if(ERROR_SUCCESS !=lRet)
return HRESULT_FROM_WIN32(lRet);
GetModuleFileName(ghModule, szModulePath, MAX_PATH);
lRet = RegSetValueEx(hInProcSvrKey,NULL,0,REG_SZ,(const BYTE *)szModulePath,sizeof(TCHAR)* (lstrlen(szModulePath)+1));
if(ERROR_SUCCESS != lRet)
return HRESULT_FROM_WIN32(lRet);
lRet = RegSetValueEx(hInProcSvrKey, TEXT("ThreadingModel"), 0, REG_SZ, (const BYTE *)szThreadingModel, sizeof(szThreadingModel));
if (ERROR_SUCCESS != lRet)
return HRESULT_FROM_WIN32(lRet);
}
__finally {
if (NULL != hCLSIDKey)
RegCloseKey(hCLSIDKey);
if (NULL != hInProcSvrKey)
RegCloseKey(hInProcSvrKey);
}
return(S_OK);
}
STDAPI DllUnregisterServer() {
RegDeleteKey(HKEY_CLASSES_ROOT,TEXT("CLSID\\{B8A96FF5-94C9-43FD-911C-D2C5E582C1E6}\\InProcServer32"));
RegDeleteKey(HKEY_CLASSES_ROOT, TEXT("CLSID\\{B8A96FF5-94C9-43FD-911C-D2C5E582C1E6}"));
return S_OK;
}
| true |
6fa2865dbf28246595cf6e4a0b3d4075dfaa2600 | C++ | dhawt/Immerse | /Code/GeomMngr/imr_gm_figure.cpp | UTF-8 | 14,287 | 2.625 | 3 | [] | no_license | /****************************************************************\
iMMERSE Engine
(C) 1999 No Tears Shed Software
All rights reserved
Filename: IMR_GM_Figure.hpp
Description: Figure module
\****************************************************************/
#include "IMR_GM_Figure.hpp"
/***************************************************************************\
**
** Skeleton Segment stuff
**
\***************************************************************************/
/***************************************************************************\
Sets the name of the skeleton segment.
\***************************************************************************/
void IMR_SkelSegment::Set_Name(char *NewName)
{
if (strlen(NewName) > 8)
{
memcpy((void *)Name, (void *)NewName, 8);
Name[8] = '/0';
}
else
strcpy(Name, NewName);
}
/***************************************************************************\
Sets the name of the object for skeleton segment.
\***************************************************************************/
void IMR_SkelSegment::Set_ObjectName(char *Name)
{
if (strlen(Name) > 8)
{
memcpy((void *)ObjName, (void *)Name, 8);
ObjName[8] = '/0';
}
else
strcpy(ObjName, Name);
}
/***************************************************************************\
**
** Key skeleton stuff
**
\***************************************************************************/
/***************************************************************************\
Sets the name of the skeleton.
\***************************************************************************/
void IMR_Skeleton::Set_Name(char *NewName)
{
if (strlen(NewName) > 8)
{
memcpy((void *)Name, (void *)NewName, 8);
Name[8] = '/0';
}
else
strcpy(Name, NewName);
}
/***************************************************************************\
Searches the specified lists for the objects to attach to each segment.
\***************************************************************************/
int IMR_Skeleton::Setup(IMR_NamedList<IMR_Object> *GlbObj,
IMR_NamedList<IMR_Object> *LocObj)
{
IMR_SkelSegment *CurrSeg = Segs;
char *ObjName;
IMR_Object *Tmp;
// Loop while we have a segment:
while (CurrSeg)
{
// Get the name of the object for the segment:
ObjName = CurrSeg->Get_ObjectName();
// Search the local list (if there is one) for the object:
if (LocObj)
Tmp = LocObj->Get_Item(ObjName, NULL);
// If we haven't found the object already, search the global list:
if (!Tmp && GlbObj)
Tmp = GlbObj->Get_Item(ObjName, NULL);
// Set the object:
CurrSeg->Set_Object(Tmp);
// Set next segment:
CurrSeg = CurrSeg->Get_Next();
}
// And return ok:
return IMR_OK;
}
/***************************************************************************\
Adds a new segment into the skeleton.
Returns IMR_OK if successful, otherwise an error.
\***************************************************************************/
int IMR_Skeleton::Add_Segment(char *Name)
{
IMR_SkelSegment *NewSeg;
// Create a new segment:
NewSeg = new IMR_SkelSegment;
// If we're out of memory, return an error:
if (!NewSeg)
{
IMR_LogMsg(__LINE__, __FILE__, "IMR_Skeleton::Add_Segment(): Out of memory in segment %s!", Name);
return IMRERR_OUTOFMEM;
}
// Now make this segment the head:
NewSeg->Set_Next(Segs);
Segs = NewSeg;
// And give it a name:
NewSeg->Set_Name(Name);
// One more segment:
++ Num_Segs;
// And return ok:
return IMR_OK;
}
/***************************************************************************\
Returns a pointer to the specified segment if found, otherwise NULL.
\***************************************************************************/
IMR_SkelSegment *IMR_Skeleton::Get_Segment(char *Name)
{
IMR_SkelSegment *Curr = Segs;
// Loop while we have a segment:
while (Curr)
{
if (Curr->Is(Name))
return Curr;
Curr = Curr->Get_Next();
}
// No segment by that name, so return null:
return NULL;
}
/***************************************************************************\
Deletes the specified segment.
\***************************************************************************/
void IMR_Skeleton::Delete_Segment(char *Name)
{
IMR_SkelSegment *Curr = Segs,
*Prev = NULL;
// Find the specified segment:
while (Curr && !Curr->Is(Name))
{
Prev = Curr;
Curr = Curr->Get_Next();
}
// If we couldn't find the segment, return:
if (!Curr) return;
// Unlink the segment:
if (Prev)
Prev->Set_Next(Curr->Get_Next());
else
Segs = Curr->Get_Next();
// And delete the node:
delete Curr;
// One less seg:
++ Num_Segs;
}
/***************************************************************************\
Deletes all the segments in the list.
\***************************************************************************/
void IMR_Skeleton::Wipe_Segments(void)
{
IMR_SkelSegment *Curr = Segs, *Next;
// Loop and delete while we have a segment:
while (Curr)
{
Next = Curr->Get_Next();
delete Curr;
Curr = Next;
}
// And set segs to null:
Segs = NULL;
Num_Segs = 0;
}
/***************************************************************************\
**
** Keyed figure stuff
**
\***************************************************************************/
/***************************************************************************\
Sets the name of the figure.
\***************************************************************************/
void IMR_Figure::Set_Name(char *NewName)
{
if (strlen(NewName) > 8)
{
memcpy((void *)Name, (void *)NewName, 8);
Name[8] = '/0';
}
else
strcpy(Name, NewName);
}
/***************************************************************************\
Sets up the figure.
\***************************************************************************/
int IMR_Figure::Setup(IMR_NamedList<IMR_Object> *GlbObj,
IMR_NamedList<IMR_Object> *LocObj)
{
IMR_Skeleton *CurrKey = Keys;
IMR_Object *Tmp;
// Setup our root object (if it hasn't been already):
if (!RootObj)
{
if (LocObj) Tmp = LocObj->Get_Item(RootObjName, NULL);
if (!Tmp && GlbObj)
Tmp = GlbObj->Get_Item(RootObjName, NULL);
Set_RootObj(Tmp);
}
// Loop while we have a key skeleton:
while (CurrKey)
{
// Setup the key:
CurrKey->Setup(GlbObj, LocObj);
// Set next key:
CurrKey = CurrKey->Get_Next();
}
// And return ok:
return IMR_OK;
}
/***************************************************************************\
Adds a new key into the figure.
Returns IMR_OK if successful, otherwise an error.
\***************************************************************************/
int IMR_Figure::Add_Key(char *Name)
{
IMR_Skeleton *NewKey;
// Create a new key:
NewKey = new IMR_Skeleton;
// If we're out of memory, return an error:
if (!NewKey)
{
IMR_LogMsg(__LINE__, __FILE__, "IMR_Figure::Add_Key(): Out of memory in skeleton %s!", Name);
return IMRERR_OUTOFMEM;
}
// Now make this segment the head:
NewKey->Set_Next(Keys);
Keys = NewKey;
// And give it a name:
NewKey->Set_Name(Name);
// One more key:
++ Num_Keys;
// And return ok:
return IMR_OK;
}
/***************************************************************************\
Returns a pointer to the specified key if found, otherwise NULL.
\***************************************************************************/
IMR_Skeleton *IMR_Figure::Get_Key(char *Name)
{
IMR_Skeleton *Curr = Keys;
// Loop while we have a key:
while (Curr)
{
if (Curr->Is(Name))
return Curr;
Curr = Curr->Get_Next();
}
// No key by that name, so return null:
return NULL;
}
/***************************************************************************\
Deletes the specified key.
\***************************************************************************/
void IMR_Figure::Delete_Key(char *Name)
{
IMR_Skeleton *Curr = Keys, *Prev = NULL;
// Find the specified key:
while (Curr && !Curr->Is(Name))
{
Prev = Curr;
Curr = Curr->Get_Next();
}
// If we couldn't find the key, return:
if (!Curr) return;
// Unlink the key:
if (Prev)
Prev->Set_Next(Curr->Get_Next());
else
Keys = Curr->Get_Next();
// And delete the node:
delete Curr;
// One less key:
++ Num_Keys;
}
/***************************************************************************\
Deletes all the keys in the list.
\***************************************************************************/
void IMR_Figure::Wipe_Keys(void)
{
IMR_Skeleton *Curr = Keys, *Next;
// Loop and delete while we have a key:
while (Curr)
{
Next = Curr->Get_Next();
delete Curr;
Curr = Next;
}
// And set keys to null:
Keys = NULL;
Num_Keys = 0;
}
/***************************************************************************\
"Jumps" the figure to the specified relative position and attitude.
\***************************************************************************/
void IMR_Figure::Animation_Jump(char *KeyName)
{
IMR_Skeleton *Key;
IMR_SkelSegment *Seg;
IMR_Object *Obj;
// Find the specified key:
if (!(Key = Get_Key(KeyName))) return;
// Now loop through all the segments in the key:
Seg = Key->GetFirstSegment();
while (Seg)
{
// Get the object:
Obj = Seg->Get_Object();
// Make sure there is an object:
if (Obj) Obj->Animation_Jump(Seg->Get_Pos(), Seg->Get_Atd());
// Get the next segment:
Seg = Seg->Get_Next();
}
}
/***************************************************************************\
Initializes an animation to the specified relative position and attitude
over the specified number of frames.
\***************************************************************************/
void IMR_Figure::Animation_Init(char *KeyName, int Length)
{
IMR_Skeleton *Key;
IMR_SkelSegment *Seg;
IMR_Object *Obj;
// Find the specified key:
if (!(Key = Get_Key(KeyName))) return;
// Now loop through all the segments in the key:
Seg = Key->GetFirstSegment();
while (Seg)
{
// Get the object:
Obj = Seg->Get_Object();
// Make sure there is an object:
if (Obj)
Obj->Animation_Init(Seg->Get_Pos(), Seg->Get_Atd(), Length);
// Get the next segment:
Seg = Seg->Get_Next();
}
// Now setup stuff:
Animation_Status = IMR_ANIMATION_ACTIVE;
Animation_Time = 0;
Animation_Length = Length;
Animation_Key = Key;
}
/***************************************************************************\
Changes to the next frame in an animation.
\***************************************************************************/
int IMR_Figure::Animation_Step(void)
{
IMR_Skeleton *Key;
IMR_SkelSegment *Seg;
IMR_Object *Obj;
// Make sure an animation is in progress:
if (Animation_Status == IMR_ANIMATION_DONE) return IMR_ANIMATION_DONE;
// Find the specified key:
Key = Animation_Key;
// Now loop through all the segments in the key:
Seg = Key->GetFirstSegment();
while (Seg)
{
// Get the object:
Obj = Seg->Get_Object();
// Make sure there is an object:
if (Obj) Obj->Animation_Step();
// Get the next segment:
Seg = Seg->Get_Next();
}
// Increment counter:
Animation_Time += IMR_Time_GetFrameTime();
// Tell the user our status:
if (Animation_Time >= Animation_Length)
{
Animation_Status = IMR_ANIMATION_DONE;
return IMR_ANIMATION_DONE;
}
else
{
Animation_Status = IMR_ANIMATION_ACTIVE;
return IMR_ANIMATION_ACTIVE;
}
}
/***************************************************************************\
Writes the figure to the specified RDF.
Returns OK if succesfull.
\***************************************************************************/
/*
int IMR_Figure::Write_RDF(char *Filename)
{
IMR_Segment *Current;
IMR_ObjectKF_Joint *Curr_Joint;
int Current_Seg, Current_KF;
int RDF, Temp;
// Open the file:
RDF = open(Filename, O_RDWR | O_BINARY | O_CREAT | O_TRUNC,
S_IWUSR | S_IRUSR);
// If we can't, return an error:
if (RDF == -1)
{
ErrorCall("Could not open %s! (Object::Write_RDF())", Filename);
return ERR_BADFILE;
}
// Write id string:
write(RDF, "OBJ", 3);
// Write name of object:
write(RDF, Name, 8);
// Write number of segs:
write(RDF, &Num_Segs, 2);
// Write number of keyframes:
write(RDF, &Num_Keyframes, 2);
// Loop through each seg and write it to the file:
for (Current_Seg = 0; Current_Seg < Num_Segs; ++ Current_Seg)
{
// Set the current segment to this seg:
Current = Seg_List[Current_Seg];
// Write the name of the segment:
write(RDF, Current->Name, 8);
// Write the name of the model attached to this segment:
write(RDF, Current->Model_Name, 8);
// Write the pos:
Temp = Current->Position.X >> 16; write(RDF, &Temp, 2);
Temp = Current->Position.Y >> 16; write(RDF, &Temp, 2);
Temp = Current->Position.Z >> 16; write(RDF, &Temp, 2);
// Write the angle:
write(RDF, &Current->Angle.X, 2);
write(RDF, &Current->Angle.Y, 2);
write(RDF, &Current->Angle.Z, 2);
}
// Write all the keyframes:
for (Current_KF = 0; Current_KF < Num_Keyframes; Current_KF ++)
{
// Write the name of the keyframe:
write(RDF, Keyframes[Current_KF].Name, 8);
// Write the number of joints in the keyframe:
write(RDF, &Keyframes[Current_KF].Num_Joints, 2);
// Write all the joints:
Curr_Joint = Keyframes[Current_KF].JointList;
while (Curr_Joint)
{
// Write the segment for the joint:
write(RDF, Curr_Joint->Seg_Name, 8);
// Write the pos:
Temp = Curr_Joint->Position.X >> 16; write(RDF, &Temp, 2);
Temp = Curr_Joint->Position.Y >> 16; write(RDF, &Temp, 2);
Temp = Curr_Joint->Position.Z >> 16; write(RDF, &Temp, 2);
// Write the angle:
write(RDF, &Curr_Joint->Angle.X, 2);
write(RDF, &Curr_Joint->Angle.Y, 2);
write(RDF, &Curr_Joint->Angle.Z, 2);
// Set next joint:
Curr_Joint = Curr_Joint->Next;
}
}
// Close the file:
close(RDF);
// And return OK:
return OK;
}
*/
| true |
8f74eb3945dd5bb18d67167544018bf95256f8b1 | C++ | alerodriguezz/teacher_grading_system | /project3_rodriguez.cpp | UTF-8 | 11,305 | 3.6875 | 4 | [] | no_license | /*
Title: Project 3
Abstract: This program will read a file that reads a student's name, id, five quiz scores, two midterm scores, and one final scores. This program and calculate the numeric average, letter grade, and ranking of each student. After that,
your program should display the course result in order of numeric averages and first names respectively. This program will display results in a histogram.
Author: Alex Rodriguuez
Date: 5/6/15
*/
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <iomanip>
using namespace std;
class Student
{
private:
string name;
int id;
double avg;
double final_scor;
char grade_lttr;
int rank;
public:
Student();
void summary();
//get functions
double getavg();
char getgrade_lttr();
int getid();
string get_name();
//set function
void setstudentinfo(string newName, int newID, double newAvg);
void setrank(int newRank);
void setGrade_Lttr();
};
//Prototype
int read_file(Student students[]);
void numericalavg_header();
void s_sort(Student students[], int size);
void abc_sort(Student x[], int n);
void search_name(Student students[],int size,string name);
//main function
int main(void)
{
Student students[30];
int size = read_file(students);
//sorts student ranks
s_sort(students,size);
//prints out numerical average header
//Header
cout <<"-------------------------------------------------\n"
<< "Course Report: Numerical Average Order\n"
<<"-------------------------------------------------\n";
//format and alignment
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.setf(ios::left);
cout.precision(2);
//assigns ranks to private varibale "rank"
int r=1;
int count=1;
for(int i=0; i < size; i++) //assigns ranks
{
if (students[i].getavg()==students[i+1].getavg())
{
r=count;
students[i].setrank(r);
count++;
}
else if (students[i].getavg()!=students[i+1].getavg())
{
students[i].setrank(r);
r++;
count++;
}
}
//for loop that prints out students in order of rank
for(int i=0; i < size; i++)
{
students[i].summary();
}
cout << "-------------------------------------------------\n\n"
<<"-------------------------------------------------\n"
<<"Course Report: First Name Order\n"
<<"-------------------------------------------------\n";
//call abc sorting function
abc_sort(students,size);
for (int i=0; i < size; i++)
{
students[i].summary();
}
cout <<"-------------------------------------------------\n\n";
//Statistics header
cout <<"-------------------------------------------------\n"
<< "Statistics\n"
<<"-------------------------------------------------\n";
//Number of Students
cout << "Number of Students: " << size<<endl;
//Class Average Calculations
double class_total=0, class_avg=0;
for (int i=0;i<size;i++)
{
class_total= class_total+students[i].getavg();
}
class_avg=class_total/size;
cout << "Class Average: " << class_avg <<endl;
//Histogram
cout<< "Grade Average Distribution\n";
//counts number of grades for each student
int letter_counts[5]={0};
int count_a=0, count_b=0, count_c=0, count_d=0,count_f=0;
//grade letter conditionals
for (int i=0;i<size;i++)
{
if (students[i].getavg() >= 90)
{ //A value goes up by one
letter_counts[0]++;
}
if ( students[i].getavg()< 90 && students[i].getavg() >= 80)
{//B Value goes up
letter_counts[1]++;
}
if (students[i].getavg() < 80 && students[i].getavg()>= 70)
{//C value goes up
letter_counts[2]++;
}
if (students[i].getavg() < 70 && students[i].getavg() >= 60)
{//D value goes up
letter_counts[3]++;
}
if (students[i].getavg() <60&& students[i].getavg()>=0)
{//F value goes up
letter_counts[4]++;
}
}
//code for histogram
double heights[5]={0};
int x,y; //set histogram variables
for (x=0; x<5; x++)
{
heights[x]=letter_counts[x]; //grade counts get placed into heights array
}
for (y=size; y>=0; y--) //prints out stars vertically
{
for (x=0; x<5; x++)
{
if (heights[x]<=y)
{ cout << " ";}
else
{ cout << " * ";}
//sets width
}
cout << endl;
}
cout<<" A B C D F" <<endl;
cout<<"-------------------------------------------------\n"
//Record Finder Part
<<"-------------------------------------------------\n";
string student_name;
cout<<"Record Finder: Enter the name of a student: "; cin>> student_name;
cout<<"-------------------------------------------------\n";
//program that searches for user's input
search_name(students,size,student_name);
// User is asked if he/she would like to continue
cout<<"-------------------------------------------------\n";
char answer;
cout << "Do you want to continue? (y/n): "; cin >> answer;
cout<<"-------------------------------------------------\n";
//if yes
while (answer=='y'||answer=='Y')
{
cout << "Record Finder: Enter the name of a student: "; cin >> student_name;
cout <<"-------------------------------------------------\n";
search_name(students,size,student_name);
cout <<"-------------------------------------------------\n"
<<"Do you want to continue? (y/n): "; cin >> answer;
cout<<"-------------------------------------------------\n";
if (answer=='n'||answer=='N')
break;
}
//if no
if (answer=='n'||answer=='N')
{
cout <<"Done.\n";
}
return 0;
}
char Student::getgrade_lttr()
{
char newGrade_Lttr=grade_lttr;
return newGrade_Lttr;
}
void Student::setGrade_Lttr()
{
//grade letter conditionals
if (avg >= 90)
{
grade_lttr = 'A';
}
if (avg < 90 && avg >= 80)
{
grade_lttr = 'B';
}
if (avg < 80 && avg >= 70)
{
grade_lttr = 'C';
}
if (avg < 70 && avg >= 60)
{
grade_lttr = 'D';
}
if (avg < 60)
{
grade_lttr = 'F';
}
}
void Student::summary() //summary function definition
{ cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.setf(ios::left);
cout.precision(2);
cout.width(6);
cout << name << id << " - " << avg << " (" << grade_lttr << ") (rank: " << rank << ")" << endl;
}
Student::Student() //default constructor
{
name = "Alex";
id=0000;
avg=00;
}
int read_file(Student students[])
{
ifstream in_file;
string name;
int id;
double quiz_scor[5];
double midterm_scor[2];
double final_scor;
double numeric_avg=0;
//ask user to input file
string filepath;
cout<< "Enter an input file: ";
cin>> filepath;
in_file.open(filepath);
//in_file.open("studentinfo.txt");
if(in_file.fail())
{
cout << "Error, file could not open.\n";
}
int i=0;
while (!in_file.eof())
{
in_file>> name >> id >> quiz_scor[0] >> quiz_scor[1] >> quiz_scor[2] >> quiz_scor[3] >> quiz_scor[4] >> midterm_scor[0] >> midterm_scor[1] >> final_scor;
//sort quiz scores from least to greatest
int quiz_size=5;
//sorts through wach element of the array
for (int start_indx=0; start_indx<quiz_size; start_indx++)
{
//temp variable for smallest value
int smallestindx= start_indx;
//sorts through quiz scores array atarting at quizstart+1
for (int currentindx=start_indx+1;currentindx <quiz_size; currentindx++)
{
if (quiz_scor[currentindx]< quiz_scor[smallestindx])
smallestindx=currentindx;
}
//swap smallest number from inner-most for loop with the new smallest index
swap(quiz_scor[start_indx], quiz_scor[smallestindx]);
}
//disregards first quiz score and calculates quiz average
double quiz_total=0;
double quiz_avg=0;
for ( int g=1; g< quiz_size; g++)
{
quiz_total= quiz_total+quiz_scor[g];
}
quiz_avg=quiz_total/4;
quiz_avg=quiz_avg*10;
// Calculates total mid-term average
double midterm_total, midterm_avg;
midterm_total=midterm_scor[0]+midterm_scor[1];
midterm_avg=midterm_total/2;
//Calculates Overall Student Average
numeric_avg=(quiz_avg*.20)+(midterm_avg*.40)+(final_scor*.40);
students[i].setstudentinfo(name, id, numeric_avg);
i++;
}
return i;
}
void Student::setrank(int newRank)
{
rank=newRank;
}
void Student::setstudentinfo(string newName, int newID, double newAvg)
{
name = newName;
id = newID;
avg = newAvg;
setGrade_Lttr();
}
double Student::getavg()
{
double student_avg =avg;
return student_avg;
}
string Student::get_name()
{
string student_name=name;
return student_name;
}
void s_sort(Student students[], int size) //sorts ranks from greatest to least
{
int m; // keep the index of current largest value
Student hold;
for (int k=0; k<=size-2; k++)
{
m = k;
for (int j=k+1; j <= size; j++)
{
if (students[j].getavg() > students[m].getavg())
{
m = j;
}
}
hold = students[m];
students[m] = students[k];
students[k] = hold;
}
}
void abc_sort(Student x[], int n) //sorts names alphabetically
{
int m; // keep the index of current smallest value
Student hold;
for (int k = 0; k <= n - 2; k++)
{
m = k;
for (int j = k + 1; j <= n - 1; j++) {
if (x[j].get_name() < x[m].get_name()) //if
m = j;
if (x[j].get_name() == x[m].get_name()) //if same name
{
if(x[j].getid() < x[m].getid())
m = j;
}
}
swap(x[m], x[k]);
}
return;
}
int Student::getid()
{
return id;
}
void search_name(Student students[],int size,string name)
{
int index=0 ; //index array in case of duplicates
//while loop that searches through names
int name_count=0;
for (index;index<size;index++)
{ //if names are found
if (students[index].get_name() == name)
{ cout << "Name: " << students[index].get_name() << endl;
cout << "ID: " << students[index].getid() << endl;
cout << "Average: " << students[index].getavg() << " (" << students[index].getgrade_lttr() << ")" << endl;
name_count++;
}
}
//if not found
if(name_count<1)
{
cout<< "Fail. " << name << " is not enrolled in this class.\n" ;
}
} | true |
ead4ca160bdcc51429863226ea4669ff0cbfe4ac | C++ | realn/CodeBox | /src/CBCore/StringConvert.cpp | UTF-8 | 1,972 | 2.953125 | 3 | [
"BSL-1.0"
] | permissive | #include "stdafx.h"
#include "utf8.h"
#include <sstream>
#include <CBCore/StringConvert.h>
#include <CBCore/StringFunctions.h>
namespace cb {
using namespace std::string_literals;
auto const STR_BOOL_TRUE = L"true"s;
auto const STR_BOOL_FALSE = L"false"s;
auto const STR_BOOL_TRUE_CAP = L"True"s;
auto const STR_BOOL_FALSE_CAP = L"False"s;
auto const STR_BOOL_TRUE_HIGH = L"TRUE";
auto const STR_BOOL_FALSE_HIGH = L"FALSE";
auto const STR_FORMAT_BRACE_LEFT = L"{"s;
auto const STR_FORMAT_BRACE_RIGHT = L"}"s;
string toStr(string const& val) {
return val;
}
string toStr(bool const& val) {
return val ? STR_BOOL_TRUE : STR_BOOL_FALSE;
}
bool fromStr(string const& text, string& outVal) {
outVal = text;
return true;
}
bool fromStr(string const& text, bool& outVal) {
if (text == STR_BOOL_TRUE || text == STR_BOOL_TRUE_CAP || text == STR_BOOL_TRUE_HIGH) {
outVal = true;
return true;
}
if (text == STR_BOOL_FALSE || text == STR_BOOL_FALSE_CAP || text == STR_BOOL_FALSE_HIGH) {
outVal = false;
return true;
}
return false;
}
utf8string toUtf8(string const& text) {
auto result = utf8string();
utf8::utf16to8(text.begin(), text.end(), std::back_inserter(result));
return result;
}
string fromUtf8(utf8string const& text) {
auto result = string();
utf8::utf8to16(text.begin(), text.end(), std::back_inserter(result));
return result;
}
size_t utf8len(utf8string const& text) {
return utf8::distance(text.begin(), text.end());
}
string varReplace(string const& format, strvector const& list) {
if (format.empty()) {
return string();
}
if (list.empty()) {
return format;
}
auto result = format;
for (auto i = 0u; i < list.size(); i++) {
auto var = STR_FORMAT_BRACE_LEFT + toStr(i) + STR_FORMAT_BRACE_RIGHT;
result = replace(result, var, list[i]);
}
return result;
}
}
| true |
5f21ed9d61323baf24419b2e94649f9297455599 | C++ | bbetsey/cppPiscine | /cpp03/ex01/ScavTrap.cpp | UTF-8 | 1,188 | 3.296875 | 3 | [] | no_license | #include "ScavTrap.hpp"
//MARK: - Class Constructor
ScavTrap::ScavTrap( std::string name ) : ClapTrap( name, 100, 50, 20) {
std::cout << "ScavTrap Default Constructor called" << std::endl;
}
//MARK: - Class Distructor
ScavTrap::~ScavTrap( void ) {
std::cout << "ScavTrap Class Distructor called" << std::endl;
}
//MARK: - Class Copy Constructor
ScavTrap::ScavTrap( const ScavTrap &src ) : ClapTrap( src.getName(), 100, 50, 20 ) {
std::cout << "ScavTrap Copy Constructor called" << std::endl;
}
//MARK: - Class Assignation Overload
ScavTrap &ScavTrap::operator = ( const ScavTrap &src ) {
if (this != &src) {
this->name = src.name;
this->hitpoints = src.hitpoints;
this->energyPoints = src.energyPoints;
this->attackDamage = src.attackDamage;
}
std::cout << "ScavTrap Assignation Overload called" << std::endl;
return *this;
}
//MARK: - Class Methods
void ScavTrap::guardGate( void ) {
std::cout << "ScavTrap " << name << " have enterred in Gate keeper mode" << std::endl;
}
void ScavTrap::attack( std::string const &target ) {
std::cout << "ScavTrap " << name << " attack " << target << " causing " << attackDamage << " points of damage!" << std::endl;
}
| true |
77e523d18ad390ba36e171c005fefa1f5763b0fc | C++ | scofieldfirst/meteor | /utilities/collections/Queue.h | UTF-8 | 2,777 | 3.578125 | 4 | [
"LicenseRef-scancode-public-domain"
] | permissive | #ifndef QUEUE_H
#define QUEUE_H
#include <new>
#include <stddef.h>
template<typename T>
class Queue
{
private:
T* buffer;
size_t capacity;
size_t front, rear;
public:
explicit Queue(size_t capacity):
capacity(capacity),
front(0),
rear(0)
{
buffer = (T*) ::operator new[](sizeof(T) * capacity);
}
~Queue()
{
::operator delete[](buffer);
}
void Enqueue(const T& element)
{
size_t next = (rear + 1) % capacity;
if(next == front) return;
rear = next;
new(&buffer[next]) T(element);
}
bool Dequeue(T* element)
{
if(front == rear) return false;
front = (front + 1) % capacity;
*element = buffer[front];
buffer[front].~T();
return true;
}
inline T& Front()
{
return buffer[front];
}
inline const T& Front() const
{
return buffer[front];
}
inline bool Is_Empty() const
{
return front == rear;
}
void Clear()
{
for(auto it = First(), end = Last(); it != end; ++it)
it->~T();
front = rear = 0;
::operator delete[](buffer);
buffer = ::operator new[](sizeof(T) * capacity);
}
Iterator First()
{
return Iterator(*this, buffer + front);
}
ConstIterator First() const
{
return ConstIterator(*this, buffer + front);
}
Iterator Last()
{
return Iterator(*this, buffer + rear);
}
ConstIterator Last() const
{
return ConstIterator(*this, buffer + rear);
}
friend class Iterator;
class Iterator
{
private:
Queue& container;
T* current;
public:
Iterator(Queue& queue, T* pointer):
container(queue),
current(pointer)
{}
Iterator(const Iterator& other):
container(other.container),
current(other.current)
{}
T& operator * () { return *current; }
T* operator -> () { return current; }
bool operator != (const Iterator& other) const { return current != other.current; }
bool operator == (const Iterator& other) const { return current == other.current; }
Iterator& operator++()
{
T* base = container.buffer;
current = base + ((current - base + 1) % container.capacity);
return *this;
}
};
friend class ConstIterator;
class ConstIterator
{
private:
Queue& container;
T* current;
public:
ConstIterator(Queue& queue, T* pointer):
container(queue),
current(pointer)
{}
ConstIterator(const ConstIterator& other):
container(other.container),
current(other.current)
{}
const T& operator * () const { return *current; }
const T* operator -> () const { return current; }
bool operator != (const Iterator& other) const { return current != other.current; }
bool operator == (const Iterator& other) const { return current == other.current; }
ConstIterator& operator++()
{
T* base = container.buffer;
current = base + ((current - base + 1) % container.capacity);
return *this;
}
};
};
#endif
| true |
6d9611d15d4e4786fa8abd0d20dcd44546d7affe | C++ | CraigBarryDev/PBRShading | /backdrop.cpp | UTF-8 | 1,494 | 2.609375 | 3 | [] | no_license | #include "backdrop.h"
Backdrop::Backdrop() {}
Backdrop::Backdrop(Loader* loader, ModelTexture* tex, BackdropShader* bShader) {
vector<GLfloat> vPositions(std::begin(vertices), std::end(vertices));
vector<GLfloat> vNormals(std::begin(normals), std::end(normals));
vector<GLfloat> vTexCoords(std::begin(texCoords), std::end(texCoords));
vector<GLuint> vIndices(std::begin(indices), std::end(indices));
model = loader->loadToVAO(vPositions, vNormals, vTexCoords, vIndices);
this->tex = tex;
shader = bShader;
}
Backdrop::~Backdrop() {}
void Backdrop::cleanUp() {
delete model;
}
void Backdrop::render() {
//Bind the shader program
shader->start();
//Disable depth testing when drawing backdrop
glDisable(GL_DEPTH_TEST);
//Bind the VAO to the context
glBindVertexArray(model->getVAOID());
//Enable the attribute list index 0 on the VAO (our positional data)
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
//Bind the texture to the texture unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex->getTextureID());
//Draw the model
glDrawElements(GL_TRIANGLES, model->getVertexCount(), GL_UNSIGNED_INT, 0);
//Disable the attribute lists from the VAO
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
//Unbind the VAO from the context
glBindVertexArray(0);
//Re-enable depth testing
glEnable(GL_DEPTH_TEST);
//Unbind the shader program
shader->stop();
} | true |
3d060caf7a1eb69e4f3e4c9bbcf3606ef7bfc1d2 | C++ | baterobeto/TP1-Ciclista | /SegundaParte/GregoEjercicioProductoria.cpp | UTF-8 | 725 | 3.984375 | 4 | [] | no_license | #include <iostream>
using namespace std;
void leer(string mensaje, int &valor)
{
cout << mensaje << endl;
cin >> valor;
}
void calculo(int numero, int &producto, int resultado)
{
while (numero != 0)
{
producto = numero * producto;
resultado = producto;
leer("Ingrese un numero: (Presione 0 para finalizar)", numero);
}
}
void imprimeResultado(string mensaje, int valor)
{
cout << mensaje << valor << endl;
}
int main()
{
int numero = 1;
int producto = 1;
int resultado;
leer("Ingrese un numero: (Presione 0 para finalizar)", numero);
calculo(numero, producto, resultado);
imprimeResultado("El producto total es: ", producto);
return 0;
} | true |
57e88b42a7f2cc9a2fa1778999b15e78fbbd0f81 | C++ | XEnDash/ProjectTemplate | /src/str.cpp | UTF-8 | 6,893 | 3.203125 | 3 | [] | no_license | #include "defines.h"
#include "import_std.h"
String::String()
{
num_of_string_objects++;
this->length = 0;
this->c_str = 0;
this->allocated = false;
}
String::~String()
{
num_of_string_objects++;
if(this->allocated)
{
this->Deallocate();
}
this->length = 0;
this->c_str = 0;
this->allocated = false;
}
String::String(const String &s)
{
num_of_string_objects++;
this->length = 0;
this->c_str = 0;
this->allocated = false;
if(!this->Assign(s.c_str))
{
LogError("String::Assign failed");
}
}
String::String(char *str)
{
num_of_string_objects++;
this->length = 0;
this->c_str = 0;
this->allocated = false;
if(!this->Assign(str))
{
LogError("String::Assign failed");
}
}
String::String(int64 i)
{
num_of_string_objects++;
this->length = 0;
this->c_str = 0;
this->allocated = false;
uint32 size = GetNumberOfCharactersInNumber(i);
if(!this->Allocate(size))
{
LogError("String::Allocate failed");
}
ParseIntIntoCStr(this->c_str, i);
this->length = CalcLength(this->c_str);
}
bool32 String::Allocate(uint32 size)
{
DAssert(size);
num_of_string_allocations++;
size_of_string_bytes_allocated += size;
if(this->allocated)
{
ldelete(this->c_str);
this->length = 0;
this->allocated = false;
}
this->c_str = (char *)lnew((sizeof(char) * size) + 1);
if(!this->c_str)
{
this->allocated = false;
return false;
}
this->allocated = true;
return true;
}
bool32 String::Reallocate(uint32 size)
{
DAssert(size);
num_of_string_reallocations++;
size_of_string_bytes_reallocated += size;
if(!this->allocated)
{
this->Allocate(size);
return true;
}
this->c_str = (char *)lrealloc(this->c_str, (sizeof(char) * size + 1));
if(!this->c_str)
{
this->allocated = false;
return false;
}
this->allocated = true;
return true;
}
bool32 String::Deallocate()
{
DAssert(this->allocated);
DAssert(this->c_str);
num_of_string_deallocations++;
size_of_string_bytes_deallocated += this->length;
ldelete(this->c_str);
this->c_str = 0;
this->length = 0;
this->allocated = false;
return true;
}
void String::operator =(char *str)
{
this->length = 0;
this->c_str = 0;
this->allocated = false;
if(!this->Assign(str))
{
LogError("String::Assign failed");
}
}
void String::operator =(int64 i)
{
this->length = 0;
this->c_str = 0;
this->allocated = false;
uint32 size = GetNumberOfCharactersInNumber(i);
if(!this->Allocate(size))
{
LogError("String::Allocate failed");
}
ParseIntIntoCStr(this->c_str, i);
this->length = CalcLength(this->c_str);
}
void String::operator +=(char *str)
{
if(!this->Append(str))
{
LogError("String::Append failed");
}
}
void String::operator +=(int64 i)
{
uint32 prev_len = this->length;
uint32 size = GetNumberOfCharactersInNumber(i);
if(!this->Reallocate(prev_len + size))
{
LogError("String::Reallocate failed");
}
ParseIntIntoCStr(&this->c_str[prev_len], i);
this->length = CalcLength(this->c_str);
}
String String::operator +(char *str)
{
if(!this->Append(str))
{
LogError("String::Append failed");
}
return *this;
}
String String::operator +(int64 i)
{
uint32 prev_len = this->length;
uint32 size = GetNumberOfCharactersInNumber(i);
if(!this->Reallocate(prev_len + size))
{
LogError("String::Reallocate failed");
}
ParseIntIntoCStr(&this->c_str[prev_len], i);
this->length = CalcLength(this->c_str);
return *this;
}
bool32 String::Assign(char *str)
{
DAssert(str);
uint32 new_len = CalcLength(str);
if(!this->Allocate(CalcLength(str)))
{
LogError("String::Allocate failed");
return false;
}
if(!CopyLim(this->c_str, str, new_len))
{
LogError("String::CopyLim failed");
return false;
}
this->length = CalcLength(this->c_str);
return true;
}
bool32 String::Append(char *str)
{
DAssert(str);
if(!this->allocated)
{
LogError("Appending non allocated string");
return false;
}
uint32 prev_len = this->Length();
uint32 append_len = CalcLength(str);
uint32 new_len = prev_len + append_len + 1;
this->c_str = (char *)lrealloc(this->c_str, new_len);
if(!this->c_str)
{
LogError("Unable to reallocate string");
return false;
}
if(!CopyLim(&this->c_str[prev_len], str, append_len))
{
LogError("String::CopyLim failed");
return false;
}
this->length = CalcLength(this->c_str);
return true;
}
uint32 String::Length()
{
return this->length;
}
uint32 String::CalcLength(char *str)
{
DAssert(str);
uint32 count = 0;
char *p = str;
while(*p != 0)
{
p++;
count++;
if(count >= STRING_COUNTING_LIMIT)
{
count = 0;
break;
}
}
return count;
}
bool String::Copy(char *dest, char *src)
{
DAssert(dest);
DAssert(src);
int count = 0;
while(*src != 0)
{
*dest = *src;
dest++;
src++;
count++;
if(count >= STRING_COUNTING_LIMIT)
break;
}
// NOTE(daniel): make sure it is zero terminated
*dest = 0;
return true;
}
bool String::CopyLim(char *dest, char *src, uint32 size)
{
DAssert(dest);
DAssert(src);
int count = 0;
for(uint32 i = 0; i < size; i++)
{
*dest = *src;
dest++;
src++;
count++;
if(count >= STRING_COUNTING_LIMIT)
break;
}
// NOTE(daniel): make sure it is zero terminated
*dest = 0;
return true;
}
String String::ParseInt(int64 i)
{
bool negative = (i < 0);
uint32 size = GetNumberOfCharactersInNumber(i);
String output;
output.Allocate(size + 1);
if(!output.allocated)
{
LogError("String::Allocate failed");
}
char *ptr = output.c_str;
if(negative)
{
ptr[0] = '-';
size -= 1;
ptr += 1;
i = -i;
}
for(uint32 j = size; j > 0; j--)
{
int power = pow((float)(10), (float)(j - 1));
uint32 n = i / power;
ptr[size - j] = n + 0x30;
i -= n * power;
}
if(negative)
size += 1;
output.length = size;
output.c_str[output.length] = 0;
return output;
}
void String::ParseIntIntoCStr(char *c_str, int64 i)
{
DAssert(c_str);
bool negative = (i < 0);
uint32 size = GetNumberOfCharactersInNumber(i);
char *output = c_str;
char *ptr = c_str;
if(negative)
{
ptr[0] = '-';
size -= 1;
ptr += 1;
i = -i;
}
for(uint32 j = size; j > 0; j--)
{
int power = pow((float)(10), (float)(j - 1));
uint32 n = i / power;
ptr[size - j] = n + 0x30;
i -= n * power;
}
if(negative)
size += 1;
output[size] = 0;
}
| true |
b2e831302e6961991573eca8798353ee296cb80c | C++ | soulsystem00/bj_2798 | /bj_2798/bj_1934.cpp | UTF-8 | 364 | 2.765625 | 3 | [] | no_license | //#include <iostream>
//
//using namespace std;
//
//int main(void)
//{
// int loop;
// cin >> loop;
// for (int i = 0; i < loop; i++)
// {
// int N, M;
// cin >> N >> M;
// if (N > M)
// {
// swap(N, M);
// }
// int j = N;
// for (;; j--)
// {
// if (N % j == 0 && M % j == 0)
// {
// break;
// }
// }
// cout << (N / j) * M << endl;
// }
//} | true |
b6d6ce786f0ed804b6c5588cd7b7988db3d0096c | C++ | 18600130137/leetcode | /LeetCodeCPP/207. Course Schedule/main.cpp | UTF-8 | 1,415 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | //
// main.cpp
// 207. Course Schedule
//
// Created by admin on 2019/6/12.
// Copyright © 2019年 liu. All rights reserved.
//
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
bool canFinish(int n, vector<pair<int, int>>& p) {
//1、直接满足条件
int m=p.size();
if(n==0 || m==0){
return true;
}
//2、构建邻接表 入度表
vector<vector<int>> graph(n);
vector<int> indegree(n,0);
for(auto item:p){
graph[item.second].push_back(item.first);
indegree[item.first]++;
}
//3、构建起点队列
queue<int> helper;
for(int i=0;i<n;i++){
if(!indegree[i]){
helper.push(i);
}
}
//4、走起
int count=0;
while(!helper.empty()){
int front=helper.front();
helper.pop();
count++;
for(auto i:graph[front]){
if(--indegree[i]==0){
helper.push(i);
}
}
}
return count==n;
}
};
int main(int argc, const char * argv[]) {
vector<pair<int,int>> input={{1,0}};
Solution so=Solution();
bool ret=so.canFinish(2, input);
cout<<"The ret is:"<<ret<<endl;
return 0;
}
| true |
1480d451e740b5688344b1a93a0186d62d3e11fa | C++ | arcbot-id/arduino | /Servo_Distance_Indicator/servo_distance_indicator.ino | UTF-8 | 845 | 3.15625 | 3 | [] | no_license | //import library Servo
#include <Servo.h>
//import library NewPing
#include <NewPing.h>
//declare constants
const int ServoPin = 10;
const int TriggerPin = 6;
const int EchoPin = 7;
//declare a NewPing object called sonar with TriggerPin as trigger, EchoPin as echo, and 100 cm as max distance
NewPing sonar (TriggerPin, EchoPin, 100);
//declare a Servo object called servo
Servo servo;
////setup procedure; only run once in the beginning
void setup()
{
Serial.begin(9600);
//attach servo pin to ServoPin
servo.attach(ServoPin);
}
void loop()
{
//measure distance and output them to serial monitor
int cm = sonar.ping_cm();
Serial.println(cm);
//map the distance to scale of 15-100
int angle = map(cm, 2, 15, 15, 100);
//move servo to certain degree of angle
servo.write(angle);
//delay between loops
delay(50);
}
| true |
82bcb9deb437a7a5482fe2eb2fd80ebe8e3f2f73 | C++ | 15831944/BeijingEVProjects | /小浪底泥沙三维/EV_Xld/jni/src/EV_XldManager/RenderLibDataType.h | GB18030 | 1,049 | 2.609375 | 3 | [] | no_license | #ifndef RENDERLIBDATATYPE_H_
#define RENDERLIBDATATYPE_H_
namespace EarthView
{
namespace Xld
{
namespace RenderLib
{
/// <summary>
/// öָʾɵ״̬
/// </summary>
enum CMousePickState
{
/// <summary>
/// ɵһ
/// </summary>
ToFirst = 1,
/// <summary>
/// ɵڶ
/// </summary>
ToSecond = 2,
/// <summary>
/// ɵ
/// </summary>
ToThird = 3,
/// <summary>
/// ɵ
/// </summary>
Picking = 4,
/// <summary>
/// ɵ
/// </summary>
Over = 5,
};
enum CMoveLineType
{
/// <summary>
/// ֱ
/// </summary>
Line,
/// <summary>
/// Բ
/// </summary>
Circle,
/// <summary>
/// ģ㣬ֱ
/// </summary>
StraightLine,
/// <summary>
///
/// </summary>
Rectangle,
/// <summary>
///
/// </summary>
Polygon
};
}
}
}
#endif
| true |
65e2a82c92ad54aba41c8708c34081717e1e46be | C++ | edisonhello/waynedisonitau123 | /Codebook/string/KMP.cpp | UTF-8 | 800 | 3.203125 | 3 | [] | no_license | vector<int> Failure(const string &s) {
vector<int> f(s.size(), 0);
// f[i] = length of the longest prefix (excluding s[0:i]) such that it coincides with the suffix of s[0:i] of the same length
// i + 1 - f[i] is the length of the smallest recurring period of s[0:i]
int k = 0;
for (int i = 1; i < (int)s.size(); ++i) {
while (k > 0 && s[i] != s[k]) k = f[k - 1];
if (s[i] == s[k]) ++k;
f[i] = k;
}
return f;
}
vector<int> Search(const string &s, const string &t) {
// return 0-indexed occurrence of t in s
vector<int> f = Failure(t), res;
for (int i = 0, k = 0; i < (int)s.size(); ++i) {
while (k > 0 && (k == (int)t.size() || s[i] != t[k])) k = f[k - 1];
if (s[i] == t[k]) ++k;
if (k == (int)t.size()) res.push_back(i - t.size() + 1);
}
return res;
}
| true |