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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c54f4f0643b770d854cbf297ac8b6fb05a87434e | C++ | hgaiser/roman-technologies | /mobile_base/include/mobile_base/PathFollower.h | UTF-8 | 3,672 | 2.625 | 3 | [] | no_license | /*
* PathFollower.h
*
* Created on: Jan 20, 2012
* Author: hans
*/
#ifndef PATHFOLLOWER_H_
#define PATHFOLLOWER_H_
#include "ros/ros.h"
#include "nav_msgs/Path.h"
#include "tf/transform_listener.h"
#include "std_msgs/Float32.h"
#include "std_msgs/UInt8.h"
#include "mobile_base/LocalPlanner.h"
enum FollowState
{
FOLLOW_STATE_IDLE,
FOLLOW_STATE_TURNING,
FOLLOW_STATE_FORWARD,
FOLLOW_STATE_FINISHED,
FOLLOW_STATE_MAX,
};
class PathFollower
{
private:
LocalPlanner mLocalPlanner;
ros::Subscriber mPathSub; /// Subscriber that listens to paths from PathPlanner
ros::Publisher mCommandPub; /// Publishes velocity commands
ros::Publisher mGoalPub; /// Re-publishes goals when a new path needs to be calculated
ros::Publisher mPathLengthPub; /// Publishes path length when path is refreshed
ros::Publisher mFollowStatePub; /// Publishes the current state of the follower
std::list<geometry_msgs::Pose> mPath; /// Current path to follow
geometry_msgs::Point mOrigin; /// Point the robot originated from when moving to a next waypoint
tf::StampedTransform mRobotPosition; /// Current position of the robot on the map
tf::TransformListener mTransformListener; /// Listens to transforms of the robot
double mMinAngularSpeed, mMaxAngularSpeed; /// min-max speed at which to turn, robot will scale depending on the amount of yaw to turn
double mAngularAdjustmentSpeed; /// Angular speed while driving to adjust for offsets
double mMinLinearSpeed, mMaxLinearSpeed; /// min-max linear speed when turning, robot will scale depending on the distance to drive
FollowState mFollowState; /// Current state of the follower
double mYawTolerance; /// Tolerance before turning correctly while driving forward
double mFinalYawTolerance; /// Tolerance while turning before the orientation is accepted
double mDistanceTolerance; /// Tolerance in distance for considering a waypoint as reached
double mResetDistanceTolerance; /// Distance from robot to path before it will reset its path
inline geometry_msgs::Pose getGoal() { return mPath.back(); }; /// Returns goal position
inline geometry_msgs::Point getOrigin() { return mOrigin; };
inline geometry_msgs::Point getNextPoint() { return mPath.front().position; }; /// Returns current waypoint the robot is getting to
inline uint32_t getPathSize() { return mPath.size(); }; /// Returns the size of the remaining path
inline bool reachedNextPoint() /// Checks if we are close enough to the next point
{
btVector3 np(getNextPoint().x, getNextPoint().y, getNextPoint().z);
return np.distance(mRobotPosition.getOrigin()) < mDistanceTolerance;
};
inline double getScaledLinearSpeed() /// Scales linear speed based on distance to drive
{
btVector3 np(getNextPoint().x, getNextPoint().y, getNextPoint().z);
double scale = (std::max(std::min(np.distance(mRobotPosition.getOrigin()), 3.0), 1.0) - 1.0) / 2.0;
return scale * (mMaxLinearSpeed - mMinLinearSpeed) + mMinLinearSpeed;
};
inline double getScaledAngularSpeed(double rotationAngle) /// Scales the angular speed based on the turn to be made
{
double scale = fabs(rotationAngle) / M_PI;
return scale * (mMaxAngularSpeed - mMinAngularSpeed) + mMinAngularSpeed;
};
double calculateDiffYaw();
/// Listen to Twist messages and stream them
void pathCb(const nav_msgs::Path &path);
void continuePath();
void clearPath();
bool updateCurrentPosition();
void publishPathLength();
void publishState();
public:
void updatePath();
PathFollower(ros::NodeHandle *nodeHandle);
~PathFollower() {};
};
#endif /* PATHFOLLOWER_H_ */
| true |
8e99f2965c506e200eb5d7c43b27523b75561109 | C++ | whlprogram/LeetCode | /108ConvertSortedArrayToBinarySearchTree/main.cpp | GB18030 | 2,445 | 3.625 | 4 | [] | no_license | //ԭ https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/#/description
//˲ http://blog.csdn.net/whl_program/article/details/72803058
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int>& nums) {//16ms
return BuildTree(nums, 0, nums.size()-1);
}
TreeNode *BuildTree(vector<int> &nums, int Start, int End){
if(Start > End) return nullptr;
if(Start == End) return new TreeNode(nums[Start]);
int Min = (Start+End)/2;
TreeNode *node = new TreeNode(nums[Min]);// ڵ
node->left = BuildTree(nums, Start, Min-1);//
node->right = BuildTree(nums, Min+1, End);//
return node;
}
// α
vector<vector<int> > LevelOrder(TreeNode *root) {
vector<int> level;
vector<vector<int> > levels;
if(root == NULL){
return levels;
}
queue<TreeNode*> cur,next;
//
cur.push(root);// rootԪؽӵеĩˣ
// α
while(!cur.empty()){
//ǰ
while(!cur.empty()){
TreeNode *p = cur.front();//cur.front() ʶԪ
cur.pop();// еĵһԪأ᷵Ԫصֵ
level.push_back(p->val);
// nextһڵ
//
if(p->left){
next.push(p->left);
}
//
if(p->right){
next.push(p->right);
}
}//end while
levels.push_back(level);
level.clear();
swap(next,cur);
}//end while
return levels;
}
};
int main()
{
Solution S;
vector<int> num = {0,1,2,3,4,5,6,7,8,9};
TreeNode* root = S.sortedArrayToBST(num);
vector<vector<int> > levels = S.LevelOrder(root);
for(int i = 0;i < levels.size();i++){
for(int j = 0;j < levels[i].size();j++){
cout<<levels[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
| true |
9644cd1658856acf9015c39e5193b8d69b1e3a42 | C++ | JackBro/PEGGY | /Projects/UDWT/Main.cpp | UTF-8 | 6,008 | 2.546875 | 3 | [] | no_license | // Copyright (c) Microsoft Corporation. All rights reserved.
#include "Source/Filter.h"
#include <RunTest.h>
//#include <Timings.h>
// Reuse the filter from the normal convolution (may as well).
Filter *
g_filter = 0;
//extern Timings
// gTimings;
//Data1DFloat *
//Loop1D *
Data1DFloat *
g_data = 0;
size_t
g_level = 3;
bool
Compare(ParallelCode & a, ParallelCode & b)
{
// Checks that two convolvers are close enough.
Data1DFloat
& d0 = dynamic_cast<Data1DFloat &>(a.GetResult()),
& d1 = dynamic_cast<Data1DFloat &>(b.GetResult());
size_t
jt = d0.GetWidth();
//if (it != d1.GetHeight() || jt != d1.GetWidth())
//{
// return false;
//}
if (jt != d1.GetWidth())
{
return false;
}
//for (size_t i = 0; i != it; ++i)
//{
for (size_t j = 0; j != jt; ++j)
{
//if (!Compare(d0(i, j), d1(i, j)))
// For some reason, every implementation comes out with slightly
// different values every multiple of 256 - this is an interestng point
// at which to have a bug, but I can't solve it right now...
if (!Compare(d0(j), d1(j)) && (j & 0xFF))
{
std::cout.precision(10);
// No point finishing the loop.
std::cout << j << " : " << d0(j) << " <> " << d1(j) << std::endl;
//std::cout << j << " : " << d0(j) << " <> " << d1(j) << std::endl;
//return false;
}
}
//}
return true;
}
bool
Print(ParallelCode & a)
{
// Checks that two convolvers are close enough.
Data1DFloat
& d0 = dynamic_cast<Data1DFloat &>(a.GetResult());
size_t
jt = d0.GetWidth();
for (size_t j = 0; j != jt; ++j)
{
std::cout << j << " : " << d0(j) << std::endl;
}
std::cout << "Data size: " << jt << std::endl;
return true;
}
void
Setup(UDWT & c)
{
try {c.SetFilter(*g_filter);}
catch (...) {}
try {c.SetLevel(g_level);}
catch (...) {}
try {c.SetData(*g_data);}
catch (...) {}
}
extern char
g_fname[32];
#define SIZES (sizeof (sizes) / sizeof (int))
int
main(int argc, char ** argv)
{
const int
sizes[] =
{
//1, 2, 4, 8, 16, 23, 32, 39, 42, 64, 71, 128, 135, 256, 263, 512, 519, 555, 700, 1000, 1024, 1500, 2000, 2007, 2048, 4000, 4007, 4096, 4500, 4501, 5000, 10000, 20000
//32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, , , , , , , , , , , ,
//32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, 1056, 1088, 1120, 1152, 1184, 1216, 1248, 1280, 1312, 1344, 1376, 1408, 1440, 1472, 1504, 1536, 1568, 1600, 1632, 1664, 1696, 1728, 1760, 1792, 1824, 1856, 1888, 1920, 1952, 1984, 2016, 2048
128, 256, 384, 512, 640, 768, 896, 1024,
1152, 1280, 1408, 1536, 1664, 1792, 1920, 2048,
2176, 2304, 2432, 2560, 2688, 2816, 2944, 3072,
3200, 3328, 3456, 3584, 3712, 3840, 3968, 4096,
4224, 4352, 4480, 4608, 4736, 4864, 4992, 5120,
5248, 5376, 5504, 5632, 5760, 5888, 6016, 6144,
6272, 6400, 6528, 6656, 6784, 6912, 7040, 7168,
7296, 7424, 7552, 7680, 7808, 7936, 8064, 8192,
//1, 32, 256, 1000//, 1024, 1500, 2000, 2007, 2048, 4000, 4007, 4096, 4500, 4501, 5000
//1000, 2000, 4000, 4007, 4096, 4500, 4501, 5000
};
if (argc < 5) // 5 with filter size
{
std::cout << "Usage:" << std::endl;
std::cout << "[x size index] [level] <o|c|a|x|r|f|e|d|b|y|m|n|h> <s|c|v|p>" << std::endl;
std::cout << "Any number of items in the angle brackets may be included in a single string to run multiple tests." << std::endl;
std::cout << "Note however that not all listed targets are currently supported." << std::endl;
return 0;
}
int
i,
j = 0;
char
c;
int
rm = (int)E_RUN_NONE,
cm = (int)E_COMP_NONE,
radius = 3;
i = atoi(argv[1]);
//j = atoi(argv[2]);
g_level = atoi(argv[2]);
//radius = atoi(argv[4]);
if (i < 0 || i >= SIZES)//8193)//
{
std::cout << "i out of range (0 - " << (SIZES - 1) << ").";
return 0;
}
/*else if (j < 0 || j >= SIZES)//8193)//
{
std::cout << "j out of range (0 - " << (SIZES - 1) << ").";
return 0;
}*/
else if (g_level < 0)
{
std::cout << "Please enter a valid level.";
return 0;
}
else if (g_level > 6)
{
std::cout << "The level must be <= 6.";
return 0;
}
/*else if (radius < 1)
{
std::cout << "Please enter a valid radius.";
return 0;
}
else if (radius > 23)
{
std::cout << "Warning: CUDA currently only supports filter sizes <= 23." << std::endl;
}*/
// Create the filter.
g_filter = new Filter(); //3, FILTER_SIGMA);
// Create the data. NOTE THAT THIS IS 1D DATA IN A 2D ARRAY TO GET MORE.
// NO IT ISN'T!
//g_data = new Data1DFloat(sizes[i] * sizes[j], GT_Seed, 2012 * 42);
g_data = new Data1DFloat(sizes[i] * 2048, GT_Test);
for (size_t k = 0; (c = argv[3][k]); ++k)
{
switch (c)
{
#if !defined NO_OPEN_CL
TARGET('O', E_COMP_OPEN_CL);
#endif
#if !defined NO_ACCELERATOR
TARGET('A', E_COMP_ACC);
TARGET('X', E_COMP_X64);
TARGET('M', E_COMP_AC_C);
#endif
#if !defined NO_ACCELERATOR_OPT
TARGET('B', E_COMP_ACC2);
TARGET('Y', E_COMP_X642);
TARGET('N', E_COMP_AC_C2);
#endif
#if !defined NO_CUDA
TARGET('C', E_COMP_CUDA);
#if !defined NO_HASKELL
TARGET('K', E_COMP_HASKELL);
#endif
#endif
#if !defined NO_OBS
TARGET('H', E_COMP_OBS);
#endif
#if !defined NO_CUDA_OPT
TARGET('D', E_COMP_CUDA2);
#endif
#if !defined NO_REFERENCE
TARGET('R', E_COMP_REF);
#endif
#if !defined NO_REFERENCE_OPT
TARGET('E', E_COMP_CACHE);
TARGET('F', E_COMP_FAST);
#endif
default:
std::cout << "Unknown/unsupported target.";
return 0;
}
}
for (size_t k = 0; (c = argv[4][k]); ++k)
{
switch (c)
{
MODE('C', E_RUN_C);
MODE('S', E_RUN_S);
MODE('V', E_RUN_V);
MODE('P', E_RUN_P);
default:
std::cout << "Unknown run mode.";
return 0;
}
}
sprintf(g_fname, OUTPUT_DIR "Report2 %d %d %d %d.txt", i, j, g_level, radius);
//Test((E_RUN)rm, i, j, (E_COMP)cm);
Test((E_RUN)rm, sizes[i] * 2048, 0, (E_COMP)cm);
return 0;
}
| true |
28889aced81b41cfb5af71fdff8d8003ec765d5c | C++ | droidream/dukv8 | /src/Context.cpp | UTF-8 | 3,575 | 2.84375 | 3 | [
"MIT"
] | permissive | //
// Created by Jiang Lu on 6/2/15.
//
#include <cassert>
#include <dukv8/Context.h>
#include <dukv8/Persistent.h>
#include <dukv8/Isolate.h>
#include <dukv8/Local.h>
#include <dukv8/Object.h>
namespace v8 {
Context *Context::s_current_context_ = NULL;
Context::Context() :
previous_context_(NULL) {
// printf("%s\n", __PRETTY_FUNCTION__);
}
Context::~Context() {
// printf("%s\n", __PRETTY_FUNCTION__);
}
/**
* Returns the global proxy object or global object itself for
* detached contexts.
*
* Global proxy object is a thin wrapper whose prototype points to
* actual context's global object with the properties like Object, etc.
* This is done that way for security reasons (for more details see
* https://wiki.mozilla.org/Gecko:SplitWindow).
*
* Please note that changes to global proxy object prototype most probably
* would break VM---v8 expects only global object as a prototype of
* global proxy object.
*
* If DetachGlobal() has been invoked, Global() would return actual global
* object until global is reattached with ReattachGlobal().
*/
Local<Object> Context::Global() {
Isolate *isolate = Isolate::GetCurrent();
duk_context *ctx = isolate->GetDukContext();
duk_push_global_object(ctx);
void *obj_heap_ptr = duk_get_heapptr(ctx, -1);
duk_pop(ctx);
return Local<Object>::New(Handle<Object>(new Object(ctx, obj_heap_ptr)));
}
/** Creates a new context.
*
* Returns a persistent handle to the newly allocated context. This
* persistent handle has to be disposed when the context is no
* longer used so the context can be garbage collected.
*
* \param extensions An optional extension configuration containing
* the extensions to be installed in the newly created context.
*
* \param global_template An optional object template from which the
* global object for the newly created context will be created.
*
* \param global_object An optional global object to be reused for
* the newly created context. This global object must have been
* created by a previous call to Context::New with the same global
* template. The state of the global object will be completely reset
* and only object identify will remain.
*/
Persistent<Context> Context::New(
ExtensionConfiguration *extensions,
Handle<ObjectTemplate> global_template,
Handle<Value> global_object) {
Handle<Context> context(new Context());
// Handle<Object> global;
//
// if (!global_object.IsEmpty() && global_object->IsObject()) {
// global = context->external_global_object_ = global_object->ToObject();
// } else {
// global = context->global_object_;
// }
// apply global object template to global object
if (!global_template.IsEmpty() && !global_object.IsEmpty()) {
// global_template->ApplyToObject(global_object);
// internal::Helper *helper = global_object->GetHelper();
// helper->m_object_template = global_template;
// helper->SetInternalFieldCount(global_template->m_internal_field_count);
}
return Persistent<Context>::New(context);
}
void Context::Enter() {
previous_context_ = s_current_context_;
s_current_context_ = this;
// printf("%s\n", __PRETTY_FUNCTION__);
}
void Context::Exit() {
// printf("%s\n", __PRETTY_FUNCTION__);
assert(s_current_context_ == this);
s_current_context_ = previous_context_;
}
Local<Context> Context::GetCurrent() {
if (s_current_context_) {
return Local<Context>::New(Handle<Context>(s_current_context_));
}
return Local<Context>();
}
} | true |
ead7dd325012f5f4a6126b3d7e73f33ad34a4b09 | C++ | userdw/Arduino_Sensor_Training_Kit | /code/08_Grove_Buzzer/Vibration_Detection/Vibration_Detection.ino | UTF-8 | 808 | 2.53125 | 3 | [] | no_license | /*===============VIBRATION DETECTION==============
Dibuat Oleh Tim Digiware
==========================================
Konfigurasi Pin:
|--------------------------------------------------------|
| | Arduino Base HAT |
|--------------------------------------------------------|
|Grove - Red/Green/Blue LED / Buzzer | D3 |
|Grove - Vibration Sensor | D2 |
|--------------------------------------------------------|
*/
int vib = 2;
int out = 3;
void setup() {
Serial.begin(9600);
pinMode(vib,INPUT);
pinMode(out,OUTPUT);
}
void loop() {
int data = digitalRead(vib);
if(data == HIGH)
{
digitalWrite(out, LOW);
}
else
{
digitalWrite(out, HIGH);
delay(500);
}
}
| true |
bc9d357d65fd57ddf78030915174175063cfe8e2 | C++ | bioidiap/bob.learn.linear | /bob/learn/linear/cpp/pca.cpp | UTF-8 | 6,042 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @date Tue Jan 18 17:07:26 2011 +0100
* @author André Anjos <andre.anjos@idiap.ch>
* @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>
*
* @brief Principal Component Analysis implemented with Singular Value
* Decomposition or using the Covariance Method. Both are implemented using
* LAPACK. Implementation.
*
* Copyright (C) Idiap Research Institute, Martigny, Switzerland
*/
#include <algorithm>
#include <blitz/array.h>
#include <boost/format.hpp>
#include <bob.math/stats.h>
#include <bob.math/svd.h>
#include <bob.math/eig.h>
#include <bob.learn.linear/pca.h>
namespace bob { namespace learn { namespace linear {
PCATrainer::PCATrainer(bool use_svd)
: m_use_svd(use_svd), m_safe_svd(false)
{
}
PCATrainer::PCATrainer(const PCATrainer& other)
: m_use_svd(other.m_use_svd), m_safe_svd(other.m_safe_svd)
{
}
PCATrainer::~PCATrainer() {}
PCATrainer& PCATrainer::operator= (const PCATrainer& other) {
if (this != &other) {
m_use_svd = other.m_use_svd;
m_safe_svd = other.m_safe_svd;
}
return *this;
}
bool PCATrainer::operator== (const PCATrainer& other) const {
return m_use_svd == other.m_use_svd &&
m_safe_svd == other.m_safe_svd;
}
bool PCATrainer::operator!= (const PCATrainer& other) const {
return !(this->operator==(other));
}
/**
* Sets up the machine calculating the PC's via the Covariance Matrix
*/
static void pca_via_covmat(Machine& machine,
blitz::Array<double,1>& eigen_values, const blitz::Array<double,2>& X,
int rank) {
/**
* computes the covariance matrix (X-mu)(X-mu)^T / (len(X)-1) and then solves
* the generalized eigen-value problem taking into consideration the
* covariance matrix is symmetric (and, by extension, hermitian).
*/
blitz::Array<double,1> mean(X.extent(1));
blitz::Array<double,2> Sigma(X.extent(1), X.extent(1));
bob::math::scatter_(X, Sigma, mean);
Sigma /= (X.extent(0)-1); //unbiased variance estimator
blitz::Array<double,2> U(X.extent(1), X.extent(1));
blitz::Array<double,1> e(X.extent(1));
bob::math::eigSym_(Sigma, U, e);
e.reverseSelf(0);
U.reverseSelf(1);
/**
* sets the linear machine with the results:
*/
machine.setInputSubtraction(mean);
machine.setInputDivision(1.0);
machine.setBiases(0.0);
if (e.size() == eigen_values.size()) {
eigen_values = e;
machine.setWeights(U);
}
else {
eigen_values = e(blitz::Range(0,rank-1));
machine.setWeights(U(blitz::Range::all(), blitz::Range(0,rank-1)));
}
}
/**
* Sets up the machine calculating the PC's via SVD
*/
static void pca_via_svd(Machine& machine, blitz::Array<double,1>& eigen_values,
const blitz::Array<double,2>& X, int rank, bool safe_svd) {
// removes the empirical mean from the training data
blitz::Array<double,2> data(X.extent(1), X.extent(0));
blitz::Range a = blitz::Range::all();
for (int i=0; i<X.extent(0); ++i) data(a,i) = X(i,a);
// computes the mean of the training data
blitz::secondIndex j;
blitz::Array<double,1> mean(X.extent(1));
mean = blitz::mean(data, j);
// applies the training data mean
for (int i=0; i<X.extent(0); ++i) data(a,i) -= mean;
/**
* computes the singular value decomposition using lapack
*
* note: Lapack already organizes the U,Sigma,V**T matrixes so that the
* singular values in Sigma are organized by decreasing order of magnitude.
* You **don't** need sorting after this.
*/
const int rank_1 = (rank == (int)X.extent(1))? X.extent(1) : X.extent(0);
blitz::Array<double,2> U(X.extent(1), rank_1);
blitz::Array<double,1> sigma(rank_1);
bob::math::svd_(data, U, sigma, safe_svd);
/**
* sets the linear machine with the results:
*
* note: eigen values are sigma^2/X.extent(0) diagonal
* eigen vectors are the rows of U
*/
machine.setInputSubtraction(mean);
machine.setInputDivision(1.0);
machine.setBiases(0.0);
blitz::Range up_to_rank(0, rank-1);
machine.setWeights(U(a,up_to_rank));
//weight normalization (if necessary):
//norm_factor = blitz::sum(blitz::pow2(V(all,i)))
// finally, we set also the eigen values in this version
eigen_values = (blitz::pow2(sigma)/(X.extent(0)-1))(up_to_rank);
}
void PCATrainer::train(Machine& machine, blitz::Array<double,1>& eigen_values,
const blitz::Array<double,2>& X) const {
// data is checked now and conforms, just proceed w/o any further checks.
const int rank = output_size(X);
// Checks that the dimensions are matching
if (machine.inputSize() != (size_t)X.extent(1)) {
boost::format m("Number of features at input data set (%d columns) does not match machine input size (%d)");
m % X.extent(1) % machine.inputSize();
throw std::runtime_error(m.str());
}
if (machine.outputSize() != (size_t)rank) {
boost::format m("Number of outputs of the given machine (%d) does not match the maximum covariance rank, i.e., min(#samples-1,#features) = min(%d, %d) = %d");
m % machine.outputSize() % (X.extent(0)-1) % X.extent(1) % rank;
throw std::runtime_error(m.str());
}
if (eigen_values.extent(0) != rank) {
boost::format m("Number of eigenvalues on the given 1D array (%d) does not match the maximum covariance rank, i.e., min(#samples-1,#features) = min(%d,%d) = %d");
m % eigen_values.extent(0) % (X.extent(0)-1) % X.extent(1) % rank;
throw std::runtime_error(m.str());
}
if (m_use_svd) pca_via_svd(machine, eigen_values, X, rank, m_safe_svd);
else pca_via_covmat(machine, eigen_values, X, rank);
}
void PCATrainer::train(Machine& machine, const blitz::Array<double,2>& X) const {
blitz::Array<double,1> throw_away_eigen_values(output_size(X));
train(machine, throw_away_eigen_values, X);
}
size_t PCATrainer::output_size (const blitz::Array<double,2>& X) const {
return (size_t)std::min(X.extent(0)-1,X.extent(1));
}
}}}
| true |
fd78067c55418910fb1c12e033a4f2ee4bd566fb | C++ | s00ler/algorithms-and-data-structures | /task1.cpp | UTF-8 | 1,192 | 3.5625 | 4 | [] | no_license | #include <vector>
#include <iostream>
std::vector<int> factor(int value) {
std::vector<int> result;
int d = 2;
while (d * d <= value) {
if (value % d == 0) {
result.push_back(d);
value /= d;
}
else
d++;
}
if (value > 1)
result.push_back(value);
return result;
}
void print_vector(std::vector<int> vec) {
std::cout << "[";
for (size_t i = 0; i < vec.size(); i++) {
if (i != 0)
std::cout << ", ";
std::cout << vec[i];
}
std::cout << "]" << '\n';
}
void factorize_vector(int N) {
for (size_t i = 1; i <= N; i++) {
std::cout << i <<": ";
print_vector(factor(i));
}
}
int main(int argc, char const *argv[]) {
if (argc < 2) {
std::cout << "Right way: python task1.py <int number>" << std::endl;
return 0;
}
factorize_vector(strtol(argv[1], nullptr, 0));
return 0;
}
| true |
0315509bfbc6b1daecef7806cba531f9b70d31ba | C++ | minzo/DPM | /source/ThreadPool.h | UTF-8 | 6,109 | 3.265625 | 3 | [] | no_license | //==============================================================================
//
// Thread Pool
//
//==============================================================================
#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_
#include <thread>
#include <mutex>
#include <condition_variable>
#include <map>
#include <queue>
#include <vector>
#include <functional>
class ThreadPool
{
public:
//--------------------------------------------------------------------------
// @brief コンストラクタ
// @param nThreads スレッド数
//--------------------------------------------------------------------------
ThreadPool(int nThreads_ = std::thread::hardware_concurrency()) : nThreads(nThreads_)
{
// スレッド内の処理
auto worker = [](ThreadPool& threadPool)
{
std::function<void(int)> task;
while(true)
{
{
std::unique_lock<std::mutex> lock(threadPool.mutexTaskQueue);
// タスクが入るまで待機状態
while(threadPool.taskQueue.empty() && !threadPool.isDestruct)
{
// アイドル状態のスレッド数を1つ増やす
threadPool.nIdleThreads++;
// 全スレッドアイドル状態なら Join によるブロッキング解除
if(threadPool.nIdleThreads == threadPool.nThreads)
{
threadPool.conditionThreadPoolJoin.notify_all();
}
// スレッドを待機状態にする
threadPool.condition.wait(lock);
// アイドル状態のスレッド数を1つ減らす
threadPool.nIdleThreads--;
}
// 終了処理
if(threadPool.taskQueue.empty() || threadPool.isDestruct)
{
return;
}
// タスク取り出し
task = threadPool.taskQueue.front();
threadPool.taskQueue.pop();
}
// タスクの実行
task(threadPool.thread_map[std::this_thread::get_id()]);
}
};
// スレッド生成
for(int i=0; i<nThreads; i++)
{
std::thread thread = std::thread(worker, std::ref(*this));
thread_map[thread.get_id()] = i;
threads.push_back(std::move(thread));
}
}
//--------------------------------------------------------------------------
// @brief デストラクタ
//--------------------------------------------------------------------------
~ThreadPool()
{
// 終了フラグ
isDestruct = true;
// 全スレッドに通知
condition.notify_all();
// Join に通知
conditionThreadPoolJoin.notify_all();
// スレッド後始末
for(int i = 0;i<threads.size(); i++)
{
threads[i].join();
}
}
//--------------------------------------------------------------------------
// @brief タスクを追加する
//--------------------------------------------------------------------------
void Request(std::function<void(int)> task)
{
{
std::unique_lock<std::mutex> lock(mutexTaskQueue);
taskQueue.push(task);
}
// 待機スレッドのどれか 1 つに通知して待機解除
condition.notify_one();
}
//--------------------------------------------------------------------------
// @brief 全てのスレッドがアイドル状態
//--------------------------------------------------------------------------
bool IsAllThreadIdle()
{
return nIdleThreads == nThreads;
}
//--------------------------------------------------------------------------
// @brief 全スレッド数を返す
//--------------------------------------------------------------------------
int GetNumThread()
{
return nThreads;
}
//--------------------------------------------------------------------------
// @brief アイドル状態のスレッド数を返す
//--------------------------------------------------------------------------
int GetNumThreadIdle()
{
return nIdleThreads;
}
//--------------------------------------------------------------------------
// @brief スレッドプール内の処理が全て終了するのを待機する
//--------------------------------------------------------------------------
void Join()
{
std::mutex mutex;
std::unique_lock<std::mutex> lock(mutex);
// タスクが空かつ全スレッドがアイドル状態になるまで待つ
while(!IsAllThreadIdle() || !taskQueue.empty())
{
if(isDestruct) break;
conditionThreadPoolJoin.wait(lock);
}
}
private:
// task queue
std::queue<std::function<void(int)> > taskQueue;
// mutex for task queue
std::mutex mutexTaskQueue;
// task queue 用の状態変数
std::condition_variable condition;
// スレッド
std::vector<std::thread> threads;
// スレッド番号
std::map<std::thread::id, int> thread_map;
// スレッド数
int nThreads;
// アイドル状態のスレッド数
int nIdleThreads = 0;
// スレッドプールの処理が終わるまで待機させるための状態変数
std::condition_variable conditionThreadPoolJoin;
// スレッドプールが破棄されるフラグ
bool isDestruct = false;
};
#endif | true |
f530db9478de7c75282775ed96e6d282c5a8d772 | C++ | ztipnis/imaplw | /test/miniz_test.cpp | UTF-8 | 4,137 | 2.703125 | 3 | [
"BSL-1.0",
"MIT",
"OpenSSL",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows"
] | permissive | //test_miniz
#include <miniz.h>
#include <string>
#include <sstream>
#include <boost/log/trivial.hpp>
#include <iostream>
#define ifThenElse(a,b,c) (a ? b : c)
#define min(a,b) ( a < b ? a : b)
#define max(a,b) ( a > b ? a : b)
#define Z_BUF_SIZE (1024*1024)
typedef unsigned int uint;
const std::string deflate(const std::string& data, const int level){
z_stream strm = {0};
std::string outbuf(Z_BUF_SIZE, 0);
std::string inbuf(min(Z_BUF_SIZE, data.length()), 0);
std::stringstream buf;
strm.next_out = reinterpret_cast<unsigned char*>(&outbuf[0]);
strm.avail_out = Z_BUF_SIZE;
strm.next_in = reinterpret_cast<unsigned char*>(&inbuf[0]);
strm.avail_in = 0;
uint remaining = data.length();
if(deflateInit(&strm, level) != Z_OK){
BOOST_LOG_TRIVIAL(error) << "Unable to init deflate";
return data;
}
while(1){
if(!strm.avail_in){
uint bytesToRead = min(Z_BUF_SIZE, remaining);
inbuf = data.substr(data.length() - remaining, bytesToRead);
strm.next_in = reinterpret_cast<unsigned char*>(&inbuf[0]);
strm.avail_in = bytesToRead;
remaining -= bytesToRead;
}
int status = deflate(&strm, ifThenElse(remaining, Z_NO_FLUSH, Z_FINISH));
if(status == Z_STREAM_END || (!strm.avail_out)){
// Output buffer is full, or compression is done.
uint n = Z_BUF_SIZE - strm.avail_out;
buf << outbuf.substr(0,n);
std::fill(outbuf.begin(), outbuf.end(), 0);
strm.next_out = reinterpret_cast<unsigned char*>(&outbuf[0]);
strm.avail_out = Z_BUF_SIZE;
}
if(status == Z_STREAM_END)
break;
else if(status != Z_OK)
BOOST_LOG_TRIVIAL(error) << "Deflate status not 'OK'";
return data;
}
if(deflateEnd(&strm) != Z_OK){
BOOST_LOG_TRIVIAL(warning) << "zlib unable to cleanup deflate stream";
}
std::string ret = buf.str();
if(ret.length() != strm.total_out){
BOOST_LOG_TRIVIAL(error) << "Output size mismatch - Expected: " << strm.total_out << " Got: " << ret.length();
}
// BOOST_LOG_TRIVIAL(trace) << "DEFLATE: " << ((ret.length() * 100) / data.length()) << "%" << ret;
return ret;
}
const std::string inflate(const std::string& data){
z_stream strm = {0};
std::string outbuf(Z_BUF_SIZE, 0);
std::string inbuf(Z_BUF_SIZE, 0);
std::stringstream buf;
strm.next_out = reinterpret_cast<unsigned char*>(&outbuf[0]);
strm.avail_out = Z_BUF_SIZE;
strm.next_in = reinterpret_cast<unsigned char*>(&inbuf[0]);
strm.avail_in = 0;
uint remaining = data.length();
if(inflateInit(&strm) != Z_OK){
throw std::runtime_error("Unable to inflate command data: Init failed.\n");
}
while(1){
if(!strm.avail_in){
uint bytesToRead = min(Z_BUF_SIZE, remaining);
inbuf = data.substr(data.length() - remaining, bytesToRead);
strm.next_in = reinterpret_cast<unsigned char*>(&inbuf[0]);
strm.avail_in = bytesToRead;
remaining -= bytesToRead;
}
int status = inflate(&strm, Z_SYNC_FLUSH);
if ((status == Z_STREAM_END) || (!strm.avail_out)){
// Output buffer is full, or decompression is done
uint n = Z_BUF_SIZE - strm.avail_out;
buf << outbuf.substr(0,n);
std::fill(outbuf.begin(), outbuf.end(), 0);
strm.next_out = reinterpret_cast<unsigned char*>(&outbuf[0]);
strm.avail_out = Z_BUF_SIZE;
}
if(status == Z_STREAM_END)
break;
else if(status != Z_OK)
throw std::runtime_error("Unable to inflate");
}
if(inflateEnd(&strm) != Z_OK){
BOOST_LOG_TRIVIAL(warning) << "zlib unable to cleanup inflate stream";
}
std::string ret = buf.str();
if(ret.length() != strm.total_out){
BOOST_LOG_TRIVIAL(error) << "Output size mismatch - Expected: " << strm.total_out << " Got: " << ret.length();
}
return ret;
}
int main(int argc, char** argv){
std::string data = "A001 CAPABILITY\nA001 CAPABILITY\nA001 CAPABILITY\nA001 CAPABILITY\nA001 CAPABILITY\n";
std::cout << "Data:" <<data << std::endl;
std::string cdata = deflate(data, 4);
std::cout << "Deflated:" <<cdata << std::endl;
std::string udata = inflate(cdata);
std::cout << "Inflated:" <<udata << std::endl;
return 0;
}
| true |
58c5fab1d2df5e2e84e903fcc9bac6a1d71d255e | C++ | hello-lx/CodingTest | /4/573.cpp | UTF-8 | 2,926 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <vector>
#include <math.h>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <list>
#include <queue>
#include <stack>
using namespace std;
#define INT_MIN -99999999999
#define INT_MAX 99999999999
class Solution {
public:
bool is_empty_space(int x, int y, vector<vector<int>>& grid) {
if (x < 0 || x >= grid.size() ||
y < 0 || y >= grid[0].size()) {
return false;
}
if (grid[x][y] != 0) {
return false;
}
return true;
}
/**
* @param grid: a 2D grid
* @return: An integer
*/
int shortestDistance(vector<vector<int>> &grid) {
if (grid.size() == 0 || grid[0].size() == 0) {
return -1;
}
int row = grid.size();
int col = grid[0].size();
// find all houses
vector<pair<int,int>> houses;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == 1) {
houses.push_back(make_pair(i,j));
}
}
}
// distance (sum) from different houses to this point
vector<vector<int>> dist(row, vector<int>(col,0));
// how many houses reaches this point
vector<vector<int>> reach(row, vector<int>(col,0));
// bfs from *each* houses
for (auto house : houses) {
// bfs
queue<pair<int,int>> q;
vector<vector<bool>> visited(row, vector<bool>(col,false));
q.push(house);
visited[house.first][house.second] = true; // this is not necessary here
int steps = 0;
while (!q.empty()) {
int size = q.size();
steps++;
for (int i = 0; i < size; i++) {
pair<int,int> cur = q.front(); q.pop();
for (auto d : dir) {
int x = cur.first + d[0];
int y = cur.second + d[1];
if (!is_empty_space(x, y, grid) || visited[x][y]) {
continue;
}
reach[x][y] ++;
dist[x][y] += steps;
q.push(make_pair(x,y));
visited[x][y] = true;
}
}
}
}
int res = INT_MAX;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == 0 && reach[i][j] == houses.size()) {
res = min(res, dist[i][j]);
}
}
}
return (res == INT_MAX) ? -1 : res;
}
private:
vector<vector<int>> dir = {{0,1},{0,-1},{1,0},{-1,0}};
};
| true |
dce0cd7bfcbd4b2c4e04ef67042cf10735195a5b | C++ | gruizFING/SOs | /Lab3/soAgenda/MEMORIA.CPP | UTF-8 | 1,354 | 2.90625 | 3 | [] | no_license | #include "memoria.h"
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#define PERMISOS S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
int abrir_segmento(char clave, int segsize)
{
key_t llave;
llave = ftok(".",clave);
if(llave == (key_t)-1)
return -1;
return shmget(llave, segsize, IPC_CREAT | PERMISOS); // si existe no se devuelve error
}
bool existe_segmento(char clave, int segsize)
{
int shmid = shmget(ftok(".",clave), segsize, PERMISOS);
return !(shmid == -1 && errno == ENOENT);
}
void * mapear_segmento(char clave, int segsize)
{
key_t llave;
llave = ftok(".",clave);
if(llave == (key_t)-1)
return NULL;
int shmid = shmget(llave, segsize,PERMISOS);
if(shmid != -1)
return shmat(shmid, 0, 0); // mismos permisos
else
return NULL;
}
int liberar_segmento(void* addr)
{
return shmdt(addr);
}
int destruir_segmento(char clave, int segsize)
{
key_t llave;
llave = ftok(".",clave);
if(llave == (key_t)-1)
return -1;
int shmid = shmget(llave, segsize, PERMISOS);
if(shmid != -1)
return(shmctl(shmid, IPC_RMID, NULL));
else
return -1;
}
void* mapear_segmento_id(int shmid)
{
return shmat(shmid, 0, 0);
}
int destruir_segmento_id(int shmid)
{
return (shmctl(shmid, IPC_RMID, NULL));
}
| true |
c2dae49e2991e14be3c95da2dae272cf39fea8bd | C++ | paucazou/FRUMUL2 | /frumul/parameters.cpp | UTF-8 | 20,232 | 2.765625 | 3 | [] | no_license | #include <climits>
#include <unordered_map>
#include "functions.inl"
#include "parameters.h"
#include "parmqueuer.h"
#include "compiler.h"
#include "symbol.h"
#include "vm.h"
namespace frumul {
Parameter::Parameter(const Node& node, Symbol& np) :
Parameter(node,&np)
{}
Parameter::Parameter(const Node& node,Symbol* np) :
type{node.get("variable").get("type")},
name{node.get("variable").get("name").getValue()},
parent{np}
{
/* Constructs the base of the parameter
*/
assert (node.type() == Node::PARAM&&"Node is not a parameter");
//type
/*
const FString& t{node.get("variable").get("type").getValue()};
if (t == "text")
type = Text;
else if (t == "int")
type = Int;
else if (t == "bool")
type = Bool;
else if (t == "Symbol")
type = Symbol;
else
throw exc(exc::UnknownType,"Unknown type",node.get("variable").get("type").getPosition());
*/
const StrNodeMap& fields{node.getNamedChildren()};
// arg number
setMinMax(fields);
// optional
// // choices
if (fields.count("choices"))
choices = std::make_unique<Node>(fields.at("choices"));
// // default value
const StrNodeMap& var_fields{node.get("variable").getNamedChildren()};
if (var_fields.count("value"))
def = std::make_unique<Node>(var_fields.at("value"));
// positions
pos.push_back(node.getPosition());
if (type.isStatic())
throw exc(exc::TypeError,"A parameter can not be static",node.getPosition());
}
Parameter::Parameter (const FString& nname, const ExprType& ntype, const std::vector<Position>& npos,Symbol& nparent) :
type{ntype},
name{nname},
limit1 {std::make_unique<Limit>(Limit(1,Limit::EQUAL))},
pos{npos},
parent{&nparent}
{
/* Creates a parameter with a limit equal to 1
*/
}
Parameter::Parameter(const Parameter& other) :
type{other.type},
name{other.name},
limit1{uniq_copy<Limit>(other.limit1)},
limit2{uniq_copy<Limit>(other.limit2)},
min{other.min},
max{other.max},
def{uniq_copy<Node>(other.def)},
choices{uniq_copy<Node>(other.choices)},
_choices{uniq_copy<std::vector<ValVar>>(other._choices)},
//_choices{ other._choices ? std::make_unique<std::vector<ValVar>>(*other._choices) : nullptr},
_def{ other._def ? std::make_unique<ValVar>(*other._def) : nullptr},
pos{other.pos},
parent{other.parent},
index{other.index}
{
/* Copy constructor
* Temporary is not copied
*/
if (other.limit1)
limit1 = std::make_unique<Limit>(*other.limit1);
if (other.limit2)
limit2 = std::make_unique<Limit>(*other.limit2);
}
Parameter::~Parameter () {
/* Destructor.
* TODO it's probably useless now
*/
/*
if (limit1)
delete limit1;
if (limit2)
delete limit2;
*/
}
void Parameter::appendPos(const Position& npos) {
/* Add a new position (when the user declares two
* series of parameters identical
*/
pos.push_back(npos);
}
void Parameter::setMinMax(const StrNodeMap& fields) {
/* Try to find the number of args and set min and max
* according to the fields entered
*/
assert(!limit1&&!limit2&&"Limits have been set already");
if (fields.count("argnb0")) {
// at least one parameter
const Node& arg {fields.at("argnb0")};
Limit::Comparison c{comparisonValue(arg.getValue())};
limit1 = std::make_unique<Limit>(
arg.getNumberedChildren()[0],
c);
if (fields.count("argnb1")) {
const Node& arg {fields.at("argnb1")};
Limit::Comparison c{comparisonValue(arg.getValue())};
limit2 = std::make_unique<Limit>(
arg.getNumberedChildren()[0],
c);
// check consistency
switch(limit1->getComparison()) {
case Limit::SUPERIOR:
case Limit::SEQUAL:
case Limit::EQUAL:
break;
case Limit::IEQUAL:
case Limit::INFERIOR:
throw exc(exc::ArgumentNBError,"When setting two limits, the only comparison symbols allowed for the first one are >,>= and =",limit1->getPosition());
};
switch (limit2->getComparison()) {
case Limit::IEQUAL:
case Limit::INFERIOR:
case Limit::EQUAL:
break;
case Limit::SEQUAL:
case Limit::SUPERIOR:
throw exc(exc::ArgumentNBError,"When setting two limits, the only comparison symbols allowed for the second one are <,<= and =",limit1->getPosition());
}
}
}
else {
// implicit: =1
limit1 = std::make_unique<Limit>(Limit(1,Limit::EQUAL));
}
}
void Parameter::setMinMax(int min_, int max_) {
/* Set min and max
*/
min = min_;
max = max_;
}
void Parameter::setParent(Symbol& np) {
/* Set a new parent
*/
parent = &np;
}
void Parameter::setDefault(const ValVar& value) {
/* Set the default value
* of the parameter
*/
_def = std::make_unique<ValVar>(value);
}
void Parameter::setIndex(int i) {
/* Set the index
*/
assert(index == -1 && "index already set");
index = i;
}
void Parameter::setChoices(const std::vector<ValVar>& nchoices) {
/* Set the choices if they have'nt been set yet
*/
#if DEBUG
// check that choices match with the type
for (const auto& choice : nchoices) {
if (!type.check(choice))
assert (false&&"Choice has not the right type");
}
#endif
assert(!choices && !_choices && "choices have been defined yet");
_choices = std::make_unique<std::vector<ValVar>>(nchoices);
}
Parameter::Limit::Comparison Parameter::comparisonValue(const FString& val) const{
/* Return an enum
* matching with val
*/
if (val == "=")
return Limit::EQUAL;
else if (val == ">")
return Limit::SUPERIOR;
else if (val == "<")
return Limit::INFERIOR;
else if (val == ">=")
return Limit::SEQUAL;
else if (val == "<=")
return Limit::IEQUAL;
else
assert(false&&"Unknown binary operator");
}
bool Parameter::operator == (const Parameter& other) const {
/* true if other is strictly equal to *this
* (except for the positions)
*/
return (type == other.type &&
name == other.name &&
limit1 == other.limit1 &&
limit2 == other.limit2);
}
bool Parameter::operator != (const Parameter& other) const {
/* true if operator == is false
*/
return !(*this == other);
}
const Node& Parameter::getNodeDefault() const {
return *def;
}
const Node& Parameter::getChoices() const {
return *choices;
}
const ExprType& Parameter::getType() const {
return type;
}
const FString& Parameter::getName() const {
return name;
}
int Parameter::getMin(const FString& lang) {
if (min == -1)
calculateMinMax(lang);
return min;
}
int Parameter::getMax(const FString& lang) {
if (max == -1)
calculateMinMax(lang);
return max;
}
void Parameter::calculateMinMax(const FString& lang) {
/* Calculate min and max
* and returns it, min as first,
* and max as second
* checks the error (impossible to do this before)
*/
assert(parent&&"Parameter: parent is not set");
assert(min == -1 && "Min already set");
assert(max == -1 && "Max already set");
if (limit2) {
int min_ { limit1->getLimit(lang,*parent) };
int max_ {limit2->getLimit(lang,*parent) };
// limits are equal
if (min_ == max_) {
if (limit1->getComparison() != limit2->getComparison())
throw iexc(exc::ArgumentNBError,"Limits given to the parameter have the same value but not the same sign. Limit 1:",limit1->getPosition(),"Limit 2:",limit2->getPosition());
return calculateMinMaxWithOneLimit(min_,limit1->getComparison());
}
else if (min_ > max_)
throw iexc(exc::ArgumentNBError,"Min is over max. Min: ",limit1->getPosition(),"Max: ",limit2->getPosition());
// get real value
if (limit1->getComparison() == Limit::SUPERIOR)
++min_;
if (limit2->getComparison() == Limit::INFERIOR)
--max_;
// last checks
if (min_ < 0)
throw exc(exc::ValueError,"Limit given is under zero",limit1->getPosition());
min = min_;
max = max_;
}
return calculateMinMaxWithOneLimit(limit1->getLimit(lang,*parent),limit1->getComparison());
}
void Parameter::calculateMinMaxWithOneLimit(int limit, Limit::Comparison c) {
constexpr int absolute_min {0};
// check errors
if (limit<absolute_min)
throw exc(exc::ValueError,"Limit given is under zero",limit1->getPosition());
switch (c) {
case Limit::EQUAL:
min = limit;
max = limit;
break;
case Limit::SUPERIOR:
min = limit +1;
max = INT_MAX;
break;
case Limit::INFERIOR:
min = absolute_min;
max = limit-1;
break;
case Limit::SEQUAL:
min = limit;
max = INT_MAX;
break;
case Limit::IEQUAL:
min = absolute_min;
max = limit;
break;
};
}
const PosVect& Parameter::getPositions() const {
return pos;
}
int Parameter::getIndex() const {
assert(index > -1 && "Index not set");
return index;
}
bool Parameter::operator == (int nb) const {
/* true if nb is equal to min AND max
*/
return (nb == min && nb == max);
}
bool Parameter::operator > (int nb) const {
/* true if max is above nb
*/
return max > nb;
}
bool Parameter::operator < (int nb) const {
/* true if min is beyond nb
*/
return min < nb;
}
bool Parameter::between (int nb) const {
/* true if nb is between or equal to min
* and max
*/
assert(min > -1 && max > -1 && "Min and max not set");
return (nb <= max && nb >= min);
}
bool Parameter::between (int nb, const FString& lang) {
/* Can set min and max
*/
return (nb <= getMax(lang) && nb >= getMin(lang));
}
bool Parameter::hasDefault() const {
/* true if a default value is set
*/
return static_cast<bool>(def||_def);
}
bool Parameter::operator == (const FString& n) const {
/* true if n is equal to name
*/
return n == name;
}
FString Parameter::toString() const {
/* representation of the instance
* Return a partial one, in order to be filled
* by overloads of this function
*/
FString s{"<Parameter|"};
s += type.toString(true) + ">\n"; // true: to avoid unnecessary details
s += "Name: " + name + "\n";
if (def)
s += "Has default value\n";
if (choices)
s += "Has choices\n";
s += "Has ";
if (limit1) {
if (limit2)
s += "2";
else
s += "1";
} else
s += "0";
s += " limit(s)\n";
for (const auto& p : pos)
s += p.toString();
return s;
}
// Parameter::Limit
Parameter::Limit::Limit(const Node& n, Limit::Comparison c) :
comparison{c}, isNode{true}, node{ new Node(n)}, pos{n.getPosition()}
{
/* Constructs with a node
* yet to be evaluated
*/
}
Parameter::Limit::Limit (int ni, Limit::Comparison c) :
comparison{c}, isNode{false}, i{ni}, pos{-1,-1,"",""}
{
/* Constructs directly an int
*/
}
Parameter::Limit::Limit(const Limit& other):
comparison{other.comparison}, isNode{other.isNode},
pos{other.getPosition()}
{
if (other.isNode)
node = new Node(*other.node);
else
i = other.i;
}
Parameter::Limit::~Limit() {
/*Destructor
*/
if (isNode)
delete node;
}
int Parameter::Limit::getLimit(const FString& lang,Symbol& parent) {
/* Return the limit as an int.
* Evaluates the node (if there is a node)
* or return the int
* the int returned should be compared with the comparison field
*/
if (isNode) {
auto compiler {MonoExprCompiler(*node, ET::INT, parent,lang)};
auto bt {compiler.compile()};
auto vm {VM(bt, lang, std::vector<ValVar>())};
delete node;
i = vm.run().as<int>();
isNode = false;
}
return i;
}
Parameter::Limit::Comparison Parameter::Limit::getComparison() const {
return comparison;
}
const Position& Parameter::Limit::getPosition() const {
return pos;
}
FString Parameter::Limit::toString() const {
FString s { "<Limit> " };
if (isNode) {
s += "(Node)\n";
s += node->toString();
}
else {
s += "(Bytecode)\n";
s += pos.toString();
}
return s;
}
bool Parameter::Limit::isConform(int x,const FString& lang,Symbol& parent) {
/* true if x respects the limit
*/
int limit {getLimit(lang,parent)};
switch (comparison) {
case EQUAL:
return x == limit;
case SUPERIOR:
return limit > x;
case INFERIOR:
return limit < x;
case SEQUAL:
return limit >= x;
case IEQUAL:
return limit <= x;
default:
assert(false&&"Limit::Comparison operator not correctly set");
};
return false;
}
bool Parameter::choiceMatch(const ValVar& elt,const FString& lang) {
/* true if elt match one of the elements
* of the choices list
*/
// if no choice has been set
if (!_choices && !choices)
return true;
// compile expression if necessary
if (!_choices) {
auto compiler { MonoExprCompiler(*choices,ExprType(ET::LIST,type),*parent,lang)};
auto bt { compiler.compile() };
auto vm { VM(bt, lang, std::vector<ValVar>()) };
_choices = std::make_unique<std::vector<ValVar>>(
vm.run().as<std::vector<ValVar>>());
choices.reset();
}
// checks that elt match one of _choices
switch (type) { // this gets only the high level type, not the full type. It is equal to &
case ET::INT:
for (const auto& choice : *_choices)
if (cast_equal<int>(elt,choice))
return true;
break;
case ET::TEXT:
for (const auto& choice : *_choices)
if (cast_equal<FString>(elt,choice))
return true;
break;
case ET::BOOL:
for (const auto& choice : *_choices)
if (cast_equal<bool>(elt,choice))
return true;
break;
case ET::SYMBOL:
for (const auto& choice : *_choices)
if (cast_equal<RSymbol>(elt,choice))
return true;
break;
case ET::LIST:
for (const auto& choice : *_choices)
if (_list_match(elt,choice,type))
return true;
break;
default:
assert(false&&"Type not recognized");
};
// default return: elt was not found
return false;
}
ValVar Parameter::getDefault(const FString& lang) {
/* Return the default parameter if it has one
*/
assert((def||_def) && "No default set. Please use Parameter::hasDefault to check it");
if (!_def) {
ExprType real_type {getMax(lang) > 1 ? ExprType(ET::LIST,type) : type};
auto compiler { MonoExprCompiler(*def,real_type,*parent,lang) };
auto bt {compiler.compile()};
auto vm { VM(bt,lang,std::vector<ValVar>()) };
_def = std::make_unique<ValVar>(vm.run());
// checks
if (getMax(lang) > 1) {
auto vect_def { _def->as<std::vector<ValVar>>() };
if (!between(vect_def.size(),lang))
throw iexc(exc::ArgumentNBError,"Default arguments doesn't match the number required by the parameter. Default defined here: ",def->getPosition(),"Argument defined here: ", pos);
}
}
return *_def;
}
bool Parameter::_list_match(const ValVar& first, const ValVar& second, const ExprType& type) {
/* true if first is equal to second.
* if type & ET::LIST, call this function
*/
switch (type) {
case ET::INT:
return cast_equal<int>(first,second);
case ET::TEXT:
return cast_equal<FString>(first,second);
case ET::BOOL:
return cast_equal<bool>(first, second);
case ET::SYMBOL:
return cast_equal<RSymbol>(first,second);
case ET::LIST:
{
const auto first_c { first.as<std::vector<ValVar>>() };
const auto second_c { second.as<std::vector<ValVar>>() };
// check the size
if (first_c.size() != second_c.size())
return false;
// compare each element
for (size_t i{0}; i < first_c.size(); ++i) {
if (!_list_match(first_c[i],second_c[i],type.getContained()))
return false;
}
return true;
}
break;
default:
assert(false&&"Type unknown");
};
}
// Parameters
Parameters::Parameters()
{
}
Parameters::Parameters(Symbol& np) :
parent{&np}
{
}
Parameters& Parameters::operator= (const Parameters& other) {
/* Assignment
*/
for (const auto& elt : other.parms)
parms.push_back(elt);
return *this;
}
bool Parameters::contains(const FString& name) const {
/* true if name names a parameter
*/
for (const auto& p : parms)
if (p == name)
return true;
return false;
}
bool Parameters::operator == (const Parameters& others) const {
/* true if others are exactly equals to *this
*/
if (others.parms.size() != parms.size())
return false;
for (size_t i{0}; i<others.parms.size();++i)
if (others.parms[i] != parms[i])
return false;
return true;
}
PosVect Parameters::getPositions() const {
/* Return all positions of the parameters
*/
PosVect rv;
for (const auto& prm : parms)
for (const auto& pos : prm.getPositions())
rv.push_back(pos);
return rv;
}
void Parameters::push_back(const Parameter& np) {
/* Add a new parameter
*/
// check name collision
for (const auto& p : parms)
if (p == np.getName())
throw iexc(exc::NameError,"Name already taken by another parameter",np.getPositions(),"Name already defined here: ",p.getPositions());
parms.push_back(np);
parms.back().setIndex(parms.size()-1);
}
bool Parameters::empty() const{
return parms.empty();
}
size_t Parameters::size() const {
return parms.size();
}
const std::vector<Parameter>& Parameters::getList() const{
return parms;
}
void Parameters::setParent(Symbol& np) {
/*Set parent and the parent
* of every Parameter
*/
parent = &np;
for (auto& elt : parms)
elt.setParent(np);
}
std::vector<Parameter>& Parameters::getList(){
return parms;
}
std::vector<Parameter>::iterator Parameters::begin() {
return parms.begin();
}
std::vector<Parameter>::iterator Parameters::end() {
return parms.end();
}
std::vector<ValVar> Parameters::formatArgs(const std::vector<Arg>& args, const FString& lang) {
/*Check the arguments and format them
*/
std::vector<ValVar> formatted;
formatted.resize(parms.size());
auto queue { ParmQueuer(parms,lang) };
size_t arg_idx{0};
for (; arg_idx < args.size(); ++arg_idx) {
// get the argument
const Arg& arg{args[arg_idx]};
// get matching parameter
Parameter& parm{queue(arg)};
ValVar value;
// check type
if (parm.getMax(lang) > 1)
value = get_multiple_args(args,arg_idx,lang,parm);
else {
if (arg.type != parm.getType())
throw iexc(exc::TypeError,"Argument entered does not match the type of the parameter. Argument: ",arg.pos,"Parameter set here: ",parm.getPositions());
value = arg.value;
}
// check choice
if (!parm.choiceMatch(value,lang))
throw iexc(exc::ValueError,"Value entered does not match the choices set. Value entered: ",arg.pos,"Choices: ",parm.getChoices().getPosition());
// append to formatted
formatted.at(static_cast<size_t>(parm.getIndex())) = value;
}
// fill default
if (queue.hasUnfilledDefault()) {
auto unfilled_def { queue.getUnfilledDefault() };
for (auto& parm_rf : unfilled_def) {
auto& parm {parm_rf.get()};
formatted.at(static_cast<size_t>(parm.getIndex())) = parm.getDefault(lang);
queue.markFinished(parm);
}
}
// check if every parameter has been checked
if (!queue.areParametersFilled()) {
std::vector<Position> pos;
for (const auto& arg : args)
pos.push_back(arg.pos);
throw iexc(exc::ArgumentNBError,"The number of arguments required does not match the number of arguments entered. Arguments: ", pos,"Parameters defined here: ", getPositions());
}
return formatted;
}
ValVar Parameters::get_multiple_args(const std::vector<Arg>& args, size_t& arg_idx, const FString& lang,Parameter& parm) {
/* Return a multiple arg
*/
const FString& arg_name { args[arg_idx].name };
std::vector<ValVar> value;
for (; arg_idx < args.size() && args[arg_idx].name == arg_name; ++arg_idx) {
const Arg& arg {args[arg_idx]};
if (args[arg_idx].type != parm.getType())
throw iexc(exc::TypeError,"Argument entered does not match the type of the parameter. Argument: ",arg.pos,"Parameter set here: ",parm.getPositions());
value.push_back(arg.value);
}
if (!parm.between(lang))
throw iexc(exc::ArgumentNBError,"Argument number entered does not match the number required. Last argument: ",args[arg_idx-1].pos,"Parameter set here: ",parm.getPositions());
return value;
}
bool operator == (CRParameter& f, CRParameter& s) {
/* true if f and s points to the same object
*/
return &f.get() == &s.get();
}
}
| true |
ce07d4df5228b2169f97109f95283e794874f238 | C++ | CIVIVFanatic/TSK | /Micro/components/speaker.h | UTF-8 | 448 | 2.609375 | 3 | [] | no_license | //authors: Robert Hayes
//TechSmartKids 2014
#include <micro_component.h>
class Speaker{
public:
Speaker(GpioPwmPin p):pin(p){};
void playNote(int note);
void playNote(int note, int duration);
void stop();
private:
GpioPwmPin pin;
};
void Speaker::playNote(int note){
tone(pin.getPin(),note);
}
void Speaker::playNote(int note, int duration){
tone(pin.getPin(),note,duration);
}
void Speaker::stop(){
noTone(pin.getPin());
} | true |
51485c2bb75055e43e99013d919e52a926bdce74 | C++ | sarojku17/csAcademy | /Build_the_Fence.cpp | UTF-8 | 650 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
long N;long long K;
long max_height=0;
bool check(vector<long> trees,long mid){
if(mid==0) return false;
long sol=0;
for(long i=0;i<N;i++)
{
sol+=floor(trees[i]/mid);
if(sol>=K)
{
max_height=mid;
return true;
}
}
return false;
}
int main(){
cin>>N>>K;vector<long> trees(N);
for(int i=0;i<N;i++)
{
cin>>trees[i];
}
long l=1;
long r=(long)1e9;
long mid;
while(!(l>r))
{
mid=(l+r)>>1;
bool flag=check(trees,mid);
if(flag)
l=mid+1;
else
r=mid-1;
}
cout<<max_height<<endl;
}
| true |
05df21b90245b3ff132aeb15af4d1f302361860a | C++ | bvbfan/stlxx | /test.cpp | UTF-8 | 1,420 | 2.859375 | 3 | [
"MIT"
] | permissive |
#include "stlxx.h"
#include <algorithm>
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>
struct Employee {
std::string id;
Employee(Employee &&) = default;
Employee(std::string id) : id(id) {}
std::vector<std::string> lunch_partners;
};
int main(int argc, char *argv[])
{
Employee mat("mat");
std::thread *workers[16];
stlxx::atomic<std::vector<std::int64_t>> vec;
stlxx::atomic<Employee> mel = Employee{"mel"}, bob = Employee{"bob"};
for (auto &worker : workers) {
worker = new std::thread([=, &mat]() {
std::stringstream s;
s << std::this_thread::get_id();
std::int64_t i64; s >> i64;
vec->push_back(i64);
using mutex = std::recursive_mutex&;
stlxx::synchronized([=, &mat]() {
mel->lunch_partners.push_back(mat.id);
mat.lunch_partners.push_back(bob->id);
bob->lunch_partners.push_back(mel->id);
}, mutex(mel), mutex(bob));
});
}
for (auto &worker : workers) {
worker->join();
delete worker;
}
auto &v = vec;
auto &v1 = mel->lunch_partners;
auto &v2 = mat.lunch_partners;
auto &v3 = bob->lunch_partners;
std::cout << v->size() << ": "
<< v1.size() << ": "
<< v2.size() << ": "
<< v3.size() << '\n';
return 0;
}
| true |
937067db3eba104af115e1cb53f5a7a39921986d | C++ | jhluo/EFM_Server | /Client/Data/CommandHandler.cpp | UTF-8 | 1,903 | 2.515625 | 3 | [] | no_license | #include "CommandHandler.h"
#include "Client/AClient.h"
#define ACK_TIMEOUT 3000 //expect acknowledge to come back in 3 seconds
#define COMMAND_TIMER 60 * 1000 //send command every 1 minute (for version 3 only)
CommandHandler::CommandHandler(QIODevice* pInput, int version, QObject *pParent) :
QObject(pParent),
m_ClientVersion(version),
m_pIoDevice(pInput),
m_WaitingForReply(false)
{
//time out command without acknowledgment
m_pAckTimer = new QTimer(this);
m_pAckTimer->setInterval(ACK_TIMEOUT);
m_pAckTimer->setSingleShot(true);
connect(m_pAckTimer, SIGNAL(timeout()), this, SLOT(onAckTimeout()));
//command timer
m_pCommandTimer = new QTimer(this);
m_pCommandTimer->setInterval(COMMAND_TIMER);
connect(m_pCommandTimer, SIGNAL(timeout()), this, SLOT(onCommandTimeout()));
sendCommand(m_pIoDevice, "READDATA");
}
CommandHandler::~CommandHandler()
{
m_pAckTimer->stop();
m_pCommandTimer->stop();
}
bool CommandHandler::sendCommand(QIODevice *pOutputChannel, const QByteArray &command, const QString &expectedAck)
{
if(pOutputChannel==NULL)
return false;
int bytes = pOutputChannel->write(command);
if(expectedAck!="") {
m_pAckTimer->start();
m_WaitingForReply = true;
m_ExpectedAck=expectedAck;
}
return (bytes == command.size());
}
void CommandHandler::processCommand(const QString &command)
{
if(m_WaitingForReply) {
if(command.contains(m_ExpectedAck)) {
m_pAckTimer->stop();
m_WaitingForReply=false;
m_ExpectedAck="";
emit commandAcknowledged(true);
}
}
}
void CommandHandler::onAckTimeout()
{
emit commandAcknowledged(false);
}
void CommandHandler::onCommandTimeout()
{
if(m_ClientVersion == static_cast<int>(AClient::eVersion3)) {
sendCommand(m_pIoDevice, "READDATA");
}
}
| true |
17164351447c519deb53120da98394f30b11af56 | C++ | Fareolla/CppBase22.01.2019 | /QuadDiff/main.cpp | UTF-8 | 756 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
int main()
{
double a, b, c, D, x;
std::cout << " ax2 + bx + c = 0 " << std::endl;
std::cout << "Please insert a" << std::endl;
std::cin >> a;
std::cout << "Please insert b" << std::endl;
std::cin >> b;
std::cout << "Please insert c" << std::endl;
std::cin >> c;
D = b * b - 4 * a * c;
std::cout << "Discriminant is: " << D << std::endl;
if (D >= 0)
{
x = (-1*b + sqrt(D)) / (2 * a);
std::cout << "First root is: " << x << std::endl;
x = (-1*b - sqrt(D)) / (2 * a);
std::cout << "Second root is: " << x << std::endl;
}
else
{
std::cout << "D < 0. No decisions!" << std::endl;
}
return 0;
}
| true |
805d8c6740d8fefb0c53df4bca233cb1c0eb4b64 | C++ | FuentesFelipe/lab1so | /Proceso.cpp | UTF-8 | 1,703 | 3.1875 | 3 | [] | no_license | #include "Proceso.h"
#include <iostream>
#include <ctime>
Proceso::Proceso(){
}
void Proceso::copiarProceso(Proceso proceso){
this->id= proceso.getId();
this->priority = proceso.getPriority();
this->rafaga = proceso.getCurrentTime();
this->tpoLlegada = proceso.getTpoLlegada();
this->currentTime = proceso.getRafaga();
this->waitingTime = proceso.getwaitingTime();
}
Proceso::~Proceso(){}
void Proceso::show(){
cout<<endl<<"Nombre: "<<this->id
<<endl<<"Rafaga: "<<this->rafaga
<<endl<<"Prioridad: "<<this->priority
<<endl<<"Tpo Llegada: "<<this->tpoLlegada
<<endl<<"rafaga restante: "<<this->rafaga<<endl<<endl;
}
void Proceso::crear(string nombre ,float rafaga ,int priority, float t0){
this->id = nombre;
this->rafaga = rafaga;
this->priority = priority;
this->tpoLlegada = float(clock() - t0)*10/CLOCKS_PER_SEC;
this->currentTime = this->rafaga;
this->waitingTime = 0;
}
void Proceso::setRafaga(float rafaga){
this->rafaga = rafaga;
}
void Proceso::setPriority(int priority){
this->priority = priority;
}
void Proceso::setID(std::string id){
this->id = id;
}
std::string Proceso::getId(){
return this->id;
}
float Proceso::getRafaga(){
return this->rafaga;
}
int Proceso::getPriority(){
return this->priority;
}
float Proceso::getTpoLlegada(){
return this->tpoLlegada;
}
float Proceso::getCurrentTime(){
return this->currentTime;
}
float Proceso::getwaitingTime(){
return this->waitingTime;
}
void Proceso::setCurrentTime(clock_t fin, clock_t inicio){
this->currentTime = this->rafaga - double(fin - inicio)*10/CLOCKS_PER_SEC;
}
| true |
194ce5e96b55b567311d442bc35a97bb251f8f5c | C++ | mahdikhaliki/CS-Classes | /CS14 Into to C++ Workplace/Lab 11 Part 2/Lab 11 Part 2/lab11Part2.cpp | UTF-8 | 1,373 | 3.953125 | 4 | [] | no_license | //
// lab11Part2.cpp
//
// Mahdi Khaliki and Farris Tang
// Lab 11 part 2
// Uses an input file for the items and price of items on a menu and creates a
// output file using the values of the input file to create a menu.
//
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct menuItem // Creating struct
{
string item;
float price;
};
const int ARRAYSIZE = 10;
void ReadItem(istream&, menuItem&);
void PrintItem(ostream&, menuItem);
int main()
{
int i;
menuItem m[ARRAYSIZE]; // Declaring array of struct menuItem
ifstream menu("menu.txt"); // Opening input file
ofstream menuOutput("menuOutput.txt"); // Opening output file
if (!menu || !menuOutput) // Checking if files opened
{
cout << "Error opening file." << endl;
return -1;
}
for (i = 0; i < ARRAYSIZE; i++) // Looping to call the functions
{
ReadItem(menu, m[i]);
PrintItem(menuOutput, m[i]);
}
menu.close();
menuOutput.close();
return 0;
}
void ReadItem(istream &menu, menuItem &m) // Pulling data from the input file
{
menu >> m.item >> m.price;
}
void PrintItem(ostream &menuOutput, menuItem m) // Printing menu to output file
{
menuOutput << "Name of menu item is: " << m.item << '\t'
<< "$" << fixed << showpoint
<< setprecision(2) << m.price << endl;
}
| true |
55306ba5261e6b2d85425e40ef46acf0444106c6 | C++ | vstuhumanoid/robot-controller-ros | /src/AR60x_driver/PowerController/PowerController.cpp | UTF-8 | 2,401 | 2.671875 | 3 | [] | no_license | //
// Created by garrus on 23.03.18.
//
#include "PowerController.h"
PowerController::PowerController(AR60xHWDriver &driver, ros::NodeHandle &nh) : BaseController(driver, nh)
{
init_topics();
}
PowerController::PowerController(AR60xHWDriver& driver, ros::NodeHandle& nh, double publishingFrequency) :
BaseController(driver, nh, publishingFrequency)
{
init_topics();
}
void PowerController::init_topics()
{
robot_supply_state_publisher_ = nh_.advertise<RobotSupplyState>(namespace_ + "/sources_state", 100);
joints_supply_state_publiser_ = nh_.advertise<JointsSupplyState>(namespace_ + "/joints_state", 100);
power_commands_subscriber_ = nh_.subscribe<std_msgs::Bool>(namespace_ + "/command", 100, &PowerController::robot_supply_command_cb, this);
}
std::string PowerController::controller_name()
{
return "PowerController";
}
void PowerController::loop()
{
robot_supply_state_publisher_.publish(driver_.PowerGetSourcesSupplyState());
joints_supply_state_publiser_.publish(driver_.PowerGetJointsSupplyState());
}
void PowerController::robot_supply_command_cb(std_msgs::Bool msg)
{
if(msg.data)
PowerOn();
else
PowerOff();
}
void PowerController::PowerOn()
{
ROS_INFO("Power on command received. Powering on robot...");
driver_.SupplySetOnOff(PowerSources::Supply48V, true);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply8V1, true);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply8V2, true);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply6V1, true);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply6V2, true);
ros::Duration(0.5).sleep();
ROS_INFO("Power on commands sent");
}
void PowerController::PowerOff()
{
ROS_INFO("Power off command received. Powering off robot...");
driver_.SupplySetOnOff(PowerSources::Supply6V1, false);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply6V2, false);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply8V1, false);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply8V2, false);
ros::Duration(0.5).sleep();
driver_.SupplySetOnOff(PowerSources::Supply48V, false);
ros::Duration(0.5).sleep();
ROS_INFO("Power off commands sent");
}
| true |
fde3144949ceb596ce20ec347b4d185202962bf4 | C++ | IUniner/Asm | /debug/LAB7/LAB7.Win32_API/S1/kmpex.cpp | UTF-8 | 756 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
vector<int> kmp(const string& s) {
vector<int> pi(s.size());
for (int i = 1; i < s.size(); i++) {
int j = pi[i - 1];
while (j > 0 && s[j] != s[i])
j = pi[j - 1];
if (s[j] == s[i])
j++;
pi[i] = j;
}
return pi;
}
int main()
{
int size = -1;
string message = "NO";
string s= "acaacaaca cacacacaacaacaacaxacac"; //000100000000001234000
//char chs[100];
//cin >> s;
vector<int> str = kmp(s);
for (int i = 0; i < s.size(); ++i)
{
if (s[i] == ' ')
size = i;
if (str[i] == size)
message = "YES";
}
for (int i = 0; i < s.size(); i++)
cout << str[i];
cout<< endl;
for(int i =0; i < message.size();++i)
cout << message[i];
system("pause");
} | true |
4510fae12da456df264d5f32ba6315b538541906 | C++ | iamslash/learntocode | /leetcode/PartitiontoKEqualSumSubsets/InsertintoaBinarySearchTree/a.cpp | UTF-8 | 838 | 3.453125 | 3 | [] | no_license | /* Copyright (C) 2019 by iamslash */
#include <cstdio>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
TreeNode(int x, TreeNode* l, TreeNode* r) :
val(x), left(l), right(r) {}
};
// 96ms 99.75% 33.2MB 25.35%
// O(lgN) O(1)
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
// base
if (root == NULL)
return new TreeNode(val);
// recursion
if (root->val > val)
root->left = insertIntoBST(root->left, val);
else
root->right = insertIntoBST(root->right, val);
return root;
}
};
int main() {
int val = 5;
TreeNode* root = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)), new TreeNode(7));
Solution sln;
root = sln.insertIntoBST(root, val);
return 0;
}
| true |
4c7735735b50ba0e518bcd4463b6e38cb5a1543e | C++ | erickveil/Qt-GUI-socket-server | /threadmonitor.cpp | UTF-8 | 543 | 2.578125 | 3 | [] | no_license | #include "threadmonitor.h"
ThreadMonitor::ThreadMonitor(QThread* watch){
watch_thread=watch;
startLoop();
}
void ThreadMonitor::startLoop()
{
QTimer *mon_loop=new QTimer(this);
connect(mon_loop, SIGNAL(timeout()), this, SLOT(eventListenerStateMonitor()));
mon_loop->start(1000);
}
void ThreadMonitor::eventListenerStateMonitor()
{
bool current_state=watch_thread->isRunning();
if(current_state==last_state){
return;
}
last_state=current_state;
emit threadStateChanged(current_state);
}
| true |
8a6371ce7dadd7aaf46456c432b0ea790cd1c98c | C++ | LenihanConor/Cluiche | /Dia/DiaCore/Containers/Misc/CircularBufferIterator.inl | UTF-8 | 5,345 | 3.140625 | 3 | [] | no_license | namespace Dia
{
namespace Core
{
namespace Containers
{
//------------------------------------------------------------------------------------
// CircularBufferIterator - Implementation
//------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template <class T> inline
CircularBufferIterator<T>::CircularBufferIterator(T* start, const T* begin, const T* end)
: mBegin(begin)
, mEnd(end)
, mIter(start)
{
DIA_ASSERT(begin, "Empty array");
DIA_ASSERT(end, "Empty array");
DIA_ASSERT(start, "Empty array");
DIA_ASSERT(start >= begin && start <= end, "Start must between begin and end");
}
//-----------------------------------------------------------------------------
template <class T> inline
const T* CircularBufferIterator<T>::Begin()const
{
return mBegin;
}
//-----------------------------------------------------------------------------
template <class T> inline
const T* CircularBufferIterator<T>::End()const
{
return mEnd;
}
//-----------------------------------------------------------------------------
template <class T> inline
void CircularBufferIterator<T>::Next()
{
mIter++;
}
//-----------------------------------------------------------------------------
template <class T> inline
void CircularBufferIterator<T>::Previous()
{
--mIter;
}
//-----------------------------------------------------------------------------
template <class T> inline
bool CircularBufferIterator<T>::IsDone() const
{
return (mIter < mBegin || mIter > mEnd);
}
//-----------------------------------------------------------------------------
template <class T> inline
T* CircularBufferIterator<T>::Current()
{
DIA_ASSERT(mIter >= mBegin && mIter <= mEnd, "Current iterator out of bounds");
return mIter;
}
//-----------------------------------------------------------------------------
template <class T> inline
const T* CircularBufferIterator<T>::Current() const
{
DIA_ASSERT(mIter >= mBegin && mIter <= mEnd, "Current iterator out of bounds");
return mIter;
}
//-----------------------------------------------------------------------------
template <class T> inline
bool CircularBufferIterator<T>::operator==(const CircularBufferIterator<T>& other) const
{
return (mIter == other.mIter);
}
//-----------------------------------------------------------------------------
template <class T> inline
bool CircularBufferIterator<T>::operator!=(const CircularBufferIterator<T>& other) const
{
return (mIter != other.mIter);
}
//------------------------------------------------------------------------------------
// CircularBufferConstIterator - Implementation
//------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template <class T> inline
CircularBufferConstIterator<T>::CircularBufferConstIterator(const T* start, const T* begin, const T* end)
: mBegin(begin)
, mEnd(end)
, mIter(start)
{
DIA_ASSERT(begin, "Empty array");
DIA_ASSERT(end, "Empty array");
DIA_ASSERT(start, "Empty array");
DIA_ASSERT(begin <= end, "Start must be less then or equal to beginning");
DIA_ASSERT(start >= begin && start <= end, "Start must between begin and end");
}
//-----------------------------------------------------------------------------
template <class T> inline
const T* CircularBufferConstIterator<T>::Begin()const
{
return mBegin;
}
//-----------------------------------------------------------------------------
template <class T> inline
const T* CircularBufferConstIterator<T>::End()const
{
return mEnd;
}
//-----------------------------------------------------------------------------
template <class T> inline
void CircularBufferConstIterator<T>::Next()
{
if (mIter == mEnd)
{
mIter = mBegin;
}
else
{
mIter++;
}
}
//-----------------------------------------------------------------------------
template <class T> inline
void CircularBufferConstIterator<T>::Previous()
{
if (mIter == mBegin)
{
mIter = mEnd;
}
else
{
--mIter;
}
}
//-----------------------------------------------------------------------------
template <class T> inline
const T* CircularBufferConstIterator<T>::Current() const
{
DIA_ASSERT(mIter >= mBegin && mIter <= mEnd, "Current iterator out of bounds");
return mIter;
}
//-----------------------------------------------------------------------------
template <class T> inline
bool CircularBufferConstIterator<T>::operator==(const CircularBufferConstIterator<T>& other) const
{
return (mIter == other.mIter);
}
//-----------------------------------------------------------------------------
template <class T> inline
bool CircularBufferConstIterator<T>::operator!=(const CircularBufferConstIterator<T>& other) const
{
return (mIter != other.mIter);
}
}
}
} | true |
946292e9b41e44c6a802b13f1a5c09c3173249db | C++ | song493818557/mfc | /C语言基础/算法 A-star/基础班_16_数据结构(A-Start算法)/AStar.h | GB18030 | 1,744 | 3.015625 | 3 | [] | no_license | #pragma once
#include <windows.h>
#include <vector>
using std::vector;
class AStar
{
//Ҫֵ
typedef struct _NODE
{
int G; // ƶ
int H; // Ŀĵصľ
int F; // GH֮
COORD stcThis; // ڵĵǰλ
_NODE* pFront; // ڵһڵָ
bool operator==(_NODE stcNode);
void operator=(_NODE stcNode);
}NODE, *PNODE;
public:
AStar();
~AStar();
//Ҫı
vector<PNODE> m_vecOpen; //Open //̽ĵ
vector<PNODE> m_vecClose; //Close//̽ĵ
//ҪõϢ
NODE m_stcStart; // Ѱ·ʼ
NODE m_stcEnd; // Ѱ·Ŀ
int m_nMaxX; // Ѱ·
int m_nMaxY; // Ѱ·߶
PBYTE m_pSpace; // A*Ѱ·ͼռ
void SetSpace( /**A*Ѱ·ͼռ**************/
int nWidth, //[in] Ѱ·
int nHigh, //[in] Ѱ·߶
PBYTE pSpace //[in] A*Ѱ·ͼռ
);
void SetStartAndEnd( /**A*Ѱ·ʼĿ*******/
COORD stcBegin, //[in] ʼ
COORD stcEnd //[in] Ŀ
);
void GetPath( /**ȡA*Ѱ·*******************/
vector<COORD> & vecPos //[out]·꼯
);
private:
bool GetPathNode( /**ȡA*Ѱ·*******************/
vector<PNODE> & vecPos //[out]·ڵ㼯
);
};
| true |
c995abd1367dcc483d717fede17ff49276f87e0f | C++ | fahim-ahmed-7861/competitive-programming | /greedy.Activity selection.cpp | UTF-8 | 998 | 2.828125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef struct
{
int activity;
int start;
int end;
}one;
int main()
{
one std[100],temp;
int i,n,j,c=1;
cin>>n;
for(i=0; i<n; i++)
{
cin>>std[i].activity>>std[i].start>>std[i].end;
}
cout<<endl<<endl;
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(std[i].end>std[j].end)
{
temp=std[i];
std[i]=std[j];
std[j]=temp;
}
}
}
cout<<endl<<endl;
for(i=0; i<n; i++)
{
cout<<std[i].activity<<" "<<std[i].start<<" "<<std[i].end<<endl;
}
int ara[n+5];
int p=0;
cout<<std[0].activity<<" "<<std[0].start<<" "<<std[0].end<<endl;
for(i=1; i<n; i++)
{
if(std[p].end<=std[i].start)
{
c++;
p=i;
cout<<std[p].activity<<" "<<std[p].start<<" "<<std[p].end<<endl;
}
}
cout<<endl<<c<<endl;
}
| true |
8129b5c27828ecfdc46f90ecf3dae84f77516db3 | C++ | raghvendra1218/Data-Structures-and-Algorithm-Analysis | /Search a Linked List Using Recursion/LLIST.cpp | UTF-8 | 1,384 | 3.5625 | 4 | [] | no_license | /*
LLIST.cpp
21-Feb-2018
Raghvendra
*/
#include "../DSArchive/Search a Linked List Using Recursion/LLIST.h"
#include <iostream>
using namespace std;
List::List() {
head = nullptr;
curr = nullptr;
temp = nullptr;
}
void List::addNode(int addData){
nodePtr n = new node;
n->data = addData;
n->next = nullptr;
if(head != nullptr) {
curr = head;
while(curr->next != nullptr) {
curr = curr->next;
}
curr->next = n;
n->next = nullptr;
} else {
head = n;
}
}
void List::searchRecursive(nodePtr n, int value){
// n = head; -- Don't make this blunder of initializing inside of the function,
// though recursive calls does not seems like to be going in loop (because of missing
// loops statements, but they do, because of it's in-call function from inside,
// every time head will initialized to head, by un-commenting this line.
if(n == nullptr){
cout<<value<<" is not found in the List"<<endl;
return;
}
else if(n->data == value){
cout<<value<< " is present in the List"<<endl;
}
else {
searchRecursive(n->next, value);
}
}
void List::search(int value){
searchRecursive(head,value);
}
void List::printNode() {
if(head!=nullptr) {
curr = head;
while(curr != nullptr){
cout<<curr->data<<endl;
curr = curr->next;
}
cout<<"*********************"<<endl;
} else {
cout<<"List is empty!"<<endl;
cout<<"*********************"<<endl;
}
}
| true |
77ab2c08961ad2b4cd9c1888e1bd13df4d39d880 | C++ | greyhillman/cppLearning | /globalVariables/main.cpp | UTF-8 | 413 | 3.09375 | 3 | [] | no_license | #include "main.h"
int x = 10; // global variable
// global varabiesl have global/file scope
// global variables have static durataion
// which means they are created when the program starts
// and are destroyed when the program ends
int func() {
int x = 4;
std::cout << x << std::endl; // local x
std::cout << ::x << std::endl; // global x
// :: is the global namespace operator
}
int main() {
func();
}
| true |
80678adb80262fc0f0914690f1ec5b22f3406946 | C++ | rayzandbergen/patcher | /src/networkif.cpp | UTF-8 | 1,874 | 3.203125 | 3 | [] | no_license | /*! \file networkif.cpp
* \brief Contains a function to obtain network interface addresses.
*
* Copyright 2013 Raymond Zandbergen (ray.zandbergen@gmail.com)
*/
#include "networkif.h"
#include <stdio.h>
#include <iostream>
#include <sstream>
/*! \brief This function runs "ifconfig" and parses the output to show only network interfaces and their addresses
*/
std::string getNetworkInterfaceAddresses()
{
/* use C-style streams for the pipe, then parse the
output line by line using C++ std::strings */
FILE *fp = popen("/sbin/ifconfig", "r");
if (!fp)
{
return std::string("could not run ifconfig *** ");
}
char lineBuffer[100];
std::string interface;
std::string address;
size_t nofInterfaces = 0;
std::ostringstream deviceString;
while (!feof(fp))
{
if (!fgets(lineBuffer, sizeof(lineBuffer), fp))
break;
std::string line(lineBuffer);
/* if the line does not start with whitespace,
then it is an interface name */
size_t ifLen = line.find_first_of(" \t\n");
if (ifLen != 0)
{
interface = line.substr(0, ifLen);
}
/* if this is an address line that does not belong to "lo"
then parse the address */
size_t addrOffset = line.find("inet addr:");
if (addrOffset != line.npos && interface.compare("lo"))
{
nofInterfaces++;
size_t addrBegin =
line.find_first_of("0123456789", addrOffset);
size_t addrEnd =
line.find_first_not_of("0123456789.", addrBegin);
address = line.substr(addrBegin, addrEnd-addrBegin);
deviceString << interface << ": " << address << " *** ";
}
}
pclose(fp);
return nofInterfaces > 0 ?
deviceString.str()
: std::string("no network *** ");
}
| true |
689638a547a3ee17ebf574254949915745dc4b4b | C++ | dunkean/TerrainGenerator | /richdem/richdem.cpp | UTF-8 | 1,024 | 2.59375 | 3 | [] | no_license | #include <richdem/common/logger.hpp>
#include <map>
#include <string>
namespace richdem {
//TODO: Could use vector for this since the enum just compiles to an int. But
//need to make sure things are in the right order.
std::map<LogFlag, std::string> log_flag_chars_begin = {
{ALG_NAME, "\nA"},
{CITATION, "C"},
{CONFIG, "c"},
{DEBUG, "\033[95md"},
{ERROR, "E"},
{MEM_USE, " "},
{MISC, "m"},
{PROGRESS, "p"},
{TIME_USE, "t"},
{WARN, "\033[91mW"}
};
std::map<LogFlag, std::string> log_flag_chars_end = {
{ALG_NAME, ""},
{CITATION, "\n"},
{CONFIG, ""},
{DEBUG, ""},
{ERROR, ""},
{MEM_USE, ""},
{MISC, ""},
{PROGRESS, ""},
{TIME_USE, ""},
{WARN, ""}
};
void RDLOGfunc(LogFlag flag, const char* file, const char* func, unsigned line, std::string msg) {
std::cerr<<log_flag_chars_begin.at(flag)<<" "<<msg
#ifdef RICHDEM_DEBUG
<<" ("<<file<<" : "<<func<<" : "<<line<<")"
#endif
<<"\033[39m"
<<log_flag_chars_end.at(flag)
<<std::endl;
}
} | true |
1f29755cd877f974c340ebd31c0e6460f4201fd6 | C++ | mlz000/Algorithms | /codeforces/Codeforces Round #221 (Div. 2)/A.cpp | UTF-8 | 517 | 2.609375 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1000005;
char s[N];
int main(){
scanf("%s",s);
int l=strlen(s);
int pos;
long long le=0ll,ri=0ll;
for(int i=0;i<l;++i) if(s[i]=='^') {pos=i;break;}
for(int i=0;i<pos;++i) if(s[i]>='1' && s[i]<='9') le+=(s[i]-'0')*(pos-i);
for(int i=pos+1;i<l;++i) if(s[i]>='1' && s[i]<='9') ri+=(s[i]-'0')*(i-pos);
if(le==ri) printf("balance\n");
else if(le>ri) printf("left\n");
else printf("right\n");
return 0;
}
| true |
781ba2cfcca54cf4af5f7465cdab9db4bb8b2b93 | C++ | edwinandradeospino/CplusConsoleQt | /Source/Adresse.cpp | UTF-8 | 4,162 | 3.34375 | 3 | [] | no_license | /*
* Adresse.cpp
** \brief Implantation de la classe Adresse
* balises Doxygen
* Created on: 2017-11-20
* Author: Edwin Andrade Ospino
*/
#include"Adresse.h"
#include<iostream>
#include<sstream>
#include"ContratException.h"
using namespace std;
namespace util {
/**
* \brief constructeur avec paramètres
* On construit un objet Date à partir de valeurs passées en paramètres.
* Les attributs sont assignés seulement si la date est considérée comme valide.
* Autrement, une erreur d'assertion est générée.
* \param[in] p_jour est un entier long qui représente le jour de la date
* \param[in] p_mois est un entier long qui représente le mois de la date
* \param[in] p_annee est un entier long qui représente l'année de la date
* \pre p_jour, p_mois, p_annee doivent correspondre à une date valide
* \post l'objet construit a été initialisé à partir des entiers passés en paramètres
*/
Adresse::Adresse(const int& p_numeroDeLaRue,
const std::string& p_nomDeLaRue,
const std::string& p_ville,
const std::string& p_codePostal,
const std::string& p_province)
: m_numeroDeLaRue(p_numeroDeLaRue),m_nomDeLaRue(p_nomDeLaRue),m_ville(p_ville),
m_codePostal(p_codePostal),m_province(p_province)
{
PRECONDITION(p_numeroDeLaRue >= 0);
PRECONDITION(!p_nomDeLaRue.empty());
PRECONDITION(!p_ville.empty());
PRECONDITION(!p_codePostal.empty());
PRECONDITION(!p_province.empty());
POSTCONDITION(m_numeroDeLaRue == p_numeroDeLaRue);
POSTCONDITION(m_nomDeLaRue == p_nomDeLaRue);
POSTCONDITION(m_ville == p_ville);
POSTCONDITION(m_codePostal == p_codePostal);
POSTCONDITION(m_province == p_province);
INVARIANTS();
}
/**
* \brief retourne le numero civique.
* \return un entier qui représente le numero civique.
*/
int Adresse::reqNumeroDeLaRue() const {
return m_numeroDeLaRue;
}
/**
* \brief retourne le nom de la rue
* \return une chaîne de caracères (string) qui représente le nom de la rue.
*/
std::string Adresse::reqNomDeLaRue() const {
return m_nomDeLaRue;
}
/**
* \brief retourne le nom de la ville.
* \return une chaîne de caracères (string) qui représente le nom de la ville.
*/
std::string Adresse::reqVille() const {
return m_ville;
}
/**
* \brief retourne le code postal
* \return une chaîne de caracères (string) qui représente le code postal.
*/
std::string Adresse::reqCodePostal() const {
return m_codePostal;
}
/**
* \brief retourne le nom de la Province.
* \return une chaîne de caracères (string) qui représente le nom de la province.
*/
std::string Adresse::reqProvince() const {
return m_province;
}
/**
* \brief Assigne une nouvelle adresse à l'objet courrant
*/
void Adresse::asgNouvelleAdresse(util::Adresse& p_nouvelleAdresse) {
p_nouvelleAdresse = (*this);
}
/**
* \brief surcharge de l'opérateur ==
* \param[in] p_date à comparer à la date courante
* \return un booléen indiquant si les deux dates sont égales ou non
*/
bool Adresse::operator ==(const Adresse& p_outreAdresse){
return (m_numeroDeLaRue == p_outreAdresse.reqNumeroDeLaRue() &&
m_nomDeLaRue == p_outreAdresse.reqNomDeLaRue() &&
m_ville == p_outreAdresse.reqVille() &&
m_codePostal == p_outreAdresse.reqCodePostal() &&
m_province == p_outreAdresse.reqProvince());
}
/**
* \brief retourne une date formatée dans une chaîne de caracères (string)
* \return lformatée dans une chaîne de caractères
*/
std::string Adresse::reqChaineFormatee() const{
ostringstream os;
os << m_numeroDeLaRue << " , " << m_nomDeLaRue << " , "
<< m_ville << " , " << m_codePostal << " , " << m_province;
return os.str();
}
/**
* \brief surcharge de l'opérateur ==
* \param[in] p_adresse à comparer à l'adresse courante
* \return un booléen indiquant si les deux adresses sont égaux ou non.
*/
std::ostream& operator<<(std::ostream& p_os, const Adresse& p_adresse) {
p_os << p_adresse.m_numeroDeLaRue;
p_os << p_adresse.m_nomDeLaRue;
p_os << p_adresse.m_ville;
p_os << p_adresse.m_codePostal;
p_os << p_adresse.m_province;
return p_os;
}
void Adresse::verifieInvariant() const {
INVARIANT(m_numeroDeLaRue > 0);
}
}// fin du namespace
| true |
f0b54363987f684f6d10dcdf1418a4dba836b435 | C++ | xijiang/ABG.jl | /cpp/raw2gt.cpp | UTF-8 | 1,078 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cctype>
#include <vector>
/**
* Remove the header line.
* Remove the first 6 columns of a plink.raw file.
* Remove all the spaces between the genotypes.
* Write genotypes to stdout
* Calculate the allele frequencies into argv[1].
*/
using namespace std;
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(false);
if(argc !=2){
cerr << "Usage: cat plink.raw | "<<argv[0]<<" freq.txt >genotypes"<<endl;
return 1;
}
string line, t;
int nlc{-6}, div{0};
getline(cin, line);
{
stringstream ss(line);
string t;
while(ss>>t) ++nlc;
}
double frq[nlc]{0.};
while(getline(cin, line)){
stringstream ss(line);
for(auto i{0}; i<6; ++i) ss>>t;
getline(ss, line);
line.erase(remove_if(line.begin(), line.end(), ::isspace), line.end());
cout<<line<<'\n';
for(auto i=0; i<nlc; ++i) frq[i] += line[i] - '0';
div += 2;
}
ofstream foo(argv[1]);
foo.precision(17);
for(auto&x:frq) foo<<x/div<<'\n';
return 0;
}
| true |
70a6b0179dd10a5e037ffaaae14f9cca1e0eae0e | C++ | LuckiiGoggy/OpenGL-Game | /Project/OpenGL-Game/Rect.cpp | UTF-8 | 2,630 | 2.828125 | 3 | [] | no_license |
#include "Rect.h"
Rect::Rect()
{
sx = 0;
sy = 0;
ex = 0;
ey = 0;
r = 1.0f;
g = 0.0f;
b = 0.0f;
color = glm::vec3(r, g, b);
id = -1;
Bbox = BoundingBox(glm::vec3(sx, sy, 1), glm::vec3(sx, ey, 1), glm::vec3(ex, ey, 1), glm::vec3(ex, ey, 1),
glm::vec3(sx, sy, 2), glm::vec3(sx, ey, 2), glm::vec3(ex, ey, 2), glm::vec3(ex, ey, 2));
}
Rect::Rect(int xs, int ys, int xe, int ye)
{
sx = xs;
sy = ys;
ex = xe;
ey = ye;
r = 1.0f;
g = 0.0f;
b = 0.0f;
color = glm::vec3(r, g, b);
id = -1;
/*char *intStr = new char;
_itoa_s(id, intStr, 1, 10);
id_c = (const unsigned char *)intStr;//*/
Bbox = BoundingBox(glm::vec3(sx, sy, 1), glm::vec3(sx, ey, 1), glm::vec3(ex, ey, 1), glm::vec3(ex, ey, 1),
glm::vec3(sx, sy, 2), glm::vec3(sx, ey, 2), glm::vec3(ex, ey, 2), glm::vec3(ex, ey, 2));
}
Rect::Rect(int xs, int ys, int xe, int ye, glm::vec3 c)
{
sx = xs;
sy = ys;
ex = xe;
ey = ye;
r = c.x;
g = c.y;
b = c.z;
color = c;
id = -1;
/*char *intStr = new char;
_itoa_s(id, intStr, 1, 10);
id_c = (const unsigned char *)intStr;//*/
Bbox = BoundingBox(glm::vec3(sx, sy, 1), glm::vec3(sx, ey, 1), glm::vec3(ex, ey, 1), glm::vec3(ex, ey, 1),
glm::vec3(sx, sy, 2), glm::vec3(sx, ey, 2), glm::vec3(ex, ey, 2), glm::vec3(ex, ey, 2));
}
Rect::Rect(int xs, int ys, int xe, int ye, glm::vec3 c, int id_)
{
sx = xs;
sy = ys;
ex = xe;
ey = ye;
r = c.x;
g = c.y;
b = c.z;
color = c;
id = id_;
char *intStr = new char;
_itoa_s(id, intStr, 3, 10);
id_c = (const unsigned char *)intStr;
Bbox = BoundingBox(glm::vec3(sx, sy, 1), glm::vec3(sx, ey, 1), glm::vec3(ex, ey, 1), glm::vec3(ex, ey, 1),
glm::vec3(sx, sy, 4), glm::vec3(sx, ey, 4), glm::vec3(ex, ey, 4), glm::vec3(ex, ey, 4));
}
Rect::Rect(int xs, int ys, int xe, int ye, float r_, float g_, float b_, int id_)
{
sx = xs;
sy = ys;
ex = xe;
ey = ye;
r = r_;
g = g_;
b = b_;
color = glm::vec3(r, g, b);
id = id_;
char *intStr = new char;
_itoa_s(id, intStr, 3, 10);
id_c = (const unsigned char *)intStr;
Bbox = BoundingBox(glm::vec3(sx, sy, 1), glm::vec3(sx, ey, 1), glm::vec3(ex, ey, 1), glm::vec3(ex, ey, 1),
glm::vec3(sx, sy, 4), glm::vec3(sx, ey, 4), glm::vec3(ex, ey, 4), glm::vec3(ex, ey, 4));
}
void Rect::move(int x, int y)
{
sx += x;
sy += y;
ex += x;
ey += y;
Bbox.translate(x, y, 0);
}
void Rect::setColor(float r_, float g_, float b_)
{
r = r_;
g = g_;
b = b_;
color = glm::vec3(r, g, b);
}
void Rect::setColor(glm::vec3 c)
{
r = c.x;
g = c.y;
b = c.z;
color = c;
}
int Rect::getWidth()
{
int w = (ex - sx);
return abs(w);
}
int Rect::getHeight()
{
int h = (ey - sy);
return abs(h);
}
| true |
64fc1089918b2517dea42b7aa19c71d46874ff7a | C++ | reginabezhanyan/study_tasks_contests | /2kurs/IV sem/2k/regina_complex.h | UTF-8 | 2,811 | 3.390625 | 3 | [] | no_license | #ifndef __COMPLEX_H
#define __COMPLEX_H
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <cmath>
namespace numbers {
class complex
{
double re_, im_;
public:
complex(double _re_ = 0, double _im_ = 0) : re_(_re_), im_(_im_) {}
explicit complex(const std::string & s)
{
std::stringstream ss(s);
ss.ignore(s.length(), '(');
ss >> re_;
ss.ignore(s.length(), ',');
ss >> im_;
};
double re() const { return re_; }
double im() const { return im_; }
double abs2() const
{
return re_ * re_ + im_ * im_;
}
double abs() const
{
return sqrt(abs2());
}
std::string to_string() const
{
std::stringstream ss;
ss << "(" << std::setprecision(10) << re_ << "," << im_ << ")";
return ss.str();
}
const complex& operator += (const complex &v)
{
re_ += v.re_;
im_ += v.im_;
return *this;
}
const complex& operator -= (const complex &v)
{
re_ -= v.re_;
im_ -= v.im_;
return *this;
}
const complex& operator *= (const complex &v)
{
double re_tmp = re_ * v.re_ - im_ * v.im_;
double im_tmp = im_ * v.re_ + re_ * v.im_;
re_ = re_tmp;
im_ = im_tmp;
return *this;
}
const complex& operator /= (const complex &v)
{
double re_tmp = (re_ * v.re_ + im_ * v.im_) / (v.re_ * v.re_ + v.im_ * v.im_);
double im_tmp = (im_ * v.re_ - re_ * v.im_) / (v.re_ * v.re_ + v.im_ * v.im_);
re_ = re_tmp;
im_ = im_tmp;
return *this;
}
complex operator ~() const
{
complex tmp(re_, -im_);
return tmp;
}
complex operator -() const
{
complex tmp(-re_, -im_);
return tmp;
}
};
complex operator +(const complex &v1, const complex &v2)
{
complex tmp(v1);
tmp += v2;
return tmp;
}
complex operator -(const complex &v1, const complex &v2)
{
complex tmp(v1);
tmp -= v2;
return tmp;
}
complex operator *(const complex &v1, const complex &v2)
{
complex tmp(v1);
tmp *= v2;
return tmp;
}
complex operator /(const complex &v1, const complex &v2)
{
complex tmp(v1);
tmp /= v2;
return tmp;
}
}
#endif /* __COMPLEX_H */
| true |
72956bc8f84aa800d7fabf0abb761b7d581bddb5 | C++ | polyakovkrylo/killemall | /src/graphicsview/worldgraphicsview.cpp | UTF-8 | 5,103 | 2.65625 | 3 | [] | no_license | /*!
* \file worldgraphicsview.cpp
*
* WorldGraphicsView class definition
*
* \version 1.0
*
* \author Vladimir Poliakov
* \author Brian Segers
* \author Kasper De Volder
*/
#include "worldgraphicsview.h"
WorldGraphicsView::WorldGraphicsView(QWidget *parent) :
QGraphicsView(parent), model_{nullptr}, scene_{nullptr}
{
healthBar_ = new QProgressBar(this);
energyBar_ = new QProgressBar(this);
QLabel *lh = new QLabel("Health", this);
QLabel *le = new QLabel("Energy", this);
healthBar_->setStyleSheet("QProgressBar::chunk{background-color:green;}");
energyBar_->setStyleSheet("QProgressBar::chunk{background-color:yellow;}");
healthBar_->setTextVisible(false);
energyBar_->setTextVisible(false);
lh->setAlignment(Qt::AlignCenter);
le->setAlignment(Qt::AlignCenter);
healthBar_->setGeometry(10,10,100,20);
energyBar_->setGeometry(10,40,100,20);
lh->setGeometry(healthBar_->geometry());
le->setGeometry(energyBar_->geometry());
}
void WorldGraphicsView::setModel(WorldModel *model)
{
// disconnect all slots from the previous model
if(model_) {
disconnect(model_, SIGNAL(reload()),this, SLOT(reloadScene()));
disconnect(model_->getProtagonist().get(), SIGNAL(posChanged(int,int)), this, SLOT(onProtagonistPositionChanged(int,int)));
disconnect(model_->getProtagonist().get(),SIGNAL(healthLevelChanged(int)),healthBar_,SLOT(setValue(int)));
disconnect(model_->getProtagonist().get(),SIGNAL(energyLevelChanged(int)),energyBar_,SLOT(setValue(int)));
}
model_ = model;
if(model_->ready())
reloadScene();
// connect new model reload signal
connect(model_, SIGNAL(reload()),this, SLOT(reloadScene()));
}
void WorldGraphicsView::keyPressEvent(QKeyEvent *e)
{
int x = model_->getProtagonist()->getXPos();
int y = model_->getProtagonist()->getYPos();
switch(e->key()) {
case Qt::Key_Up:
model_->move(x,--y);
break;
case Qt::Key_Down:
model_->move(x,++y);
break;
case Qt::Key_Right:
model_->move(++x,y);
break;
case Qt::Key_Left:
model_->move(--x,y);
break;
}
}
void WorldGraphicsView::mousePressEvent(QMouseEvent *e)
{
if(e->button() == Qt::LeftButton){
model_->move(mapToScene(e->pos()).toPoint());
}
}
void WorldGraphicsView::mouseMoveEvent(QMouseEvent *e)
{
mousePressEvent(e);
}
void WorldGraphicsView::onProtagonistPositionChanged(int x, int y)
{
//move protagonist and center view
protagonist_->setPos(x,y);
ensureVisible(protagonist_, 100, 100);
}
void WorldGraphicsView::reloadScene()
{
// reset scene
if(scene_ != nullptr)
scene_->deleteLater();
// create scene and draw background
QImage back(model_->getLevel());
scene_ = new WorldGraphicsScene(back, QRectF(0,0,back.width(),back.height()),this);
scene_->setBackgroundBrush(back);
// draw enemies and connect them to lambda slot
for(auto &e: model_->getEnemies()) {
QGraphicsEllipseItem *eIt = scene_->addEllipse(e->area(),QPen(),QBrush(Qt::red));
connect(e.get(), &UEnemy::dead, [=]() {
// mark enemy as defeated
eIt->setBrush(Qt::gray);
} );
}
// draw enemies and connect them to lambda slot for dead poisonLevelChanged slots
for(auto &pe: model_->getPEnemies()) {
QGraphicsEllipseItem *peIt = scene_->addEllipse(pe->area(),QPen(),QBrush(Qt::red));
connect(pe.get(), &UPEnemy::dead, [=]() {
// mark enemy as defeated
peIt->setBrush(Qt::gray);
} );
// draw poison area
QGraphicsEllipseItem *pIt = scene_->addEllipse(pe->poisonArea(),
QPen(Qt::transparent),QBrush());
connect(pe.get(), &UPEnemy::poisonLevelUpdated, [=](int value) {
// Set alpha channel as doubled poison level
pIt->setBrush(QColor(230,230,0,value*2));
} );
}
//draw health packs with the center at tile's x and y
for(auto &p: model_->getHealthpacks()) {
QGraphicsEllipseItem *it = scene_->addEllipse(p->area(), QPen(), QBrush(Qt::green));
connect(p.get(), &UHealthPack::used, [=]() {
// Delete used health pack
scene_->removeItem(it);
} );
}
//draw protagonist with the center at tile's x and y
auto &p = model_->getProtagonist();
protagonist_ = scene_->addEllipse(p->area(), QPen(), QBrush(Qt::blue));
protagonist_->setPos(p->getXPos(), p->getYPos());
healthBar_->setValue(p->getHealth());
energyBar_->setValue(p->getEnergy());
connect(p.get(), SIGNAL(posChanged(int,int)), this, SLOT(onProtagonistPositionChanged(int,int)));
connect(p.get(),SIGNAL(healthLevelChanged(int)),healthBar_,SLOT(setValue(int)));
connect(p.get(),SIGNAL(energyLevelChanged(int)),energyBar_,SLOT(setValue(int)));
setScene(scene_);
centerOn(protagonist_);
}
void WorldGraphicsView::enlarge()
{
scale(1.25f, 1.25f);
}
void WorldGraphicsView::shrink()
{
scale(0.8f, 0.8f);
}
| true |
f9891e7c5decac442a5287b838f6a872bf6f72e9 | C++ | coolcodehere/project4 | /src/DirectedWeightedGraph.h | UTF-8 | 842 | 2.84375 | 3 | [] | no_license | #ifndef DIRECTED_WEIGHTED_GRAPH_H_
#define DIRECTED_WEIGHTED_GRAPH_H_
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class DirectedWeightedGraph {
private:
vector<vector<int>> *adjacencyMatrix;
map<string, int> *nodeNameToIndex;
void addNode(string nodeName);
void addEdge(string edgeData);
void buildGraph(vector<string> *graphData);
public:
DirectedWeightedGraph();
DirectedWeightedGraph(string graphDataFilename);
~DirectedWeightedGraph();
DirectedWeightedGraph(const DirectedWeightedGraph &other);
DirectedWeightedGraph operator=(const DirectedWeightedGraph &other);
pair<int, int>* size();
void ReadGraph(string graphDataFilename);
void TopologicalSort();
void ShortestPath(string nodeName);
void MinimumSpanningTree(string startNode);
};
#endif | true |
d830594a5de3f08c7201672056cc08880d35082f | C++ | dotnet/docs | /docs/standard/exceptions/snippets/how-to-use-the-try-catch-block-to-catch-exceptions/cpp/catchexception.cpp | UTF-8 | 509 | 2.9375 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | //<snippet3>
using namespace System;
using namespace System::IO;
public ref class ProcessFile
{
public:
static void Main()
{
try
{
StreamReader^ sr = File::OpenText("data.txt");
Console::WriteLine("The first line of this file is {0}", sr->ReadLine());
sr->Close();
}
catch (Exception^ e)
{
Console::WriteLine("An error occurred: '{0}'", e);
}
}
};
int main()
{
ProcessFile::Main();
}
//</snippet3>
| true |
53de32a2e9b151a9592459dccb5ba8fcf553395c | C++ | ShinriiTin/CodeLibrary | /Heynihao's Standard Code Library/source/zhongzihao/random.cpp | UTF-8 | 1,270 | 3.296875 | 3 | [
"MIT"
] | permissive | // 随机数模板
#include<bits/stdc++.h>
#define ll long long
// 产生一个 [0, n) 的随机数
int randint(int n){
return (rand() << 15 | rand()) % n;
}
// 产生一个 [0, n) 的随机数
ll randll(ll n){
return (1ll * rand() << 45 | 1ll * rand() << 30 | rand() << 15 | rand()) % n;
}
// 产生一个整数部分 digit 位,小数部分 scale 位的实数
double randdb(int digit, int scale){
double ret = 0;
for (int i = 0; i < digit; ++ i){
ret = ret * 10 + randint(10);
}
double now = 0.1;
for (int i = 0; i < scale; ++ i, now /= 10){
ret = ret + randint(10) * now;
}
return ret;
}
// 产生一个小写字母
char randlower(){
return 'a' + randint(26);
}
// 产生一个大写字母
char randupper(){
return 'A' + randint(26);
}
// 产生一个数字字符
char randdigit(){
return '0' + randint(10);
}
// 产生一个字母或数字字符
char randchar(){
int x = randint(3);
switch (x){
case 0 : return randlower();
case 1 : return randupper();
case 2 : return randdigit();
}
}
// 产生一个 digit 位的大整数(直接输出)
void randBigInteger(int digit){
for (int i = 0; i < digit; ++ i){
putchar('0' + (i ? randint(10) : randint(9) + 1));
}
}
int main(){
srand((unsigned) time(NULL));
return 0;
} | true |
4fa1997a7287b13b3c92a3ef2b6a3e9bc9da317a | C++ | Rhyzster/RhyzHomepass | /setup.cpp | UTF-8 | 2,691 | 2.625 | 3 | [] | no_license | #include "setup.h"
namespace Public_RhyzHomepass{
setup::setup()
{
newMac = new changeMac();
macList = new std::vector<std::string>;
}
void setup::startNetwork()
{
DWORD version;
HANDLE clientHandle;
PWLAN_HOSTED_NETWORK_REASON failReason = {};
if(WlanOpenHandle(2, NULL, &version, &clientHandle) == ERROR_SUCCESS){
if(WlanHostedNetworkForceStart(clientHandle, failReason, NULL) == ERROR_SUCCESS){
std::cout << std::endl << SSID << " Network Started" << std::endl;
}else{
std::cout << "Error Starting Network, Error Code: " << failReason << std::endl;
WlanCloseHandle(clientHandle, NULL);
return;
}
}else{
std::cout << "Error Starting Network. (Unable to get Client WLAN Handle)" << std::endl;
return;
}
WlanCloseHandle(clientHandle, NULL);
}
void setup::stopNetwork()
{
DWORD version;
HANDLE clientHandle;
PWLAN_HOSTED_NETWORK_REASON failReason = {};
if(WlanOpenHandle(2, NULL, &version, &clientHandle) == ERROR_SUCCESS){
if(WlanHostedNetworkForceStop(clientHandle, failReason, NULL) == ERROR_SUCCESS){
std::cout << std::endl << SSID << " Network Stopped\n" << std::endl;
}else{
std::cout << "Error Stopping Network, Error Code: " << failReason << std::endl;
WlanCloseHandle(clientHandle, NULL);
return;
}
}else{
std::cout << "Error Stopping Network. (Unable to get Client WLAN Handle)" << std::endl;
return;
}
WlanCloseHandle(clientHandle, NULL);
}
int setup::time(int time)
{
//wanna add file l8r to dynmically update
if(time > 0){
time = time * 60000; //milliseconds to minutes
return time;
}else{
return 130000; //30mins
}
}
int setup::macCount()
{
return macList->size();
}
void setup::clearMacs()
{
macList->clear();
}
void setup::shuffle()
{
//macList->erase(macList->begin()+macCount()-1); //last mac in the txt file gets added twice
for(int i = 0; i < (int) macList->size(); i++){
int index = rand() % (i + 1);
std::string mac = macList->at(index);
macList->at(index) = macList->at(i);
macList->at(i) = mac;
}
}
bool setup::spoofMac(const char * network, int index, std::string networkBuffer)
{
return newMac->setMac(network, macList->at(index).c_str(), networkBuffer.c_str());
}
bool setup::checkMac(std::string AdapterNameBuffer, int index)
{
std::string MAC = macList->at(index);
for (int i = 0; i < 14; i++) {
i = i + 2;
MAC.insert(i, ":");
}
return newMac->checkMac(AdapterNameBuffer.c_str(), MAC.c_str());
}
std::string setup::searchAdapter(const char * AdapterName)
{
return newMac->searchAdapter(AdapterName);
}
} | true |
746f4b99f930c0d4bdc9107d42fd2a746c4eb512 | C++ | Kitware/VTK | /Domains/Chemistry/Testing/Cxx/TestMolecule.cxx | UTF-8 | 3,013 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | // SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause
#include "vtkMolecule.h"
#include "vtkNew.h"
#include "vtkVector.h"
#include "vtkVectorOperators.h"
// Example code from the molecule documentation. If this breaks,
// update the docs in vtkMolecule.h
bool MoleculeExampleCode1()
{
vtkNew<vtkMolecule> mol;
vtkAtom h1 = mol->AppendAtom(1, 0.0, 0.0, -0.5);
vtkAtom h2 = mol->AppendAtom(1, 0.0, 0.0, 0.5);
vtkBond b = mol->AppendBond(h1, h2, 1);
int errors(0);
if (fabs(b.GetLength() - 1.0) > 1e-8)
{
cout << "Error bond length incorrect. Expected 1.0, but got " << b.GetLength() << endl;
++errors;
}
if (!h1.GetPosition().Compare(vtkVector3f(0.0, 0.0, -0.5), 1e-8))
{
cout << "Error atom position incorrect. Expected 0.0, 0.0, -0.5 but got " << h1.GetPosition()
<< endl;
++errors;
}
if (!h2.GetPosition().Compare(vtkVector3f(0.0, 0.0, 0.5), 1e-8))
{
cout << "Error atom position incorrect. Expected 0.0, 0.0, 0.5 but got " << h2.GetPosition()
<< endl;
++errors;
}
if (h1.GetAtomicNumber() != 1)
{
cout << "Error atomic number incorrect. Expected 1 but got " << h1.GetAtomicNumber() << endl;
++errors;
}
if (h2.GetAtomicNumber() != 1)
{
cout << "Error atomic number incorrect. Expected 1 but got " << h2.GetAtomicNumber() << endl;
++errors;
}
return errors == 0;
}
// Example code from the molecule documentation. If this breaks,
// update the docs in vtkMolecule.h
bool MoleculeExampleCode2()
{
vtkNew<vtkMolecule> mol;
vtkAtom h1 = mol->AppendAtom();
h1.SetAtomicNumber(1);
h1.SetPosition(0.0, 0.0, -0.5);
vtkAtom h2 = mol->AppendAtom();
h2.SetAtomicNumber(1);
vtkVector3f displacement(0.0, 0.0, 1.0);
h2.SetPosition(h1.GetPosition() + displacement);
vtkBond b = mol->AppendBond(h1, h2, 1);
int errors(0);
if (fabs(b.GetLength() - 1.0) > 1e-8)
{
cout << "Error bond length incorrect. Expected 1.0, but got " << b.GetLength() << endl;
++errors;
}
if (!h1.GetPosition().Compare(vtkVector3f(0.0, 0.0, -0.5), 1e-8))
{
cout << "Error atom position incorrect. Expected 0.0, 0.0, -0.5 but got " << h1.GetPosition()
<< endl;
++errors;
}
if (!h2.GetPosition().Compare(vtkVector3f(0.0, 0.0, 0.5), 1e-8))
{
cout << "Error atom position incorrect. Expected 0.0, 0.0, 0.5 but got " << h2.GetPosition()
<< endl;
++errors;
}
if (h1.GetAtomicNumber() != 1)
{
cout << "Error atomic number incorrect. Expected 1 but got " << h1.GetAtomicNumber() << endl;
++errors;
}
if (h2.GetAtomicNumber() != 1)
{
cout << "Error atomic number incorrect. Expected 1 but got " << h2.GetAtomicNumber() << endl;
++errors;
}
return errors == 0;
}
int TestMolecule(int, char*[])
{
// Check that the example code given in the molecule docs compiles:
bool test1 = MoleculeExampleCode1();
bool test2 = MoleculeExampleCode2();
return (test1 && test2) ? 0 : 1;
}
| true |
0635d651b4f333c174f6218d324e60f7674ec34f | C++ | ririripley/Algorithm580 | /AlgorithmReadingNote/Search/DFS-NQueen.cpp | UTF-8 | 2,591 | 3.328125 | 3 | [] | no_license | //
// Created by 黄紫君 on 11/03/2020.
//
#include <iostream>
#include <vector>
const int STEP[][2] = {
{1, 1},
{1, -1},
{-1, -1},
{-1, 1}
};
using namespace std;
bool check_constraint(vector<int> vec, int len);
void DFS(vector< vector<int> > & vecList, vector<int> vec, int len, int & total);
int main(){
int len;
int total = 0;
// cout << "please input the number for N : " << endl;
cin >> len;
vector< vector<int> > vecList;
vector<int> vec;
DFS(vecList, vec, len, total);
// cout << "The total number is : " << total << endl;
// cout << "The solutions are listed as follows: " << endl;
for(int i = 0 ; i < vecList.size(); i++){
vector<int> vec_ = vecList[i];
for (int j = 0; j < len; j++){
cout << vec_[j] << " ";
}
cout << endl;
}
cout << total<<endl;
}
void DFS(vector< vector<int> > & vecList, vector<int> vec, int len, int & total){
if(vec.size() == len){
total++;
if(vecList.size() < 3)
vecList.push_back(vec);
return;
}
// your choice
for(int i = 1; i <= len; i++){
vec.push_back(i);
if (check_constraint(vec, len)){
DFS(vecList, vec, len, total);
}
vec.pop_back();
}
}
bool check_constraint(vector<int> vec, int len){
int nums[len][len];
for(int i = 0; i < len; i++){
for (int j = 0; j < len; j++){
nums[i][j] = 0;
}
}
for (int i = 0; i < vec.size(); i++){
nums[i][vec[i] - 1] = 1;
}
for(int i =0; i < vec.size();i++){
int row = i;
int col = vec[i] - 1;
// row check
for(int k = 0, num = 0; k < len; k++){
if(nums[row][k] == 1)
num++;
if(num > 1){
return false;
}
}
// column check
for(int k = 0, num = 0; k < len; k++){
if(nums[k][col] == 1)
num++;
if(num > 1){
return false;
}
}
//diagonal check
for (int k = 0; k < 4; k++){
int nrow = row;
int ncol = col;
nrow = nrow + STEP[k][0];
ncol = ncol + STEP[k][1];
while(nrow >= 0 && nrow < len && ncol > 0 && ncol < len){
if(nums[nrow][ncol] == 1){
return false;
}
nrow = nrow + STEP[k][0];
ncol = ncol + STEP[k][1];
}
}
}
return true;
}
| true |
bf8fa9777cf2e5fdacc46393aafdd513aac3dbe1 | C++ | psj5329/API_TeamProject2 | /Unrailed/Unrailed/Unit.h | UTF-8 | 555 | 2.796875 | 3 | [] | no_license | #pragma once
#include "GameObject.h"
class Image;
class Unit : public GameObject
{
protected:
Image* mImage;
Direction mDirection;
int mHp;
public:
virtual void Init() override;
virtual void Release()override;
virtual void Update() override;
virtual void Render(HDC hdc) override;
public:
// Get
inline Direction GetDirection() { return mDirection; }
inline int GetHp() { return mHp; }
//Set
inline void SetDirection(Direction dir) { mDirection = dir; }
inline void SetHp(int hp) { mHp = hp; }
inline void DamagedHp() { mHp -= 1; }
}; | true |
bba8b2c229f76a10e0a5d5bc137482e95cfb40a0 | C++ | vxl/vxl | /contrib/mul/vil3d/algo/vil3d_find_blobs.h | UTF-8 | 1,167 | 2.546875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | // This is contrib/mul/vil3d/algo/vil3d_find_blobs.h
#ifndef vil3d_find_blobs_h_
#define vil3d_find_blobs_h_
//:
// \file
// \brief Identify and enumerate all disjoint blobs in a binary image.
// \author Ian Scott, Kevin de Souza
#include <vil3d/vil3d_fwd.h>
#include <vil3d/vil3d_chord.h>
//: Specify 6- or 26- neighbour connectivity
enum vil3d_find_blob_connectivity
{
vil3d_find_blob_connectivity_6_conn,
vil3d_find_blob_connectivity_26_conn
};
//: \brief Identify and enumerate all disjoint blobs in a binary image.
// \param src Input binary image, where false=background, true=foreground.
// \retval dst Output int image; 0=background, and 1...n are labels for each disjoint blob.
void vil3d_find_blobs(const vil3d_image_view<bool>& src,
vil3d_find_blob_connectivity conn,
vil3d_image_view<unsigned>& dst);
//: Convert a label image into a list of chorded regions.
// A blob label value of n will be returned in dest_regions[n-1].
void vil3d_blob_labels_to_regions(const vil3d_image_view<unsigned>& src_label,
std::vector<vil3d_region>& blob_regions);
#endif // vil3d_find_blobs_h_
| true |
3aeea2591d0e6e70c5bb28d8a682b0180159b6e7 | C++ | Codeon-GmbH/mulle-clang | /test/Sema/asm-goto.cpp | UTF-8 | 2,100 | 2.953125 | 3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | // RUN: %clang_cc1 %s -triple i386-pc-linux-gnu -verify -fsyntax-only
// RUN: %clang_cc1 %s -triple x86_64-pc-linux-gnu -verify -fsyntax-only
struct NonTrivial {
~NonTrivial();
int f(int);
private:
int k;
};
void JumpDiagnostics(int n) {
// expected-error@+1 {{cannot jump from this goto statement to its label}}
goto DirectJump;
// expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
NonTrivial tnp1;
DirectJump:
// expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
asm goto("jmp %l0;" ::::Later);
// expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
NonTrivial tnp2;
// expected-note@+1 {{possible target of asm goto statement}}
Later:
return;
}
struct S { ~S(); };
void foo(int a) {
if (a) {
FOO:
// expected-note@+2 {{jump exits scope of variable with non-trivial destructor}}
// expected-note@+1 {{jump exits scope of variable with non-trivial destructor}}
S s;
void *p = &&BAR;
// expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
asm goto("jmp %l0;" ::::BAR);
// expected-error@+1 {{cannot jump from this indirect goto statement to one of its possible targets}}
goto *p;
p = &&FOO;
goto *p;
return;
}
// expected-note@+2 {{possible target of asm goto statement}}
// expected-note@+1 {{possible target of indirect goto statement}}
BAR:
return;
}
//Asm goto:
int test16(int n)
{
// expected-error@+2 {{cannot jump from this asm goto statement to one of its possible targets}}
// expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
asm volatile goto("testl %0, %0; jne %l1;" :: "r"(n)::label_true, loop);
// expected-note@+2 {{jump bypasses initialization of variable length array}}
// expected-note@+1 {{possible target of asm goto statement}}
return ({int a[n];label_true: 2;});
// expected-note@+1 {{jump bypasses initialization of variable length array}}
int b[n];
// expected-note@+1 {{possible target of asm goto statement}}
loop:
return 0;
}
| true |
3c9b5423fb42982866abed1dd5050498ac827bb3 | C++ | YoungGouda/Rock-Paper-Scissors | /LoserGameForLosers/Options.h | UTF-8 | 3,794 | 2.859375 | 3 | [] | no_license | #pragma once
#include "SDL.h"
#include <vector>
#include "Vector2D.h"
#include "OptionLinks.h"
#include "LinkCommands.h"
class Options
{
std::vector<Link *> links_ {new CursorLeftLink(new ChangeStateCommand(STATE_COMBAT)), new CursorLeftLink(new NothingCommand()), new CursorLeftLink(new NothingCommand()), new CursorLeftLink(new NothingCommand()), new NoAssetLink(new NothingCommand), new NoAssetLink(new NothingCommand), new NoAssetLink(new NothingCommand), new NoAssetLink(new NothingCommand) };
public:
Options(Choices* choices)
{
std::vector<Link *> y_links{};
SDL_Rect starting_rect{};
//sets the starting position to the first option
choices->options[0][0].position = choices->link_parameters.starting_position;
links_[choices->options[0][0].link]->set_link_information(choices->link_parameters, choices->options[0][0].position, choices->options[0][0].asset);
// sets up the first rect to be used in alignment calculations
starting_rect = links_[choices->options[0][0].link]->get_box_dimensions();
option_rect = starting_rect;
for (auto x = 0; x < choices->options.size(); x++)
{
y_links.clear();
for (auto y = 0; y < choices->options[x].size(); y++)
{
auto current_link = links_[choices->options[x][y].link];
current_link->set_link_information(choices->link_parameters, choices->options[x][y].position, choices->options[x][y].asset, &starting_rect);
y_links.push_back(current_link);
// setting up next x link position if it exists
if (x+1 < choices->options.size())
choices->options[x+1][y].position = Vector2D(current_link->get_box_dimensions().x + current_link->get_box_dimensions().w,
current_link->get_box_dimensions().y);
// setting up next y link position if it exists
if (y+1 < choices->options[x].size())
choices->options[x][y+1].position = Vector2D(current_link->get_box_dimensions().x,
current_link->get_box_dimensions().y + current_link->get_box_dimensions().h);
// setting up option_rect
if (option_rect.x > current_link->get_box_dimensions().x)
option_rect.x = current_link->get_box_dimensions().x;
if (option_rect.y > current_link->get_box_dimensions().y)
option_rect.y = current_link->get_box_dimensions().y;
if (option_rect.x + option_rect.w < current_link->get_box_dimensions().x + current_link->get_box_dimensions().w)
option_rect.w += current_link->get_box_dimensions().x + current_link->get_box_dimensions().w - (option_rect.x + option_rect.w);
if (option_rect.y + option_rect.h < current_link->get_box_dimensions().y + current_link->get_box_dimensions().h)
option_rect.h += current_link->get_box_dimensions().y + current_link->get_box_dimensions().h - (option_rect.y + option_rect.h);
std::cout << "cursor dimensions = ( " << current_link->get_cursor_dimensions().x << ", " << current_link->get_cursor_dimensions().y << ", " << current_link->get_cursor_dimensions().w << ", " << current_link->get_cursor_dimensions().h << " )" << std::endl;
std::cout << "box dimensions = ( " << current_link->get_box_dimensions().x << ", " << current_link->get_box_dimensions().y << ", " << current_link->get_box_dimensions().w << ", " << current_link->get_box_dimensions().h << " )" << std::endl;
std::cout << "link dimensions = ( " << current_link->get_link_dimensions().x << ", " << current_link->get_link_dimensions().y << ", " << current_link->get_link_dimensions().w << ", " << current_link->get_link_dimensions().h << " )" << std::endl;
}
option_links.push_back(y_links);
}
std::cout << "option dimensions = ( " << option_rect.x << ", " << option_rect.y << ", " << option_rect.w << ", " << option_rect.h << " )" << std::endl;
}
std::vector<std::vector<Link *>> option_links{};
SDL_Rect option_rect{};
};
| true |
a15f4dd5140c1f0e6c5cab6603a2af0a273c3b19 | C++ | gfcodearq/HackerRank | /Sets-STL.cpp | UTF-8 | 529 | 2.90625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
set <int>s; //creo el iterador
int n;
cin>>n; //pide la cantidad de iteradores
for (int i =0;i<n;i++)
{
int a,option;
cin>>option>>a;
switch(option)
{
case 1:
s.insert(a);
break;
case 2:
s.erase(a);
break;
case 3:
cout << (s.find(a) == s.end() ? "No" : "Yes") << endl;
break;
}
}
return 0;
}
| true |
0dc72125bfe16a97454c00014c46ee4d549ee976 | C++ | JimsWithWang/CPP_PP | /3/examples/3_6/src/main.cpp | UTF-8 | 418 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <climits>
int main(int argv, char *argc[])
{
using namespace std;
char ch = 'M';
int i = ch;
cout<<"The one to the character code:"<<endl;
ch +=1;
i=ch;
cout<<"The ASCII code for "<<ch<<" is "<<i<<endl;
cout<<"Displaying char ch using cout.put(ch):";
cout.put(ch);
cout.put('!');
cout<<endl<<"Done"<<endl;
return 0;
} | true |
ab8b219e971e8f149c82098cafc6bcb3952208f3 | C++ | Kenneth-Raymond/ReadingAndWritingFiles | /dataFileTest/Inventory.h | UTF-8 | 377 | 2.9375 | 3 | [] | no_license | #pragma warning(disable:4996)
#include "string"
class Inventory
{
public:
//Default parameters constr
explicit Inventory(std::string = "", int = 0, double = 0);
//GETTERS AND SETTERS
void SetName(std::string);
std::string GetName();
void SetQty(int);
int GetQty();
void SetPerUnit(double);
double GetPerUnit();
private:
char name[25];
int qty;
double perUnit;
};
| true |
625564c2a3e52b4a4fd0b2a4be01a93ebc8d53c6 | C++ | meteora211/SelfLearning | /DataStructure/Stack/ex_digitalconvert.cc | UTF-8 | 603 | 3.359375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int convert(int num, int digit)
{
int res = 0, count = 0;
while(num > 0)
{
int rem = num % digit;
num /= digit;
res = rem * pow(10,count++) + res;
}
return res;
}
int main(int argc, char* argv[])
{
if(argc != 3)
{
printf("wrong input arguments\n");
return 1;
}
int num = atoi(argv[1]), digit = atoi(argv[2]);
int res = convert(num, digit);
printf("Convert input number: %d to %d digit number------> %d", num, digit, res);
return 0;
}
| true |
b4e5587f5728b8d6216dab1c053979e0d8a8a850 | C++ | bolvarak/NeuralNetwork | /C++/GenAlg/GeneticAlgorithmMap.h | UTF-8 | 1,344 | 2.984375 | 3 | [] | no_license | // Application Definitions
#ifndef GENETICALGORITHMMAP_H
#define GENETICALGORITHMMAP_H
// Application Headers
#include <stdlib.h>
#include <windows.h>
#include <vector>
#include "Definitions.h"
// Namespace Definition
using namespace std;
// Map class definition
class GeneticAlgorithmMap {
// Private properties
private:
// Map Storage
static const int iMap[MAP_HEIGHT][MAP_WIDTH];
static const int mMapWidth;
static const int mMapHeight;
// Starting points
static const int mStartX;
static const int mStartY;
// End points
static const int mEndX;
static const int mEndY;
// Public Properties
public:
// Memory storage
int iMemory[MAP_HEIGHT][MAP_WIDTH];
// Constructor Definition
GeneticAlgorithmMap() {
// Clear memory
ResetMemory();
}
// Tests the route to see how far the organism can get and returns
// a fitness score proportional to the distance reached from the exit
double TestRoute(const std::vector<int> &vPath, GeneticAlgorithmMap &cMemory);
// Displays the map using Windows GDI
void Render(const int cxClient, const int cyClient, HDC hdcSurface);
// Draws the path that is stored in memory
void RenderFromMemory(const int cxClient, const int cyClient, HDC hdcSurface);
// Clears memory
void ResetMemory();
};
#endif
| true |
5d1b8650e2765e044cbb7f6f554009c3d57a85c3 | C++ | maximhouston/labs | /Двусвязный список/DLS.cpp | WINDOWS-1251 | 6,429 | 3.359375 | 3 | [] | no_license | #include <cstdlib>
#include <locale>
#include <iostream>
using namespace std;
struct Node{
int names;
Node *next;
};
struct Rings {
int name;
Node *first;
Node *last;
Rings *next;
Rings *prev;
} *ring;
int N=0;
void Push(int n){
N++;
Rings *temp = new Rings;
temp->name = n;
temp->first = NULL;
temp->last = NULL;
if(ring){
temp->next = ring->next;
temp->prev = ring;
ring->next->prev=temp;
(ring)->next = temp;
}
else{
temp->prev = temp;
temp->next = temp;
}
ring = temp;
}
Rings* FindRing(int element){
Rings *el = ring;
while (el){
if(el->name == element) break;
el = el->next;
}
return el;
}
void PushAfter(int element, int n){
ring=FindRing(element);
Push(n);
}
void PushBefore(int element, int n){
N++;
ring=FindRing(element);
Rings *temp = new Rings;
temp->name = n;
temp->first = NULL;
temp->last = NULL;
if(ring){
temp->prev = ring->prev;
temp->next = ring;
ring->prev->next=temp;
(ring)->prev = temp;
}
else temp->prev = temp;
ring = temp;
}
void Print(Node *elFirst){
Node* el = elFirst;
while(el>0){
cout<<el->names<<" ";
el=el->next;
}
}
void Print_r(){
Rings* el = ring;
cout<<": "<<endl;
for(int i=0; i<N; i++){
cout<<el->name<<" ";
Print(el->first);
el=el->next;
}
}
void Print_l(){
Rings* el = ring;
cout<<": "<<endl;
for(int i=0; i<N; i++){
el=el->prev;
cout<<el->name<<" ";
Print(el->first);
}
}
void Pop(int element){
N--;
Rings *pcur=FindRing(element);
pcur->next->prev=pcur->prev;
pcur->prev->next=pcur->next;
ring=pcur->next;
delete pcur;
}
void PopBeforeN(int element){
Rings *pcur=FindRing(element);
pcur=pcur->prev;
Pop(pcur->name);
}
void PopAfterN(int element){
Rings *pcur=FindRing(element);
pcur=pcur->next;
Pop(pcur->name);
}
Node* FindElement(Node * const elFirst, int element){
Node *el = elFirst;
while (el){
if(el->names == element)break;
el = el->next;
}
return el;
}
Node* FindPrevFirst(Node * const elFirst, Node* element){
Node *el = elFirst;
while (el){
if(el->next == element)break;
el = el->next;
}
return el;
}
Node* CreateRing(int names){
Node *el = new Node;
el->names = names;
el->next = 0;
return el;
}
void PushFirst(int names){
if(ring->first){
Node *el = new Node;
el->names = names;
el->next = ring->first;
ring->first = el;
}
else {
ring->first=CreateRing(names);
ring->last=ring->first;
}
}
void PushBack(int names){
if(ring->first){
Node *el = new Node;
el->names = names;
el->next = 0;
ring->last->next = el;
ring->last = el;
}
else {
ring->first=CreateRing(names);
ring->last=ring->first;
}
}
void PushAfterN(int element, int names){
Node* find = FindElement(ring->first, element);
if(find){
if (find == ring->last) PushBack(names);
else{
Node* el = new Node;
el->names=names;
el->next=find->next;
find->next=el;
}
}
}
void PushBeforeN(int element, int names){
Node* find=FindElement(ring->first, element);
if(find){
if(find == ring->first) PushFirst(names);
else{
Node* el = new Node;
el->next=find;
el->names=names;
Node* p = FindPrevFirst(ring->first, find);
p -> next = el;
}
}
}
void PopElement(int element){
Node* find=FindElement(ring->first, element);
if(find){
Node* p = FindPrevFirst(ring->first, find);
if (find == ring->first) ring->first = (ring->first) -> next;
else if (find == ring->last) p->next=0;
else p->next=find->next;
delete find;
}
}
void PopAfter(int element){
Node* find=FindElement(ring->first, element);
if (find->next){
find=find->next;
PopElement(find->names);
}
}
void PopBefore(int element){
Node* find=FindElement(ring->first, element);
find=FindPrevFirst(ring->first, find);
if (find) PopElement(find->names);
}
int main(){
setlocale (0, "");
ring = NULL;
Node *head = NULL;
int el = 0;
int pos = 0;
cout<<" :\n";
cin>>el;
Push(el);
Print_r();
int com;
while (true){
cout<<"\n ?\n";
cout<<"1 - \n";
cout<<"2 - \n";
cout<<"3 - \n";
cout<<"4 - \n";
cout<<"5 - \n";
cout<<"6 - \n";
cout<<"7 - \n";
cout<<"8 - \n";
cout<<"9 - \n";
cin>>com;
switch (com){
case 1:
cout<<" \n";
cin>>el;
PushFirst(el);
break;
case 2:
cout<<" \n";
cin>>el;
PushBack(el);
break;
case 3:
cout<<" \n";
cin>>el;
cout<<" ?\n";
cin>>pos;
PushBefore(pos, el);
break;
case 4:
cout<<" \n";
cin>>el;
cout<<"c ?\n";
cin>>pos;
PushAfter(pos, el);
break;
case 5:
cout<<" , \n";
cin>>el;
PopAfterN(el);
break;
case 6:
cout<<" , \n";
cin>>el;
PopBeforeN(el);
break;
case 7:
cout<<" , \n";
cin>>el;
PopElement(el);
break;
case 8:
Print_r();
break;
case 9:
Print_l();
break;
default:
cout<<" !\n";
break;
}
}
}
| true |
ad0da01b9d1f30ac82423953937cc7e54b2c3a3e | C++ | DMLou/dmlist | /list/SmartLock.h | UTF-8 | 1,343 | 3.59375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | /*****************************************************************************
SmartLock
Defines an object that is "smart" in that it will automatically unlock a
mutex (or any object supporting Lock() and Unlock()) when it goes out of
scope. Simply create this object and use it for doing Lock/Unlock operations.
The object is created in a completely unlocked state.
*****************************************************************************/
#ifndef _SMARTLOCK_H
#define _SMARTLOCK_H
template<class Mutex>
class SmartLock
{
public:
SmartLock (Mutex *ParentMutex)
{
guard
{
TheMutex = ParentMutex;
StillLocked = 0;
return;
} unguard;
}
~SmartLock ()
{
guard
{
while (StillLocked > 0)
TheMutex->Unlock ();
return;
} unguard;
}
void Lock (void)
{
guard
{
TheMutex->Lock ();
StillLocked++;
return;
} unguard;
}
void Unlock (void)
{
guard
{
if (StillLocked > 0)
{
TheMutex->Unlock ();
StillLocked--;
}
return;
} unguard;
}
private:
int StillLocked;
Mutex *TheMutex;
};
#endif | true |
46466d7b0f6eda282a7cfcbf0d58e7c2cad1b0f0 | C++ | try1117/PascalCompiler | /Compiler/Compiler/ExpressionParser.cpp | UTF-8 | 2,278 | 3.046875 | 3 | [
"MIT"
] | permissive | #include "ExpressionParser.h"
#include "Exceptions.h"
//ExpressionParser::ExpressionParser(std::shared_ptr<Tokenizer> tokenizer)
// : tokenizer(tokenizer)
//{
//}
//
//std::shared_ptr<Expression> ExpressionParser::parse()
//{
// return parseExpr();
//}
//
//std::shared_ptr<Expression> ExpressionParser::parseExpr()
//{
// auto node = parseTerm();
// auto token = tokenizer->getCurrentToken();
//
// while (isExpr(token)) {
// tokenizer->next();
// node = std::make_shared<ExprBinaryOp>(token, std::initializer_list<std::shared_ptr<SyntaxNode>>({ node, parseTerm() }));
// token = tokenizer->getCurrentToken();
// }
//
// return node;
//}
//
//std::shared_ptr<Expression> ExpressionParser::parseTerm()
//{
// auto node = parseFactor();
// auto token = tokenizer->getCurrentToken();
//
// while (isTerm(token)) {
// tokenizer->next();
// node = std::make_shared<ExprBinaryOp>(token, std::initializer_list<std::shared_ptr<SyntaxNode>>({ node, parseFactor() }));
// token = tokenizer->getCurrentToken();
// }
//
// return node;
//}
//
//std::shared_ptr<Expression> ExpressionParser::parseFactor()
//{
// auto token = tokenizer->getCurrentToken();
// tokenizer->next();
//
// if (token->type == SEP_BRACKET_LEFT) {
// auto node = parseExpr();
// if (tokenizer->getCurrentToken()->type != SEP_BRACKET_RIGHT) {
// throw SyntaxException(token->row, token->col, "Unclosed brackets");
// }
// tokenizer->next();
// return node;
// }
// else if (isVar(token)) {
// return std::make_shared<ExprVar>(token);
// }
// else if (token->type == OP_MINUS || token->type == OP_PLUS) {
// return std::make_shared<ExprUnaryOp>(token, std::initializer_list<std::shared_ptr<SyntaxNode>>({ parseFactor() }));
// }
// else {
// throw SyntaxException(token->row, token->col, "Expected identifier, constant or expression");
// }
//}
//
//bool ExpressionParser::isVar(std::shared_ptr<Token> token)
//{
// return
// token->type == VARIABLE ||
// token->type == CONST_DOUBLE ||
// token->type == CONST_INTEGER;
//}
//
//bool ExpressionParser::isExpr(std::shared_ptr<Token> token)
//{
// return token->type == OP_PLUS || token->type == OP_MINUS;
//}
//
//bool ExpressionParser::isTerm(std::shared_ptr<Token> token)
//{
// return token->type == OP_MULT || token->type == OP_DIVISION;
//}
// | true |
a5002b49cc8edba76e540bea34db20fed5224eff | C++ | anvv5/studingCPP | /day04/ex01/AWeapon.hpp | UTF-8 | 544 | 3.21875 | 3 | [] | no_license | //
// Created by Shantay Budding on 4/18/21.
//
#ifndef EX01_AWEAPON_HPP
#define EX01_AWEAPON_HPP
#include <string>
#include <iostream>
class AWeapon
{
protected:
std::string _name;
int _apcost;
int _damage;
AWeapon();
public:
AWeapon(std::string const & name, int apcost, int damage);
AWeapon( AWeapon &src );
AWeapon &operator=( AWeapon const & );
virtual ~AWeapon();
virtual std::string getName() const;
int getAPCost() const;
int getDamage() const;
virtual void attack() const = 0;
};
#endif //EX01_AWEAPON_HPP
| true |
fcfa2b9d49baa429ed2f4d0981c27dc0bfacbff9 | C++ | jBosak98/WUST-object-oriented-programming | /10/1/Calculator.cpp | UTF-8 | 1,278 | 3.65625 | 4 | [] | no_license | #include "Calculator.h"
Calculator::Calculator(){}
void Calculator::performOperation(std::string op){
double firstNumber;
double secondNumber;
double result;
numbers.pop(secondNumber);
numbers.pop(firstNumber);
if(op == opADD)
result = firstNumber + secondNumber;
else if(op == opSUB)
result = firstNumber - secondNumber;
else if (op == opMUL)
result = firstNumber * secondNumber;
else if(op == opDIV)
result = firstNumber / secondNumber;
else if(op == opPOW)
result = pow(firstNumber, secondNumber);
numbers.push(result);
}
double Calculator::calc(std::string input){
numbers = Stack<double>();
std::istringstream ss(input);
std::string tmp;
double d;
while(!ss.eof()){
ss>>tmp;
if(isDouble(tmp)){
d = stringToDouble(tmp);
numbers.push(d);
}else if(isOperator(tmp)){
performOperation(tmp);
}
}
if (numbers.pop(d)){
return d;
}else return -1;
}
double Calculator::calc(Stack<CalcElement> *outputStack){
CalcElement e;
double d;
while(!outputStack->isEmpty()){
outputStack->pop(e);
if(e.type == CALC_VALUE){
d = stringToDouble(e.value);
numbers.push(d);
}else if(e.type == CALC_OPERATOR){
performOperation(e.value);
}
}
if (numbers.pop(d)){
return d;
}else return -1;
} | true |
cae631f69a80bb7b1ab16ce86f8686eefbb465f9 | C++ | btdat2506/IT.CLA.K18---CP---btdat2506 | /TH3/DayTamGiacBaoNhau.cpp | UTF-8 | 1,745 | 3.015625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct dat
{
double dt = 0; // dien tich
int stt = 0; //so thu tu
pair <int, int> a;
pair <int, int> b;
pair <int, int> c;
};
double dientich(pair <int, int> a, pair <int, int> b, pair <int, int> c)
{
return abs((b.first-a.first)*(c.second-a.second)-(c.first-a.first)*(b.second-a.second)) / 2;
}
bool Comparison(const dat &l, const dat &r)
{
return l.dt < r.dt;
}
bool kiemtra(dat data[], int i, int j)
{
if (
data[i].dt == dientich(data[i].a, data[i].b, data[j].a)
+ dientich(data[i].a, data[i].c, data[j].a)
+ dientich(data[i].b, data[i].c, data[j].a)
&&
data[i].dt == dientich(data[i].a, data[i].b, data[j].b)
+ dientich(data[i].a, data[i].c, data[j].b)
+ dientich(data[i].b, data[i].c, data[j].b)
&&
data[i].dt == dientich(data[i].a, data[i].b, data[j].c)
+ dientich(data[i].a, data[i].c, data[j].c)
+ dientich(data[i].b, data[i].c, data[j].c)
) return 1; else return 0;
}
int main()
{
int n, res = 0;
cin >> n;
dat data[n+100];
for (int i = 0; i < n; i++)
cin >> data[i].a.first >> data[i].a.second >> data[i].b.first >> data[i].b.second >> data[i].c.first >> data[i].c.second;
for (int i = 0; i < n; i++)
{
data[i].dt = dientich(data[i].a, data[i].b, data[i].c);
data[i].stt = i;
}
sort(data, data+n, Comparison);
int c[100000];
memset(c, 0, sizeof(c));
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
if (kiemtra(data, i, j)) c[i]++;
res = max(res, c[i]);
}
cout << res << endl;
system("pause");
return 0;
} | true |
b7696c037b404cc913185567bee57774255c5621 | C++ | Simon-ster/advent-2019-Cpp | /intcode.cpp | UTF-8 | 3,900 | 2.6875 | 3 | [] | no_license | #include "common.hpp"
// using Program = Vector<int>;
struct Memory : Map<long long int, long long int> {
void load(const String line) {
auto inputs = splitString(line, ',');
clear();
long long int i = 0;
for (auto &input : inputs) {
(*this)[i] = std::stoll(input);
i++;
}
}
};
struct Computer {
Memory program;
unsigned int cursor{0};
bool recFirstInput{false};
long long int relativeBase;
void load(const Memory &pgrm) {
program = pgrm;
cursor = 0;
//recFirstInput = false;
relativeBase = 0;
}
long long run(const int signal, const int setting = 0) {
while (cursor < program.size()) {
long long value = program[cursor];
std::map<char, int> info;
char array[] = {'A', 'B', 'C', 'D', 'E'};
String valueStr = std::to_string(value);
while (valueStr.size() < 5) {
valueStr = "0" + valueStr;
}
for (int j = 4; j >= 0; j--) {
info[array[j]] = int(valueStr[j]) - 48;
}
int opcode = (info['D'] * 10 + info['E']);
int firstMode = info['C'];
int secondMode = info['B'];
int thirdMode = info['A'];
long long int index1 = program[cursor + 1];
long long int index2 = program[cursor + 2];
long long int index3 = program[cursor + 3];
if (firstMode == 1) {
index1 = cursor + 1;
} else if (firstMode == 2) {
index1 += relativeBase;
}
if (secondMode == 1) {
index2 = cursor + 2;
} else if (secondMode == 2) {
index2 += relativeBase;
}
if (thirdMode == 1) {
index3 = cursor + 3;
} else if (thirdMode == 2) {
index3 += relativeBase;
}
if (opcode == 1) {
program[index3] = program[index1] + program[index2];
cursor += 4;
} else if (opcode == 2) {
program[index3] = program[index1] * program[index2];
cursor += 4;
} else if (opcode == 3) {
if (!recFirstInput) {
program[index1] = signal;
} else {
program[index1] = setting;
}
cursor += 2;
} else if (opcode == 4) {
cursor += 2;
return program[index1];
} else if (opcode == 5) {
if (program[index1] != 0) {
cursor = program[index2];
} else {
cursor += 3;
}
} else if (opcode == 6) {
if (program[index1] == 0) {
cursor = program[index2];
} else {
cursor += 3;
}
} else if (opcode == 7) {
if (program[index1] < program[index2]) {
program[index3] = 1;
} else {
program[index3] = 0;
}
cursor += 4;
} else if (opcode == 8) {
if (program[index1] == program[index2]) {
program[index3] = 1;
} else {
program[index3] = 0;
}
cursor += 4;
} else if (opcode == 9) {
relativeBase += program[index1];
cursor += 2;
} else if (opcode == 99) {
return -99;
} else {
std::cout << "You shouldn't be here" << std::endl;
cursor++;
}
cursor %= program.size();
}
return -99;
}
}; | true |
88f41f0575983dd850354b81176e99fe8af682e5 | C++ | marezelej/tecnomate | /franco/uri/dole_queue.cpp | UTF-8 | 1,200 | 3.359375 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct node {
int num;
node* sig;
node* ant;
};
node* createnode (int x,node* ant,node* p){
node* elcoso = new node();
elcoso->num = x;
elcoso->sig = p;
elcoso->ant = ant;
ant->sig=elcoso;
return elcoso;
}
void link (int n, node* l){
l->num=1;
l->sig=l;
l->ant=l;
node*ant=l;
for(int i=2;i<=n;i++){
ant=createnode(i,ant,l);
}
l->ant=ant;
}
void borrar(node* l,int x)
{
while(l->num!=x){
l=l->sig;
}
l->sig->ant=l->ant;
l->ant->sig=l->sig;
delete(l);
}
int main(int argc, char *argv[]) {
node*h=new node();
int N,k,m;
cin>>N>>k>>m;
link(N,h);
node*cr=h;
node*r=h->ant;
node*aux=h;
for(int i=1;i<=10;i++){
cout<<aux->num;
aux=aux->sig;
}
while(N>2){
for(int i=1;i<k;i++){
cr=cr->sig;
}
for(int i=1;i<m;i++){
r=r->ant;
}
if(cr->num==r->num){
int x=r->num;
cout<<" "<<x<<",";
cr=cr->sig;
r=r->ant;
borrar(h,x);
N--;
}
else
{
cout<<" "<<cr->num<<" "<<r->num<<",";
int x=cr->num;
int y=r->num;
cr=cr->sig;
if (cr->num==r->num){
cr=cr->sig;
}
borrar(h,x);
r=r->ant;
borrar(h,y);
N--;
N--;
}
}
cout<<" "<<r->num;
return 0;
}
| true |
4f4e32cbc032fb28150dd048359cf04de74167cb | C++ | visseck/animengine | /animcore/math/fixed_precision.h | UTF-8 | 2,504 | 2.921875 | 3 | [] | no_license | #pragma once
#include <type_traits>
#include <stdint.h>
#include "util/namespace.h"
ANIM_NAMESPACE_BEGIN
template<typename T>
struct DoubleSizeType
{
};
template<>
struct DoubleSizeType<int8_t>
{
typedef int16_t value;
};
template<>
struct DoubleSizeType<int16_t>
{
typedef int32_t value;
};
template<>
struct DoubleSizeType<int32_t>
{
typedef int64_t value;
};
template <typename BaseType, uint32_t PRECISION>
class FixedPoint
{
public:
typedef typename DoubleSizeType<BaseType>::value NextType;
FixedPoint operator+(FixedPoint other)
{
other.m_Value += m_Value;
return other;
}
FixedPoint& operator+=(FixedPoint other)
{
m_Value += other.m_Value;
return *this;
}
FixedPoint operator-(FixedPoint other)
{
other.m_Value -= m_Value;
return other;
}
FixedPoint& operator-=(FixedPoint other)
{
m_Value -= other.m_Value;
return *this;
}
FixedPoint& operator*=(FixedPoint other)
{
m_Value = ((NextType)(m_Value)* other.m_Value) >> PRECISION;
return *this;
}
FixedPoint operator*(FixedPoint other)
{
other *= *this;
return other;
}
FixedPoint& operator/=(FixedPoint other)
{
m_Value = (m_Value << PRECISION) / other.m_Value;
return *this;
}
FixedPoint operator/(FixedPoint other)
{
FixedPoint p(*this);
p /= other;
return p;
}
bool operator==(FixedPoint other) const
{
return m_Value == other.m_Value;
}
bool operator!=(FixedPoint other) const
{
return m_Value != other.m_Value;
}
bool operator>(FixedPoint other) const
{
return m_Value > other.m_Value;
}
bool operator>=(FixedPoint other) const
{
return m_Value >= other.m_Value;
}
bool operator<(FixedPoint other) const
{
return m_Value < other.m_Value;
}
bool operator<=(FixedPoint other) const
{
return m_Value <= other.m_Value;
}
static constexpr float EPSILON_F = 1 / (float)(1 << PRECISION);
FixedPoint& operator=(float f)
{
FromFloat(f);
return *this;
}
float ToFloat() const
{
return m_Value / (float)((NextType)1 << PRECISION);
}
void FromFloat(float value)
{
m_Value = (BaseType)(value * ((NextType)1 << PRECISION));
}
private:
BaseType m_Value;
};
using FPRatio32 = FixedPoint<int32_t, 31>;
using FPRatio64 = FixedPoint<int64_t, 63>;
static_assert(std::is_pod<FPRatio32>::value, "Not POD");
static_assert(std::is_pod<FPRatio64>::value, "Not POD");
ANIM_NAMESPACE_END
| true |
6ca882d4e5a5346c10bec70d1aaae157453d12f5 | C++ | Behrouz-Babaki/FactoredSCP | /fscp_src/brancher_exputil.hpp | UTF-8 | 4,410 | 2.578125 | 3 | [] | no_license | // brancher for use with constraint_exputil and bn_engine.
// based on MPG 'minsize' brancher
#ifndef _BRANCHER_EXPUTIL_HPP_
#define _BRANCHER_EXPUTIL_HPP_
#include <gecode/int.hh>
#include "policy_tree_state.h"
using namespace Gecode;
// sorting on second pair entry
template <typename T1, typename T2>
struct greater_second {
typedef std::pair<T1, T2> type;
bool operator ()(type const& a, type const& b) const {
return a.second > b.second;
}
};
void branch_exputil(Home home,
const IntVarArgs& x,
PolTreeState& poltree,
bool order_or_max,
bool order_and_max,
int depth_or,
int depth_and);
class BranchExpUtil : public Brancher {
protected:
// variables
Gecode::ViewArray<Int::IntView> vars;
// state
PolTreeState& poltree;
mutable int pos;
const bool order_or_max; // for OR nodes, max value first or min value first
const bool order_and_max;
const int depth_or;
const int depth_and;
class VarChoice : public Choice {
public:
int id;
std::vector<int> vals;
std::vector<double> upperbounds;
VarChoice(const BranchExpUtil& b, int id0, const std::vector<int>& vals0, const std::vector<double>& ubs)
: Choice(b, vals0.size()), id(id0), vals(vals0), upperbounds(ubs) {}
virtual size_t size(void) const {
return sizeof(*this);
}
virtual void archive(Archive& e) const {
Choice::archive(e);
e << id;
e << (int)vals.size();
for(size_t i = 0; i < vals.size(); i++) {
e<<vals[i];
e<<upperbounds[i];
}
}
};
public:
// for rand vars, we branch based on mass
// for decision vars... min value (could be an option)
BranchExpUtil(Home home, ViewArray<Int::IntView>& vars0, PolTreeState& poltree0,
bool order_or_max0, bool order_and_max0, int depth_or0, int depth_and0)
: Brancher(home), vars(vars0), poltree(poltree0), pos(0),
order_or_max(order_or_max0), order_and_max(order_and_max0), depth_or(depth_or0), depth_and(depth_and0) {}
static void post(Home home, ViewArray<Int::IntView>& vars, PolTreeState& poltree,
bool order_or_max, bool order_and_max, int depth_or, int depth_and) {
(void) new (home) BranchExpUtil(home,vars,poltree,order_or_max,order_and_max,depth_or,depth_and);
}
virtual size_t dispose(Space& home) {
(void) Brancher::dispose(home);
return sizeof(*this);
}
BranchExpUtil(Space& home, bool share, BranchExpUtil& b)
: Brancher(home,share,b), poltree(b.poltree), pos(b.pos),
order_or_max(b.order_or_max), order_and_max(b.order_and_max), depth_or(b.depth_or), depth_and(b.depth_and) {
vars.update(home,share,b.vars);
}
virtual Brancher* copy(Space& home, bool share) {
return new (home) BranchExpUtil(home,share,*this);
}
// check whether there is something to branch on
virtual bool status(const Space& home) const {
for (int i=pos; i<vars.size(); i++) {
if (!vars[i].assigned()) {
pos = i; return true;
}
}
return false;
}
// return one Choice object that contains how many values to branch over
// this is called just once per variable
virtual Choice* choice(Space& home);
// something technical, depends on Choice* implementation
virtual Choice* choice(const Space&, Archive& e) {
int id;
int n;
e >> id >> n;
std::vector<int> vals;
vals.reserve(n);
int v;
std::vector<double> ubs;
ubs.reserve(n);
int ub;
for(int i=0; i < n; i++) {
e >> v;
vals.push_back(v);
e >> ub;
ubs.push_back(ub);
}
return new VarChoice(*this, id, vals, ubs);
}
// c is our Choice implementation
// a is the how-manyth value of this choice
// this is called for each value of the variable
virtual ExecStatus commit(Space& home,
const Choice& c,
unsigned int a) ;
// printing Choice nr a to o.
virtual void print(const Space& home, const Choice& c,
unsigned int a,
std::ostream& o) const {
const VarChoice& vc = static_cast<const VarChoice&>(c);
int id = vc.id;
int val = vc.vals[a];
o << "x[" << id << "] = " << val;
}
void reset_frompos(int pos);
};
#endif
| true |
f7495e68e863ee601e0b0b64628147d5c371ea8e | C++ | RaphiOriginal/cpp | /NativeMatrix/NativeMatrix/main.cpp | UTF-8 | 2,052 | 3.078125 | 3 | [] | no_license | #include "Matrix.h"
#include <iostream>
void multiplyCal(jdouble *m, jdouble *thi, jdouble *result, jint mcolumn, jint thisrow, jint thiscolumn) {
int indexer1 = 0;
int indexer3 = 0;
for (int i = 0; i < thisrow; i++) {
//each column from m
for (int j = 0; j < mcolumn; j++) {
//next column in this
int indexer2 = 0;
jdouble val = 0;
for (int k = 0; k < thiscolumn; k++) {
val += thi[indexer1 + k] * m[indexer2 + j];
indexer2 += mcolumn;
}
result[indexer3++] = val;
}
indexer1 += thisrow;
}
}
void copy(jdouble*& target, jdouble*& source, jint size) {
for (jint i = 0; i < size; i++) {
target[i] = source[i];
}
}
JNIEXPORT void JNICALL Java_Matrix_multiplyC
(JNIEnv *env, jobject, jdoubleArray a, jdoubleArray b, jdoubleArray r, jint mcolumn, jint thisrow, jint thiscolumn) {
jdouble *m = env->GetDoubleArrayElements(b, 0);
jdouble *thi = env->GetDoubleArrayElements(a, 0);
jdouble *result = env->GetDoubleArrayElements(r, 0);
multiplyCal(m, thi, result, mcolumn, thisrow, thiscolumn);
env->ReleaseDoubleArrayElements(r, result, 0);
env->ReleaseDoubleArrayElements(a, thi, JNI_ABORT);
env->ReleaseDoubleArrayElements(b, m, JNI_ABORT);
}
void swap(jdouble*& target, jdouble*& source) {
jdouble *temp = target;
target = source;
source = temp;
}
JNIEXPORT void JNICALL Java_Matrix_powerC
(JNIEnv *env, jobject, jdoubleArray a, jdoubleArray r, jint pow, jint dimension) {
jdouble *thi = env->GetDoubleArrayElements(a, 0);
jint size = dimension*dimension;
jdouble *temp = new jdouble[size];
jdouble * const mytemp = temp;
jdouble *result = env->GetDoubleArrayElements(r, 0);
copy(temp, thi, size);
while (pow > 1) {
multiplyCal(thi, temp, result, dimension, dimension, dimension);
swap(temp, result);
pow--;
}
if (!(mytemp == temp)) {
swap(temp, result);
}
else {
//result is stored in temp, need to put it back to result!
copy(result, temp, size);
}
delete[] mytemp;
env->ReleaseDoubleArrayElements(r, result, 0);
env->ReleaseDoubleArrayElements(a, thi, JNI_ABORT);
}
| true |
70b8edb08276856b07c6a8ac39012983bcbfb34e | C++ | Bebo-K/game_project_1 | /game_project_1/game/races_and_classes.hpp | UTF-8 | 1,106 | 2.9375 | 3 | [] | no_license | #ifndef RACES_AND_CLASSES_H
#define RACES_AND_CLASSES_H
#include <game_project_1/types/str.hpp>
#include <game_project_1/game/stats.hpp>
typedef int RaceID;
struct Race{
RaceID id;
wchar* name;
int max_styles_1;
int max_styles_2;
int max_styles_3;
float hitsphere_height;
float hitsphere_radius;
BaseStats stat_base;
};
typedef int ClassID;
struct Class{
ClassID id;
wchar* name;
BaseStats stat_bonus;
};
namespace Races{
const Race Human = {0,L"Human",3,3,3, 3.0f,0.75f, {12,8,10,9,11}};
const Race Golem = {1,L"Golem",3,3,3, 3.0f,0.75f, {11,9,12,10,8}};
const Race Impkin = {2,L"Impkin",3,3,3, 3.0f,0.75f, {10,11,8,9,12}};
const Race Torag = {3,L"Torag",3,3,3, 3.0f,0.75f, {10,10,10,10,10}};
extern int Max;
Race GetRaceByID(RaceID id);
};
namespace Classes{
const Class Warrior = {0,L"Warrior",{2,0,2,0,0}};
const Class Archer = {1,L"Archer",{0,1,0,1,2}};
const Class Mage = {2,L"Mage",{0,2,0,2,0}};
const Class Thief = {3,L"Thief",{2,0,1,0,2} };
extern int Max;
Class GetClassByID(ClassID id);
};
#endif | true |
813ef8bba7cbbcd4f81b96e6dc22085d60ae1962 | C++ | graziel666/first-try | /primer_juego/player.h | UTF-8 | 2,411 | 2.75 | 3 | [] | no_license | #pragma once
#ifndef PLAYER_H
#define PLAYER_H
#include "globals.h"
#include "map.h"
bool isWalking = false;
enum class HorizontalDirection : uint8_t {Left, Right};
uint8_t frame = 0;
uint8_t x = 16;
uint8_t y = 16*2;
HorizontalDirection playerDir = HorizontalDirection::Right; //Left,Right
constexpr uint8_t CharW = 16;
constexpr uint8_t CharH = 16;
#define MaxX (WIDTH - tileSize )
#define MaxY (HEIGHT - CharH*2+3)
#define MinX 16
//jump
uint8_t groundLevel = 35;
uint8_t playerY = 35;
int playerVelocityY;
uint8_t gravity = 1;
void WalkingAnim(){
isWalking = true;
if (arduboy.everyXFrames(8)) frame ++;
if (frame > 4) frame = 1;
}
void playerMove(){
//moving player and map
if (arduboy.pressed(RIGHT_BUTTON)){
//player movement
if (x < MaxX){
WalkingAnim();
x++;
playerDir = HorizontalDirection::Right;
}
//map movement
if (x == MaxX && mapX < mapMaxY){
WalkingAnim();
mapX++;
}
}
/*if (arduboy.pressed(RIGHT_BUTTON) && x == MaxX && mapX < 114){
Walking();
mapX++;
}*/
if (arduboy.pressed(LEFT_BUTTON)){
//player movement
if (x > MinX){
WalkingAnim();
x--;
playerDir = HorizontalDirection::Left;
}
//map movement
if (x == MinX && mapX > 0 && mapX <= mapMaxY){
WalkingAnim();
mapX--;
}
}
/*if (arduboy.pressed(LEFT_BUTTON)&& x == MinX && mapX > 0 && mapX <= 114) {
Walking();
mapX--;*/
//jump
if (arduboy.pressed(A_BUTTON)){
if (playerY == groundLevel){
playerVelocityY = -7;
}
}
//moving player up or down
if (playerVelocityY < 0) playerY += playerVelocityY;
if (playerVelocityY < 0) playerVelocityY += gravity;
if (playerY < groundLevel) playerY += gravity%playerVelocityY;
//stop
if (playerY > groundLevel) playerY = groundLevel;
//animation reset
if (isWalking && arduboy.notPressed(RIGHT_BUTTON) && arduboy.notPressed(LEFT_BUTTON)) isWalking = false;
if (!isWalking ) frame = 0;
//setting direction
if (playerDir == HorizontalDirection::Left){
sprites.drawPlusMask(x ,playerY,PjWalkingLeft,frame);
}
if (playerDir == HorizontalDirection::Right){
sprites.drawPlusMask(x ,playerY,PjWalkingRight,frame);
}
}
#endif
| true |
0f70583beab94474dc92a9b7beaea67f23d65071 | C++ | am-Anmol/DS-Algorithm | /Arrays/Smallest_Subarray_with_sum_greater_than_a_given_value.cpp | UTF-8 | 1,079 | 3.90625 | 4 | [] | no_license | //Smallest Subarray with sum greater than a given value
# include <iostream>
using namespace std;
int smallestSubWithSum(int arr[], int n, int x)
{
int min_len = n + 1;
for (int start=0; start<n; start++)
{
int curr_sum = arr[start];
if (curr_sum > x) return 1;
for (int end=start+1; end<n; end++)
{
curr_sum += arr[end];
if (curr_sum > x && (end - start + 1) < min_len)
min_len = (end - start + 1);
}
}
return min_len;
}
int main()
{
int arr1[] = {1, 4, 45, 6, 10, 19};
int x = 51;
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int res1 = smallestSubWithSum(arr1, n1, x);
(res1 == n1+1)? cout << "Not possible\n" :cout << res1 << endl;
int arr2[] = {1, 10, 5, 2, 7};
int n2 = sizeof(arr2)/sizeof(arr2[0]);
x = 9;
int res2 = smallestSubWithSum(arr2, n2, x);
(res2 == n2+1)? cout << "Not possible\n" :cout << res2 << endl;
int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250};
int n3 = sizeof(arr3)/sizeof(arr3[0]);
x = 280;
int res3 = smallestSubWithSum(arr3, n3, x);
(res3 == n3+1)? cout << "Not possible\n" :cout << res3 << endl;
return 0;
}
| true |
64c11d1bada83ff0abd7a93f6ab9493ffd8aa18a | C++ | mbiggio/ctci | /3_stacks_and_queues/5_sort_stack.cpp | UTF-8 | 1,226 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <stack>
#include <stdexcept>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace std;
void sort_stack(stack<int> &s) {
stack<int> s_sorted;
while (!s.empty()) {
int tmp = s.top();
s.pop();
int popped = 0;
while (!s_sorted.empty() && tmp <= s_sorted.top()) {
s.push(s_sorted.top());
s_sorted.pop();
++popped;
}
s_sorted.push(tmp);
for (int i=0; i<popped; ++i) {
s_sorted.push(s.top());
s.pop();
}
}
while (!s_sorted.empty()) {
s.push(s_sorted.top());
s_sorted.pop();
}
}
TEST(sort_stack_test, nominal) {
stack<int> s;
// push a few elements
s.push(80);
s.push(15);
s.push(30);
s.push(1);
s.push(10);
s.push(27);
sort_stack(s);
EXPECT_EQ(1,s.top());
EXPECT_NO_THROW(s.pop());
EXPECT_EQ(10,s.top());
EXPECT_NO_THROW(s.pop());
EXPECT_EQ(15,s.top());
EXPECT_NO_THROW(s.pop());
EXPECT_EQ(27,s.top());
EXPECT_NO_THROW(s.pop());
EXPECT_EQ(30,s.top());
EXPECT_NO_THROW(s.pop());
EXPECT_EQ(80,s.top());
EXPECT_NO_THROW(s.pop());
EXPECT_TRUE(s.empty());
}
int main(int argc, char** argv) {
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
35c421d1c7a6fafae2fcf39bcc665f6d31614236 | C++ | Trompowsky/Calculator | /Calculator/main.cpp | UTF-8 | 4,097 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <stdexcept>
#include "Expression.h"
#include "PrintVect.h"
#include "Exp.h"
#include "Constant.h"
#include "Addition.h"
#include "Subtraction.h"
#include "Multiplication.h"
#include "Division.h"
using namespace std;
int main()
{
string User;
string prntnum;
string prntop;
std::vector<string> strVector;
cout << "Enter your expression: ";
cin >> User;
Expression a(User);
while (!a.Emp()){
prntnum = a.printnum();
strVector.push_back(prntnum);
if (!a.Emp()){
prntop = a.printop();
strVector.push_back(prntop);
}
}
PrintVect b(strVector);
//cout << b.Bracketing() << endl;
for (vector<string>::iterator it = strVector.begin(); it != strVector.end(); ++it) {
//cout << (*it) << endl;
}
double value;
double val;
istringstream iss(strVector[0]);
iss >> value;
istringstream is(strVector[2]);
is >> val;
vector <string>::iterator it2 = strVector.begin();
string num = *it2++;
Exp * LHS = new Exp(new Constant(num));
//cout << LHS->Print() << endl;
int i = 0;
while(2*i+1<strVector.size()){
string op = *it2++;
string num1 = *it2++;
Exp * Number = new Exp(new Constant(num1));
if (op == "+"){
Exp * temp = new Exp(new Addition(), LHS, Number);
//cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
if (op == "-"){
Exp * temp = new Exp(new Subtraction(), LHS, Number);
//cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
if (op == "/"){
Exp * temp = new Exp(new Division(), LHS, Number);
//cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
if (op == "*"){
Exp * temp = new Exp(new Multiplication(), LHS, Number);
//cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
/*
if (op!= "*", "-", "+", "/"){
throw domain_error("Unexpected input - expected an operator");
}*/
//cout << i << "\t" << 2*i+1 << "\t" << strVector.size() << endl;
// Exp * temp = new Exp(op, LHS, Number);
//LHS = temp;
i++;
if (2*i+1==strVector.size()){
if (op == "+"){
Exp * temp = new Exp(new Addition(), LHS, Number);
cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
if (op == "-"){
Exp * temp = new Exp(new Subtraction(), LHS, Number);
cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
if (op == "/"){
Exp * temp = new Exp(new Division(), LHS, Number);
cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
if (op == "*"){
Exp * temp = new Exp(new Multiplication(), LHS, Number);
cout << "Calc> " << LHS->Print() << "=" << LHS->Eval() << endl;
LHS = temp;
}
}
}
}
/*
while(not the end of the vector){
op = *it++;
if it's safe:
num *it++;
exp * temp = new Exp(op, LHS, Num)
LHS = Temp
}
Exp * e = new Exp (new Constant ("1"));
cout << "test e=" << e->Print() << "=" << e->Eval() << endl;
Exp * f = new Exp (new Division(), new Exp (new Constant ("1")), new Exp(new Constant ("5")));
cout << "test f=" << f->Print() << "=" << f->Eval() << endl;
Exp q(new Subtraction(), e, f);
cout << "test q=" << q.Print() << "=" << q.Eval() << endl;
}
/*
for(unsigned int i=0;i<strVector.size()-1;i+=2){
istringstream is(strVector[i+2]);
is >> val;
if (strVector[i+1] == "+"){
value = value+val;
}
}
cout << value << endl;
*/
// now value has the double value or 0.0
| true |
1ffed8cc091eec43a4be2550507d2333614b3446 | C++ | sreejond/FileAuditSystem | /DaemonProcess.h | UTF-8 | 601 | 2.609375 | 3 | [] | no_license | #ifndef DAEMONPROCESS_H
#define DAEMONPROCESS_H
/**
* \class DaemonProcess
*
* \brief
*
* This class is responsible to create a daemon process
*/
class DaemonProcess
{
public:
/**
* \brief create the daemon process
*/
static void create();
/**
* \brief deleted copy constructor
*/
DaemonProcess(const DaemonProcess&) = delete;
/**
* \brief deleted copy assignment operator
*/
void operator=(DaemonProcess const&) = delete;
private:
/**
* \brief default constructor
*/
DaemonProcess() = default;
};
#endif /* DAEMONPROCESS_H */
| true |
170495e674385af9f0afc2bcfbc2d5fdfcd829d2 | C++ | wangkendy/grids | /2712.cc | UTF-8 | 635 | 3.109375 | 3 | [] | no_license | /*
* source: http://poj.grids.cn/practice/2712
* tag: date and time
*
*/
#include <iostream>
using namespace std;
int get_days(int bm, int bd, int em, int ed)
{
static int mon[12] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
int days = 0;
if (bm < em) {
days = mon[bm] - bd + ed;
} else { // same month
days = ed - bd;
}
for (int i = bm + 1; i < em; i++) {
days += mon[i];
}
return days;
}
int main()
{
int N;
unsigned long init;
int bm, bd, em, ed;
cin >> N;
while (N--) {
cin >> bm >> bd >> init >> em >> ed;
int days = get_days(bm, bd, em, ed);
cout << (init << days) << endl;
}
return 0;
}
| true |
8a08cdac874d8dab8dd4062811e37c770b158260 | C++ | Nemaleswang/Course-Of-Master | /研一上学期/Linux高级环境编程实验/实验四/code/4.2/main.cpp | UTF-8 | 437 | 2.71875 | 3 | [] | no_license | #include <dlfcn.h>
#include <iostream>
using namespace std;
int main()
{
void *handle = dlopen("./libfun.so", RTLD_LAZY);
if(handle == 0)
{
cout << "dlopen error" << endl;
return 0;
}
typedef void (*FUNC_PRINT)();
FUNC_PRINT dl_print = (FUNC_PRINT)dlsym(handle, "Print");
if(dl_print == 0)
{
cout << "dlsym error" << endl;
return 0;
}
(dl_print)();
dlclose(handle);
return 0;
}
| true |
fcc98c3188e79746dc98759635e438cbde95746d | C++ | tankeeh/exercise5 | /stack/vec/stackvec.hpp | UTF-8 | 2,376 | 2.875 | 3 | [] | no_license |
#ifndef STACKVEC_HPP
#define STACKVEC_HPP
/* ************************************************************************** */
#include <stdexcept>
#include "../stack.hpp"
#include "../../vector/vector.hpp"
/* ************************************************************************** */
namespace lasd {
/* ************************************************************************** */
template <typename Data>
class StackVec: virtual public Stack<Data>,virtual protected Vector<Data> {
private:
protected:
using Vector<Data>::size;
using Vector<Data>::elem;
unsigned int index = 0;
// ...
public:
// Default constructor
StackVec();
// Copy constructor
StackVec(const StackVec& stack);
// Move constructor
StackVec(StackVec&& stack) noexcept;
/* ************************************************************************ */
// Destructor
~StackVec() = default;
/* ************************************************************************ */
// Copy assignment
StackVec &operator=(const StackVec& stack);
// Move assignment
StackVec &operator=(StackVec&& stack);
/* ************************************************************************ */
// Comparison operators
bool operator==(const StackVec& stack)const;
bool operator!=(const StackVec& stack)const;
/* ************************************************************************ */
// Specific member functions (inherited from Stack)
Data Top() const override ; // Override Stack member (might throw std::length_error)
void Pop() override ; // Override Stack member (might throw std::length_error)
Data TopNPop() override ; // Override Stack member (might throw std::length_error)
void Push(const Data& item) override; // Override Stack member
void Push(Data&& item) override;
/* ************************************************************************ */
// Specific member functions (inherited from Container)
bool Empty()const noexcept override ; // Override Container member
int Size()const noexcept override ;// Override Container member
void Clear() override; // Override Container member
protected:
void Expand(); // Accessory function
void Reduce(); // Accessory function
};
/* ************************************************************************** */
#include "stackvec.cpp"
}
#endif
| true |
50abbc9cadb52ea05846abc262fdfe9e4972ca6d | C++ | moderncoder/SDRReradiationSpectrumAnalyzer | /SDRSpectrumAnalyzerOpenGL/SDRSpectrumAnalyzerOpenGL/FrequencyRange.cpp | UTF-8 | 543 | 3.234375 | 3 | [] | no_license | #include "FrequencyRange.h"
FrequencyRange::FrequencyRange()
{
lower = 0;
upper = 0;
length = 0;
strength = 0;
centerFrequency = 0;
}
FrequencyRange::FrequencyRange(uint32_t lower, uint32_t upper, double strengthValue)
{
Set(lower, upper);
strength = strengthValue;
}
void FrequencyRange::Set(FrequencyRange *range)
{
Set(range->lower, range->upper);
}
void FrequencyRange::Set(uint32_t lower, uint32_t upper)
{
this->lower = lower;
this->upper = upper;
length = (upper - lower);
centerFrequency = (lower + upper) / 2;
} | true |
141cfde9ecd9745a8e76a2500c2aab09c29ce8a8 | C++ | TiFu/thrill-hyperloglog | /tests/common/lru_cache_test.cpp | UTF-8 | 1,758 | 2.578125 | 3 | [
"BSD-2-Clause"
] | permissive | /*******************************************************************************
* tests/common/lru_cache_test.cpp
*
* Borrowed from https://github.com/lamerman/cpp-lru-cache by Alexander
* Ponomarev under BSD license and modified for Thrill's block pool.
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2013 Alexander Ponomarev
* Copyright (C) 2016 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#include <thrill/common/lru_cache.hpp>
#include <gtest/gtest.h>
using namespace thrill;
static constexpr int kNumOfTest2Records = 100;
static constexpr int kTest2CacheCapacity = 50;
TEST(LruCacheTest, SimplePut) {
common::LruCache<int, int> cache;
cache.put(7, 777);
EXPECT_TRUE(cache.exists(7));
EXPECT_EQ(777, cache.get(7));
EXPECT_EQ(1, cache.size());
}
TEST(LruCacheTest, MissingValue) {
common::LruCache<int, int> cache;
EXPECT_THROW(cache.get(7), std::range_error);
}
TEST(LruCacheTest1, KeepAllValuesWithinCapacity) {
common::LruCache<int, int> cache;
for (int i = 0; i < kNumOfTest2Records; ++i) {
cache.put(i, i);
while (cache.size() > kTest2CacheCapacity)
cache.pop();
}
for (int i = 0; i < kNumOfTest2Records - kTest2CacheCapacity; ++i) {
EXPECT_FALSE(cache.exists(i));
}
for (int i = kNumOfTest2Records - kTest2CacheCapacity; i < kNumOfTest2Records; ++i) {
EXPECT_TRUE(cache.exists(i));
EXPECT_EQ(i, cache.get(i));
}
size_t size = cache.size();
EXPECT_EQ(kTest2CacheCapacity, size);
}
/******************************************************************************/
| true |
bb38009a3a9bd0ad51eb371e739a80dfde8fe617 | C++ | perezite/cheesy | /jvgs-minimal/src/game/Camera.cpp | UTF-8 | 2,551 | 2.5625 | 3 | [] | no_license | #include "Camera.h"
#include "Entity.h"
#include "Level.h"
#include "../core/LogManager.h"
using namespace jvgs::core;
using namespace std;
#include "../video/VideoManager.h"
using namespace jvgs::video;
using namespace jvgs::math;
#include "../tinyxml/tinyxml.h"
namespace jvgs
{
namespace game
{
void Camera::loadData(TiXmlElement *element)
{
Vector2D::fromXML(element->FirstChildElement("position"),
&position);
element->QueryFloatAttribute("maxdistance", &maxDistance);
if(element->Attribute("target"))
target = element->Attribute("target");
Entity *entity = getLevel()->getEntityById(target);
if(entity)
setPosition(entity->getPosition());
}
Camera::Camera(const std::string &target, float maxDistance,
const math::Vector2D &position, Level *level)
{
this->level = level;
this->position = position;
this->target = target;
this->maxDistance = maxDistance;
}
Camera::Camera(TiXmlElement *element, Level *level)
{
this->level = level;
load(element);
}
Camera::~Camera()
{
}
Level *Camera::getLevel() const
{
return level;
}
void Camera::update(float ms)
{
Entity *entity = getLevel()->getEntityById(target);
if(entity) {
Vector2D position= getPosition();
Vector2D direction = entity->getPosition() - position;
if(direction.getLength() > maxDistance) {
direction.setLength((direction.getLength() - maxDistance));
setPosition(position + direction);
}
}
}
const Vector2D &Camera::getPosition() const
{
return position;
}
void Camera::setPosition(const Vector2D &position)
{
this->position = position;
}
void Camera::transform() const
{
VideoManager *videoManager = VideoManager::getInstance();
videoManager->translate(-position + videoManager->getSize() * 0.5f);
}
BoundingBox& Camera::getBoundingBox()
{
VideoManager *videoManager = VideoManager::getInstance();
boundingBox = BoundingBox(position - videoManager->getSize() * 0.5f,
position + videoManager->getSize() * 0.5f);
return boundingBox;
}
}
}
| true |
095d0e68c63d737765afc60db52fcaca37eab0e5 | C++ | ByteFest/ByteFest-Spring-2015 | /Competition Day Problems/a_rock_paper_scissors/rock_paper_scissors.cpp | UTF-8 | 1,027 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int p1Count, p2Count, tieCount;
int testCases;
int roundSize;
char ch1, ch2;
ifstream fin("a.in");
fin >> testCases;
for (int i = 0; i < testCases; i++)
{
fin >> roundSize;
p1Count = 0;
p2Count = 0;
tieCount = 0;
for (int j = 0; j < roundSize; j++)
{
fin >> ch1 >> ch2;
if (ch1 == 'R')
{
if (ch2 == 'R')
tieCount++;
else if (ch2 == 'P')
p2Count++;
else //ch2 == 'S'
p1Count++;
}
else if (ch1 == 'P')
{
if (ch2 == 'P')
tieCount++;
else if (ch2 == 'S')
p2Count++;
else //ch2 == 'R'
p1Count++;
}
else //ch1 == 'S'
{
if (ch2 == 'S')
tieCount++;
else if (ch2 == 'R')
p2Count++;
else //ch2 == 'P'
p1Count++;
}
}//end j loop
//report winner
if (p1Count > p2Count)
cout << "Player 1" << endl;
else if (p2Count > p1Count)
cout << "Player 2" << endl;
else
cout << "TIE" << endl;
}//end i loop
}
| true |
075b274ec74bbd6de17387611048c5b6155d3254 | C++ | avovana/Otus.Cpp.Homework10 | /tests/test_benchmark.cpp | UTF-8 | 8,266 | 2.703125 | 3 | [] | no_license | #include "FileOutput.h"
#include <algorithm>
#include <functional>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define BOOST_TEST_MODULE test_benchmark
#include <boost/test/unit_test.hpp>
#include <boost/test/included/unit_test.hpp>
using namespace std::chrono_literals;
class FileOutputWithCPUOverhead : public FileOutput
{
public:
explicit FileOutputWithCPUOverhead(size_t threads_count = 0)
: FileOutput(threads_count) {}
auto StopWorkers() {
is_end_of_infinite_loop = true;
return FileOutput::StopWorkers();
}
void Output(const std::size_t timestamp, std::shared_ptr<const std::list<std::string>>& data) override {
AddTask([this, timestamp, data]() {
std::unique_lock<std::shared_timed_mutex> lock_filenames(filenames_mutex);
processed_filenames.push_back(MakeFilename(timestamp, 0));
lock_filenames.unlock();
std::shared_lock<std::shared_timed_mutex> lock_statistics(statistics_mutex);
auto statistics = threads_statistics.find(std::this_thread::get_id());
if(std::cend(threads_statistics) == statistics)
throw std::runtime_error("FileOutput::Output. Statistics for this thread doesn't exist.");
lock_statistics.unlock();
while(!is_end_of_infinite_loop) {
// Каждый поток модифицирует только свою статистику, поэтому безопасно ее модифицировать без блокировки.
++statistics->second.blocks;
for(auto i{0}; i < 10000; ++i) {
std::for_each(std::cbegin(*data),
std::cend(*data),
[&statistics] (const auto& str) {
statistics->second.commands += std::hash<std::string>()(str);
});
}
WriteBulkToFile(timestamp, *data, 0);
}
});
}
private:
std::atomic_bool is_end_of_infinite_loop{false};
};
static char buffer_file_io[1024] __attribute__ ((__aligned__ (1024)));
void benchmark_iteration(size_t threads_count,
std::chrono::seconds iteration_period) {
FileOutputWithCPUOverhead thread_pool;
std::shared_ptr<const std::list<std::string>> data{ new std::list<std::string>{"cmd1", "cmd2", "cmd3"}};
for(decltype(threads_count) i{0}; i < threads_count; ++i) {
thread_pool.AddWorker();
thread_pool.Output(i, data);
}
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(iteration_period);
auto files_statistics = thread_pool.StopWorkers();
auto end = std::chrono::high_resolution_clock::now();
auto filenames = thread_pool.GetProcessedFilenames();
for(const auto& filename : filenames) {
std::remove(filename.c_str());
}
size_t total_blocks{0};
for(const auto& file_statistics : files_statistics) {
total_blocks += file_statistics.second.blocks;
}
std::cout << threads_count
<< " : "
<< total_blocks
<< " : "
<< (1000 * static_cast<double>(total_blocks) / (threads_count * std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count()))
<< std::endl;
}
void benchmark_iteration(size_t threads_count,
std::chrono::seconds iteration_period,
int fd,
size_t filesize) {
FileOutputWithCPUOverhead thread_pool;
std::shared_ptr<const std::list<std::string>> data{ new std::list<std::string>{"cmd1", "cmd2", "cmd3"}};
size_t read_counts{0};
for(decltype(threads_count) i{0}; i < threads_count; ++i) {
thread_pool.AddWorker();
thread_pool.Output(i, data);
}
auto start = std::chrono::high_resolution_clock::now();
auto file_read_end = std::chrono::high_resolution_clock::now();
while(iteration_period > std::chrono::duration_cast<std::chrono::seconds>(file_read_end-start)) {
BOOST_REQUIRE(0 == lseek(fd, 0, SEEK_SET));
for(size_t i{0}; i < filesize/sizeof(buffer_file_io); ++i) {
BOOST_REQUIRE(sizeof(buffer_file_io) == read(fd, buffer_file_io, sizeof(buffer_file_io)));
++read_counts;
}
file_read_end = std::chrono::high_resolution_clock::now();
}
auto files_statistics = thread_pool.StopWorkers();
auto end = std::chrono::high_resolution_clock::now();
auto filenames = thread_pool.GetProcessedFilenames();
for(const auto& filename : filenames) {
std::remove(filename.c_str());
}
size_t total_blocks{0};
for(const auto& file_statistics : files_statistics) {
total_blocks += file_statistics.second.blocks;
}
std::cout << threads_count
<< " : "
<< total_blocks
<< " : "
<< (0 == threads_count ? 0 :
(1000 * static_cast<double>(total_blocks) / (threads_count * std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count())))
<< " : "
<< (1000 * static_cast<double>(read_counts) / std::chrono::duration_cast<std::chrono::milliseconds>(file_read_end-start).count())
<< std::endl;
}
BOOST_AUTO_TEST_SUITE(test_suite_main)
BOOST_AUTO_TEST_CASE(benchmark_without_file_reading)
{
const size_t max_threads_count = 3 * std::thread::hardware_concurrency();
const std::chrono::seconds iteration_period{10};
std::cout << "Тест производительности многопоточной записи блоков в файлы.\n"
<< "Внимание! Данный тест будет выполняться не менее " << max_threads_count * iteration_period.count() << " секунд.\n"
<< "Одновременно возможно выполнение " << std::thread::hardware_concurrency() << " потоков.\n"
<< "Значения столбцов:\n"
<< "1. Количество потоков записи в файл.\n"
<< "2. Общее количество записанных блоков.\n"
<< "3. Среднее количество блоков, записываемых потоками в секунду.\n";
for(size_t i{1}; i <= max_threads_count; ++i) {
benchmark_iteration(i, iteration_period);
}
}
BOOST_AUTO_TEST_CASE(benchmark_with_file_reading)
{
const size_t max_threads_count = 3 * std::thread::hardware_concurrency();
const std::chrono::seconds iteration_period{10};
const std::string filename {"benchmark.dat"};
const size_t filesize = 512*sizeof(buffer_file_io);
std::fill(std::begin(buffer_file_io), std::end(buffer_file_io), 0xAC);
auto fd = open(filename.c_str(), O_CREAT | O_RDWR | O_DIRECT | O_SYNC, S_IRWXU | S_IRWXG | S_IRWXO);
BOOST_REQUIRE(-1 != fd);
for(size_t i{0}; i < filesize/sizeof(buffer_file_io); ++i) {
if(sizeof(buffer_file_io) != write(fd, buffer_file_io, sizeof(buffer_file_io))) {
close(fd);
std::remove(filename.c_str());
BOOST_FAIL("Ошибка создания файла для чтения.");
}
}
BOOST_REQUIRE(0 == lseek(fd, 0, SEEK_SET));
std::cout << "Тест производительности многопоточной записи блоков в файлы и одновременного чтения из файла.\n"
<< "Внимание! Данный тест будет выполняться не менее " << max_threads_count * iteration_period.count() << " секунд.\n"
<< "Одновременно возможно выполнение " << std::thread::hardware_concurrency() << " потоков.\n"
<< "Значения столбцов:\n"
<< "1. Количество потоков записи в файл.\n"
<< "2. Общее количество записанных блоков.\n"
<< "3. Среднее количество блоков, записываемых потоками в секунду.\n"
<< "4. Скорость чтения файла основным потом в КБ/с.\n";
for(size_t i{0}; i <= max_threads_count; ++i) {
benchmark_iteration(i, iteration_period, fd, filesize);
}
BOOST_REQUIRE(0 == close(fd));
std::remove(filename.c_str());
}
BOOST_AUTO_TEST_SUITE_END()
| true |
7f154457055b2efbc21189761632f09a52f850b2 | C++ | mister345/WorkSamples | /Platformer/Platformer/Assets/D3DGraphics.cpp | UTF-8 | 9,725 | 2.515625 | 3 | [] | no_license | /***************************************************************************************
* File: D3DGraphics.cpp *
* *
* Author: Gregory Weiner *
* Version: 1.0 8.21.2014 *
* Last Modified: 11.17.2014 *
* License: Free Software (GNU License Included) *
* Purpose: This is part of a DirectX 9 framework for powering Win32 graphics *
* for 2D games. Many thanks to Chili and his excellent tutorials in *
* game programming with C++ for making this possible. *
* *
* Description: Main graphics class using D3D API. Includes a simple PutPixel() *
* function that takes int values for rgb and outputs a single pixel *
* to the screen. Several more complex vector art functions are built *
* on top of this using trigonometry, such as DrawCircle, DrawDisc, *
* and DrawLine. DrawChar and DrawString are for in-game font loading. *
* DrawSurface is used for sprites. *
* *
* BeginFrame() and EndFrame() are the core functions for interacting *
* with the GPU to draw to the final output by locking and unlocking *
* the backbuffer, presenting to the output device, etc. The D3D Device *
* is created, and settings such as Swap Effect type initialized, in *
* the constructor. *
* *
* Requirements: Latest Visual Studio C++ compiler recommended. *
* Runs in windowed mode. *
* *
***************************************************************************************/
#include "D3DGraphics.h"
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <GdiPlus.h>
#include "Bitmap.h"
#include "FrameTimer.h"
#pragma comment( lib,"gdiplus.lib" )
void LoadFont( Font* font,D3DCOLOR* surface,const char* filename,
int charWidth,int charHeight,int nCharsPerRow )
{
LoadBmp( filename,surface );
font->charHeight = charHeight;
font->charWidth = charWidth;
font->nCharsPerRow = nCharsPerRow;
font->surface = surface;
}
D3DGraphics::D3DGraphics( HWND hWnd )
:
pDirect3D( NULL ),
pDevice( NULL ),
pBackBuffer( NULL ),
pSysBuffer( NULL )
{
HRESULT result;
backRect.pBits = NULL;
pDirect3D = Direct3DCreate9( D3D_SDK_VERSION );
assert( pDirect3D != NULL );
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp,sizeof( d3dpp ) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
d3dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
result = pDirect3D->CreateDevice( D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE,&d3dpp,&pDevice );
assert( !FAILED( result ) );
result = pDevice->GetBackBuffer( 0,0,D3DBACKBUFFER_TYPE_MONO,&pBackBuffer );
assert( !FAILED( result ) );
pSysBuffer = new D3DCOLOR[ SCREENWIDTH * SCREENHEIGHT ];
}
D3DGraphics::~D3DGraphics()
{
if( pDevice )
{
pDevice->Release();
pDevice = NULL;
}
if( pDirect3D )
{
pDirect3D->Release();
pDirect3D = NULL;
}
if( pBackBuffer )
{
pBackBuffer->Release();
pBackBuffer = NULL;
}
if( pSysBuffer )
{
delete pSysBuffer;
pSysBuffer = NULL;
}
}
void D3DGraphics::PutPixel( int x,int y,int r,int g,int b )
{
assert( x >= 0 );
assert( y >= 0 );
assert( x < SCREENWIDTH );
assert( y < SCREENHEIGHT );
pSysBuffer[ x + SCREENWIDTH * y ] = D3DCOLOR_XRGB( r,g,b );
}
void D3DGraphics::PutPixel( int x,int y,D3DCOLOR c )
{
assert( x >= 0 );
assert( y >= 0 );
assert( x < SCREENWIDTH );
assert( y < SCREENHEIGHT );
pSysBuffer[ x + SCREENWIDTH * y ] = c;
}
D3DCOLOR D3DGraphics::GetPixel( int x,int y )
{
assert( x >= 0 );
assert( y >= 0 );
assert( x < SCREENWIDTH );
assert( y < SCREENHEIGHT );
return pSysBuffer[ x + SCREENWIDTH * y ];
}
void D3DGraphics::BeginFrame()
{
memset( pSysBuffer,FILLVALUE,sizeof( D3DCOLOR ) * SCREENWIDTH * SCREENHEIGHT );
}
void D3DGraphics::EndFrame()
{
HRESULT result;
result = pBackBuffer->LockRect( &backRect,NULL,NULL );
assert( !FAILED( result ) );
for( int y = 0; y < SCREENHEIGHT; y++ )
{
memcpy( &((BYTE*)backRect.pBits)[ backRect.Pitch * y ],&pSysBuffer[ SCREENWIDTH * y ],sizeof( D3DCOLOR ) * SCREENWIDTH );
}
result = pBackBuffer->UnlockRect();
assert( !FAILED( result ) );
result = pDevice->Present( NULL,NULL,NULL,NULL );
assert( !FAILED( result ) );
}
void D3DGraphics::DrawDisc( int cx,int cy,int r,int rd,int g,int b )
{
for( int x = cx - r; x < cx + r; x++ )
{
for( int y = cy - r; y < cy + r; y++ )
{
if( sqrt( (float)( (x - cx)*(x - cx) + (y - cy)*(y - cy) ) ) < r )
{
PutPixel( x,y,rd,g,b );
}
}
}
}
void D3DGraphics::DrawLine( int x1,int y1,int x2,int y2,int r,int g,int blu )
{
int dx = x2 - x1;
int dy = y2 - y1;
if( dy == 0 && dx == 0 )
{
PutPixel( x1,y1,r,g,blu );
}
else if( abs( dy ) > abs( dx ) )
{
if( dy < 0 )
{
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
float m = (float)dx / (float)dy;
float b = x1 - m*y1;
for( int y = y1; y <= y2; y = y + 1 )
{
int x = (int)(m*y + b + 0.5f);
PutPixel( x,y,r,g,blu );
}
}
else
{
if( dx < 0 )
{
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
float m = (float)dy / (float)dx;
float b = y1 - m*x1;
for( int x = x1; x <= x2; x = x + 1 )
{
int y = (int)(m*x + b + 0.5f);
PutPixel( x,y,r,g,blu );
}
}
}
void D3DGraphics::DrawCircle( int centerX,int centerY,int radius,int r,int g,int b )
{
int rSquared = radius*radius;
int xPivot = (int)(radius * 0.707107f + 0.5f);
for( int x = 0; x <= xPivot; x++ )
{
int y = (int)(sqrt( (float)( rSquared - x*x ) ) + 0.5f);
PutPixel( centerX + x,centerY + y,r,g,b );
PutPixel( centerX - x,centerY + y,r,g,b );
PutPixel( centerX + x,centerY - y,r,g,b );
PutPixel( centerX - x,centerY - y,r,g,b );
PutPixel( centerX + y,centerY + x,r,g,b );
PutPixel( centerX - y,centerY + x,r,g,b );
PutPixel( centerX + y,centerY - x,r,g,b );
PutPixel( centerX - y,centerY - x,r,g,b );
}
}
void D3DGraphics::DrawChar( char c,int xoff,int yoff,Font* font,D3DCOLOR color )
{
if( c < ' ' || c > '~' )
return;
const int sheetIndex = c - ' ';
const int sheetCol = sheetIndex % font->nCharsPerRow;
const int sheetRow = sheetIndex / font->nCharsPerRow;
const int xStart = sheetCol * font->charWidth;
const int yStart = sheetRow * font->charHeight;
const int xEnd = xStart + font->charWidth;
const int yEnd = yStart + font->charHeight;
const int surfWidth = font->charWidth * font->nCharsPerRow;
for( int y = yStart; y < yEnd; y++ )
{
for( int x = xStart; x < xEnd; x++ )
{
if( font->surface[ x + y * surfWidth ] == D3DCOLOR_XRGB( 0,0,0 ) )
{
PutPixel( x + xoff - xStart,y + yoff - yStart,color );
}
}
}
}
void D3DGraphics::DrawString( const char* string,int xoff,int yoff,Font* font,D3DCOLOR color )
{
for( int index = 0; string[ index ] != '\0'; index++ )
{
DrawChar( string[ index ],xoff + index * font->charWidth,yoff,font,color );
}
}
void D3DGraphics::DrawSolidRect(RectI rect, D3DCOLOR color, /*const*/ RectI & clippingBox)
{
rect.ClipTo(clippingBox);
for (int iy = rect.top; iy < rect.bottom; iy++)
{
for (int ix = rect.left; ix < rect.right; ix++)
{
PutPixel(ix, iy, color);
}
}
}
void D3DGraphics::DrawRect(RectI rect, int r, int g, int b)
{
DrawLine(rect.left, rect.top, rect.right, rect.top, r, g, b);
DrawLine(rect.right, rect.top, rect.right, rect.bottom, r, g, b);
DrawLine(rect.right, rect.bottom, rect.left, rect.bottom, r, g, b);
DrawLine(rect.left, rect.top, rect.left, rect.bottom, r, g, b);
}
void D3DGraphics::DrawSurface(D3DCOLOR* pixels, D3DCOLOR key, int width, int height, int x, int y, /*const*/ RectI& clippingBox)
{
RectI rect(y, y + height, x, x + width);
rect.ClipTo(clippingBox);
const int yStart = rect.top - y; // get source rectangle back
const int xStart = rect.left - x;
const int yEnd = rect.bottom - y;
const int xEnd = rect.right - x;
for (int iy = yStart; iy < yEnd; iy++)
{
for (int ix = xStart; ix < xEnd; ix++)
{
D3DCOLOR srcPixel = pixels[ix + iy * width];
if (srcPixel != key)
{
// "The object has type qualifiers that prevent a match"
PutPixel(ix + x, iy + y, srcPixel);
}
}
}
}
| true |
5e48a3962cf4f40b8dd66511908d6372c9b6909a | C++ | ayoubHam2000/fs_licence | /s5_repository/c++/exams/exam2020/list.cpp | UTF-8 | 2,131 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include "list.h"
List::List(int size){
capacite = size;
nbelement = 0;
data = new T[size];
}
List::List(T* d, int size){
capacite = size;
nbelement = size;
data = new T[size];
for(int i = 0; i < size; i++)
data[i] = d[i];
}
List::List(const List &a){
delete []data;
data = new T[a.capacite];
capacite = a.capacite;
nbelement = a.nbelement;
for(int i = 0; i < nbelement; i++)
data[i] = a.data[i];
}
List::~List(){
delete[] data;
}
const List& List::operator=(const List &a){
*this = a; //copy constructor;
return *this;
}
T& List::operator[](int index){
return data[index];
}
bool List::operator%(T a){
for(int i = 0; i < nbelement; i++)
if(data[i] == a)
return true;
return false;
}
void List::operator<<(T a){
if(nbelement < capacite){
data[nbelement] = a;
nbelement++;
}else{
T* newD = new T[capacite + CAPACITE_PLUS];
for(int i = 0; i < capacite; i++)
newD[i] = data[i];
newD[capacite] = a;
delete[] data;
data = newD;
nbelement++;
}
}
void operator>>(T& e, List &l){
if(l.nbelement < l.capacite){
for(int i = l.nbelement - 1; i >= 0; i--)
l.data[i + 1] = l.data[i];
l.data[0] = e;
l.nbelement++;
}else{
T* newD = new T[l.capacite + CAPACITE_PLUS];
newD[0] = e;
for(int i = 0; i < l.capacite; i++)
newD[i + 1] = l.data[i];
delete[] l.data;
l.data = newD;
l.nbelement++;
}
}
void operator<<(T&e, List &l){
e = l.data[0];
l.nbelement--;
for(int i = 0; i < l.nbelement; i++)
l.data[i] = l.data[i + 1];
}
void List::operator>>(T &a){
a = this->data[this->nbelement];
nbelement--;
}
std::ostream &operator<<(std::ostream &stream, const List &l){
for(int i = 0; i < l.nbelement; i++)
stream << l.data[i] << ", ";
return stream;
}
int main(){
T e = 10.2;
List l = List(10);
l << e;
std::cout << l << std::endl;
return 0;
}
| true |
edffec3ace2aa0e877b8ffe9743d922ba33bc7b3 | C++ | bosecodes/CP-by-bosecodes | /30 days coding challenge/Dynamic Programming/fibonacci_dp.cpp | UTF-8 | 623 | 3.328125 | 3 | [] | no_license | // Fibonacci Series
// Using Dynamic Programming
// Somdev Basu
// Waste time with the masterpiece
#include <bits/stdc++.h>
using namespace std;
int fibo(int n, vector<int> &dp) {
int i = 0;
if(n <= 1)
return n;
// check if previously visited state has been visited or not
if(dp[n] != -1)
return dp[n];
else
dp[n] = fibo(n-1, dp) + fibo(n-2, dp);
return dp[n];
}
int main() {
int n;
cin >> n;
// initially mark every element as -1
// which means none of them have been visited
vector<int> dp(n+1, -1);
int ans = fibo(n, dp);
cout << ans;
}
| true |
9df24fb301867a08e851d42beaa504632e4bb594 | C++ | stalker5217/algorithm | /BAEKJOON/2587.cpp | UTF-8 | 490 | 2.78125 | 3 | [] | no_license | #define DEBUG 0
#define LOG(string) cout << string
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int avg;
int sum = 0;
vector<int> arr;
for(int i = 0 ; i < 5 ; i++){
int temp;
cin >> temp;
sum += temp;
arr.push_back(temp);
}
avg = sum / 5;
sort(arr.begin(), arr.end());
cout << avg << "\n" << arr[2];
return 0;
}
| true |
c6fa0ecc0cc85b05a61fddf7ff82d0610ac7f64c | C++ | adityanjr/code-DS-ALGO | /LeetCode-Challenges/2020/6. June/26.cpp | UTF-8 | 1,221 | 3.9375 | 4 | [
"MIT"
] | permissive | /*
Sum Root to Leaf Numbers
------------------------
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
return getSum(root, 0);
}
int getSum(TreeNode *node, int sum) {
if (node == NULL) return 0;
int current_sum = sum * 10 + node->val;
if (node->left == NULL && node->right == NULL) return current_sum;
return getSum(node->left, current_sum) + getSum(node->right, current_sum);
}
}; | true |
819c7b67020150cfc66c5f60779e0a227a60eb2e | C++ | AndyLem/arduino_experiments | /led8.h | UTF-8 | 1,884 | 2.71875 | 3 | [
"MIT"
] | permissive | #ifndef led8_h
#define led8_h
#include "Arduino.h"
struct SYMBOL
{
char Symbol;
char Code;
};
class Led8
{
protected:
int _data;
int _clock;
int _latch;
#define SYMBOLS_COUNT 24
SYMBOL const _symbols[SYMBOLS_COUNT] = {
// 76543210
{ '0', B11000000 },
{ '1', B11111001 },
{ '2', B10100100 },
{ '3', B10110000 },
{ '4', B10011001 },
{ '5', B10010010 },
{ '6', B10000010 },
{ '7', B11111000 },
{ '8', B10000000 },
{ '9', B10010000 },
{ '-', B10111111 },
{ 'A', B10001000 },
{ 'B', B10000011 },
{ 'C', B11000110 },
{ 'D', B10100001 },
{ 'E', B10000110 },
{ 'F', B10001110 },
{ 'H', B10001001 },
{ 'L', B11000111 },
{ 'O', B11000000 },
{ 'P', B10001100 },
{ 'S', B10010010 },
{ 'U', B11000001 },
{ 'Y', B10010001 },
};
int const _space = 0xFF;
int _buf[8];
int _cursor = 0;
#define DISPLAY_LENGTH 8
void moveRight(int steps);
void update();
void outputBinary(int pos, int binary);
char getBinaryCode(char symbol);
String padLeftAndTrim(String value, int length);
public:
void setBinary(int pos, int binary);
void andBinary(int pos, int binary);
void orBinary(int pos, int binary);
void init(int dataPin, int clockPin, int latchPin);
void clear();
void printBinary(int pos, int binary);
void printBinary(int binary);
void putBinary(int binary);
void print(int pos, String value);
void print(int pos, int value);
void print(int pos, String value, int fieldLength);
void print(int pos, int value, int fieldLength);
void print(String value);
void print(int value);
void put(String value);
void printSpace();
void moveTo(int pos);
void moveToStart();
void tick(int millis);
};
#endif
| true |
d647512dab268fb7d70bb2be4962c1d531782ce7 | C++ | arunyalamarthy/MultiFormatLogger | /MultiFormatLogger/Logger.cpp | UTF-8 | 4,027 | 2.671875 | 3 | [] | no_license | // Logger.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include <ILogger.h>
#include "Logger.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <atlstr.h>
#include <atltime.h>
using namespace std;
CLogger :: CLogger()
{
m_filename = nullptr;
m_LogLevel = LOG_LEVEL_ERROR;
m_LogType = OUTPUT_DEBUG_LOG;
}
CLogger ::~CLogger(void)
{
//ending html
if (m_LogType == HTML_FILE_LOG)
m_File << "</body></html>";
//myfile.close();
m_File.close();
}
bool CLogger ::EnableLog(LogLevel level, LogType type, const TCHAR* filename)
{
USES_CONVERSION;
m_LogLevel = level;
m_filename = filename;
LogType prevLogtype = m_LogType;
m_LogType = type;
if (m_LogType == FILE_LOG)
{
if (m_filename)
{
m_File.open((m_filename));
//ofstream myfile;
//m_File.open("report.html");
m_File << "<!DOCTYPE html><html><head></head><body>"; //starting html
}
else
{
m_LogType = prevLogtype;
return false;
}
}
if (m_LogType == HTML_FILE_LOG)
{
if (m_filename)
{
//ensure it ends with html or append it
m_File.open((m_filename));
m_File << "<!DOCTYPE html><html><head></head><body>"; //starting html
}
else
{
m_LogType = prevLogtype;
return false;
}
}
return true;
}
void CLogger ::DisableLog()
{
m_LogLevel = LOG_LEVEL_NONE;
}
void CLogger ::LOG_ERROR(const TCHAR *lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
TCHAR szBuffer[8192] = {};
_vsntprintf_s(szBuffer, _countof(szBuffer), _TRUNCATE,lpszFormat, args);
CString strDebug;
strDebug.Format(_T("%s:%s"), _T("[ERROR]:"), szBuffer);
log(strDebug, LOG_LEVEL_ERROR);
va_end(args);
}
void CLogger ::LOG_DEBUG(const TCHAR *lpszFormat, ...)
{
va_list args = nullptr;
va_start(args, lpszFormat);
TCHAR szBuffer[8192] = {};
_vsntprintf_s(szBuffer, _countof(szBuffer), _TRUNCATE, lpszFormat, args);
CString strDebug;
strDebug.Format(_T("%s:%s"), _T("[DEBUG]:"), szBuffer);
log(strDebug, LOG_LEVEL_DEBUG);
va_end(args);
}
void CLogger ::LOG_INFO(const TCHAR *lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
TCHAR szBuffer[8192] = {};
_vsntprintf_s(szBuffer, _countof(szBuffer), _TRUNCATE,lpszFormat, args);
CString strDebug;
strDebug.Format(_T("%s:%s"), _T("[INFO]:"), szBuffer);
log(strDebug, LOG_LEVEL_INFO);
va_end(args);
}
void CLogger ::log(CString& data, LogLevel level)
{
if (level <= m_LogLevel)
{
if(m_LogType == FILE_LOG)
{
logIntoFile(data);
}
else if(m_LogType == CONSOLE_LOG)
{
logOnConsole(data);
}
else if (m_LogType == HTML_FILE_LOG)
{
logHtml(data, level);
}
else
{
::OutputDebugString(data);
}
}
}
void CLogger ::logIntoFile(CString& data)
{
USES_CONVERSION;
CTime atime = CTime::GetCurrentTime();
CString cur_time = atime.Format(_T("%x:%X"));
m_File << (cur_time.GetString()) << (data.GetString()) << endl;
}
void CLogger ::logOnConsole(CString& data)
{
CTime atime;
atime = CTime::GetCurrentTime();
CStringW cur_time = atime.Format(_T("%x:%X"));
printf("\n %s:%s", cur_time.GetString(), data.GetString());
}
void CLogger::logHtml(CString& data, LogLevel level)
{
CTime atime;
atime = CTime::GetCurrentTime();
CStringW cur_time = atime.Format(_T("%x:%X"));
CString prefix;
if (level == LOG_LEVEL_INFO)
{
prefix = "<p style = 'color:green'>";
}
else if (level == LOG_LEVEL_DEBUG)
{
prefix = "<p style = 'color:blue'>";
}
else //error
{
prefix = "<p style = 'color:red'>";
}
m_File <<prefix<< (cur_time.GetString()) << (data.GetString()) << "</p>"<<endl;
}
void CLogger ::logRelease()
{
//not needed right now
}
/********************************************************************************************/
LOGAPI ILogger* GetLogger()
{
static CLogger aLogger;
return &aLogger;
}
| true |
386bf84dea16035af19ca6cc26c027a1e95ae263 | C++ | YossiMH/PSMoveService | /src/psmoveclient/ClientGeometry.cpp | UTF-8 | 18,164 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | //-- includes -----
#include "ClientGeometry.h"
#include "MathUtility.h"
#include "MathGLM.h"
#include <algorithm>
//-- pre-declarations -----
//-- constants -----
const PSMoveFloatVector3 g_psmove_float_vector3_zero= {0.f, 0.f, 0.f};
const PSMoveFloatVector3 *k_psmove_float_vector3_zero= &g_psmove_float_vector3_zero;
const PSMoveFloatVector3 g_psmove_float_vector3_one= {1.f, 1.f, 1.f};
const PSMoveFloatVector3 *k_psmove_float_vector3_one= &g_psmove_float_vector3_one;
const PSMoveFloatVector3 g_psmove_float_vector3_i = { 1.f, 0.f, 0.f };
const PSMoveFloatVector3 *k_psmove_float_vector3_i = &g_psmove_float_vector3_i;
const PSMoveFloatVector3 g_psmove_float_vector3_j = { 0.f, 1.f, 0.f };
const PSMoveFloatVector3 *k_psmove_float_vector3_j = &g_psmove_float_vector3_j;
const PSMoveFloatVector3 g_psmove_float_vector3_k = { 0.f, 0.f, 1.f };
const PSMoveFloatVector3 *k_psmove_float_vector3_k = &g_psmove_float_vector3_k;
const PSMoveIntVector3 g_psmove_int_vector3_zero= {0, 0, 0};
const PSMoveIntVector3 *k_psmove_int_vector3_zero= &g_psmove_int_vector3_zero;
const PSMoveIntVector3 g_psmove_int_vector3_one= {1, 1, 1};
const PSMoveIntVector3 *k_psmove_int_vector3_one= &g_psmove_int_vector3_one;
const PSMovePosition g_psmove_position_origin= {0.f, 0.f, 0.f};
const PSMovePosition *k_psmove_position_origin= &g_psmove_position_origin;
const PSMoveQuaternion g_psmove_quaternion_identity= {1.f, 0.f, 0.f, 0.f};
const PSMoveQuaternion *k_psmove_quaternion_identity= &g_psmove_quaternion_identity;
const PSMoveMatrix3x3 g_psmove_matrix_identity = { 1.f, 0.f, 0.f , 0.f, 1.f, 0.f, 0.f, 0.f, 1.f };
const PSMoveMatrix3x3 *k_psmove_matrix_identity = &g_psmove_matrix_identity;
const PSMovePose g_psmove_pose_identity = { g_psmove_position_origin, g_psmove_quaternion_identity };
const PSMovePose *k_psmove_pose_identity = &g_psmove_pose_identity;
//-- methods -----
// -- PSMoveFloatVector3 --
PSMoveFloatVector2 PSMoveFloatVector2::create(float i, float j)
{
PSMoveFloatVector2 v;
v.i = i;
v.j = j;
return v;
}
PSMoveFloatVector2 PSMoveFloatVector2::operator + (const PSMoveFloatVector2 &other) const
{
return PSMoveFloatVector2::create(i + other.i, j + other.j);
}
PSMoveFloatVector2 PSMoveFloatVector2::operator - (const PSMoveFloatVector2 &other) const
{
return PSMoveFloatVector2::create(i - other.i, j - other.j);
}
PSMoveFloatVector2 PSMoveFloatVector2::operator * (const float s) const
{
return PSMoveFloatVector2::create(i*s, j*s);
}
PSMoveFloatVector2 PSMoveFloatVector2::unsafe_divide(const float s) const
{
return PSMoveFloatVector2::create(i / s, j / s);
}
PSMoveFloatVector2 PSMoveFloatVector2::unsafe_divide(const PSMoveFloatVector2 &v) const
{
return PSMoveFloatVector2::create(i / v.i, j / v.j);
}
PSMoveFloatVector2 PSMoveFloatVector2::safe_divide(const float s, const PSMoveFloatVector2 &default_result) const
{
return !is_nearly_zero(s) ? unsafe_divide(s) : default_result;
}
PSMoveFloatVector2 PSMoveFloatVector2::safe_divide(const PSMoveFloatVector2 &v, const PSMoveFloatVector2 &default_result) const
{
return
PSMoveFloatVector2::create(
!is_nearly_zero(v.i) ? i / v.i : default_result.i,
!is_nearly_zero(v.j) ? j / v.j : default_result.j);
}
PSMoveFloatVector2 PSMoveFloatVector2::abs() const
{
return PSMoveFloatVector2::create(fabsf(i), fabsf(j));
}
PSMoveFloatVector2 PSMoveFloatVector2::square() const
{
return PSMoveFloatVector2::create(i*i, j*j);
}
float PSMoveFloatVector2::length() const
{
return sqrtf(i*i + j*j);
}
float PSMoveFloatVector2::normalize_with_default(const PSMoveFloatVector2 &default_result)
{
const float divisor = length();
*this = this->safe_divide(divisor, default_result);
return divisor;
}
float PSMoveFloatVector2::minValue() const
{
return std::min(i, j);
}
float PSMoveFloatVector2::maxValue() const
{
return std::max(i, j);
}
float PSMoveFloatVector2::dot(const PSMoveFloatVector2 &a, const PSMoveFloatVector2 &b)
{
return a.i*b.i + a.j*b.j;
}
PSMoveFloatVector2 PSMoveFloatVector2::min(const PSMoveFloatVector2 &a, const PSMoveFloatVector2 &b)
{
return PSMoveFloatVector2::create(std::min(a.i, b.i), std::min(a.j, b.j));
}
PSMoveFloatVector2 PSMoveFloatVector2::max(const PSMoveFloatVector2 &a, const PSMoveFloatVector2 &b)
{
return PSMoveFloatVector2::create(std::max(a.i, b.i), std::max(a.j, b.j));
}
// -- PSMoveFloatVector3 --
PSMoveFloatVector3 PSMoveFloatVector3::create(float i, float j, float k)
{
PSMoveFloatVector3 v;
v.i= i;
v.j= j;
v.k= k;
return v;
}
PSMovePosition PSMoveFloatVector3::castToPSMovePosition() const
{
return PSMovePosition::create(i, j, k);
}
PSMoveFloatVector3 PSMoveFloatVector3::operator + (const PSMoveFloatVector3 &other) const
{
return PSMoveFloatVector3::create(i + other.i, j + other.j, k + other.k);
}
PSMoveFloatVector3 PSMoveFloatVector3::operator - (const PSMoveFloatVector3 &other) const
{
return PSMoveFloatVector3::create(i - other.i, j - other.j, k - other.k);
}
PSMoveFloatVector3 PSMoveFloatVector3::operator * (const float s) const
{
return PSMoveFloatVector3::create(i*s, j*s, k*s);
}
PSMoveFloatVector3 PSMoveFloatVector3::unsafe_divide(const float s) const
{
return PSMoveFloatVector3::create(i/s, j/s, k/s);
}
PSMoveFloatVector3 PSMoveFloatVector3::unsafe_divide(const PSMoveFloatVector3 &v) const
{
return PSMoveFloatVector3::create(i/v.i, j/v.j, k/v.k);
}
PSMoveFloatVector3 PSMoveFloatVector3::safe_divide(const float s, const PSMoveFloatVector3 &default_result) const
{
return !is_nearly_zero(s) ? unsafe_divide(s) : default_result;
}
PSMoveFloatVector3 PSMoveFloatVector3::safe_divide(const PSMoveFloatVector3 &v, const PSMoveFloatVector3 &default_result) const
{
return
PSMoveFloatVector3::create(
!is_nearly_zero(v.i) ? i/v.i : default_result.i,
!is_nearly_zero(v.j) ? j/v.j : default_result.j,
!is_nearly_zero(v.k) ? k/v.k : default_result.k);
}
float PSMoveFloatVector3::length() const
{
return sqrtf(i*i + j*j + k*k);
}
float PSMoveFloatVector3::normalize_with_default(const PSMoveFloatVector3 &default_result)
{
const float divisor= length();
*this= this->safe_divide(divisor, default_result);
return divisor;
}
PSMoveFloatVector3 PSMoveFloatVector3::abs() const
{
return PSMoveFloatVector3::create(fabsf(i), fabsf(j), fabsf(k));
}
PSMoveFloatVector3 PSMoveFloatVector3::square() const
{
return PSMoveFloatVector3::create(i*i, j*j, k*k);
}
float PSMoveFloatVector3::minValue() const
{
return std::min(std::min(i, j), k);
}
float PSMoveFloatVector3::maxValue() const
{
return std::max(std::max(i, j), k);
}
float PSMoveFloatVector3::dot(const PSMoveFloatVector3 &a, const PSMoveFloatVector3 &b)
{
return a.i*b.i + a.j*b.j + a.k*b.k;
}
PSMoveFloatVector3 PSMoveFloatVector3::cross(const PSMoveFloatVector3 &a, const PSMoveFloatVector3 &b)
{
return PSMoveFloatVector3::create(a.j*b.k - b.j*a.k, a.i*b.k - b.i*a.k, a.i*b.j - b.i*a.j);
}
PSMoveFloatVector3 PSMoveFloatVector3::min(const PSMoveFloatVector3 &a, const PSMoveFloatVector3 &b)
{
return PSMoveFloatVector3::create(std::min(a.i, b.i), std::min(a.j, b.j), std::min(a.k, b.k));
}
PSMoveFloatVector3 PSMoveFloatVector3::max(const PSMoveFloatVector3 &a, const PSMoveFloatVector3 &b)
{
return PSMoveFloatVector3::create(std::max(a.i, b.i), std::max(a.j, b.j), std::max(a.k, b.k));
}
// -- PSMoveIntVector3 --
PSMoveIntVector3 PSMoveIntVector3::create(int i, int j, int k)
{
PSMoveIntVector3 v;
v.i= i;
v.j= j;
v.k= k;
return v;
}
PSMoveFloatVector3 PSMoveIntVector3::castToFloatVector3() const
{
return PSMoveFloatVector3::create(static_cast<float>(i), static_cast<float>(j), static_cast<float>(k));
}
PSMoveIntVector3 PSMoveIntVector3::operator + (const PSMoveIntVector3 &other) const
{
return PSMoveIntVector3::create(i + other.i, j + other.j, k + other.k);
}
PSMoveIntVector3 PSMoveIntVector3::operator - (const PSMoveIntVector3 &other) const
{
return PSMoveIntVector3::create(i - other.i, j - other.j, k - other.k);
}
PSMoveIntVector3 PSMoveIntVector3::unsafe_divide(const int s) const
{
return PSMoveIntVector3::create(i/s, j/s, k/s);
}
PSMoveIntVector3 PSMoveIntVector3::unsafe_divide(const PSMoveIntVector3 &v) const
{
return PSMoveIntVector3::create(i/v.i, j/v.j, k/v.k);
}
PSMoveIntVector3 PSMoveIntVector3::safe_divide(const int s, const PSMoveIntVector3 &default_result) const
{
return s != 0 ? unsafe_divide(s) : default_result;
}
PSMoveIntVector3 PSMoveIntVector3::safe_divide(const PSMoveIntVector3 &v, const PSMoveIntVector3 &default_result) const
{
return
PSMoveIntVector3::create(
v.i != 0 ? i/v.i : default_result.i,
v.j != 0 ? j/v.j : default_result.j,
v.k != 0 ? k/v.k : default_result.k);
}
PSMoveIntVector3 PSMoveIntVector3::abs() const
{
return PSMoveIntVector3::create(std::abs(i), std::abs(j), std::abs(k));
}
PSMoveIntVector3 PSMoveIntVector3::square() const
{
return PSMoveIntVector3::create(i*i, j*j, k*k);
}
int PSMoveIntVector3::lengthSquared() const
{
return i*i + j*j + k*k;
}
int PSMoveIntVector3::minValue() const
{
return std::min(std::min(i, j), k);
}
int PSMoveIntVector3::maxValue() const
{
return std::max(std::max(i, j), k);
}
PSMoveIntVector3 PSMoveIntVector3::min(const PSMoveIntVector3 &a, const PSMoveIntVector3 &b)
{
return PSMoveIntVector3::create(std::min(a.i, b.i), std::min(a.j, b.j), std::min(a.k, b.k));
}
PSMoveIntVector3 PSMoveIntVector3::max(const PSMoveIntVector3 &a, const PSMoveIntVector3 &b)
{
return PSMoveIntVector3::create(std::max(a.i, b.i), std::max(a.j, b.j), std::max(a.k, b.k));
}
// -- PSMovePosition --
PSMovePosition PSMovePosition::create(float x, float y, float z)
{
PSMovePosition p;
p.x= x;
p.y= y;
p.z= z;
return p;
}
const PSMovePosition& PSMovePosition::identity()
{
return g_psmove_position_origin;
}
PSMoveFloatVector3 PSMovePosition::toPSMoveFloatVector3() const
{
return PSMoveFloatVector3::create(x, y, z);
}
PSMoveFloatVector3 PSMovePosition::operator - (const PSMovePosition &other) const
{
return PSMoveFloatVector3::create(x - other.x, y - other.y, z - other.z);
}
PSMovePosition PSMovePosition::operator + (const PSMoveFloatVector3 &v) const
{
return PSMovePosition::create(x + v.i, y + v.j, z + v.k);
}
PSMovePosition PSMovePosition::operator - (const PSMoveFloatVector3 &v) const
{
return PSMovePosition::create(x - v.i, y - v.j, z - v.k);
}
PSMovePosition PSMovePosition::operator * (const float s) const
{
return PSMovePosition::create(x*s, y*s, z*s);
}
// -- PSMovePosition --
PSMoveScreenLocation PSMoveScreenLocation::create(float x, float y)
{
PSMoveScreenLocation p;
p.x = x;
p.y = y;
return p;
}
PSMoveFloatVector2 PSMoveScreenLocation::toPSMoveFloatVector2() const
{
return PSMoveFloatVector2::create(x, y);
}
PSMoveFloatVector2 PSMoveScreenLocation::operator - (const PSMoveScreenLocation &other) const
{
return PSMoveFloatVector2::create(x - other.x, y - other.y);
}
// -- PSMoveQuaternion --
// psuedo-constructor to keep this a POD type
PSMoveQuaternion PSMoveQuaternion::create(float w, float x, float y, float z)
{
PSMoveQuaternion q;
q.w = w;
q.x = x;
q.y = y;
q.z = z;
return q;
}
// psuedo-constructor to keep this a POD type
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/
PSMoveQuaternion PSMoveQuaternion::create(const PSMoveFloatVector3 &eulerAngles)
{
PSMoveQuaternion q;
// Assuming the angles are in radians.
float c1 = cosf(eulerAngles.j / 2);
float s1 = sinf(eulerAngles.j / 2);
float c2 = cosf(eulerAngles.k / 2);
float s2 = sinf(eulerAngles.k / 2);
float c3 = cosf(eulerAngles.i / 2);
float s3 = sinf(eulerAngles.i / 2);
float c1c2 = c1*c2;
float s1s2 = s1*s2;
q.w = c1c2*c3 - s1s2*s3;
q.x = c1c2*s3 + s1s2*c3;
q.y = s1*c2*c3 + c1*s2*s3;
q.z = c1*s2*c3 - s1*c2*s3;
return q;
}
const PSMoveQuaternion& PSMoveQuaternion::identity()
{
return g_psmove_quaternion_identity;
}
PSMoveQuaternion PSMoveQuaternion::operator + (const PSMoveQuaternion &other) const
{
return PSMoveQuaternion::create(w + other.w, x + other.x, y + other.y, z + other.z);
}
PSMoveQuaternion PSMoveQuaternion::operator * (const PSMoveQuaternion &other) const
{
return PSMoveQuaternion::create(
w*other.w - x*other.x - y*other.y - z*other.z,
w*other.x + x*other.w + y*other.z - z*other.y,
w*other.y - x*other.z + y*other.w + z*other.x,
w*other.z + x*other.y - y*other.x + z*other.w);
}
PSMoveQuaternion PSMoveQuaternion::unsafe_divide(const float s) const
{
return PSMoveQuaternion::create(w / s, x / s, y / s, z / s);
}
PSMoveQuaternion PSMoveQuaternion::safe_divide(const float s, const PSMoveQuaternion &default_result) const
{
return !is_nearly_zero(s) ? unsafe_divide(s) : default_result;
}
PSMoveQuaternion PSMoveQuaternion::inverse() const
{
return PSMoveQuaternion::create(w, -x, -y, -z);
}
PSMoveQuaternion PSMoveQuaternion::concat(const PSMoveQuaternion &first, const PSMoveQuaternion &second)
{
return second * first;
}
//http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/
PSMoveFloatVector3 PSMoveQuaternion::rotate_vector(const PSMoveFloatVector3 &v) const
{
PSMoveFloatVector3 result;
result.i = w*w*v.i + 2 * y*w*v.k - 2 * z*w*v.j + x*x*v.i + 2 * y*x*v.j + 2 * z*x*v.k - z*z*v.i - y*y*v.i;
result.j = 2 * x*y*v.i + y*y*v.j + 2 * z*y*v.k + 2 * w*z*v.i - z*z*v.j + w*w*v.j - 2 * x*w*v.k - x*x*v.j;
result.k = 2 * x*z*v.i + 2 * y*z*v.j + z*z*v.k - 2 * w*y*v.i - y*y*v.k + 2 * w*x*v.j - x*x*v.k + w*w*v.k;
return result;
}
PSMovePosition PSMoveQuaternion::rotate_position(const PSMovePosition &p) const
{
PSMoveFloatVector3 v = p.toPSMoveFloatVector3();
PSMoveFloatVector3 v_rotated = rotate_vector(v);
PSMovePosition p_rotated = v_rotated.castToPSMovePosition();
return p_rotated;
}
float PSMoveQuaternion::length() const
{
return sqrtf(w*w + x*x + y*y + z*z);
}
PSMoveQuaternion & PSMoveQuaternion::normalize_with_default(const PSMoveQuaternion &default_result)
{
const float divisor = length();
*this = this->safe_divide(divisor, default_result);
return *this;
}
// -- PSMoveMatrix3x3 --
PSMoveMatrix3x3 PSMoveMatrix3x3::create(
const PSMoveFloatVector3 &basis_x,
const PSMoveFloatVector3 &basis_y,
const PSMoveFloatVector3 &basis_z)
{
PSMoveMatrix3x3 mat;
mat.m[0][0] = basis_x.i; mat.m[0][1] = basis_x.j; mat.m[0][2] = basis_x.k;
mat.m[1][0] = basis_y.i; mat.m[1][1] = basis_y.j; mat.m[1][2] = basis_y.k;
mat.m[2][0] = basis_z.i; mat.m[2][1] = basis_z.j; mat.m[2][2] = basis_z.k;
return mat;
}
PSMoveMatrix3x3 PSMoveMatrix3x3::create(const PSMoveQuaternion &q)
{
PSMoveMatrix3x3 mat;
const float qw = q.w;
const float qx = q.x;
const float qy = q.y;
const float qz = q.z;
const float qx2 = q.x*q.x;
const float qy2 = q.y*q.y;
const float qz2 = q.z*q.z;
mat.m[0][0] = 1.f - 2.f*qy2 - 2.f*qz2; mat.m[0][1] = 2.f*qx*qy - 2.f*qz*qw; mat.m[0][2] = 2.f*qx*qz + 2.f*qy*qw;
mat.m[1][0] = 2.f*qx*qy + 2.f*qz*qw; mat.m[1][1] = 1.f - 2.f*qx2 - 2.f*qz2; mat.m[1][2] = 2.f*qy*qz - 2.f*qx*qw;
mat.m[2][0] = 2.f*qx*qz - 2.f*qy*qw; mat.m[2][1] = 2.f * qy*qz + 2.f*qx*qw; mat.m[2][2] = 1.f - 2.f*qx2 - 2.f*qy2;
return mat;
}
PSMoveFloatVector3 PSMoveMatrix3x3::basis_x() const
{
return PSMoveFloatVector3::create(m[0][0], m[0][1], m[0][2]);
}
PSMoveFloatVector3 PSMoveMatrix3x3::basis_y() const
{
return PSMoveFloatVector3::create(m[1][0], m[1][1], m[1][2]);
}
PSMoveFloatVector3 PSMoveMatrix3x3::basis_z() const
{
return PSMoveFloatVector3::create(m[2][0], m[2][1], m[2][2]);
}
// -- PSMovePose --
PSMovePose PSMovePose::create(const PSMovePosition& position, const PSMoveQuaternion& orientation)
{
PSMovePose p;
p.Position = position;
p.Orientation = orientation;
return p;
}
const PSMovePose& PSMovePose::identity()
{
return g_psmove_pose_identity;
}
void PSMovePose::Clear()
{
Position= *k_psmove_position_origin;
Orientation = *k_psmove_quaternion_identity;
}
PSMovePose PSMovePose::inverse() const
{
PSMoveQuaternion q_inv = Orientation.inverse();
PSMovePose result;
result.Orientation = q_inv;
result.Position = q_inv.rotate_position(Position) * -1.f;
return result;
}
PSMovePose PSMovePose::concat(const PSMovePose &first, const PSMovePose &second)
{
PSMovePose result;
result.Orientation = PSMoveQuaternion::concat(first.Orientation, second.Orientation);
result.Position = second.Orientation.rotate_position(first.Position) + second.Position.toPSMoveFloatVector3();
//result.Position = first.Position + first.Orientation.rotate_position(second.Position).toPSMoveFloatVector3();
return result;
}
PSMovePosition PSMovePose::apply_transform(const PSMovePosition &p) const
{
PSMovePosition result= Position + Orientation.rotate_vector(p.toPSMoveFloatVector3());
return result;
}
PSMovePosition PSMovePose::apply_inverse_transform(const PSMovePosition &p) const
{
PSMoveQuaternion q_inv = Orientation.inverse();
PSMovePosition result = (q_inv.rotate_position(p) - q_inv.rotate_position(Position)).castToPSMovePosition();
return result;
}
// -- PSMoveFrustum --
void PSMoveFrustum::set_pose(const PSMovePose &pose)
{
const glm::quat orientation(pose.Orientation.w, pose.Orientation.x, pose.Orientation.y, pose.Orientation.z);
const glm::vec3 position(pose.Position.x, pose.Position.y, pose.Position.z);
const glm::mat4 rot = glm::mat4_cast(orientation);
const glm::mat4 trans = glm::translate(glm::mat4(1.0f), position);
const glm::mat4 glm_mat4 = trans * rot;
forward = PSMoveFloatVector3::create(glm_mat4[2].x, glm_mat4[2].y, glm_mat4[2].z); // z-axis
left = PSMoveFloatVector3::create(glm_mat4[0].x, glm_mat4[0].y, glm_mat4[0].z); // x-axis
up = PSMoveFloatVector3::create(glm_mat4[1].x, glm_mat4[1].y, glm_mat4[1].z); // y-axis
origin = PSMovePosition::create(glm_mat4[3].x, glm_mat4[3].y, glm_mat4[3].z);
} | true |
76b098cdf1cfe992b032bda3b81b5dbc8859d66c | C++ | gusrb/student_coding | /2.cpp | UTF-8 | 363 | 2.703125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int sum = 0, n , g ,d;
int di(int k)
{
if (k != 0) {
n = n / k;
d += n % k;
sum += n;
}
if (d >= k)
{
sum += d / k;
d += n % k;
}
if (n < k)
return sum;
else
di(k);
}
int main()
{
int k;
cin >> g >> k;
n = g;
cout << di(k)+g;
return 0;
} | true |
5216449845284e4c2a56b701adb7a5cc93bf48e6 | C++ | nidamon/CS202 | /Labs/CS202Lab3SmartPointers/Lab2Class.cpp | UTF-8 | 864 | 3.4375 | 3 | [] | no_license | /*Lab2Class.cpp
Nathan Damon
CS 202
1/19/2021
This is the cpp file for the lab2 class
*/
#include "Lab2Class.h"
Lab2::Lab2() : _name("default")
{
cout << "Called Lab2 default constructor." << endl;
}
Lab2::Lab2(const Lab2& orig)
{
cout << "Called Lab2 copy constructor." << endl;
}
Lab2::Lab2(string str) : _name(str)
{
cout << "Called Lab2 name constructor. Name is \"" << _name << "\"." << endl;
}
Lab2::Lab2(string str, double value) : _name(str), _data(value)
{
cout << "Called Lab2 data constructor. Name is \"" << _name << "\" and data is \"" << _data << "\"." << endl;
}
Lab2::~Lab2()
{
cout << "Called Lab2 destructor. Goodbye \"" << _name << "\"." << endl;
}
void Lab2::printStuff()
{
cout << "\"Stuff\" has been printed." << endl;
}
ostream& operator<<(ostream& os, const Lab2& lab)
{
return os << "This is the name of the lab: " << lab._name;
} | true |
86c76a3e7975e6eae0c871a5d9c82ad076ec1275 | C++ | TheNsBhasin/CodeChef | /XORAGN/main.cpp | UTF-8 | 481 | 2.59375 | 3 | [] | no_license | /*input
1
2
1 2
*/
//
// main.cpp
// XORAGN
//
// Created by Nirmaljot Singh Bhasin on 11/05/18.
// Copyright © 2018 Nirmaljot Singh Bhasin. All rights reserved.
//
#include <iostream>
using namespace std;
const int MAXN = 100005;
typedef long long int lli;
lli arr[MAXN];
int main(int argc, const char * argv[]) {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
lli res = 0;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
res ^= (arr[i] << 1);
}
cout << res << endl;
}
return 0;
}
| true |
394ace92f8c5769d56546a8605e7fa62352b9cce | C++ | 719400737/LeetCode | /70.cpp | UTF-8 | 388 | 2.78125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n+1,0);
for(int i=1;i<=n;i++){
if(i==1 || i==2)
dp[i]=i;
else dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
};
int main(){
Solution s;
int n=s.climbStairs(2);
cout<<n<<endl;
return 0;
} | true |
d1244669d3b9be102a699d4a4b6d5b53bcbba950 | C++ | SCS2017/Leetcode-Solution | /堆栈队列/用一个栈对另一个栈排序.cpp | UTF-8 | 1,414 | 4.125 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/*
题目:
一个栈中元素的类型为整型,现在想将该栈从顶到底按从大到小的顺序排序,只许申请一个栈,
除此之外可以申请新的变量,但不能申请额外的数据结构。如何完成排序?
题解:
需要用到辅助栈。stack执行pop操作,弹出元素记为cur;
如果cur小于或等于assist的栈顶元素,则将cur直接压入assist;
如果cur大于assist的栈顶元素,则将assist的元素逐一弹出并压入stack,知道cur小于或等于assist的栈顶元素,再将cur压入assist
执行上述操作后,直到stack空,将assist所有元素逐一压入stack
*/
void sortStack(stack<int>& s){
stack<int> tmp;
while(!s.empty()){
int cur = s.top();
s.pop();
//cur < tmp.top()栈弹出的元素为从小到大,cur > tmp.top()栈弹出的元素为从大到小
while(!tmp.empty() && cur < tmp.top()){
s.push(tmp.top());
tmp.pop();
}
tmp.push(cur);
}
while(!tmp.empty()){
s.push(tmp.top());
tmp.pop();
}
}
int main()
{
vector<int> arr{3, 4, 2, 1, 5};
stack<int> s;
for (int i = 0; i < arr.size(); ++i) {
s.push(arr[i]);
}
sortStack(s);
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
return 0;
} | true |
76efb8eb3e6d4b075766fa2135e395fd4d78cc48 | C++ | CarlosManuelRodr/QBill | /src/ConfigParser.h | UTF-8 | 4,985 | 3.390625 | 3 | [] | no_license | /**
* @file ConfigParser.h
* @brief This header file contains the ConfigParser class.
*
* The ConfigParser class is used to retrieve values from a configuration file.
* @copyright GNU Public License v3
* @author Carlos Manuel Rodriguez y Martinez
* @date 7/18/2012
*
* This file is part of QBill: https://github.com/cmrm/QBill
*/
#pragma once
#ifndef _configParser
#define _configParser
#include <vector>
#include <string>
/**
* @class ConfigParser
* @brief Analyzes a configuration file.
*
* It's used when the program starts to load parameters from the "config.ini" file.
*/
class ConfigParser
{
std::vector<std::string> m_labels; ///< Vector that contains all the labels found.
std::vector<std::string> m_args; ///< Vector that contains all the arguments found.
bool m_fileOpened; ///< Status of the opened file.
bool m_error;
std::string m_filename;
public:
///@brief Constructor
///@param filename File to analyze.
ConfigParser(const std::string filename);
///@brief Ask for the state of the opened file.
///@return true if file was opened. false if not.
bool FileOpened();
///@brief Ask if there has been an error parsing an arg or opening the file. Then clears the flag.
///@return true if there is an error. false if not.
bool Error();
///@brief Replaces the argument of the label.
///@param label Label to replace argument.
///@param replaceArg New argument.
void ReplaceArg(const std::string label, const std::string replaceArg);
///@brief Gets int value from expresion.
///@param myVar int var to store value.
///@param expr Label to find.
///@param defaultValue If expr isn't found stores this default value.
///@return true if expr was found. False if not.
bool IntArgToVar(int& myVar, const std::string expr, const int defaultValue);
///@brief Gets uInt value from expresion.
///@param myVar uInt var to store value.
///@param expr Label to find.
///@param defaultValue If expr isn't found stores this default value.
///@return true if expr was found. False if not.
bool UIntArgToVar(unsigned int& myVar, const std::string expr, const unsigned int defaultValue);
///@brief Gets double value from expresion.
///@param myVar double var to store value.
///@param expr Label to find.
///@param defaultValue If expr isn't found stores this default value.
///@return true if expr was found. False if not.
bool DblArgToVar(double& myVar, const std::string expr, const double defaultValue);
///@brief Gets bool value from expresion.
///@param myVar bool var to store value.
///@param expr Label to find.
///@param defaultValue If expr isn't found stores this default value.
///@return true if expr was found. False if not.
bool BoolArgToVar(bool& myVar, const std::string expr, const bool defaultValue);
///@brief Gets std::string value from expresion.
///@param myVar std::string var to store value.
///@param expr Label to find.
///@param defaultValue If expr isn't found stores this default value.
///@return true if expr was found. False if not.
bool StringArgToVar(std::string& myVar, const std::string expr, const std::string defaultValue);
/**
* @brief Stores M element in myVar.
*
* A vector of labels to search is given in the options parameter, also a vector of values.
* In order to work properly they must have the same order.
* @param myVar M var to store value.
* @param expr Label to find.
* @param options Vector which contains all the labels of the options to find.
* @param values Vector of values to store in myVar.
* @param defaultValue If expr isn't found stores this default value.
*/
template<class M> void OptionToVar(M& myVar, const std::string expr, const std::vector<std::string> options,
const std::vector<M> values, const M defaultValue);
};
template<class M> void ConfigParser::OptionToVar(M& myVar, const std::string expr, const std::vector<std::string> options,
const std::vector<M> values, const M defaultValue)
{
bool found = false;
if(options.size() == values.size())
{
for(unsigned int i=0; i<m_labels.size() && !found; i++)
{
if(m_labels[i] == expr)
{
for(unsigned int j=0; j<options.size(); j++)
{
if(m_args[i] == options[j])
{
myVar = values[j];
found = true;
break;
}
}
}
}
if(!found)
{
myVar = defaultValue;
m_error = true;
}
}
else myVar = defaultValue;
}
#endif
| true |
09521306f4d33d71d77a1684750f258ea30f7562 | C++ | martynovmaxim/FPS-1 | /PracticeProject/Source/PracticeProject/Public/AI/Path Following/Splines/BezierCurve.h | UTF-8 | 2,245 | 2.515625 | 3 | [] | no_license | // By Polyakov Pavel
#pragma once
#include "Spline.h"
#include "BezierCurve.generated.h"
/** A Bezier curve to move along */
class PRACTICEPROJECT_API FBezierCurve : public FSpline
{
TArray<TArray<FVector>> ControlPoints;
public:
FORCEINLINE FBezierCurve(TArray<TArray<FVector>> InControlPoints)
: ControlPoints(MoveTemp(InControlPoints)) {}
virtual FVector GetValue(int32 InPiece, double InParameter) const override;
virtual int32 GetPieceNumber() const override;
FORCEINLINE const TArray<TArray<FVector>>& GetControlPoints() const { return ControlPoints; }
};
/** Bezier curve building parameters */
USTRUCT()
struct PRACTICEPROJECT_API FBezierCurveBuildParams
{
GENERATED_USTRUCT_BODY()
/** Minimal distance between control points in a single part of a Bezier curve */
UPROPERTY(EditDefaultsOnly, meta = (ClampMin = "0.0", ClampMax = "1000.0"))
float MinDistanceBetweenControlPoints;
/** Additional number of points that should be added on both sides of existing ones before calculating bezier curve parts */
UPROPERTY(EditDefaultsOnly, meta = (ClampMin = "0", ClampMax = "5"))
int32 AdditionalPathPointsNumber;
/** This the offset used to place aditional path points around existing ones */
UPROPERTY(EditDefaultsOnly, meta = (ClampMin = "0.0", ClampMax = "1000.0"))
float AdditionalPathPointsOffset;
FORCEINLINE FBezierCurveBuildParams()
: MinDistanceBetweenControlPoints(200), AdditionalPathPointsNumber(2), AdditionalPathPointsOffset(75) {};
};
/** Class responsible for building a bezier curve */
class PRACTICEPROJECT_API FBezierCurveBuilder
{
static TArray<FVector> RetrivePathPoints(const TArray<FNavPathPoint>& NavPathPoints, const FBezierCurveBuildParams &BuildParams, const FNavAgentProperties& AgentProperties, const UWorld* World);
static TArray<int32> CalculateSubsequencesArray(const TArray<FVector>& PathPoints, const FNavAgentProperties& AgentProperties, const UWorld* World);
public:
static TUniquePtr<FBezierCurve> BuildBezierCurve(const TArray<FNavPathPoint>& NavPathPoints, const FVector& CurrentMoveDirection, const FBezierCurveBuildParams &BuildParams, const FNavAgentProperties& AgentProperties, const UWorld* World);
};
| true |
4daf2c2bab2f135827e24ad1a189d6c21df756ad | C++ | tao-pr/52-challenges | /018-graph-traversal/headers/Functions.hpp | UTF-8 | 605 | 2.8125 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef FF_HPP
#define FF_HPP
#include <tuple>
using namespace std;
double inline distance(tuple<double,double> p1, tuple<double,double> p2){
// Haversine
const double R = 6371e3;
double pp = M_PI / 180;
double phi1 = get<0>(p1) * pp;
double phi2 = get<0>(p2) * pp;
double deltaPhi = (get<0>(p2) - get<0>(p1)) * pp;
double deltaLambda = (get<1>(p2) - get<1>(p1)) * pp;
double a = sin(deltaPhi/2) * sin(deltaPhi/2) +
cos(phi1) * cos(phi2) *
sin(deltaLambda/2) * sin(deltaLambda/2);
double c = 2 * atan2(sqrt(a), sqrt(1-a));
return R * c * 0.001; // km
}
#endif | true |
c00459e826939001cf60fe82c42900f65616eabc | C++ | Jaa-c/kdtree | /KDTree.h | UTF-8 | 21,430 | 3.15625 | 3 | [] | no_license | /*
* File: KDTree.h
* Author: Daniel Princ
*
* KDTree.
* It's a template, so it's all in the header file.
*
*/
#ifndef KDTREE_H
#define KDTREE_H
#include <vector>
#include <stack>
#include <queue>
#include <limits>
#include <math.h>
using namespace std;
#include "Point.h"
#include "KDTreeNodes.h"
#include "PlyHandler.h"
/**
* kd-tree!
*/
template<const int D = 3>
class KDTree {
typedef vector< Point<D> *> points;
typedef typename vector< Point<D> *>::iterator points_it;
typedef pair<Inner *, Visited> exInner; //DEPRECATED, only in simple method
/** Size of the bucket*/
const static int bucketSize = 10;
/** root of the tree */
Inner * root;
/** number of points inside the tree */
int sizep;
/** bounding box of the tree, format: xmin, xmax, ymin, ymax, ...*/
float boundingBox[2*D];
/** number of visited nodes during NN searches*/
int visitedNodes;
/**
* Find in which bucket does given point belong
* @param point point in question
* @return bucket in which the point belongs
*/
Leaf<D> * findBucket(const Point<D> *point) const {
Inner* node = root;
while(true) {
if((*point)[node->dimension] <= node->split) {
if(!node->left) {
if(node->right->isLeaf())
return (Leaf<D> *) node->right;
else {
node = (Inner *) node->right;
continue;
}
}
if(node->left->isLeaf())
return (Leaf<D> *) node->left;
node = (Inner *) node->left;
}
else {
if(!node->right) {
if(node->left->isLeaf())
return (Leaf<D> *) node->left;
else {
node = (Inner *) node->left;
continue;
}
}
if(node->right->isLeaf())
return (Leaf<D> *) node->right;
node = (Inner *) node->right;
}
}
}
/**
* Calculates distance
* @param p1 D dimensional point
* @param p2 D dimensional point
* @param sqrtb if false, the returned distance is squared
* @return distance between points
*/
inline const float distance(const Point<D> * p1, const Point<D> * p2, bool sqrtb = false) {
float dist = 0;
for(int d = 0; d < D; d++) {
float tmp = fabs((*p1)[d] - (*p2)[d]);
dist += tmp*tmp;
}
if(sqrtb)
return sqrt(dist);
else
return dist;
}
/**
* Gets distance from given point to defined hyper rectangle
* @param point query point
* @param min min coords of a hyper reectangle
* @param max max coords of a hyper reectangle
* @return squared distance
*/
inline const float minBoundsDistance(const Point<D> * point, const float * min, const float * max) {
float dist = 0;
for(int d = 0; d < D; d++) {
if ((*point)[d] < min[d]) {
const float tmp = min[d] - (*point)[d];
dist += tmp*tmp;
}
else if ((*point)[d] > max[d]) {
const float tmp = max[d] - (*point)[d];
dist += tmp*tmp;
}
}
return dist;
}
public:
/**
* Creates empty kd-tree
*/
KDTree() {
root = new Inner(NULL);
sizep = 0;
}
/**
* Destructor
*/
~KDTree() {
delete root;
}
/**
* Returns the root of the tree
* @return pointer to the root node
*/
const Inner *getRoot() const {
return root;
}
/**
* Returns the number of visited nodes during last search
* @return number of visited nodes
*/
const int getVisitedNodes() const {
return visitedNodes;
}
/**
* Bounding box of the tree
* @return array of size 2D, format: xmin, xmax, ymin, ymax, ...
*/
const float *getBoundingBox() const {
return &boundingBox[0];
}
/**
* Returns number of points in the tree
* @return number of points in the tree
*/
const int size() const {
return sizep;
}
/**
* Builds the KD-Tree on a given set of unordered points
*
* @param[in] data vector of unordered points
* @param[in] bounds array with bounds of the coordinates \
* expects array like this - 2D: [xmin, xmax, ymin, ymax]
*/
void construct(vector< Point<D> > * data, float * bounds = NULL) {
vector< Point<D>* > pointers;
for(typename vector< Point<D> >::iterator it = data->begin(); it != data->end(); ++it) {
pointers.push_back(&(*it));
}
construct(&pointers, bounds);
}
/**
* Builds the KD-Tree on a given set of points with unknown bounds
*
* @param[in] data vector of pointers to unordered points
* @param[in] bounds array with bounds of the coordinates \
* expects array like this - 2D: [xmin, xmax, ymin, ymax]
*/
void construct(points * adata, float * abounds = NULL) {
if(!abounds) { //calculate the bounds if not specified
for(int d = 0; d < D; d++) {
boundingBox[2*d] = numeric_limits<float>::max();
boundingBox[2*d + 1] = numeric_limits<float>::min();
}
for(points_it it = adata->begin(); it != adata->end(); ++it) {
Point<D> *p = *it;
for(int d = 0; d < D; d++) {
if((*p)[d] < boundingBox[2*d]) boundingBox[2*d] = (*p)[d];
if((*p)[d] > boundingBox[2*d + 1]) boundingBox[2*d + 1] = (*p)[d];
}
}
}
else {
copy(abounds, abounds + 2*D, boundingBox);
}
sizep = adata->size();
if(root != NULL) {
delete root;
root = new Inner(NULL);
}
//construct the tree
stack<Constr<D>> stack;
stack.push(Constr<D>(*adata, boundingBox, root));
while(!stack.empty()) {
Constr<D> curr = stack.top();
stack.pop();
points * data = &curr.data;
float* bounds = &curr.bounds[0];
Inner *parent = curr.parent;
int dim = -1; //dimension to split
float size = 0;
for(int i = 0; i < D; i++) {
if(bounds[2*i + 1] - bounds[2*i] > size) {
size = bounds[2*i + 1] - bounds[2*i];
dim = i;
}
}
float split = bounds[2*dim] + size / 2.0f; //split value
points left, right;
float lmax = -1000000, rmin = 1000000; //TODO
for(points_it it = data->begin(); it != data->end(); ++it) {
Point<D> *p = (*it);
if((*p)[dim] <= split) { //NOTE: points exactly on split line belong to left node!
left.push_back(*it);
float tmp = (*p)[dim];
if(tmp > lmax)
lmax = tmp;
}
if((*p)[dim] > split) {
right.push_back(*it);
float tmp = (*p)[dim];
if(tmp < rmin)
rmin = tmp;
}
}
//sliding midpoint split
if(right.size() == 0)
split = lmax;
if(left.size() == 0)
split = rmin;
//set split to node
parent->dimension = dim;
parent->split = split;
//create nodes
if(left.size() > 0) {
if(left.size() > bucketSize) {
Inner *node = new Inner(parent);
parent->left = node;
float b[2*D];
std::copy(bounds, bounds + 2*D, &b[0]);
b[2*dim + 1] = split;
stack.push(Constr<D>(left, &b[0], node));
}
else {
Leaf<D> * leaf = new Leaf<D>(parent, left);
parent->left = leaf;
}
}
if(right.size() > 0) {
if(right.size() > bucketSize) {
Inner *node = new Inner(parent);
parent->right = node;
float b[2*D];
std::copy(bounds, bounds + 2*D, &b[0]);
b[2*dim] = split;
stack.push(Constr<D>(right, &b[0], node));
}
else {
Leaf<D> * leaf = new Leaf<D>(parent, right);
parent->right = leaf;
}
}
}
}
/**
* Inserts point into the tree
* @param point point to insert
*/
void insert(Point<D> *point) {
if(sizep == 0) {
points tmp;
tmp.push_back(point);
construct(&tmp);
return;
}
sizep++;
Leaf<D> * leaf = findBucket(point);
if(leaf->bucket.size() < bucketSize) {
leaf->add(point);
return; //OK, bucket is not full yet
}
else { //split the bucket into 2 new leaves
points data(leaf->bucket);
data.push_back(point); //add the point to bucket
//create new inner node
Inner * node = new Inner(leaf->parent);
if((Leaf<D> *)leaf->parent->left == leaf) {
leaf->parent->left = node;
}
else if((Leaf<D> *)leaf->parent->right == leaf) {
leaf->parent->right = node;
}
else {
cerr << "somethig is very wrong! Point not inserted.\n";
return;
}
delete leaf; //no longer necessary
//split the nodes along the dimension with greatest local variance
Point<D> min = *(data[0]);
Point<D> max = *(data[0]);
for(points_it it = data.begin(); it != data.end(); ++it) {
Point<D> p = *(*it);
for(int d = 0; d < D; d++) {
if(p[d] < min[d]) {
min[d] = p[d];
continue;
}
if(p[d] > max[d]) {
max[d] = p[d];
}
}
}
int dim;
float dist = 0;
for(int d = 0; d < D; d++) {
if(max[d] - min[d] > dist) {
dist = max[d] - min[d];
dim = d;
}
}
node->split = min[dim] + dist / 2.0f;
points l, r; //split the data
for(points_it it = data.begin(); it != data.end(); ++it) {
Point<D> p = *(*it);
if(p[dim] <= node->split) {
l.push_back(*it);
}
if(p[dim] > node->split) {
r.push_back(*it);
}
}
//create two new leafs
Leaf<D> * left = new Leaf<D>(node, l);
node->left = left;
Leaf<D> * right = new Leaf<D>(node, r);
node->right = right;
}
}
/**
* Returns the exact nearest neighbor (NN).
* If there are more NNs, method retuns one random.
* @param query the point whose NN we search
* @return nearest neigbor
*/
Point<D> * nearestNeighbor(const Point<D> *query) {
visitedNodes = 0;
Leaf<D> *leaf = findBucket(query);
/** squared distance of the current nearest neigbor */
float dist = numeric_limits<float>::max();
/** current best NN */
Point<D> * nearest;
//find nearest point in the bucket
for(points_it it = leaf->bucket.begin(); it != leaf->bucket.end(); ++it) {
visitedNodes++;
//(*it)->setColor(0, 255, 0); //debug
float tmp = distance(query, *it);
if(tmp < dist && tmp > 0) { //ie points are not the same!
dist = tmp;
nearest = *it;
}
}
ExtendedNode<D> firstNode(leaf->parent);
if((Leaf<D> *)leaf->parent->left == leaf)
firstNode.status = LEFT;
else
firstNode.status = RIGHT;
stack< ExtendedNode<D> > stack; //avoid recursion
stack.push(firstNode);
// check possible nodes for NN
while(!stack.empty()) {
ExtendedNode<D> exNode = stack.top();
stack.pop();
Node * nleft = NULL;
Node * nright = NULL;
float ldiff = 0, rdiff = 0, ladd = 0, radd = 0;
/// if right child exist && it has not been searchd yet
if(exNode.node->right && (exNode.status != RIGHT || exNode.status == NONE)) {
radd = exNode.node->split - (*query)[exNode.node->dimension];
if(radd > 0) // only if I'm "crossing line from left to right"
rdiff = exNode.tn.getUpdatedLength(exNode.node->dimension, radd);
else
rdiff = exNode.tn.getLengthSquare();
if(rdiff < dist) { //if there possibly can be nearer point than current nearest
nright = exNode.node->right;
}
}
/// if left child exist && it has not been searchd yet
if(exNode.node->left && (exNode.status != LEFT || exNode.status == NONE)) {
ladd = (*query)[exNode.node->dimension] - exNode.node->split;
if(ladd > 0)
ldiff = exNode.tn.getUpdatedLength(exNode.node->dimension, ladd);
else
ldiff = exNode.tn.getLengthSquare();
if(ldiff < dist) {
nleft = exNode.node->left;
}
}
//on my way up && not in root
if(exNode.status != NONE && exNode.node->parent) {
ExtendedNode<D> add(exNode.node->parent);
add.tn = exNode.tn;
if((Inner *) exNode.node->parent->right == exNode.node)
add.status = RIGHT;
else
add.status = LEFT;
stack.push(add);
}
// this iterates over 2 children
// a bit mess, but there are too many variables and it does not look
// nice as a method.
for(int c = 0; c <= 1; c++) {
Node * node;
float add;
//path ordering, choose the worse first so
//the better will be first to pop of the stack
if(c == 0) {
node = (ldiff >= rdiff) ? nleft : nright;
add = (ldiff >= rdiff) ? ladd : radd;
}
else { //in second iteration, choose the better (=the other node)
node = (ldiff < rdiff) ? nleft : nright;
add = (ldiff < rdiff) ? ladd : radd;
}
if(node) {
if(node->isLeaf()) { // if node is leaf we search the bucket
Leaf<D> * leaf = (Leaf<D> *) node;
///BOB test
if(minBoundsDistance(query, leaf->min, leaf->max) < dist) {
points *bucket = &leaf->bucket;
for(points_it it = bucket->begin(); it != bucket->end(); ++it) {
visitedNodes++;
//(*it)->setColor(255, 255, 0); //debug
float tmp = distance(query, *it);
if(tmp < dist && tmp > 0) { //ie points are not the same!
dist = tmp;
nearest = *it;
}
}
}
}
else { //Not leaf, add node to the stack with correct tracking node
ExtendedNode<D> newN((Inner *) node);
newN.tn = exNode.tn;
if(add > 0) {
newN.tn.set(exNode.node->dimension, add);
}
newN.status = NONE;
if(newN.tn.getLengthSquare() < dist) { //check if the dist hasn't changed
stack.push(newN);
}
}
}
}
}
return nearest;
}
/**
* Returns exact k-nearest neighbors (kNN).
* @param query the point whose kNN we search
* @param k the number of points we look for
* @return vector of kNN
*/
vector< Point<D> * > kNearestNeighbors(const Point<D> *query, const int k) {
visitedNodes = 0;
Point<D> *n = nearestNeighbor(query);
float r = distance(n, query, true) * (1 + 2 / (float)D);
vector< Point<D> * > knn;
//TODO: this is certainly not the most efficient solution
//however all "clever" solutions I tried failed in hight dimension or on
//various data. So I'll leave this, usually returns result <5 iterations.
for(int i = 100; i > 1; i--) {
knn = circularQuery(query, r);
if(knn.size() > k + 1 || knn.size() == sizep) {
break;
}
else {
r *= 1 + (1 / (float) D);
}
}
//C++11, I guess it's OK to use it
sort(knn.begin(), knn.end(),
[query, this](const Point<D> * a, const Point<D> * b) -> bool {
return distance(a, query) < distance(b, query);
});
vector< Point<D> * > result;
int size = (k + 1 < knn.size()) ? k + 1 : knn.size();
result.insert(result.end(), knn.begin() + 1, knn.begin() + size);
return result;
}
/**
* Returns all points in a hypersphere around given point
*
* Basicaly similar implementation to NN, except there is a fixed radius,
* so no distance revisions
*
* TODO: most parts are very simliar to NN search, consider refactoring
* to avoid code duplicity
*
* @param query center of the sphere
* @param radius radius of the sphere
* @return list of points inside
*/
vector< Point<D> * > circularQuery(const Point<D> *query, const float radius) {
//visitedNodes = 0; //comment for kNN
Leaf<D> *leaf = findBucket(query);
vector< Point<D> * > data;
float r = radius * radius;
//find nearest point in the bucket
for(points_it it = leaf->bucket.begin(); it != leaf->bucket.end(); ++it) {
visitedNodes++;
float tmp = distance(query, *it, false);
if(tmp < r) { //ie points are not the same!
data.push_back(*it);
}
}
ExtendedNode<D> firstNode(leaf->parent);
if((Leaf<D> *)leaf->parent->left == leaf)
firstNode.status = LEFT;
else
firstNode.status = RIGHT;
stack< ExtendedNode<D> > stack; //avoid recursion
stack.push(firstNode);
// check possible nodes for NN
while(!stack.empty()) {
ExtendedNode<D> exNode = stack.top();
stack.pop();
Node * nleft = NULL;
Node * nright = NULL;
float ldiff, rdiff, ladd, radd;
/// if right child exist && it has not been searchd yet
if(exNode.node->right && (exNode.status != RIGHT || exNode.status == NONE)) {
radd = exNode.node->split - (*query)[exNode.node->dimension];
if(radd > 0) // only if I'm "crossing line from left to right"
rdiff = exNode.tn.getUpdatedLength(exNode.node->dimension, radd);
else
rdiff = exNode.tn.getLengthSquare();
if(rdiff < r) { //if there possibly can be nearer point than current nearest
nright = exNode.node->right;
}
}
/// if left child exist && it has not been searchd yet
if(exNode.node->left && (exNode.status != LEFT || exNode.status == NONE)) {
ladd = (*query)[exNode.node->dimension] - exNode.node->split;
if(ladd > 0)
ldiff = exNode.tn.getUpdatedLength(exNode.node->dimension, ladd);
else
ldiff = exNode.tn.getLengthSquare();
if(ldiff < r) {
nleft = exNode.node->left;
}
}
//on my way up && not in root
if(exNode.status != NONE && exNode.node->parent) {
ExtendedNode<D> add(exNode.node->parent);
add.tn = exNode.tn;
if((Inner *) exNode.node->parent->right == exNode.node)
add.status = RIGHT;
else
add.status = LEFT;
stack.push(add);
}
// this iterates over 2 children
// a bit mess, but there are too many variables and it does not look
// nice as a method.
for(int c = 0; c <= 1; c++) {
Node * node;
float add;
//path ordering, choose the worse first so
//the better will be first to pop of the stack
if(c == 0) {
node = (ldiff >= rdiff) ? nleft : nright;
add = (ldiff >= rdiff) ? ladd : radd;
}
else { //in second iteration, choose the better (=the other node)
node = (ldiff < rdiff) ? nleft : nright;
add = (ldiff < rdiff) ? ladd : radd;
}
if(node) {
if(node->isLeaf()) { // if node is leaf we search the bucket
Leaf<D> * leaf = (Leaf<D> *) node;
///BOB test
if(minBoundsDistance(query, leaf->min, leaf->max) < r) {
visitedNodes++;
points *bucket = &leaf->bucket;
for(points_it it = bucket->begin(); it != bucket->end(); ++it) {
float tmp = distance(query, *it, false);
if(tmp < r) { //ie points are not the same!
data.push_back(*it);
}
}
}
}
else { //Not leaf, add Node to the stack with correct tracking node
ExtendedNode<D> newN((Inner *) node);
newN.tn = exNode.tn;
if(add > 0)
newN.tn.set(exNode.node->dimension, add);
newN.status = NONE;
if(newN.tn.getLengthSquare() < r) { //check if the dist hasn't changed
stack.push(newN);
}
}
}
}
}
return data;
}
/**
* !! This is just to compare the performance with the better version !!
*
* Returns the exact nearest neighbor (NN).
* If there are more NNs, method retuns one random.
* @param query the point whose NN we search
* @return nearest neigbor
*/
Point<D> * simpleNearestNeighbor(const Point<D> *query) {
visitedNodes = 0;
Leaf<D> *leaf = findBucket(query);
float dist = numeric_limits<float>::max();
Point<D> * nearest;
//find nearest point in the bucket
for(points_it it = leaf->bucket.begin(); it != leaf->bucket.end(); ++it) {
//(*it)->setColor(0, 255, 0); //debug only
float tmp = distance(query, *it, true);
if(tmp < dist && tmp > 0) { //ie points are not the same!
dist = tmp;
nearest = *it;
}
}
//create initial window
float window[2*D];
for(int d = 0; d < D; d++) {
window[2*d] = (*query)[d] - dist;
window[2*d + 1] = (*query)[d] + dist;
}
//cout << window[0] << " " << window[1]<< " " << window[2]<< " " << window[3] << "\n";
//PlyHandler::saveWindow<D>(window);
exInner n;
n.first = leaf->parent;
if((Leaf<D> *)leaf->parent->left == leaf)
n.second = LEFT;
else
n.second = RIGHT;
stack<exInner> stack; //avoid recursion
stack.push(n);
while(!stack.empty()) { //check possible nodes
exInner exNode = stack.top();
stack.pop();
Inner* node = exNode.first;
Visited status = exNode.second;
Node *nodes[2]; //left and right child
nodes[0] = nodes[1] = NULL;
if(node->right && (status != RIGHT || status == NONE)) {
if(window[2*node->dimension + 1] > node->split) {
nodes[0] = node->right;
}
}
if(node->left && (status != LEFT || status == NONE)) {
if(window[2*node->dimension] <= node->split) {
nodes[1] = node->left;
}
}
for(int i = 0; i < 2; i++) {
if(nodes[i]) { //check node
if((nodes[i])->isLeaf()) {
points *bucket = &((Leaf<D> *)(nodes[i]))->bucket;
for(points_it it = bucket->begin(); it != bucket->end(); ++it) {
//(*it)->setColor(255, 255, 0);
visitedNodes++;
float tmp = distance(query, *it, true);
if(tmp < dist && tmp > 0) { //ie points are not the same!
dist = tmp;
nearest = *it;
for(int d = 0; d < D; d++) {
window[2*d] = (*query)[d] - dist;
window[2*d + 1] = (*query)[d] + dist;
}
}
}
}
else {
//Not leaf, add Node to the stack
exInner add((Inner *) nodes[i], NONE);
stack.push(add);
}
}
}
//on my way up && not in root
if(status != NONE && node->parent) {
exInner add;
add.first = (Inner *) node->parent;
if((Inner *) node->parent->right == node)
add.second = RIGHT;
else
add.second = LEFT;
stack.push(add);
}
}
return nearest;
}
};
#endif /* KDTREE_H */
| true |
4e98c0784e945c304b7f91b48ca7eb02dec88a22 | C++ | clivic/C-code-examples | /_C++ tests and problem solving/current/main.cpp | UTF-8 | 744 | 3.53125 | 4 | [
"MIT"
] | permissive | #include "class.h"
#include <iostream>
int main()
{
Time time1(19,40,00);
Time time2;
std::cout << "Write time1: ";
time1.Write();
std::cout << std::endl;
std::cout << "Write time2: ";
time2.Write();
std::cout << std::endl;
time2.Increment();
std::cout << "Incremented time2: ";
time2.Write();
std::cout << std::endl;
std::cout << "AM/PM time1: ";
time1.WriteAmPm();
std::cout << std::endl;
std::cout << "Compare time1 and time2:\n"
<< "Less than? " << time1.LessThan(time2) << std::endl
<< "equal to? " << time1.Equal(time2) << std::endl;
time1.SetTime(8, 50, 35);
std::cout << "Seted time1 and AM/PM: ";
time1.Write();
std::cout << std::endl;
time1.WriteAmPm();
std::cout << std::endl;
return 0;
}
| true |
a52ffe8c0bc7de630ebcb0a9c2ec5c5754ba930d | C++ | cssham/URI | /uri1038.cpp | UTF-8 | 506 | 2.828125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int x,y;
cin>>x>>y;
switch(x)
{
case 1:
printf("Total: R$ %.2f\n",4.00*y);
break;
case 2:
printf("Total: R$ %.2f\n",4.50*y);
break;
case 3:
printf("Total: R$ %.2f\n",5.00*y);
break;
case 4:
printf("Total: R$ %.2f\n",2.00*y);
break;
case 5:
printf("Total: R$ %.2f\n",1.50*y);
break;
default:
break;
}
return 0;
}
| true |
176d729b5e339530e1913b232e1adb18d1c1f00c | C++ | sysfce2/SFML_Space-Invaders.Groszczu | /ScoreDisplayState.hpp | UTF-8 | 801 | 2.546875 | 3 | [] | no_license | #pragma once
#include "State.hpp"
#include "Game.hpp"
namespace rstar
{
class ScoreDisplayState : public State
{
public:
ScoreDisplayState(GameDataPtr data, int playerScore, std::string fileName);
void HandleInput() override;
void Update() override;
void Draw() override;
private:
GameDataPtr data_;
int const playerScore_;
std::string const fileName_;
std::string playerNick_{};
sf::Text playerNickTxt_;
sf::Text playerScoreTxt_;
sf::Text scoreTableTxt_;
sf::Text pressEnterTxt_;
sf::Sprite background_;
std::vector<std::pair<std::string, int>> scoreTable_;
sf::Clock animationClock_;
bool nameEntered_{ false };
bool scoreCalculated_{ false };
void loadScores();
void writeScores() const;
void generateScoreTable();
void animateTxt();
};
}
| true |
adae2847e51220dacf95141071e7a5944ac18a57 | C++ | william-wang-stu/Junqi | /chess.h | GB18030 | 5,996 | 2.8125 | 3 | [] | no_license | #pragma once
#include <vector>
#include <iostream>
#include <queue>
#include <map>
#include "game.h"
#include "connect.h"
#include "cmd_console_tools.h"
// ̵ĴС
static const int Chess_H = 13;
static const int Chess_W = 5;
class Movement;
class Coord;
class Connect;
extern const int ROLE_BLANK;
extern const int ROLE_LOWER;
extern const int ROLE_UPPER;
//ȼжҪ
const char RANK[] = "AJSVTYLPGF";
const char BLANK = ' ';
#define UNDER -1
#define ABOVE 1
#define SAME_RANK 0
enum class PlayerType;
/*
洢ʽWordһôдСд
*/
class Chess
{
private:
std::vector<std::vector<char> > Board;
int Rank_Judgement(char a, char b);
public:
Chess()
{
Board.resize(Chess_H);
for (int i = 0; i < Chess_H; i++)
Board[i].resize(Chess_W);
}
Chess(std::vector<std::vector<char> > board_data)
{
Board.resize(Chess_H);
for (int i = 0; i < Chess_H; i++) {
Board[i].resize(Chess_W);
Board[i] = board_data[i];
}
}
bool Is_Over(const int& Role);
int Evaluate_Chess(const int& Role);
int Evaluater(const int x, const int y, const char ch);
std::vector<Movement> Search_Movement(const int& State, PlayerType Player);
Chess Apply_Move(const Movement& V);
void Display();
bool Is_Movable(Movement M);
void Set_Board(int x, int y, int ch);
void BFSSearch(int x, int y, std::vector<Coord>& Pos);
int Selector(Chess chess, const int& Role, Movement M);
std::vector<Movement> SelectMoveMent(std::vector <Movement> M, const int& Role, PlayerType Player);
};
const int frontEndPos = 7; // ǰλ
// Ӧλõɫ
inline int isColor(int linePos,char ch);
//
inline void common_draw_background(const Coord sizeofall, bool border, bool solid, bool display, const Coord cursor);
//
inline void Display_Chess(std::vector<std::vector<char> > Board, class Coord sizeofall, bool border, bool display);
// ·λ
const int Railway[Chess_H][Chess_W]{
{0, 0, 0, 0, 0},
{2, 1, 2, 1, 2},
{1, 0, 0, 0, 1},
{1, 0, 0, 0, 1},
{1, 0, 0, 0, 1},
{2, 1, 3, 1, 2},
{1, 0, 1, 0, 1},
{2, 1, 3, 1, 2},
{1, 0, 0, 0, 1},
{1, 0, 0, 0, 1},
{1, 0, 0, 0, 1},
{2, 1, 1, 1, 2},
{0, 0, 0, 0, 0}
};
// Ӫλ
const bool Station[Chess_H][Chess_W]{
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 1, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 1, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}
};
// ɲƶλ
const bool SpecialPos[Chess_H][Chess_W]{
{1, 1, 1, 1, 1},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{1, 1, 1, 1, 1}
};
// ĸ
const int HV_DirectX[4] = { 1,0,0,-1 };
const int HV_DirectY[4] = { 0,1,-1,0 };
// ԽǷ
const int Cross_DirectX[4] = { 1,1,-1,-1 };
const int Cross_DirectY[4] = { 1,-1,1,-1 };
// ·λ
// ·ͨ
enum class HighwayConn { full, half, none };
// ·ͨ
enum class ConnWay { Railway, Highway, none };
// ˾*1*1ʦ*2ó*2ų*2Ӫ*2*3ų*3*3*3ը*2*1 25ö
const int chessClassNum = 12;
enum class chessClass { none, zhadan, dilei, junqi, gongbing, pai, lian, ying, tuan, lv, shi, jun, siling };
// ַ
const std::map<char, chessClass> chessMap{
{BLANK,chessClass::none},
{'a',chessClass::siling},
{'A',chessClass::siling},
{'j',chessClass::jun},
{'J',chessClass::jun},
{'s',chessClass::shi},
{'S',chessClass::shi},
{'v',chessClass::lv},
{'V',chessClass::lv},
{'t',chessClass::tuan},
{'T',chessClass::tuan},
{'y',chessClass::ying},
{'Y',chessClass::ying},
{'l',chessClass::lian},
{'L',chessClass::lian},
{'p',chessClass::pai},
{'P',chessClass::pai},
{'g',chessClass::gongbing},
{'G',chessClass::gongbing},
{'d',chessClass::dilei},
{'D',chessClass::dilei},
{'z',chessClass::zhadan},
{'Z',chessClass::zhadan},
{'f',chessClass::junqi},
{'F',chessClass::junqi}
};
// ̸
enum class BoardClass {
camp, // ͨӪ
frontline, // ǰ
station, // Ӫ
headquarter, // Ӫ
empty, // Ӻ֮
};
// ̲
const int Field[Chess_H][Chess_W] = {
{(int)BoardClass::camp, (int)BoardClass::headquarter,(int)BoardClass::camp,(int)BoardClass::headquarter,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::station,(int)BoardClass::camp,(int)BoardClass::station,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::camp,(int)BoardClass::station,(int)BoardClass::camp,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::station,(int)BoardClass::camp,(int)BoardClass::station,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp},
{(int)BoardClass::frontline, (int)BoardClass::empty,(int)BoardClass::frontline,(int)BoardClass::empty,(int)BoardClass::frontline},
{(int)BoardClass::camp, (int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::station,(int)BoardClass::camp,(int)BoardClass::station,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::camp,(int)BoardClass::station,(int)BoardClass::camp,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::station,(int)BoardClass::camp,(int)BoardClass::station,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp,(int)BoardClass::camp},
{(int)BoardClass::camp, (int)BoardClass::headquarter,(int)BoardClass::camp,(int)BoardClass::headquarter,(int)BoardClass::camp}
};
| true |
75fece4b0e5156dbc95f37a99747c53cbf319a2f | C++ | fireairforce/CPPalgorithm | /蓝桥杯日记/1932.cpp | UTF-8 | 2,466 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct code
{
int x;
int y;
int z;
}q[5];
bool cmp(const code&a1,const code&a2)
{
if(a1.x==a2.x)
{
if(a1.y==a2.y)
{
return a1.z<a2.z;
}
return a1.y<a2.y;
}
return a1.x<a2.x;
}
int panduan(int year,int month)
{
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
return 31;
}
else if(month==2)
{
if((year%4==0&&year%100!=0)&&year%400==0)
{
return 29;
}
return 28;
}
else return 30;
}
int main()
{
int a,b,c;
char gang;
cin>>a>>gang>>b>>gang>>c;
if(a<60&&c>=60)
{
q[0].x=a+2000;
q[0].y=b;
q[0].z=c;
q[1].x=c+1900;
q[1].y=a;
q[1].z=b;
q[2].x=c+1900;
q[2].y=b;
q[2].z=a;
}
else if(a<60&&c<60)
{
q[0].x=a+2000;
q[0].y=b;
q[0].z=c;
q[1].x=c+2000;
q[1].y=a;
q[1].z=b;
q[2].x=c+2000;
q[2].y=b;
q[2].z=a;
}
else if(a>=60&&c>=60)
{
q[0].x=a+1900;
q[0].y=b;
q[0].z=c;
q[1].x=c+1900;
q[1].y=a;
q[1].z=b;
q[2].x=c+1900;
q[2].y=b;
q[2].z=a;
}
else if(a>=60&&c<60)
{
q[0].x=a+1900;
q[0].y=b;
q[0].z=c;
q[1].x=c+2000;
q[1].y=a;
q[1].z=b;
q[2].x=c+2000;
q[2].y=b;
q[2].z=a;
}
sort(q,q+3,cmp);
int start=0;
for(int i=0;i<3;i++)
{
if((1960<=q[i].x&&q[i].x<=2059)&&(1<=q[i].z&&q[i].z<=panduan(q[i].x,q[i].y))&&(1<=q[i].y&&q[i].y<=12))
{
printf("%04d",q[i].x);
printf("-");
printf("%02d",q[i].y);
printf("-");
printf("%02d\n",q[i].z);
start=i;
break;
}
}
for(int i=start+1;i<3;i++)
{
if((1960<=q[i].x&&q[i].x<=2059)&&(1<=q[i].z&&q[i].z<=panduan(q[i].x,q[i].y))&&(1<=q[i].y&&q[i].y<=12))
{
if((q[i].x==q[i-1].x)&&(q[i].y==q[i-1].y)&&(q[i].z==q[i-1].z))
{
continue;
}
else
{
printf("%04d",q[i].x);
printf("-");
printf("%02d",q[i].y);
printf("-");
printf("%02d\n",q[i].z);
}
}
}
return 0;
}
| true |
4b060df776fb8740c9b27b83fc2a260dc0fe0c6e | C++ | YoungSeokHong/Young_algorithm_study | /백준_2042.cpp | UTF-8 | 1,290 | 3.015625 | 3 | [] | no_license | #include <iostream>
typedef long long ll;
ll arr[1000000] = {0,};
ll tree[4000000] = {0,};
ll init(int start, int end, int node)
{
if(start == end) return tree[node] = arr[start];
int mid = (start + end) / 2;
return tree[node] = init(start, mid, node * 2) + init(mid + 1, end, node * 2 + 1);
}
ll sum(int start, int end, int node, int left, int right)
{
if(left > end || right < start) return 0;
if(left <= start && end <= right) return tree[node];
int mid = (start + end) / 2;
return sum(start, mid, node * 2, left, right) + sum(mid + 1, end, node * 2 + 1, left, right);
}
void update(int start, int end, int node, int index, ll dif)
{
if(index < start || index > end) return;
if(start == end) {
arr[index] = dif;
tree[node] = arr[index];
return;
}
tree[node] += dif - arr[index];
int mid = (start + end) / 2;
update(start, mid, node * 2, index, dif);
update(mid + 1, end, node * 2 + 1, index, dif);
}
int main(void)
{
int n, m, k, i;
scanf("%d %d %d", &n, &m, &k);
for(i=0; i<n; i++){
scanf("%d", &arr[i]);
}
init(0, n - 1, 1);
int a, b;
ll c;
for(i=0; i<m + k; i++){
scanf("%d %d %lld", &a, &b, &c);
if(a == 1){
update(0, n - 1, 1, b - 1, c);
}else if(a == 2){
printf("%lld\n", sum(0, n -1, 1, b - 1, c - 1));
}
}
return 0;
}
| true |
bc3326e56e4aeaba80c0106349be608d0ca4ecbf | C++ | lihongjun1201/my_cpp_demoprojs | /wordcount_20150724/word_count.cpp | UTF-8 | 4,069 | 3.109375 | 3 | [] | no_license | /*************************************************************************
> File Name: word_count.cpp
> Author:
> Mail:
> Created Time: Fri 24 Jul 2015 05:13:42 AM PDT
************************************************************************/
#include<iostream>
#include "word_count.h"
using namespace std;
//字典树构造函数
TrieTree::TrieTree() {
root = new TrieNode();
//词频统计表,记录单词和出现次数
word_index = 0;
lines_count = 0;
all_words_count = 0;
distinct_words_count = 0;
words_count_table = new WordHash[30000];
}
//建立字典树,将单词插入字典树
void TrieTree::insert(const char *word) {
TrieNode *location = root; //遍历字典树的指针
const char *pword = word;
//插入单词
while( *word ) {
if ( location->next_char[ *word - 'a' ] == NULL ) {
TrieNode *temp = new TrieNode();
location->next_char[ *word - 'a' ] = temp;
}
location = location->next_char[ *word - 'a' ];
word++;
}
location->count++;
location->is_word = true; //到达单词末尾
if ( location->count ==1 ) {
strcpy(this->words_count_table[word_index++].word,pword);
distinct_words_count++;
}
}
//查找字典树中的某个单词
bool TrieTree::search(const char *word) {
TrieNode *location = root;
//将要查找的单词没到末尾字母,且字典树遍历指针非空
while ( *word && location ) {
location = location->next_char[ *word - 'a' ];
word++;
}
this->words_count_table[word_index++].show_times = location->count;
//在字典树中找到单词,并将其词频记录到词频统计表中
return (location != NULL && location->is_word);
}
//删除字典树,递归法删除每个节点
void TrieTree::deleteTrieTree(TrieNode *root) {
int i;
for( i=0;i<child_num;i++ ) {
if ( root->next_char[i] != NULL ) {
deleteTrieTree(root->next_char[i]);
}
}
delete root;
}
//---------------------------------------------------------------
void WordStatics::set_open_filename(string input_path) {
this->open_filename = input_path;
}
string& WordStatics::get_open_filename() {
return this->open_filename;
}
void WordStatics::open_file(string filename) {
set_open_filename(filename);
cout<<"文件词频统计中...请稍后"<<endl;
fstream fout;
fout.open(get_open_filename().c_str());
const char *pstr;
while (!fout.eof() ) { //将文件单词读取到vector中
string line,word;
getline(fout,line);
dictionary_tree.lines_count++;
istringstream is(line);
while ( is >> word ) {
pstr = word.c_str();
dictionary_tree.all_words_count++;
words.push_back(word);
}
}
//建立字典树
vector<string>::iterator it;
for ( it=words.begin();it != words.end();it++ ) {
if ( isalpha(it[0][0]) ) {
dictionary_tree.insert( (*it).c_str() );
}
}
}
void WordStatics::getResult() {
cout<<"文本总行数:"<<dictionary_tree.lines_count<<endl;
cout<<"所有单词的总数 : "<<dictionary_tree.all_words_count-1<<endl;
cout<<"不重复单词的总数 : "<<dictionary_tree.distinct_words_count<<endl;
//在树中查询不重复单词的出现次数
dictionary_tree.setZero_wordindex();
for(int i=0;i<dictionary_tree.distinct_words_count;i++) {
dictionary_tree.search(dictionary_tree.words_count_table[i].word);
result_table.push_back(dictionary_tree.words_count_table[i]);
}
}
bool compare(const WordHash& lhs,const WordHash& rhs) {
return lhs.show_times > rhs.show_times ;
}
void WordStatics::getTopX(int x) {
sort(result_table.begin(),result_table.end(),compare);
cout<<"文本中出现频率最高的前5个单词:"<<endl;
for( int i = 0; i<x; i++) {
cout<<result_table[i].word<<": "<<result_table[i].show_times<<endl;
}
}
| true |