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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9ff8d3e285e0c978580dacbe879517c4ac807b97 | C++ | KrunalChande/ctci-cpp | /ctci/Chap4-TreesAndGraphs/4-1.cpp | UTF-8 | 1,075 | 3.03125 | 3 | [] | no_license | /*
* @Name : 4-1.cpp
* @Author : Krunal Chande
* @Created : Mar 11, 2015
* @Description : Check if a binary tree is balanced
*/
#define DEBUG false
#include <myADTs/BinaryTree.h>
#include <iostream>
using namespace std;
using namespace myADTs;
int main() {
BinaryTree<int> binaryTree;
binaryTree.insert(10);
binaryTree.insert(11);
binaryTree.insert(7);
binaryTree.print();
cout << "Is tree balanced: " << binaryTree.isBalanced() << "\t" << binaryTree.isBalancedInefficient() << endl;
cout << "height of tree:" << binaryTree.height() << endl;
binaryTree.insert(12);
binaryTree.print();
binaryTree.insert(1);
binaryTree.print();
cout << "Is tree balanced: " << binaryTree.isBalanced() << "\t" << binaryTree.isBalancedInefficient() << endl;
cout << "height of tree:" << binaryTree.height() << endl;
binaryTree.insert(3);
binaryTree.print();
cout << "Is tree balanced: " << binaryTree.isBalanced() << "\t" << binaryTree.isBalancedInefficient() << endl;
cout << "height of tree:" << binaryTree.height() << endl;
return 0;
}
| true |
5b49c4935c55e71189a1d3c116f394ce3e7b58b4 | C++ | artem-grishin/CodecademyProjectsCPP | /module2-variables/dog_years/dog_years.cpp | UTF-8 | 312 | 3.53125 | 4 | [] | no_license | #include <iostream>
int main() {
int dog_age;
std::cout << "Enter your dog's age: ";
std::cin >> dog_age;
if(dog_age <= 2) {
dog_age *= 10.5;
}
else if (dog_age > 2) {
dog_age -= 2;
dog_age *= 4;
dog_age += 21;
}
std::cout << "Your dog's age is: " << dog_age << "\n";
}
| true |
c9eef904e6439ab46ed159161a840fd71502dae3 | C++ | iliazeus/magex | /src/nfa.cc | UTF-8 | 2,008 | 2.8125 | 3 | [
"MIT"
] | permissive | // Copyright 2018 Ilia Pozdnyakov
// This file is distributed under the MIT license.
// See the LICENSE.txt file for details.
#include "./nfa.h"
namespace magex {
NFA::Transition::Transition(State *f, const std::string &l, State *t)
: from(f), label(l), to(t) {}
NFA::Transition::Transition(State *f, std::string &&l, State *t)
: from(f), label(std::move(l)), to(t) {}
NFA::NFA(const std::string &s)
: states_(2), transitions_{{&states_.front(), s, &states_.back()}} {}
NFA::NFA(std::string &&s)
: states_(2),
transitions_{{&states_.front(), std::move(s), &states_.back()}} {}
NFA::NFA() : states_(2) {}
void NFA::Merge(NFA &&other) {
states_.splice(states_.end(), std::move(other.states_));
transitions_.splice(transitions_.end(), std::move(other.transitions_));
}
void NFA::Concatenate(NFA &&other) {
transitions_.emplace_back(&terminal_state(), "", &other.initial_state());
Merge(std::move(other));
}
void NFA::Sum(NFA &&other) {
State *this_init = &initial_state();
State *other_init = &other.initial_state();
State *this_term = &terminal_state();
State *other_term = &other.terminal_state();
states_.emplace_front();
transitions_.emplace_front(&initial_state(), "", this_init);
transitions_.emplace_front(&initial_state(), "", other_init);
Merge(std::move(other));
states_.emplace_back();
transitions_.emplace_back(this_term, "", &terminal_state());
transitions_.emplace_back(other_term, "", &terminal_state());
}
void NFA::IterateAtLeastOnce() {
transitions_.emplace_back(&terminal_state(), "", &initial_state());
}
void NFA::Iterate() {
transitions_.emplace_back(&terminal_state(), "", &initial_state());
transitions_.emplace_back(&initial_state(), "", &terminal_state());
}
std::ostream &operator<<(std::ostream &out, const NFA &nfa) {
for (const auto &trans : nfa.transitions_) {
out << trans.from;
out << " \"" << trans.label << "\" ";
out << trans.to;
out << std::endl;
}
return out;
}
} // namespace magex
| true |
e11bbf5393aa3b5c6b7eb3ffcef25eab9bd7e967 | C++ | iwtbam/leetcode | /code/lt1420.cpp | UTF-8 | 1,124 | 2.5625 | 3 | [] | no_license | #include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int numOfArrays(int n, int m, int k) {
k = min(k, n);
vector<vector<vector<int>>> dp(n, vector<vector<int>>(m + 1, vector<int>(k + 1, 0)));
const static int MOD = pow(10, 9) + 7;
for(int i = 1; i <= m; i++)
dp[0][i][1] = 1;
int res = 0;
for(int i = 1; i < n; i++){
for(int j = 1; j <= m; j++){
for(int pj = 1; pj<=m; pj++){
for(int c = 1; c <= k; c++){
if(j > pj){
if(c < k)
dp[i][j][c+1] = (dp[i][j][c + 1] + dp[i - 1][pj][c]) % MOD;
}else{
dp[i][pj][c] = (dp[i][pj][c] + dp[i - 1][pj][c]) % MOD;
}
}
}
}
}
for(int j = 1; j <= m; j++){
res = (res + dp[n - 1][j][k]) % MOD;
}
return res;
}
}; | true |
900c95b3ad67c95b0182ef3564577634c505214c | C++ | dylanmcgauley/PirateGame | /FinalGame/Animation.h | UTF-8 | 444 | 2.6875 | 3 | [] | no_license | #pragma once
#include "SFML\Graphics.hpp"
#include "AnimatedSprite.h"
class Animation : public AnimatedSprite
{
public:
Animation();
~Animation();
void init(int left, int top, int width, int height, int frames, float speed);
sf::IntRect getCurrentFrame();
float getAnimationTime() { return animationSpeed; };
void nextFrame();
bool flipped;
protected:
sf::IntRect frame;
int numberOfFrames;
float animationSpeed;
int currentFrame;
}; | true |
2d524ad4f91b09ac80be3cc895cc866cd4cd0a4b | C++ | Matrix-Ke/RouteLibraryTestDemo | /routeLib/AVL.cpp | GB18030 | 7,074 | 3.765625 | 4 | [] | no_license | /*
* ʵֶƽIJ롢ɾ
*/
#include "stdafx.h"
#include "AVL.h"
/*
*
* *TΪĶƽнkeyʧܣFALSE
* key뵽УȻΪƽTRUE
*/
bool AVLInsert(BiTree *T, TElemType key)
{
BiTree t;
//ǰҵĸΪ˽㣬ʲ㡣
if (!*T)
{
t = (BiTree)malloc(sizeof(BiNode));
t->data = key;
t->height = 1;
t->lchild = NULL;
t->rchild = NULL;
*T = t;
return true;
}
//д˽㣬ٲ롣
else if (key == (*T)->data)
{
return false;
}
//еݹ롣
else if (key < (*T)->data)
{
if (!AVLInsert(&((*T)->lchild), key))
return false;
else
{
//ɹĸ߶ȡ
(*T)->height = __max(GetHeight((*T)->lchild), GetHeight((*T)->rchild)) + 1;
//*TkeyжǷҪתԱֶƽԡ
if (2 == GetHeight((*T)->lchild) - GetHeight((*T)->rchild))
{
//в㡣
if (GetHeight((*T)->lchild->lchild) > GetHeight((*T)->lchild->rchild))
{
LLRotate(T);
}
//в㡣
else
{
LRRotate(T);
}
}
return true;
}
}
//еݹ롣
else // (key > (*T)->data)
{
if (!AVLInsert(&(*T)->rchild, key))
return false;
else
{
//ɹĸ߶ȡ
(*T)->height = __max(GetHeight((*T)->lchild), GetHeight((*T)->rchild)) + 1;
//*TkeyжǷҪתԱֶƽԡ
if (-2 == GetHeight((*T)->lchild) - GetHeight((*T)->rchild))
{
//в㡣
if (GetHeight((*T)->rchild->lchild) > GetHeight((*T)->rchild->rchild))
{
RLRotate(T);
}
//в㡣
else
{
RRRotate(T);
}
}
return true;
}
}
}
/*
* ɾ
* *TΪдڽkeyɾTRUE
* ɾʧܣFALSE
*/
bool AVLDelete(BiTree *T, TElemType key)
{
BiTree pre, post;
//ûҵý㡣
if (!*T)
return false;
//ҵ㣬ɾ
else if (key == (*T)->data)
{
//ɾڵΪҶӽ㡣
if (!(*T)->lchild && !(*T)->rchild)
*T = NULL;
//ɾֻҺӡ
else if (!(*T)->lchild)
*T = (*T)->rchild;
//ɾֻӡ
else if (!(*T)->rchild)
*T = (*T)->lchild;
//ɾӣҺӡ
else
{
//ɾ*Tĸ߶ȴĸ߶ʱ*Tǰpre*T
//ٽpreɾԱ֤ɾΪƽ
if (GetHeight((*T)->lchild) > GetHeight((*T)->rchild))
{
//Ѱǰpre
pre = (*T)->lchild;
while (pre->rchild)
{
pre = pre->rchild;
}
//pre滻*T
(*T)->data = pre->data;
//ɾڵpre
//ȻܹȷpreСĸΪ&pre
//DzAVLDelete(&pre,pre->data)ɾpreĿǷݹĽڵĸ߶ȡ
AVLDelete(&((*T)->lchild), pre->data);
}
//ɾ*Tĸ߶Сڻߵĸ߶ʱ*Tĺ̽post*T
//ٽpostɾԱ֤ɾΪƽ
else
{
//ѰҺ̽ڵpost
post = (*T)->rchild;
while (post->lchild)
post = post->lchild;
//post滻*T
(*T)->data = post->data;
//ɾڵpost
//ȻܹȷpostСĸΪ&post
//DzAVLDelete(&post,post->data)ɾpostĿǷݹĽڵĸ߶ȡ
AVLDelete(&((*T)->rchild), post->data);
}
}
return true;
}
//еݹɾ
else if (key < (*T)->data)
{
if (!AVLDelete(&((*T)->lchild), key))
return false;
else
{
//ɾɹĸ߶ȡ
(*T)->height = __max(GetHeight((*T)->lchild), GetHeight((*T)->rchild)) + 1;
//*TɾkeyжǷҪתԱֶƽԡ
if (-2 == GetHeight((*T)->lchild) - GetHeight((*T)->rchild))
{
if (GetHeight((*T)->lchild->lchild) > GetHeight((*T)->lchild->rchild))
{
LLRotate(T);
}
else
{
LRRotate(T);
}
}
return true;
}
}
//еݹɾ
else
{
if (!AVLDelete(&((*T)->rchild), key))
return false;
else
{
//ɾɹĸ߶ȡ
(*T)->height = __max(GetHeight((*T)->lchild), GetHeight((*T)->rchild)) + 1;
//*TɾkeyжǷҪתԱֶƽԡ
if (2 == GetHeight((*T)->lchild) - GetHeight((*T)->rchild))
{
if (GetHeight((*T)->rchild->lchild) > GetHeight((*T)->rchild->rchild))
{
RLRotate(T);
}
else
{
RRRotate(T);
}
}
return true;
}
}
}
/*
* TϵĽڵʹTƽΪ2ʱTΪĽ
*/
bool LLRotate(BiTree *T)
{
BiTree lc;
lc = (*T)->lchild;
(*T)->lchild = lc->rchild;
lc->rchild = (*T);
//עҪ½ĸ߶ȡֻ*Tlc˱仯ֻĸ߶ȡ
(*T)->height = __max(GetHeight((*T)->lchild), GetHeight((*T)->rchild)) + 1;
lc->height = __max(GetHeight(lc->lchild), GetHeight(lc->rchild)) + 1;
*T = lc;
return true ;
}
/*
* TϵĽڵʹTƽΪ2ʱ
* TΪĽTΪĽ
*/
bool LRRotate(BiTree *T)
{
RRRotate(&((*T)->lchild));
LLRotate(T);
return true;
}
/*
* TϵĽڵʹTƽΪ-2ʱ
* TΪĽTΪĽ
*/
bool RLRotate(BiTree *T)
{
LLRotate(&((*T)->rchild));
RRRotate(T);
return true;
}
/*
* TϵĽڵʹTƽΪ-2ʱTΪĽ
*/
bool RRRotate(BiTree *T)
{
BiTree rc;
rc = (*T)->rchild;
(*T)->rchild = rc->lchild;
rc->lchild = (*T);
//עҪ½ĸ߶ȡֻ*Tlc˱仯ֻĸ߶ȡ
(*T)->height = __max(GetHeight((*T)->lchild), GetHeight((*T)->rchild)) + 1;
rc->height = __max(GetHeight(rc->lchild), GetHeight(rc->rchild)) + 1;
*T = rc;
return true;
}
/*
* T=NULL ,ΪʱͨT->heightȡĸ߶0Ҫдú
*/
int GetHeight(BiTree T)
{
if (T)
return T->height;
return 0;
} | true |
cdc661e000b852238f23a1f6ffb6fcdc1da32895 | C++ | aldeacristina96/programming_priciples_and_practice_exercices_solved | /Chapet4Ex16_Mode.cpp | UTF-8 | 875 | 3.9375 | 4 | [] | no_license | #include<iostream>
#include<vector>
/*
Get a set of values from the user and see which value repeted the most*/
using namespace std;
int main()
{
vector<int> v;
int a,contor=0,maxim=0;
int value;
//get the values from the user
cout<<"Plese introduce integer values.Press any leter to stop"<<endl;
while(cin>>a)
{
v.push_back(a);
}
//compare every value with all the values in the vector
for(int i=0; i<v.size(); i++)
{
contor=0;
for(int j=0; j<v.size(); j++)
{
if(v[i]==v[j])
{
contor++;
//how much the current value repeted itself
}
if(contor>maxim){
maxim=contor;
value=v[i];
}
}
}
cout<<"Value : "<<value<<" repetead "<<maxim<<" times."<<endl;
}
| true |
4dffe4ee088c3447a179d156b8143abfef0706dd | C++ | Xiangyan93/CPP_HEAD | /XYHeadFile/xy_function.h | UTF-8 | 4,972 | 3.296875 | 3 | [] | no_license | #ifndef XYFUNC_h
#define XYFUNC_h
void right_fprintf(FILE *fp, std::string line, unsigned n) {
if (n > 20) {
error("function: right_fprintf(FILE *fp, string line, unsigned n) can be used only for n <=20\n");
}
std::string temp = line;
temp.insert(0, " ", n - temp.size());
fprintf(fp, "%s", temp.c_str());
}
/*double atof(std::string s)*/
/*{*/
/*return atof(s.c_str());*/
/*}*/
//judge whether all elements in a vector is diffrent
bool IsOnlyOneTrue(unsigned num, ...) {
va_list ap;
va_start(ap, num);
unsigned k = 0;
for (unsigned i = 0;i < num;++i) {
bool temp=va_arg(ap, int);
if (temp) k++;
}
va_end(ap);
if (k == 1) return true;
else return false;
}
//square function
template <class Type>
Type square(Type value) {
Type s = value*value;
return s;
}
//judge whether a data can be found in a vector
template <class Type>
bool IsInside(Type in, std::vector<Type> value)
{
for(unsigned i=0;i<value.size();++i){
if(in==value[i])
return true;
}
return false;
}
template <class Type>
bool IsInside(Type in, std::vector<Type> value, unsigned &a)
{
for(unsigned i=0;i<value.size();++i){
if(in==value[i]){
a=i;
return true;
}
}
return false;
}
//
std::string HeadSpace(std::string s, unsigned length) {
if (s.length() > length) {
printf("%s,%d\n", s.c_str(), length);
error("In function std::string HeadSpace(string s, int length), the length of string s must small than int length\n");
return 0;
}
else {
std::string info;
unsigned l = length - s.length();
for (unsigned i = 0; i < l; ++i) info += " ";
info += s;
return info;
}
}
std::string TailSpace(std::string s, unsigned length) {
if (s.length() > length) {
printf("%s,%d\n", s.c_str(), length);
error("In function std::string TailSpace(string s, int length), the length of string s must small than int length\n");
return 0;
}
else {
std::string info = s;
unsigned l = length - s.length();
for (unsigned i = 0; i < l; ++i) info += " ";
return info;
}
}
//get the length of a integer
unsigned GetLength(unsigned num) {
unsigned l=1;
while (num > 10) {
num /= 10;
l++;
}
return l;
}
//get the minimum value of a vector
template <class Type>
Type GetMin(std::vector <Type> value)
{
Type min=value[0];
for(unsigned i=1;i<value.size();++i){
if(value[i]<min)
min = value[i];
}
return min;
}
//get the minimum value of a vector, and the position of the minimum value
template <class Type>
Type GetMin(std::vector <Type> value,unsigned &a)
{
Type min=value[0];
a=0;
for(unsigned i=1;i<value.size();++i){
if(value[i]<min){
min = value[i];
a=i;
}
}
return min;
}
//get the minimum value of a series of double type number
double GetMinDouble(unsigned num, ...) {
va_list ap;
va_start(ap, num);
double min = va_arg(ap, double);
for (unsigned i = 1;i < num;++i) {
double temp = va_arg(ap, double);
if (temp < min)
min = temp;
}
return min;
}
//get the minimum value of a series of int type number
int GetMinInt(unsigned num, ...) {
va_list ap;
va_start(ap, num);
int min = va_arg(ap, int);
for (unsigned i = 1;i < num;++i) {
int temp = va_arg(ap, int);
if (temp < min)
min = temp;
}
return min;
}
//get the maximum value of a vector
template <class Type>
Type GetMax(std::vector <Type> value)
{
Type max=value[0];
for(unsigned i=1;i<value.size();++i){
if(value[i]>max)
max = value[i];
}
return max;
}
//get the maximum value of a vector, and the position of the maximum value
template <class Type>
Type GetMax(std::vector <Type> value,unsigned &a)
{
Type max=value[0];
a=0;
for(unsigned i=1;i<value.size();++i){
if(value[i]>max){
max = value[i];
a=i;
}
}
return max;
}
//get product
//get sum
template <class Type>
Type GetSum(std::vector <Type> value)
{
Type a = 0;
for (unsigned i = 0;i<value.size();++i) {
a += value[i];
}
return a;
}
//get average
std::vector <double> GetAverage(std::vector <std::vector <double> > v) {
std::vector <double> temp(v[0].size(), 0);
for (unsigned i = 0; i < temp.size(); ++i) {
for (unsigned j = 0; j < v.size(); ++j) {
temp[i] += v[j][i];
}
temp[i] /= v.size();
}
return temp;
}
double GetAverage(std::vector <double> value)
{
double a=0.;
for(unsigned i=0;i<value.size();++i){
a += value[i];
}
return a/value.size();
}
//get standard deviation
double GetSTD(std::vector <double> value)
{
double sum=0.;
for(unsigned i=0;i<value.size();++i){
sum += value[i];
}
double average=sum/value.size();
double ebar=0.;
for(unsigned i=0;i<value.size();++i){
double dv = value[i]-average;
ebar += dv*dv;
}
ebar /= value.size()-1;
return sqrt(ebar);
}
#endif
| true |
0a02bd5a837d13ca12d70ac23a4af46fc8d29d4d | C++ | jinseongbe/cpp_study | /CPP_80(단언하기_Assert+StaticAssert)/CPP_80/main.cpp | UTF-8 | 835 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <cassert> // assert.h
#include <array>
// assert : 런타임중에 생기는 오류를 찾아서 알려주고, 어디인지 알려줌!
using namespace std;
void printValue(const array<int, 5> &my_array, const int &ix);
int main()
{
const int number = 5;
assert(number == 5);
std::array<int, 5> my_array{ 1, 2, 3, 4, 5 };
cout << my_array[5] << endl;
printValue(my_array, 100);
// static_assert
const int y = 5; // static_assert는 변수일때는 작동 암함! + 메세지를 남길수있음
static_assert(y == 5, "x should be 5");
return 0;
}
void printValue(const array<int, 5> &my_array, const int &ix)
{
assert(ix >= 0);
assert(ix <= my_array.size() - 1);
cout << my_array[ix] << endl;
}
| true |
3d60ee0d613ab987bae5e10ff084ea85a2c6c499 | C++ | VladyslavBychok/MesonProject | /abstract_factory/include/ConcreteProductA2.hpp | UTF-8 | 321 | 2.71875 | 3 | [] | no_license | #ifndef __CONCRETE_PRODUCT_A2_HPP
#define __CONCRETE_PRODUCT_A2_HPP
#include "AbstractProductA.hpp"
/**
* Concrete Products are created by corresponding Concrete Factories.
*/
class ConcreteProductA2 : public AbstractProductA {
std::string UsefulFunctionA() const override;
};
#endif // __CONCRETE_PRODUCT_A2_HPP | true |
565ac3a94443f80fee561e6f75ecde99e33006dd | C++ | shubhamsingh91/Pinocchio_ss | /unittest/symmetric.cpp | UTF-8 | 9,238 | 2.53125 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | //
// Copyright (c) 2015-2016,2018 CNRS
//
/* --- Unitary test symmetric.cpp This code tests and compares two ways of
* expressing symmetric matrices. In addition to the unitary validation (test
* of the basic operations), the code is validating the computation
* performances of each methods.
*
* The three methods are:
* - Eigen SelfAdjoint (a mask atop of a classical dense matrix) ==> the least efficient.
* - Pinocchio rewritting of Metapod code with LTI factor as well and minor improvement.
*
* IMPORTANT: the following timings seems outdated.
* Expected time scores on a I7 2.1GHz:
* - Eigen: 2.5us
* - Pinocchio: 6us
*/
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/skew.hpp"
#include "pinocchio/utils/timer.hpp"
#include <boost/random.hpp>
# include <eigen3/Eigen/Geometry>
#include "pinocchio/spatial/symmetric3.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/utility/binary.hpp>
# include <eigen3/Eigen/StdVector>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Matrix3d)
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(pinocchio::Symmetric3)
void timeSym3(const pinocchio::Symmetric3 & S,
const pinocchio::Symmetric3::Matrix3 & R,
pinocchio::Symmetric3 & res)
{
res = S.rotate(R);
}
#ifdef WITH_METAPOD
#include <metapod/tools/spatial/lti.hh>
#include <metapod/tools/spatial/rm-general.hh>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::ltI<double>)
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::RotationMatrixTpl<double>)
void timeLTI(const metapod::Spatial::ltI<double>& S,
const metapod::Spatial::RotationMatrixTpl<double>& R,
metapod::Spatial::ltI<double> & res)
{
res = R.rotTSymmetricMatrix(S);
}
#endif
void timeSelfAdj( const Eigen::Matrix3d & A,
const Eigen::Matrix3d & Sdense,
Eigen::Matrix3d & ASA )
{
typedef Eigen::SelfAdjointView<const Eigen::Matrix3d,Eigen::Upper> Sym3;
Sym3 S(Sdense);
ASA.triangularView<Eigen::Upper>()
= A * S * A.transpose();
}
BOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )
/* --- PINOCCHIO ------------------------------------------------------------ */
/* --- PINOCCHIO ------------------------------------------------------------ */
/* --- PINOCCHIO ------------------------------------------------------------ */
BOOST_AUTO_TEST_CASE ( test_pinocchio_Sym3 )
{
using namespace pinocchio;
typedef Symmetric3::Matrix3 Matrix3;
typedef Symmetric3::Vector3 Vector3;
{
// op(Matrix3)
{
Matrix3 M = Matrix3::Random(); M = M*M.transpose();
Symmetric3 S(M);
BOOST_CHECK(S.matrix().isApprox(M, 1e-12));
}
// S += S
{
Symmetric3
S = Symmetric3::Random(),
S2 = Symmetric3::Random();
Symmetric3 Scopy = S;
S+=S2;
BOOST_CHECK(S.matrix().isApprox(S2.matrix()+Scopy.matrix(), 1e-12));
}
// S + M
{
Symmetric3 S = Symmetric3::Random();
Matrix3 M = Matrix3::Random(); M = M*M.transpose();
Symmetric3 S2 = S + M;
BOOST_CHECK(S2.matrix().isApprox(S.matrix()+M, 1e-12));
S2 = S - M;
BOOST_CHECK(S2.matrix().isApprox(S.matrix()-M, 1e-12));
}
// S*v
{
Symmetric3 S = Symmetric3::Random();
Vector3 v = Vector3::Random();
Vector3 Sv = S*v;
BOOST_CHECK(Sv.isApprox(S.matrix()*v, 1e-12));
}
// Random
for(int i=0;i<100;++i )
{
Matrix3 M = Matrix3::Random(); M = M*M.transpose();
Symmetric3 S = Symmetric3::RandomPositive();
Vector3 v = Vector3::Random();
BOOST_CHECK_GT( (v.transpose()*(S*v))[0] , 0);
}
// Identity
{
BOOST_CHECK(Symmetric3::Identity().matrix().isApprox(Matrix3::Identity(), 1e-12));
}
// Skew2
{
Vector3 v = Vector3::Random();
Symmetric3 vxvx = Symmetric3::SkewSquare(v);
Vector3 p = Vector3::UnitX();
BOOST_CHECK((vxvx*p).isApprox(v.cross(v.cross(p)), 1e-12));
p = Vector3::UnitY();
BOOST_CHECK((vxvx*p).isApprox(v.cross(v.cross(p)), 1e-12));
p = Vector3::UnitZ();
BOOST_CHECK((vxvx*p).isApprox(v.cross(v.cross(p)), 1e-12));
Matrix3 vx = skew(v);
Matrix3 vxvx2 = (vx*vx).eval();
BOOST_CHECK(vxvx.matrix().isApprox(vxvx2, 1e-12));
Symmetric3 S = Symmetric3::RandomPositive();
BOOST_CHECK((S-Symmetric3::SkewSquare(v)).matrix()
.isApprox(S.matrix()-vxvx2, 1e-12));
double m = Eigen::internal::random<double>()+1;
BOOST_CHECK((S-m*Symmetric3::SkewSquare(v)).matrix()
.isApprox(S.matrix()-m*vxvx2, 1e-12));
Symmetric3 S2 = S;
S -= Symmetric3::SkewSquare(v);
BOOST_CHECK(S.matrix().isApprox(S2.matrix()-vxvx2, 1e-12));
S = S2; S -= m*Symmetric3::SkewSquare(v);
BOOST_CHECK(S.matrix().isApprox(S2.matrix()-m*vxvx2, 1e-12));
}
// (i,j)
{
Matrix3 M = Matrix3::Random(); M = M*M.transpose();
Symmetric3 S(M);
for(int i=0;i<3;++i)
for(int j=0;j<3;++j)
BOOST_CHECK_SMALL(S(i,j) - M(i,j), Eigen::NumTraits<double>::dummy_precision());
}
}
// SRS
{
Symmetric3 S = Symmetric3::RandomPositive();
Matrix3 R = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();
Symmetric3 RSRt = S.rotate(R);
BOOST_CHECK(RSRt.matrix().isApprox(R*S.matrix()*R.transpose(), 1e-12));
Symmetric3 RtSR = S.rotate(R.transpose());
BOOST_CHECK(RtSR.matrix().isApprox(R.transpose()*S.matrix()*R, 1e-12));
}
// Test operator vtiv
{
Symmetric3 S = Symmetric3::RandomPositive();
Vector3 v = Vector3::Random();
double kinetic_ref = v.transpose() * S.matrix() * v;
double kinetic = S.vtiv(v);
BOOST_CHECK_SMALL(kinetic_ref - kinetic, 1e-12);
}
// Test v x S3
{
Symmetric3 S = Symmetric3::RandomPositive();
Vector3 v = Vector3::Random();
Matrix3 Vcross = skew(v);
Matrix3 M_ref(Vcross * S.matrix());
Matrix3 M_res;
Symmetric3::vxs(v,S,M_res);
BOOST_CHECK(M_res.isApprox(M_ref));
BOOST_CHECK(S.vxs(v).isApprox(M_ref));
}
// Test S3 vx
{
Symmetric3 S = Symmetric3::RandomPositive();
Vector3 v = Vector3::Random();
Matrix3 Vcross = skew(v);
Matrix3 M_ref(S.matrix() * Vcross);
Matrix3 M_res;
Symmetric3::svx(v,S,M_res);
BOOST_CHECK(M_res.isApprox(M_ref));
BOOST_CHECK(S.svx(v).isApprox(M_ref));
}
// Test isZero
{
Symmetric3 S_not_zero = Symmetric3::Identity();
BOOST_CHECK(!S_not_zero.isZero());
Symmetric3 S_zero = Symmetric3::Zero();
BOOST_CHECK(S_zero.isZero());
}
// Test isApprox
{
Symmetric3 S1 = Symmetric3::RandomPositive();
Symmetric3 S2 = S1;
BOOST_CHECK(S1.isApprox(S2));
Symmetric3 S3 = S1;
S3 += S3;
BOOST_CHECK(!S1.isApprox(S3));
}
// Time test
{
const size_t NBT = 100000;
Symmetric3 S = Symmetric3::RandomPositive();
std::vector<Symmetric3> Sres (NBT);
std::vector<Matrix3> Rs (NBT);
for(size_t i=0;i<NBT;++i)
Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();
std::cout << "Pinocchio: ";
PinocchioTicToc timer(PinocchioTicToc::US); timer.tic();
SMOOTH(NBT)
{
timeSym3(S,Rs[_smooth],Sres[_smooth]);
}
timer.toc(std::cout,NBT);
}
}
/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
BOOST_AUTO_TEST_CASE ( test_eigen_SelfAdj )
{
using namespace pinocchio;
typedef Eigen::Matrix3d Matrix3;
typedef Eigen::SelfAdjointView<Matrix3,Eigen::Upper> Sym3;
Matrix3 M = Matrix3::Random();
Sym3 S(M);
{
Matrix3 Scp = S;
BOOST_CHECK((Scp-Scp.transpose()).isApprox(Matrix3::Zero(), 1e-16));
}
Matrix3 M2 = Matrix3::Random();
M.triangularView<Eigen::Upper>() = M2;
Matrix3 A = Matrix3::Random(), ASA1, ASA2;
ASA1.triangularView<Eigen::Upper>() = A * S * A.transpose();
timeSelfAdj(A,M,ASA2);
{
Matrix3 Masa1 = ASA1.selfadjointView<Eigen::Upper>();
Matrix3 Masa2 = ASA2.selfadjointView<Eigen::Upper>();
BOOST_CHECK(Masa1.isApprox(Masa2, 1e-16));
}
const size_t NBT = 100000;
std::vector<Eigen::Matrix3d> Sres (NBT);
std::vector<Eigen::Matrix3d> Rs (NBT);
for(size_t i=0;i<NBT;++i)
Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();
std::cout << "Eigen: ";
PinocchioTicToc timer(PinocchioTicToc::US); timer.tic();
SMOOTH(NBT)
{
timeSelfAdj(Rs[_smooth],M,Sres[_smooth]);
}
timer.toc(std::cout,NBT);
}
BOOST_AUTO_TEST_CASE(comparison)
{
using namespace pinocchio;
Symmetric3 sym1(Symmetric3::Random());
Symmetric3 sym2(sym1);
sym2.data() *= 2;
BOOST_CHECK(sym2 != sym1);
BOOST_CHECK(sym1 == sym1);
}
BOOST_AUTO_TEST_CASE(cast)
{
using namespace pinocchio;
Symmetric3 sym(Symmetric3::Random());
BOOST_CHECK(sym.cast<double>() == sym);
BOOST_CHECK(sym.cast<long double>().cast<double>() == sym);
}
BOOST_AUTO_TEST_SUITE_END ()
| true |
e83e47edd8f49b02f0c9db49f6669e7e066adf84 | C++ | JZChrysos/Graph | /graph/main.cpp | UTF-8 | 4,000 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
// adjacency table
// weight 0 will be considered as no edge
float adj[20][20];
//labels
char labels[20];
// added
bool vadded[20];
//add edge
void addedge(int from, int to, float weight){
adj[from - 1][to - 1] = weight;
}
//remove vertex
void remvert(int num){
for(int i = 0; i<20; i++){
adj[num - 1][i] = 0;
adj[i][num - 1] = 0;
}
}
//remove edge
void remedge(int from, int to){
adj[from - 1][to - 1] = 0;
}
//dijkstra algorithm
void path(int from, int to){
bool visited[20]; // true if vertex is visited, false if not
float dist[20]; // effective distance from start node, 0 will mean no connection
for(int i=0; i<20; i++){
visited[i] = false;
if(i + 1 == from){
dist[i] = 0;
}
else{
dist[i] = adj[from - 1][i];
}
}
for(int i=0; i<20; i++){
for(int j=0; j<20; j++){
if(dist[i] != 0 && adj[i][j] != 0 && (dist[j] == 0 || dist[j] > dist[i] + adj[i][j])){
dist[j] = dist[i]+adj[i][j];
}
}
visited[i] = true;
}
if(dist[to-1] != 0){
cout << "The minimum distance from vertex " << from << " to " << to << " is "<< dist[to-1]<< endl;
}
else{
cout << "There is no path from vertex " <<from << " to " << to << endl;
}
}
//search
int search(char lab){
int i=0;
bool quit = false;
while(i<20 && quit == false){
if(labels[i]==lab && vadded[i] == true){
return i;
quit = true;
}
else{
i++;
}
}
return 88; // not found
}
int main(){
for(int i=0; i<20;i++){
vadded[i] = false;
labels[i] = 'a';
for(int j=0;j<20;j++){
adj[i][j] = 0;
}
}
bool quit = false;
while(quit == false){
cout <<"Welcome to graph creator! Would you like to print (PR), add vertex (AV), remove vertex (RV), add edge (AE), remove edge (RE), or find a shortest path (SP)? Or quit (Q). ";
char input[5];
cin >> input;
if(strcmp(input, "AV") == 0){
bool added = false;
int i = 0;
while(added == false && i<20){
if(vadded[i]==false){
added = true;
vadded[i] = true;
}
else{
i++;
}
}
cout << "Give the vertex a character label: ";
char lab;
cin >> lab;
labels[i] = lab;
if(added == true){
cout <<endl <<"Vertex Added." << endl;
}
else{
cout << "No more vertices for you, 20 is the max" << endl;
}
}
else if(strcmp(input, "RV") == 0){
cout << "remove which vertex? ";
char uservertex;
cin >> uservertex;
remvert(search(uservertex));
vadded[search(uservertex)] = false;
}
else if(strcmp(input, "AE") == 0){
cout << "Specify the edge you would like to add." << endl;
cout << "Start vertex: ";
char from;
cin >> from;
cout << endl << "End vertex: ";
char to;
cin >> to;
cout << endl << "Weight: ";
float weight;
cin >> weight;
addedge(search(from)+1, search(to)+1, weight);
}
else if(strcmp(input, "RE") == 0){
cout << "Specify the edge you would like to remove." << endl;
cout << "Start vertex: ";
char from;
cin >> from;
cout << endl << "End vertex: ";
char to;
cin >> to;
remedge(search(from)+1, search(to)+1);
}
else if(strcmp(input, "SP") == 0){
cout << "What path do you want to find?" << endl;
cout << "Start vertex: ";
char from;
cin >> from;
cout << endl << "End vertex: ";
char to;
cin >> to;
path(search(from)+1, search(to)+1);
}
else if(strcmp(input, "PR") == 0){
cout << " ";
for(int i=0; i<20; i++){
if(vadded[i] == true){
cout << left << setw(8) << setfill(' ') << labels[i];
}
else{
cout << left << setw(8) << setfill(' ') << " ";
}
}
cout << endl;
for(int i=0; i<20; i++){
if(vadded[i] == true){
cout << left << setw(8) << setfill(' ') << labels[i];
}
else{
cout << left << setw(8) << setfill(' ') << " ";
}
for(int j=0; j<20; j++){
if(adj[i][j] != 0){
cout << left << setprecision(3) << setw(8) << setfill(' ') << adj[i][j];
}
else{
cout << left << setw(8) << setfill(' ') << " ";
}
}
cout << endl;
}
}
else{
quit = true;
}
}
return 0;
}
| true |
07c33080c03f86e26c755db1a801a9cf58225176 | C++ | halfmvsq/histolozee | /src/imageio/util/MathFuncs.cpp | UTF-8 | 3,314 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include "MathFuncs.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/transform.hpp>
#include <algorithm>
#include <array>
#include <limits>
namespace imageio
{
namespace math
{
glm::dvec3 subjectImageDimensions(
const glm::u64vec3& pixelDimensions,
const glm::dvec3& pixelSpacing )
{
return glm::dvec3{ static_cast<double>( pixelDimensions.x ) * pixelSpacing.x,
static_cast<double>( pixelDimensions.y ) * pixelSpacing.y,
static_cast<double>( pixelDimensions.z ) * pixelSpacing.z };
}
glm::dmat4 computeImagePixelToSubjectTransformation(
const glm::dmat3& directions,
const glm::dvec3& pixelSpacing,
const glm::dvec3& origin )
{
return glm::dmat4{
glm::dvec4{ pixelSpacing.x * directions[0], 0.0 }, // column 0
glm::dvec4{ pixelSpacing.y * directions[1], 0.0 }, // column 1
glm::dvec4{ pixelSpacing.z * directions[2], 0.0 }, // column 2
glm::dvec4{ origin, 1.0 } }; // column 3
}
glm::dmat4 computeImagePixelToTextureTransformation(
const glm::u64vec3& pixelDimensions )
{
const glm::dvec3 invDim( 1.0 / pixelDimensions.x,
1.0 / pixelDimensions.y,
1.0 / pixelDimensions.z );
return glm::translate( 0.5 * invDim ) * glm::scale( invDim );
}
std::pair< glm::dvec3, glm::dvec3 > computeImageSubjectAABBoxCorners(
const glm::u64vec3& pixelDimensions,
const glm::dmat3& directions,
const glm::dvec3& pixelSpacing,
const glm::dvec3& origin )
{
// Image has 8 corners
static constexpr size_t N = 8;
const glm::dmat4 subject_O_pixel = computeImagePixelToSubjectTransformation(
directions, pixelSpacing, origin );
const glm::u64vec3 D = pixelDimensions - glm::u64vec3{ 1, 1, 1 };
const std::array< glm::dvec3, N > pixelCorners =
{
glm::dvec3{ 0.0, 0.0, 0.0 },
glm::dvec3{ D.x, 0.0, 0.0 },
glm::dvec3{ 0.0, D.y, 0.0 },
glm::dvec3{ D.x, D.y, 0.0 },
glm::dvec3{ 0.0, 0.0, D.z },
glm::dvec3{ D.x, 0.0, D.z },
glm::dvec3{ 0.0, D.y, D.z },
glm::dvec3{ D.x, D.y, D.z }
};
std::array< glm::dvec3, N > subjectCorners;
std::transform( std::begin( pixelCorners ),
std::end( pixelCorners ),
std::begin( subjectCorners ),
[ &subject_O_pixel ]( const glm::dvec3& v )
{
return glm::dvec3{ subject_O_pixel * glm::dvec4{ v, 1.0 } };
} );
glm::dvec3 minSubjectCorner{ std::numeric_limits<double>::max() };
glm::dvec3 maxSubjectCorner{ std::numeric_limits<double>::lowest() };
for ( uint32_t c = 0; c < N; ++c )
{
for ( int i = 0; i < 3; ++i )
{
if ( subjectCorners[c][i] < minSubjectCorner[i] )
{
minSubjectCorner[i] = subjectCorners[c][i];
}
if ( subjectCorners[c][i] > maxSubjectCorner[i] )
{
maxSubjectCorner[i] = subjectCorners[c][i];
}
}
}
return std::make_pair( minSubjectCorner, maxSubjectCorner );
}
} // namespace math
} // namespace imageio
| true |
5a609925118fe3ec0497435efd4a939e7e2f9893 | C++ | PrajBak/Ray-Tracer-in-One-Weekend | /Ray Tracer/camera.h | UTF-8 | 885 | 2.9375 | 3 | [] | no_license | #pragma once
#include "ray.h"
class camera {
public:
camera()
: asp_(0.0f),
focal_length_(0.0f),
origin_(float3(0.0f)),
horizontal_(float3(0.0f)),
vertical_(float3(0.0f)) {}
camera(float3 origin, float width, float height)
: origin_(origin) {
asp_ = width / height;
const float view_height = 2.0f;
const float view_width = view_height * asp_;
focal_length_ = 1.0f;
horizontal_ = float3(view_width, 0.0f, 0.0f);
vertical_ = float3(0.0f, view_height, 0.0f);
lower_left_ = origin - horizontal_/2.0f
- vertical_ / 2.0f - float3(0.0f, 0.0f, focal_length_);
}
ray get_ray_to(const float u, const float v) const {
return ray(origin_, lower_left_ + u * horizontal_ + v * vertical_ - origin_);
}
private:
float asp_;
float focal_length_;
float3 origin_;
float3 horizontal_;
float3 vertical_;
float3 lower_left_;
}; | true |
35313283c456ff8878dcd86a0660b6a4e29b6f1f | C++ | rishusingh022/Standard-Template-Libraries | /wave_print.cpp | UTF-8 | 897 | 3.296875 | 3 | [
"MIT"
] | permissive | // Sample Input: 4 4
// 11 12 13 14
// 21 22 23 24
// 31 32 33 34
// 41 42 43 44
// Output Format: All M * N integers seperated by commas with 'END' wriiten in the end(as shown in example).
// Sample Output: 11, 21, 31, 41, 42, 32, 22, 12, 13, 23, 33, 43, 44, 34, 24, 14, END
// =====Solution=====
#include <iostream>
using namespace std;
int main() {
int nRow,nCol;
std::cin >> nRow >> nCol;
int a[nRow][nCol];
for (int i = 0; i < nRow; i++) {
for (int j = 0; j < nCol; j++) {
std::cin >> a[i][j];
}
}
for (int j = 0; j < nCol; j++) {
if(j&1){
for (int i = nRow-1; i >= 0; i--) {
std::cout << a[i][j] << ", ";
}
}else{
for (int i = 0; i < nRow; i++) {
std::cout << a[i][j] << ", ";
}
}
}
std::cout << "END" << std::endl;
} | true |
eb8fcd6259dcfcec7b926bfaff0ae35494a21505 | C++ | Sonny-kun/baitapLTNC | /baitapweek3/Phan A/bai5.cpp | UTF-8 | 489 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
srand(time(NULL));
int f[30];
for (int i=0; i<30; i++) {
f[i]=rand()%100+1;
cout<<f[i]<<" ";
}
cout<<endl;
for (int i=0; i<29; i++){
for (int j=i+1; j <30; j++)
{
if (f[i] > f[j]) {
int sw=f[i];
f[i]=f[j];
f[j]=sw;
}
}
}
for (int i=0; i<30; i++)
{
cout<<f[i]<<" ";
}
return 0;
}
| true |
e2d095b82c3e4beb306f5e03f68fe3fb985eb05a | C++ | zeroplusone/AlgorithmPractice | /Leetcode/540. Single Element in a Sorted Array-2.cpp | UTF-8 | 426 | 2.71875 | 3 | [] | no_license | class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n=nums.size();
int l=0, r=n-1;
while(l<r) {
int mid=(l+r)>>1;
if(mid%2==1) {
mid--;
}
if(nums[mid]==nums[mid+1]) {
l=mid+2;
} else {
r=mid;
}
}
return nums[r];
}
};
| true |
e751c4e8746a8fca0166feb64a7a77ba3049d661 | C++ | Jamxscape/LearnCPlusPlus | /1/1/2.cpp | UTF-8 | 1,178 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
#include <string>
using namespace std;
int main()
{
string a;
int n=0;
int p=0,t;
while(getline(cin,a)){
for (int i=0;i<a.length();i++)
{
if(i==0){
for(int j=i;j<a.length();j++){
if(a[j]==' '){break;}
n++;
}
p=n;
i=i+n;
}
n=0;
while(a[i]==' '){
for(int j=i+1;j<a.length();j++){
if(a[j]==' '){break;}
n++;
}
t=n;
if(t>p){p=t;}
i=i+n;
}
n=0;
}
cout<<p<<endl;
for(int i=0;i<a.length();i++)
{
if(i==0&&a[i+p]==' ')
{
for(int j=0;j<=p;j++)
cout<<a[j];
i=i+p;
cout<<' ';
}
else if((a[i]==' '&&a[i+p+1]==' ')||(a[i]==' '&&i+p+1==a.length())){
for(int j=i+1;j<=i+p;j++)
cout<<a[j];
cout<<' ';
i=i+p;
}
}
cout<<endl;p=0;n=0;
}
return 0;
}
| true |
5f0e1ec042731ea246a2cfde2fa888d6ec18bfcf | C++ | s00ler/parallels | /task2/triplet.h | UTF-8 | 1,351 | 3.734375 | 4 | [] | no_license | #ifndef TASK2_TRIPLET_H
#define TASK2_TRIPLET_H
#include <iostream>
template <typename T>
struct triplet {
T x {}, y {}, z {};
triplet(T x = 0, T y = 0, T z = 0) {
this->x = x;
this->y = y;
this->z = z;
}
triplet operator* (T value) {
return {x * value,
y * value,
z * value};
}
triplet operator/ (T value) {
return {x / value,
y / value,
z / value};
}
triplet operator+ (T value) {
return {x + value,
y + value,
z + value};
}
triplet operator- (T value) {
return {x - value,
y - value,
z - value};
}
void print() {
std::cout << *this << std::endl;
}
template <typename CT>
friend std ::ostream& operator<< (std::ostream& os, const triplet<CT>& obj);
};
template <typename CT>
std::ostream& operator<< (std::ostream& os, const triplet<CT>& obj) {
os << "x = " << obj.x << ", "
<< "y = " << obj.y << ", "
<< "z = " << obj.z;
return os;
}
#endif //TASK2_TRIPLET_H
| true |
e36013d0702aa74ade743c43a9135235d6876517 | C++ | darzouras/OSU-Assignments | /CS162/ModuleC/Path.hpp | UTF-8 | 772 | 2.5625 | 3 | [] | no_license | /*********************************************************************
** Program Filename: Path.cpp
** Author: Darlene Zouras
** Date: 4/13/2016
** Description: Path class header file
** Holds variables and function headers for the Path class.
*********************************************************************/
#ifndef PATH_HPP
#define PATH_HPP
#include "Ant.hpp"
class Ant;
class Critter;
class Path {
private:
int x;
int y;
int numMoves;
char empty;
char crit;
Ant* **grid;
int numCritters;
int critX;
int critY;
int names;
public:
Path(int a, int b);
void setCritters(int crits);
void findCritters();
void run(int numMoves);
void gridSet(Ant* **&grid);
void gridDisplay();
void remove();
};
#endif
| true |
ae2714c47fc9db6388a3670f84881cc20c5a9d3e | C++ | tvs/sol | /src/image/image.cpp | UTF-8 | 3,074 | 3.421875 | 3 | [] | no_license | #include "image.h"
// #include <iostream>
#include <fstream>
using namespace std;
Image::Image() {}
Image::Image(int width, int height) {
nx = width; ny = height;
raster = new RGB*[nx];
for (int i = 0; i < nx; i++)
raster[i] = new RGB[ny];
}
Image::Image(int width, int height, RGB background) {
nx = width; ny = height;
raster = new RGB*[nx];
for (int i = 0; i < nx; i++) {
raster[i] = new RGB[ny];
for (int j = 0; j < ny; j++)
raster[i][j] = background;
}
}
bool Image::set(int x, int y, const RGB& color) {
// Check out-of-bounds errors
if (0 > x || x > nx) return false;
if (0 > y || y > ny) return false;
raster[x][y] = color;
return true;
}
void Image::gammaCorrect(double gamma) {
RGB temp;
double power = 1.0/gamma;
for (int i = 0; i < nx; i++)
for (int j = 0; j < ny; j++) {
temp = raster[i][j];
raster[i][j] = RGB(pow(temp.r(), power),
pow(temp.g(), power),
pow(temp.b(), power));
}
}
void Image::writePPM(ostream& out) {
// Output header
out << "P6\n";
out << nx << ' ' << ny << '\n';
out << "255\n";
int i, j;
unsigned int ired, igreen, iblue;
unsigned char red, green, blue;
// output clamped [0, 255] values
for (i = ny-1; i >= 0; i--)
for(j = 0; j < nx; j++) {
ired = (unsigned int) (256*raster[j][i].r());
igreen = (unsigned int) (256*raster[j][i].g());
iblue = (unsigned int) (256*raster[j][i].b());
if (ired > 255) ired = 255;
if (igreen > 255) igreen = 255;
if (iblue > 255) iblue = 255;
red = (unsigned char) (ired);
green = (unsigned char) (igreen);
blue = (unsigned char) (iblue);
out.put(red);
out.put(green);
out.put(blue);
}
}
// reads in a binary PPM
void Image::readPPM(string file_name) {
// open stream to file
ifstream in;
in.open(file_name.c_str());
if (!in.is_open()) {
cerr << " ERROR -- Couldn't open file \'" << file_name << "\' .\n";
exit(-1);
}
char ch, type;
char red, green, blue;
int i, j, cols, rows;
int num;
// read in header info
in.get(ch);
in.get(type);
in >> cols >> rows >> num;
nx = cols;
ny = rows;
// allocate raster
raster = new RGB*[nx];
for (i = 0; i < nx; i++)
raster[i] = new RGB[ny];
// Clean up newline
in.get(ch);
// Store PPM pixel values in raster
for (i = ny-1; i >= 0; i--)
for (j = 0; j < nx; j++) {
in.get(red);
in.get(green);
in.get(blue);
raster[j][i] = RGB((double) ((unsigned char) red)/255.0,
(double) ((unsigned char) green)/255.0,
(double) ((unsigned char) blue)/255.0);
}
} | true |
30d57608ce634be1e0ec32573e67a020db875233 | C++ | eheath23/RapidSynthVST | /SynthGUI/Source/OscillatorComponent.h | UTF-8 | 1,708 | 2.625 | 3 | [] | no_license | /*
==============================================================================
OscillatorComponent.h
Created: 6 Mar 2017 5:18:11pm
Author: Eliot Heath
==============================================================================
*/
#ifndef OSCILLATORCOMPONENT_H_INCLUDED
#define OSCILLATORCOMPONENT_H_INCLUDED
#include "../JuceLibraryCode/JuceHeader.h"
//==============================================================================
/*
*/
class OscillatorComponent : public Component
{
public:
OscillatorComponent()
{
dial1.setSliderStyle (Slider::Rotary);
dial1.setTextBoxStyle (Slider::NoTextBox, false, 0, 0);
addAndMakeVisible (dial1);
dial2.setSliderStyle (Slider::Rotary);
dial2.setTextBoxStyle (Slider::NoTextBox, false, 0, 0);
addAndMakeVisible (dial2);
}
~OscillatorComponent()
{
}
void paint (Graphics& g) override
{
// g.fillAll (Colours::darkred); // clear the background
// g.setColour (Colours::white);
// g.drawRect (getLocalBounds(), 1); // draw an outline around the component
}
void resized() override
{
int border = 10;
auto r = getLocalBounds();
auto titleArea = r.removeFromTop(50);
auto dialArea = r;
dial1.setBounds(dialArea.removeFromTop (dialArea.getHeight() / 2).reduced (border));
dial2.setBounds(dialArea.reduced(border));
}
private:
Slider dial1;
Slider dial2;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OscillatorComponent)
};
#endif // OSCILLATORCOMPONENT_H_INCLUDED
| true |
96a68367b56bcd598c343a3db6c8fc3398d65a01 | C++ | anjalipanikar/CS_Projects | /Hunt The Wumpus/gameflow.cpp | UTF-8 | 16,023 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string>
#include "wumpus.h"
#include "room.h"
#include "event.h"
#include "pit.h"
#include "bat.h"
#include "wumpus.h"
#include "gold.h"
#include "hunter.h"
using namespace std;
/*********************************************************************
* ** Function: display_cave
* ** Description: displays cave contents
* ** Pre-Conditions: filled cave
* ** Post-Conditions: None
* *********************************************************************/
void display_cave(vector < vector< Room > > &cave, int size, string mode, Hunter& hunter) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout << "+---";
}
cout << "+" << endl << "|";
for (int j = 0; j < size; j++) {
//for regular mode
if (mode == "false") {
if (hunter.x == i && hunter.y == j) {
cout << " " << "*" << " ";
} else {
cout << " ";
}
cout << "|";
}
//for debug mode
if (mode == "true") {
if (hunter.x == i && hunter.y == j) {
cout << " " << "*" << " ";
} else if (cave[i][j].get_event()->event() != " ") {
cout << " " << cave[i][j].get_event()->event() << " ";
} else {
cout << " ";
}
cout << "|";
}
}
cout << endl;
}
for (int i = 0; i < size; i++) {
cout << "+---";
}
cout << "+";
cout << endl;
}
/*********************************************************************
* ** Function: set_x
* ** Description: these functions randomly select an x and y coordinate to set events in
* ** Parameters: cave, size, object
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void set_bat(vector< vector< Room > > &cave, int size, Bat& b) {
srand(time(NULL));
int x_bat = rand() % size;
int y_bat = rand() % size;
bool check = false;
while (check != true) {
while (cave[x_bat][y_bat].get_event()->event() != " ") {
x_bat = rand() % size;
y_bat = rand() % size;
}
cave[y_bat][y_bat].set_event(b);
check = true;
}
}
void set_pit(vector< vector< Room > > &cave, int size, Pit& p) {
srand(time(NULL));
int x_pit = rand() % size;
int y_pit = rand() % size;
bool check = false;
while (check != true) {
while (cave[x_pit][y_pit].get_event()->event() != " ") {
x_pit = rand() % size;
y_pit = rand() % size;
}
cave[x_pit][y_pit].set_event(p);
check = true;
}
}
void set_wumpus(vector< vector< Room > > &cave, int size, Wumpus& w) {
srand(time(NULL));
int x_wumpus = rand() % size;
int y_wumpus = rand() % size;
bool check = false;
while (check != true) {
while (cave[x_wumpus][y_wumpus].get_event()->event() != " ") {
x_wumpus = rand() % size;
y_wumpus = rand() % size;
}
cave[x_wumpus][y_wumpus].set_event(w);
check = true;
}
}
void set_gold(vector< vector< Room > > &cave, int size, Gold& g) {
srand(time(NULL));
int x_gold = rand() % size;
int y_gold = rand() % size;
bool check = false;
while (check != true) {
while (cave[x_gold][y_gold].get_event()->event() != " ") {
x_gold = rand() % size;
y_gold = rand() % size;
}
cave[x_gold][y_gold].set_event(g);
check = true;
}
}
void set_hunter_start(vector< vector< Room > > &cave, int size, Hunter& hunter, HunterStart& s) {
srand(time(NULL));
hunter.count = 1;
int x_start = rand() % size;
int y_start = rand() % size;
bool check = false;
while (check != true) {
while (cave[x_start][y_start].get_event()->event() != " ") {
x_start = rand() % size;
y_start = rand() % size;
}
cave[x_start][y_start].set_event(s);
hunter.x = x_start;
hunter.y = y_start;
check = true;
}
}
void set_empty(vector< vector< Room > > &cave, int size, Fill& f) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cave[i][j].set_event(f);
}
}
}
void set_all(vector< vector< Room > > &cave, int size, Bat& b, Pit& p, Wumpus& w, Gold& g, Fill& f, Hunter& hunter, HunterStart& s) {
set_empty(cave, size, f);
set_bat(cave, size, b);
set_pit(cave, size, p);
set_wumpus(cave, size, w);
set_gold(cave, size, g);
set_hunter_start(cave, size, hunter, s);
}
/*********************************************************************
* ** Function: is_player_alive
* ** Description: these functions check to see if player is still alive in game
* ** Parameters: cave vector, hunter
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
string is_player_alive(vector< vector< Room > > &cave, Hunter& hunter) {
if (cave[hunter.x][hunter.y].get_event()->event() == "W") {
return "death_by_wumpus";
} else if (cave[hunter.x][hunter.y].get_event()->event() == "P") {
return "death_by_pit";
} else {
return "alive";
}
}
/*********************************************************************
* ** Function: check_adjacent2
* ** Description: these functions check adjacent rooms to sense an event
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void check_adjacent2(vector< vector< Room > > &cave, int x, int y, Hunter& hunter) {
if (cave[x][y].get_event()->event() == " ") {
return;
}
if (cave[x][y].get_event()->event() == "W") {
cout << "You smell a terrible stench nearby." << endl;
return;
}
if (cave[x][y].get_event()->event() == "P") {
cout << "You feel a breeze." << endl;
return;
}
if (cave[x][y].get_event()->event() == "B") {
cout << "You hear wings flapping." << endl;
return;
}
if (cave[x][y].get_event()->event() == "G") {
cout << "You see a glimmer nearby." << endl;
return;
}
}
/*********************************************************************
* ** Function: check_event
* ** Description: these functions check to see if player is in a room w/ an event
* ** Parameters: cave vector, objects, size, mode
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void check_event(vector< vector< Room > > &cave, int size, Bat& b, Pit& p, Wumpus& w, Gold& g, Fill& f, Hunter& hunter, HunterStart& s, string mode) {
srand(time(NULL));
//check room for gold
if (cave[hunter.x][hunter.y].get_event()->event() == "G") {
cout << "\nYou've found the gold! Quick, return back to your starting position to escape the cave with your treasure!" << endl;
}
if (cave[hunter.x][hunter.y].get_event()->event() == "B") {
int x_rand = rand() % size;
int y_rand = rand() % size;
hunter.x = x_rand;
hunter.y = y_rand;
cout << "\nYou just entered the room with Bats! Your position was randomly displaced." << endl;
display_cave(cave, size, mode, hunter);
}
if (cave[hunter.x][hunter.y].get_event()->event() == "S" && hunter.count == 2) {
cout << "\nCongrats! you escaped the Wumpus' cave with the gold!" << endl;
cout << "Would you like to play again? y/n " << endl;
string ans;
getline(cin, ans);
if (ans == "n") {
cout << "Thanks for playing!" << endl;
exit (EXIT_FAILURE);
}
cout << "Would you like to restart the game with the same cave configuration (1) or a new one (2)?" << endl;
getline(cin, ans);
if (ans == "1") {
//play(cave, size, b, p, w, g, hunter, s, mode);
}
if (ans == "2") {
set_all(cave, size, b, p, w, g, f, hunter, s);
//play(cave, size, b, p, w, g, hunter, s, mode);
}
}
}
/*********************************************************************
* ** Function: check_adjacent1
* ** Description: these functions aid in moving to the right rooms
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void check_adjacent1(vector< vector< Room > > &cave, int size, string mode, Hunter& hunter) {
bool moveUp = false, moveDown = false, moveLeft = false, moveRight = false;
//find adjacent rooms
int x_above = hunter.x - 1, y_above = hunter.y,
x_below = hunter.x + 1, y_below = hunter.y,
x_left = hunter.x, y_left = hunter.y - 1,
x_right = hunter.x, y_right = hunter.y + 1;
//check adjacent room validity
if (x_above >=0 && x_above < size) {
moveUp = true;
}
if (x_below >=0 && x_below < size) {
moveDown = true;
}
if (y_left >=0 && y_left < size) {
moveLeft = true;
}
if (y_right >=0 && y_right < size) {
moveRight = true;
}
//check for percepts
if (moveUp) {
check_adjacent2(cave, x_above, y_above, hunter);
}
if (moveDown) {
check_adjacent2(cave, x_below, y_below, hunter);
}
if (moveLeft) {
check_adjacent2(cave, x_left, y_left, hunter);
}
if (moveRight) {
check_adjacent2(cave, x_right, y_right, hunter);
}
}
/*********************************************************************
* ** Function: instructions
* ** Description: these functions display the instructions for the player to make a move
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void instructions(Hunter& hunter) {
cout << "\n\nSelect any of the commands below to make your next move." << endl;
cout << "\nCommands:" << endl;
cout << "\tw (North)" << endl;
cout << "\ts (South)" << endl;
cout << "\td (East)" << endl;
cout << "\ta (West)" << endl;
cout << "\tw (North)" << endl;
cout << "\tSpacebar + w, s, d, or a (Shoot Arrow + Direction)" << endl;
cout << "\tq (Quit)" << endl;
cout << "\nNumber of Arrows: " << hunter.num_arrows << endl;
cout << "\nType your command ";
}
/*********************************************************************
* ** Function: moves
* ** Description: this function makes sure the players desired move is in bounds
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void moves(Hunter& hunter, int size, string input) {
if (input == "w") {
while (hunter.x - 1 < 0) {
cout << "You are trying to move out of bounds. Pick another direction" << endl;
getline(cin, input);
moves(hunter, size, input);
}
hunter.x = hunter.x - 1;
}
if (input == "s") {
while (hunter.x + 1 > (size - 1)) {
cout << "You are trying to move out of bounds. Pick another direction" << endl;
getline(cin, input);
moves(hunter, size, input);
}
hunter.x = hunter.x + 1;
}
if (input == "d") {
while (hunter.y + 1 > (size - 1)) {
cout << "You are trying to move out of bounds. Pick another direction" << endl;
getline(cin, input);
moves(hunter, size, input);
}
hunter.y = hunter.y + 1;
}
if (input == "a") {
while (hunter.y - 1 < 0) {
cout << "You are trying to move out of bounds. Pick another direction" << endl;
getline(cin, input);
moves(hunter, size, input);
}
hunter.y = hunter.y - 1;
}
}
/*********************************************************************
* ** Function: shoot_arrow
* ** Description: these functions display the percept and return a letter for event type
* ** Parameters: virutal percept() and event() functions
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
bool shoot_arrow(vector< vector< Room > > &cave, Hunter& hunter, int size, string input) {
if (input == " ") {
if (hunter.num_arrows == 0) {
cout << "\nYou don't have enough arrows! Choose a different option" << endl;
getline(cin, input);
}
cout << "\nIn which direction do you want to shoot? (w, s, d, a) " << endl;
getline(cin, input);
if (input == "w") {
hunter.num_arrows = hunter.num_arrows - 1;
if (cave[hunter.x - 1][hunter.y].get_event()->event() == "W") {
cout << "\nYou killed the Wumpus!" << endl;
return true;
} else {
cout << "No hit" << endl;
}
}
if (input == "s") {
hunter.num_arrows = hunter.num_arrows - 1;
if (cave[hunter.x + 1][hunter.y].get_event()->event() == "W") {
cout << "\nYou killed the Wumpus!" << endl;
return true;
} else {
cout << "No hit" << endl;
}
}
if (input == "d") {
hunter.num_arrows = hunter.num_arrows - 1;
if (cave[hunter.x][hunter.y + 1].get_event()->event() == "W") {
cout << "\nYou killed the Wumpus!" << endl;
return true;
} else {
cout << "No hit" << endl;
}
}
if (input == "a") {
hunter.num_arrows = hunter.num_arrows - 1;
if (cave[hunter.x][hunter.y - 1].get_event()->event() == "W") {
cout << "\nYou killed the Wumpus!" << endl;
return true;
} else {
cout << "No hit" << endl;
}
}
}
}
/*********************************************************************
* ** Function: percept() & event()
* ** Description: these functions display the percept and return a letter for event type
* ** Parameters: virutal percept() and event() functions
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
bool player_status(vector< vector< Room > > &cave, Hunter& hunter, int size) {
string input;
getline(cin, input);
moves(hunter, size, input);
bool kill = shoot_arrow(cave, hunter, size, input);
return kill;
}
/*********************************************************************
* ** Function: percept() & event()
* ** Description: these functions display the percept and return a letter for event type
* ** Parameters: virutal percept() and event() functions
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void play(vector< vector< Room > > &cave, int size, Bat& b, Pit& p, Wumpus& w, Gold& g, Fill& f, Hunter& hunter, HunterStart& s, string mode) {
string alive_message;
bool game_over = false;
hunter.num_arrows = 3;
//welcome messages
cout << "\nWelcome to the Dangerous World of Hunt the Wumpus" << endl;
cout << "Kill the Wumpus before it kills you!\n" << endl;
do {
display_cave(cave, size, mode, hunter);
alive_message = is_player_alive(cave, hunter);
if (alive_message == "death_by_wumpus") {
cout << "\nGame Over! You entered the Wumpus' room and got eaten!\n" << endl;
game_over = true;
}
if (alive_message == "death_by_pit") {
cout << "\nGame Over! You entered a room with a bottomless pit and fell to your demise!\n" << endl;
game_over = true;
}
if (alive_message == "alive") {
check_event(cave, size,b, p, w, g, f, hunter, s, mode);
check_adjacent1(cave, size, mode, hunter);
hunter.count = 2;
instructions(hunter);
if (!game_over) {
game_over = player_status(cave, hunter, size);
}
}
} while (!game_over);
}
/*********************************************************************
* ** Function: percept() & event()
* ** Description: these functions display the percept and return a letter for event type
* ** Parameters: virutal percept() and event() functions
* ** Pre-Conditions: None
* ** Post-Conditions: None
* *********************************************************************/
void validate(int size) {
if (size < 4) {
cout << "Cave dimensions must be at least 4x4. Choose a larger number for 2nd argument." << endl;
exit (EXIT_FAILURE);
}
}
| true |
a2a62257017526c2598e0a5a42b2a11df833ad30 | C++ | Namlitruong/SED-2019 | /HaloSST-Lab1/HaloSST/old_Lab1.cpp | UTF-8 | 10,688 | 3.296875 | 3 | [] | no_license | //##########################################################################################################################################
// School of Science & Technology
// EEET2482 - Software Engineering Design
// Lab 1 - Simple 2-Argument Calculator
// Team name: HaloSST
// Member 1: Nam Truong - s3518702
// Member 2: Tin Nguyen - s3607833
// Member 3: Hoang Tran - s3618889
//###########################################################################################################################################
#include "pch.h"
#include <iostream>
#define ASCIIspace 32
#define INPUTLIMIT 100
#define INTUPPERLIMIT 32767
#define INTLOWERLIMIT -32767
using namespace std;
//Global variables
char iString[1000];
int arg1;
int arg2;
char op;
// Function prototype
char* SpaceEliminate(char*);
int ExtractInput(char*, int&, int&, char&);
bool CheckRange(char*, int&);
bool checkValidNumber(char*);
int DoCalculate(int&, int&, char&);
bool ErrMess(int);
bool CheckExit(char *);
void PrintResult (int&, int&, char&, int);
//Main program
int main() {
while (1) {
cout << "___________________________________________________________\n";
cout << "\n#NOTE: Input String cannot larger than 100 character." << endl; //Acknowledge user the input constraint
cout << "Input the elements of simple 2-argument Calculator: ";
cin.getline(iString, 1000); //Declare and set the input lenght of iString is 1000, but just allow user to input 100 characters.
//This action to prevent buffer overflow which will cause fatal error and exit the program immediately.
if (strlen(iString) < INPUTLIMIT) {
if (CheckExit(iString)) return 0; //If the "Exit" is recognised, return 0 to exit the program and print team information.
if (ErrMess(ExtractInput(SpaceEliminate(iString), arg1, arg2, op)))
PrintResult(arg1, arg2, op, DoCalculate(arg1, arg2, op)); //If no errors are detected, the result of the calculation will display.
}else cout << "ERROR: Too many characters. Please input the expression again !!!" << endl; //Print error message if too many characters have been input
}
}
/* Function name: SpaceEliminate.
Usage: Using to eleiminate spaces before and after the input expression.
Input: Raw input argument string.
Output: New expression without spaces at the front and from the back.
*/
char* SpaceEliminate(char* iString) {
int StartIndex = 0;
int EndIndex = strlen(iString);
char* Data = &(*iString);
for (int i = 1; iString[i - 1] == ' '; i++) StartIndex = i; // Check space from the front
for (int i = strlen(iString) - 1; iString[i] == ' '; i--) EndIndex = i - 1; // Check space from the back
for (int i = 0; i <= (EndIndex - StartIndex); i++) Data[i] = iString[StartIndex + i]; // Take out the expression from 'Start Index' to 'End Index'
Data[(EndIndex - StartIndex) + 1] = '\0'; // Add NULL at the end of the new string
return Data;
}
/* Function name: ExtractInput.
Usage: Extract correct form of data from the input string to arg1, arg2 and op.
Input: The address of arg1, arg2, op (oarg1 mean output argument 1).
Output: Return error code if any invalid inputs are being detected.
*/
int ExtractInput(char* iData, int& oarg1, int& oarg2, char& op) {
char arg1[50]; //Buffer for arg1
char arg2[50]; //Buffer for arg2
char temp[50]; //Temporary buffer is reserved
int StartIndex = 0;
int EndIndex = strlen(iData);
//If the input just have one argument and it is not "Exit", then return error code 5.
for (int i = 0; iData[i] != ASCIIspace; i++) {
if (i == strlen(iData)-1) return 5;
}
//If the input just have spaces and no arguments, then return error code 5.
for (int i = 0; iData[i] == ASCIIspace; i++) {
if (i == strlen(iData)-1) return 5;
}
//Extract ARG1 from the input string by scanning from the front until detect 'space'
for (int i = 0; iData[i] != ASCIIspace; i++) {
arg1[i] = iData[i];
StartIndex = i;
}
arg1[StartIndex + 1] = '\0'; // Add NULL at the end of the arg1 string.
//Extract ARG2 from the input string by scanning from the back until detect 'space' and store it in the temporary array
//Because scan and extract from the back, thus, it is in the reverse form.
for (int i = strlen(iData) - 1; iData[i] != ASCIIspace; i--) {
temp[strlen(iData) - i - 1] = iData[i];
EndIndex = i;
}
temp[strlen(iData) - EndIndex] = '\0';
//Flip the temporary array and store the correct data in the arg2 string.
for (unsigned int i = 0; i < strlen(temp); i++) {
arg2[i] = temp[strlen(temp) - i - 1];
}
arg2[strlen(temp)] = '\0';// Add NULL at the end of the arg2 string.
if (!checkValidNumber(arg1) || !checkValidNumber(arg2)) return 1; // Check if the arg1 and arg2 are in the valid form or not. If not return error code 1
if (!CheckRange(arg1, oarg1) || !CheckRange(arg2, oarg2)) return 2; // Check if the arg1 and arg2 are in the valid range or not. If not return error code 2
// Advancing StartIndex by 2 to skip the white space between arg1 and op
// Substracting EndIndex by 2 to skip the white space between op and arg2
// Because just one single white space is allowed between argument.
StartIndex = StartIndex + 2;
EndIndex = EndIndex - 2;
if (StartIndex != EndIndex) { // If StartIndex is not equal to EndIndex, then error occur. there will be two cases.
for (StartIndex; iData[StartIndex] != ASCIIspace; StartIndex++) if (StartIndex == EndIndex) return 3; // Case 1: If the argument between StartIndex and EndIndex do not have white space, then return invalid operator
return 5; // Case 2: If white space exist in the mentioned range, then return dummy variables.
} else {
op = iData[StartIndex]; // If SatrtIndex equal to EndIndex, then that is the position of the operand. Since op just can represent by a single character.
if ((op == '+') || (op == '-') || (op == '*') || (op == '/') || (op == '%')) { // Consider whether the character 'op' is the correct form of valid operand.
if ((op == '/') && (oarg2 == 0)) return 4; // If the operation is division or modulo and the srg2 is 0, then return error code 4.
else if ((op == '%') && (oarg2 == 0)) return 4;
else return 0; // If not in the mentioned cases above then return no error.
}else return 3; // Return error code 3 if op is not in any operands form.
}
}
/* Function name: CheckRange.
Usage: Check the input argument in the range of signed 16 bits interger.
Input: Input argument in the text form, and the address of the argument in the interger form.
Output: Boolean flag if the argument is in the range or not.
*/
bool CheckRange(char* Input, int& oarg) {
oarg = atoi(Input); // Convernt into interger to check the value easier.
if (oarg < INTLOWERLIMIT || oarg > INTUPPERLIMIT) return 0;
return 1;
}
/* Function name: checkValidNumber.
Usage: Check if the input argument is in the valid integer form.
Input: Argument in test form.
Output: Boolean flag if the argument is a valid integer or not.
*/
bool checkValidNumber(char* inputArgv) {
bool dotDetect = false;
for (int i = 0; inputArgv[i] != '\0'; i++) { // Using loop to scan the iput string
if (!isdigit(inputArgv[i]) && inputArgv[i] != '+' && inputArgv[i] != '-' && inputArgv[i] != '.') return false; // A number, '+', '-', and a dot are allowed at the first index. If not return false.
if (i > 0 && (inputArgv[i] == '-' || inputArgv[i] == '+')) return false; // After the first Index, just number is allowed, and maybe a dot if it not present at the first index.
// A dot just can present one time inside the string and after the dot, everything must be zero or NULL.
if (dotDetect) {
if (inputArgv[i] == '.') return false;
else if (inputArgv[i] != '0') return false;
} else {
if (inputArgv[i] == '.') dotDetect = true;
}
}
return true;
}
/* Function name: DoCalculate.
Usage: Do the calculation between 2 arguments respect to the operand have been detected.
Input: Pass the address of two arguments and the operand.
Output: Result of the calculation.
*/
int DoCalculate(int& arg1, int& arg2, char& op) {
switch (op) { // Using switch statement to detect correct operand, by default it will return an addition.
case '+': return arg1 + arg2;
case '-': return arg1 - arg2;
case '*': return arg1 * arg2;
case '/': return arg1 / arg2;
case '%': return arg1 % arg2;
default: return arg1 + arg2;
}
}
/* Function name: ErrMess.
Usage: Print out the error messeage
Input: Error code
Output: Boolean flag to detect if any error occurs during the process. 0 mean no error and will return 1, other cases mean error occurs and return 0.
*/
bool ErrMess(int Err) {
switch (Err) { //Using switch statement to print out correct error message.
case 0: return 1;
case 1:
cout << "ERROR CHECK 1: Invalid Number Input" << endl;
return 0;
case 2:
cout << "ERROR CHECK 2: Invalid Range of Input" << endl;
return 0;
case 3:
cout << "ERROR CHECK 3: Invalid Operator Input" << endl;
return 0;
case 4:
cout << "ERROR CHECK 4: Division by 0" << endl;
return 0;
case 5:
cout << "ERROR CHECK 5: Dummy Variable" << endl;
return 0;
default: return 0;
}
}
/* Function name: CheckExit.
Usage: Check if the input string is Exit or not. If "Exit" is pressed then exit the program and print team information.
Input: pointer to input raw string.
Output: Boolean flag to acknowledge "Exit" have been pressed or not.
*/
bool CheckExit(char * iString) {
if (!strcmp(iString, "Exit") || !strcmp(iString, "exit")) { // Consider both Capital (Exit) and non-capital (exit) of the first character to compare with the input string.
cout << "LABORATORY GROUP HaloSST" << endl;
cout << "s3518702, s3518702@rmit.edu.vn, Nam Truong" << endl;
cout << "s3607833, s3607833@rmit.edu.vn, Tin Nguyen" << endl;
cout << "s3618889, s3618889@rmit.edu.vn, Hoang Tran" << endl;
return 1;
}
return 0;
}
/* Function name: PrintResult.
Usage: Print the values of each argument as well as the result.
Input: The address of arg1, arg2, op and value of the result.
Output: NULL - void function.
*/
void PrintResult(int& arg1, int& arg2, char& op, int Result) {
cout << "int arg1: |" << arg1 << "|" << endl;
cout << "int arg2: |" << arg2 << "|" << endl;
cout << "out Op: |" << op << "|" << endl;
cout << "RESULT: " << Result << endl;
}
| true |
032a4b89561c68e16b31685828e3979583829353 | C++ | TakuyaSatoM/TFVIS | /tfvisV/Common.h | SHIFT_JIS | 1,937 | 2.609375 | 3 | [] | no_license | //
// Common.h
// ʂŎgp}N萔̒`
//
#ifndef _CommonA_h_
#define _CommonA_h_
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h> //for sprintf
#include <assert.h>
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#define CheckBox(txt){ MessageBoxA(NULL, txt, ("Error"), MB_OK | MB_ICONEXCLAMATION);}
class INT2
{
public:
int x,y;
INT2(){x=y=0;}
INT2(int ix,int iy){x=ix;y=iy;}
INT2(int a){x=a;y=a;}
int SIZE(){return x*y;}
INT2 operator + (INT2 obj) {
return INT2(this->x+obj.x,this->y+obj.y);
}
INT2 operator - (INT2 obj) {
return INT2(this->x-obj.x,this->y-obj.y);
}
INT2 operator * (INT2 obj) {
return INT2(this->x*obj.x,this->y*obj.y);
}
INT2 operator / (INT2 obj) {
return INT2(this->x/obj.x,this->y/obj.y);
}
bool operator == (INT2 obj) {
if(this->x == obj.x && this->y == obj.y){return 1;}
return 0;
}
bool operator != (INT2 obj) {
if(this->x != obj.x || this->y != obj.y){return 1;}
return 0;
}
};
// ̉
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
// QƃJE^̃fNg
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
// G[̕ƃAvP[V̏I
#define ERROR_EXIT() { int line = __LINE__; const char *file = __FILE__;\
char msg[_MAX_FNAME + _MAX_EXT + 256];\
char drive[_MAX_DRIVE];\
char dir[_MAX_DIR];\
char fname[_MAX_FNAME];\
char ext[_MAX_EXT];\
_splitpath(file, drive, dir, fname, ext);\
sprintf(msg, "炩̃G[߃AvP[VI܂\r\n"\
"t@C : %s%s\r\n"\
"sԍ : %d", fname, ext, line);\
MessageBoxA(NULL, msg, "Error", MB_OK | MB_ICONEXCLAMATION);\
PostQuitMessage(1);\
}
#endif // _Common_h_ | true |
fbbc0eabf1b2f41d2c15407bd91e9903d1ffaa39 | C++ | DimanVoroshillo/TimpLaba_4 | /third_server/replace.cpp | UTF-8 | 1,167 | 3.25 | 3 | [] | no_license | #include "replace.h"
#include <string>
#include <iostream>
using namespace std;
Replace::Replace( string in)
{
this->key = in;
};
string Replace::encrypt(string in)
{
this->expression = in;
for (int i = 0; i < this->expression.size(); i++)
{
for (int j = 0; j < this->english_abc.size(); j++)
{
if (this->expression[i] == this->english_abc[j])
{
this->expression[i] = this->key[j];
break;
}
// Capital letters
else if ((this->expression[i] - 32) == this->english_abc[j])
{
this->expression[i] = this->key[j] + 32;
}
}
}
return this->expression;
};
string Replace::decrypt(string in)
{
this->expression = in;
for (int i = 0; i < this->expression.size(); i++)
{
for (int j = 0; j < this->english_abc.size(); j++)
{
if (this->expression[i] == this->key[j])
{
this->expression[i] = this->english_abc[j] ;
break;
}
// Capital letters
else if ((this->expression[i]-32) == this->key[j])
{
this->expression[i] = this->english_abc[j] + 32;
break;
}
}
}
return this->expression;
};
| true |
8c5e3b60bee324b8b3a32162cf2bc6adca5849f1 | C++ | dshahid380/Algos | /SPOJ/CLFLARR_SPOJ.cpp | UTF-8 | 816 | 2.65625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int MAX = 1000002;
vector<int> tree(MAX,0);
vector<int> arr;
void update(int idx, int val, int N) {
for(; idx < N; idx = idx | (idx + 1))
tree[idx] += val;
}
void range_update(int l, int r, int val, int N) {
update(l, val, N);
update(r+1, -val, N);
}
int query(int r) {
int res = 0;
for(; r>= 0; r =(r & (r+1))-1)
res += tree[r];
return res;
}
int point_query(int idx) {
return query(idx)-query(idx-1);
}
void build(int N) {
for(int i=0; i < N; i++){
update(i, arr[i], N);
}
}
int main() {
int N, M, C;
cin>>N>>M>>C;
arr.assign(N, C);
build(N);
while(M--){
char t;
cin>>t;
if(t=='Q'){
int p;
cin>>p;
cout<<point_query(p)<<endl;
}
else{
int u, v, k;
cin>>u>>v>>k;
range_update(u-1, v-1, k, N);
}
}
return 0;
}
| true |
5ea92ab23eef256f43ad37a2fd8fada020e2eb57 | C++ | jacobchesley/Rover_2015 | /Arduino/src/Compass/Compass.cpp | UTF-8 | 2,942 | 3.09375 | 3 | [] | no_license | /**
* @author Jacob Chesley
* @date 3/12/2015
*/
#include <Compass.h>
//#define MAG_ADDR 0x0E
Compass::Compass(){
address = 0x0E;
degreesInRad = 57.2957795;
pi = 3.14159265359;
}
Compass::~Compass(){
}
void Compass::Configure(){
Wire.beginTransmission(address);
Wire.write(0x11); // control register2
Wire.write(0x80); // eenable auto resets
Wire.endTransmission();
delay(15);
Wire.beginTransmission(address);
Wire.write(0x10); // control register 1
Wire.write(1); // Active mode
Wire.endTransmission();
}
void Compass::Calibrate(int numberSeconds){
// First values
minX = GetMagX();
minY = GetMagY();
minZ = GetMagZ();
// Set max values to miniumum
maxX = minX;
maxY = minY;
maxZ = minZ;
float tmpX = 0.0f;
float tmpY = 0.0f;
float tmpZ = 0.0f;
// Look for max and min for X, Y and Z values, with a 20 millisecond delay
for(int i = 0; i < (numberSeconds * 50); i++){
tmpX = GetMagX();
tmpY = GetMagY();
tmpZ = GetMagZ();
if(tmpX > maxX){
maxX = tmpX;
}
if(tmpX < minX){
minX = tmpX;
}
if(tmpY > maxY){
maxY = tmpY;
}
if(tmpY < minY){
minY = tmpY;
}
if(tmpZ > maxZ){
maxZ = tmpZ;
}
if(tmpZ < minZ){
minZ = tmpZ;
}
delay(20);
}
// Scale the values to 0 to 1 range
scaleX = 1.0f/(maxX - minX);
scaleY = 1.0f/(maxY - minY);
scaleZ = 1.0f/(maxZ - minZ);
// Offset the values to -0.5 to 0.5 range
offsetX = (minX + maxX) * 0.5f;
offsetY = (minY + maxY) * 0.5f;
offsetZ = (minZ + maxZ) * 0.5f;
}
float Compass::GetDegrees(){
// Get data for each axis
float x = (float)GetMagX();
float y = (float)GetMagY();
float z = (float)GetMagZ();
// Offset and scale values
x -= offsetX;
y -= offsetY;
z -= offsetZ;
x *= scaleX;
z *= scaleZ;
// Get the radians
float heading = atan2(-z, x);
// Make sure heading is in 0- 2PI range
if(heading < 0.0f){
heading += 2.0f * pi;
}
// Convert to degrees
return heading * degreesInRad;
}
int Compass::GetMagX(){
return ReadData(0x01, 0x02);
}
int Compass::GetMagY(){
return ReadData(0x03, 0x04);
}
int Compass::GetMagZ(){
return ReadData(0x05, 0x06);
}
int Compass::ReadData(char reg_address1, char reg_address2){
int lsb, msb; //define the MSB and LSB
Wire.beginTransmission(address);
Wire.write(reg_address1); // x MSB reg
Wire.endTransmission();
delayMicroseconds(2); //needs at least 1.3us free time between start and stop
Wire.requestFrom(address, 1);
while(Wire.available()){
msb = Wire.read();
}
delayMicroseconds(2); //needs at least 1.3us free time between start and stop
Wire.beginTransmission(address);
Wire.write(reg_address2); // x LSB reg
Wire.endTransmission();
delayMicroseconds(2); //needs at least 1.3us free time between start and stop
Wire.requestFrom(address, 1);
while(Wire.available()) {
lsb = Wire.read();
}
int out = (lsb|(msb << 8)); //concatenate the MSB and LSB
return out;
}
| true |
0a839474fec6b7878909b3ea6289757a59f8618e | C++ | Neverous/codeforces | /ASC26/c.cpp | UTF-8 | 4,074 | 2.828125 | 3 | [] | no_license | /* 2013
* Maciej Szeptuch
* II UWr
*/
#include <cstdio>
#include <algorithm>
#include <vector>
const int MASKS = 131072;
int jewelery,
r1, r2;
long long int lower,
upper,
weight[32],
value[32],
valueF[MASKS],
valueS[MASKS],
weightF[MASKS],
weightS[MASKS];
std::vector<int> repr;
inline
bool weightCompare(int a, int b)
{
return weightS[a] < weightS[b];
}
inline
bool valueCompare(int a, int b)
{
return valueS[a] < valueS[b];
}
inline
bool weightCompare2(int a, long long int b)
{
return weightS[a] < b;
}
inline
bool weightCompare3(long long int a, int b)
{
return weightS[b] > a;
}
inline int MAX(int a, int b){return valueCompare(b, a)?a:b;}
class iTree
{
static const int SIZE = MASKS;
int max[SIZE * 2];
int getMax(int start, int end, int iStart = 0, int iEnd = SIZE - 1, int pos = 1);
public:
iTree(void);
void init();
int findMax(long long int start, long long int end);
};
iTree tree;
int main(void)
{
#ifndef SELENE
freopen("dowry.in", "r", stdin);
freopen("dowry.out", "w", stdout);
#endif // SELENE
scanf("%d %lld %lld", &jewelery, &lower, &upper);
for(int j = 0; j < jewelery; ++ j)
scanf("%lld %lld", &weight[j], &value[j]);
for(int m = 1; m < (1 << (jewelery / 2)); ++ m)
for(int j = 0; j < jewelery; ++ j)
if(m & (1 << j))
{
valueF[m] += value[j];
weightF[m] += weight[j];
}
for(int m = 1; m < (1 << ((jewelery + 1) / 2)); ++ m)
{
for(int j = jewelery / 2; j < jewelery; ++ j)
if(m & (1 << (j - jewelery / 2)))
{
valueS[m] += value[j];
weightS[m] += weight[j];
}
repr.push_back(m);
}
repr.push_back(MASKS - 1);
valueS[MASKS - 1] = 0;
weightS[MASKS - 1] = 1000000000000000000LL;
std::sort(repr.begin(), repr.end(), weightCompare);
// for(unsigned int r = 0; r < repr.size(); ++ r)
// printf("%d: %lld/%lld\n", repr[r], weightS[repr[r]], valueS[repr[r]]);
tree.init();
for(int m1 = 0; m1 < (1 << (jewelery / 2)); ++ m1)
{
int m2 = tree.findMax(lower - weightF[m1], upper - weightF[m1]);
if(lower <= weightF[m1] + weightS[m2] && weightF[m1] + weightS[m2] <= upper && valueF[r1] + valueS[r2] < valueF[m1] + valueS[m2])
{
r1 = m1;
r2 = m2;
}
}
printf("%d\n", __builtin_popcount(r1) + __builtin_popcount(r2));
for(int j = 0; j < jewelery / 2; ++ j)
if(r1 & (1 << j))
printf("%d ", j + 1);
for(int j = jewelery / 2; j < jewelery; ++ j)
if(r2 & (1 << (j - jewelery / 2)))
printf("%d ", j + 1);
puts("");
return 0;
}
inline
iTree::iTree(void)
:max()
{
}
inline
void iTree::init()
{
for(unsigned int s = 0; s < repr.size(); ++ s)
max[SIZE + s] = repr[s];
for(int s = SIZE - 1; s > 0; -- s)
max[s] = MAX(max[s * 2], max[s * 2 + 1]);
}
inline
int iTree::getMax(int start, int end, int iStart/* = 0*/, int iEnd/* = SIZE - 1*/, int pos/* = 1*/)
{
if(start == iStart && end == iEnd)
return max[pos];
int iMid = (iStart + iEnd) / 2;
if(end <= iMid)
return getMax(start, end, iStart, iMid, pos * 2);
if(start > iMid)
return getMax(start, end, iMid + 1, iEnd, pos * 2 + 1);
return MAX(getMax(start, iMid, iStart, iMid, pos * 2),
getMax(iMid + 1, end, iMid + 1, iEnd, pos * 2 + 1));
}
inline
int iTree::findMax(long long int start, long long int end)
{
int iStart = std::lower_bound(repr.begin(), repr.end(), start, weightCompare2) - repr.begin(),
iEnd = std::upper_bound(repr.begin(), repr.end(), end, weightCompare3) - repr.begin() - 1;
// printf("%lld %lld => %d %d\n", start, end, iStart, iEnd);
if(iStart > iEnd)
return 0;
int res = getMax(iStart, iEnd);
// printf("%d: %lld\n", res, valueS[res]);
return res;
}
| true |
5f0b1fc11e0edf94008000a1d02234bc61fce2f1 | C++ | nilesh-s-b/Cpp_Programs_By_nilesh | /String_Operations.cpp | UTF-8 | 4,609 | 4.0625 | 4 | [] | no_license | // Without Using Built-In String Functions
/*
a program which should implement your own function equivalent to the library
function to perform various string operations
such as copy, length, reversing, palindrome, concatenation
and to find occurrence of a sub-string. (Your user define function must
have same parameter & return type as library function but different in name) */
#include<iostream>
using namespace std;
void copy_string( char destination[], char source[] ){
int i;
for ( i = 0; source[i]!='\0'; i++)
{
destination[i] = source [i];
}
destination[i] = '\0';
}
int length_of_string(char str[] ){
int count=0;
for (int i = 0; str[i]!='\0'; i++)
{
count++;
}
return count;
}
void reverse_string(char rev[], char str[]){
int i, len=0,temp=0;
len = length_of_string(str)-1;
temp = len;
for ( i = 0; i <= temp; i++, len--)
{
rev[i] = str[len];
}
}
int palindrome_string(char str[]){
char rev[20];
reverse_string(rev, str);
int len=0, flag=0;
len = length_of_string(str);
for (int i = 0; i < len; i++)
{
if ( rev[i]!=str[i])
flag=1;
}
if( flag == 1)
return flag;
else
return flag;
}
void concat_string( char str1[], char str2[]){
int i, len1=0, len2=0;
len1 = length_of_string(str1);
len2 = length_of_string(str2);
cout<<"\t "<<len1<<"\t "<<len2;
for ( i = len1; i < (len1 + len2); i++)
{
str1[i] = str2[i-len1];
}
str1[i] = '\0';
}
void occur_of_string(char str[], char sub[]){
int i, j, flag, N=0, M=0;
int count=0;
N = length_of_string(str);
M = length_of_string(sub);
/* A loop to slide sub[] one by one */
for ( i = 0; i <= N; i++)
{
for ( j = 0; j <= M; j++)
{
/* for current index i, check for
pattern match */
if ( str[ i+j ] != sub[j])
{
break;
}
}
// if pat[0...M-1] = txt[i, i+1, ...i+M-1]
if (j == M)
{
count++;
j = 0;
}
}
if( count!=0)
cout<<"\n\t Sub String Ocurred "<<count<<" times.";
else
cout<<"\n\t Sub String Is Not Found.";
}
// Main function
int main(){
int ch=0;
char str1[20], str2[20], cpy[20], rev[20];
int len, flag=0;
cout<<"\n\t Which Operation do you want to perform on string. \n";
cout<<"\n\t\t 1. Copy string.";
cout<<"\n\t\t 2. length of string.";
cout<<"\n\t\t 3. Reverse string.";
cout<<"\n\t\t 4. Check string is palindrome or not.";
cout<<"\n\t\t 5. String Concatenation.";
cout<<"\n\t\t 6. Find Occurance of sub-string.";
cout<<"\n\t\t 7. EXIT.";
while ( 1 )
{
cout<<"\n\t Your Choice: ";
cin>>ch;
switch ( ch )
{
case 1:
cout<<"\n Enter a string: ";
cin>>str1;
copy_string(cpy, str1);
cout<<"\n\t str1 copied into cpy: "<<cpy;
break;
case 2:
cout<<"\n Enter a string: ";
cin>>str1;
len = length_of_string(str1);
cout<<"\n\t Length of "<<str1<<" is : "<<len;
break;
case 3:
cout<<"\n Enter string to reverse: ";
cin>>str1;
reverse_string(rev, str1);
cout<<"\n\t Reversed string: "<<rev;
break;
case 4:
cout<<"\n Enter a string : ";
cin>>str1;
flag = palindrome_string(str1);
if( flag==1 )
cout<<"\n\t String is not palindrome.";
else
cout<<"\n\t is palindrome.";
break;
case 5:
cout<<"\n Enter a string 1 : ";
cin>>str1;
cout<<"\n Enter a string 2 : ";
cin>>str2;
concat_string(str1, str2);
cout<<"\n\t Concatination of str1 and str2 : "<<str1;
break;
case 6:
cout<<"\n Enter a string: ";
cin>>str1;
cout<<"\n Enter sub string to find in above string: ";
cin>>str2;
occur_of_string(str1, str2);
break;
case 7:
exit(1);
default:
cout<<"\n\t PLEASE, CHOOSE CORRECT CHOICE.";
break;
}
}
return 0;
} | true |
64fb88ffa0b484737bcc2adf5ee76348826c3982 | C++ | GitJunk76345/Cpp_code | /Cpp_code/headers/lifo.h | UTF-8 | 1,934 | 3.921875 | 4 | [] | no_license | #pragma once
/*
Template based, fixed capacity lifo (Last In First Out) container class
*/
#include <iostream>
namespace containers {
template <typename T>
class lifo
{
size_t height;
size_t capacity;
T* data;
public:
lifo(size_t size) : capacity(size), height(0) { data = new T[capacity]; }
~lifo() { delete[] data; }
lifo(const lifo<T>& stack) : height(stack.height), capacity(stack.capacity) {
data = new T[capacity];
for (size_t i = 0; i < height; ++i)
data[i] = stack.data[i];
}
lifo(lifo<T>&& stack) : height(stack.height), capacity(stack.capacity) {
data = stack.data;
stack.data = nullptr;
}
lifo<T>& operator=(const lifo<T>& stack) {
height = stack.height;
capacity = stack.capacity;
delete[] data;
data = new T[capacity];
for (size_t i = 0; i < height; ++i)
data[i] = stack.data[i];
}
lifo<T>& operator=(lifo<T>&& stack) {
height = stack.height;
capacity = stack.capacity;
delete[] data;
data = stack.data;
stack.data = nullptr;
}
const T& push(const T& elem) {
if (height < capacity)
{
data[height] = elem;
++height;
return data[height - 1];
}
else
std::cerr << "Stack overflow\n"; //error
}
T& pop() {
if (height > 0)
{
--height;
return data[height];
}
else
std::cerr << "Stack empty\n"; //error
}
const T& peek() const {
if (height > 0)
{
return data[height - 1];
}
else
std::cerr << "Stack empty\n"; //error
}
size_t getCapacity() const { return capacity; }
size_t getFree() const { return capacity - height; }
size_t getHeight() const { return height; }
bool isEmpty() const { return height == 0; }
bool isFull() const { return height == capacity; }
};
// Dumps and prints lifo content
template <class T>
void dumpstack(lifo<T>& stack) {
while (!stack.isEmpty())
std::cout << stack.pop();
std::cout << std::endl;
}
} | true |
16f711f6d5bbad23934665290dc444deb60dfffe | C++ | Char-Mander/Juego-uno-solo | /Práctica 3/Práctica 3/unosolo.cpp | ISO-8859-1 | 18,824 | 2.8125 | 3 | [] | no_license | #include "unosolo.h"
#include <locale.h>
#include <cstdlib>
#include <stdio.h>
#include <windows.h>
#include <fstream>
using namespace std;
void colorFondo(int color); // Funcin que sirve para asignar un color para el fondo
void mostrar(const tJuego &juego); // Muestra el tablero y el nmero de movimientos realizados por pantalla
bool cargar(tJuego &juego, string nombre); // Carga el archivo (el nonmbre del archivo fue introducido de teclado)
void guardar(const tJuego &juego, string nombre); // Guarda de nuevo en el archivo las dimensiones, dnde est la meta, el tablero, etc.
void partida(tJuego &juego); // Lleva a cabo todo el juego
bool leerMovimiento(const tTablero tablero, tMovimiento &mov); // Lleva a cabo toda la funcin de pedir, mostrar, etc. movimientos con las
//funciones: pedirFicha, posiblesMovimientos, y mostrarPosiblesMovimientos.
bool pedirFicha(const tTablero tablero, tMovimiento &mov); //Funcin que pide de teclado la fila y columna de la ficha que se desea mover.
// Comprueba que haya ficha, y que no se haya salido del tablero.
bool posiblesMovimientos(const tTablero tablero, tMovimiento &mov); //Dada una posicin vlida, devuelve true si la ficha tiene movimientos.
void mostrarPosiblesMovimientos(const tTablero tablero, tMovimiento &mov); // Muestra por pantalla los movimientos de la ficha
//elegida (ya comprobada que es vlida)
void ejecutarMovimiento(tTablero tablero, const tMovimiento &mov); //Ejecuta el movimiento elegido por el usuario
void nuevoEstado(tJuego &juego); // Recalcula el nuevo estado a partir de la funcin comprobarEstado
bool comprobarEstado(tJuego &juego); // Funcin que recorre el tablero comprobando si una ficha tiene algn movimiento posible. Cuando encuentre
// una que s tiene, saldr de la funcin y devolver true, si no encuentra ninguna, devuelve false
void generarTablero(tJuego &juego, int movimientos); //Funcin que se encarga de la generacin del tablero
void iniciarTablero(tTablero tablero); //Pone en el tablero todas las posiciones NULAS
void fijarMeta(tJuego &juego); //Fija una meta aleatoria
bool movimientoInverso(tJuego &juego);//Funcin que lleva a cabo el movimiento inverso
void seleccionarFichaAleatoria(tJuego &juego, tMovimiento &movInverso); //selecciona una ficha aleatoria
bool posiblesMovimientosInversos(tTablero &tablero, tMovimiento &movInverso); // comprueba si la ficha tiene movimientos posibles.
//si los tiene, elige uno al azar.
void ejecutarMovimientoInverso(tTablero &tablero, const tMovimiento &movInverso); //ejecuta el movimiento inverso
void colorFondo(int color) {
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, 15 | (color << 4));
}
void mostrar(const tJuego &juego) {
cout << '\n';
for (int numerosColumnas = 0; numerosColumnas < DIM; numerosColumnas++) {
if (numerosColumnas == 0) {
cout << " " << (numerosColumnas + 1);
}
else
cout << " " << (numerosColumnas + 1);
}
for (int f = 0; f < DIM; f++) {
cout << '\n' << '\n' << (f + 1);
colorFondo(0);
cout << " ";
for (int c = 0; c < DIM; c++) {
colorFondo(juego.tablero[f][c]);
if (f == juego.filaM && c == juego.columnaM) {
cout << char(254);
}
else cout << " ";
colorFondo(0);
cout << " ";
}
}
cout << '\n' << '\n' << "El numero de movimientos realizados es: " << endl;
cout << juego.movimientos << " movimientos. " << endl;
}
bool cargar(tJuego &juego, string nombre) { //Comprobada
ifstream archivo;
bool valido = false;
int n, celda;
archivo.open(nombre);
if (archivo.is_open()) {
archivo >> n;
if (n == DIM) {
valido = true;
while (!archivo.eof()) {
archivo >> juego.bolasIniciales;
archivo >> juego.filaM;
archivo >> juego.columnaM;
for (int f = 0; f < DIM; f++) {
for (int c = 0; c < DIM; c++) {
archivo >> celda;
juego.tablero[f][c] = tCelda(celda);
}
}
archivo >> juego.movimientos;
}
archivo.close();
}
else cout << '\n' << "Las dimensiones no son vlidas";
}
else cout << '\n' << "El archivo no ha podido abrirse. " << endl;
return valido;
}
void guardar(const tJuego &juego, string nombre) {
ofstream archivo;
archivo.open(nombre);
archivo << DIM << endl;
archivo << juego.bolasIniciales << endl;
archivo << juego.filaM << endl;
archivo << juego.columnaM;
for (int f = 0; f < DIM; f++) {
archivo << '\n';
for (int c = 0; c < DIM; c++) {
archivo << juego.tablero[f][c] << " ";
}
}
archivo << '\n' << juego.movimientos;
archivo.close();
}
void partida(tJuego &juego) {
tMovimiento mov;
do {
mostrar(juego);
if (leerMovimiento(juego.tablero, mov)) {
ejecutarMovimiento(juego.tablero, mov);
juego.movimientos++;
nuevoEstado(juego);
}
else {
cout << '\n' << "Ha elegido salir. " << '\n';
juego.estadoJuego = ABANDONO;
}
} while (juego.estadoJuego == JUGANDO);
}
bool leerMovimiento(const tTablero tablero, tMovimiento &mov) {
bool noSalir; //Booleano que controla si en algn momento el usuario decide salir.
//Devuelve false si el usuario pulsara '0' (la opcin de salir)
int direccionAux; // Variable auxiliar que sirve para transformar el nmero introducido de teclado en un tipo tDireccion
mov.direccionMov = INCORRECTA;
noSalir = pedirFicha(tablero, mov);
while (noSalir && mov.direccionMov == INCORRECTA) {
while (!posiblesMovimientos(tablero, mov) && noSalir) {
mov.direccionMov = INCORRECTA;
cout << '\n' << "No hay ningun movimiento valido" << endl;
noSalir = pedirFicha(tablero, mov);
}
if (noSalir) {
mostrarPosiblesMovimientos(tablero, mov);
cin >> direccionAux;
while (direccionAux < 0 || direccionAux>4 || (direccionAux != 0 && !mov.movPosibles[direccionAux - 1])) {
cout << '\n' << "Por favor, introduzca una eleccion valida: " << '\n';
cin >> direccionAux;
}
if (direccionAux != 0) {
direccionAux--;
mov.direccionMov = tDireccion(direccionAux);
}
else {
mov.direccionMov = INCORRECTA;
while (mov.direccionMov == INCORRECTA&&noSalir) {
noSalir = pedirFicha(tablero, mov);
while (!posiblesMovimientos(tablero, mov) && noSalir) {
mov.direccionMov = INCORRECTA;
cout << '\n' << "No hay ningun movimiento valido" << endl;
noSalir = pedirFicha(tablero, mov);
}
if (noSalir) {
mostrarPosiblesMovimientos(tablero, mov);
cin >> direccionAux;
while (direccionAux < 0 || direccionAux>4 || (direccionAux != 0 && !mov.movPosibles[direccionAux - 1])) {
cout << '\n' << "Por favor, introduzca una eleccion valida: " << '\n';
cin >> direccionAux;
}
if (direccionAux != 0) {
direccionAux--;
mov.direccionMov = tDireccion(direccionAux);
}
else mov.direccionMov = INCORRECTA;
}
}
}
}
}
return noSalir;
}
bool pedirFicha(const tTablero tablero, tMovimiento &mov) {
bool dimensiones = false; // booleano que hace que se comprueben si se ha salido del tablero el usuario
bool noSalir = true; // booleano que devolver la funcin "pedirFicha" . Si el usuario decide salir, devuelve false
bool ficha = false; // booleano que comprueba si hay ficha o no en la posicin elegida
cout << '\n' << "Por favor, introduzca la fila y columna de la ficha que desea mover " << endl;
cout << "Recuerde que puede elegir salir pulsando '0' " << endl;
cin >> mov.filamov;
if (mov.filamov != 0) {
cin >> mov.columnamov;
mov.filamov--;
mov.columnamov--;
while (!dimensiones || !ficha) {
if (mov.filamov >= DIM || mov.columnamov >= DIM && noSalir) {
cout << '\n' << " Te has salido fuera del tablero. Introduce la fila y columna de nuevo: " << endl;
cin >> mov.filamov;
if (mov.filamov != 0) {
cin >> mov.columnamov;
mov.filamov--;
mov.columnamov--;
}
else noSalir = false;
}
else dimensiones = true;
if (tablero[mov.filamov][mov.columnamov] != int(tCelda(FICHA)) && noSalir) {
cout << '\n' << "Has elegido una posicin del tablero que no tiene ficha. Introduzca de nuevo la fila y columna: " << endl;
cin >> mov.filamov;
if (mov.filamov != 0) {
cin >> mov.columnamov;
mov.filamov--;
mov.columnamov--;
dimensiones = false;
}
else noSalir = false;
}
else ficha = true;
}
}
else {
noSalir = false;
}
return noSalir; //devolver false si se ha elegido 0, la opcin de salir,
//o true en el caso de que se haya elegido una ficha vlida
}
bool posiblesMovimientos(const tTablero tablero, tMovimiento &mov) {
bool valido = false;
for (int i = 0; i < NUM_DIRS; i++) {
switch (i) {
case ARRIBA: if (tablero[mov.filamov - 1][mov.columnamov] == FICHA && tablero[mov.filamov - 2][mov.columnamov] == VACIA
&& (mov.filamov - 2)<DIM && (mov.filamov - 1)<DIM) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
case ABAJO: if (tablero[mov.filamov + 1][mov.columnamov] == FICHA && tablero[mov.filamov + 2][mov.columnamov] == VACIA
&& (mov.filamov + 2)<DIM && (mov.filamov + 1)<DIM) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
case IZQUIERDA: if (tablero[mov.filamov][mov.columnamov - 1] == FICHA && tablero[mov.filamov][mov.columnamov - 2] == VACIA
&& (mov.columnamov - 2)<DIM && (mov.columnamov - 1)<DIM) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
case DERECHA: if (tablero[mov.filamov][mov.columnamov + 1] == FICHA && tablero[mov.filamov][mov.columnamov + 2] == VACIA
&& (mov.columnamov + 2)<DIM && (mov.columnamov + 1)<DIM) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
}
}
return valido;
}
void mostrarPosiblesMovimientos(const tTablero tablero, tMovimiento &mov) {
cout << '\n' << "Elija direccion: ";
cout << '\n' << "0.- Cambiar de ficha" << '\n';
for (int i = 0; i < NUM_DIRS; i++) {
if (mov.movPosibles[i] == true) {
switch (i) {
case ARRIBA: cout << i + 1 << ".- Arriba" << '\n'; break;
case ABAJO: cout << i + 1 << ".- Abajo" << '\n'; break;
case IZQUIERDA: cout << i + 1 << ".- Izquierda" << '\n'; break;
case DERECHA: cout << i + 1 << ".- Derecha" << '\n'; break;
}
}
}
}
void ejecutarMovimiento(tTablero tablero, const tMovimiento &mov) {
tablero[mov.filamov][mov.columnamov] = VACIA;
switch (mov.direccionMov) {
case ARRIBA: tablero[mov.filamov - 1][mov.columnamov] = VACIA;
tablero[mov.filamov - 2][mov.columnamov] = FICHA; break;
case ABAJO: tablero[mov.filamov + 1][mov.columnamov] = VACIA;
tablero[mov.filamov + 2][mov.columnamov] = FICHA; break;
case IZQUIERDA: tablero[mov.filamov][mov.columnamov - 1] = VACIA;
tablero[mov.filamov][mov.columnamov - 2] = FICHA; break;
case DERECHA: tablero[mov.filamov][mov.columnamov + 1] = VACIA;
tablero[mov.filamov][mov.columnamov + 2] = FICHA; break;
}
}
void nuevoEstado(tJuego &juego) {
bool sePuedeJugar; // ser true si se puede seguir jugando
if (juego.bolasIniciales - juego.movimientos == 1 && juego.tablero[juego.filaM][juego.columnaM] == FICHA) {
juego.estadoJuego = GANA;
cout << '\n' << '\n' << "//////////////////////";
cout << '\n' << "///// HAS GANADO /////";
cout << '\n' << "//////////////////////" << '\n' << '\n';
}
else {
if (juego.bolasIniciales - juego.movimientos == 1) {
juego.estadoJuego = BLOQUEO;
cout << '\n' << '\n' << "///////////////////////";
cout << '\n' << "///// HAS PERDIDO /////";
cout << '\n' << "///////////////////////" << '\n' << '\n';
}
else {
sePuedeJugar = comprobarEstado(juego);
switch (sePuedeJugar) {
case true: juego.estadoJuego = JUGANDO; break;
case false: juego.estadoJuego = BLOQUEO;
cout << '\n' << '\n' << "///////////////////////";
cout << '\n' << "///// HAS PERDIDO /////";
cout << '\n' << "///////////////////////" << '\n' << '\n'; break;
}
}
}
}
bool comprobarEstado(tJuego &juego) {
int contador = 0; // lleva la cuenta de las filas que va recorriendo el for
// se usar para que si dicho for recorriera todas las filas y devuelva false, se salga del while.
bool valido = false; // variable que indicar si hay algn movimiento posible, o no.
// Devuelve true si hay, y false, en caso contrario.
tMovimiento mov; // variable de tipo Movimiento, para poder manejar el array de tipo tPosibles
while (!valido && contador < DIM) { //bucle que comprobar cada ficha del tablero
//hasta encontrar alguna con movimiento vlido
for (int f = 0; f < DIM; f++) {
for (int c = 0; c < DIM; c++) {
if (juego.tablero[f][c] == FICHA) { //solo comprobar la posicin si hay una ficha en ella
for (int i = 0; i < NUM_DIRS; i++) {
switch (i) {
case 0: if (juego.tablero[f - 1][c] == FICHA && juego.tablero[f - 2][c] == VACIA) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
case 1: if (juego.tablero[f + 1][c] == FICHA && juego.tablero[f + 2][c] == VACIA) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
case 2: if (juego.tablero[f][c - 1] == FICHA && juego.tablero[f][c - 2] == VACIA) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
case 3: if (juego.tablero[f][c + 1] == FICHA && juego.tablero[f][c + 2] == VACIA) {
mov.movPosibles[i] = true;
valido = true;
}
else mov.movPosibles[i] = false; break;
}
}
}
}
contador++;
}
}
return valido;
}
void generarTablero(tJuego &juego, int movimientos) {
bool movOk = true;
iniciarTablero(juego.tablero);
fijarMeta(juego);
mostrar(juego);
juego.movimientos = 0;
juego.bolasIniciales = 1;
while (juego.movimientos < movimientos && movOk) {
movOk = movimientoInverso(juego);
mostrar(juego);
system("pause");
}
}
void iniciarTablero(tTablero tablero) {
for (int f = 0; f < DIM; f++) {
for (int c = 0; c < DIM; c++) {
tablero[f][c] = NULA;
}
}
}
void fijarMeta(tJuego &juego) {
juego.filaM = rand() % DIM;
juego.columnaM = rand() % DIM;
juego.tablero[juego.filaM][juego.columnaM] = FICHA;
juego.movimientos = 0;
}
bool movimientoInverso(tJuego &juego) {
tMovimiento movInverso;
bool valido;
int contador;
seleccionarFichaAleatoria(juego, movInverso);
valido = posiblesMovimientosInversos(juego.tablero, movInverso);
if (valido) {
ejecutarMovimientoInverso(juego.tablero, movInverso);
juego.movimientos++;
juego.bolasIniciales++;
}
else {
contador = 0;
while (!valido && contador<DIM*DIM) {
seleccionarFichaAleatoria(juego, movInverso);
valido = posiblesMovimientosInversos(juego.tablero, movInverso);
contador++;
}
if (contador != DIM*DIM) {
ejecutarMovimientoInverso(juego.tablero, movInverso);
juego.movimientos++;
juego.bolasIniciales++;
}
else cout << '\n' << "El tablero ya no puede generar mas fichas" << '\n';
}
return valido;
}
void seleccionarFichaAleatoria(tJuego &juego, tMovimiento &movInverso) {
int posicionAux;
int filaFicha, columnaFicha;
if (juego.movimientos == 0) {//si no ha habido movimientos, se partir desde la meta
movInverso.filamov = juego.filaM;
movInverso.columnamov = juego.columnaM;
}
else { //si ha habido al menos un movimiento, se elige ficha aleatoria
filaFicha = rand() % DIM;
columnaFicha = rand() % DIM;
while (juego.tablero[filaFicha][columnaFicha] != FICHA) {
filaFicha = rand() % DIM;
columnaFicha = rand() % DIM;
}
movInverso.filamov = filaFicha;
movInverso.columnamov = columnaFicha;
}
}
bool posiblesMovimientosInversos(tTablero &tablero, tMovimiento &movInverso) {
bool valido = false;
int dirFicha;
for (int i = 0; i < NUM_DIRS; i++) {
switch (i) {
case ARRIBA: if (tablero[movInverso.filamov - 1][movInverso.columnamov] != FICHA && tablero[movInverso.filamov - 2][movInverso.columnamov] != FICHA
&& (movInverso.filamov - 2) >= 0 && (movInverso.filamov - 1)>0) {
movInverso.movPosibles[i] = true;
valido = true;
}
else movInverso.movPosibles[i] = false;
break;
case ABAJO: if (tablero[movInverso.filamov + 1][movInverso.columnamov] != FICHA && tablero[movInverso.filamov + 2][movInverso.columnamov] != FICHA
&& (movInverso.filamov + 2)<DIM && (movInverso.filamov + 1)<(DIM - 1)) {
movInverso.movPosibles[i] = true;
valido = true;
}
else movInverso.movPosibles[i] = false;
break;
case IZQUIERDA: if (tablero[movInverso.filamov][movInverso.columnamov - 1] != FICHA && tablero[movInverso.filamov][movInverso.columnamov - 2] != FICHA
&& (movInverso.columnamov - 2) >= 0 && (movInverso.columnamov - 1)>0) {
movInverso.movPosibles[i] = true;
valido = true;
}
else movInverso.movPosibles[i] = false;
break;
case DERECHA: if (tablero[movInverso.filamov][movInverso.columnamov + 1] != FICHA && tablero[movInverso.filamov][movInverso.columnamov + 2] != FICHA
&& (movInverso.columnamov + 2)<DIM && (movInverso.columnamov + 1)<(DIM - 1)) {
movInverso.movPosibles[i] = true;
valido = true;
}
else movInverso.movPosibles[i] = false;
break;
}
}
if (valido) { // en el caso de que vlido sea true (es decir, que haya un movimiento disponible)
// se elegir una direccin al azar, y si resulta que es de las que se pueden,
dirFicha = rand() % NUM_DIRS;
while (!movInverso.movPosibles[dirFicha]) {
dirFicha = rand() % NUM_DIRS;
}
movInverso.direccionMov = tDireccion(dirFicha);
}
return valido;
}
void ejecutarMovimientoInverso(tTablero &tablero, const tMovimiento &movInverso) {
switch (movInverso.direccionMov) {
//ARRIBA
case ARRIBA: tablero[movInverso.filamov - 1][movInverso.columnamov] = FICHA;
tablero[movInverso.filamov - 2][movInverso.columnamov] = FICHA;
tablero[movInverso.filamov][movInverso.columnamov] = VACIA;
break;
//ABAJO
case ABAJO: tablero[movInverso.filamov + 1][movInverso.columnamov] = FICHA;
tablero[movInverso.filamov + 2][movInverso.columnamov] = FICHA;
tablero[movInverso.filamov][movInverso.columnamov] = VACIA;
break;
//IZQUIERDA
case IZQUIERDA: tablero[movInverso.filamov][movInverso.columnamov - 1] = FICHA;
tablero[movInverso.filamov][movInverso.columnamov - 2] = FICHA;
tablero[movInverso.filamov][movInverso.columnamov] = VACIA;
break;
//DERECHA
case DERECHA: tablero[movInverso.filamov][movInverso.columnamov + 1] = FICHA;
tablero[movInverso.filamov][movInverso.columnamov + 2] = FICHA;
tablero[movInverso.filamov][movInverso.columnamov] = VACIA;
break;
}
} | true |
07141d48cf312afc4227b0cf9c3b250ee4bc305d | C++ | dotnet/diagnostics | /src/shared/inc/safewrap.h | UTF-8 | 6,203 | 2.734375 | 3 | [
"MIT"
] | permissive | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// SafeWrap.h
//
//
// This file contains wrapper functions for Win32 API's that take SStrings
// and use CLR-safe holders.
//*****************************************************************************
/*
Guidelines for SafeWrapper APIs:
Most of these are 'common-sense', plus a few arbitrary decisions thrown in for
consistency's sake.
- THROWING: Throw on oom, but return all other failure codes.
The rationale here is that SString operations already throw, so to make these APIs
non-throwing would require an extra EX_TRY/EX_CATCH. Most callees will want to throw
on OOM anyways. So making these APIs non-throwing would mean an extra try/catch in
the caller + an extra check at the callee. We can eliminate that overhead and just make
it throwing.
Return non-oom failure codes because callees actually freqeuntly expect an API to fail.
For example, the callee will have special handling for file-not-found.
For convenience, you could add a no-throwing wrapper version of the API:
ClrGetEnvironmentVariable <-- default throws on oom.
ClrGetEnvironmentVariableNoThrow <-- never throws.
- NAMING: Prefix the name with 'Clr', just like we do for win32 APIs going through hosting.
- DON'T FORGET CONTRACTS: Most of these APIs will likely be Throws/GC_Notrigger.
Also use PRECONDITIONs + POSTCONDITIONS when possible.
- SIGNATURES: Keep the method signture as close the the original win32 API as possible.
- Preserve the return type + value. (except allow it to throw on oom). If the return value
should be a holder, then use that as an out-parameter at the end of the argument list.
We don't want to return holders because that will cause the dtors to be called.
- For input strings use 'const SString &' instead of 'LPCWSTR'.
- Change ('out' string, length) pairs to 'SString &' (this is the convention the rest of the CLR uses for SStrings)
- Use Holders where appropriate.
- Preserve other parameters.
- USE SSTRINGS TO AVOID BUFFER OVERRUN ISSUES: Repeated here for emphasis. Use SStrings when
applicable to make it very easy to verify the code does not have buffer overruns.
This will also simplify callsites from having to figure out the length of the output string.
- USE YOUR BEST JUDGEMENT: The primary goal of these API wrappers is to embrace 'security-safe' practices.
Certainly take any additional steps to that goal. For example, it may make sense to eliminate
corner case inputs for a given API or to break a single confusing API up into several discrete and
move obvious APIs.
*/
#ifndef _safewrap_h_
#define _safewrap_h_
#include "holder.h"
class SString;
bool ClrGetEnvironmentVariable(LPCSTR szEnvVarName, SString & value);
bool ClrGetEnvironmentVariableNoThrow(LPCSTR szEnvVarName, SString & value);
void ClrGetModuleFileName(HMODULE hModule, SString & value);
void ClrGetCurrentDirectory(SString & value);
/* --------------------------------------------------------------------------- *
* Simple wrapper around WszFindFirstFile/WszFindNextFile
* --------------------------------------------------------------------------- */
class ClrDirectoryEnumerator
{
WIN32_FIND_DATAW data;
FindHandleHolder dirHandle;
BOOL fFindNext; // Skip FindNextFile first time around
public:
ClrDirectoryEnumerator(LPCWSTR pBaseDirectory, LPCWSTR pMask = W("*"));
bool Next();
LPCWSTR GetFileName()
{
return data.cFileName;
}
DWORD GetFileAttributes()
{
return data.dwFileAttributes;
}
void Close()
{
dirHandle.Clear();
}
};
// Read a REG_SZ (null-terminated string) value from the registry. Throws.
void ClrRegReadString(HKEY hKey, const SString & szValueName, SString & value);
/* --------------------------------------------------------------------------- *
* Simple wrapper around RegisterEventSource/ReportEvent/DeregisterEventSource
* --------------------------------------------------------------------------- */
// Returns ERROR_SUCCESS if succeessful in reporting to event log, or
// Windows error code to indicate the specific error.
DWORD ClrReportEvent(
LPCWSTR pEventSource,
WORD wType,
WORD wCategory,
DWORD dwEventID,
PSID lpUserSid,
WORD wNumStrings,
LPCWSTR *lpStrings,
DWORD dwDataSize = 0,
LPVOID lpRawData = NULL);
DWORD ClrReportEvent(
LPCWSTR pEventSource,
WORD wType,
WORD wCategory,
DWORD dwEventID,
PSID lpUserSid,
LPCWSTR pMessage);
//*****************************************************************************
// This provides a wrapper around GetFileSize() that forces it to fail
// if the file is >4g and pdwHigh is NULL. Other than that, it acts like
// the genuine GetFileSize().
//
//
//*****************************************************************************
DWORD inline SafeGetFileSize(HANDLE hFile, DWORD *pdwHigh)
{
if (pdwHigh != NULL)
{
return ::GetFileSize(hFile, pdwHigh);
}
else
{
DWORD hi;
DWORD lo = ::GetFileSize(hFile, &hi);
if (lo == 0xffffffff && GetLastError() != NO_ERROR)
{
return lo;
}
// api succeeded. is the file too large?
if (hi != 0)
{
// there isn't really a good error to set here...
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return 0xffffffff;
}
if (lo == 0xffffffff)
{
// note that a success return of (hi=0,lo=0xffffffff) will be
// treated as an error by the caller. Again, that's part of the
// price of being a slacker and not handling the high dword.
// We'll set a lasterror for them to pick up.
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
}
return lo;
}
}
#endif // _safewrap_h_
| true |
3c4de80378079b30a10d70051f767cf32b90fb4c | C++ | jmjatlanta/bitcoin-toolbox | /utils/calc_redeem_script.cpp | UTF-8 | 2,548 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <string>
#include <iostream>
#include <vector>
#include <script.hpp>
#include <iomanip>
#include <sstream>
void print_help_and_exit(int argc, char** argv)
{
std::cerr << "Syntax: " << argv[0] << " [ testnet | mainnet ] HASH160_HASHLOCK RECEIVER_PRIMARY_KEY TIMELOCK SENDER_PRIMARY_KEY\n";
if (argc > 1)
{
std::cerr << "Parameters passed: ";
for(int i = 1; i < argc; ++i)
{
std::cerr << argv[i] << " ";
}
std::cerr << "\n";
}
exit(1);
}
std::vector<uint8_t> string_to_vector(std::string input)
{
std::vector<uint8_t> v(input.begin(), input.end());
return v;
}
std::string vector_to_hex_string(std::vector<uint8_t> incoming)
{
std::stringstream ss;
for(auto i : incoming)
{
ss << std::hex << std::setw(2) << std::setfill('0') << (int)i;
}
return ss.str();
}
int main(int argc, char**argv)
{
// parse the command line
if(argc < 5)
print_help_and_exit(argc, argv);
bool testnet = false;
if (std::string(argv[1]) == "testnet")
testnet = true;
if (!testnet && std::string(argv[1]) != "mainnet")
print_help_and_exit(argc, argv);
std::vector<uint8_t> hash160_hash_lock = bc_toolbox::hex_string_to_vector(argv[2]);
std::vector<uint8_t> recipient_pubkey = bc_toolbox::hex_string_to_vector(argv[3]);
std::vector<uint8_t> recipient_pubkey_hash = bc_toolbox::ripemd160(bc_toolbox::sha256(recipient_pubkey));
uint32_t timeout = std::atoi(argv[4]);
std::vector<uint8_t> sender_pubkey = bc_toolbox::hex_string_to_vector(argv[5]);
std::vector<uint8_t> sender_pubkey_hash = bc_toolbox::ripemd160(bc_toolbox::sha256(sender_pubkey));
// following bip199
bc_toolbox::script s;
s.add_opcode(bc_toolbox::OP_IF);
s.add_opcode(bc_toolbox::OP_HASH160);
s.add_bytes_with_size(hash160_hash_lock);
s.add_opcode(bc_toolbox::OP_EQUALVERIFY);
s.add_opcode(bc_toolbox::OP_DUP);
s.add_opcode(bc_toolbox::OP_HASH160);
s.add_bytes_with_size(recipient_pubkey_hash);
s.add_opcode(bc_toolbox::OP_ELSE);
s.add_int(timeout);
s.add_opcode(bc_toolbox::OP_CHECKLOCKTIMEVERIFY);
s.add_opcode(bc_toolbox::OP_DROP);
s.add_opcode(bc_toolbox::OP_DUP);
s.add_opcode(bc_toolbox::OP_HASH160);
s.add_bytes_with_size(sender_pubkey_hash);
s.add_opcode(bc_toolbox::OP_ENDIF);
s.add_opcode(bc_toolbox::OP_EQUALVERIFY);
s.add_opcode(bc_toolbox::OP_CHECKSIG);
std::vector<uint8_t> redeem_script = s.get_bytes_as_vector();
std::cout << vector_to_hex_string(redeem_script) << "\n";
return 0;
}
| true |
aee3ffc40c7775f919ec78fcad4a98de09a9d739 | C++ | caomw/ShadingCurves | /Curve/BSpline.h | UTF-8 | 2,789 | 2.53125 | 3 | [] | no_license | #ifndef BSPLINE_H
#define BSPLINE_H
#include <vector>
#include <QPainterPath>
#include <opencv2/core/core.hpp>
#include "ControlPoint.h"
#define DEFAULT_SUBDV_LEVELS 0
class BSplineGroup;
class Surface;
class BSpline
{
public:
BSpline();
void recompute();
void computeSurfaces(cv::Mat dt, cv::Mat luminance, bool clipHeight);
void fix_orientation();
void change_generic_extent(float extent);
void change_bspline_type(bool _is_slope, bool _has_uniform_subdivision, bool _has_inward, bool _has_outward);
//Normal at the (index)th control point
QPointF get_normal(int index, bool subdivided = true, bool is_inward = true);
//Utilites
QVector<ControlPoint> getPoints(); // HENRIK: return list of control points
QVector<ControlPoint> getDisplayPoints(int levels = 5, bool recompute = false);
QVector<ControlPoint> getControlPoints();
void computeControlPointNormals();
void computeJunctionNormals(QVector<ControlPoint>& cpts, int i, QPointF& in_normal, QPointF& out_normal);
std::string ghostSurfaceString(NormalDirection direction, cv::Mat img);
ControlPoint& pointAt(int index);
Surface& surfaceAt(int index);
bool has_loop()
{
return (num_cpts()>1 && cptRefs.front() == cptRefs.back());
}
int num_cpts()
{
return cptRefs.size();
}
int num_surfaces()
{
return surfaceRefs.size();
}
QVector<QPointF> getNormals(bool is_inward)
{
if (inward_subdivided_normals.size() == 0)
computeControlPointNormals();
if (is_inward) return inward_subdivided_normals;
else return outward_subdivided_normals;
}
void write(cv::FileStorage& fs) const ;
void read(const cv::FileNode& node);
BSpline(cv::FileNode node):ref(-1), has_inward_surface(false), has_outward_surface(false), has_uniform_subdivision(false), is_slope(false), generic_extent(30.0f)//:BSpline()
{
thickness = 0;
read(node);
}
public:
BSplineGroup *m_splineGroup;
QVector<int> cptRefs;
QVector<int> surfaceRefs;
int ref;
float generic_extent;
bool is_slope;
bool has_uniform_subdivision;
bool has_inward_surface;
bool has_outward_surface;
int thickness;
cv::Vec3b boundary_colors[2];
int subv_levels;
QVector<ControlPoint> subdivided_points;
QVector<ControlPoint> display_points;
QVector<QPointF> inward_subdivided_normals, outward_subdivided_normals;
QVector<QPointF> inward_normals, outward_normals;
bool start_has_zero_height[2]; //for inward and outward directions. Use for surface creation
bool end_has_zero_height[2];
std::vector< std::pair<int, Attribute> > junctionPoints[2]; //Position and height
};
#endif // BSPLINE_H
| true |
8ce9692c038ad1764f8e2aa7357ed3b461207acc | C++ | federicomrossi/7542-tp-final-grupo04 | /Codigo/common_socket.cpp | UTF-8 | 7,022 | 3.09375 | 3 | [] | no_license | //
// common_socket.cpp
// CLASE SOCKET
//
// Clase que implementa la interfaz de los sockets de flujo (utilizando el
// protocolo TCP), proporcionando un conjunto medianamente extenso de métodos
// y propiedades para las comunicaciones en red.
//
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <netdb.h>
#include "common_socket.h"
/* ****************************************************************************
* DEFINICIÓN DE LA CLASE
* ***************************************************************************/
// Constructor.
Socket::Socket() : activo(false) { }
// Constructor privado.
// Crea un nuevo socket.
// PRE: 'sockfd' es un filedescriptor que identifica a un socket.
Socket::Socket(const int sockfd) : sockfd(sockfd), activo(true) { }
// Destructor.
// Cierra el socket.
Socket::~Socket() {
if(close(this->sockfd) == -1)
std::cerr << "ERROR: No se ha podido cerrar el socket." << std::endl;
}
// Crea el socket
// POST: lanza una excepción si no se logra llevar a cabo la creación.
void Socket::crear() {
if((this->sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
throw "ERROR: No se ha podido crear el socket.";
// Cambiamos el estado del socket
this->activo = true;
}
// Devuelve el ID del socket.
// PRE: para considerarse válido, debe haberse creado previamente el
// socket.
int Socket::obtenerID() {
return this->sockfd;
}
// Conecta el socket a una dirección y puerto destino.
// PRE: 'hostDestino' es una cadena que contiene el nombre del host o la
// dirección IP a la que se desea conectar; 'puertoDestino' es el puerto
// al que se desea conectar.
// POST: determina dirección y puertos locales si no se utilizó el método
// bind() previamente. Además, lanza una excepción si no se pudo llevar a
// cabo la conexión.
void Socket::conectar(std::string hostDestino, int puertoDestino) {
// Obtenemos host
struct hostent *he = gethostbyname(hostDestino.c_str());
// Cargamos datos de la conexión a realizar
destinoDir.sin_family = AF_INET;
destinoDir.sin_port = htons(puertoDestino);
// destinoDir.sin_addr.s_addr = inet_addr(ipDestino.c_str());
destinoDir.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(destinoDir.sin_zero), '\0', sizeof(destinoDir.sin_zero));
// Conectamos
if(connect(this->sockfd, (struct sockaddr *)&destinoDir,
sizeof(struct sockaddr)) == -1)
throw "ERROR: No se pudo llevar a cabo la conexión.";
}
// Configura el socket para recibir conexiones en la dirección y puerto
// previamente asociados mediante el método enlazar();
// PRE: 'maxConexiones' es el número de conexiones entrantes permitidas en
// la cola de entrada.
// POST: lanza una excepción si no se pudo inicializar la escucha.
void Socket::escuchar(int maxConexiones, int puerto, std::string ip) {
// Enlazamos
enlazar(puerto, ip);
// Comenzamos la escucha
if(listen(this->sockfd, maxConexiones) == -1)
throw "ERROR: No se pudo comenzar a escuchar.";
}
// Espera una conexión en el socket previamente configurado con el método
// escuchar().
// POST: lanza una excepción si no pudo aceptar la conexión.
Socket* Socket::aceptar() {
unsigned sin_size = sizeof(struct sockaddr_in);
int sCliente = accept(sockfd, (struct sockaddr *)&destinoDir, &sin_size);
// Corroboramos si no se cerró el socket
if(!this->estaActivo()) return 0;
// Corroboramos si se produjo un error
else if (sCliente < 0)
throw "ERROR: No se pudo aceptar la conexión";
return (new Socket(sCliente));
}
// Envía datos a través del socket de forma completa.
// PRE: 'dato' es el dato que se desea enviar; 'longDato' es la longitud
// de los datos en bytes.
// POST: devuelve 0 si se ha realizado el envio correctamente o -1 en caso
// de error.
int Socket::enviar(const void* dato, int longDato) {
// Cantidad de bytes que han sido enviados
int bytesTotal = 0;
// Cantidad de bytes que faltan enviar
int bytesRestantes = longDato;
// Variable auxiliar
int n = 0;
while(bytesRestantes > 0) {
// Realizamos envío de bytes
n = send(this->sockfd, (char *) dato + bytesTotal, bytesRestantes, 0);
// En caso de error, salimos
if(n == -1) break;
// Incrementamos la cantidad de bytes ya enviados
bytesTotal += n;
// Decrementamos cantidad de bytes restantes
bytesRestantes -= n;
}
return (n == -1) ? -1:0;
}
// Recibe datos a través del socket.
// PRE: 'buffer' es el buffer en donde se va a depositar la información
// leida; 'longBuffer' es la longitud máxima del buffer.
// POST: devuelve el número de bytes que han sido leidos o 0 (cero) si el
// host remoto a cerrado la conexión.
int Socket::recibir(void* buffer, int longBuffer) {
// Limpiamos buffer
memset(buffer, '\0', longBuffer);
// Recibimos datos en buffer
return recv(this->sockfd, buffer, longBuffer, 0);
}
// Cierra el socket. Brinda distintos tipos de formas de cerrar permitiendo
// realizar un cierre del envío y recepción de datos en forma controlada.
// PRE: si 'modo' es 0, no se permite recibir más datos; si es 1, no se
// permite enviar más datos; si es 2, no se permite enviar ni recibir más
// datos, quedando inutilizable el socket. Si no se especifica ningún modo
// al llamar al método, se utiliza por defecto el modo 2.
// POST: el socket quedará parcial o completamente inutilizable
// dependiendo del modo elegido.
int Socket::cerrar(int modo) {
if(modo == 2)
this->activo = false;
return shutdown(this->sockfd, modo);
}
// Corrobora si el socket se encuentra activo. Que no este activo significa
// da cuenta de que el socket se encuentra inutilizable para la transmisión
// y recepción de datos.
// POST: devuelve true si el socket se encuentra activo o false en su
// defecto.
bool Socket::estaActivo() {
return this->activo;
}
// Enlaza (asocia) al socket con un puerto y una dirección IP.
// PRE: 'ip' es una cadena que contiene el nombre del host o la dirección
// IP a la que se desea asociar; 'puerto' es el puerto al que se desea
// enlazar.
// POST: lanza una excepción si no se logra llevar a cabo el enlace.
void Socket::enlazar(int puerto, std::string ip) {
int yes = 1;
// Reutilizamos socket
if(setsockopt(this->sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))
== -1)
throw "ERROR: Antes de enlazar, no se pudo reutilizar socket.";
// Cargamos datos del enlace a realizar
this->miDir.sin_family = AF_INET;
this->miDir.sin_port = htons(puerto);
// Obtenemos host
if(ip == "")
this->miDir.sin_addr.s_addr = htonl(INADDR_ANY);
else {
struct hostent *he = gethostbyname(ip.c_str());
this->miDir.sin_addr = *((struct in_addr *)he->h_addr);
}
memset(miDir.sin_zero, '\0', sizeof(miDir.sin_zero));
// Enlazamos
if(bind(this->sockfd, (struct sockaddr *)&miDir, sizeof(miDir)) < 0)
throw "ERROR: No se pudo llevar a cabo el enlace.";
}
| true |
c190ee4673626dd3ee0a1cfd71b231fbb7bdc8f4 | C++ | phani653/fresh-water | /clg_programs/hacker rank/NigratoryBirds.cpp | UTF-8 | 360 | 2.765625 | 3 | [] | no_license | //https://www.hackerrank.com/challenges/migratory-birds/problem
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
int ar[n], type[6]={0};
for(int i=0; i< n; i++) cin >> ar[i];
for(int i=0;i<n;i++) type[ar[i]]++;
int lrg_typ= 1;
for(int i=2;i<=5;i++) if(type[i] > type[lrg_typ]) lrg_typ = i;
cout << lrg_typ;
return 0;
} | true |
3ae3140d49bcf6fc8cba38b45b55a17829e9201f | C++ | CytronTechnologies/Arduino_SN-FPR-SM630 | /SM630_AddFinger/SM630_AddFinger.ino | UTF-8 | 3,807 | 2.515625 | 3 | [] | no_license | #include <SoftwareSerial.h>
#define DEBUG 0
SoftwareSerial mySerial(10, 11); // RX, TX
/************************************************************************
Communication Packet
************************************************************************/
byte addFingerPrint0[] = {0x4D, 0x58, 0x10, 0x03, 0x40, 0x00, 0x00, 0xF8};
byte receiveCorrect[] = {0x4D, 0x58, 0x30, 0x01, 0x01, 0xD7};
byte operationSuccessAdd[] = {0x4D, 0x58, 0x30, 0x02, 0x40, 0x31, 0x48};
byte parameterErrorAdd[] = {0x4D, 0x58, 0x30, 0x02, 0x40, 0x35, 0x4C};
byte processFailureAdd[] = {0x4D, 0x58, 0x30, 0x02, 0x40, 0x34, 0x4B};
byte timeOutAdd[] = {0x4D, 0x58, 0x30, 0x02, 0x40, 0x33, 0x4A};
/************************************************************************
Variables
************************************************************************/
byte respond[6], operation[7], operationSecond[7];
byte a,b,c,d,e,f,g,h;
int A = 0;
void setup()
{
mySerial.begin(57600);
Serial.begin(9600);
}
void loop()
{
if(A == 0)
{
addFinger0();
if(correctRespond())
operationStart();
delay(1000); // a delay for next operation
}
}
void addFinger0() {
Serial.println("Add fingerprint at ID #0");
mySerial.write(addFingerPrint0, sizeof(addFingerPrint0));
}
bool correctRespond()
{
while(mySerial.available() <= 0) {}; //wait for incoming data
delay(10); // give some time for all incoming bytes to be stored into serial buffer
while(mySerial.available() > 6) // this is to make sure removal of respond from previous command
mySerial.read();
memset(respond, '\0', 6); // clear respond buffer
mySerial.readBytes(respond, 6); //store the remaining data to respond buffer
#if DEBUG
for(byte x=0; x<sizeof(respond); x++)
Serial.print(respond[x], HEX);
Serial.println();
#endif
a = memcmp(receiveCorrect, respond, sizeof(receiveCorrect));
if (a == 0)
{
Serial.println("Receive Correct");
return 1;
}
else
{
Serial.println("Error!");
return 0;
}
}
void operationStart()
{
while(mySerial.available() <= 0) {}; //wait for incoming data
memset(operation, '\0', 7); // clear operation buffer
mySerial.readBytes(operation, 7); //store data
#if DEBUG
for(byte x=0; x<6; x++)
Serial.print(operation[x], HEX);
Serial.println();
#endif
b = memcmp(operationSuccessAdd, operation, sizeof(operationSuccessAdd));
c = memcmp(processFailureAdd, operation, sizeof(processFailureAdd));
d = memcmp(parameterErrorAdd, operation, sizeof(parameterErrorAdd));
e = memcmp(timeOutAdd, operation, sizeof(timeOutAdd));
if (b == 0)
{
Serial.println("First Fingerprint Scanned");
while(mySerial.available() <= 0) {}; //wait for incoming data
memset(operation, '\0', 7); //clear operation buffer
mySerial.readBytes(operation, 7); //store data to buffer
#if DEBUG
for(byte x=0; x<6; x++)
Serial.print(operation[x], HEX);
Serial.println();
#endif
f = memcmp(operationSuccessAdd, operation, sizeof(operationSuccessAdd));
g = memcmp(processFailureAdd, operation, sizeof(processFailureAdd));
h = memcmp(timeOutAdd, operation, sizeof(timeOutAdd));
if (f == 0)
{
Serial.println("Second Fingerprint Scanned");
Serial.println("Fingerprint Added");
A = 1;
}
else
{
if (g == 0)
Serial.println("Fingerprint Process Failure");
else if (h == 0)
Serial.println("Time Out");
Serial.println("Starting new operation!");
}
}
else
{
if (c == 0)
Serial.println("Fingerprint Process Failure");
else if (d == 0)
Serial.println("Parameter Error");
else if (e == 0)
Serial.println("Time Out");
Serial.println("Starting new operation!");
}
}
| true |
f8012b3bc3a14983270775cbb3e8122a78a6f3db | C++ | hackettccp/CSCI112 | /Modules/Module10/SampleCode/a_basics/Example4_VariablesAndTypes.cpp | UTF-8 | 2,432 | 4.09375 | 4 | [
"MIT"
] | permissive | /**
* Demonstrates variables and primitive data types in C++
*
*/
#include <iostream>
using namespace std;
/**
* Main Function.
*/
int main() {
int number = 75; //Same 4-byte (32-bit) signed integer data type as Java
long number2 = 1234L; //Same as an int (4-bytes). Historically, ints were 16-bits.
long long number3 = 12345L; //Equivalent to the 8-byte (64-bit) signed "long" data type in Java.
float number4 = 100.6F; //Same 4-byte (32-bit) signed floating point data type as Java
double number5 = 123.456; //Same 8-byte (64-bit) signed floating point data type as Java
long double number6 = 45.23; //12-byte (96-bit) signed floating point data type
short int number7 = 100; //Equivalent to the 2-byte (16-bit) signed short data type in Java
short number8 = 432; //Equivalent to "short int"
char char1 = 10; //Equivalent to the 1-byte (8-bit) signed byte data type in Java
char char2 = 'X'; //Can be used like the char data type in Java.
bool boolean1 = true; //Equivalent to the 1-byte (8-bit, though only 1 is ever used) boolean data type in Java.
//Prints the size of each of these variables.
//The sizeof function returns an int- The number of bytes the type uses.
cout << "Size of number: " << sizeof(number) << " bytes." << endl;
cout << "Size of number2: " << sizeof(number2) << " bytes." << endl;
cout << "Size of number3: " << sizeof(number3) << " bytes.\n" << endl;
cout << "Size of number4: " << sizeof(number4) << " bytes." << endl;
cout << "Size of number5: " << sizeof(number5) << " bytes." << endl;
cout << "Size of number6: " << sizeof(number6) << " bytes.\n" << endl;
cout << "Size of number7: " << sizeof(number7) << " bytes." << endl;
cout << "Size of number8: " << sizeof(number8) << " bytes.\n" << endl;
cout << "Size of char1: " << sizeof(char1) << " byte." << endl;
cout << "Size of char2: " << sizeof(char2) << " byte." << endl;
cout << "Size of boolean1: " << sizeof(boolean1) << " byte." << endl;
return 0;
} | true |
0b74d6e691ed8eeb7e3efe0744c64074c7a2345c | C++ | pedroAdami17/A.I_Assignment4 | /src/FloatCondition.h | UTF-8 | 416 | 2.75 | 3 | [] | no_license | #pragma once
#ifndef __FLOAT_CONDITION__
#define __FLOAT_CONDITION__
#include "Condition.h"
class FloatCondition :public Condition
{
public:
FloatCondition(const float min_value = 0.0f, const float max_value= 1.0f);
~FloatCondition();
void setTestValue(const float value);
bool Test() override;
private:
float m_minValue;
float m_maxValue;
float m_testValue;
};
#endif /* defined (__FLOAT_CONDITION__) */
| true |
e2cebab637721ca014f0ccd66f6eaf4b3a4dd457 | C++ | hieuhdh/OOP | /Theory/More/Problems/Friend/09.cpp | UTF-8 | 230 | 3.1875 | 3 | [] | no_license |
#include<iostream>
using namespace std;
class A{
int a = 10;
friend class B;
};
class B{
public:
void display(A&a){
cout << a.a;
}
};
int main(){
A a;
B b;
b.display(a);
return 0;
} | true |
2852183c53bd098cc2a8e041eb1daef23745666c | C++ | Davinatoratoe/Centipede | /CentipedeGame/CentipedeGame/DequeueScene.cpp | UTF-8 | 1,885 | 2.703125 | 3 | [] | no_license | #include "DequeueScene.h"
#include "imgui.h"
#include "string"
#include "CentipedeGameApp.h"
using namespace ImGui;
/// <summary>
/// Overloaded constructor.
/// </summary>
/// <param name="_font">The font to use.</param>
DequeueScene::DequeueScene()
{
}
/// <summary>
/// Deconstructor.
/// </summary>
DequeueScene::~DequeueScene()
{
}
/// <summary>
/// Called when the scene loads.
/// </summary>
void DequeueScene::OnStart()
{
dequeue = Dequeue<int>();
value = 0;
}
/// <summary>
/// Called when the scene closes.
/// </summary>
void DequeueScene::OnClose()
{
}
/// <summary>
/// Called once per frame.
/// </summary>
/// <param name="deltaTime">The time passed since last frame.</param>
/// <param name="input">A pointer to the input handler.</param>
void DequeueScene::Update(float deltaTime, Input* input)
{
CreateGUI("Dequeue");
InputInt("Value", &value);
if (Button("Generate dequeue", ImVec2(150, 0)))
{
dequeue.Clear();
for (unsigned int i = 0; i < 10; ++i)
dequeue.PushFront(rand() % 10);
}
if (Button("Push Front", ImVec2(150, 0)))
dequeue.PushFront(value);
if (Button("Push Back", ImVec2(150, 0)))
dequeue.PushBack(value);
if (Button("Pop Front", ImVec2(150, 0)))
dequeue.PopFront();
if (Button("Pop Back", ImVec2(150, 0)))
dequeue.PopBack();
if (Button("Clear", ImVec2(150, 0)))
dequeue.Clear();
if (Button("Copy", ImVec2(150, 0)))
dequeue = Dequeue<int>(dequeue);
if (Button("Assign", ImVec2(150, 0)))
dequeue = dequeue;
if (Button("Menu", ImVec2(150, 0)))
app->ChangeScene(app->menuScene);
End();
}
/// <summary>
/// Draws the graphics.
/// </summary>
/// <param name="renderer"></param>
void DequeueScene::Draw(Renderer2D* renderer)
{
renderer->drawText(app->font, ("List: " + dequeue.ToString()).c_str(), 20, 850);
renderer->drawText(app->font, ("Size: " + to_string(dequeue.Size())).c_str(), 20, 800);
}
| true |
150d2683388505d48d52263bab21ea9cdc27f313 | C++ | liujiawei2333/aha-algorithm | /1_sort/sort1.cpp | UTF-8 | 689 | 3.46875 | 3 | [] | no_license | //排序的练习题,去重并排序
//使用桶排序,先去重再排序,去重就是不再计算每个桶插旗子的数量了,只要出现的都赋值为1即可
#include <stdio.h>
int main()
{
int a[1001],n,i,t;
for (i=1;i<=1000;i++)
a[i]=0;//初始化
scanf("%d",&n);//读入n
for (i=1;i<=n;i++)//循环读入n个编号
{
scanf("%d",&t);//每个编号读入变量t
a[t]=1;//标记出现过的编号(去重)
}
for (i=1;i<=1000;i++)//依次判断1000个桶
{
if (a[i]==1)//如果编号出现过则打印出来
printf("%d ",i);
}
getchar();getchar();
return 0;
}
//时间复杂度O(M+N) | true |
7044f0c989c558ed06e9c87621cf2f68e4a7b6b5 | C++ | john1995/CSE168 | /Triangle.cpp | UTF-8 | 5,561 | 2.953125 | 3 | [] | no_license | #include "Triangle.h"
#include "TriangleMesh.h"
#include "Ray.h"
Triangle::Triangle(TriangleMesh * m, unsigned int i) :
m_mesh(m), m_index(i)
{
m_material = new const Material[3];
}
Triangle::~Triangle()
{
}
void
Triangle::renderGL()
{
//The individual triangle only holds its index within the mesh.
//The mesh holds its vertices and normals, as well as the indices of each.
//Get the triangle by its index within the mesh it is a part of
TriangleMesh::TupleI3 ti3 = m_mesh->vIndices()[m_index];
//Get each of its vertices through their indices in the mesh, which
//are stored in a custom-defined 'tuple' within the triangle mesh
const Vector3 & v0 = m_mesh->vertices()[ti3.x]; //vertex a of triangle
const Vector3 & v1 = m_mesh->vertices()[ti3.y]; //vertex b of triangle
const Vector3 & v2 = m_mesh->vertices()[ti3.z]; //vertex c of triangle
glBegin(GL_TRIANGLES);
glVertex3f(v0.x, v0.y, v0.z);
glVertex3f(v1.x, v1.y, v1.z);
glVertex3f(v2.x, v2.y, v2.z);
glEnd();
}
bool
Triangle::intersect(HitInfo& result, const Ray& r,float tMin, float tMax)
{
//Get the triangle by its index within the mesh it is a part of
TriangleMesh::TupleI3 ti3 = m_mesh->vIndices()[m_index];
const Vector3& a = m_mesh->vertices()[ti3.x]; //vertex a of triangle
const Vector3& b = m_mesh->vertices()[ti3.y]; //vertex b of triangle
const Vector3& c = m_mesh->vertices()[ti3.z]; //vertex c of triangle
//Compute how far away ray's origin is from the triangle's plane
//(or even if it hits the plane at all. Won't hit if ray parallel).
//First need to get normal of triangle
const Vector3& normal = (cross(b - a, c - a)).normalize();
//Solve n dot (p - x) = 0, for p, where n = normal and x = ray
//First check if n dot d is zero. If it is, ray is parallel to triangle
float denom = dot(normal, r.d);
if (denom == 0.0f)
return false;
result.t = dot(normal, a - r.o) / denom;
if (result.t < tMin || result.t > tMax)
{
return false;
}
//Assign hit location to HitInfo result
result.P = r.o + result.t * r.d;
//////////////////////BARYCENTRIC COORDINATES METHOD 1/////////////////////
//Find smallest two components of triangle's normal vector
int u, v; //min indices
float maxCmpnt = fmax(normal.x, fmax(normal.y, normal.z));
if (maxCmpnt == normal.x) { u = 1; v = 2; }
else if (maxCmpnt == normal.y) { u = 0; v = 2; }
else { u = 0; v = 1; }
//Compute barycentric coordinates of result.P relative to this triangle.
//If alpha and beta both between 0 and 1, and alpha + beta <= 1, HIT
//Check notes 4/5/16 for setup of linear equation and how Cramer's rule is used
//to solve for each coordinate.
//denominator in Cramer's Rule is same for both alpha and beta
float denominator = (b[u] - a[u]) * (c[v] - a[v]) - (b[v] - a[v]) * (c[u] - a[u]);
float alpha = ((result.P[u] - a[u]) * (c[v] - a[v]) -
(result.P[v] - a[v]) * (c[u] - a[u])) / denominator;
float beta = ((b[u] - a[u]) * (result.P[v] - a[v]) -
(b[v] - a[v]) * (result.P[u] - a[u])) / denominator;
//std::cerr << "Alpha method 1: " << alpha << std::endl;
//std::cerr << "Beta method 1: " << beta << std::endl;
////////////////////BARYCENTRIC COORDINATES METHOD 2////////////////////////
/*Vector3 n_a = cross(c - b, result.P - b);
Vector3 n_b = cross(a - c, result.P - c);
Vector3 n = cross(b - a, c - a);
float denominator2 = n.length() * n.length();
//float tri_Area = 0.5f * cross(b - a, c - a).length();
alpha = dot(n, n_a) / denominator2;
beta = dot(n, n_b) / denominator2;
std::cerr << "Alpha method 2: " << alpha << std::endl;
std::cerr << "Beta method 2: " << beta << std::endl;*/
if (alpha >= 0.0f && alpha <= 1.0f && beta >= 0.0f && beta <= 1.0f && alpha + beta <= 1.0f)
{
//There was a hit. Calculate Barycentric interpolation of normals so we can find
//normal to shade with at hit point.
//First, get vertex normals of vertices making up triangle.
TriangleMesh::TupleI3 ti3 = m_mesh->nIndices()[m_index];
const Vector3& normalA = m_mesh->normals()[ti3.x]; //Normal of A vert. of tri.
const Vector3& normalB = m_mesh->normals()[ti3.y]; //Normal of B vert. of tri.
const Vector3& normalC = m_mesh->normals()[ti3.z]; //Normal of C vert. of tri.
//Interpolate and assign result.N
//ARE ALPHA, BETA, AND GAMMA BEING MULTIPLIED BY THE RIGHT NORMALS?
float gamma = 1.0f - alpha - beta;
result.N = (gamma * normalA + alpha * normalB + beta * normalC).normalize();
//Set material
result.material = this->m_material;
return true;
}
else
return false;
}
Vector3 Triangle::calcCentroid()
{
//get vertices of triangle
//Get the triangle by its index within the mesh it is a part of
TriangleMesh::TupleI3 ti3 = m_mesh->vIndices()[m_index];
const Vector3& a = m_mesh->vertices()[ti3.x]; //vertex a of triangle
const Vector3& b = m_mesh->vertices()[ti3.y]; //vertex b of triangle
const Vector3& c = m_mesh->vertices()[ti3.z]; //vertex c of triangle
return Vector3 ((a.x + b.x + c.x) / 3.0,
(a.y + b.y + c.y) / 3.0,
(a.z + b.z + c.z) / 3.0);
}
| true |
ae3a8288b5a2019bf1c8f8bdab0ad3f1995857aa | C++ | ericlin1001/importSicilyToVmatrix | /unzip/2339 - Polymorphism and I_O/1001/main.cpp | UTF-8 | 353 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
int N;
string name, code;
double cost;
cin >> N;
while(N--) {
cin >> name >> code >> cost;
cout << setw(15) << left << name <<
setw(15) << left << code <<
setw(10) << right << setprecision(2) << fixed << cost << endl;
}
}
| true |
79a6f34ddf867ced9ad1409a93ab539027f8b42a | C++ | Herael/Aquarium | /Seaweed.h | UTF-8 | 425 | 2.640625 | 3 | [] | no_license | //
// Created by Benjamin Rousval on 26/01/2020.
//
#ifndef AQUARIUM_SEAWEED_H
#define AQUARIUM_SEAWEED_H
#include <ostream>
class Seaweed {
private:
int hp;
int turn;
public:
int getHp();
int getTurn();
void setHp(int i);
void setTurn(int i);
Seaweed();
Seaweed(int hp, int turn);
friend std::ostream &operator<<(std::ostream &os, const Seaweed &seaweed);
};
#endif //AQUARIUM_SEAWEED_H
| true |
fc3d3788c02cfc68b7ea956db1f2c7a985475217 | C++ | sigman78/sobjectizer | /so_5/rt/h/so_layer.hpp | UTF-8 | 2,464 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | /*
SObjectizer 5.
*/
/*!
\file
\brief An addition layer for the SObjectizer Environment definition.
*/
#pragma once
#include <memory>
#include <map>
#include <typeindex>
#include <so_5/h/declspec.hpp>
#include <so_5/h/ret_code.hpp>
#include <so_5/rt/h/fwd.hpp>
namespace so_5
{
//
// so_layer_t
//
//! An interface of the additional SObjectizer Environment layer.
class SO_5_TYPE layer_t
{
friend class impl::layer_core_t;
// Note: clang-3.9 requires this on Windows platform.
layer_t( const layer_t & ) = delete;
layer_t( layer_t && ) = delete;
layer_t & operator=( const layer_t & ) = delete;
layer_t & operator=( layer_t && ) = delete;
public:
layer_t();
virtual ~layer_t();
//! Start hook.
/*!
* The default implementation do nothing.
*/
virtual void
start();
//! Shutdown signal hook.
/*!
* The default implementation do nothing.
*/
virtual void
shutdown();
//! Waiting for the complete shutdown of a layer.
/*!
* The default implementation do nothing and returned immediately.
*/
virtual void
wait();
protected:
//! Access to the SObjectizer Environment.
/*!
* Throws an exception if a layer is not bound to
* the SObjectizer Environment.
*/
environment_t &
so_environment();
private:
//! Bind layer to the SObjectizer Environment.
void
bind_to_environment( environment_t * env );
//! SObjectizer Environment to which layer is bound.
/*!
* Pointer has the actual value only after binding
* to the SObjectizer Environment.
*/
environment_t * m_env;
};
//! Typedef for the layer's autopointer.
using layer_unique_ptr_t = std::unique_ptr< layer_t >;
//! Typedef for the layer's smart pointer.
using layer_ref_t = std::shared_ptr< layer_t >;
//! Typedef for the map from a layer typeid to the layer.
using layer_map_t = std::map< std::type_index, layer_ref_t >;
namespace rt
{
/*!
* \deprecated Will be removed in v.5.6.0. Use so_5::layer_t instead.
*/
using so_layer_t = so_5::layer_t;
/*!
* \deprecated Will be removed in v.5.6.0. Use so_5::layer_unique_ptr_t
* instead.
*/
using so_layer_unique_ptr_t = so_5::layer_unique_ptr_t;
/*!
* \deprecated Will be removed in v.5.6.0. Use so_5::layer_ref_t instead.
*/
using so_layer_ref_t = so_5::layer_ref_t;
/*!
* \deprecated Will be removed in v.5.6.0. Use so_5::layer_map_t
* instead.
*/
using so_layer_map_t = so_5::layer_map_t;
} /* namespace rt */
} /* namespace so_5 */
| true |
5d9e687a62e8624d2ae1e8b3d45a09d2ccf845a5 | C++ | netxpto/QuantumMiningSMC | /lib/hamming_decoder_20180608.cpp | UTF-8 | 4,422 | 2.765625 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <Windows.h>
#include "netxpto_20180418.h"
#include "hamming_decoder_20180608.h"
using namespace std;
void HammingDeCoder::initialize(void) {
outputSignals[0]->setSymbolPeriod(inputSignals[0]->getSymbolPeriod());
outputSignals[0]->setSamplingPeriod(inputSignals[0]->getSamplingPeriod());
}
bool HammingDeCoder::runBlock(void) {
bool alive{ false };
/* Update the parity bits according to the defined nBits and kBits */
setParityBits();
if (parityBits == 0) {
OutputDebugString("ERROR: (Hamming DeCoder) Invalid conmbination of (n, k) Hamming Code. \n");
return alive;
}
/* Determine n and k parameters according to selected parity for Hamming Code */
int hamming_n = nBits;
int hamming_k = kBits;
/* Avaiable bits on input buffer */
int ready = inputSignals[0]->ready();
/* Avaiable space on output buffer */
int space = outputSignals[0]->space();
/* Cycle to process data */
while ((ready >= hamming_k) && (space >= hamming_n)) {
/* Vectors for input/output data */
std::vector<int> inputData(hamming_n);
std::vector<int> outputData(hamming_k);
std::vector<int> errorData(hamming_n - hamming_k);
// Get the first k bits
for (int k = 0; k < hamming_n; k++) {
int in;
inputSignals[0]->bufferGet(&in);
inputData[k] = in;
}
// Multiply Vector by Matrix (in order to detect bit errors)
int sumError = 0;
for (int k = 0; k < hamming_n - hamming_k; k++) {
for (int m = 0; m < hamming_n; m++) {
errorData[k] += (H[m][k] * inputData[m]);
if (errorData[k] > 1) {
errorData[k] = 0;
}
}
sumError += errorData[k];
}
/* Check if an error was detected */
if (sumError != 0) {
/* Detect were the error was produced */
int errorLocation = -1;
/* Loacte error */
for (int m = getParityBits(); m < hamming_n; m++) {
int errorValidation = 0;
for (int k = 0; k < hamming_n - hamming_k; k++) {
if (H[m][k] == errorData[k]) {
errorValidation += 1;
}
}
/* Save the location were the error was detected */
if (errorValidation == getParityBits()) {
errorLocation = m;
break;
}
}
/* Correct the previously detected error */
if (errorLocation != -1) {
inputData[errorLocation] += 1;
if (inputData[errorLocation] > 1) {
inputData[errorLocation] = 0;
}
} /* If the error was detected in the parity bits, do nothing */
}
/* Filter data for output */
for (int k = 0; k < hamming_k; k++) {
outputData[k] = inputData[hamming_n - hamming_k + k];
}
// Store data in output
for (int k = 0; k < hamming_k; k++) {
outputSignals[0]->bufferPut(outputData[k]);
}
ready = inputSignals[0]->ready();
space = outputSignals[0]->space();
}
return alive;
}
void HammingDeCoder::setParityBits(void) {
/* Save the selected parity bits for the Hamming Code */
parityBits = getNBits() - getKBits();
for (int k = 0; k < (int)size(parity_array); k++) {
if (parity_array[k] == parityBits) {
if ((k_array[k] == kBits) && (n_array[k] == nBits)) {
/* Calculate the G matrix according to the selected parity bits */
setHMatrix(parityBits);
return;
}
}
}
parityBits = 0;
}
int HammingDeCoder::getNBits() {
return nBits;
}
void HammingDeCoder::setNBits(int s_n) {
/* Save the selected Code Word length for the Hamming Code */
nBits = s_n;
}
int HammingDeCoder::getKBits() {
return kBits;
}
void HammingDeCoder::setKBits(int s_n) {
/* Save the selected Data length for the Hamming Code */
kBits = s_n;
}
int HammingDeCoder::getParityBits() {
return parityBits;
}
void HammingDeCoder::setHMatrix(int s_n) {
/* Determine n and k parameters according to selected parity for Hamming Code */
const int hamming_n = n_array[getParityBits() - 2];
/* Auxiliary G Matrix to perform calculations */
vector<vector<int>> H_aux(hamming_n, vector<int>(getParityBits()));
/* Parity Part of G matrix */
for (int i = 0; i < getParityBits(); i++) {
for (int j = 0; j < getParityBits(); j++) {
if (i == j) {
H_aux[i][j] = 1;
} else {
H_aux[i][j] = 0;
}
}
}
/* Data Part of G matrix */
for (int i = getParityBits(); i < hamming_n; i++) {
for (int j = 0; j < getParityBits(); j++) {
if (i - getParityBits() == j) {
H_aux[i][j] = 0;
} else {
H_aux[i][j] = 1;
}
}
}
/* Assign the auxiliary matrix to the private G matrix */
H = H_aux;
}
| true |
4cc72547142dc9dbb608b9706f576a679fbc0715 | C++ | hancockyang/cpp-programming-language | /week3/Homework/1/main.cpp | UTF-8 | 511 | 3.015625 | 3 | [] | no_license | //
// main.cpp
// Homework1
//
// Created by hankang yang on 2/5/16.
// Copyright © 2016 hankang yang. All rights reserved.
//
#include <iostream>
using namespace std;
class A {
int val;
public:
A(int n) { val = n; }
int GetVal() { return val; }
};
class B: public A {
private:
int val;
public:
B(int n):val(n+2),A(n+4)
{ }
int GetVal() { return val; }
};
int main(int argc, const char * argv[]) {
B b1(2);
cout << b1.GetVal() << "," << b1.A::GetVal() << endl;
return 0;
}
| true |
31ca6e7c19f1de1f8397c7af606e17f760876cca | C++ | yuuyuk99/TankGame | /3D Game Framework 2017-06/DirectXgameFramework/Tower/Tower.cpp | SHIFT_JIS | 1,864 | 2.546875 | 3 | [] | no_license | #include "Tower.h"
#include "../Graphics.h"
#include <Effects.h>
#include <CommonStates.h>
#include "../Camera/Camera.h"
using namespace DirectX::SimpleMath;
using namespace DirectX;
using namespace std;
/*
*@RXgN^
*/
Tower::Tower()
{
//^[̐
this->_Tower = std::make_shared<ObjectBase>();
this->_health = 10;
}
/*
*@TowerIuWFNg̏
*/
void Tower::Initialize()
{
//GraphicsNX̃CX^X擾
auto& graphics = Graphics::Get();
//CommonStates
this->_commonState = make_unique<CommonStates>(graphics.Device().Get());
//GtFNgt@Ng̍쐬
_factory = make_unique<EffectFactory>(graphics.Device().Get());
//eNX`̓ǂݍ݃pXw eNX`t@Cw
_factory->SetDirectory(L"Resources/cModels");
//^[̃fǂݍ
this->_Tower->LoadModelFile(L"Resources/cModels/cTower.cmo");
//蔻̐ݒ
_collisionNode.Initialize();
//蔻̃[hWݒ
_collisionNode.SetParentMatrix(&this->_Tower->GetLocalWorld());
//蔻̑傫ݒ
_collisionNode.SetLocalRadius(1.0f);
//蔻肪eǂꂾĂ邩
_collisionNode.SetTrans(Vector3(0.0f, 0.0f, 0.0f));
}
/*
*@TowerIuWFNg̍XV
*/
void Tower::Update()
{
//[hW
Matrix world = Matrix::Identity;
//sXV
this->_Tower->Calc(world);
//蔻̍XV
this->_collisionNode.Update();
}
/*
*@TowerIuWFNg̕`揈
*/
void Tower::Draw(shared_ptr<Camera> camera)
{
//^[̕`
this->_Tower->Draw(camera);
//蔻̕`
this->_collisionNode.Draw();
}
/*
*@TowerIuWFNǧ㏈
*/
void Tower::Finalize()
{
}
| true |
446f290ebb81c51719e6c92f025de4019646dcbc | C++ | lberserq/mg | /branch.h | UTF-8 | 479 | 2.5625 | 3 | [] | no_license | #pragma once
#include "object.h"
enum
{
MAX_DEPTH = 20,
MAX_CAPACITY = 20
};
//branch of tree is cylinder
class branch : public object
{
friend class object;
int level_id;
void init_matrix() override;
public:
branch(object *parent = NULL);
virtual ~branch(void);
//redefinition of
void set_level(int id) {
level_id = id;
}
virtual void add_child(object *obj) override;
void draw() override;
void grow() override;
};
| true |
972ae82c0f3d9997c6c8848502167426e4b7fa56 | C++ | prizm-labs/olaunch-hardware | /led_coaster/led_coaster_beginner_attiny/led_coaster_beginner_attiny.ino | UTF-8 | 1,701 | 3.125 | 3 | [] | no_license | // Indentifies the Pins used on the ATtiny
int pinLedRed = 0;
int pinLedYellow = 1;
int pinLedGreen = 2;
int pinPressureSensor = 3;
// The number of pressure levels on their ranges
int countPressureLevels = 4;
int colorPressureLevels[4][2] = {
{0,100},
{101,103},
{104,106},
{107,1000}
};
// This is the color for each pressure level
int colorRGBValues[4][3] = {
{0,0,0},
{255,0,0}, //red
{0,255,0}, //yellow
{0,0,255} //green
};
/* ATtiny's don't have the serial library due to their smaller size, so thats
why is commented out.
*/
void setup() {
//Serial.begin(9600);
pinMode(pinPressureSensor, INPUT);
pinMode(pinLedRed, OUTPUT);
pinMode(pinLedGreen, OUTPUT);
pinMode(pinLedYellow, OUTPUT);
}
void loop() {
int pressureLevel = getPressureLevel();
//Serial.println(pressureLevel);
setColor(pressureLevel);
}
// Finds the color for the right pressure vaule and turns on and off the LED's
void setColor(int pressureLevel) {
int redValue = colorRGBValues[pressureLevel][0];
int yellowValue = colorRGBValues[pressureLevel][1];
int greenValue = colorRGBValues[pressureLevel][2];
analogWrite(pinLedRed,redValue);
analogWrite(pinLedGreen,greenValue);
analogWrite(pinLedYellow,yellowValue);
}
// This finds the pressure level between the to copper PCB's
int getPressureLevel() {
int pressureLevel=0;
int pressureSensorValue = analogRead(pinPressureSensor);
for (int i=0; i<countPressureLevels; i++) {
int minValue = colorPressureLevels[i][0];
int maxValue = colorPressureLevels[i][1];
if (pressureSensorValue>=minValue && pressureSensorValue<=maxValue) {
pressureLevel=i;
break;
}
}
return pressureLevel;
}
| true |
ebb57b7343b263af92eee65040af6aacc6f7b91e | C++ | UnicornMane/AG_homework7.12.2019 | /8.cpp | UTF-8 | 939 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <random>
#include <algorithm>
using namespace std;
/*void kStatistics(vector <int> &arr, int &k)
{
nth_element(arr.begin(), arr.begin() + k - 1, arr.end());
}
*/
int kStatistics(std::vector<int> a, int n, int k)
{
for (int l = 1, r = n; ; )
{
if (r <= l + 1)
{
if (r == l + 1 && a[r] < a[l])
swap(a[l], a[r]);
return a[k];
}
int mid = (l + r) >> 1;
swap(a[mid], a[l + 1]);
if (a[l] > a[r])
swap(a[l], a[r]);
if (a[l + 1] > a[r])
swap(a[l + 1], a[r]);
if (a[l] > a[l + 1])
swap(a[l], a[l + 1]);
int i = l + 1, j = r;
const int cur = a[l + 1];
while(1)
{
while (a[++i] < cur);
while (a[--j] > cur);
if (i > j)
break;
swap(a[i], a[j]);
}
a[l + 1] = a[j];
a[j] = cur;
if (j >= k)
r = j - 1;
if (j <= k)
l = i;
}
}
int main()
{
}
| true |
b05b45caa721e6ac6a1e339123ed8830656198e1 | C++ | acolombier/MSc-OSProject-NachOS | /code/machine/translate.h | UTF-8 | 3,144 | 2.984375 | 3 | [
"MIT-Modern-Variant"
] | permissive | // translate.h
// Data structures for managing the translation from
// virtual page # -> physical page #, used for managing
// physical memory on behalf of user programs.
//
// The data structures in this file are "dual-use" - they
// serve both as a page table entry, and as an entry in
// a software-managed translation lookaside buffer (TLB).
// Either way, each entry is of the form:
// <virtual page #, physical page #>.
//
// DO NOT CHANGE -- part of the machine emulation -- *Updated to the way we do it in the 21st centuary*
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#ifndef TLB_H
#define TLB_H
#include "copyright.h"
#include "utility.h"
// The following class defines an entry in a translation table -- either
// in a page table or a TLB. Each entry defines a mapping from one
// virtual page to one physical page.
// In addition, there are some extra bits for access control (valid and
// read-only) and some bits for usage information (use and dirty).
//
class TranslationEntry {
public:
enum Type {VALID = 0b1, READ_ONLY = 0b10, USE = 0b100, DIRTY = 0b1000};
// start of "mainMemory"
TranslationEntry(unsigned int vpage = 0, unsigned int ppage = 0):
mFlag(0), mVirtualPage(vpage), mPhysicalPage(ppage) {}
inline bool valid() const { return mFlag & VALID; } // If this bit is set, the translation is ignored.
// (In other words, the entry hasn't been initialized.)
inline bool readOnly() const { return mFlag & READ_ONLY; } // If this bit is set, the user program is not allowed
// to modify the contents of the page.
inline bool use() const { return mFlag & USE; }// This bit is set by the hardware every time the
// page is referenced or modified.
inline bool dirty() const { return mFlag & DIRTY; }// This bit is set by the hardware every time the
// page is modified.
inline void valid(bool v) {
mFlag = (v ? mFlag | VALID : mFlag & ~VALID);
}
inline void setValid() { valid(true); }
inline void clearValid() { valid(false); }
inline void readOnly(bool v) {
mFlag = (v ? mFlag | READ_ONLY : mFlag & ~READ_ONLY);
}
inline void setReadOnly() { readOnly(true); }
inline void clearReadOnly() { readOnly(false); }
inline void use(bool v) {
mFlag = (v ? mFlag | USE : mFlag & ~USE);
}
inline void setUse() { use(true); }
inline void clearUse() { use(false); }
inline void dirty(bool v) {
mFlag = (v ? mFlag | DIRTY : mFlag & ~DIRTY);
}
inline void setDirty() { dirty(true); }
inline void clearDirty() { dirty(false); }
inline void virtualPage(unsigned int p) {
mVirtualPage = p;
}
inline void physicalPage(unsigned int p) {
mPhysicalPage = p;
}
inline unsigned int virtualPage() {
return mVirtualPage;
}
inline unsigned int physicalPage() {
return mPhysicalPage;
}
protected:
char mFlag;
unsigned int mVirtualPage; // The page number in virtual memory.
unsigned int mPhysicalPage; // The page number in real memory (relative to the
};
#endif
| true |
c9667d73dc841c6d38c14bd4a7fa3306f23d83be | C++ | Smeany/ADS | /Aufgabe 4.1/Graph.h | UTF-8 | 1,058 | 2.53125 | 3 | [] | no_license | #ifndef _GRAPH_H
#define _GRAPH_H
#include <string>
#include <iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<deque>
#include<queue>
#include<set>
#include<algorithm>
#include"GraphNode.h"
using namespace std;
class Graph
{
public:
Graph();
Graph(int numberNodes);
void init(string fname, bool direc);
~Graph();
struct teilGraph {
int parent;
int rank;
};
void resetVisited();
void resetConsidered();
int numNodes;
bool weighted;
bool directed;
vector<GraphNode*> nodes;
bool breadthSearch();
bool depthSearch(int key);
void depthSearchRekursion( GraphNode * node);
double prim(int key);
int kleinsterKey(int * keys, bool * nodesStillToDo);
double kruskal();
int find(vector<teilGraph> &teilGraphen, int i);
void makeUnion(vector<teilGraph> &teilGraphen, int x, int y);
void print();
void clear();
GraphNode * returnNodeWithKey(int key);
static bool compareByWeight(GraphNode::edge a, GraphNode::edge b)
{
return a.weight < b.weight;
}
private:
};
#endif | true |
581481b82ac2b97f0eef89897bc3b68ba45f9fcc | C++ | RickyL-2000/Algorithm | /leetcode/easy/countCharacters3.cpp | UTF-8 | 2,245 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
bool check;
int sum = 0;
for (string& str : words) {
check = 1;
vector<int> hmc(26, 0);
for (auto c : chars) {
hmc[c - 'a']++;
}
for (auto c : str) {
if (hmc[c - 'a'] <= 0) {
check = 0;
break;
}
hmc[c - 'a']--;
}
if (check) {
sum += str.length();
}
}
return sum;
}
void test() {
vector<string> words1 = {"dyiclysmffuhibgfvapygkorkqllqlvokosagyelotobicwcmebnpznjbirzrzsrtzjxhsfpiwyfhzyonmuabtlwin",
"ndqeyhhcquplmznwslewjzuyfgklssvkqxmqjpwhrshycmvrb",
"ulrrbpspyudncdlbkxkrqpivfftrggemkpyjl",
"boygirdlggnh",
"xmqohbyqwagkjzpyawsydmdaattthmuvjbzwpyopyafphx",
"nulvimegcsiwvhwuiyednoxpugfeimnnyeoczuzxgxbqjvegcxeqnjbwnbvowastqhojepisusvsidhqmszbrnynkyop",
"hiefuovybkpgzygprmndrkyspoiyapdwkxebgsmodhzpx",
"juldqdzeskpffaoqcyyxiqqowsalqumddcufhouhrskozhlmobiwzxnhdkidr",
"lnnvsdcrvzfmrvurucrzlfyigcycffpiuoo",
"oxgaskztzroxuntiwlfyufddl",
"tfspedteabxatkaypitjfkhkkigdwdkctqbczcugripkgcyfezpuklfqfcsccboarbfbjfrkxp",
"qnagrpfzlyrouolqquytwnwnsqnmuzphne",
"eeilfdaookieawrrbvtnqfzcricvhpiv",
"sisvsjzyrbdsjcwwygdnxcjhzhsxhpceqz",
"yhouqhjevqxtecomahbwoptzlkyvjexhzcbccusbjjdgcfzlkoqwiwue",
"hwxxighzvceaplsycajkhynkhzkwkouszwaiuzqcleyflqrxgjsvlegvupzqijbornbfwpefhxekgpuvgiyeudhncv",
"cpwcjwgbcquirnsazumgjjcltitmeyfaudbnbqhflvecjsupjmgwfbjo",
"teyygdmmyadppuopvqdodaczob",
"qaeowuwqsqffvibrtxnjnzvzuuonrkwpysyxvkijemmpdmtnqxwekbpfzs",
"qqxpxpmemkldghbmbyxpkwgkaykaerhmwwjonrhcsubchs"};
string chars = "usdruypficfbpfbivlrhutcgvyjenlxzeovdyjtgvvfdjzcmikjraspdfp";
vector<string> words2 = {"boygirdlggnh"};
vector<string> words3 = {"lnnvsdcrvzfmrvurucrzlfyigcycffpiuoo"};
int ans = countCharacters(words1, chars);
cout << ans << endl;
}
};
int main() {
Solution s;
s.test();
return 0;
} | true |
c36aba85d3f4bfbf85ee4afbcd170436126d4ed1 | C++ | ZeddYu/CryptoCourseExperiment | /course5/sha1.cpp | UTF-8 | 2,977 | 3.171875 | 3 | [] | no_license | //
// Created by Zedd on 2019/1/8.
//
#include "sha1.h"
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
vector<int> X; // 8*64=512,每个下标存放8位
int W[80]; //32位为一组
int A, B, C, D, E;
int A1, B1, C1, D1, E1;//缓冲区寄存器,产生最后结果
int Turn;//加密分组数量N
using namespace std;
/**
* 循环左移
* @param x 待循环数
* @param n 移动位数
* @return 循环结果
*/
int LeftShift(unsigned int x, int n){
return x >> (32 - n) | (x << n);
}
void printX() {//输出填充后的文本
for (int i = 0; i < X.size(); i++) {
printf("%02x", X[i]);
if ((i + 1) % 4 == 0)
printf(" ");
if ((i + 1) % 16 == 0)
printf("\n");
}
}
/**
* 产生M数组
* 文本的填充处理
*/
void append(string m){
Turn = m.size() / 64 + 1;
X.resize(Turn * 64);
//原文直接赋值
int i = 0;
for (; i < m.size(); i++){
X[i] = m[i];
}
//填充1
X[i++] = 0x80;
while (i < X.size() - 8){
X[i] = 0;
i++;
}
//最后 64位表示 m的长度
long long int a = m.size() * 8;
for (i = X.size() - 1; i >= X.size() - 8; i--) {
X[i] = a % 256;
a /= 256;
}
}
/**
* X数组的生成
*
*/
void setW(vector<int> m, int n){
//16 * 4
n *= 64;
for (int j = 0; j < 16; j++) {
W[j] = (m[n + 4 * j] << 24) + (m[n + 4 * j + 1] << 16) + (m[n + 4 * j + 2] << 8) + m[n + 4 * j + 3];
}
for (int j = 16; j < 80; j++) {
W[j] = LeftShift(W[j - 16] ^ W[j - 14] ^ W[j - 8] ^ W[j - 3], 1);
}
}
/**
* fi函数
* @param t 次数
*/
int ft(int t) {
//f1
if (t < 20)
return (B & C) | ((~B) & D);
//f2
else if (t < 40)
return B ^ C ^ D;
//f3
else if (t < 60)
return (B & C) | (B & D) | (C & D);
//f4
else
return B ^ C ^ D;
}
/**
* 返回Ki常数
* @param t 次数
* @return Ki常数
*/
int Kt(int t) {
if (t < 20)
return 0x5a827999;
else if (t < 40)
return 0x6ed9eba1;
else if (t < 60)
return 0x8f1bbcdc;
else
return 0xca62c1d6;
}
/**
* sha1算法接口
* @param t 次数
* @param ch 字符数组
*/
void sha1(string text, char *ch) {
A1 = A = 0x67452301;
B1 = B = 0xefcdab89;
C1 = C = 0x98badcfe;
D1 = D = 0x10325476;
E1 = E = 0xc3d2e1f0;
append(text);
for (int i = 0; i < Turn; i++) {
setW(X, i);
for (int t = 0; t < 80; t++) {
int temp = E + ft(t) + LeftShift(A, 5) + W[t] + Kt(t);
E = D;
D = C;
C = LeftShift(B, 30);
B = A;
A = temp;
}
A1 = A = A + A1;
B1 = B = B + B1;
C1 = C = C + C1;
D1 = D = D + D1;
E1 = E = E + E1;
}
printf("The sha1 result of msg is: %x%x%x%x%x\n", A1, B1, C1, D1, E1);
sprintf(ch,"%x%x%x%x%x", A1, B1, C1, D1, E1);
} | true |
ddd42899415412c2be06a7fae8ac90085353aabf | C++ | cwmagnus/bsf | /Source/Foundation/bsfEngine/GUI/BsGUIPanel.h | UTF-8 | 5,695 | 2.640625 | 3 | [
"MIT"
] | permissive | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "BsPrerequisites.h"
#include "GUI/BsGUILayout.h"
namespace bs
{
/** @addtogroup GUI
* @{
*/
/** Represents a GUI panel that you can use for free placement of GUI elements within its bounds. */
class BS_EXPORT GUIPanel final : public GUILayout
{
public:
GUIPanel() = default;
GUIPanel(INT16 depth, UINT16 depthRangeMin, UINT16 depthRangeMax, const GUIDimensions& dimensions);
~GUIPanel() = default;
/**
* Changes values that control at which depth is GUI panel and its children rendered.
*
* @param[in] depth Determines rendering order of the GUI panel. Panels with lower depth will be
* rendered in front of panels with higher depth. Provided depth is relative to depth
* of the parent GUI panel (if any).
* @param[in] depthRangeMin Minimum range of depths that children of this GUI panel can have. If any panel has
* depth outside of the range [depth - depthRangeMin, depth + depthRangeMax] it will
* be clamped to nearest extreme. Value of -1 means infinite range.
* @param[in] depthRangeMax Maximum range of depths that children of this GUI panel can have. If any panel has
* depth outside of the range [depth - depthRangeMin, depth + depthRangeMax] it will
* be clamped to nearest extreme. Value of -1 means infinite range.
*/
void setDepthRange(INT16 depth = 0, UINT16 depthRangeMin = -1, UINT16 depthRangeMax = -1);
/**
* Creates a new GUI panel.
*
* @param[in] depth Determines rendering order of the GUI panel. Panels with lower depth will be
* rendered in front of panels with higher depth. Provided depth is relative to depth
* of the parent GUI panel (if any).
* @param[in] depthRangeMin Minimum range of depths that children of this GUI panel can have. If any panel has
* depth outside of the range [depth - depthRangeMin, depth + depthRangeMax] it will
* be clamped to nearest extreme. Value of -1 means infinite range.
* @param[in] depthRangeMax Maximum range of depths that children of this GUI panel can have. If any panel has
* depth outside of the range [depth - depthRangeMin, depth + depthRangeMax] it will
* be clamped to nearest extreme. Value of -1 means infinite range.
*/
static GUIPanel* create(INT16 depth = 0, UINT16 depthRangeMin = -1, UINT16 depthRangeMax = -1);
/**
* Creates a new GUI panel.
*
* @param[in] options Options that allow you to control how is the element positioned and sized.
*/
static GUIPanel* create(const GUIOptions& options);
/**
* Creates a new GUI panel.
*
* @param[in] depth Determines rendering order of the GUI panel. Panels with lower depth will be
* rendered in front of panels with higher depth. Provided depth is relative to depth
* of the parent GUI panel (if any).
* @param[in] depthRangeMin Minimum range of depths that children of this GUI panel can have. If any panel has
* depth outside of the range [depth - depthRangeMin, depth + depthRangeMax] it will be
* clamped to nearest extreme. Value of -1 means infinite range.
* @param[in] depthRangeMax Maximum range of depths that children of this GUI panel can have. If any panel has
* depth outside of the range [depth - depthRangeMin, depth + depthRangeMax] it will be
* clamped to nearest extreme. Value of -1 means infinite range.
* @param[in] options Options that allow you to control how is the element positioned and sized.
*/
static GUIPanel* create(INT16 depth, UINT16 depthRangeMin, UINT16 depthRangeMax, const GUIOptions& options);
public: // ***** INTERNAL ******
/** @name Internal
* @{
*/
/** @copydoc GUIElementBase::_getType */
Type _getType() const override { return GUIElementBase::Type::Panel; }
/** Calculate optimal sizes of all child layout elements. */
void _updateOptimalLayoutSizes() override;
/** @copydoc GUIElementBase::_calculateLayoutSizeRange */
LayoutSizeRange _calculateLayoutSizeRange() const override;
/** @copydoc GUILayout::_getElementAreas */
void _getElementAreas(const Rect2I& layoutArea, Rect2I* elementAreas, UINT32 numElements,
const Vector<LayoutSizeRange>& sizeRanges, const LayoutSizeRange& mySizeRange) const override;
/** Calculates the size of the provided child within this layout with the provided dimensions. */
Rect2I _getElementArea(const Rect2I& layoutArea, const GUIElementBase* element, const LayoutSizeRange& sizeRange) const;
/**
* Calculates an element size range for the provided child of the GUI panel. Will return cached bounds so make sure
* to update optimal size ranges before calling.
*/
LayoutSizeRange _getElementSizeRange(const GUIElementBase* element) const;
/** Assigns the specified layout information to a child element of a GUI panel. */
void _updateChildLayout(GUIElementBase* element, const GUILayoutData& data);
/** @copydoc GUIElementBase::_updateLayoutInternal */
void _updateLayoutInternal(const GUILayoutData& data) override;
/**
* Updates the provided depth range by taking into consideration the depth range of the panel. This depth range
* should be passed on to child elements of the panel.
*/
void _updateDepthRange(GUILayoutData& data);
/** @} */
protected:
INT16 mDepthOffset;
UINT16 mDepthRangeMin;
UINT16 mDepthRangeMax;
};
/** @} */
}
| true |
e8de431dc1c73a5cde2dbda178831d6592cfa08c | C++ | tom-cb/old-dev | /cplus/sedgewick/List.cpp | UTF-8 | 1,304 | 3.234375 | 3 | [] | no_license | #include "List.h"
#include "Node.h"
#include <stdlib.h>
#include <iostream>
/*
LinkNode List::newNode(int i)
{
LinkNode x = deleteNext(freeList);
x->data = i;
x->next = x;
return x;
}
*/
List::List(LinkNode iHead)
{
head = iHead;
head->next = NULL;
}
void List::traverse(LinkNode x, void (*visit)(LinkNode))
{
}
int List::count(LinkNode x)
{
if (x == NULL)
return 0;
else
return 1 + count(x->next);
}
void List::insertNext(LinkNode x, LinkNode t)
{
if ( x == NULL)
{
head = t;
head->next = NULL;
}
else
{
t->next = x->next;
x->next = t;
}
}
LinkNode List::deleteNext(LinkNode x)
{
LinkNode t = x->next;
x->next = t->next;
return t;
}
void List::sortNSqrd(List* iList, List* oList)
{
LinkNode t;
LinkNode u;
LinkNode x;
LinkNode b;
b = oList->head;
for (t = iList->head; t != NULL; t = u)
{
u = t->next;
std::cout << "t data: " << t->data << "\n";
for (x = b; x->next != NULL; x=x->next)
{
std::cout << "x data: "<< x->data << "\n";
if (x->next->data > t->data)
{
std::cout << "break\n";
break;
}
}
t->next = x->next;
x->next = t;
}
}
LinkNode List::getNext(LinkNode x)
{
return x->next;
}
int List::getData(LinkNode x)
{
return x->data;
}
| true |
d5b453a1c091d38b2b4d37f2ecef890bb0e74a88 | C++ | LTLattig/CS273HW5and6 | /HW6/HW6/Customer.h | UTF-8 | 3,835 | 3.484375 | 3 | [] | no_license | #pragma once
#ifndef CUSTOMER_H_
#define CUSTOMER_H_
#include <string>
using std::string;
/**
The Bank has Customers. Each Customer has a name, address, age, and telephone number.
Additionally, there are specialized types of Customers: Adult, Senior, and Student.
Each type of Customer has its own checking and savings interest rates,
as well as its own checking and overdraft fees.
@author: Ed Walker
*/
class Customer // FIXME: Complete the implementation!
{
protected:
string name;
string address;
unsigned int age;
string teleNumber;
unsigned int custID;
double savings_interest;
double check_interest;
double check_charge;
int overdarft_penalty;
public:
// /////////////////CONSTRUCTOR(S)////////////////// //
Customer(string _name, string _address, unsigned int _age, string _teleNumber, unsigned int _custID)
{
name = _name;
address = _address;
age = _age;
teleNumber = _teleNumber;
custID = _custID;
}
// //////////////////////////////////////////////// //
// /////////////////ACCESSOR FXNS ////////////////// //
const string get_name() { return name; }
const string get_address() { return address; }
const unsigned int get_age() { return age; }
const string get_tele() { return teleNumber; }
const unsigned int get_id() { return custID; }
// ///////////////////////////////////////////////// //
// /////////////////MUTATOR FXNS//////////////////// //
void ch_name(string nName) { name = nName; }
void ch_address(string nAddress) { address = nAddress; }
void ch_age(unsigned int nAge) { age = nAge; }
void ch_tele(unsigned int nTele) { teleNumber = nTele; }
void ch_id(unsigned int nID) { custID = nID; }
// ///////////////////////////////////////////////// //
// /////////////////VIRTUAL FXNS//////////////////// //
virtual const double get_sinterest() = 0;
virtual const double get_cinterest() = 0;
virtual const double get_ccharge() = 0;
virtual const int get_penalty() = 0;
// ///////////////////////////////////////////////// //
};
// Adult Account Type
class Adult : public Customer
{
public:
Adult(string _name, string _address, unsigned int _age, string _teleNumber, unsigned int _custID)
:
Customer(_name, _address, _age, _teleNumber, _custID)
{
savings_interest = .02;
check_interest = 0.002;
check_charge = 3;
overdarft_penalty = 15;
}
const double get_sinterest() { return savings_interest; }
const double get_cinterest() { return check_interest; }
const double get_ccharge() { return check_charge; }
const int get_penalty() { return overdarft_penalty; }
};
// End Type
//--------------------------------------------------//
// Senior Account Type
class Senior : public Customer
{
public:
Senior(string _name, string _address, unsigned int _age, string _teleNumber, unsigned int _custID)
:
Customer(_name, _address, _age, _teleNumber, _custID)
{
savings_interest = .04;
check_interest = 0.004;
check_charge = 1;
overdarft_penalty = 8;
}
const double get_sinterest() { return savings_interest; }
const double get_cinterest() { return check_interest; }
const double get_ccharge() { return check_charge; }
const int get_penalty() { return overdarft_penalty; }
};
// End Type
//--------------------------------------------------------//
// Student Account Type
class Student : public Customer
{
public:
Student(string _name, string _address, unsigned int _age, string _teleNumber, unsigned int _custID)
:
Customer(_name, _address, _age, _teleNumber, _custID)
{
savings_interest = .03;
check_interest = 0.005;
check_charge = 2;
overdarft_penalty = 10;
}
const double get_sinterest() { return savings_interest; }
const double get_cinterest() { return check_interest; }
const double get_ccharge() { return check_charge; }
const int get_penalty() { return overdarft_penalty; }
};
// End Type
#endif | true |
d3a5db845d322bc86c6585cba103271336a0ab2a | C++ | GraphicsDreamTeam/CGFinalProject | /src/librt/Camera.cpp | UTF-8 | 3,421 | 3.078125 | 3 | [
"MIT"
] | permissive | //------------------------------------------------------------------------------
// Copyright 2015 Corey Toler-Franklin, University of Florida
// Camera.cpp
// Camera Object - position, up and lookat
//------------------------------------------------------------------------------
#include "Camera.h"
#include <assert.h>
#include <stdio.h>
#include <string>
#include "STMatrix4.h"
#include "STVector3.h"
Camera::Camera(STVector3 lookat, STVector3 position, STVector3 up)
{
SetLookAt(lookat);
SetPosition(position);
SetUp(up);
SetFov(90);
}
Camera::~Camera()
{
}
// set the up and right vectors
void Camera::SetUpAndRight(void)
{
m_Right = STVector3::Cross(m_LookAt - m_Position, m_Up);
m_Right.Normalize();
m_Up = STVector3::Cross(m_Right, m_LookAt - m_Position);
m_Up.Normalize();
}
// reset the camera position
void Camera::Reset(void)
{
m_Position = STVector3(0.f, 0.f, 1.f);
m_LookAt = STVector3(0.f,0.f,0.f);
m_Up = STVector3(0.f,1.f,-1.f);
m_Up.Normalize();
SetUpAndRight();
}
void Camera::SetFov(int newFov) {
fov = newFov;
}
int Camera::GetFov(void) {
return fov;
}
// reset the camera up vector
void Camera::ResetUp(void)
{
m_Up = STVector3(5.f,5.f,0.f);
m_Right = STVector3::Cross(m_LookAt - m_Position, m_Up);
m_Right.Normalize();
m_Up = STVector3::Cross(m_Right, m_LookAt - m_Position);
m_Up.Normalize();
}
//
// Rotate the camera
void Camera::Rotate(float delta_x, float delta_y)
{
float yaw_rate=1.f;
float pitch_rate=1.f;
m_Position -= m_LookAt;
STMatrix4 m;
m.EncodeR(-1*delta_x*yaw_rate, m_Up);
m_Position = m * m_Position;
m.EncodeR(-1*delta_y*pitch_rate, m_Right);
m_Position = m * m_Position;
m_Position += m_LookAt;
}
//
// This controlls camera zoom
//
void Camera::Zoom(float delta_y)
{
STVector3 direction = m_LookAt - m_Position;
float magnitude = direction.Length();
direction.Normalize();
float zoom_rate = 0.1f*magnitude < 0.5f ? .1f*magnitude : .5f;
if(delta_y * zoom_rate + magnitude > 0)
{
m_Position += (delta_y * zoom_rate) * direction;
}
}
//
// This moves the camera left and right
//
void Camera::Strafe(float delta_x, float delta_y)
{
float strafe_rate = 0.05f;
m_Position -= strafe_rate * delta_x * m_Right;
m_LookAt -= strafe_rate * delta_x * m_Right;
m_Position += strafe_rate * delta_y * m_Up;
m_LookAt += strafe_rate * delta_y * m_Up;
}
// This is the 3D position of the camera in space
//
STVector3 Camera::Position (void)
{
return(m_Position);
}
// set the look at vector w
// the viewing direction is -w
STVector3 Camera::LookAt (void)
{
return(m_LookAt);
}
// sets the up vector v
STVector3 Camera::Up (void)
{
return(m_Up);
}
STVector3 Camera::Right(void) {
return (m_Right);
}
STVector3 Camera::SetPosition(float x, float y, float z) { SetPosition(STVector3(x,y,z)); }
STVector3 Camera::SetPosition(STVector3 newPos) {
m_Position.x = newPos.x;
m_Position.y = newPos.y;
m_Position.z = newPos.z;
SetUpAndRight();
}
STVector3 Camera::SetLookAt(float x, float y, float z) { SetLookAt(STVector3(x, y, z)); }
STVector3 Camera::SetLookAt(STVector3 newLookAt) {
m_LookAt.x = newLookAt.x;
m_LookAt.y = newLookAt.y;
m_LookAt.z = newLookAt.z;
SetUpAndRight();
}
void Camera::SetUp(STVector3 newUp) {
m_Up = newUp;
SetUpAndRight();
} | true |
6543fb215728d926879f051e3c63c1766552f4f9 | C++ | savitarai/util | /log.h | UTF-8 | 2,633 | 2.71875 | 3 | [] | no_license | /**
* @file log.h
* @brief 日志输出接口
* @version 1.0
* @date 01/17/2019 11:43:37 AM
* @author tashanji (jitashan), jitashan@gmail.com
*/
#ifndef _UTIL_LOG_H_
#define _UTIL_LOG_H_
#include <string>
#include <iostream>
#include <log4cpp/Category.hh>
#include <log4cpp/PropertyConfigurator.hh>
#include <log4cpp/OstreamAppender.hh>
#include <boost/serialization/singleton.hpp>
namespace savitar{
namespace util{
class Log:public boost::serialization::singleton<Log>
{
public:
Log():init_(false),pcategory_(NULL)
{
}
/**
* @brief 初始化日志
**/
bool Init(const std::string conffile, const std::string category);
/**
* @brief 返回log4cpp的category
**/
log4cpp::Category & Category();
private:
bool init_;
log4cpp::Category * pcategory_;
};//class Log
}//namespace util
}//savitar
//初始化日志
#define LOG_INIT(conffile, category) savitar::util::Log::get_mutable_instance().Init(conffile, category)
//打印日志的宏
//因为log4cpp不支持打印行号、文件名等信息,这里用宏实现
//注意,LOG_XXXX(fmt, ...)这里的fmt不能是变量,必须是字符串,
//因为变量不支持默认连接操作,
//所以如果
//char * str="I am a str";
//LOG_DEBUG(str); //error, because debug("%d in %s"str);编译不过去
//解决办法==>LOG_DEBUG("I am a str") or LOG_DEBUG("%s", str)
//
//注意:不直接调用debug&info,主要是因为函数调用的参数在调用前就会被执行,DEBUG的日志可能会比较多,影响线上执行的性能
//如 debug("%d", busy_func()); 虽然最后可能没有打印任何东西,但busy_func()都会被执行,用下面宏则不然。
#define LOG_DEBUG(fmt, a...) do{\
auto &cate= savitar::util::Log::get_mutable_instance().Category();\
if(cate.isDebugEnabled())\
{\
cate.debug("[%d in %s]" fmt, __LINE__, __FILE__, ##a);\
}\
}while(0)
#define LOG_INFO(fmt, a...) savitar::util::Log::get_mutable_instance().Category().info("[%d in %s]" fmt, __LINE__, __FILE__, ##a)
#define LOG_NOTICE(fmt, a...) savitar::util::Log::get_mutable_instance().Category().notice("[%d in %s]" fmt, __LINE__, __FILE__, ##a)
#define LOG_WARN(fmt, a...) savitar::util::Log::get_mutable_instance().Category().warn("[%d in %s]" fmt, __LINE__, __FILE__, ##a)
#define LOG_ERROR(fmt, a...) savitar::util::Log::get_mutable_instance().Category().error("[%d in %s]" fmt, __LINE__, __FILE__, ##a)
#define LOG_FATAL(fmt, a...) savitar::util::Log::get_mutable_instance().Category().fatal("[%d in %s]" fmt, __LINE__, __FILE__, ##a)
#endif // _UTIL_LOG_H_
| true |
2ea3f63ef93a20653e142e251ca658a855e904ff | C++ | epics-base/pvDataCPP | /src/misc/pv/thread.h | UTF-8 | 5,505 | 2.71875 | 3 | [
"MIT"
] | permissive | /* thread.h */
/*
* Copyright information and license terms for this software can be
* found in the file LICENSE that is included with the distribution
*/
/**
* @author mrk
*/
#ifndef THREAD_H
#define THREAD_H
#include <memory>
#include <sstream>
#include <stdexcept>
#if __cplusplus>=201103L
#include <functional>
#endif
#include <epicsThread.h>
#include <shareLib.h>
#include <pv/noDefaultMethods.h>
#include <pv/pvType.h>
namespace epics { namespace pvData {
enum ThreadPriority {
lowestPriority =epicsThreadPriorityLow,
lowerPriority =epicsThreadPriorityLow + 15,
lowPriority =epicsThreadPriorityMedium - 15,
middlePriority =epicsThreadPriorityMedium,
highPriority =epicsThreadPriorityMedium + 15,
higherPriority =epicsThreadPriorityHigh - 15,
highestPriority =epicsThreadPriorityHigh
};
class Thread;
typedef std::tr1::shared_ptr<Thread> ThreadPtr;
typedef std::tr1::shared_ptr<epicsThread> EpicsThreadPtr;
typedef epicsThreadRunable Runnable;
namespace detail {
template<typename C>
struct MethRunner : public epicsThreadRunable
{
typedef void(C::*fn_t)();
fn_t fn;
C* inst;
MethRunner(C* i, fn_t f) :fn(f), inst(i) {}
virtual ~MethRunner() {}
virtual void run()
{
(inst->*fn)();
}
};
} // namespace detail
/**
* @brief C++ wrapper for epicsThread from EPICS base.
*
*/
class epicsShareClass Thread : public epicsThread {
EPICS_NOT_COPYABLE(Thread)
public:
/** @brief Holds all the configuration necessary to launch a @class Thread
*
* The defaults may be used except for the runnable, which must be given
* either in the constructor, or the @method run() method.
*
* @note Instances of @class Config may not be reused.
*
* Defaults:
* name: ""
* priority: epicsThreadPriorityLow (aka epics::pvData::lowestPriority)
* stack size: epicsThreadStackSmall
* auto start: true
* runner: nil (must be set explictly)
*
@code
stuct bar { void meth(); ... } X;
// with a static thread name
Thread foo(Thread::Config(&X, &bar::meth)
.name("example")
.prio(epicsThreadPriorityHigh));
// with a constructed thread name
Thread foo(Thread::Config(&X, &bar::meth)
.prio(epicsThreadPriorityHigh)
<<"example"<<1);
@endcode
*/
class epicsShareClass Config
{
unsigned int p_prio, p_stack;
std::ostringstream p_strm;
bool p_autostart;
Runnable *p_runner;
typedef epics::auto_ptr<Runnable> p_owned_runner_t;
p_owned_runner_t p_owned_runner;
friend class Thread;
Runnable& x_getrunner();
void x_setdefault();
public:
Config();
Config(Runnable *r);
Config(void(*fn)(void*), void *ptr);
template<typename C>
Config(C* inst, void(C::*meth)()) {this->x_setdefault();this->run(inst, meth);}
#if __cplusplus>=201103L
Config(std::function<void()>&& fn);
#endif
Config& name(const std::string& n);
Config& prio(unsigned int p);
Config& stack(epicsThreadStackSizeClass s);
Config& autostart(bool a);
//! Thread will execute Runnable::run()
Config& run(Runnable* r);
//! Thread will execute (*fn)(ptr)
Config& run(void(*fn)(void*), void *ptr);
//! Thread will execute (inst->*meth)()
template<typename C>
Config& run(C* inst, void(C::*meth)())
{
this->p_owned_runner.reset(new detail::MethRunner<C>(inst, meth));
this->p_runner = this->p_owned_runner.get();
return *this;
}
#if __cplusplus>=201103L
Config& run(std::function<void()>&& fn);
#endif
//! Append to thread name string. Argument must be understood by std::ostream::operator<<
template<typename T>
Config& operator<<(T x) { this->p_strm<<x; return *this; }
};
/**
*
* Constructor
* @param name thread name.
* @param priority priority is one of:
@code
enum ThreadPriority {
lowestPriority, lowerPriority, lowPriority,
middlePriority,
highPriority, higherPriority, highestPriority
};
@endcode
* @param runnable this is a c function
* @param stkcls stack size as specified by epicsThreadStackSizeClass
*/
Thread(std::string name,
ThreadPriority priority,
Runnable *runnable,
epicsThreadStackSizeClass stkcls=epicsThreadStackBig);
/**
*
* Constructor
* @param runnable this is a c function
* @name thread name.
* @param stkcls stack size as specified by epicsThreadStackSizeClass
* @param priority priority is one of:
@code
enum ThreadPriority {
lowestPriority, lowerPriority, lowPriority,
middlePriority,
highPriority, higherPriority, highestPriority
};
@endcode
*/
Thread(Runnable &runnable,
std::string name,
unsigned int stksize,
unsigned int priority=lowestPriority);
//! @brief Create a new thread using the given @class Config
//! @throws std::logic_error for improper @class Config (ie. missing runner)
Thread(Config& c);
/**
* Destructor
*/
~Thread();
static size_t num_instances;
private:
Config::p_owned_runner_t p_owned;
};
}}
#endif /* THREAD_H */
| true |
67e9096b4daec1811e5170f6b95d47fc55a2bc9f | C++ | tistatos/TNCG15-ray-tracer | /include/triangle.h | UTF-8 | 501 | 2.65625 | 3 | [] | no_license | /**
* @file triangle.h
* @author Erik Sandrén
* @date 31-08-2016
* @brief [Description Goes Here]
*/
#ifndef __TRIANGLE_H__
#define __TRIANGLE_H__
#include <glm/glm.hpp>
#include "ray.h"
#include "color.h"
#include "intersectable.h"
class Triangle : public Intersectable {
public:
Triangle();
~Triangle();
Triangle(glm::vec3 v0, glm::vec3 v1, glm::vec3 v2);
bool rayIntersection(Ray* r, float &tOut);
glm::vec3 getPoint(float u, float v, glm::vec3 from);
glm::vec3 mV0, mV1, mV2;
};
#endif
| true |
3d81c84e65483d66183bc6a88247cf5a11221c3b | C++ | playbar/glespainting | /app/src/main/cpp/draw/myjni.cpp | UTF-8 | 3,905 | 2.546875 | 3 | [] | no_license |
#include <jni.h>
#include <stdlib.h>
#include "painter.h"
#include "mylog.h"
extern "C" {
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_exit(JNIEnv* env, jobject obj);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_init(
JNIEnv* env, jobject obj,
jint canvasWidth, jint canvasHeight,
jint viewportWidth, jint viewportHeight);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_setTexture(JNIEnv * env, jobject obj,
jint id, jint width, jint height, jintArray pixels);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_drawBlankCanvas(JNIEnv* env, jobject obj,
jfloat r, jfloat g, jfloat b);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_pan(JNIEnv* env, jobject obj,
jfloat x0, jfloat y0, jfloat x1, jfloat y1);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_zoom(JNIEnv* env, jobject obj,
jfloat scale, jfloat cx, jfloat cy);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_resize(
JNIEnv* env, jobject obj,
jint width, jint height);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_changeCanvas(
JNIEnv* env, jobject obj,
jint width, jint height, jint color);
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_drawNormalLine(JNIEnv* env, jobject obj,
jint action, jfloat x, jfloat y, jfloat width, jint color, jint textureID);
JNIEXPORT jfloatArray JNICALL
Java_com_haowan_openglnew_JNILib_getCanvasCoord(JNIEnv* env, jobject obj,
jfloat x, jfloat y);
};
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_init(
JNIEnv* env, jobject obj,
jint canvasWidth, jint canvasHeight,
jint viewportWidth, jint viewportHeight)
{
mh_init(canvasWidth, canvasHeight,
viewportWidth, viewportHeight);
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_exit(JNIEnv* env, jobject obj) {
mh_exit();
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_setTexture(JNIEnv * env, jobject obj,
jint id, jint width, jint height, jintArray pixels)
{
int size = env->GetArrayLength(pixels);
jint *pdat = (jint*)malloc(sizeof(jint)*size);
env->GetIntArrayRegion(pixels, 0, size, pdat);
mh_setTexture(id, width, height, (unsigned char*)pdat);
free(pdat);
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_drawBlankCanvas(JNIEnv* env, jobject obj,
jfloat r, jfloat g, jfloat b){
mh_drawBlankCanvas(r,g,b);
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_resize(
JNIEnv* env, jobject obj,
jint width, jint height)
{
mh_resize(width,height);
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_changeCanvas(
JNIEnv* env, jobject obj,
jint width, jint height, jint color)
{
mh_changeCanvas(width,height,color);
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_pan(JNIEnv* env, jobject obj,
jfloat x0, jfloat y0, jfloat x1, jfloat y1)
{
mh_pan(x0,y0,x1,y1);
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_zoom(JNIEnv* env, jobject obj,
jfloat scale, jfloat cx, jfloat cy)
{
mh_zoom(scale,cx,cy);
}
JNIEXPORT void JNICALL
Java_com_haowan_openglnew_JNILib_drawNormalLine(JNIEnv* env, jobject obj,
jint action, jfloat x, jfloat y, jfloat width, jint color, jint textureID)
{
LOGE("Fun:%s", __FUNCTION__);
mh_drawNormalLine(action, x, y, width, color, textureID);
}
JNIEXPORT jfloatArray JNICALL
Java_com_haowan_openglnew_JNILib_getCanvasCoord(JNIEnv* env, jobject obj,
jfloat x, jfloat y){
jfloat outCArray[] = {0.0f, 0.0f};
Vec3 pt = mh_getCanvasCoord(x,y);
outCArray[0] = pt.x; outCArray[1] = pt.y;
jfloatArray outJNIArray = env->NewFloatArray(2); // allocate
if (NULL == outJNIArray) return NULL;
env->SetFloatArrayRegion(outJNIArray, 0 , 2, outCArray); // copy
return outJNIArray;
}
| true |
09138eb5e2380cdfea0a30e32707204a858246ae | C++ | moohoorama/moohoorama | /include/ywq.h | UTF-8 | 4,112 | 2.875 | 3 | [] | no_license | /* Copyright [2014] moohoorama@gmail.com Kim.Youn-woo */
#ifndef INCLUDE_YWQ_H_
#define INCLUDE_YWQ_H_
#include <ywcommon.h>
#include <ywspinlock.h>
#include <ywutil.h>
template<typename DATA>
class ywQueue {
public:
ywQueue():next(this) {
}
ywQueue * next;
DATA data;
};
template<typename DATA, bool sync = true>
class ywQueueHead {
public:
ywQueueHead():head(&head_instance) {
init();
}
void init() {
head->next = head;
tail = head;
}
ywQueue<DATA> *get_head() {
return head;
}
template<typename T>
bool cas(T *ptr, T prev, T next) {
if (sync)
return __sync_bool_compare_and_swap(ptr, prev, next);
*ptr = next;
return true;
}
template<typename T>
T *make_circle(T *ptr) {
T * old_next = ptr->next;
if (ptr == tail) {
cas(&tail, tail, tail->next);
return NULL;
}
if (old_next != ptr) {
if (cas(&ptr->next, old_next, ptr)) {
if (ptr == tail) {
cas(&tail, tail, tail->next);
}
return old_next;
}
}
return NULL;
}
void synchronize() {
if (sync)
__sync_synchronize();
}
void push(ywQueue<DATA> *node) {
ywQueue<DATA> *cur_tail;
int32_t retry = 0;
do {
while (true) {
synchronize();
cur_tail = tail;
assert(tail->next);
node->next = cur_tail->next;
if (node->next == head) {
break;
}
if (cur_tail->next == cur_tail) {
tail = head;
assert(tail->next);
} else {
cas(&tail, cur_tail, node->next);
assert(tail->next);
}
++retry;
if (retry > 1000000) {
dump();
retry = 0;
}
}
} while (!cas(&tail->next, head, node));
}
ywQueue<DATA> * pop() {
ywQueue<DATA> *ret;
ywQueue<DATA> *new_next;
do {
synchronize();
ret = head->next;
if (ret == head) {
return NULL;
}
} while (!(new_next = make_circle(ret)));
assert(cas(&head->next, ret, new_next));
return ret;
}
size_t calc_count() {
size_t k = 0;
ywQueue<int32_t> * iter;
for (iter = head->next; iter != head; iter = iter->next) {
k++;
}
return k;
}
/* src_q : -A-B-C-D- => dst_q.bring(A,C) => src_q : -A-D-
* dst_q : -E-F- dst_q : -B-C-E-F- */
void bring(ywQueue<DATA> * _before_first, ywQueue<DATA> *_last) {
assert(sync == false);
ywQueue<DATA> * _first = _before_first->next;
/* detach targets from src_1 */
/* src_q : -A-B-C-D- => src_q : -A-D- */
_before_first->next = _last->next;
/* dst_q :-E-F- => -B-C-E-F- */
_last->next = head->next;
head->next = _first;
}
void bring_all(ywQueueHead<DATA, sync> * src_q) {
ywQueue<DATA> * iter;
ywQueue<DATA> * s_head = src_q->head;
for (iter = s_head->next; iter->next != s_head; iter = iter->next) {
}
bring(s_head, iter);
}
void dump() {
ywQueue<DATA> * iter;
intptr_t ptr;
printf("dump {");
for (iter = head; iter->next != head; iter = iter->next) {
ptr = reinterpret_cast<intptr_t>(iter);
if (iter == tail) {
printf("T[%08" PRIxPTR "] ", ptr);
} else {
printf(" [%08" PRIxPTR "] ", ptr);
}
}
printf("}\n");
}
private:
ywQueue<DATA> *head;
ywQueue<DATA> *tail;
ywQueue<DATA> head_instance;
friend class ywqTestClass;
};
void ywq_test();
#endif // INCLUDE_YWQ_H_
| true |
218601a290eaedc040634ee45f9787d057a9c377 | C++ | lains/libezsp | /src/ezsp/zigbee-tools/zigbee-messaging.h | UTF-8 | 1,362 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @file zigbee-messaging.h
*
* @brief Manages zigbee message, timeout, retry
*/
#pragma once
#include "ezsp/ezsp-dongle-observer.h"
#include "ezsp/ezsp-dongle.h"
#include "ezsp/zbmessage/zigbee-message.h"
#include "spi/ByteBuffer.h"
namespace NSEZSP {
class CZigbeeMessaging : public CEzspDongleObserver {
public:
/**
* @brief Constructor
*
* @param[in] i_dongle The EZSP adapter used to send/receive Zigbee messages
* @param[in] i_timer_builder Timer builder object used to generate timers
*/
CZigbeeMessaging(CEzspDongle& i_dongle, const NSSPI::TimerBuilder& i_timer_builder);
void SendBroadcast( EOutBroadcastDestination i_destination, uint8_t i_radius, CZigBeeMsg i_msg);
void SendUnicast( EmberNodeId i_node_id, CZigBeeMsg i_msg );
/**
* @brief Send a ZDO unicast command
* @param i_node_id Short address of destination
* @param i_cmd_id Command
* @param[in] payload Payload for the ZDO unicast
* @return true if message can be send
*/
void SendZDOCommand( EmberNodeId i_node_id, uint16_t i_cmd_id, const NSSPI::ByteBuffer& payload );
/**
* Observer
*/
void handleEzspRxMessage( EEzspCmd i_cmd, NSSPI::ByteBuffer i_msg_receive );
private:
CEzspDongle &dongle;
const NSSPI::TimerBuilder& timerBuilder; // needed in the future to well manage retry/timeout on unicast zigbee message
};
} // namespace NSEZSP
| true |
566bd91bb4e827aae67ae307fce66dc40bde0547 | C++ | ekdnam/competitive | /codechef/APRIL21C/SSCRIPT/sscript.cc | UTF-8 | 1,061 | 2.671875 | 3 | [
"MIT"
] | permissive | // https://www.codechef.com/APRIL21C/problems/SSCRIPT
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <set>
#include <string>
#include <string.h>
using namespace std;
int main(void)
{
long long int t;
vector<string> out;
cin >> t;
long long int k, n;
string in;
while (t--)
{
cin >> n >> k >> in;
int count = 0, count_max = 0;
bool ans = false;
for (int i = 0; i < n; i++)
{
if (in[i] == '*')
{
count += 1;
if (count > count_max)
{
count_max = count;
}
}
else
{
count = 0;
}
}
ans = count_max >= k;
if (ans)
{
out.push_back("YES");
}
else
{
out.push_back("NO");
}
}
for (int i = 0; i < out.size() - 1; i++)
{
cout << out[i] << "\n";
}
cout << out[out.size() - 1];
}
| true |
f3a1d71a62e95d42ef5cca7606d3a96e7285f2dd | C++ | semrich/ds302_20 | /notes/8_2-4_PQ/pqueue.h | UTF-8 | 1,124 | 3.640625 | 4 | [] | no_license | #include <vector>
#include <set>
using namespace std;
/* The Main Priority Queue Interface. */
class PQueue {
public:
virtual ~PQueue() {};
virtual void Push(double d) = 0;
virtual double Pop() = 0;
virtual int Size() = 0;
virtual bool Empty() = 0;
virtual void Print() = 0;
};
/* PQueueSet: Implementing the priority
queue with a multiset */
class PQueueSet : public PQueue {
public:
void Push(double d);
double Pop();
int Size();
bool Empty();
void Print();
PQueueSet();
protected:
multiset <double> elements;
};
/* PQueueHeap: Implementing the priority
queue with a binary heap. You'll note
that there is a second constructor
here that creates the priority queue
from a vector of doubles. */
class PQueueHeap : public PQueue {
public:
void Push(double d);
double Pop();
int Size();
bool Empty();
void Print();
PQueueHeap();
PQueueHeap(vector <double> &init);
protected:
vector <double> h;
void Percolate_Down(int index);
};
| true |
64b7c2b5edc752377c8d38086618f5f98d124ff5 | C++ | ssjf409/PS | /라인/2.cpp | UTF-8 | 1,159 | 3.0625 | 3 | [] | no_license | #include <string>
#include <vector>
#include <deque>
using namespace std;
vector<int> solution(vector<int> ball, vector<int> order) {
vector<int> answer;
deque<int> dq;
for(int i = 0; i < ball.size(); i++) {
dq.push_back(ball[i]);
}
vector<bool> isReserved(1000001, false);
for(int i = 0; i < order.size(); i++) {
int target = order[i];
if(dq.front() == target) {
answer.push_back(target);
dq.pop_front();
while(!dq.empty() && isReserved[dq.front()]) {
answer.push_back(dq.front());
isReserved[dq.front()] = false;
dq.pop_front();
}
} else if(dq.back() == target) {
answer.push_back(target);
dq.pop_back();
while(!dq.empty() && isReserved[dq.back()]) {
answer.push_back(dq.back());
isReserved[dq.back()] = false;
dq.pop_back();
}
} else {
isReserved[target] = true;
}
}
return answer;
} | true |
d9ff0ef7c65221369a4c2ae00cfbcc7c9e637c62 | C++ | Hipepper/Genetic-algorithm-C-- | /源.cpp | UTF-8 | 13,664 | 2.75 | 3 | [] | no_license |
# include <cstdlib>
#include <stdio.h>
# include <iostream>
# include <iomanip>
# include <fstream>
# include <iomanip>
# include <math.h>
# include <ctime>
# include <cstring>
using namespace std;
# define POPSIZE 50//种群内个体数量
# define MAXGENS 1000//最大的迭代次数
# define NVARS 3//变量个数,即用以表示基因型的bit数
# define PXOVER 0.8//交换率
# define PMUTATION 0.15//突变率
struct genotype
{
double gene[NVARS];
double fitness;
double upper[NVARS];
double lower[NVARS];
double rfitness;
double cfitness;
};
struct genotype population[POPSIZE + 1];
struct genotype newpopulation[POPSIZE + 1];
int main();
void crossover(int& seed);//交叉操作。selects two parents for the single point crossover
void elitist();//stores the best member of the previous generation
void evaluate();//implements the user-defined valuation function
int i4_uniform_ab(int a, int b, int& seed);//returns a scaled pseudorandom I4 between A and B
int Int_uniform_ab(int a, int b);//my own function to get a value between "a" and "b"
void initialize(string filename, int& seed);//initializes the genes within the variables bounds
void keep_the_best();//keeps track of the best member of the population
void mutate(int& seed);//performs a random uniform mutation
double r8_uniform_ab(double a, double b, int& seed);//returns a scaled pseudorandom R8
double Dou_uniform_ab(double a, double b);//return a double value between "a" and "b"
void report(int generation);//reports progress of the simulation
void selector(int& seed);// is the selection function
double round(double number);//returns the integral value that is nearest to x, with halfway cases rounded away from zero
void timestamp();//prints the current YMDHMS date as a time stamp
void Xover(int one, int two, int& seed);//performs crossover of the two selected parents
//****************************************************************************80
int main()
{
string filename = "simple_ga_input.txt";
int generation;
int i;
int seed;
timestamp();
cout << "\n";
cout << "SIMPLE_GA:\n";
cout << " C++ version\n";
cout << " A simple example of a genetic algorithm.\n";
if (NVARS < 2)
{
cout << "\n";
cout << " The crossover modification will not be available,\n";
cout << " since it requires 2 <= NVARS.\n";
}
seed = 123456789;
srand((unsigned)time(NULL));
initialize(filename, seed);
evaluate();
keep_the_best();
for (generation = 0; generation < MAXGENS; generation++)
{
selector(seed);
crossover(seed);
mutate(seed);
report(generation);
evaluate();
elitist();
}
cout << "\n";
cout << " Best member after " << MAXGENS << " generations:\n";
cout << "\n";
for (i = 0; i < NVARS; i++)
{
cout << " var(" << i << ") = " << population[POPSIZE].gene[i] << "\n";
}
cout << "\n";
cout << " Best fitness = " << population[POPSIZE].fitness << "\n";
//
// Terminate.
//
cout << "\n";
cout << "SIMPLE_GA:\n";
cout << " Normal end of execution.\n";
cout << "\n";
timestamp();
return 0;
}
//****************************************************************************80
void crossover(int& seed)
{
const double a = 0.0;
const double b = 1.0;
int mem;
int one;
int first = 0;
double x;
for (mem = 0; mem < POPSIZE; ++mem)
{
//x = r8_uniform_ab ( a, b, seed );
x = Dou_uniform_ab(a, b);
if (x < PXOVER)
{
++first;
if (first % 2 == 0)
{
Xover(one, mem, seed);
}
else
{
one = mem;
}
}
}
return;
}
void elitist()
{
int i;
double best;
int best_mem;
double worst;
int worst_mem;
best = population[0].fitness;
worst = population[0].fitness;
for (i = 0; i < POPSIZE - 1; ++i)
{
if (population[i + 1].fitness < population[i].fitness)
{
if (best <= population[i].fitness)
{
best = population[i].fitness;
best_mem = i;
}
if (population[i + 1].fitness <= worst)
{
worst = population[i + 1].fitness;
worst_mem = i + 1;
}
}
else
{
if (population[i].fitness <= worst)
{
worst = population[i].fitness;
worst_mem = i;
}
if (best <= population[i + 1].fitness)
{
best = population[i + 1].fitness;
best_mem = i + 1;
}
}
}
if (population[POPSIZE].fitness <= best)
{
for (i = 0; i < NVARS; i++)
{
population[POPSIZE].gene[i] = population[best_mem].gene[i];
}
population[POPSIZE].fitness = population[best_mem].fitness;
}
else
{
for (i = 0; i < NVARS; i++)
{
population[worst_mem].gene[i] = population[POPSIZE].gene[i];
}
population[worst_mem].fitness = population[POPSIZE].fitness;
}
return;
}
void evaluate()
// The current function is: x[1]^2-x[1]*x[2]+x[3]
{
int member;
int i;
double x[NVARS + 1];
for (member = 0; member < POPSIZE; member++)
{
for (i = 0; i < NVARS; i++)
{
x[i + 1] = population[member].gene[i];
}
population[member].fitness = (x[1] * x[1]) - (x[1] * x[2]) + x[3];
}
return;
}
int i4_uniform_ab(int a, int b, int& seed)
{
int c;
const int i4_huge = 2147483647;
int k;
float r;
int value;
if (seed == 0)
{
cerr << "\n";
cerr << "I4_UNIFORM_AB - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit(1);
}
//
// Guarantee A <= B.
//
if (b < a)
{
c = a;
a = b;
b = c;
}
k = seed / 127773;
seed = 16807 * (seed - k * 127773) - k * 2836;
if (seed < 0)
{
seed = seed + i4_huge;
}
r = (float)(seed) * 4.656612875E-10;
//
// Scale R to lie between A-0.5 and B+0.5.
//
r = (1.0 - r) * ((float)a - 0.5)
+ r * ((float)b + 0.5);
//
// Use rounding to convert R to an integer between A and B.
//Returns the integral value that is nearest to x
value = round(r);//Vs2008中并没有此函数,需要自己实现。是最近取整
//
// Guarantee A <= VALUE <= B.
//
if (value < a)
{
value = a;
}
if (b < value)
{
value = b;
}
return value;
}
//my new design function of the distribution
int Int_uniform_ab(int a, int b)
{
int tmp;
tmp = (rand() % (b - a + 1)) + a;
return tmp;
}
//****************************************************************************80
void initialize(string filename, int& seed)
{
int i;
ifstream input;
int j;
double lbound;
double ubound;
input.open(filename.c_str());
if (!input)
{
cerr << "\n";
cerr << "INITIALIZE - Fatal error!\n";
cerr << " Cannot open the input file!\n";
exit(1);
}
//
// Initialize variables within the bounds
for (i = 0; i < NVARS; i++)
{
input >> lbound >> ubound;
for (j = 0; j < POPSIZE; j++)
{
population[j].fitness = 0;
population[j].rfitness = 0;
population[j].cfitness = 0;
population[j].lower[i] = lbound;
population[j].upper[i] = ubound;
//population[j].gene[i] = r8_uniform_ab ( lbound, ubound, seed );
population[j].gene[i] = Dou_uniform_ab(lbound, ubound);
}
}
input.close();
return;
}
//****************************************************************************80
void keep_the_best()
{
int cur_best;
int mem;
int i;
cur_best = 0;
for (mem = 0; mem < POPSIZE; mem++)
{
if (population[POPSIZE].fitness < population[mem].fitness)
{
cur_best = mem;
population[POPSIZE].fitness = population[mem].fitness;
}
}
//
// Once the best member in the population is found, copy the genes.
//
for (i = 0; i < NVARS; i++)
{
population[POPSIZE].gene[i] = population[cur_best].gene[i];
}
return;
}
//****************************************************************************80
void mutate(int& seed)
{
const double a = 0.0;
const double b = 1.0;
int i;
int j;
double lbound;
double ubound;
double x;
for (i = 0; i < POPSIZE; i++)
{
for (j = 0; j < NVARS; j++)
{
//x = r8_uniform_ab ( a, b, seed );
x = Dou_uniform_ab(a, b);
if (x < PMUTATION)
{
lbound = population[i].lower[j];
ubound = population[i].upper[j];
//population[i].gene[j] = r8_uniform_ab ( lbound, ubound, seed );
population[i].gene[j] = Dou_uniform_ab(lbound, ubound);
}
}
}
return;
}
//****************************************************************************80
double r8_uniform_ab(double a, double b, int& seed)
{
int i4_huge = 2147483647;
int k;
double value;
if (seed == 0)
{
cerr << "\n";
cerr << "R8_UNIFORM_AB - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit(1);
}
k = seed / 127773;
seed = 16807 * (seed - k * 127773) - k * 2836;
if (seed < 0)
{
seed = seed + i4_huge;
}
value = (double)(seed) * 4.656612875E-10;
value = a + (b - a) * value;
return value;
}
// my new function of product a value between "a" and "b"
double Dou_uniform_ab(double a, double b)
{
double tmp;
//rand() / double(RAND_MAX)可以生成0~1之间的浮点数
tmp = a + static_cast<double>(rand()) / RAND_MAX * (b - a);
return tmp;
}
void report(int generation)
{
double avg;
double best_val;
int i;
double square_sum;
double stddev;
double sum;
double sum_square;
if (generation == 0)
{
cout << "\n";
cout << " Generation Best Average Standard \n";
cout << " number value fitness deviation \n";
cout << "\n";
}
sum = 0.0;
sum_square = 0.0;
for (i = 0; i < POPSIZE; i++)
{
sum = sum + population[i].fitness;
sum_square = sum_square + population[i].fitness * population[i].fitness;
}
avg = sum / (double)POPSIZE;
square_sum = avg * avg * POPSIZE;
stddev = sqrt((sum_square - square_sum) / (POPSIZE - 1));
best_val = population[POPSIZE].fitness;
cout << " " << setw(8) << generation
<< " " << setw(14) << best_val
<< " " << setw(14) << avg
<< " " << setw(14) << stddev << "\n";
return;
}
void selector(int& seed)
{
const double a = 0.0;
const double b = 1.0;
int i;
int j;
int mem;
double p;
double sum;
//
// Find the total fitness of the population.
//
sum = 0.0;
for (mem = 0; mem < POPSIZE; mem++)
{
sum = sum + population[mem].fitness;
}
//
// Calculate the relative fitness of each member.
//
for (mem = 0; mem < POPSIZE; mem++)
{
population[mem].rfitness = population[mem].fitness / sum;
}
//
// Calculate the cumulative fitness.
//
population[0].cfitness = population[0].rfitness;
for (mem = 1; mem < POPSIZE; mem++)
{
population[mem].cfitness = population[mem - 1].cfitness +
population[mem].rfitness;
}
//
// Select survivors using cumulative fitness.
//
for (i = 0; i < POPSIZE; i++)
{
//p = r8_uniform_ab ( a, b, seed );
p = Dou_uniform_ab(a, b);
if (p < population[0].cfitness)
{
newpopulation[i] = population[0];
}
else
{
for (j = 0; j < POPSIZE; j++)
{
if (population[j].cfitness <= p && p < population[j + 1].cfitness)
{
newpopulation[i] = population[j + 1];
}
}
}
}
//
// Overwrite the old population with the new one.
//
for (i = 0; i < POPSIZE; i++)
{
population[i] = newpopulation[i];
}
return;
}
//****************************************************************************80
double round(double number)
{
return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}
void timestamp()
// TIMESTAMP prints the current YMDHMS date as a time stamp.
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct tm* tm;
size_t len;
time_t now;
now = time(NULL);
tm = localtime(&now);
//将时间格式化
len = strftime(time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm);
cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
//****************************************************************************80
void Xover(int one, int two, int& seed)
{
int i;
int point;
double t;
// Select the crossover point.
//point = i4_uniform_ab ( 0, NVARS - 1, seed );
point = Int_uniform_ab(0, NVARS - 1);
//
// Swap genes in positions 0 through POINT-1.
//
for (i = 0; i < point; i++)
{
t = population[one].gene[i];
population[one].gene[i] = population[two].gene[i];
population[two].gene[i] = t;
}
return;
}
| true |
6bdbfcc2b5faad9efe2be91fc70c10b035bf8fd2 | C++ | kk2491/CPP_Quick_Tour | /Examples/oop_152.cpp | UTF-8 | 1,419 | 4.0625 | 4 | [] | no_license | #include <iostream>
#include <string>
class Player {
private:
std::string name;
int health;
int xp;
public:
Player(std::string name = "None", int health = 0, int xp = 0);
~Player();
void SetName(std::string name);
std::string GetName() const;
};
Player::Player(std::string name, int health, int xp) :
name {name}, health {health}, xp {xp} {}
Player::~Player() {
std::cout << "Destructor Called" << std::endl;
}
void Player::SetName(std::string new_name) {
this->name = new_name;
return;
}
// Normal get function
std::string Player::GetName() const {
return this->name;
}
void DisplayAll(const Player &player_obj) {
std::cout << "Player : " << player_obj.GetName() << std::endl;
}
int main() {
// Normal Object - No error
Player player_1("Sachin", 10, 100);
std::cout << "Player Name : " << player_1.GetName() << std::endl;
// error: passing ‘const Player’ as ‘this’ argument discards qualifiers [-fpermissive]
const Player player_2("Dravid", 11, 11);
std::cout << "Player Name : " << player_2.GetName() << std::endl;
// Define function as const - such that explicitly saying function does not modify the class objects
// const Player player_2("Dravid", 11, 11);
// std::cout << "Player Name : " << player_2.GetName() << std::endl;
DisplayAll(player_1);
DisplayAll(player_2);
return 0;
} | true |
ab2ab1c709e002e5cc52c8cee87de2c52128cd45 | C++ | emfomy/pass | /src/genlog/pass.cpp | UTF-8 | 19,716 | 2.703125 | 3 | [] | no_license | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file genlog/pass.cpp
/// @brief The main PaSS algorithm for general logistic regression
///
/// @author Mu Yang <emfomy@gmail.com>
///
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @mainpage Particle Swarm Stepwise (PaSS) Algorithm for General Logistic Regression
///
/// @code{.unparsed}
/// ==========================================================================================================================
///
/// Notation:
/// X : the regressors
/// Y : the regressand
/// Beta : the effects
/// P : the probability of Y=1
/// Theta : the logit function of P
/// lv : the likelihood value
/// llv : the log-likelihood value
///
/// ==========================================================================================================================
///
/// Logistic model:
/// P := exp(X*Beta) ./ 1+exp(X*Beta)
/// Theta := logit(P) = X*Beta
///
/// Update Beta:
/// Theta := X * Beta
/// Eta := exp(Theta)
/// P := Eta ./ (1+Eta)
/// 1-P = 1 ./ (1+Eta)
/// W := P .* (1-P)
/// Beta += inv( X'*diag(W)*X ) * X' * (Y-P)
///
/// Compute log-likelihood:
/// lv := prod( p^y * (1-p)^(1-y) )
/// llv := log( lv )
/// = sum( y * log(p) + (1-y) * log(1-p) )
/// = sum( y * log(eta) - y * log(1+eta) - (1-y) * log(1+eta) )
/// = Y' * Theta - sum( log(1+eta) )
///
/// Newton-Raphson method:
/// d(llv)/d(Beta) = X' * (Y-P)
/// d^2(llv)/d(Beta)^2 = - X' * diag(W) * X
///
/// ==========================================================================================================================
///
/// Select the index in forward step:
/// idx = argmax_{i not in I} llv_hat
/// Theta_hat := Theta_new - Theta = Beta[i] * X[i col]
/// Eta_hat := Eta_new ./ Eta = exp( Theta_hat )
/// llv_hat := llv_new - llv
/// = ( Y' * Theta_new - Y' * Theta )
/// - ( sum( log(1+eta_new) ) - sum( log(1+eta) ) )
/// = Y' * Theta_hat - sum( log( (1+eta_new)/(1+eta) ) )
/// = Y' * Theta_hat - sum( log( 1 + (eta_hat-1)*p ) )
///
/// Approximate Beta[i] with Newton-Raphson method:
/// Beta[i] += ( X[i col]'*(Y-P_new) ) / ( X[i col]'*diag(W_new)*X[i col] )
///
/// ==========================================================================================================================
///
/// Select the index in backward step:
/// idx = argmax_{i in I} llv_hat
/// Theta_hat := Theta_new - Theta = -Beta[i] * X[i col]
/// Eta_hat := Eta_new ./ Eta = exp( Theta_hat )
/// llv_hat := llv_new - llv
/// = ( Y' * Theta_new - Y' * Theta )
/// - ( sum( log(1+eta_new) ) - sum( log(1+eta) ) )
/// = Y' * Theta_hat - sum( log( (1+eta_new)/(1+eta) ) )
/// = Y' * Theta_hat - sum( log( 1 + (eta_hat-1)*p ) )
///
/// ==========================================================================================================================
///
/// References:
/// Chen, R.-B., Huang, C.-C., & Wang, W. (2015). Particle Swarm Stepwise (PaSS) Algorithm for Variable Selection.
///
/// Liu, Z., & Liu, M. (2011). Logistic Regression Parameter Estimation Based on Parallel Matrix Computation.
/// In Q. Zhou (Ed.), Communications in Computer and Information Science (Vol. 164, pp. 268–275).
/// Berlin, Heidelberg: Springer Berlin Heidelberg. http://doi.org/10.1007/978-3-642-24999-0_38
///
/// Singh, S., Kubica, J., Larsen, S., & Sorokina, D. (2013).
/// Parallel Large Scale Feature Selection for Logistic Regression (pp. 1172–1183).
/// Philadelphia, PA: Society for Industrial and Applied Mathematics. http://doi.org/10.1137/1.9781611972795.100
///
/// Barbu, A., She, Y., Ding, L., & Gramajo, G. (2014). Feature Selection with Annealing for Big Data Learning.
/// http://arxiv.org/pdf/1310.288
///
/// ==========================================================================================================================
/// @endcode
///
/// @author Mu Yang <emfomy@gmail.com>
///
#include "pass.hpp"
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <omp.h>
#include <mkl.h>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The log-binomial function
///
/// @param n a number
/// @param k a number
///
/// @return return the log-binomial value of n and k
///
static inline float lbinom( const int n, const int k ) {
int i;
return (lgammaf_r(n+1, &i) - lgammaf_r(n-k+1, &i) - lgammaf_r(k+1, &i));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The namespace of PaSS
//
namespace pass {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The namespace of general logistic regression
//
namespace genlog {
int n; // scalar, the number of statistical units
int p; // scalar, the number of total effects
float *X0; // matrix, n by p, the regressors
float *Y0; // vector, n by 1, the regressand
bool *I0; // vector, 1 by p, the chosen indices
float phi0; // scalar, the criterion value
Parameter parameter; // the PaSS parameters
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The PaSS algorithm for linear regression
///
/// @param[in] pass::n scalar, the number of statistical units
/// @param[in] pass::p scalar, the number of total effects
/// @param[in] pass::X0 matrix, n by p, the regressors
/// @param[in] pass::Y0 vector, n by 1, the regressand
/// @param[in] pass::parameter the PaSS parameters
///
/// @param[out] pass::I0 vector, 1 by p, the chosen indices
/// @param[out] pass::phi0 scalar, the criterion value
///
/// @note Please call @c srand() before using this routine.
///
void GenLog() {
// Check parameters
auto num_thread = omp_get_max_threads();
auto num_particle = num_thread * parameter.num_particle_thread;
// ======== Normalize the original data ================================================================================= //
if ( !parameter.is_normalized ) {
// Normalize X0
for ( auto j = 0; j < p; ++j ) {
cblas_sscal(n, (1.0f/cblas_snrm2(n, X0+j*n, 1)), X0+j*n, 1);
}
// Normalize Y0
cblas_sscal(n, (1.0f/cblas_snrm2(n, Y0, 1)), Y0, 1);
}
// ======== Run PaSS ==================================================================================================== //
// Allocate particles
auto particle = new Particle[num_particle];
phi0 = INFINITY;
// Use openMP parallel
#pragma omp parallel
{
unsigned int tid = omp_get_thread_num();
for ( auto j = tid; j < num_particle; j+=num_thread ) {
// Initialize particles
particle[j].InitializeModel();
particle[j].ComputeCriterion();
particle[j].phi_old = particle[j].phi;
// Copy best model
if ( phi0 > particle[j].phi ) {
phi0 = particle[j].phi;
memcpy(I0, particle[j].I, sizeof(bool) * p);
}
}
#pragma omp barrier
// Find best model
for ( auto i = 1u; i < parameter.num_iteration; ++i ) {
for ( auto j = tid; j < num_particle; j+=num_thread ) {
// Update model
int idx;
particle[j].SelectIndex(idx);
particle[j].UpdateModel(idx);
particle[j].ComputeCriterion();
// Check singularity
if ( std::isnan(particle[j].phi) ) {
particle[j].InitializeModel();
particle[j].ComputeCriterion();
}
// Change status
if ( particle[j].phi > particle[j].phi_old ) {
particle[j].status = !particle[j].status;
}
if ( particle[j].k <= 1 ) {
particle[j].status = true;
}
if ( particle[j].k >= n-1 || particle[j].k >= p-4 ) {
particle[j].status = false;
}
particle[j].phi_old = particle[j].phi;
// Copy best model
if ( phi0 > particle[j].phi ) {
phi0 = particle[j].phi;
memcpy(I0, particle[j].I, sizeof(bool) * p);
}
}
}
}
// ====================================================================================================================== //
// Delete memory
delete[] particle;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The constructor
///
Particle::Particle() {
X = static_cast<float*>(mkl_malloc(n * n * sizeof(float), 64));
Y = static_cast<float*>(mkl_malloc(n * sizeof(float), 64));
Beta = static_cast<float*>(mkl_malloc(n * sizeof(float), 64));
Theta = static_cast<float*>(mkl_malloc(n * sizeof(float), 64));
Eta = static_cast<float*>(mkl_malloc(n * sizeof(float), 64));
P = static_cast<float*>(mkl_malloc(n * sizeof(float), 64));
W = static_cast<float*>(mkl_malloc(n * sizeof(float), 64));
M = static_cast<float*>(mkl_malloc(n*(n+1)/2 * sizeof(float), 64));
STemp = static_cast<float*>(mkl_malloc(n * sizeof(float), 64));
Idx_lo = static_cast<int* >(mkl_malloc(n * sizeof(int), 64));
Idx_ol = static_cast<int* >(mkl_malloc(p * sizeof(int), 64));
Idx_temp = static_cast<int* >(mkl_malloc(p * sizeof(int), 64));
I = static_cast<bool* >(mkl_malloc(p * sizeof(bool), 64));
iseed = rand();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// The destructor
///
Particle::~Particle() {
mkl_free(X);
mkl_free(Y);
mkl_free(Beta);
mkl_free(Theta);
mkl_free(Eta);
mkl_free(P);
mkl_free(W);
mkl_free(M);
mkl_free(STemp);
mkl_free(Idx_lo);
mkl_free(Idx_ol);
mkl_free(Idx_temp);
mkl_free(I);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Initialize the model randomly
///
void Particle::InitializeModel() {
InitializeModel(rand_r(&iseed) % p);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Initialize the model
///
/// @param[in] idx the index of the effect
///
void Particle::InitializeModel( const int idx ) {
// Initialize size
k = 0;
// Initialize index
memset(I, false, sizeof(bool) * p);
// X[0 col] := 1.0
for ( auto i = 0; i < n; ++i ) {
X[i] = 1.0f;
}
// Y := Y0
cblas_scopy(n, Y0, 1, Y, 1);
// Set status
status = true;
// Insert effect
UpdateModel(idx);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Update the model
///
/// @param[in] idx the index of the effect
///
void Particle::UpdateModel( const int idx ) {
if ( status ) { // forward step
// Update size
k++;
// Update index
I[idx] = true;
Idx_lo[k] = idx;
Idx_ol[idx] = k;
// Set Xnew
auto Xnew = X+k*n;
// Insert new row of X
cblas_scopy(n, X0+idx*n, 1, Xnew, 1);
// insert Beta by zero
Beta[k] = 0.0f;
} else { // Backward step
// Update index
I[idx] = false;
// Find index
auto j = Idx_ol[idx];
// Copy index end to index j
if ( j != k ) {
cblas_scopy(n, X+k*n, 1, X+j*n, 1);
Beta[j] = Beta[k];
Idx_lo[j] = Idx_lo[k];
Idx_ol[Idx_lo[j]] = j;
}
// Update size
k--;
}
// Compute Beta
ComputeBeta();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Compute Beta
///
void Particle::ComputeBeta() {
auto kp = k+1;
// ======== Find Beta using Newton-Raphson's method ===================================================================== //
do {
// Theta := X * Beta
cblas_sgemv(CblasColMajor, CblasNoTrans, n, kp, 1.0f, X, n, Beta, 1, 0.0f, Theta, 1);
// Eta := exp(Theta)
vsExp(n, Theta, Eta);
// P := Eta ./ (1+Eta)
vsLinearFrac(n, Eta, Eta, 1.0f, 0.0f, 1.0f, 1.0f, P);
// W := P .* (1-P)
vsLinearFrac(n, P, Eta, 1.0f, 0.0f, 1.0f, 1.0f, W);
// -------- Beta += inv(X'*diag(W)*X) * X' * (Y-P) ------------------------------------------------------------------ //
// M := X' * diag(W) * X
for ( auto i = 0; i < kp*(kp+1)/2; ++i ) {
M[i] = 0.0f;
}
for ( auto i = 0; i < n; ++i ) {
cblas_sspr(CblasColMajor, CblasLower, kp, W[i], X+i, n, M);
}
// Compute Cholesky decomposition of M
LAPACKE_spptrf(LAPACK_COL_MAJOR, 'L', kp, M);
// W := (Y-P)
vsSub(n, Y, P, W);
// STemp := X' * W
cblas_sgemv(CblasColMajor, CblasTrans, n, kp, 1.0f, X, n, W, 1, 0.0f, STemp, 1);
// Solve STemp = inv(M) * STemp
cblas_stpsv(CblasColMajor, CblasLower, CblasNoTrans, CblasNonUnit, kp, M, STemp, 1);
// Solve STemp = inv(M') * STemp
cblas_stpsv(CblasColMajor, CblasLower, CblasTrans, CblasNonUnit, kp, M, STemp, 1);
// Beta += STemp
vsAdd(kp, Beta, STemp, Beta);
// ------------------------------------------------------------------------------------------------------------------ //
} while ( cblas_snrm2(kp, STemp, 1) > sqrt(kp) * 1e-4f );
// ====================================================================================================================== //
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Select the index of the effect to update
///
/// @param[out] idx the index of the effect
///
void Particle::SelectIndex( int& idx ) {
auto srand = static_cast<float>(rand_r(&iseed)) / RAND_MAX;
if ( status ) { // Forward step
// Idx_temp[0~itemp] := I0 exclude I
// Idx_temp[0~(p-k)] := complement of I
int itemp = 0;
for ( auto i = 0, j = p-k; i < p; ++i ) {
if ( !I[i] ) {
if ( I0[i] ) {
Idx_temp[itemp] = i;
itemp++;
} else {
j--;
Idx_temp[j] = i;
}
}
}
int choose;
if ( itemp ) {
choose = (srand < parameter.prob_forward_best) + (srand < parameter.prob_forward_best+parameter.prob_forward_improve);
} else {
choose = srand < parameter.prob_forward_improve / (parameter.prob_forward_improve+parameter.prob_forward_random);
}
switch( choose ) {
case 2: { // Choose randomly from best model
idx = Idx_temp[rand_r(&iseed) % itemp];
break;
}
case 1: { // Choose most improvement index
auto llv_temp = -INFINITY;
for ( auto i = 0; i < p-k; ++i ) {
// beta := 0
auto beta = 0.0f;
// Xnew := X0[Idx_temp[i] col]
auto Xnew = X0+Idx_temp[i]*n;
// stemp := Xnew' * Y
auto stemp = cblas_sdot(n, Xnew, 1, Y, 1);
// ======== Solve Y = X * Beta for Beta ========================================================================= //
auto beta_temp = 0.0f;
do {
// STemp(Theta_new) := Theta + beta * Xnew
cblas_scopy(n, Theta, 1, STemp, 1);
cblas_saxpy(n, beta, Xnew, 1, STemp, 1);
// Eta(Eta_new) := exp(Theta_new)
vsExp(n, STemp, Eta);
// STemp(P_new) := Eta_new ./ (1+Eta_new)
vsLinearFrac(n, Eta, Eta, 1.0f, 0.0f, 1.0f, 1.0f, STemp);
// W(W_new) := P_new .* (1-P_new)
vsLinearFrac(n, STemp, Eta, 1.0f, 0.0f, 1.0f, 1.0f, W);
// beta += (Xnew'*(Y-P_new)) / (Xnew'*diag(W_new)*Xnew)
vsMul(n, W, Xnew, W);
beta_temp = (stemp - cblas_sdot(n, Xnew, 1, STemp, 1)) / cblas_sdot(n, Xnew, 1, W, 1);
beta += beta_temp;
} while ( beta_temp > 1e-4f );
// ======== stemp := Y' * Theta_hat - sum( log( 1 + (eta_hat-1)*p ) ) =========================================== //
// STemp(Theta_hat) := beta * Xnew
cblas_saxpby(n, beta, Xnew, 1, 0.0f, STemp, 1);
// stemp := Y' * Theta_hat
stemp = cblas_sdot(n, Y, 1, STemp, 1);
// STemp := log(1+(Eta_hat-1)*P)
vsExpm1(n, STemp, Eta);
vsMul(n, Eta, P, W);
vsLog1p(n, W, STemp);
// stemp += sum(STemp)
for ( auto j = 0; j < n; ++j ) {
stemp += STemp[j];
}
// ============================================================================================================== //
// Check if this value is maximum
if ( llv_temp < stemp ) {
llv_temp = stemp;
idx = Idx_temp[i];
}
}
break;
}
case 0: { // Choose randomly
idx = Idx_temp[rand_r(&iseed) % (p-k)];
break;
}
}
} else { // Backward step
if ( srand < parameter.prob_backward_improve ) { // Choose most improvement index
auto llv_temp = INFINITY;
for ( auto i = 1; i <= k; ++i ) {
// ======== stemp := Y' * Theta_hat - sum( log( 1 + (eta_hat-1)*p ) ) ============================================= //
// STemp(Theta_hat) := -Beta[i] * X[i]
cblas_saxpby(n, -Beta[i], X+i*n, 1, 0.0f, STemp, 1);
// stemp := Y' * Theta_hat
auto stemp = cblas_sdot(n, Y, 1, STemp, 1);
// STemp := log(1+(Eta_hat-1)*P)
vsExpm1(n, STemp, Eta);
vsMul(n, Eta, P, W);
vsLog1p(n, W, STemp);
// stemp += sum(STemp)
for ( auto j = 0; j < n; ++j ) {
stemp += STemp[j];
}
// ============================================================================================================== //
// Check if this value is minimal
if ( llv_temp > stemp ) {
llv_temp = stemp;
idx = Idx_lo[i];
}
}
} else { // Choose randomly
idx = Idx_lo[rand_r(&iseed) % k + 1];
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Compute the criterion value
///
void Particle::ComputeCriterion() {
// llv := Y' * Theta - sum(log(1+Eta))
vsLog1p(n, Eta, STemp);
llv = cblas_sdot(n, Y, 1, Theta, 1);
for ( auto i = 0; i < n; ++i ) {
llv += STemp[i];
}
// Compute criterion
switch(parameter.criterion) {
case AIC: { // phi := n*log(e^2/n) + 2k
phi = -2.0f*llv + 2.0f*k;
break;
}
case BIC: { // phi := n*log(e^2/n) + k*log(n)
phi = -2.0f*llv + k*logf(n);
break;
}
case HQC: { // phi := n*log(e^2/n) + 2k*log(log(n))
phi = -2.0f*llv + 2.0f*k*logf(logf(n));
break;
}
case EBIC: { // phi := n*log(e^2/n) + k*log(n) + 2gamma*log(binom(p, k))
phi = -2.0f*llv + k*logf(n) + 2.0f*parameter.ebic_gamma*lbinom(p, k);
break;
}
case HDAIC: { // phi := n*log(e^2/n) + 2k*log(p)
phi = -2.0f*llv + 2.0f*k*logf(p);
break;
}
case HDBIC: { // phi := n*log(e^2/n) + k*log(n)*log(p)
phi = -2.0f*llv + k*logf(n)*logf(p);
break;
}
case HDHQC: { // phi := n*log(e^2/n) + 2k*log(log(n))*log(p)
phi = -2.0f*llv + 2.0f*k*logf(logf(n))*logf(p);
break;
}
}
}
} // namespace genlog
} // namespace pass
| true |
8cd300ab95be121ea8e16357ff222fb3f1e3b934 | C++ | yunteng/CubicaPlus | /include/geometry/SPHERE.h | UTF-8 | 1,428 | 2.578125 | 3 | [
"BSD-2-Clause"
] | permissive | /******************************************************************************
*
* Copyright (c) 2015, Yun Teng (yunteng.cs@cs.ucsb.edu), University of
# California, Santa Barbara.
* All rights reserved.
*
*****************************************************************************/
#ifndef SPHERE_H
#define SPHERE_H
#include <geometry/SURFACE.h>
class SPHERE: public SURFACE
{
public:
SPHERE(Real radius = 0.5, const VEC3F& center = VEC3F(0, 0, 0));
virtual ~SPHERE();
Real& radius() { return _radius; };
VEC3F& center() { return _center; };
Real radius() const { return _radius; };
const VEC3F& center() const { return _center; };
virtual void draw();
virtual bool inside(const VEC3F& point);
// signed distance < 0, point inside, > 0 outside
virtual Real distance(const VEC3F& point);
virtual VEC3F contactPoint(const VEC3F& point);
virtual VEC3F force(const VEC3F& collisionPoint, const VEC3F& collisionVelocity = VEC3F(0, 0, 0));
virtual MATRIX3 springJacobian(const VEC3F& collisionPoint);
// debug function -- verify that the spring Jacobian is correct
virtual void verifySpringJacobian(VEC3F& collisionPoint);
// virtual MATRIX3 dampingJacobian(const VEC3F& collisionPoint, const VEC3F& collisionVelocity = VEC3F(0, 0, 0));
virtual bool intersect(const SPHERE& rightSphere);
virtual void boundingBox(VEC3F& mins, VEC3F& maxs);
private:
Real _radius;
VEC3F _center;
};
#endif
| true |
7d5b631bdca4dd0dfc43edb7bdff104aa2245f18 | C++ | MelihOzbk/deneyapkart-platformio-core | /examples/07_BLE/BLE_write/src/BLE_write.cpp | UTF-8 | 2,343 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// UUID oluşturmak için aşağıdaki linki kullanabilirsiniz:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "7cdddbbf-b5a6-4c20-aaf1-f873fa503243"
#define CHARACTERISTIC_UUID "47332d64-d60d-4831-b135-aadbb34e2b92"
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) { // Yazma isteği için callback fonksiyonu
std::string value = pCharacteristic->getValue(); // Karakteristiğin değeri alındı
if (value.length() > 0) { // Karakteristik değerinin uzunluğu (karakter cinsinden) 0'dan büyük ise
Serial.println("*********");
Serial.print("Yeni Deger: ");
for (int i = 0; i < value.length(); i++) // Karakteristik değeri seri monitöre yazıldı
Serial.print(value[i]);
Serial.println();
Serial.println("*********");
}
}
};
void setup() {
Serial.begin(115200);
Serial.println("1- Telefonunuza bir BLE tarayici uygulamasi(BLE Scanner, nRF Connect, LightBlue vb.) indirin ve yukleyin");
Serial.println("2- Uygulamada BLE cihazlarini tarayin");
Serial.println("3- DENEYAP KART'a baglanin");
Serial.println("4- Oluşturduğunuz servisin içerisindeki karakteristiğe gidin ve bir şeyler yazın");
BLEDevice::init("DENEYAP KART"); // BLE cihazı başlatıldı
BLEServer *pServer = BLEDevice::createServer(); // BLE server oluşturuldu
BLEService *pService = pServer->createService(SERVICE_UUID); // BLE servis oluşturuldu
BLECharacteristic *pCharacteristic = pService->createCharacteristic( // BLE karakteristik oluşturuldu
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setCallbacks(new MyCallbacks()); // Karakteristik için callback ayarlandı
pCharacteristic->setValue("Merhaba Dunya"); // Karakteristiğin değeri ayarlandı
pService->start(); // Servis başlatıldı
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->start(); // Yayın başlatıldı
}
void loop() {
delay(2000);
}
| true |
b99c6319917025091d8475871444a737e4b745ae | C++ | tadelemon/qiaqia | /client/clientmain.cpp | UTF-8 | 898 | 2.8125 | 3 | [
"MIT"
] | permissive | // #include <iostream>
#include <cstdio>
#include "client.h"
#include "../utils/cmdline.h"
#include "../utils/asciilogo.h"
int main(int argc,char **argv){
cmdline::parser cmd;
char logo[MAXLINE];
cmd.add<std::string>("host", 'h', "host for the server,default 127.0.0.1", false, "127.0.0.1");
cmd.add<std::string>("port", 'p', "port number to be connect, default 8080", false, "8080");
cmd.parse_check(argc, argv);
//get hostname and port from the command parser
std::string port=cmd.get<std::string>("port");
std::string host=cmd.get<std::string>("host");
client_ns::client client(host,port);
// if init error,return...
if (client.init()<0) return 0;
// format the ascii logo
sprintf(logo,ascii_logo.c_str(),host.c_str(),port.c_str());
//connected, show logo.
printf("%s",logo);
client.start_loop();
return 0;
} | true |
13fc03d5bdeb7420fe33e5c674ddb644ef9a4848 | C++ | GBDT-PL/GBDT-PL | /include/row_histogram.hpp | UTF-8 | 1,813 | 2.65625 | 3 | [
"MIT"
] | permissive | //
// row_histogram.hpp
// LinearGBMVector
//
//
#ifndef row_histogram_hpp
#define row_histogram_hpp
#include <stdio.h>
#include <vector>
#include <map>
#include <string>
#include <cassert>
#include <iostream>
#include "alignment_allocator.hpp"
using std::vector;
using std::string;
using std::map;
class RowHistogram {
private:
vector<dvec32> *sub_histograms;
public:
int max_bin;
int leaf_id;
int feature_id;
int depth;
int max_var;
int row_size;
int cur_var;
bool need_augment;
RowHistogram(int _max_bin, int _feature_id, int _max_var) {
max_bin = _max_bin;
feature_id = _feature_id;
sub_histograms = new vector<dvec32>(max_bin);
max_var = _max_var;
int max_row_size = 2 + 3 * max_var;
if(max_var >= 2) {
max_row_size += max_var * (max_var - 1) / 2;
}
for(int i = 0; i < max_bin; ++i) {
//+8 to avoid write out of bound in linear_bin_feature histogram construction
(*sub_histograms)[i].resize(max_row_size + 8, 0.0);
}
}
void SetDepthAndLeafID(int _cur_var, int _leaf_id, bool _need_augment) {
cur_var = _cur_var;
row_size = 2 + 3 * cur_var;
if(cur_var >= 2) {
row_size += cur_var * (cur_var - 1) / 2;
}
need_augment = _need_augment;
}
vector<dvec32>* Get() {
return sub_histograms;
}
void Clear() {
for(int i = 0; i < max_bin; ++i) {
dvec32& histogram = (*sub_histograms)[i];
#pragma omp simd
for(int j = 0; j < row_size; ++j) {
histogram[j] = 0.0;
}
}
}
void Substract(RowHistogram* child);
};
#endif /* row_histogram_hpp */
| true |
a68f6a26f17d2d61eec25365e319214bc638a538 | C++ | berry8192/Atc | /abc172/E.cc | UTF-8 | 1,409 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(v) v.begin(), v.end()
#define SP << " "
#define LLi long long int
using namespace std;
int imax=2147483647;
long long int llimax=9223372036854775807;
LLi mod=1000000007;
//int型vectorを出力
void PV(vector<int> pvv) {
rep(i, pvv.size()) cout << pvv[i] SP;
cout << endl;
}
//LLi型vectorを出力
void PVL(vector<LLi> pvv) {
rep(i, pvv.size()) cout << pvv[i] SP;
cout << endl;
}
LLi modinv(LLi a) {
LLi b = mod, u = 1, v = 0;
while (b) {
LLi t = a / b;
a -= t * b; swap(a, b);
u -= t * v; swap(u, v);
}
u %= mod;
if (u < 0) u += mod;
return u;
}
int main(){
LLi n, m, ans=0, tmp;
vector<LLi> v;
vector<LLi> con(1), par;
cin>> n >> m;
par.resize(m+1);
con[0]=1;
for(int i=1;i<=m;i++){
tmp=con[i-1];
tmp*=n+1-i;
tmp=tmp%mod;
tmp*=modinv((LLi)i);
tmp=tmp%mod;
con.push_back(tmp);
//cout<< n << "C" << i << "=" << con[i] <<endl;
}
par[m]=1;
for(int i=0;i<n;i++){
par[m]*=(m-i);
par[m]=par[m]%mod;
}
for(int i=m-1;i>0;i--){
par[i]=par[i+1]*modinv((LLi)i+1);
par[i]=par[i]%mod;
}
par[0]=1;
//rep(i, m+1) cout<< par[i] <<endl;
for(int i=0;i<=n;i++){
tmp=con[i]*par[m-i];
tmp=tmp%mod;
if(i%2==0) ans+=tmp;
else ans-=tmp;
ans=(mod+ans)%mod;
}
ans*=par[m];
ans=ans%mod;
cout<< ans << endl;
return 0;
} | true |
3eaecd27e5a64e8a8e464e5b26a8e111ee71e4b6 | C++ | JarvistFth/webServer | /Base/ThreadPool.cpp | UTF-8 | 1,237 | 2.90625 | 3 | [] | no_license | //
// Created by jarvist on 3/19/20.
//
#include "ThreadPool.h"
#include <memory>
void std::ThreadPool::init() {
for(int i=0;i<thread_num;i++){
pool.emplace_back(std::move(std::make_unique<thread>(std::bind(&ThreadPool::runInThread,this))));
}
}
void std::ThreadPool::runInThread() {
while(!isStopped){
Task task;
{
std::unique_lock<mutex> tasklock(mutex_lock);
this->condition.wait(tasklock,[this]{
return this->isStopped|| !this->workqueue.empty();
});
if(this->isStopped && this->workqueue.empty()){
return;
}
task = std::move(workqueue.front());
this->workqueue.pop();
}
task();
}
}
void std::ThreadPool::commit(Task task) {
if(isStopped){
throw runtime_error("thread pool is stopped");
}
{
std::unique_lock<mutex> commitLock(mutex_lock);
workqueue.emplace(std::move(task));
condition.notify_one();
}
}
std::ThreadPool::~ThreadPool() {
this->isStopped = true;
condition.notify_all();
for(auto &threads:pool){
if(threads->joinable()){
threads->join();
}
}
}
| true |
0a71310d3de39495898599a7ef3b0fbf60d4f2a2 | C++ | huanxuantian/arduino_demowork | /libraries/PJON/examples/SpeedTest/Receiver/Receiver.ino | UTF-8 | 1,177 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | #include <PJON.h>
float test;
float mistakes;
// network(Arduino pin used, selected device id)
PJON network(12, 44);
void setup() {
Serial.begin(115200);
network.set_receiver(receiver_function);
};
void receiver_function(uint8_t length, uint8_t *payload) {
// Do nothing to avoid affecting speed analysis
}
void loop() {
Serial.println("Starting 10 seconds communication speed test...");
long time = millis();
int response = 0;
while(millis() - time < 10000) {
response = network.receive(1000);
if(response == ACK)
test++;
if(response == NAK)
mistakes++;
}
Serial.print("Absolute com speed: ");
Serial.print( (test * 24 ) / 10 );
Serial.print(" B/s |Practical bandwidth: ");
Serial.print( (test * 20 ) / 10 );
Serial.print(" B/s |Packets sent: ");
Serial.print(test);
Serial.print(" |Mistakes ");
Serial.print(mistakes);
Serial.print(" |Accuracy: ");
Serial.print(100 - (100 / (test / mistakes)));
Serial.print(" %");
Serial.println();
Serial.println();
if(mistakes > test / 4 || test == 0)
Serial.println("Check wiring! Maybe you need a pull down resistor.");
test = 0;
mistakes = 0;
};
| true |
b4494a4964be5229783c5d419184eb9dc3b18512 | C++ | amireh/Hax | /include/Hax/Configurable.hpp | UTF-8 | 3,420 | 2.515625 | 3 | [] | no_license | /*
* Copyright (c) 2011-2012 Ahmad Amireh <ahmad@amireh.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef H_HAX_CONFIGURABLE_H
#define H_HAX_CONFIGURABLE_H
#include "Hax/Hax.hpp"
#include <vector>
namespace Hax {
class Configurator;
/**
* @class Configurable
*
* Configurables can subscribe themselves to "contexts" that contain settings
* related to them and will be called with the defined settings when the configuration
* is parsed.
*/
class Configurable {
public:
/**
* Default ctor, does not subscribe to any context: you must manually do that by calling
* Configurable::subscribeContext().
*/
explicit Configurable();
/**
* Subscribes this instance to every context in the list.
*
* @note
* You clearly don't have to call Configurator::subscribeContext() anymore
* if you use this constructor.
*/
explicit Configurable(std::vector<string_t> contexts);
Configurable(const Configurable&);
Configurable& operator=(const Configurable&);
virtual ~Configurable();
/** Called whenever a cfg setting is encountered and parsed. */
virtual void setOption(string_t const& key, string_t const& value)=0;
/**
* All Configurables must provide some defaults that will be set when
* they're constructed.
*/
virtual void setDefaults() = 0;
/**
* Called when the config section is fully parsed, implementations
* can do the actual configuration here if needed.
*
* @note
* Sometimes this isn't really required as an implementation could configure
* itself on-the-fly as setOption() is called, but others might have dependant
* options.
*/
inline virtual void configure() { }
/** Is this instance subscribed to this configuration context? */
bool isSubscribedToContext(string_t const&);
protected:
friend class Configurator;
/** This instance will be called whenever the given context is encountered. */
void subscribeContext(string_t const&);
/**
* When a Configurable is subscribed to more than 1 context,
* this string can be used to determine the current context being parsed.
*/
string_t mCurrentCtx;
std::vector<string_t> mContexts;
void copy(const Configurable& src);
};
}
#endif
| true |
777ddd4799d7d022052f23fd6b938144a618d131 | C++ | lineCode/TXPK | /example/app/src/Main.cpp | UTF-8 | 2,708 | 2.796875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <SFML/Graphics.hpp>
#include "Atlas.hpp"
#include "CustomSprite.hpp"
#include "skeleton.hpp"
#define PI 3.14159265359f
#define DEG(x) (x / 2 * PI) * 360
#define RAD(x) (180 * x) / PI
int main()
{
sf::RenderWindow window(sf::VideoMode(450, 250), "TXPK Usage Example");
Atlas atlas;
if (!atlas.load("content/meta/skeleton.json"))
return 1;
std::vector<CustomSprite> attackSprites;
for(unsigned int i = SKELETON_ATTACK_1; i <= SKELETON_ATTACK_18; ++i)
attackSprites.push_back(atlas.getSprite(i));
std::vector<CustomSprite> dyingSprites;
for (unsigned int i = SKELETON_DEAD_1; i <= SKELETON_DEAD_15; ++i)
dyingSprites.push_back(atlas.getSprite(i));
sf::Clock clock;
float dt;
float attackElapsed = 0;
const float attackAnimTime = 2;
const float attackPart = attackAnimTime / attackSprites.size();
float dyingElapsed = 0;
const float dyingAnimTime = 1.5f;
const float dyingPart = dyingAnimTime / dyingSprites.size();
float rotation = 0;
float rotationSpeed = 0.1f;
while (window.isOpen())
{
sf::Event e;
while (window.pollEvent(e))
if (e.type == sf::Event::Closed)
window.close();
dt = clock.restart().asSeconds();
attackElapsed += dt;
dyingElapsed += dt;
rotation += (rotationSpeed * dt);
if (attackElapsed >= attackAnimTime)
attackElapsed = 0;
if (dyingElapsed >= dyingAnimTime)
dyingElapsed = 0;
if (rotation >= 2 * PI)
rotation = 0;
sf::RenderStates states;
states.transform.scale(4, 4);
window.clear(sf::Color(0xAD9B89FF));
CustomSprite& currentAttackSprite = attackSprites[attackElapsed / attackPart];
currentAttackSprite.setPosition(30, 30);
currentAttackSprite.setOrigin(currentAttackSprite.getWidth() / 2, currentAttackSprite.getHeight() / 2);
currentAttackSprite.setRotation(DEG(rotation));
CustomSprite& currentDyingSprite = dyingSprites[dyingElapsed / dyingPart];
currentDyingSprite.setPosition(85, 30);
currentDyingSprite.setOrigin(currentDyingSprite.getWidth() / 2, currentDyingSprite.getHeight() / 2);
currentDyingSprite.setRotation(DEG(rotation));
sf::RectangleShape rect;
rect.setSize(currentAttackSprite.getSize());
rect.setPosition(currentAttackSprite.getPosition());
rect.setFillColor(sf::Color(0x00000011));
rect.setOrigin(currentAttackSprite.getOrigin());
rect.setRotation(DEG(rotation));
window.draw(rect, states);
window.draw(currentAttackSprite, states);
rect.setSize(currentDyingSprite.getSize());
rect.setPosition(currentDyingSprite.getPosition());
rect.setFillColor(sf::Color(0x00000011));
rect.setOrigin(currentDyingSprite.getOrigin());
window.draw(rect, states);
window.draw(currentDyingSprite, states);
window.display();
}
return 0;
} | true |
feabed1b09f80e8fb7f78a82df83e61255d67643 | C++ | ahakouz17/Competitive-Programming-Practice | /Codeforces/D_100247.cpp | UTF-8 | 416 | 2.59375 | 3 | [
"MIT"
] | permissive | // solved: 2014-01-31 04:22:08
// https://codeforces.com/gym/100247/problem/D
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n;
string a, b, c, f = "";
cin >> n >> a >> b >> c;
for (int i = 0; i < n; i++)
{
if (b[i] == c[i])
f += c[i];
else
f += a[i];
}
cout << f;
return 0;
} | true |
1b16fba9442d79a8526f6fa1954ff1867ceb4d86 | C++ | rverma870/DSA-practice | /gfg/must do interview que/Recursion/JosephusProblem.cpp | UTF-8 | 492 | 2.828125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void solve(int idx,int n,vector<int>&cur_people,int k)
{
if(cur_people.size()==1)
{
return ;
}
idx= (idx+k)%cur_people.size();
cur_people.erase(cur_people.begin()+idx);
solve(idx,n,cur_people,k);
}
int josephus(int n, int k)
{
k--;
vector<int>cur_people(n);
for(int i=1;i<=n;i++)
cur_people[i-1]=i;
solve(0,n,cur_people,k);
return cur_people[0];
}
int main()
{
int n,k;
cin>>n>>k;
cout<<josephus(n,k);
}
| true |
9b2b26c5a73f9065a48f561eb0f17a4d39e58a5a | C++ | ehsanx/MatchItSE | /src/KM-Abadie.cpp | UTF-8 | 448 | 2.5625 | 3 | [] | no_license | #include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double cppKMsqSum(CharacterMatrix m, CharacterVector c, NumericVector w){
int N = m.nrow();
int P = m.ncol();
int K = c.length();
NumericVector km(K);
for (int k = 0; k < K; k++){ // geht mit der std vermutlich besser
for (int n = 0; n < N; n++){
for (int p = 0; p < P; p++){
if (m(n,p) == c(k)){
km(k) += w(n);
}
}
}
km(k) *= km(k);
}
return sum(km);
}
| true |
0cb0294cae1fcae52a13e3e3abc6cc1f34a732fa | C++ | SarthakArora23/xicpp | /swtuch_demo.cpp | UTF-8 | 555 | 2.703125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int dno;
cout<<"\n Enter day number :";
cin>>dno;
system("cls"); //clrscr();
switch(dno){
cout<<"Hello chetan...Thoda saa dhyan de";
case 1: cout<<"Monday";
break;
case 2: cout<<"Tuesday";
break;
case 3: cout<<"Wednesday";
break;
case 4: cout<<"Thursday";
break;
case 5: cout<<"Friday";
break;
case 6: cout<<"Saturday";
break;
case 7: cout<<"Sunday";
break;
default:
cout<<"\n Wrong Day number...Please try something valid";
}
return 0;
}
| true |
0824160d806b4a57d79d48c4f102865973692161 | C++ | iulian-manda/oop | /lab4/src/domain/Chocolate.cpp | UTF-8 | 375 | 3.265625 | 3 | [] | no_license | #include "Chocolate.h"
Chocolate::Chocolate(string name, string type, int price) {
this->name = name;
this->type = type;
this->price = price;
}
string Chocolate::get_name() {
return name;
}
string Chocolate::get_type() {
return type;
}
int Chocolate::get_price() {
return price;
}
void Chocolate::set_price(int price) {
this->price = price;
} | true |
41e4a477201682ab00673b105cfb77537dca091d | C++ | NX1125/cg-tf | /bullet.h | UTF-8 | 810 | 2.65625 | 3 | [
"MIT"
] | permissive | /*
* File: bullet.h
* Author: gg
*
* Created on 7 de dezembro de 2019, 01:09
*/
#ifndef BULLET_H
#define BULLET_H
#include "projectile.h"
#include "wfobj.h"
class bullet_t : public projectile_t {
private:
static wf_object_t* sModel;
bool enemy;
float radius = 10.0f;
float horizontal = 0;
float vertical = 0;
public:
bullet_t(const point3f& offset, const vector3f& velocity, bool enemy);
void setRadius(float radius) {
this->radius = radius;
}
void hit(obstacle_t* other) override;
void draw() const override;
float getRadius() const override {
return radius;
}
static void init(wf_object_loader_t& loader);
static void draw0() {
sModel->draw();
}
};
#endif /* BULLET_H */
| true |
f0f7c31cdbbe1e01812607958d256b2cc2b22066 | C++ | durkim/ter | /code/window.h | UTF-8 | 1,699 | 2.703125 | 3 | [] | no_license | /**
* \file window.h
* \brief représente l'interface graphique de l'application
* \author Fagard.C
* \version 0.1
* \date 14juin 2016
*
*
*
*/
#ifndef POLYOMINOES_WINDOW_H
#define POLYOMINOES_WINDOW_H
#include <QWidget>
#include <QGraphicsWidget>
#include <QPushButton>
#include <QLabel>
#include <QLCDNumber>
#include "Board.h"
#include "Board2.h"
/**
* @brief The Window class
* contient tous les widgets de l'application
*/
class Window : public QWidget {
Q_OBJECT
public slots:
/**
* @brief switchStartRestartBtn
* permet de lier le bouton start de l'apply et la fonction board::start().
*/
void switchStartRestartBtn();
/**
* @brief switchPausePlayBtn
* permet de lier le bouton start de l'apply et la fonction board::pause().
*/
void switchPausePlayBtn();
void switchB();
public:
/**
* @brief board
* le widget ou l'on dessine
*/
Board *boardT;
/**
* @brief board2
*
*/
Board2 *boardV;
/**
* @brief label
* nom de widget
*/
QLabel *label;
/**
* @brief startBtn
* bouton start
*/
QPushButton *startBtn;
/**
* @brief pauseBtn
* bouton pause
*/
QPushButton *pauseBtn;
/**
* @brief quitBtn
* bouton quit
*/
QPushButton *quitBtn;
/**
* @brief surfaceLcd
* affichage du score
*/
QLCDNumber *surfaceLcd;
/**
* @brief switchBtn
* switch pour passer en mode visualisation de polyominos
*/
QPushButton *switchBtn;
bool switchVisu=false;
public:/**
* @brief Window
* constructeur
*/
Window();
};
#endif //POLYOMINOES_WINDOW_H
| true |
27fcc681203e19d3f6e0711213677762591304a6 | C++ | iMeiji/C_Plus_Plus_Primer | /Chapter_04/Exercise_04_04/expression_evaluation.cpp | UTF-8 | 274 | 3.1875 | 3 | [
"Unlicense"
] | permissive | /**
* \file
* expression_evaluation.cpp
* \author
* Henrik Samuelsson
*/
#include <iostream>
using std::cout;
/**
* /brief
* Does an arithmetic calculation and prints the result.
*/
int main() {
cout << 12 / 3 * 4 + 5 * 15 + 24 % 4 / 2;
return 0;
}
| true |
2a83cf682f9da8b63183f9405d29425ff6b08819 | C++ | lionkor/GIP-19-20 | /02.05.cpp | UTF-8 | 733 | 3.359375 | 3 | [] | no_license | /*
Schreiben Sie ein C++ Programm, welches die Umrechnungen der vorigen
drei Aufgaben in einem einzigen Programm zusammenfasst.
*/
#include <iostream>
int main()
{
double input { 0 };
std::cout << "Ihre Eingabe: ? ";
std::cin >> input;
std::cout << "Ihre Auswahl der Umwandlung:" << std::endl
<< "1 - Celsius in Fahrenheit" << std::endl
<< "2 - Meter in Fuss" << std::endl
<< "3 - Euro in US Dollar" << std::endl;
int ch { 0 };
std::cin >> ch;
double ergebnis = ((input * 1.8 + 32.) * ((ch - 2) * (ch - 3) / 2.)) +
((input * 3.2808) * ((ch - 1) * (ch - 3) / -1.)) +
((input * 1.2957) * ((ch - 1) * (ch - 2) / 2.));
std::cout << "Das Ergebnis lautet: " << ergebnis << std::endl;
return 0;
}
| true |
f088c532d98f76466112ccc83588509613a867a3 | C++ | jimzrt/Tinfoil | /source/mode/mode.cpp | UTF-8 | 1,107 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "mode/mode.hpp"
#include "ui/framework/console_options_view.hpp"
#include "nx/fs.hpp"
namespace tin::ui
{
IMode::IMode(std::string name) :
m_name(name)
{
}
Category::Category(std::string name) :
m_name(name)
{
}
void Category::AddMode(std::unique_ptr<IMode> mode)
{
m_modes.push_back(std::move(mode));
}
void Category::OnSelected()
{
m_currentMode = nullptr;
tin::ui::ViewManager& manager = tin::ui::ViewManager::Instance();
auto view = std::make_unique<tin::ui::ConsoleOptionsView>();
view->AddEntry(m_name, tin::ui::ConsoleEntrySelectType::HEADING, nullptr);
view->AddEntry("", tin::ui::ConsoleEntrySelectType::NONE, nullptr);
for (auto& mode : m_modes)
{
auto modeSelected = [&] ()
{
m_currentMode = mode.get();
mode->OnSelected();
};
view->AddEntry(mode->m_name, tin::ui::ConsoleEntrySelectType::SELECT, modeSelected);
}
manager.PushView(std::move(view));
}
} | true |
bf1c66158ea4b1b8e053a3c2e9dad80003f30dc5 | C++ | nicholasdavies/ogwrangler | /src/lookup.cpp | UTF-8 | 7,771 | 2.53125 | 3 | [] | no_license | #include "lookup.h"
#include "code.h"
#include <algorithm>
#include <numeric>
#include <Rcpp.h>
using namespace std;
using namespace Rcpp;
Lookup::Lookup(Rcpp::DataFrame& d, Rcpp::DataFrame& d_code_names, Rcpp::DataFrame& d_metrics)
{
// Set geo names
geos = as<vector<string>>(d.names());
// Set codes and crmap
codes.assign(d.size(), vector<uint32_t>(d.nrows(), 0));
crmap.assign(d.size(), vector<coderow>(d.nrows(), coderow()));
for (unsigned int col = 0; col < d.size(); ++col)
{
StringVector s = d[col];
for (unsigned int row = 0; row < s.size(); ++row)
{
// TODO map_ONS on String instead of string
codes[col][row] = map_ONS(as<string>(s[row]));
crmap[col][row].c = codes[col][row];
crmap[col][row].v = row;
}
// sort crmap for this column
sort(crmap[col].begin(), crmap[col].end());
}
// Set code names
names.assign(d_code_names.nrows(), codename());
StringVector code_col = d_code_names[0];
StringVector name_col = d_code_names[1];
for (unsigned int row = 0; row < names.size(); ++row)
{
names[row].c = map_ONS(as<string>(code_col[row]));
names[row].v = as<string>(name_col[row]);
}
sort(names.begin(), names.end());
// Set metrics
if (d_metrics.nrows() != codes[0].size())
stop("d and d_metrics must have same number of rows.");
code_col = d_metrics[0];
for (unsigned int row = 0; row < code_col.size(); ++row)
if (codes[0][row] != map_ONS(as<string>(code_col[row])))
stop("d_metrics not in same row order as d.");
metric_names = as<vector<string>>(d_metrics.names());
metric_names.erase(metric_names.begin());
for (unsigned int col = 1; col < d_metrics.size(); ++col)
metrics.push_back(as<vector<double>>(d_metrics[col]));
}
uint32_t Lookup::LookUpKey(uint32_t key, const string& geo)
{
// Find geo column to index
auto column = find(geos.begin(), geos.end(), geo);
if (column == geos.end())
stop("Could not find geo %s in lookup.", geo.c_str());
// Find lookup row
auto row = lower_bound(crmap[0].begin(), crmap[0].end(), key);
if (row == crmap[0].end() || row->c != key)
stop("Could not find key %d in lookup.", key);
// Return requested code
return codes[column - geos.begin()][row - crmap[0].begin()];
}
StringVector Lookup::FindName(const regex& r)
{
StringVector results;
for (auto n = names.begin(); n != names.end(); ++n)
if (regex_search(n->v, r))
results.push_back(unmap_ONS(n->c));
return results;
}
vector<String> Lookup::GetCodes(const std::string& geo)
{
// Locate requested geography
auto geo_it = find(geos.begin(), geos.end(), geo);
if (geo_it == geos.end())
stop("Could not find geo %s.", geo.c_str());
size_t geo_i = geo_it - geos.begin();
// Get codes
// TODO Again, another great reason for having a lookup of codes by geo.
vector<uint32_t> contents(1, crmap[geo_i][0].c);
for (size_t j = 1; j < crmap[geo_i].size(); ++j)
if (crmap[geo_i][j].c != contents.back())
contents.push_back(crmap[geo_i][j].c);
vector<String> results(contents.size(), "");
for (size_t j = 0; j < contents.size(); ++j)
results[j] = unmap_ONS(contents[j]);
return results;
}
String Lookup::MatchName(const std::string& name, const std::string& geo)
{
// Locate requested geography
auto geo_it = find(geos.begin(), geos.end(), geo);
if (geo_it == geos.end())
stop("Could not find geo %s.", geo.c_str());
size_t geo_i = geo_it - geos.begin();
for (auto n = names.begin(); n != names.end(); ++n)
{
// TODO this is horribly inefficient.
// Should be storing names by geo rather than all in one vector.
if (name_match(n->v, name))
{
auto x = lower_bound(crmap[geo_i].begin(), crmap[geo_i].end(), n->c);
if (x != crmap[geo_i].end() && x->c == n->c)
return unmap_ONS(n->c);
}
}
stop("Could not find match for name %s in geo %s.", name.c_str(), geo.c_str());
return String();
}
StringVector Lookup::GetNames(const vector<uint32_t>& mapped_codes)
{
// TODO overhaul nomenclature of mapped_codes argument versus codes class member.
// TODO class member should not be called codes.
StringVector results(mapped_codes.size(), "");
for (unsigned int i = 0; i < mapped_codes.size(); ++i)
{
auto x = lower_bound(names.begin(), names.end(), mapped_codes[i]);
if (x == names.end() || x->c != mapped_codes[i])
stop("Could not find code %d in lookup.", mapped_codes[i]);
results[i] = x->v;
}
return results;
}
NumericVector Lookup::GetMetrics(const vector<uint32_t>& mapped_codes, const String& metric)
{
NumericVector results(mapped_codes.size(), 0);
// Locate requested metric
string metric_str = metric;
auto metric_it = find(metric_names.begin(), metric_names.end(), metric_str);
if (metric_it == metric_names.end())
stop("Could not find metric %s.", metric_str.c_str());
size_t metric_i = metric_it - metric_names.begin();
// Accumulate metrics for all codes
// TODO make more efficient?
for (unsigned int i = 0; i < mapped_codes.size(); ++i)
{
for (unsigned int j = 0; j < geos.size(); ++j)
{
auto range = equal_range(crmap[j].begin(), crmap[j].end(), mapped_codes[i]);
if (range.first < range.second)
{
results[i] = accumulate(metrics[metric_i].begin() + (range.first - crmap[j].begin()),
metrics[metric_i].begin() + (range.second - crmap[j].begin()), 0.0);
break;
}
if (j == geos.size() - 1)
stop("Could not find code %s in lookup.", unmap_ONS(mapped_codes[i]));
}
}
return results;
}
StringVector Lookup::TranslateGeo(const std::vector<uint32_t>& mapped_codes, const String& geo_to)
{
StringVector results(mapped_codes.size(), "");
// Locate requested geography
string geo_str = geo_to;
auto geo_it = find(geos.begin(), geos.end(), geo_str);
if (geo_it == geos.end())
stop("Could not find geo %s.", geo_str.c_str());
size_t geo_i = geo_it - geos.begin();
// Translate codes
// TODO make more efficient
for (unsigned int i = 0; i < mapped_codes.size(); ++i)
{
for (unsigned int j = 0; j < geos.size(); ++j)
{
auto range = equal_range(crmap[j].begin(), crmap[j].end(), mapped_codes[i]);
if (range.first < range.second)
{
results[i] = unmap_ONS(codes[geo_i][range.first->v]);
break;
}
if (j == geos.size() - 1)
stop("Could not find code %s in lookup.", unmap_ONS(mapped_codes[i]));
}
}
return results;
}
SEXP Lookup::GetProperties(const StringVector& code, const String& property)
{
// Map codes
vector<uint32_t> mapped_codes(code.size(), 0);
for (unsigned int i = 0; i < code.size(); ++i)
mapped_codes[i] = map_ONS(as<string>(code[i]));
string property_str = property;
if (property_str == "name")
return wrap(GetNames(mapped_codes));
else if (find(metric_names.begin(), metric_names.end(), property_str) != metric_names.end())
return wrap(GetMetrics(mapped_codes, property));
else if (find(geos.begin(), geos.end(), property_str) != geos.end())
return wrap(TranslateGeo(mapped_codes, property));
stop("Could not find requested property %s.", property_str.c_str());
return wrap(R_NilValue);
}
| true |
a8b06a39391615f54261e1fc825eecc6ae08ef4e | C++ | SHEReunice/Acwing | /基础算法课/785. 快速排序/Acwing 785. 快速排序/main.cpp | UTF-8 | 789 | 3.09375 | 3 | [] | no_license | //
// main.cpp
// Acwing 785. 快速排序
//
// Created by Eunice on 2021/7/25.
// Copyright © 2021 Eunice. All rights reserved.
//
#include <iostream>
using namespace std;
int n;
int q[100005];
void quick_sort(int q[], int l , int r);
int main(int argc, const char * argv[]) {
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%d",&q[i]);
}
quick_sort(q,0,n-1);
for(int i = 0; i < n; i++)
{
printf("%d ",q[i]);
}
return 0;
}
void quick_sort(int q[], int l, int r)
{
if(l >= r) return;
int mid = q[(l+r)/2],i = l-1, j = r+1;
while(i < j)
{
do i++; while(q[i] < mid);
do j--; while(q[j] > mid);
if(i < j) swap(q[i], q[j]);
}
quick_sort(q, l, j);
quick_sort(q, j+1, r);
}
| true |
dda3f5309456f7a19a54f4664289e350c09a228e | C++ | KuzminaIrina/tg_mpei_course | /1019_Next_Greater_Node_In_Linked_List.cpp | UTF-8 | 732 | 3.109375 | 3 | [] | no_license | https://leetcode.com/problems/next-greater-node-in-linked-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
ListNode *x = head, *prev = nullptr, *nxt;
while(x)
{
nxt = x->next;
x->next = prev;
prev = x;
x = nxt;
}
x = prev;
stack<int> s;
vector<int>res;
while(x)
{
while(!s.empty() && s.top() <= x->val)
s.pop();
if(s.empty())
res.push_back(0);
else
res.push_back(s.top());
s.push(x->val);
x = x->next;
}
reverse(res.begin(), res.end());
return res;
}
};
| true |
9d433da96746446a38bc1e375e9862d698975b5e | C++ | jr-b-reiterer/ROSPlan | /rosplan_planning_system/src/EsterelPlan.cpp | UTF-8 | 2,401 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | #include "rosplan_planning_system/EsterelPlan.h"
#include <vector>
#include <string>
#include <ostream>
std::ostream& operator<<(std::ostream& os, const KCL_rosplan::StrlEdge& edge)
{
os << "\t[Esterel Edge] - ";
switch (edge.signal_type)
{
case KCL_rosplan::ACTION:
os << "Action: ";
break;
case KCL_rosplan::CONDITION:
os << "Condition: ";
break;
case KCL_rosplan::TIME:
os << "Time: ";
break;
};
os << edge.edge_name << (edge.active ? " ACTIVE" : " INACTIVE") << "; Addr: " << &edge << std::endl;
os << "\t\tSources: " << std::endl;
for (std::vector<KCL_rosplan::StrlNode*>::const_iterator ci = edge.sources.begin(); ci != edge.sources.end(); ++ci)
{
os << "\t\t\t" << (*ci)->node_name << std::endl;
}
os << "\t\tSinks: " << std::endl;
for (std::vector<KCL_rosplan::StrlNode*>::const_iterator ci = edge.sinks.begin(); ci != edge.sinks.end(); ++ci)
{
os << "\t\t\t" << (*ci)->node_name << std::endl;
}
os << "\t\tExternal conditions: " << std::endl;
for (std::vector<rosplan_knowledge_msgs::KnowledgeItem>::const_iterator ci = edge.external_conditions.begin(); ci != edge.external_conditions.end(); ++ci)
{
const rosplan_knowledge_msgs::KnowledgeItem& ki = *ci;
os << "\t\t\t";
if (ki.is_negative)
{
os << "(not ";
}
os << "(" << ki.attribute_name << " ";
for (std::vector<diagnostic_msgs::KeyValue>::const_iterator ci = ki.values.begin(); ci != ki.values.end(); ++ci)
{
os << (*ci).value << " ";
}
if (ki.is_negative)
{
os << ")";
}
os << ")" << std::endl;
}
return os;
};
std::ostream& operator<<(std::ostream& os, const KCL_rosplan::StrlNode& node)
{
os << "[Esterel Node] - [" << node.node_id << "] [Dispatched=" << (node.dispatched ? "TRUE" : "FALSE") << "] [COMPLETED=" << (node.completed ? "TRUE" : "FALSE") << "]; Addr: " << &node << std::endl;
os << "Input:" << std::endl;
for (unsigned int i = 0; i < node.input.size(); ++i)
{
//os << "\t" << node.input[i]->edge_name << " - " << (node.input[i]->active ? "ACTIVATED" : "INACTIVE") << std::endl;
os << *node.input[i] << std::endl;
}
os << "Output:" << std::endl;
for (unsigned int i = 0; i < node.output.size(); ++i)
{
//os << "\t" << node.output[i]->edge_name << " - " << (node.output[i]->active ? "ACTIVATED" : "INACTIVE") << std::endl;
os << *node.output[i] << std::endl;
}
os << "[\Esterel Node]" << std::endl;
return os;
};
| true |
37121709ab505abbb9d757210ff1a67a912afe14 | C++ | luotian/design_patterns_cpp | /src/bridge/bridge_lib.h | UTF-8 | 1,864 | 2.78125 | 3 | [] | no_license | #pragma once
#include "../base_def.h"
class MessagerImpl
{
public:
virtual void PlaySound() = 0;
virtual void DrawShape() = 0;
virtual void WriteText() = 0;
virtual void Connect() = 0;
virtual ~MessagerImpl() {}
};
class Messager
{
protected:
MessagerImpl* messagerImpl;
public:
virtual void Login(string username, string passowrd) = 0;
virtual void SendMessage(string message) = 0;
virtual void SendPicture(string image) = 0;
Messager(MessagerImpl* imp) { messagerImpl = imp; }
virtual ~Messager() {}
};
// 平台实现
class PCMessageImpl : public MessagerImpl
{
virtual void PlaySound()
{
// do...
}
virtual void DrawShape()
{
// do...
}
virtual void WriteText()
{
// do...
}
virtual void Connect()
{
// do...
}
};
class MobileMessageImpl : public MessagerImpl
{
virtual void PlaySound()
{
// do...
}
virtual void DrawShape()
{
// do...
}
virtual void WriteText()
{
// do...
}
virtual void Connect()
{
// do...
}
};
// 业务功能
class MessagerLite : public Messager
{
public:
virtual void Login(string username, string passowrd)
{
messagerImpl->Connect();
}
virtual void SendMessage(string message)
{
messagerImpl->WriteText();
}
virtual void SendPicture(string image)
{
messagerImpl->DrawShape();
}
};
class MessagerPerfect : public Messager
{
public:
virtual void Login(string username, string passowrd)
{
messagerImpl->PlaySound();
messagerImpl->Connect();
}
virtual void SendMessage(string message)
{
messagerImpl->WriteText();
}
virtual void SendPicture(string image)
{
messagerImpl->DrawShape();
}
};
| true |
e06e2c22677a166323cfe6d1fa492e4861de3c9b | C++ | ashlamp08/Compiler | /Reference/esil/typeTable.cpp | UTF-8 | 1,700 | 3.625 | 4 | [] | no_license | #include "typeTable.h"
#include <iostream>
int typeNode::count = 0;
typeNode::typeNode(std::string name) {
TYPE_NAME = name;
ENTRY = nullptr;
NEXT = nullptr;
INDEX = -1;
}
// Destructor
typeNode::~typeNode() {
if (isDefinition)
delete ENTRY;
}
//
typeNode *typeNode::install(std::string name, typeNode *structure) {
typeNode *last = this;
for (typeNode *i = this->NEXT; i != nullptr; i = i->NEXT) {
if (name.compare(i->TYPE_NAME) == 0)
return nullptr;
last = i;
}
typeNode *temp = new typeNode(name);
temp->ENTRY = structure;
temp->isDefinition = true;
last->NEXT = temp;
return temp;
}
typeNode *typeNode::lookUp(std::string name) {
for (typeNode *i = this; i != nullptr; i = i->NEXT) {
if (name.compare(i->TYPE_NAME) == 0)
return i;
}
return nullptr;
}
void typeNode::print() {
std::cout << "Valid Data Types:\n";
for (typeNode *i = this; i != nullptr; i = i->NEXT) {
std::cout <<i<<":"<<i->TYPE_NAME;
if (i->ENTRY) {
std::cout << ":\t{";
for (typeNode *j = i->ENTRY; j != nullptr; j = j->NEXT)
std::cout <<j<<":"<<j->INDEX<<":("<< j->ENTRY<<":"<<j->ENTRY->TYPE_NAME << ") " << j->TYPE_NAME << ((j->NEXT) ? ',' : '}');
}
std::cout << '\n';
}
}
// Getter Functions
std::string typeNode::getTypeName() {return TYPE_NAME;}
typeNode *typeNode::getNext() {return NEXT;}
typeNode *typeNode::getEntry() {return ENTRY;}
int typeNode::getIndex() {return INDEX;}
// Setter Functions
void typeNode::setNext(typeNode *next) {NEXT = next;}
void typeNode::setEntry(typeNode *entry) {ENTRY = entry;}
void typeNode::setIndex(int index) {INDEX = index;}
// Function to Return total Number of object currently in Memory
int typeNode::getCount() {return count;} | true |
62a7291ab79a0080259bb6cfe907c405076423bd | C++ | SergeyRudyanskiy/AlgorithnsAndDataStructures | /AlgorithnsAndDataStructures/Search_Element_Ternary_Recursive.hpp | UTF-8 | 1,157 | 3.796875 | 4 | [] | no_license | #pragma once
template <typename Iterator, typename ElementType>
Iterator search_element_ternary_recursive(Iterator iterator_begin, Iterator iterator_end, const ElementType key_value) {
static const Iterator iterator_not_found = iterator_end;
ptrdiff_t distance = std::distance(iterator_begin, iterator_end);
Iterator iterator_midle_left = iterator_begin + distance / 3;
Iterator iterator_midle_right = iterator_end - distance / 3;
if (iterator_begin < iterator_end) {
if (*iterator_midle_left == key_value) { return iterator_midle_left; }
else if (*iterator_midle_right == key_value) { return iterator_midle_right; }
if (*iterator_midle_left > key_value) { return search_element_ternary_recursive(iterator_begin, iterator_midle_left, key_value); }
else if (*iterator_midle_right < key_value) { return search_element_ternary_recursive(iterator_midle_right + 1, iterator_end, key_value); }
else { return search_element_ternary_recursive(iterator_midle_left + 1, iterator_midle_right, key_value); }
}
return iterator_not_found;
} | true |
0aa18807015a181bdd9a0c8c7ffdf65e35de93c2 | C++ | Sadman007/DevSkill-Programming-Course---Basic---Public-CodeBank | /DevSkill_CP/Intermediate/Batch 13/class_28/code.cpp | UTF-8 | 1,284 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int T, cs = 1;
scanf("%d", &T);
while(T--)
{
int n, M;
scanf("%d %d", &n, &M);
vector<int>c(n, 0), freq(n, 0);
for (int i = 0; i < n; i++)
scanf("%d", &c[i]);
for (int i = 0; i < n; i++)
scanf("%d", &freq[i]);
vector<int> dp(M + 1, 0);
dp[0] = 1;
for (int i = 0; i < n; i++)
{
// c[i], freq[i]
vector<int> howManyCoins(M + 1, 0); // c[i] coin koyta use korsi
for (int curr = c[i]; curr <= M; curr++)
{
if (dp[curr] == 0 && howManyCoins[curr - c[i]] < freq[i])
{
dp[curr] |= dp[curr - c[i]];
howManyCoins[curr] = howManyCoins[curr - c[i]] + (dp[curr] > 0);
}
}
}
int tot = 0;
for (int i = 1; i <= M; i++) tot += dp[i];
printf("Case %d: %d\n", cs++, tot);
}
return 0;
}
/**
vector<int> dp(W + 1, 0);
for (int i = 0; i < n; i++)
{
for (int w = W; w >= 1; w--)
{
dp[w] = max(dp[w], dp[w - weight[i]] + v[i]);
}
}
int res = 0;
for (int i = 0; i <= W; i++) res = max(res, dp[i]);
cout << res << "\n";
**/
| true |