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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f5056c6d6a063f107873a89bbe5c712842ac6a1a | C++ | mouchtaris/byrror | /src/stream.h | UTF-8 | 1,631 | 2.8125 | 3 | [] | no_license | #pragma once
#include "pig.h"
#include <optional>
#include <type_traits>
namespace stream {
template <typename T> struct
StreamOps;
template <typename T> struct
StreamOf {
using type = StreamOps<std::decay_t<T>>;
};
template <typename T> using
stream_of_t =
typename StreamOf<std::decay_t<T>>::type;
template <typename T> struct
StreamOpsConstructor {
template <typename U>
stream_of_t<T> operator () (U&& self) const
{ return { std::forward<U>(self) }; }
};
template <typename T> struct
StreamOpsConstructorOf {
using type = StreamOpsConstructor<std::decay_t<T>>;
};
template <typename T> using
constructor_of_t =
typename StreamOpsConstructorOf<std::decay_t<T>>::type;
template <typename T> auto
constructor()
-> constructor_of_t<T>
{ return { }; }
template <typename T> auto
ops(T&& self)
-> stream_of_t<T>
{ return constructor<T>()(std::forward<T>(self)); }
template <typename T> using
element_t =
typename stream_of_t<std::decay_t<T>>::Element;
template <typename T> using
head_t =
std::optional<std::reference_wrapper<element_t<T>>>;
template <typename T> auto
head(T&& self)
-> head_t<T>
{ return ops(std::forward<T>(self)).head(); }
template <typename T> auto
tail(T&& self)
{ return ops(std::forward<T>(self)).tail(); }
}
PIG_WRAP(stream::StreamOps);
PIG_WRAP(stream::StreamOf);
PIG_WRAP(stream::StreamOpsConstructor);
PIG_WRAP(stream::StreamOpsConstructorOf);
| true |
ce2a8ddec5681197550a9e8d75c07abd577acb2e | C++ | andrie/SuppDists | /src/disabled/kruskal_wallace.cpp | UTF-8 | 7,193 | 2.859375 | 3 | [] | no_license | // KRUSKAL WALLACE *************************************************************
/* Kruskal-Wallis and normal scores distributions
approximated with beta.
*/
double KruskalWallisMaxU(
int c,
int n
)
{
return double(c-1)+1.0/double(n-(c-1));
}
// Probability function for R
DISTS_API void pKruskalWallisR(
double *Hp,
int *cp,
int *np,
double *Up,
int *doNormalScorep,
int *Np,
double *valuep
)
{
int N=*Np;
int i;
for (i=0;i<N;i++)
valuep[i]=pKruskal_Wallis(Hp[i],cp[i],np[i],Up[i],(bool)doNormalScorep[i]);
}
double pKruskal_Wallis(
double H, // The Statistic
int c, // number of treatments
int n, // Total number of observations
double U, // Sum (1/ni), where ni is numb obs for each treatment
bool doNormalScore // do normal scores
)
{
double C=c;
double N=n;
if (H<0.0 || U<=0 || U>KruskalWallisMaxU(c,n))
return NA_REAL;
double V=(doNormalScore)?varNormalScores(N,C,U):varKruskal_Wallis(N,C,U);
double d=((N-C)*(C-1.0)-V)/((N-1.0)*V);
double f1=(C-1.0)*d;
double f2=(N-C)*d;
return pbeta(H/(N-1.0),f1,f2,true,false);
}
DISTS_API void uKruskalWallisR(
double *Hp,
int *cp,
int *np,
double *Up,
int *doNormalScorep,
int *Np,
double *valuep
)
{
int N=*Np;
int i;
for (i=0;i<N;i++)
valuep[i]=qKruskal_Wallis(Hp[i],cp[i],np[i],Up[i],(bool)doNormalScorep[i]);
}
double qKruskal_Wallis(
double H, // The Statistic
int c, // number of treatments
int n, // Total number of observations
double U, // Sum (1/ni), where ni is numb obs for each treatment
bool doNormalScore // do normal scores
)
{
if (H<0.0 || U<=0 || U>KruskalWallisMaxU(c,n))
return NA_REAL;
return 1.0-pKruskal_Wallis(H,c,n,U,doNormalScore);
}
DISTS_API void qKruskalWallisR(
double *pp,
int *cp,
int *np,
double *Up,
int *doNormalScorep,
int *Np,
double *valuep
)
{
int N=*Np;
int i;
for (i=0;i<N;i++)
valuep[i]=xKruskal_Wallis(pp[i],cp[i],np[i],Up[i],(bool)doNormalScorep[i]);
}
double xKruskal_Wallis(
double P,
int c, // number of treatments
int n, // Total number of observations
double U, // Sum (1/ni), where ni is numb obs for each treatment
bool doNormalScore // do normal scores
)
{
double C=c;
double N=n;
if (0>P || P>1 || U<=0 || U>KruskalWallisMaxU(c,n))
return NA_REAL;
double V=(doNormalScore)?varNormalScores(N,C,U):varKruskal_Wallis(N,C,U);
double d=((N-C)*(C-1.0)-V)/((N-1.0)*V);
double f1=(C-1.0)*d;
double f2=(N-C)*d;
return (N-1.0)*qbeta(P,f1,f2,true,false);
}
// Statistics for Kruskal_Wallis and Normal Scores
DISTS_API void sKruskalWallisR(
int *cp,
int *np,
double *Up,
int *doNormalScorep,
int *Np,
double *varp,
double *modep,
double *thirdp,
double *fourthp
)
{
int N=*Np;
int i;
for (i=0;i<N;i++) {
sKruskal_Wallis(cp[i],np[i],Up[i],(bool)doNormalScorep[i],modep+i,thirdp+i,fourthp+i);
if (Up[i]<=0 || Up[i]>KruskalWallisMaxU(cp[i],np[i])){
varp[i]=NA_REAL;
}
else {
varp[i]=(doNormalScorep[i])?varNormalScores(np[i],cp[i],Up[i]):varKruskal_Wallis(np[i],cp[i],Up[i]);
}
}
}
void sKruskal_Wallis(
int c,
int n,
double U,
bool doNormalScore,
double *mode,
double *third, // Central moments
double *fourth
)
{
int nPoints=128;
if (U<=0) {
*mode=NA_REAL;
*third=NA_REAL;
*fourth=NA_REAL;
}
else {
double minH=xKruskal_Wallis(0.01,c,n,U,doNormalScore);
double maxH=xKruskal_Wallis(0.99,c,n,U,doNormalScore);
double md=0.0;
double maxValue=0.0;
double m3=0.0;
double m4=0.0;
double sum=0.0;
double mean=(double)(c-1);
double delta=(maxH-minH)/(double)(nPoints-1);
double H=minH;
while (nPoints--) {
double val=fKruskal_Wallis(H,c,n,U,doNormalScore);
if (maxValue<val) {
maxValue=val;
md=H;
}
sum+=val;
double h=H-mean;
m3+=val*h*h*h;
m4+=val*h*h*h*h;
H+=delta;
}
m3/=sum;
m4/=sum;
*mode=md;
*third=m3;
*fourth=m4;
}
}
DISTS_API void dKruskalWallisR(
double *Hp,
int *cp,
int *np,
double *Up,
int *doNormalScorep,
int *Np,
double *valuep
)
{
int N=*Np;
int i;
for (i=0;i<N;i++)
valuep[i]=fKruskal_Wallis(Hp[i],cp[i],np[i],Up[i],(bool)doNormalScorep[i]);
}
// Use numerical derivitive
double fKruskal_Wallis(
double H, // The Statistic
int c, // number of treatments
int n, // Total number of observations
double U, // Sum (1/ni), where ni is numb obs for each treatment
bool doNormalScore // do normal scores
)
{
double delta=0.001;
return (pKruskal_Wallis(H+delta,c,n,U,doNormalScore)-
pKruskal_Wallis(H,c,n,U,doNormalScore))/delta;
}
/*
Kruskal Wallis tau random numbers
*/
DISTS_API void rKruskalWallisR(
double *randArrayp,
int *Np,
int *Mp, // size of parameter arrays
int *cp,
int *np,
double *Up,
bool *doNormalScorep
)
{
int N=*Np;
int M=*Mp;
int D;
int j;
int k;
int loc;
int cloc;
double *tArray;
if (M==1)
rKruskal_Wallis(randArrayp,N,*cp,*np,*Up,(bool)*doNormalScorep);
else { // Allow for random values for each element of nu and lambda
D=(N/M)+((N%M)?1:0);
tArray=(double *)S_alloc((long)D,sizeof(double));
loc=0;
for (j=0;j<M;j++) {
rKruskal_Wallis(tArray,D,cp[j],np[j],Up[j],doNormalScorep[j]);
for (k=0;k<D;k++) {
cloc=loc+k*M;
if (cloc<N)
randArrayp[cloc]=tArray[k];
else break;
}
loc++;
}
}
}
void rKruskal_Wallis(
double* randArray,
int N, // number of samples
int c, // number of treatments
int n, // Total number of observations
double U, // Sum (1/ni), where ni is numb obs for each treatment
bool doNormalScore // do normal scores
)
{
GetRNGstate();
for (int i=0;i<N;i++){
randArray[i]=(double)xKruskal_Wallis(unif_rand(),c,n,U,doNormalScore);
}
PutRNGstate();
}
/* Kruskal-Wallis variance
Wallace, DL. (1959). Simplified beta-approximations to
the Kruskal-Wallis H test. JASA 54, 225-230. Equation 6.2 */
double varKruskal_Wallis(
double N,
double C,
double U
)
{
double f=2.0*(C-1.0);
f-=0.4*(3.0*C*C-6.0*C+N*(2.0*C*C-6.0*C+1.0))/(N*(N+1.0));
f-=1.2*U;
return f;
}
/* Normal scores variance. See LU, HT & Smith, PJ. (1979).
Distribution of the normal scores statistic for nonparametric
one-way analysis of variance. JASA. 74, 715-772 */
double varNormalScores(
double N,
double C,
double U
)
{
double alpha=0.375;
double NP=N+1.0;
double NM=N-1.0;
double NC=N-C;
double CM=C-1.0;
double den=1.0-2.0*alpha;
long n=(long)(0.1+N/2.0);
double e2=0.0;
double e4=0.0;
for (long i=1L;i<=n;i++) {
double e=qnorm(((double)i-alpha)/(N+den),0,1,true,false);
e*=e;
e2+=e;
e4+=e*e;
}
e2*=4.0*e2;
double g=(NP*N*NM*NM*2.0*e4-3.0*NM*NM*NM*e2)/(NM*(N-2.0)*(N-3.0)*e2);
double v=2*CM*NC/NP;
v-=g*(NP*C*C+2.0*CM*NC-N*NP*U)/(N*NP);
return(v);
}
| true |
5c647d5229f457d61c660919bf08feab460ef3af | C++ | wizard00/PlayandTest | /powerof3.cpp | UTF-8 | 479 | 3.046875 | 3 | [] | no_license | #include <math.h>
#include <iostream>
using namespace std;
bool isPowerOfThree(int n);
int main(int argc, char const *argv[])
{
cout<<isPowerOfThree(243);
return 0;
}
bool isPowerOfThree(int n) {
if(n == 1)
return true;
double logs;
logs = log((double)n)/log(3);
cout<<fmod(logs,1)<<endl;
cout<<(fmod(logs,1)==1)<<endl;
cout<<logs<<endl;
cout<<(int)logs<<endl;
return (int)logs==logs;
}
| true |
ebbf11e4e162b6640072e95647b68e61a4493896 | C++ | rosekc/acm | /contest/2017/NanNingOnline/A.cpp | UTF-8 | 944 | 2.703125 | 3 | [] | no_license | //2017-09-24-14.42
//A
#include <bits/stdc++.h>
using namespace std;
double a[5][5];
int s[100000];
char buf[999999];
void cal1() {
gets(buf);
char *t = strtok(buf, " ");
int i = 0;
//cout << t << endl;
while (t != NULL) {
sscanf(t, "%d", &s[i]);
//cout << s[i] << endl;
i++;
t = strtok(NULL, " ");
}
double ans = 1;
//cout << i << endl;
for (int j = 0; j < i - 1; j++) {
//cout << s[j] <<endl;
ans *= a[s[j]][s[j + 1]];
//cout <<ans << endl;
}
printf("%.8f\n", ans);
}
void cal2() {
int t;
cin >> t;
double p = 1;
double ans = 0;
while (p >= 1e-9) {
ans += p;
p *= a[t][t];
}
printf("%.8f\n", ans);
}
int main() {
for (int i = 1; i <= 4; i++) {
for(int j = 1; j <= 4; j++) {
cin >> a[i][j];
}
}
getchar();
cal1();
cal1();
cal2();
cal2();
}
| true |
b84421c69b468ecfa82c80b59e46546fa6e2d826 | C++ | triphan2k3/CP_Train | /SPOJ/NKLINEUP.cpp | UTF-8 | 1,272 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int N=1e5;
int a[N];
int ma[N];
int mi[N];
int n;
int getmax(int l,int r)
{
int res=a[r];
while (l<=r)
{
int k=r-r&(-r);
if (r-(r&(-r))<l-1)
res=max(res,a[r--]);
else
{
res=max(res,ma[r]);
r-=r&(-r);
}
}
return res;
}
int getmin(int l,int r)
{
int res=a[r];
while (l<=r)
{
if (r-(r&(-r))<l-1)
res=min(res,a[r--]);
else
{
res=min(res,mi[r]);
r-=r&(-r);
}
}
return res;
}
void updatemax(int x)
{
int val=a[x];
while (x<=n)
{
ma[x]=max(ma[x],val);
x+=x&(-x);
}
}
void updatemin(int x)
{
int val=a[x];
while (x<=n)
{
mi[x]=min(mi[x],val);
x+=x&(-x);
}
}
int main()
{
int q;
ifstream f ("test.inp");
f >> n >> q;
mi[0]=1e7;
for (int i=1;i<=n;i++)
{
f >> a[i];
ma[i]=0;
mi[i]=1e7;
}
for (int i=1;i<=n;i++)
{
updatemax(i);
updatemin(i);
}
for (int i=1;i<=q;i++)
{
int u,v;
f >> u >> v;
int res=getmax(u,v)-getmin(u,v);
cout <<res << "\n";
}
}
| true |
e41ac14eec8866b38785d6bb9399a4a844c58145 | C++ | Smoria/RayTracer | /Code/Projects/RayTracer/sources/Bitmap.cpp | UTF-8 | 1,560 | 3.09375 | 3 | [] | no_license | #include <cstdio>
#include "Bitmap.h"
#include "Macroses.h"
const Bitmap& Bitmap::operator=(Bitmap&& uref)
{
SAFE_ARRAY_DELETE(m_pData);
m_width = uref.m_width;
m_height = uref.m_height;
m_pData = uref.m_pData;
uref.m_pData = nullptr;
return *this;
}
const Bitmap& Bitmap::operator=(const Bitmap& ref)
{
if (this != &ref)
{
SAFE_ARRAY_DELETE(m_pData);
m_width = ref.m_width;
m_height = ref.m_height;
const size_t bytesCount = m_width * m_height * sizeof(ColorsUnion);
if (bytesCount > 0)
{
m_pData = static_cast<ColorsUnion*>(malloc(bytesCount));
memcpy(m_pData, ref.m_pData, bytesCount);
}
}
return *this;
}
Bitmap::Bitmap(const std::string&)
{
throw std::exception();
}
Bitmap::Bitmap() :
m_width(0),
m_height(0),
m_pData(nullptr)
{}
Bitmap::Bitmap(const Bitmap& ref) :
m_width(ref.m_width),
m_height(ref.m_height),
m_pData(ref.m_width * ref.m_height > 0 ? new ColorsUnion[ref.m_width*ref.m_height] : nullptr)
{}
Bitmap::Bitmap(Bitmap&& uref) :
m_width(uref.m_width),
m_height(uref.m_height),
m_pData(uref.m_pData)
{
uref.m_pData = nullptr;
}
Bitmap::~Bitmap()
{
SAFE_ARRAY_DELETE(m_pData);
}
const ColorsUnion& Bitmap::GetPixel(size_t x, size_t y) const
{
if (x < m_width && y < m_height)
{
return m_pData[(y * m_width) + x];
}
else
{
throw std::exception();
}
} | true |
1db3eb027f3c6126a4ad1f2f63cedf171c69bbb0 | C++ | grok-phantom/CP-books | /2. Graph algorithms/dijkstra.cpp | UTF-8 | 1,426 | 3.484375 | 3 | [] | no_license | /*
* Dijkstra's algorithm finds shortest paths from the starting node
* to all nodes of the graph, like the Bellman-Ford algorithm. The
* benefit of Dijkstra's algorithm is that it is more efficient and
* can be used for processing large graphs. However, the algorithm
* requires that there are no negative weight edges in the graph.
*/
#include <vector>
#include <iostream>
#include <queue>
constexpr int N = 5;
std::vector<std::pair<int, int>> adj[N+1];
std::vector<int> distance(N+1, INT_MAX);
std::priority_queue<std::pair<int,int>> q; // default is max heap
std::vector<bool> processed(N+1, false);
// O(n + m*log(m))
int dijkstra(int x, int e){
distance[x] = 0;
q.push({0, x});
while(!q.empty()){
int a = q.top().second; q.pop();
if(processed[a]) continue;
processed[a] = true;
for(auto u : adj[a]){
int b = u.first, w = u.second;
if(distance[a]+w < distance[b]){
distance[b] = distance[a] + w;
q.push({-distance[b], b});
}
}
}
return distance[e];
}
int main(){
adj[1].emplace_back(2, 5);
adj[1].emplace_back(4, 9);
adj[1].emplace_back(5, 1);
adj[2].emplace_back(1, 5);
adj[2].emplace_back(3,2);
adj[3].emplace_back(2, 2);
adj[3].emplace_back(4,6);
adj[4].emplace_back(1,9);
adj[4].emplace_back(3, 6);
adj[4].emplace_back(5, 2);
adj[5].emplace_back(1,1);
adj[5].emplace_back(4,2);
std::cout<<dijkstra(1,3)<<std::endl;
} | true |
83a62bdc9d1e772e2336bc9adc59b8ed354acd69 | C++ | cj1ne/Algorithm | /Algorithm/삼성 기출 문제/10875_뱀.cpp | UTF-8 | 2,758 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <algorithm>
#include <utility>
#include <tuple>
using namespace std;
const int NONE = -1;
const int UP = 0;
const int RIGHT = 1;
const int DOWN = 2;
const int LEFT = 3;
typedef struct Line {
int x1;
int x2;
int y1;
int y2;
}line;
vector<line> lines;
int hx, hy, hd, l;
int get_dead_time(int nx, int ny) {
int result = NONE;
for (int i = 0; i < lines.size(); i++) {
if ((hx <= lines[i].x1 && nx < lines[i].x1) || (hx >= lines[i].x2 && nx > lines[i].x2)
|| (hy <= lines[i].y1 && ny < lines[i].y1) || (hy >= lines[i].y2 && ny > lines[i].y2)) continue;
else {
int time;
if (hd == RIGHT) {
time = lines[i].y1 - hy;
}
else if (hd == LEFT) {
time = hy - lines[i].y2;
}
else if (hd == UP) {
time = hx - lines[i].x2;
}
else {
time = lines[i].x1 - hx;
}
if (result == NONE || time < result) {
result = time;
}
}
}
return result;
}
void set_new_point(int &nx, int &ny, int time, bool isEmpty) {
switch (hd) {
case RIGHT:
nx = hx;
if (isEmpty) ny = (2 * l) + 1;
else ny = hy + time;
break;
case LEFT:
nx = hx;
if (isEmpty) ny = -1;
else ny = hy - time;
break;
case UP:
if (isEmpty) nx = -1;
else nx = hx - time;
ny = hy;
break;
case DOWN:
if (isEmpty) nx = (2 * l) + 1;
else nx = hx + time;
ny = hy;
break;
}
}
void rotate_direction(char rotate, int &nd) {
if (rotate == 'L') {
nd = (hd + 3) % 4;
}
else {
nd = (hd + 1) % 4;
}
}
void add_line(int nx, int ny) {
int x1, x2, y1, y2;
if (nx > hx) {
x1 = hx; x2 = nx;
}
else {
x1 = nx; x2 = hx;
}
if (ny > hy) {
y1 = hy; y2 = ny;
}
else {
y1 = ny; y2 = hy;
}
line l = { x1, x2, y1, y2 };
lines.push_back(l);
}
int main() {
queue<pair<int, char>> t;
long long result = 0;
char rotate;
int n, time = 0;
cin >> l >> n;
hx = l, hy = l, hd = RIGHT;
for (int i = 0; i < n; i++) {
cin >> time >> rotate;
t.push(make_pair(time, rotate));
}
while (true) {
int nx, ny, nd;
if (t.empty()) {
set_new_point(nx, ny, time, true);
}
else {
time = t.front().first;
rotate = t.front().second;
t.pop();
rotate_direction(rotate, nd);
set_new_point(nx, ny, time, false);
}
int dead = get_dead_time(nx, ny);
if (dead == NONE) {
if (nx < 0) {
result += hx + 1;
break;
}
else if (nx >= (2 * l) + 1) {
result += (2 * l) - hx + 1;
break;
}
else if (ny < 0) {
result += hy + 1;
break;
}
else if (ny >= (2 * l) + 1) {
result += (2 * l) - hy + 1;
break;
}
else {
add_line(nx, ny);
hx = nx; hy = ny; hd = nd;
result += time;
}
}
else {
result += dead;
break;
}
}
cout << result << "\n";
return 0;
} | true |
9c5ad39453809bde7088f8edfcbaeca6e5fa07c0 | C++ | scsewell/Mantis | /Source/Utils/Geometry/RectInt.h | UTF-8 | 734 | 2.8125 | 3 | [] | no_license | #pragma once
#include "Mantis.h"
namespace Mantis
{
/// <summary>
/// Represents a 2d rectangle.
/// </summary>
class RectInt
{
public:
int x;
int y;
int width;
int height;
/// <summary>
/// Gest the position of the rect.
/// </summary>
Vector2Int Position() const;
/// <summary>
/// Gets the size of the rect.
/// </summary>
Vector2Int Size() const;
/// <summary>
/// Gets the center of the rect.
/// </summary>
Vector2 Center() const;
/// <summary>
/// Gets the aspect ratio of the rect.
/// </summary>
float GetAspectRatio() const;
};
}
| true |
e196101693e300389dd29fd043930f20170d362e | C++ | theoldestsc/TanksGame | /src/VideoManager.cpp | UTF-8 | 1,845 | 2.828125 | 3 | [] | no_license | #include "VideoManager.h"
std::unique_ptr<VideoManager> VideoManager::VideoManagerInstance = nullptr;
VideoManager::VideoManager():mRenderer(nullptr),
mWindow(nullptr)
{
}
bool VideoManager::Initialize()
{
SDL_DisplayMode dm;
if (SDL_GetDesktopDisplayMode(0, &dm) != 0)
{
SDL_Log("Failed to get desktop display mode: %s", SDL_GetError());
return false;
}
mWindow = SDL_CreateWindow("TanksBattle", // Title
SDL_WINDOWPOS_UNDEFINED, // Top left x - coordinate of window
SDL_WINDOWPOS_UNDEFINED, // Top left y - coordinate of window
dm.w, // Width
dm.h, // Height
SDL_WINDOW_RESIZABLE // Flags //TODO:Made this optional
);
if(!mWindow)
{
SDL_Log("Failed to create window: %s", SDL_GetError());
return false;
}
mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if(!mRenderer)
{
SDL_Log("Failed to create render: %s", SDL_GetError());
return false;
}
SDL_RenderSetLogicalSize(mRenderer, dm.w, dm.h);
return true;
}
SDL_Renderer* VideoManager::GetRenderer() const
{
return mRenderer;
}
void VideoManager::GetWindowSize(int &w, int &h)
{
return SDL_RenderGetLogicalSize(mRenderer, &w, &h); // AWFUl
}
std::unique_ptr<VideoManager>& VideoManager::Instance()
{
if(!VideoManagerInstance)
{
VideoManagerInstance.reset(new VideoManager);
return VideoManagerInstance;
}
return VideoManagerInstance;
}
VideoManager::~VideoManager()
{
SDL_DestroyRenderer(mRenderer);
SDL_DestroyWindow(mWindow);
} | true |
495e18b895a4be6f20d916b0691d919577735738 | C++ | kigster/librgb | /src/librgb/FadeEffect.h | UTF-8 | 1,219 | 2.96875 | 3 | [
"MIT"
] | permissive | #ifndef _RGB_PIXEL_EFFECT_H_
#define _RGB_PIXEL_EFFECT_H_
#include "RGBColor.h"
#include "Effect.h"
/**
* Linear fade from one color to another.
*/
class FadeEffect : public Effect {
public:
FadeEffect(RGB from,
RGB to,
long periodMs) {
restart(from, to, periodMs);
};
void restart(RGB from,
RGB to,
uint32_t periodMs) {
stop();
_startColor = from;
_endColor = to;
_startTime = millis();
_duration = periodMs;
set_color(_startColor);
set_running(true);
}
void tick(long timestamp) {
long _now = timestamp == 0 ? millis() : timestamp;
if (_now - _startTime > _duration) {
set_color(_endColor);
} else {
RGBColor _intermediate = _colorAt(_now);
_lastUpdateAt = _now;
set_color(_intermediate);
}
}
RGBColor _colorAt(long timestamp) const {
return _startColor.scaleTo(_endColor, progressAt(timestamp));
}
void stop() {
_startColor = _endColor = RGB(0);
_duration = 0;
_lastUpdateAt = 0;
set_running(false);
}
};
#endif
| true |
815769850f766c6a08bcdd7bd5e1ab698a8146f9 | C++ | r-mutax/MTextProt | /src/message.cpp | UTF-8 | 2,658 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "message.h"
#include "key.h"
#include "console.h"
#include <queue>
#include <thread>
#include <mutex>
std::mutex mtx;
class CMessageEngine{
private:
std::thread m_thread_key_monitoring;
std::thread m_thread_display_monitoring;
std::queue<MESSAGE> m_msg_pool;
bool m_bRun;
void key_monitoring();
void display_monitoring();
std::mutex mtx;
public:
CMessageEngine();
~CMessageEngine();
MESSAGE_ID GetMessage(MESSAGE& msg);
void SendMessage(MESSAGE& msg);
};
namespace message_nsp
{
CMessageEngine* msg_engine;
} // namespace msg
MESSAGE_ID MMGetMessage(MESSAGE& msg){
return message_nsp::msg_engine->GetMessage(msg);
}
void MMSendMessage(MESSAGE& msg){
message_nsp::msg_engine->SendMessage(msg);
}
void MMPrepareMessageLoop(){
message_nsp::msg_engine = new CMessageEngine();
}
CMessageEngine::CMessageEngine()
: m_thread_key_monitoring(&CMessageEngine::key_monitoring, this)
, m_thread_display_monitoring(&CMessageEngine::display_monitoring, this)
, m_bRun(true)
{
}
CMessageEngine::~CMessageEngine(){
m_bRun = false;
m_thread_key_monitoring.join();
m_thread_display_monitoring.join();
}
void CMessageEngine::key_monitoring(){
while(1){
char input_key;
input_key = get_vkcode();
if(input_key){
MESSAGE msg;
msg.id = MM_KEYPRESS;
msg.lParam = (long)input_key;
SendMessage(msg);
}
}
}
void CMessageEngine::display_monitoring(){
static MSize bef,ms;
while(1){
// winsize event
// GetConsoleSize(&ms);
// if(ChkConsoleSizeChange(bef, ms)){
// ms = bef;
// MESSAGE msg;
// MSize* monitor_size = (MSize*)calloc(1, sizeof(MSize));
// *monitor_size = ms;
// msg.id = MM_CHANGE_WINSIZE;
// msg.lParam = (long)monitor_size;
// SendMessage(msg);
// }
// paint event
{
MESSAGE msg;
msg.id = MM_PAINT;
SendMessage(msg);
}
usleep(500000);
}
}
void CMessageEngine::SendMessage(MESSAGE& msg){
std::lock_guard<std::mutex> ul(mtx);
m_msg_pool.push(msg);
}
MESSAGE_ID CMessageEngine::GetMessage(MESSAGE& msg){
enum MESSAGE_ID ret;
while(1){
mtx.lock();
if(m_msg_pool.size() != 0){
msg = m_msg_pool.front();
m_msg_pool.pop();
ret = msg.id;
mtx.unlock();
break;
} else {
mtx.unlock();
usleep(30000);
}
}
return ret;
} | true |
18dc0a00fd4f913efc88218ebe5a9f713787e7a7 | C++ | MarinaNem/C_Lab | /Matrix/Matrix3D.h | UTF-8 | 311 | 2.703125 | 3 | [] | no_license | #pragma once
#include "MatrixBase.h"
class Matrix3D :public MatrixBase
{
public:
Matrix3D() : MatrixBase(m3D_size) {}
virtual int element(unsigned int i, unsigned int j) const override;
virtual int& element(unsigned int i, unsigned int j) override;
private:
int matrix[m3D_size * m3D_size];
};
| true |
f95f6a7e8b92b2f3ff3621d262427821657d90d2 | C++ | stupend-geek7/CSES | /Geometry/Point in Polygon.cpp | UTF-8 | 2,198 | 2.921875 | 3 | [] | no_license | //https://cses.fi/problemset/task/2192/
#include<bits/stdc++.h>
using namespace std;
#define int long long int
struct Point
{
int x,y;
void read(){cin>>x>>y;}
Point operator - (const Point& b)const{
return Point{x-b.x,y-b.y};
}
void operator -=(const Point& b){
x-=b.x;
y-=b.y;
}
int operator *(const Point& b)const{
return x*b.y-y*b.x;
}
int triangle(const Point& b,const Point& c)const{
return (b-*this)*(c-*this);
}
};
bool intersect (Point p1,Point q1, Point p2,Point q2){
//two segments are parallel...
//Then their cross product is zero
if((q1-p1) * (q2-p2)==0){
if(p1.triangle(p2,q1)!=0){
return false;
}
for(int i=0;i<2;++i){
//checks the two bounding boxes intersect ...
if(max(p1.x,q1.x)<min(p2.x,q2.x) or max(p1.y,q1.y)<min(p2.y,q2.y)){
return false;
}
swap(p1,p2);
swap(q1,q2);
}
return true;
}else{
for(int i=0;i<2;++i){
int sign1=p1.triangle(q1,p2);//if sign1(-ve) w.r.t p1 , point q1 is on the left of p2 or vice-versa.
int sign2=p1.triangle(q1,q2);//if sign2(+ve) w.r.t p1 , point q1 is on the right of q2 or vice-versa.
if((sign1<0 and sign2<0) or (sign1>0 and sign2>0)){
return false;
}
swap(p1,p2);
swap(q1,q2);
}
return true;
}
}
bool is_on_boundary(Point a,Point b,Point c){
if(a.triangle(b,c)!=0){
return false;
}
return min(a.x,b.x)<=c.x and c.x<=max(a.x,b.x) and
min(a.y,b.y)<=c.y and c.y<=max(a.y,b.y);
}
void Malena(){
int n,m;cin>>n>>m;
vector<Point>Polygon(n);
for(Point &p:Polygon){
p.read();
}
while(m--){
Point first;
first.read();
Point second=Point{first.x+1,(int)(2e9+1)};
int cnt=0;
bool flag=false;
for(int i=0;i<n;++i){
int j=(i==n-1?0:i+1);
if(is_on_boundary(Polygon[i],Polygon[j],first)){
flag=true;break;
}
if(intersect(first,second,Polygon[i],Polygon[j]))cnt++;
}
if(flag){
cout<<"BOUNDARY\n";continue;
}
if(cnt&1)cout<<"INSIDE";
else cout<<"OUTSIDE";
cout<<'\n';
}
}
signed main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t;
t=1;
//cin>>t;
while(t--){
Malena();
}
return 0;
}
| true |
518df2442dfb6c2f0545066e46a0ab0ab6092b30 | C++ | AndyBrown91/MusicPlayer | /Source/GUI/Controls/Sliders/VolumeControl.h | UTF-8 | 2,476 | 2.875 | 3 | [] | no_license | /*
* VolumeControl.h
* sdaMidiMeter
*
* Created by Andy on 06/01/2012.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#ifndef H_VOLUMECONTROL
#define H_VOLUMECONTROL
#include "../JuceLibraryCode/JuceHeader.h"
/**
A slider with a volume icon that updates based on the volume being displayed by the slider
*/
class VolumeControl : public Component,
public SliderListener,
public ButtonListener,
public ActionBroadcaster
{
public:
/**
Constructor
*/
VolumeControl ();
/**
Destructor
*/
~VolumeControl();
/**
@internal
*/
void paint (Graphics& g);
/**
@internal
*/
void resized();
/**
Adds the incoming class as a listener to the volume slider's Value
@param incomingListener The listener to be added to the volume slider listener list
*/
void addValueListener (Value::Listener* incomingListener);
/**
@return The Value object for the volume slider
*/
Value& getSliderValue();
/**
@return The current volume between 0 - 1
*/
double getVolume();
/**
Sets the volume between 0 - 1, triggers listeners who are listening to the slider
@param incomingVolume The new volume
*/
void setVolume(double incomingVolume);
// Binary resources:
static const char* vol0_png;
static const int vol0_pngSize;
static const char* vol25_png;
static const int vol25_pngSize;
static const char* vol50_png;
static const int vol50_pngSize;
static const char* vol75_png;
static const int vol75_pngSize;
static const char* volFull_png;
static const int volFull_pngSize;
private:
/**
Adjusts the volume based on the slider value
@param sliderThatWasMoved A pointer to the slider that moved, only ever volumeSlider
*/
void sliderValueChanged (Slider* sliderThatWasMoved);
/**
Mutes the volume if the volume icon is clicked
*/
void buttonClicked (Button* buttonThatWasClicked);
Slider volumeSlider;
ImageButton volumeButton;
Image cachedImage_vol0_png;
Image cachedImage_vol25_png;
Image cachedImage_vol50_png;
Image cachedImage_vol75_png;
Image cachedImage_volFull_png;
float volume;
float muteVolume;
};
#endif //H_VOLUMECONTROL
| true |
a54e725446b4b19c857afbbe6599b34e84171005 | C++ | gfh16/StudyNotes | /CPP/C++学习资料/C++入门经典/书本例题/Code From the 2271 Book/ch14/prog14_05/list.h | UTF-8 | 1,230 | 3.09375 | 3 | [] | no_license | // List.h classes supporting a linked list
#ifndef LIST_H
#define LIST_H
#include "Box.h"
class TruckLoad {
public:
// Constructors
TruckLoad(Box* pBox = 0, int count = 1); // Constructor
TruckLoad::TruckLoad(const TruckLoad& Load); // Copy constructor
~TruckLoad(); // Destructor
Box* getFirstBox(); // Retrieve the first Box
Box* getNextBox(); // Retrieve the next Box
void addBox(Box* pBox); // Add a new Box to the list
Box operator[](int index) const; // Overloaded subscript operator
private:
class Package {
public:
Box* pBox; // Pointer to the Box
Package* pNext; // Pointer to the next Package
Package(Box* pNewBox); // Constructor
};
Package* pHead; // First in the list
Package* pTail; // Last in the list
Package* pCurrent; // Last retrieved from the list
};
#endif
| true |
e52b23841a020d860f4188a6ad46380f51d9016a | C++ | ryanrabello/automatedNightLight | /deskLight/deskLight.ino | UTF-8 | 3,620 | 3.5625 | 4 | [] | no_license | /**
* Hi!
* This program controls an RGB LED with some fade animations.
* You can use this by adjusting the LED pins below and adjusting
* the value you'd like to use for on and off.
**/
//Initialize led pins
int led[] = {6, 5, 3};
const int ledOff = 255; //Led full off pwm value.
const int ledOn = 175; //led full on pwm brightness.
const int mainDelay = 1000;
void setup()
{
//Initialize those output ports.
for (int i = 0; i < (sizeof(led) / sizeof(int)); i++)
{
pinMode(led[i], OUTPUT);
analogWrite(led[i], ledOff); //Turn off all RGB led pins
}
//Get random brightness and use it as the seed.
randomSeed(analogRead(0));
}
/**
* Fade from the current LED state to the inputed one
**/
int time = 0;
int ledStates[] = {ledOff, ledOff, ledOff};
void fadeTo(int red, int green, int blue, int transitionTime)
{
//Want 20 fps
float spf = 1.0 / ((float)transitionTime * 9.0);
//int time = transitionTime / (transitionTime*20); //Get time percycle in microseconds.
float change[] = {
red - ledStates[0], green - ledStates[1], blue - ledStates[2]}; //Difference in all the values.
//Run transition
for (float i = 0; i <= 1.00;)
{
i += spf;
//Set all Led to the right value
for (int j = 0; j < 3; j++)
{
analogWrite(led[j], i * change[j] + (float)ledStates[j]);
}
}
ledStates[0] = red;
ledStates[1] = green;
ledStates[2] = blue;
}
/**
* Function for changing the RGB LED to a random value (either a solid color or a mix of colors)
**/
void changeLed() {
changeLed(false);
}
void changeLed(boolean slow)
{
int ranLed[3];
if ((int)(random(0, 4) + .5) == 0)
{
//25% of time.
for (int i = 0; i < 3; i++)
{
ranLed[i] = (int)(random(ledOn, ledOff) + .5);
}
}
else
{
//75% of time.
while (true)
{
for (int i = 0; i < 3; i++)
{
ranLed[i] = (ledOff - ledOn) * (int)(random(0, 2)) + ledOn;
}
if (ranLed[0] != ledOff || ranLed[1] != ledOff || ranLed[2] != ledOff)
break;
}
}
fadeTo(ranLed[0], ranLed[1], ranLed[2], slow ? 3000 : 1000);
}
/**
* Create a pattern of lights for some fun action
**/
int timeDelays[] = {2, 3, 4, 8, 16, 32};
void randomPattern()
{
int randWait = 1000 / timeDelays[(int)(random(0, 4) + .5)];
int count = 7;
int ranLed[3];
while (count > 0)
{
//Configure led array
if ((int)(random(0, 4) + .5) == 0)
{
//25% of time.
for (int i = 0; i < 3; i++)
{
ranLed[i] = (int)(random(ledOn, ledOff) + .5);
}
}
else
{
//75% of time.
while (true)
{
for (int i = 0; i < 3; i++)
{
ranLed[i] = (ledOff - ledOn) * (int)(random(0, 2)) + ledOn;
}
if (ranLed[0] != ledOff || ranLed[1] != ledOff || ranLed[2] != ledOff)
break;
}
}
fadeTo(ranLed[0], ranLed[1], ranLed[2], 100);
delay(randWait * .75);
//run atleast 4 times then there exists a probability of exiting.
if (count < (int)(random(0, 5) + .5))
break;
count--;
}
}
void loop()
{
randomPattern();
int slowCycles = random(50, 100);
for (int i = 0; i < slowCycles; i++)
{
changeLed();
delay(5000);
}
delay(mainDelay);
}
| true |
c429a142e62989a54deecce5c3b8f8a60675c1bf | C++ | msclam/CodeRepo | /c++/牛客网/剑指offer模块/J40-数组中只出现一次的两个数字.cpp | UTF-8 | 1,203 | 3.203125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
*/
vector<int> FindNumsAppearOnce(vector<int>& A) {
// int res = 0;
// for (int num : A) {
// res ^= num;
// }
// return res;
// a ^ a = 0 ^ 相当于提取出不同的数据(晒去相同元素)
// & 1 相当于取出最后一位进行判断(用作区分)
int res = 0;
for (int num : A) { // 所有数异或相当于最后两个不同的是的二进制位置的不同
res ^= num;
}
int flag = 1; // 找到两个数据最低位置不同的数 1111 ^ 0101 = 1010 ==> 0010就可以分辨这两个数
while ((flag & res) == 0) {
flag <<= 1;
}
int a = 0, b = 0;
for (int i : A) {
if ((i & flag) == 0) a ^= i;
else b ^= i;
}
if (a > b) {
swap(a, b);
}
return vector<int>{a, b};
}
}; | true |
02e175a8d8a630bbb66b2f15109a89a189aa2b46 | C++ | KarolKalbarczyk/tepLab2 | /ConsoleApplication16 - Kopia/ConsoleApplication16/DiffEval.h | UTF-8 | 1,389 | 2.640625 | 3 | [] | no_license |
#include "MscnProblem.h"
const int POPULATION_SIZE = 12;
const double CROSS_PROBABILITY = 0.08;
const double WEIGHT_DIFF = 0.8;
const int FITNESS_COUNT_TO_STOP = 50000;
class Individual {
public:
Individual(double *genes, int size) { this->genes = genes; this->size = size;result = 0; };
bool isDifferent(Individual* other);
bool setAt(int index, double value) { genes[index] = value; };
double getAt(int index) { return genes[index]; };
~Individual() { delete[] genes; };
double getFitness(Problem* problem);
int getSize() { return size; };
void printSolution();
double getResult() { return result; };
private:
double result;
double* genes;
int size;
};
class DiffEval {
public:
Individual* solve(Problem* problem,int seed);
private:
Individual* currentBest;
double currentBestFitness;
int fitnessCount;
Problem* problem;
Random rand;
Individual** population;
Individual* generateIndividual();
std::pair<double, double>* constraints;
bool isStopConditionMet();
void placeBetter(int index, Individual* newInd);
bool areDifferent(Individual* ind, Individual* base, Individual* indAdd1, Individual* indAdd2);
void generatePopulation();
bool isBetter(Individual* old, Individual* newInd);
Individual * chooseBest();
Individual* cross(Individual* ind, Individual* base, Individual* indNew1, Individual* indNew2);
};
| true |
05df1ad5b6b4066d1be6de6241c581652412aab1 | C++ | mnakata/2011120803 | /main.cc | UTF-8 | 497 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
const int N = 10000;
const double p = 0.8;
double binomdist(int n, double p, int k)
{
return
exp(
lgamma(n + 1)
- lgamma(n - k + 1)
- lgamma( k + 1)
+ k * log( p)
+ (n - k) * log(1.0 - p)
);
}
int main(int argc, char** argv)
{
double s = 0.0;
for (int k = 0; k <= N; k ++)
s += binomdist(N, p, k);
std::cout << std::fixed << s << std::endl;
}
| true |
5ce117c85b6a0dfe2c4331a5cb7fb87838391bef | C++ | humbertotg/competitivePrograming | /157B.cpp | UTF-8 | 523 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <math.h>
#include <iomanip>
using namespace std;
int main() {
int n;
cin>>n;
double ans = 0;
int radius[n];
for(int i = 0; i < n; i++)
cin>>radius[i];
sort(radius,radius+n,greater<int>());
for(int i = 0; i < n; i++){
if(i == n - 1 && n % 2 == 1){
ans += pow(radius[i],2)*3.1415926535;
} else if(i % 2 == 0){
ans += pow(radius[i],2)*3.1415926535 - pow(radius[i + 1], 2)*3.1415926535;
}
}
cout<<setprecision(10)<<ans;
} | true |
d92f053757b6603a59ec66214318f7e07b7bf920 | C++ | JoeyAndres/rl | /test/src/agent/Environment_test.cpp | UTF-8 | 2,258 | 2.71875 | 3 | [] | no_license | /**
* rl - Reinforcement Learning
* Copyright (C) 2016 Joey Andres<yeojserdna@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "catch.hpp"
#include "rl"
using rl::agent::ActionContainerFactory;
using rl::algorithm::SarsaFactory;
using rl::policy::EpsilonGreedyFactory;
SCENARIO("Environment represents the thing agent interacts with.",
"[rl::agent::AgentSupervised]") {
GIVEN("A binary environment in which 1 is good and 0 is bad.") {
rl::spState<int> state0(new int(0));
rl::spState<int> state1(new int(1));
rl::spAction<int> action0(new int(0));
rl::spAction<int> action1(new int(1));
auto policy = EpsilonGreedyFactory<int, int>(1.0F).get();
auto sarsaAlgorithm = SarsaFactory<int, int>(0.1F, 0.9F, policy).get();
auto actionSet = ActionContainerFactory<int>(
rl::spActionSet<int>({action0, action1})).get();
rl::agent::AgentSupervised<int, int> supevisedAgent(actionSet,
sarsaAlgorithm);
WHEN("When I train 1 to be good and 0 to be bad") {
// We don't transition anywhere. It's just being in state 1 is good.
supevisedAgent.train(state1, action1, 1000, state1);
// Same deal.
supevisedAgent.train(state0, action0, -1000, state0);
THEN("Agent should know that 1 should be good and 0 should be bad") {
auto value1 = sarsaAlgorithm->getStateActionValue(
rl::agent::StateAction<int, int>(state1, action1));
auto value0 = sarsaAlgorithm->getStateActionValue(
rl::agent::StateAction<int, int>(state0, action0));
REQUIRE(value1 > value0);
}
}
}
}
| true |
4f655357fbf1682675bfde790875c5a3fea30846 | C++ | epsilonknot/CodeHub | /DSA/LinkedList/reverseLinkedList.cpp | UTF-8 | 1,612 | 4.03125 | 4 | [] | no_license | /*
*
* Problem 16 : Reverse Linked List
*
*/
#include<iostream>
using namespace std;
struct Node
{
int data;
struct Node* next;
Node(int val):data(val),next(NULL){}
};
void display(Node *head)
{
while(head!=NULL)
{
cout << head->data << " " ;
head=head->next;
}
cout << endl;
}
Node* recursiveReverseLinkedList(Node* head)
{
if(head==NULL)
return NULL;
if(head->next==NULL)
return head;
Node* secondNode = head->next;
head->next = NULL;
Node* reverseList = recursiveReverseLinkedList(secondNode);
secondNode->next=head;
return reverseList;
}
void reverseLinkedList(Node** LinkedList)
{
Node *current,*prev,*next;
prev=next=NULL;
current=*LinkedList;
while(current)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*LinkedList=prev;
}
int main()
{
int n=0;
int* arr,dummy;
cout << "Creating Linked List with Loop " << endl;
cout << "Enter the number of elements in LL : " ;
cin >> n;
arr = new int[n];
cout << "Enter the elements of LL : ";
for(int i=0;i<n;i++)
{
cin >> dummy;
arr[i]=dummy;
}
Node* LinkedList=NULL;// = new Node(arr[n-1]);
Node* tmp;
Node *l;
for(int i=n-1;i>=0;--i)
{
tmp = new Node(arr[i]);
if(i==dummy-1)
l=tmp;
tmp->next = LinkedList;
LinkedList = tmp;
}
delete []arr;
cout << "After reversing the Linked List : ";
reverseLinkedList(&LinkedList);
display(LinkedList);
LinkedList=recursiveReverseLinkedList(LinkedList);
cout << "Reversing using recursive approach : ";
display(LinkedList);
return 0;
}
| true |
656e518b7d6af17aa53f8f5f010041c1ceae51ae | C++ | vinsonleelws/LeetCode | /225-Implement Stack using Queues.cpp | UTF-8 | 4,281 | 4.09375 | 4 | [] | no_license | /*Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
*/
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
}
/** Get the top element. */
int top() {
}
/** Returns whether the stack is empty. */
bool empty() {
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* bool param_4 = obj.empty();
*/
// 用队列实现栈 [E]
// 双队列
// -------------------------------------------------------------
// 注意:题目要求中给定了限制条件只能用queue的最基本的操作,像back()这样的操作是禁止使用的。
// Reference solution:
// #1
// 使用辅助队列,每次把新加入的数插到前头的方法
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue<int> tmp; // 两次转移
while (!q.empty()) // 转移到临时队列中
{
tmp.push(q.front());
q.pop();
}
q.push(x);
while (!tmp.empty()) // 转移回原队列
{
q.push(tmp.front());
tmp.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int val = top();
q.pop();
return val;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
private:
queue<int> q;
};
// #2
// 使用双队列的方法:
// 其中一个队列用来放最后加进来的数,模拟栈顶元素。剩下所有的数都按顺序放入另一个队列中。当push操作时,将新数字先加入模拟栈顶元素的队列中,
// 如果此时队列中有数字,则将原本有的数字放入另一个队中,让新数字在这队中,用来模拟栈顶元素。当top操作时,如果模拟栈顶的队中有数字则直接返
// 回,如果没有则到另一个队列中通过平移数字取出最后一个数字加入模拟栈顶的队列中。当pop操作时,先执行下top()操作,保证模拟栈顶的队列中有数字,
// 然后再将该数字移除即可。当empty操作时,当两个队列都为空时,栈为空。
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
// Push element x onto stack.
void push(int x) {
q2.push(x);
while (q2.size() > 1) {
q1.push(q2.front());
q2.pop();
}
}
// Removes the element on top of the stack.
int pop() {
int val = top();
q2.pop();
return val;
}
// Get the top element.
int top(void) {
if (q2.empty())
{
for (int i = 0; i < (int)q1.size() - 1; ++i)
{
q1.push(q1.front());
q1.pop();
}
q2.push(q1.front());
q1.pop();
}
return q2.front();
}
// Return whether the stack is empty.
bool empty(void) {
return q1.empty() && q2.empty();
}
private:
queue<int> q1, q2;
}; | true |
185709aaa2147c385655df1cbb81f3823b878565 | C++ | definelicht/knn-xeonphi | /code/include/knn/Random.h | UTF-8 | 2,839 | 3 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <random>
#include <type_traits>
namespace knn {
namespace random {
#define CPPUTILS_RANDOM_THREADLOCAL thread_local
typedef std::mt19937 DefaultRng;
namespace {
template <typename T>
using DistType =
typename std::conditional<std::is_floating_point<T>::value,
std::uniform_real_distribution<T>,
std::uniform_int_distribution<T>>::type;
template <typename T>
DistType<T>& UniformDist() {
static CPPUTILS_RANDOM_THREADLOCAL DistType<T> dist;
return dist;
}
template <typename RngType>
struct EngineWrapper {
RngType engine;
EngineWrapper() : engine(0) {
std::random_device rd;
std::uniform_int_distribution<unsigned int> dist;
engine.seed(dist(rd));
}
};
template <typename RngType>
struct SharedRng {
static EngineWrapper<RngType>& wrapper() {
// Singleton pattern
static CPPUTILS_RANDOM_THREADLOCAL EngineWrapper<RngType> wrapper;
return wrapper;
}
};
// Bitwise interpretation of input seed regardless of type
template <
typename InputType,
typename SeedType = typename std::conditional<
sizeof(InputType) == sizeof(unsigned char), unsigned char,
typename std::conditional<
sizeof(InputType) == sizeof(unsigned short), unsigned short,
typename std::conditional<
sizeof(InputType) == sizeof(unsigned int), unsigned int,
typename std::conditional<
sizeof(InputType) == sizeof(unsigned long), unsigned long,
typename std::conditional<
sizeof(InputType) == sizeof(unsigned long long),
unsigned long long, void>::type>::type>::type>::type>::
type>
typename std::enable_if<!std::is_same<SeedType, void>::value, SeedType>::type
SeedToUnsigned(InputType seed) {
return *reinterpret_cast<SeedType *>(&seed);
}
} // End anonymous namespace
/// \brief Seed random number generator of the given type.
template <typename RngType, typename SeedType = DefaultRng>
void SetSeed(SeedType seed) {
SharedRng<RngType>::wrapper().engine.seed(SeedToUnsigned<SeedType>(seed));
}
/// \return A uniform random number.
template <typename T, typename RngType = DefaultRng>
T Uniform() {
return UniformDist<T>()(SharedRng<RngType>::wrapper().engine);
}
/// \brief Fills the provided range with uniform random numbers, using the
/// (optionally) specified random number generator.
template <typename Iterator, typename RngType = DefaultRng>
void FillUniform(Iterator begin, Iterator end) {
typedef typename std::iterator_traits<Iterator>::value_type T;
std::for_each(begin, end, [](T &tgt) { tgt = Uniform<T, RngType>(); });
}
} // End namespace random
} // End namespace knn
#undef CPPUTILS_RANDOM_THREADLOCAL
| true |
0bec0b231607554b6e995af5b71c18c8a0a82304 | C++ | Kayoku/BasicPoker | /oldcpp/Poker_Player_FSP.h | UTF-8 | 2,764 | 3.109375 | 3 | [] | no_license | #ifndef poker_player_fsp_declared
#define poker_player_fsp_declared
#include <iostream>
#include <random>
#include "Poker_Player.h"
namespace poker
{
class Poker_Player_FSP : public Poker_Player
{
private:
std::mt19937 rnd;
// 0 = Fold / 1 = Call/Check / 2 = Raise
float strats_p1[170][5][3]; // 170 = Nb de cartes; 5 = Etats possibles p1
float strats_p2[170][5][3]; // 170 = Nb de cartes; 5 = Etats possibles p2
int strats_p1_count[170][5];
int strats_p2_count[170][5];
public:
Poker_Player_FSP(int id,
poker::Poker_State &state):
Poker_Player(id, state),
rnd(id)
{
for (int i = 0 ; i < 170 ; i++)
{
for (int j = 0 ; j < 5 ; j++)
{
for (int k = 0 ; k < 3 ; k++)
{
strats_p1[i][j][k] = (float)0.333333;
strats_p2[i][j][k] = (float)0.333333;
}
strats_p1_count[i][j] = 1;
strats_p2_count[i][j] = 1;
}
}
// Dernier choix P1 et P2, pas de raise possible
for (int i = 0 ; i < 170 ; i++)
{
strats_p1[i][4][0] = 0.5;
strats_p1[i][4][1] = 0.5;
strats_p1[i][4][2] = 0;
}
for (int i = 0 ; i < 170 ; i++)
{
strats_p2[i][4][0] = 0.5;
strats_p2[i][4][1] = 0.5;
strats_p2[i][4][2] = 0;
}
}
/////////////////////////////////////////
enum Possible_State
{
// P1
P1, // p1 first move
P1R_P2R, // p1 raise, then p2 raise
P1C_P2R, // p1 check, then p2 raise
P1C_P2R_P1R_P2R, // p1 check, then p2 raise, then p1, then p2
P1R_P2R_P1R_P2R, // p1 raise, then p2 raise, then p1, then p2
// P2
P1R, // p1 raise
P1C, // p1 check
P1R_P2R_P1R, // p1 raise, then p2 raise, then p1 raise
P1C_P2R_P1R, // p1 raise, then p2 raise, then p1 raise
P1C_P2R_P1R_P2R_P1R, // p1 check, then p2 raise, then p1, then p2, then p1
//
END_ROUND,
possible_state
};
/////////////////////////////////////////
/////////////////////////////////////////
// F = Fold; C = Check/Call; R = Raise
/*enum Strategy
{
P1_F,
P1_C_F,
P1_C_C,
P1_C_R_F,
P1_C_R_C,
P1_C_R_R,
P1_R_F,
P1_R_C,
P1_R_R_F,
P1_R_R_C,
P2_F,
P2_C,
P2_R_F,
P2_R_C,
P2_R_R_F,
P2_R_R_C,
strategy
};*/
/////////////////////////////////////////
void play() override;
void choose_play(poker::Move move);
poker::Move get_next_move();
Possible_State get_current_state();
void write_strats(std::string filename);
void read_strats(std::string filename);
void reset_like(Poker_Player_FSP &player);
void update_strat(std::array<float, 3> average, bool p1);
};
}
#endif
| true |
5bcb239d28a252db758b7bb5c0ca0a34d26b214e | C++ | georgesuarez/LeetCode | /C++/ToLowerCase.cpp | UTF-8 | 289 | 2.984375 | 3 | [] | no_license | #include <string>
using namespace std;
class Solution
{
public:
string toLowerCase(string str)
{
string lowerCaseStr = "";
for (int i = 0; i < str.length(); i++)
{
lowerCaseStr += tolower(str[i]);
}
return lowerCaseStr;
}
}; | true |
38d6001d967dd0a40a49c6ea0d0e9a9a9cd45220 | C++ | mviseu/Cpp_primer | /Chapter7/7_5.cc | UTF-8 | 348 | 3.5 | 4 | [] | no_license | #include "Person.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
// using data members to read from input
Person P;
if (cin >> P.NameID >> P.AddressID) {
// using member function to write to output
cout << P.Name() << endl;
cout << P.Address() << endl;
}
return 0;
}
| true |
6db21e48dd533d6deaed3721001b5b96e9cfc5be | C++ | Tanner/Picture-File-System | /source/month_directory_entity.cpp | UTF-8 | 891 | 2.71875 | 3 | [] | no_license |
#include <iostream>
#include <vector>
#include "month_directory_entity.h"
#include "storage.h"
#include "picture_entity.h"
#include "util.h"
using namespace pfs;
using namespace std;
MonthDirectoryEntity::MonthDirectoryEntity(int year, int month) : DirectoryEntity(month_to_str(month)), year_(year), month_(month) {
}
Entity* MonthDirectoryEntity::clone() {
return new MonthDirectoryEntity(*this);
}
vector<shared_ptr<Entity> > MonthDirectoryEntity::get_children() {
vector<shared_ptr<Entity> > children;
vector<Photo> photos(storage_->get_photos(year_, month_));
for (auto i = photos.begin(); i != photos.end(); ++i) {
// cout << endl << endl << "PHOTO DATA" << endl;
// cout << i->data() << endl;
shared_ptr<Entity> entity(new PictureEntity(*i));
entity->set_storage(storage_);
children.push_back(entity);
}
return children;
}
| true |
ab927436dcf3401eea86c8ccbdd1d9362140eb02 | C++ | sinarahmany/cplusplus | /ASsigment3Cplus/src/SimpleDate.cpp | UTF-8 | 3,324 | 3.875 | 4 | [] | no_license | #include "SimpleDate.h"
#include <string>
#include <iostream>
#include "../Functions.h"
// Default constructor
SimpleDate::SimpleDate():SimpleDate(1, 1, 1970, "Tuesday"){
}
// Overloaded constructor
SimpleDate::SimpleDate(int month, int day, int year, std::string dayofweek){
if (checkDate(month, day, year)){
this->month=month;
this->day=day;
this->year=year;
this->dayofweek=dayofweek;
}else{
strColor("\nDate you enter is not valid!", 12, 1);
}
}
// Copy constructor
SimpleDate::SimpleDate(const SimpleDate *obj){
this->month=obj->month;
this->day=obj->day;
this->year=obj->year;
this->dayofweek=obj->dayofweek;
}
// Destructor (empty)
SimpleDate::~SimpleDate(){
}
// A function to set the date
void SimpleDate::setDate(int month, int day, int year, std::string dayofweek){
if (checkDate(month, day, year)){
this->month=month;
this->day=day;
this->year=year;
this->dayofweek=dayofweek;
}else{
strColor("\nDate you enter is not valid!", 12, 1);
}
}
// To get and set day members
int SimpleDate::getDay(){
return this->day;
}
void SimpleDate::setDay(int day){
this->day=day;
}
// To get and set month members
int SimpleDate::getMonth(){
return this->month;
}
void SimpleDate::setMonth(int month){
this->month=month;
}
// To get and set year members
int SimpleDate::getYear(){
return this->year;
}
void SimpleDate::setYear(int year){
this->year=year;
}
// To get and set dayofweek members
std::string SimpleDate::getDOW(){
return this->dayofweek;
}
void SimpleDate::setDOW(std::string dayofweek){
this->dayofweek=dayofweek;
}
// A function to print Date
void SimpleDate::print(){
strColor(strMonth(), 14, 1); strColor("/", 8, 1);
strColor(strDay(), 14, 1); strColor("/", 8, 1);
strColor(strYear(), 14, 1);
}
// A utility function for checking year and month and day values
bool SimpleDate::checkDate(int month, int day, int year){
return(checkMonth(month)&&checkDay(day)&&checkYear(year) ? true : false);
}
// A utility function for checking day
bool SimpleDate::checkDay(int day){
return day>-1&&day<32 ? true : false;
}
// A utility function for checking month
bool SimpleDate::checkMonth(int month){
return(month>-1&&month<13 ? true : false);
}
// A utility function for checking year
bool SimpleDate::checkYear(int year){
return(year>-1 ? true : false);
}
// A funciton to print month in 2 digit string
std::string SimpleDate::strMonth(){
return(this->month<10&&this->month>-1 ? "0"+std::to_string(this->month) : std::to_string(this->month));
}
// A funciton to print day in 2 digit string
std::string SimpleDate::strDay(){
return(this->day<10&&this->day>-1 ? "0"+std::to_string(this->day) : std::to_string(this->day));
}
// A funciton to print year in 4 digit string
std::string SimpleDate::strYear(){
return(this->year<10&&this->year>-1 ? "000"+std::to_string(this->year) :
(this->year<100&&this->year>-1 ? "00"+std::to_string(this->year) :
(this->year<1000&&this->year>-1 ? "0"+std::to_string(this->year) :
std::to_string(this->year))));
}
| true |
a53f5f3c54e38790bb866da25761d382d985517e | C++ | vedikagoyal3/Coding-Questions | /Array/Ways to Make a Fair Array.cpp | UTF-8 | 998 | 3.03125 | 3 | [] | no_license | class Solution {
public:
int waysToMakeFair(vector<int>& a) {
int e=0,o=0;
for(int i=0;i<a.size();i++)
{
if(i%2==0)
e+=a[i];
else
o+=a[i];
}
int preveven=0,prevodd=0,aftereven=e,afterodd=o;
int count=0;
for(int i=0;i<a.size();i++)
{
if(i%2==0)
{
aftereven-=a[i];
swap(aftereven,afterodd);
if(preveven+aftereven==prevodd+afterodd)
count++;
preveven+=a[i];
swap(aftereven,afterodd);
}
else
{
afterodd-=a[i];
swap(aftereven,afterodd);
if(preveven+aftereven==prevodd+afterodd)
count++;
prevodd+=a[i];
swap(aftereven,afterodd);
}
}
return count;
}
}; | true |
f9c9dff4f1aab02bab9ca7a7870b24d345adabe4 | C++ | nikhilbarthwal/Random | /TwsApi/Book/CppLinux/Ch11_Bollinger/Bollinger.cpp | UTF-8 | 1,799 | 2.796875 | 3 | [] | no_license | #define BOLLINGER_PERIOD 20
#include "Bollinger.h"
Bollinger::Bollinger(const char *host, int port, int clientId) :
signal(1000),
EClientSocket(this, &signal) {
// Connect to TWS
bool conn = eConnect(host, port, clientId, false);
if (conn) {
// Launch the reader thread
reader = new EReader(this, &signal);
reader->start();
}
else
std::cout << "Failed to connect" << std::endl;
}
Bollinger::~Bollinger() { delete reader; }
// Called in response to reqHistoricalData
void Bollinger::historicalData(TickerId reqId, const Bar& bar) {
double avg, stdDev;
// Compute the moving average
prices.push_back(bar.close);
if (prices.size() == BOLLINGER_PERIOD) {
// Compute the average
avg = std::accumulate(prices.begin(),
prices.end(), 0.0) / prices.size();
avgVals.push_back(avg);
// Compute the standard deviation
auto devFunc = [&avg](double acc, const double& p) {
return acc + (p - avg)*(p - avg);
};
stdDev = std::accumulate(prices.begin(), prices.end(), 0.0, devFunc);
stdDev = std::sqrt(stdDev / BOLLINGER_PERIOD);
// Compute the upper and lower bands
upperVals.push_back(avg + 2 * stdDev);
lowerVals.push_back(avg - 2 * stdDev);
prices.pop_front();
}
}
// Called after all historical data has been received/processed
void Bollinger::historicalDataEnd(int reqId, const std::string& startDate, const std::string& endDate) {
std::cout << "Moving Average: ";
for (double val: avgVals) {
std::cout << val << " ";
}
std::cout << std::endl;
std::cout << "Upper Band: ";
for (double val : upperVals) {
std::cout << val << " ";
}
std::cout << std::endl;
std::cout << "Lower Band: ";
for (double val : lowerVals) {
std::cout << val << " ";
}
std::cout << std::endl;
}
void Bollinger::error(int id, int code, const std::string& msg) {
std::cout << "Error: " << code << ": " << msg << std::endl;
}
| true |
ee5b3564fdfa8b25d82f9f79a3e013f2ca5c523e | C++ | junblood/arduino | /uploadTemperature/uploadTemperature.ino | UTF-8 | 5,307 | 2.703125 | 3 | [] | no_license | /*
Web client
This sketch connects to a website (http://www.google.com)
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe, based on work by Adrian McEwen
*/
#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include <math.h>
#define APIKEY "547d0d14f0d8bcbc0f5d6167ea5e0275" //更换 yeelink api key
#define DEVICEID 3137 // 更换设备IDreplace your device ID
#define SENSORID 4424 // 更换传感器IDreplace your sensor ID
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x7C,0xD1,0xC3,0xE7,0x39,0xE3 };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
char server[] = "api.yeelink.net";
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,1,103);
// initialize the library instance:
EthernetClient client;
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 30*1000; // delay between 2 datapoints, 30s
void setup() {
Wire.begin();
// start serial port:
Serial.begin(57600);
// start the Ethernet connection with DHCP:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
else {
Serial.println("Ethernet configuration OK");
}
}
void loop() {
if(millis()>135000)
{
software_Reset();
}
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
// read sensor data, replace with your code
float sensorReading = readTemperatureSensor();
//send data to server
sendData(sensorReading);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers
{
asm volatile (" jmp 0");
}
// this method makes a HTTP connection to the server:
void sendData(float thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("POST /v1.0/device/");
client.print(DEVICEID);
client.print("/sensor/");
client.print(SENSORID);
client.print("/datapoints");
client.println(" HTTP/1.1");
client.println("Host: api.yeelink.net");
client.print("Accept: *");
client.print("/");
client.println("*");
client.print("U-ApiKey: ");
client.println(APIKEY);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 10 bytes for {"value":} + number of digits of the data:
int thisLength = 13 + getLength(thisData);
client.println(thisLength);
client.println("Content-Type: application/x-www-form-urlencoded");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("{\"value\":");
client.print(thisData);
client.println("}");
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}
///////////////////////////////////////////////////////////////////////////
// get data from Temperature sensor
// you can replace this code for your sensor
float readTemperatureSensor()
{
float val;//定义变量
float dat;//定义变量
val=analogRead(0);// 读取传感器的模拟值并赋值给val
//dat=(125*val)>>8;//温度计算公式
dat = (val * 500) /1024; // Convert Kelvin to Celcius
Serial.print("Sensor value is: ");
Serial.println((float)dat);
return dat;
}
| true |
0adf41bce402be5d7f9580712bb6b00214d40555 | C++ | jezgillen/platypus | /Platypus.ino | UTF-8 | 5,858 | 2.6875 | 3 | [] | no_license | #include <string.h>
#define RECEIVE 1
#define SEND 0
#define SEND_TIME 60*10
#define RED 3
#define GREEN 4
#define IR_sense 1
#define IR_LED 0
#define IR_HIGH() TCCR0A = 1<<COM0A0 | 2<<WGM00
#define IR_LOW() TCCR0A = 2<<WGM00;
#define DELAY_ONE_MILLISECOND(); for(long i = 0; i < 194; i++) {__asm__("nop\n\t");}
//function declarations
void shiftOutIR(char output);
void setInterrupt1Sec();
void setInterrupt125Microsec();
//GLOBAL VARIABLES
int Mode = RECEIVE;
char flagBuffer[30] = "\0";
unsigned long flagHash = 3205401048;
int done = false;
void setup() {
cli();
//Set each pin appropriately
pinMode(RED,OUTPUT); // Red LEDs
pinMode(GREEN,OUTPUT); // Green LEDs
pinMode(IR_sense,INPUT); // IR sensor
pinMode(IR_LED,OUTPUT); // IR LED
//Set up carrier frequency on timer0, which toggles PB0 every 13 clock cycles, or 36kHz ish
//Sets timer0 prescaler to 1. IMPORTANT NOTE: this will change how functions like delay work.
TCCR0B = 1<<CS00;
//Waveform generation Mode is set to CTC (Clear Timer on Compare match) mode,
//Compare Output Mode is set to toggle the output when comparison match occurs
TCCR0A = 1<<COM0A0 | 2<<WGM00;
//This sets the frequency to 36kHz
//OCR0A should be set to ((Clock Freq)/(2*Desired frequency)) - 1
OCR0A = 13;
IR_LOW();
//sets the mode
if(Mode == SEND) {
setInterrupt1Sec();
} else if(Mode == RECEIVE) {
setInterrupt125Microsec();
memset(flagBuffer, 0, sizeof(flagBuffer));
}
sei(); //interrupts enabled
}
void loop() {
static int greenState = LOW;
static long loopTimer = 0;
if(Mode == RECEIVE){
if(done && hash(flagBuffer) == flagHash) {
Mode = SEND;
setInterrupt1Sec();
digitalWrite(GREEN, LOW);
} else {
done = false;
}
loopTimer++;
if(loopTimer%5 == 0){
if (greenState == LOW) {
greenState = HIGH;
} else {
greenState = LOW;
}
digitalWrite(RED, LOW);
digitalWrite(GREEN, greenState);
}
}
DELAY_ONE_MILLISECOND();
}
//This function is called every 1 second
ISR(TIMER1_COMPB_vect){
static int redState = LOW;
static long secondTimer = 0;
if (redState == LOW) {
redState = HIGH;
} else {
redState = LOW;
}
digitalWrite(GREEN, LOW);
digitalWrite(RED, redState);
if(secondTimer%10 == 9){
sendFlag(flagBuffer);
}
secondTimer++;
//Stops sending after 7 mins ish
if(secondTimer > SEND_TIME){
Mode = RECEIVE;
digitalWrite(RED, LOW);
setInterrupt125Microsec();
memset(flagBuffer, 0, sizeof(flagBuffer));
//the done flag should only be set when the flag is in memory
done = false;
secondTimer = 0;
}
}
//Shift IR into buffer. This function is called by an interrupt every 125 microseconds
ISR(TIMER1_COMPA_vect){
static short tickCounter = -1;
static byte buffer = 0;
static int currentBit = 0;
static int currentByte = -1;
//read sensor pin
bool pinState = !digitalRead(IR_sense);
if(tickCounter >= 0 || pinState == HIGH){
//If sensor pin is LOW and tickCounter is -1, start tickCounter
//Otherwise increment tickCounter if it's >= 0
tickCounter++;
}
//If (tickCounter)%8 == 3)
if(tickCounter > 8 && ((tickCounter&B00000111) == 3)){
if(currentBit == 8){
//byte has finished transmitting
//reset in preparation for next byte
tickCounter = -1;
currentBit = 0;
if(currentByte >= 0){
flagBuffer[currentByte] = buffer;
currentByte++;
}
if(buffer == '~'){
done = false;
currentByte = 0;
memset(flagBuffer, 0, sizeof(flagBuffer));
digitalWrite(RED,HIGH);
} else if(buffer == '\0'){
//string has finished transmitting
currentByte = -1;
done = true;
digitalWrite(RED,LOW);
}
buffer = 0;
} else {
//record current detected pin level
bitWrite(buffer, currentBit, pinState);
//increment current bit
currentBit++;
}
}
}
//Sends one byte out of the IR LED, with one header bit, LSB first, takes about 10ms per byte.
void shiftOutIR(char output) {
for(int i = -1; i < 8; i++){
if(i == -1){
IR_HIGH();
}else if(bitRead(output, i) == 1){
IR_HIGH();
} else {
IR_LOW();
}
DELAY_ONE_MILLISECOND();
}
IR_LOW();
DELAY_ONE_MILLISECOND();
}
void sendFlag(char* flag){
shiftOutIR('~');
for(int index = 0; flag[index] != NULL; index++){
shiftOutIR(flag[index]);
}
shiftOutIR('\0');
}
unsigned long hash(char* flag){
cli();
unsigned long h = 0;
for(int index = 0; flag[index] != NULL; index++){
h = 33*h+flag[index];
}
sei();
return h;
}
//Setup timer1 to trigger an interrupt 1 time per second
void setInterrupt1Sec(){
TCCR1 = 1<<CTC1 | 14<<CS10;
//This is a bit longer than a second,
//but it makes the flashing sync up better between modes
OCR1B = 160;
OCR1C = 160;
TIMSK = 1<<OCIE1B;
}
//Setup timer1 to trigger an interrupt 8 times per millisecond
void setInterrupt125Microsec(){
TCCR1 = 1<<CTC1 | 1<<CS10;
OCR1A = 125;
OCR1C = 125;
TIMSK = 1<<OCIE1A;
}
| true |
d882dc3244be07568a398570bae9cba4f7c8dfc6 | C++ | aurelienrb/light-monitoring-tool | /src/cpu-stats.cpp | UTF-8 | 2,121 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "cpu-stats.h"
#include <cassert>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
#include <mutex>
#define _UNICODE
#include <pdh.h>
#pragma comment(lib, "Pdh.lib")
namespace {
// http://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;
void initPdh() {
if (PdhOpenQuery(NULL, NULL, &cpuQuery) != ERROR_SUCCESS ||
PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal) != ERROR_SUCCESS)
{
_CrtDbgBreak();
}
else {
// Start outside the loop as CPU requires difference
PdhCollectQueryData(cpuQuery);
}
}
double getCurrentCPUValue() {
PDH_FMT_COUNTERVALUE counterVal;
if (PdhCollectQueryData(cpuQuery) != ERROR_SUCCESS ||
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal) != ERROR_SUCCESS)
{
_CrtDbgBreak();
return 0.0;
}
else {
return counterVal.doubleValue;
}
}
}
static std::mutex s_statsMutex;
static std::vector<int> s_cpuStats;
void updateCPUStats() {
std::lock_guard<std::mutex> lock(s_statsMutex);
static bool s_initDone = false;
if (!s_initDone) {
initPdh();
s_initDone = true;
}
const size_t maxNbValues = 300;
if (s_cpuStats.empty()) {
s_cpuStats.resize(maxNbValues - 1);
}
else if (s_cpuStats.size() == maxNbValues) {
s_cpuStats.assign(s_cpuStats.begin() + 1, s_cpuStats.end());
}
const auto val = static_cast<int>(getCurrentCPUValue());
s_cpuStats.push_back(val);
assert(s_cpuStats.size() == maxNbValues);
}
std::string getCPUJSONStats() {
std::lock_guard<std::mutex> lock(s_statsMutex);
return to_json(s_cpuStats);
}
std::string to_json(const std::vector<int> & data) {
std::ostringstream oss;
oss << "{ "
<< std::quoted("label") << ": " << std::quoted("CPU") << ", "
<< std::quoted("data") << ": [";
bool isFirst = true;
for (size_t i = 0; i < data.size(); ++i) {
if (i != 0) {
oss << ", ";
}
oss << "[" << i+1 << ", " << data[i] << "]";
isFirst = false;
}
oss << "] }";
return oss.str();
} | true |
e1c2f97f2b99f7248f47d4317132175830b197a4 | C++ | opendev0/project_euler | /problem14.cpp | UTF-8 | 1,153 | 3.9375 | 4 | [] | no_license | /*
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
*/
#include <iostream>
using namespace std;
int main(void)
{
unsigned long long highest = 0, startingNumber = 0, chainLength;
for (unsigned long long i = 2; i < 1000000; ++i) {
chainLength = 0;
for (unsigned long long j = i; j > 1; ++chainLength) {
if (j & 1) {
j = 3 * j + 1;
} else {
j /= 2;
}
}
if (chainLength > highest) {
highest = chainLength;
startingNumber = i;
}
}
cout << "The starting number which produces the longest chain is " << startingNumber << '.' << endl;
return 0;
}
| true |
9bf2557a3f1c9b6ba4a6d0ec4dfab7ff60d2abb0 | C++ | Poisondo/SNMP-Sensor-DHT21 | /src/read_hw.cpp | UTF-8 | 545 | 2.53125 | 3 | [] | no_license | /**
******************************************************************************
* @file : read_hw.c
*
* @author Dyakonov Oleg <o.u.dyakonov@gmail.com>
******************************************************************************
*/
#include <Arduino.h>
#include "read_hw.h"
#include "config.h"
uint8_t hw_init(void)
{
pinMode(HW_1_PIN, INPUT_PULLDOWN);
pinMode(HW_2_PIN, INPUT_PULLDOWN);
return 0;
}
uint8_t hw_read(hw_read_t *read){
read->hw_1 = digitalRead(HW_1_PIN);
read->hw_2 = digitalRead(HW_2_PIN);
return 0;
}
| true |
6d6d6eec4810bbfe403bdddff79906927462b4be | C++ | Leoneq/iNapGPU | /gpu tester/src/main.cpp | UTF-8 | 6,012 | 2.90625 | 3 | [] | no_license | /*
0 ! 36 A 72 a
1 " 37 B 73 b
2 # 38 C 74 c
3 $ 39 D 75 d
4 % 40 E 76 e
5 & 41 F 77 f
6 ' 42 G 78 g
7 43 H 79 h
8 ( 44 I 80 i
9 ) 45 J 81 j
10 * 46 K 82 k
11 + 47 L 83 l
12 , 48 M 84 m
13 - 49 N 85 n
14 . 50 O 86 o
15 / 51 P 87 p
16 0 52 Q 88 q
17 1 53 R 89 e
18 2 54 S 90 s
19 3 55 T 91 t
20 4 56 U 92 u
21 5 57 V 93 v
22 6 58 W 94 w
23 7 59 X 95 x
24 8 60 Y 96 y
25 9 61 Z 97 z
26 : 62 [ 98 {
27 ; 63 \ 99 |
28 < 64 ] 100 }
29 = 65 ^ 101 ~
30 > 66 _
31 ? 67 `
32 @ 68 Ć
33 ą 69 ę
34 Ą 70 Ę
35 ć 71 Ł
*/
#include <Arduino.h>
//pinout
// 8 data pins,
// 10(11) address pins,
// one pin for device select and write operation (both active low)
// why not using ports?
// the pinout is kind of messed, so it's easier to connect that way.
// address bus: 32-37 x-part, 38-42 y-part
#define DATA_LSB 9
#define DATA_MSB 2
#define ADD_MSB 32
#define ADD_LSB 42
#define SEL_IO 11
#define WR 10
#define LED 13
void writeLetter(byte l, byte x, byte y)
{
for(byte xx = ADD_MSB+6; xx <= ADD_LSB; xx++) //set y-part of address
if(bitRead(y, (xx - ADD_MSB - 6)))
digitalWrite(xx, 1);
else
digitalWrite(xx, 0);
for(byte xx = ADD_MSB; xx <= ADD_LSB-5; xx++) //set x-part of address
if(bitRead(x, (xx - ADD_MSB)))
digitalWrite(xx, 1);
else
digitalWrite(xx, 0);
for(byte xy = 0; xy < 8; xy++) //set data bus
if(bitRead(l, xy))
digitalWrite((DATA_MSB+xy), 1);
else
digitalWrite((DATA_MSB+xy), 0);
digitalWrite(WR, LOW);
digitalWrite(SEL_IO, LOW);
delayMicroseconds(1);
digitalWrite(WR, HIGH);
digitalWrite(SEL_IO, HIGH); //write byte
digitalWrite(WR, LOW);
digitalWrite(SEL_IO, LOW);
delayMicroseconds(1);
digitalWrite(WR, HIGH);
digitalWrite(SEL_IO, HIGH); //let's be sure we have wrote that byte
}
void blinkLED(int x) //yes.
{
digitalWrite(LED, HIGH);
delay(x);
digitalWrite(LED, LOW);
}
void clearBuffer(bool invert) //fill buffer with empty char (7) or full char (252-255)
{
for(int x = 0; x < 50; x++)
for(int y = 0; y < 19; y++)
if(invert)
writeLetter(255,x,y);
else
writeLetter(7,x,y);
}
void pasteCharset() //entire charset
{
for(int y = 0; y < 7; y++)
for(int x = 0; x < 36; x++)
writeLetter(x + (y*36),x+4,y+4);
}
void pasteText() //some hardcoded text
{
writeLetter(80,1,0);
writeLetter(49,2,0);
writeLetter(72,3,0);
writeLetter(87,4,0);
writeLetter(7,5,0);
writeLetter(42,6,0);
writeLetter(51,7,0);
writeLetter(56,8,0);
writeLetter(73,1,1);
writeLetter(96,2,1);
writeLetter(7,3,1);
writeLetter(47,4,1);
writeLetter(76,5,1);
writeLetter(86,6,1);
writeLetter(85,7,1);
writeLetter(76,8,1);
writeLetter(88,9,1);
writeLetter(7,10,1); // iNap GPU
writeLetter(251,11,1); // by Leoneq :3
writeLetter(30,1,2); // >
writeLetter(90,20,6);
writeLetter(72,21,6);
writeLetter(84,22,6);
writeLetter(87,23,6);
writeLetter(83,24,6);
writeLetter(76,25,6);
writeLetter(7,26,6);
writeLetter(91,27,6);
writeLetter(76,28,6);
writeLetter(95,29,6);
writeLetter(91,30,6); //sample text
writeLetter(51,20,7);
writeLetter(53,21,7);
writeLetter(61,22,7);
writeLetter(60,23,7);
writeLetter(46,24,7);
writeLetter(71,25,7);
writeLetter(36,26,7);
writeLetter(39,27,7);
writeLetter(50,28,7);
writeLetter(58,29,7);
writeLetter(60,30,7);
writeLetter(7,31,7);
writeLetter(55,32,7);
writeLetter(40,33,7);
writeLetter(46,34,7);
writeLetter(54,35,7);
writeLetter(55,36,7); // PRZYKŁADOWY TEKST
writeLetter(103,30,15);
writeLetter(104,31,15);
writeLetter(105,32,15);
writeLetter(106,33,15);
writeLetter(107,34,15);
writeLetter(139,30,16);
writeLetter(140,31,16);
writeLetter(141,32,16);
writeLetter(142,33,16);
writeLetter(143,34,16); //:o
writeLetter(208, 1, 10);
writeLetter(204, 2, 10);
writeLetter(204, 3, 10);
writeLetter(204, 4, 10);
writeLetter(204, 5, 10);
writeLetter(204, 6, 10);
writeLetter(204, 7, 10);
writeLetter(204, 8, 10);
writeLetter(204, 9, 10);
writeLetter(209, 10, 10); //start of the table
writeLetter(205, 1, 11);
writeLetter(91, 2, 11);
writeLetter(72, 3, 11);
writeLetter(73, 4, 11);
writeLetter(76, 5, 11);
writeLetter(83, 6, 11);
writeLetter(82, 7, 11);
writeLetter(72, 8, 11);
writeLetter(0, 9, 11);
writeLetter(205, 10, 11); // "tabelka!"
writeLetter(223, 1, 12);
writeLetter(194, 2, 12);
writeLetter(194, 3, 12);
writeLetter(194, 4, 12);
writeLetter(194, 5, 12);
writeLetter(194, 6, 12);
writeLetter(194, 7, 12);
writeLetter(194, 8, 12);
writeLetter(194, 9, 12);
writeLetter(226, 10, 12); // line
writeLetter(205, 1, 13);
writeLetter(205, 10, 13); // border
writeLetter(205, 1, 14);
writeLetter(205, 10, 14); // border
writeLetter(218, 1, 15);
writeLetter(204, 2, 15);
writeLetter(204, 3, 15);
writeLetter(204, 4, 15);
writeLetter(204, 5, 15);
writeLetter(204, 6, 15);
writeLetter(204, 7, 15);
writeLetter(204, 8, 15);
writeLetter(204, 9, 15);
writeLetter(219, 10, 15); //end of the table
}
void setup()
{
//pinmodes
for(int x = DATA_MSB; x <= DATA_LSB; x++)
pinMode(x, OUTPUT);
for(int x = ADD_MSB; x <= ADD_LSB; x++)
pinMode(x, OUTPUT);
pinMode(SEL_IO, OUTPUT);
pinMode(WR, OUTPUT);
pinMode(LED, OUTPUT);
digitalWrite(WR, HIGH);
digitalWrite(SEL_IO, HIGH);
blinkLED(100);
clearBuffer(0);
pasteText();
//serial
Serial.begin(115200); //move to the end of setup()
Serial.println("iNap GPU tester - ready");
}
void loop()
{
writeLetter(7,2,2); //dynamic test buffer !
delay(1000);
writeLetter(66,2,2);
delay(1000);
} | true |
ea993b0247ff9c6654f0cf54da7c26723f858e80 | C++ | ejuarezg/NM4P | /Cpp/randn.cpp | UTF-8 | 370 | 2.9375 | 3 | [] | no_license | #include "NumMeth.h"
double rand( long& seed );
// Random number generator; Normal (Gaussian) dist.
double randn( long& seed ) {
// Input
// seed Integer seed (DO NOT USE A SEED OF ZERO)
// Output
// randn Random number, Gaussian distributed
double randn = sqrt( -2.0*log(1.0 - rand(seed)) )
* cos( 6.283185307 * rand(seed) );
return( randn );
} | true |
24b888b2a6ca5a251de232586888043e57b15c6a | C++ | Priyanshu078/datastructures-in-c- | /sorting.cpp | UTF-8 | 2,310 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
// selection sort
// int main()
// {
// int n;
// cin>>n;
// int array[n];
// for (int i = 0; i < n; i++)
// {
// cin>>array[i];
// }
// for (int i = 0; i < n-1; i++)
// {
// for (int j = i+1; j < n; j++)
// {
// if(array[j] < array[i]) // take 1st element and compare it with all the elements then swap it
// {
// int temp = array[i];
// array[i] = array[j];
// array[j] = temp;
// }
// }
// }
// for (int i = 0; i < n; i++)
// {
// cout<<array[i]<<" ";
// }
// return 0;
// }
// Binary search
// int main()
// {
// int n;
// cin >> n;
// int arr[n];
// for (int i = 0; i < n; i++)
// {
// cin >> arr[i];
// }
// int counter = 0;
// while (counter<n-1) // because the array get sorted in n-1 iteration in bubble sort
// {
// for (int i = 0; i < n - counter; i++) //one element of the array get its in right palce
// {
// if (arr[i] > arr[i+1])
// {
// int temp = arr[i];
// arr[i] = arr[i+1];
// arr[i+1] = temp;
// }
// }
// counter += 1;
// }
// for (int i = 0; i < n; i++)
// {
// cout<<arr[i]<<" ";
// }
// return 0;
// }
// insertion sort
// int main()
// {
// int n;
// cin >> n;
// int arr[n];
// for (int i = 0; i < n; i++)
// {
// cin >> arr[i];
// }
// for (int i = 1; i < n; i++)// starting with the 2nd element in the array
// {
// int current = arr[i];
// int j = i-1;
// while (arr[j] > current && j>=0) /* if previous element in the array is greater
// than put the current in place of previous element and increment the palce of previous element.*/
// {
// arr[j+1] = arr[j];
// j -= 1;
// }
// arr[j+1] = current;
// }
// for (int i = 0; i < n; i++)// printing the sorted array
// {
// cout << arr[i] << " ";
// }
// return 0;
// } | true |
88e94962ae6c8571cc9aa392d1078e877ebe2e8c | C++ | Song1996/Leetcode | /p130_Surrounded_Regions/p130.cpp | UTF-8 | 2,290 | 2.78125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <memory>
#include <vector>
#include <stack>
#include <map>
#include <string>
#include <assert.h>
#include <algorithm>
using namespace std;
class Solution {
public:
void solve(vector<vector<char> >& board) {
bool touch_flag = false;
for(int i = 0; i < board.size(); i++) {
for(int j = 0; j < board[i].size(); j++) {
if((i==0||j==0||i==board.size()-1||j==board[i].size()-1) && board[i][j]=='O')
dfs(board, i, j);
}
}
for(int i = 0; i < board.size(); i++) {
for(int j = 0; j < board[i].size(); j++) {
if(board[i][j]=='-') board[i][j] = 'O';
else if(board[i][j]=='O') board[i][j] = 'X';
}
}
}
void dfs(vector<vector<char> >& board, int x, int y) {
board[x][y] = '-';
if(x+1<board.size() && board[x+1][y]=='O') dfs(board, x+1, y);
if(x-1>=0 && board[x-1][y]=='O') dfs(board, x-1, y);
if(y+1<board[x].size() && board[x][y+1]=='O') dfs(board, x, y+1);
if(y-1>=0 && board[x][y-1]=='O' )dfs(board, x, y-1);
return;
}
};
int main () {
vector<vector<char> > x;
vector<char> t;
//for(int i = 0; i<4; i++)t.push_back('X');
//x.push_back(t); t.clear();
t.push_back('O'); t.push_back('X'); t.push_back('X'); t.push_back('O'); t.push_back('X');
x.push_back(t); t.clear();
t.push_back('X'); t.push_back('O'); t.push_back('O'); t.push_back('X'); t.push_back('O');
x.push_back(t); t.clear();
t.push_back('X'); t.push_back('O'); t.push_back('X'); t.push_back('O'); t.push_back('X');
x.push_back(t); t.clear();
t.push_back('O'); t.push_back('X'); t.push_back('O'); t.push_back('O'); t.push_back('O');
x.push_back(t); t.clear();
t.push_back('X'); t.push_back('X'); t.push_back('O'); t.push_back('X'); t.push_back('O');
x.push_back(t); t.clear();
for(int i = 0; i < x.size(); i++) {
for(int j = 0; j < x[i].size(); j++) {
printf("%c ",x[i][j]);
}printf("\n");
}printf("\n");
Solution s;
s.solve(x);
for(int i = 0; i < x.size(); i++) {
for(int j = 0; j < x[i].size(); j++) {
printf("%c ",x[i][j]);
}printf("\n");
}
return 0;
} | true |
ca643f815643d85ffcdea17266f128795ef46a3a | C++ | joe1166/noi | /p1149.cpp | UTF-8 | 1,157 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
using namespace std;
int numof[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
int n;
int a, b;
int c = 0;
int fnum = 0;
int count(int n, int a)
{
if (a < 10)
{
return n - numof[a];
}
else if (a < 100)
{
return n - (numof[a / 10] + numof[a % 10]);
}
else if (a < 1000)
{
return n - (numof[a / 100] + numof[(a % 100) / 10] + numof[a % 10]);
}
else
{
return -1;
}
}
int findb(int n)
{
int bn = 0;
for (int i = 0; i < 1000; i++)
{
b = i;
bn = count(n, i);
if (bn > 0)
{
c = a + b;
bn = count(bn, c);
if (bn == 0)
{
fnum++;
//cout << a << " " << b << " " << c << endl;
}
}
}
return 0;
}
int finda(int n)
{
int an = 0;
for (int i = 0; i < 1000; i++)
{
a = i;
an = count(n, i);
if (an > 0)
findb(an);
}
return 0;
}
int main(int argc, char const *argv[])
{
cin >> n;
n = n - 4;
finda(n);
cout << fnum;
//system("PAUSE");
return 0;
}
| true |
4807a0a21a9c6d043b743576e4a4f991ce97913d | C++ | FangyeReady/GAME | /Scripts/3lua/2016.10.22/C++与lua共用示例/GameInput.h | GB18030 | 833 | 3 | 3 | [] | no_license | #ifndef _GAME_INPUT_H_
#define _GAME_INPUT_H_
#include <windows.h>
#define _KS_UH 1 //״̬:ſ
#define _KS_UC 2 //״̬:ǰſ
#define _KS_DH 3 //״̬:
#define _KS_DC 4 //״̬:ǰ
class CGameInput
{
private:
//
HWND m_hWnd;
//״̬ΪWindowsֵ֧İ0xfe
//256涨װÿ
//״̬ˣֱÿļֵΪ±
int m_KeyState[256];
public:
//
CGameInput(HWND hWnd);
//
void Run();
//õij״̬
int GetKeyState(unsigned char VirtualKeyCode);
//õǰڿͻ꣬ڿ
//ͷ棬ڿͻоͷؼ
bool GetCursorPosition(int* X, int* Y);
};
#endif | true |
705d37ce1938b389a581baa9a19596a9e05efa90 | C++ | MichaelBridgette/Overhead-Racing-Game | /Joint Project/Ai.h | UTF-8 | 1,447 | 2.625 | 3 | [] | no_license | #pragma once
#include <SFML\Graphics.hpp>
#include "Car.h"
#include <Thor/Vectors.hpp>
#include "PhysicsBalls.h"
#include "Math.h"
/// <summary>
/// @mainpage Joint Project - 2D racing game.
/// @Author Dylan Murphy, Sean Regan, Micheal Bridgette, David O'Gorman
/// @Version 1.0
/// @brief A 2D racing game.
/// </summary>
class Ai
{
public:
Ai(Game &game, float carX, float carY, sf::Texture &carTexture, std::vector<sf::CircleShape> & const track);
~Ai();
void update(); // Update loop
void render(sf::RenderWindow &window); // Draw loop
void resetNode(); // Go to start of track
Car m_car; // Ai's car
private:
Game *m_game;
// These variables were moved here to save memory
sf::Vector2f trackDisVector;
sf::Vector2f aiDisVector;
sf::Vector2f vectorToNode;
sf::Vector2f m_steering;
sf::Vector2f m_velocity;
sf::Sprite m_closest;
sf::Vector2f m_ahead;
sf::Vector2f m_halfAhead;
const float MAX_FORCE = 10.0f;
float MAX_SPEED = 10.0f;
sf::Vector2f seekTrack(std::vector<sf::CircleShape> track, sf::Vector2f pos); // Method to find direction towards the next node
int m_target; // index to tell which node to head to next
std::vector<sf::CircleShape> & m_track; // Track to be followed
// Variables and methods used for the collision avoidance
const float MAX_AVOID_FORCE = 5.0f;
std::vector<sf::Sprite> m_obstacles;
sf::Sprite Ai::findMostThreateningObstacle();
const float MAX_SEE_AHEAD = 5.0f;
sf::Vector2f collisionAvoidance();
};
| true |
bd657d96f6b179e8e5fa638dab5b60f3a2b155d5 | C++ | ivk-jsc/broker | /libs/libupmq/decaf/nio/Buffer.h | UTF-8 | 9,783 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014-present IVK JSC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _DECAF_NIO_BUFFER_H_
#define _DECAF_NIO_BUFFER_H_
#include <decaf/lang/exceptions/IllegalArgumentException.h>
#include <decaf/nio/InvalidMarkException.h>
namespace decaf {
namespace nio {
/**
* A container for data of a specific primitive type.
*
* A buffer is a linear, finite sequence of elements of a specific primitive
* type. Aside from its content, the essential properties of a buffer are
* its capacity, limit, and position:
*
* A buffer's capacity is the number of elements it contains. The capacity of a
* buffer is never negative and never changes.
*
* A buffer's limit is the index of the first element that should not be read
* or written. A buffer's limit is never negative and is never greater than its
* capacity.
*
* A buffer's position is the index of the next element to be read or written.
* A buffer's position is never negative and is never greater than its limit.
*
* There is one subclass of this class for each non-boolean primitive type.
*
* Transferring data:
* Each subclass of this class defines two categories of get and put operations:
* * Relative operations read or write one or more elements starting at the
* current position and then increment the position by the number of
* elements transferred. If the requested transfer exceeds the limit then a
* relative get operation throws a BufferUnderflowException and a relative
* put operation throws a BufferOverflowException; in either case, no data
* is transferred.
* * Absolute operations take an explicit element index and do not affect the
* position. Absolute get and put operations throw an IndexOutOfBoundsException
* if the index argument exceeds the limit.
*
* Data may also, of course, be transferred in to or out of a buffer by the I/O
* operations of an appropriate channel, which are always relative to the current
* position.
*
* Marking and resetting:
*
* A buffer's mark is the index to which its position will be reset when the
* reset method is invoked. The mark is not always defined, but when it is
* defined it is never negative and is never greater than the position. If the
* mark is defined then it is discarded when the position or the limit is
* adjusted to a value smaller than the mark. If the mark is not defined then
* invoking the reset method causes an InvalidMarkException to be thrown.
*
* Invariants:
*
* The following invariant holds for the mark, position, limit, and capacity values:
* 0 <= mark <= position <= limit <= capacity
*
* A newly-created buffer always has a position of zero and a mark that is
* undefined. The initial limit may be zero, or it may be some other value that
* depends upon the type of the buffer and the manner in which it is constructed.
* The initial content of a buffer is, in general, undefined.
*
* Clearing, flipping, and rewinding:
*
* In addition to methods for accessing the position, limit, and capacity values
* and for marking and resetting, this class also defines the following operations
* upon buffers:
*
* clear() makes a buffer ready for a new sequence of channel-read or relative
* put operations: It sets the limit to the capacity and the position to zero.
*
* flip() makes a buffer ready for a new sequence of channel-write or relative
* get operations: It sets the limit to the current position and then sets the
* position to zero.
*
* rewind() makes a buffer ready for re-reading the data that it already
* contains: It leaves the limit unchanged and sets the position to zero.
*
* Read-only buffers:
*
* Every buffer is readable, but not every buffer is writable. The mutation
* methods of each buffer class are specified as optional operations that will
* throw a ReadOnlyBufferException when invoked upon a read-only buffer. A
* read-only buffer does not allow its content to be changed, but its mark,
* position, and limit values are mutable. Whether or not a buffer is read-only
* may be determined by invoking its isReadOnly method.
*
* Thread safety:
*
* Buffers are not safe for use by multiple concurrent threads. If a buffer is to
* be used by more than one thread then access to the buffer should be controlled
* by appropriate synchronization.
*
* Invocation chaining:
*
* Methods in this class that do not otherwise have a value to return are specified
* to return the buffer upon which they are invoked. This allows method invocations
* to be chained; for example, the sequence of statements
*
* b.flip();
* b.position(23);
* b.limit(42);
*
* can be replaced by the single, more compact statement
* b.flip().position(23).limit(42);
*/
class DECAF_API Buffer {
protected:
mutable int _position;
int _capacity;
int _limit;
int _mark;
bool _markSet;
public:
explicit Buffer(int capactiy);
Buffer(const Buffer &other);
virtual ~Buffer() = default;
public:
/**
* @return this buffer's capacity.
*/
virtual int capacity() const { return this->_capacity; }
/**
* @return the current position in the buffer
*/
virtual int position() const { return this->_position; }
/**
* Sets this buffer's position. If the mark is defined and larger than the
* new position then it is discarded.
*
* @param newPosition
* The new postion in the buffer to set.
*
* @return a reference to This buffer.
*
* @throws IllegalArgumentException if preconditions on the new pos don't hold.
*/
virtual Buffer &position(int newPosition);
/**
* @return this buffers Limit
*/
virtual int limit() const { return this->_limit; }
/**
* Sets this buffer's limit. If the position is larger than the new limit then
* it is set to the new limit. If the mark is defined and larger than the new
* limit then it is discarded.
*
* @param newLimit
* The new limit value; must be no larger than this buffer's capacity.
*
* @return A reference to This buffer
*
* @throws IllegalArgumentException if preconditions on the new pos don't hold.
*/
virtual Buffer &limit(int newLimit);
/**
* Sets this buffer's mark at its position.
*
* @return a reference to this buffer.
*/
virtual Buffer &mark();
/**
* Resets this buffer's position to the previously-marked position.
*
* @return a reference to this buffer.
*
* @throws InvalidMarkException - If the mark has not been set
*/
virtual Buffer &reset();
/**
* Clears this buffer. The position is set to zero, the limit is set to the
* capacity, and the mark is discarded.
*
* Invoke this method before using a sequence of channel-read or put operations
* to fill this buffer. For example:
*
* buf.clear(); // Prepare buffer for reading
* in.read(buf); // Read data
*
* This method does not actually erase the data in the buffer, but it is named
* as if it did because it will most often be used in situations in which that
* might as well be the case.
*
* @return a reference to this buffer.
*/
virtual Buffer &clear();
/**
* Flips this buffer. The limit is set to the current position and then the
* position is set to zero. If the mark is defined then it is discarded.
*
* After a sequence of channel-read or put operations, invoke this method to
* prepare for a sequence of channel-write or relative get operations. For
* example:
*
* buf.put(magic); // Prepend header
* in.read(buf); // Read data into rest of buffer
* buf.flip(); // Flip buffer
* out.write(buf); // Write header + data to channel
*
* This method is often used in conjunction with the compact method when
* transferring data from one place to another.
*
* @return a reference to this buffer.
*/
virtual Buffer &flip();
/**
* Rewinds this buffer. The position is set to zero and the mark is discarded.
*
* Invoke this method before a sequence of channel-write or get operations,
* assuming that the limit has already been set appropriately. For example:
*
* out.write(buf); // Write remaining data
* buf.rewind(); // Rewind buffer
* buf.get(array); // Copy data into array
*
* @return a reference to this buffer.
*/
virtual Buffer &rewind();
/**
* Returns the number of elements between the current position and the limit.
*
* @return The number of elements remaining in this buffer
*/
virtual int remaining() const { return _limit - _position; }
/**
* Tells whether there are any elements between the current position and the limit.
*
* @return true if, and only if, there is at least one element remaining in
* this buffer.
*/
virtual bool hasRemaining() const { return remaining() != 0; }
/**
* Tells whether or not this buffer is read-only.
*
* @return true if, and only if, this buffer is read-only.
*/
virtual bool isReadOnly() const = 0;
};
} // namespace nio
} // namespace decaf
#endif /*_DECAF_NIO_BUFFER_H_*/
| true |
0935657851dbb0cba37ac25120a4cca994011db6 | C++ | DmitriyODS/clock | /Store/Clock/reducer/reducer.cpp | UTF-8 | 1,415 | 2.734375 | 3 | [] | no_license | #include "reducer.h"
ClockState clockReducer(ClockState state, Action action) {
switch (action.type) {
case ActionTypes::SET_COLOR_ARROW_HOUR: {
state.color_clock.hour = *static_cast<Color *>(action.data);
return state;
}
case ActionTypes::SET_COLOR_ARROW_MINUTES: {
state.color_clock.minutes = *static_cast<Color *>(action.data);
return state;
}
case ActionTypes::SET_COLOR_ARROW_SECONDS: {
state.color_clock.seconds = *static_cast<Color *>(action.data);
return state;
}
case ActionTypes::SET_COLOR_CLOCK_BACKGROUND: {
state.color_clock.background = *static_cast<Color *>(action.data);
return state;
}
case ActionTypes::SET_COLOR_CLOCK_TEXT: {
state.color_clock.text = *static_cast<Color *>(action.data);
return state;
}
case ActionTypes::SET_CLOCK_TIME: {
state.current_time = *static_cast<ClockTime *>(action.data);
return state;
}
case ActionTypes::RUN_CLOCK_TIME_DAEMON: {
state.run_clock_time_daemon = true;
return state;
}
case ActionTypes::STOP_CLOCK_TIME_DAEMON: {
state.run_clock_time_daemon = false;
return state;
}
default: {
return state;
}
}
}
| true |
e30c47c15a3e73742fe0d2edddb1d7d351f1233c | C++ | openbmc/phosphor-ipmi-flash | /bmc/version-handler/test/version_canhandle_enumerate_unittest.cpp | UTF-8 | 765 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #include "version_handler.hpp"
#include "version_mock.hpp"
#include <array>
#include <gtest/gtest.h>
namespace ipmi_flash
{
TEST(VersionHandlerCanHandleTest, VerifyGoodInfoMap)
{
constexpr std::array blobNames{"blob0", "blob1", "blob2", "blob3"};
VersionBlobHandler handler(createMockVersionConfigs(blobNames));
for (const auto& blobName : blobNames)
{
EXPECT_TRUE(handler.canHandleBlob(blobName));
}
}
TEST(VersionHandlerEnumerateTest, VerifyGoodInfoMap)
{
constexpr std::array blobNames{"blob0", "blob1", "blob2", "blob3"};
VersionBlobHandler handler(createMockVersionConfigs(blobNames));
EXPECT_THAT(handler.getBlobIds(),
::testing::UnorderedElementsAreArray(blobNames));
}
} // namespace ipmi_flash
| true |
8c6760050d1a4309fc29480423924afc4e0cc0bb | C++ | moecia/CMPM-265_Flocking | /Vehicle.cpp | UTF-8 | 1,637 | 2.765625 | 3 | [] | no_license | #include "Vehicle.h"
#include "MyMathLib.h"
using namespace sf;
Vehicle::Vehicle(sf::RenderWindow* window)
{
acceleration = Vector2f(0, 0);
veclocity = Vector2f(0, 0);
location = (Vector2f)sf::Mouse::getPosition(*window);
r = 25.0f;
maxSpeed = 200;
maxForce = 1.0f;
shape.setRadius(6);
shape.setPointCount(3);
shape.setScale(1, 2);
shape.setPosition(location);
}
Vehicle::~Vehicle()
{
}
void Vehicle::Update(sf::RenderWindow* window, float deltaTime)
{
// TODO: Clamp velocity and force
veclocity += acceleration * deltaTime;
location += veclocity * deltaTime;
acceleration = acceleration * 0.0f;
shape.setRotation(atan2(veclocity.x, -veclocity.y) * 180 / 3.14f);
shape.setPosition(location);
if (shape.getPosition().x > window->getSize().x - 5)
shape.setPosition(5, shape.getPosition().y);
if (shape.getPosition().x < 5)
shape.setPosition(window->getSize().x - 5, shape.getPosition().y);
if (shape.getPosition().y > window->getSize().y - 5)
shape.setPosition(shape.getPosition().x, 5);
if (shape.getPosition().y < 5)
shape.setPosition(shape.getPosition().y, window->getSize().y - 5);
}
void Vehicle::ApplyForce(sf::Vector2f steer)
{
acceleration += steer;
}
void Vehicle::SeekNearbyGroup(sf::Vector2f target)
{
location = shape.getPosition();
Vector2f desired = Vector2f(0, 0);
if (MyMathLib::Magnitude(target - location) > r)
{
desired = MyMathLib::Normalize((target - location)) * maxSpeed;
Vector2f steer = desired - veclocity;
ApplyForce(steer);
}
else
desired *= MyMathLib::map(
MyMathLib::Magnitude(target - location),
Vector2f(0, 0),
Vector2f(r * 4, maxSpeed));
} | true |
6301a3dc5d369efd005a84f3b9c323527e00c252 | C++ | slagozd/Cplusplus | /IntroC++/from_line_to_file.cpp | UTF-8 | 583 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
if (argc!=3)
{
cout<<"Wrong number of parameters"<<endl;
return 0;
}
ifstream input_file;
input_file.open (argv[1]);
ofstream output_file;
output_file.open (argv[2]);
char c = input_file.get();
output_file<<"Kopia pliku "<<argv[2]<<endl;
while (input_file.good())
{
cout << c;
output_file << c;
//input_file>>Liczba;
c = input_file.get();
}
input_file.close();
output_file.close();
}
| true |
fbf3ebe4789d248c123b13020bd7a57255a1a2fe | C++ | StanPal/MAGE | /Framework/Core/Src/TimeUtil.cpp | UTF-8 | 1,100 | 2.921875 | 3 | [] | no_license | #include "Precompiled.h"
#include "TimeUtil.h"
using namespace MAGE::Core;
float MAGE::Core::TimeUtil::GetTime()
{
//HighResClock is best clock your pc gives you, which is your system clock,
//Because it is static the first time we call it, is when you start the stopwatch
static const auto startTime = std::chrono::high_resolution_clock::now();
//Get the current tick
auto now = std::chrono::high_resolution_clock::now();
//Cast it the milliseconds when we divide it be a 1000 we get seconds
return std::chrono::duration_cast<std::chrono::milliseconds>(now - startTime).count() / 1000.0f;
}
float MAGE::Core::TimeUtil::GetDeltaTime()
{
//Using static so that we only initialize on first call
static auto lastTime = std::chrono::high_resolution_clock::now();
auto currentTime = std::chrono::high_resolution_clock::now();
//Find the difference the last time you called the function to the current time you called the function
auto deltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - lastTime).count() / 1000.0f;
lastTime = currentTime;
return deltaTime;
}
| true |
957f44f3a121ff89b170a08092ed9704014f440f | C++ | cde8eae8/ITMO-s5 | /translation/labs/lab4-cpp/main.cpp | UTF-8 | 3,587 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <any>
#include <vector>
#include <sstream>
#include "parsing_table_generator.h"
#include "parser.h"
std::unordered_map<std::string, std::vector<std::vector<std::string>>> testGrammar = {
std::make_pair("S", std::vector<std::vector<std::string>>{{"C", "C"}}),
std::make_pair("C", std::vector<std::vector<std::string>>{{"c", "C"},
{"d"}}),
};
std::unordered_map<std::string, std::vector<std::vector<std::string>>> testGrammar2 = {
std::make_pair("S'", std::vector<std::vector<std::string>>{{"A"}}),
std::make_pair("A", std::vector<std::vector<std::string>>{{"C", "C"},
{"B", "b", "n"},
{"A"},
{"B", "B", "B", "t"},
{"B", "B", "B", "H"}}),
std::make_pair("B", std::vector<std::vector<std::string>>{{"C", "d"},
{"b", "bbb"},
{"B", "f"},
{"A"},
{}}),
std::make_pair("C", std::vector<std::vector<std::string>>{{"c", "C"},
{"d"}}),
std::make_pair("H", std::vector<std::vector<std::string>>{{"h"}}),
std::make_pair("T", std::vector<std::vector<std::string>>{{"B", "B", "B", "B", "B"},
{"g"}})
};
std::unordered_map<std::string, std::vector<std::vector<std::string>>> testGrammar3 = {
std::make_pair("S'", std::vector<std::vector<std::string>>{{"S"}}),
std::make_pair("S", std::vector<std::vector<std::string>>{{"C", "C"}}),
std::make_pair("C", std::vector<std::vector<std::string>>{{"c", "C"},
{"d"}}),
};
//struct Lexer {
// Lexer() {
// s = "cdcccccccccd";
// pos = -1;
// }
//
// TerminalGrammarSymbol next() {
// pos++;
// if (pos >= s.size()) return terminal_EOF();
//// if (s[pos] == 'c') return terminal_c();
//// if (s[pos] == 'd') return terminal_d();
// }
//
//private:
// std::string s;
// size_t pos;
//};
#include "gram.hpp"
#include <memory>
std::map<std::string, std::string> identifiers;
std::unordered_map<std::string, std::vector<RawRule>> rawGrammar;
std::string startNonterminal;
std::string header;
std::ostream &operator<<(std::ostream &out, RawRule const &rule) {
out << rule.body << " " << rule.code << std::endl;
return out;
}
#include "..."
int main(int argc, char** argv) {
parse();
std::cout << someGlobalVariable << std::endl;
}
int main(int argc, char** argv) {
if (argc == 1) {
std::cout << "args" << std::endl;
return 1;
}
yy::parser parseInput;
parseInput ();
rawGrammar.insert(std::make_pair("S'", std::vector<RawRule>{RawRule{{startNonterminal}, {"return _1;"}}}));
for (auto const& p : rawGrammar) {
std::cout << p.first << " : " << p.second << std::endl;
}
identifiers.insert(std::make_pair("S'", identifiers[startNonterminal]));
convertGrammar(argv[1], header, rawGrammar, identifiers);
return 0;
}
| true |
e1af26f11a7cd2dd4542d8b4f43d765201bfb300 | C++ | chungthaidung/MarioBros | /Project1/Cell.cpp | UTF-8 | 487 | 2.953125 | 3 | [] | no_license | #include "Cell.h"
Cell::Cell(int x, int y)
{
this->x = x;
this->y = y;
}
void Cell::Add(CGameObject* obj)
{
listobj.insert(obj);
}
unordered_set<CGameObject*> Cell::GetListObj()
{
return listobj;
}
void Cell::RemoveObj(CGameObject* obj)
{
auto find = listobj.find(obj);
if (find == listobj.end())
return;
listobj.erase(obj);
}
void Cell::Clear()
{
for (auto t: listobj)
delete t;
listobj.clear();
}
void Cell::GetIndex(int& x, int& y)
{
x = this->x;
y = this->y;
}
| true |
4ff5340561785afbd6c440cefe4816641b073c94 | C++ | SayaUrobuchi/uvachan | /Kattis/glitchbot.cpp | UTF-8 | 1,008 | 2.65625 | 3 | [] | no_license | #include <iostream>
int n;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int cx[] = {1, 0, 0};
int cy[] = {1, 0, 0};
int cd[] = {0, 3, 1};
int cmd[64];
char buf[64];
const char *cname[3] = {"Forward", "Left", "Right"};
bool check(int ex, int ey)
{
int x, y, d, i;
x = 0;
y = 0;
d = 0;
for (i=0; i<n; i++)
{
x += dx[d] * cx[cmd[i]];
y += dy[d] * cy[cmd[i]];
d = ((d+cd[cmd[i]]) & 3);
}
//printf("final: %d %d\n", x, y);
return x == ex && y == ey;
}
int main()
{
int ex, ey, i, j;
while (scanf("%d%d", &ex, &ey) == 2)
{
scanf("%d", &n);
for (i=0; i<n; i++)
{
scanf("%s", buf);
if (*buf == 'F')
{
cmd[i] = 0;
}
else if (*buf == 'L')
{
cmd[i] = 1;
}
else
{
cmd[i] = 2;
}
}
for (i=0; i<n; i++)
{
for (j=0; j<2; j++)
{
cmd[i] = (cmd[i]+1) % 3;
if (check(ex, ey))
{
printf("%d %s\n", i+1, cname[cmd[i]]);
break;
}
}
cmd[i] = (cmd[i]+1) % 3;
if (j < 2)
{
break;
}
}
}
return 0;
}
| true |
d65dab573247c4b72734f9e0ab4955f9a5aa55e3 | C++ | 8l/HrwCC | /vm/Memory.h | UTF-8 | 1,915 | 3.0625 | 3 | [] | no_license | #ifndef MEMORY_H
#define MEMORY_H
#include <vector>
#include "AllocateNode.h"
#include "VMConfig.h"
#include "GenericException.h"
#include "InstructionsFetcher.h"
//#include "ExecParser.h"
typedef char byte;
/**
* this is a full blown memory allocating class
* that allows dynamic memory allocation and deallocation
*/
class Memory
{
public:
byte *memory[VM_VIRTUAL_MEM_SIZE];
bool args_pushed;
vector<AllocateNode> allocate_nodes;
protected:
/*
* make sure the given address is within our memory boundaries
*/
void assertBoundaries(int addr, int block);
/*
* make sure the given block is allocated
*/
void assertBlock(int addr, int block);
/*
* returns the block to the given address
*/
int getBlock(int addr);
/*
* returns the slot to the given address
*/
int getSlot(int addr);
/*
* inserts a node with a given size into a list of nodes
*/
int insertAllocateNode(AllocateNode new_node);
/*
* allocates new blocks if we cross boundries
*/
void allocateBlocks();
public:
Memory();
~Memory();
/**
* set the program arguments that will be put
* into the argument block
*/
void setProgramArguments(int argc, char **argv);
/**
* allocate 'size' bytes of memory
* returns a pointer to the allocated memory
* or -1 in case of error
*/
int allocate(int size);
/**
* frees the given pointer to the allocated memory
*/
void free(int mem);
/**
* Get the size of block at mem
*/
int getSizeOfMalloc(int mem);
/*
* store a byte at this address
*/
void setb(int addr, char val);
/*
* get a byte from this address
*/
char getb(int addr);
/*
* store a long (sizeof(int)) at this address
*/
void setl(int addr, int val);
/*
* get a long (sizeof(int)) beginning from address
*/
int getl(int addr);
void print(int start, int end);
};
#endif
| true |
96827b535ed9a5a78c74999fa9aa9e0d0bfe8c27 | C++ | farnazkohankhaki/CPP-Codes-Archive | /Programming Class/Number of permutation.cpp | UTF-8 | 475 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int MAXN = 100 + 10;
int n, a[MAXN], t[MAXN], f[MAXN];
int number()
{
int ans = 1;
f[0] = 1;
for (int i = 1; i <= n; i++)
f[i] = f[i - 1] * i;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j < i; j++)
if (a[j] < a[i])
t[a[i]]--;
ans += t[a[i]] * f[n - i];
}
return ans;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
t[i] = i - 1;
}
cout << number() << endl;
return 0;
} | true |
e0f34e2cd835e0ea3320c2b459d8b809c4642ac4 | C++ | Bright1992/leetcode | /396.cpp | UTF-8 | 398 | 2.921875 | 3 | [] | no_license | //
// Created by Bright on 2017/1/3.
//
#include <vector>
#include <iostream>
using namespace std;
int maxRotateFunction(vector<int>& A){
int n=A.size();
int sum=0,msum=0,tsum=0;
for(int i=0;i<n;++i) {
msum += i * A[i];
sum += A[i];
}
tsum=msum;
for(int i=n-2;i>=0;--i){
tsum=tsum+sum-n*A[i+1];
msum=max(msum,tsum);
}
return msum;
} | true |
5b195244cfa30c4624a9614bd3d9d05a2d228926 | C++ | pavelsimo/ProgrammingContest | /spoj/7974_ACPC10A/P7974.cpp | UTF-8 | 1,302 | 2.609375 | 3 | [] | no_license | /* @BEGIN_OF_SOURCE_CODE */
/* @SPOJ ACPC10A C++ "Ad Hoc, Math, Arithmetic progression, Geometric progression" */
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <list>
#include <bitset>
#include <deque>
#include <numeric>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <climits>
#include <sys/time.h>
#include <regex.h>
using namespace std;
#define DEBUG(x) cout << #x << ": " << x << endl
#define sz(a) int((a).size())
#define all(x) (x).begin(),(x).end()
#define foreach(it,c) for(typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
const int MAXN = 3;
int a[MAXN], ratio;
bool isArithmetic() {
int d = a[1]-a[0];
ratio = d;
return a[1]==a[0]+d && a[2]==a[0]+2*d;
}
bool isGeometric() {
if(a[0]==0) return false;
int d = a[1]/a[0];
ratio = d;
return a[1]==a[0]*d && a[2]==a[1]*d;
}
int main(int argc, char *argv[]) {
while(scanf("%d%d%d",&a[0], &a[1], &a[2])==3) {
if(a[0]==0 && a[1]==0 && a[2]==0) break;
if(isArithmetic()) printf("AP %d\n",a[2]+ratio);
else if(isGeometric()) printf("GP %d\n",a[2]*ratio);
}
return 0;
}
/* @END_OF_SOURCE_CODE */
| true |
01a87938928f57c584b4fc04567962482a4267f8 | C++ | mzhKU/prcpp_lecture | /testat01/SOLUTION_TESTAT02/UnitTestVector/UnitTestsVector.cpp | UTF-8 | 5,091 | 2.609375 | 3 | [] | no_license | #include "pch.h"
#include "CppUnitTest.h"
#include "..\Testat03\Expression.hpp"
#include "..\Testat03\Vector.hpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
#define AUFGABE1
#define AUFGABE2
#define AUFGABE3
/*
#define AUFGABE4
#define AUFGABE4_1
*/
namespace UnitTest1 {
TEST_CLASS(Expression) {
public:
#ifdef AUFGABE1
// Aufgabe 1
TEST_METHOD(VectorVector) {
Vector<double, 5> A({ 1, 2, 3, 4, 5 });
Vector<double, 5> B({ 1, 4, 9, 16, 25 });
Vector<double, 5> C({ 2, 6, 12, 20, 30 });
Vector<double, 5> D;
D = A;
Assert::IsTrue(D == A);
D = A * A;
Assert::IsTrue(D == B);
Assert::IsTrue(A * A == B);
Assert::IsTrue(B[4] == (A * A)[4]);
auto E = B / A;
Assert::IsTrue(E == A);
Assert::IsTrue(A[3] == (B / A)[3]);
Assert::IsTrue(A[3] == E[3]);
Assert::IsTrue(C == A + B);
Assert::IsTrue(A + B == C);
Assert::IsTrue(C[2] == (B + A)[2]);
Assert::IsTrue(C - A == B);
Assert::IsTrue(A[1] == (C - B)[1]);
}
// Aufgabe 1
TEST_METHOD(Expr) {
Vector<double, 5> A({ 1, 2, 3, 4, 5 });
Vector<double, 5> B({ 1, 4, 9, 16, 25 });
Vector<double, 5> C({ 2, 6, 12, 20, 30 });
auto D = A * B * C;
Assert::IsTrue(D == C * B * A);
Assert::IsTrue(D == B * C * A);
Assert::IsTrue(D == B * A * C);
auto E = B * C / A;
Assert::IsTrue(E == B / A * C);
Assert::IsTrue(C * B / A == E);
Assert::IsTrue((A + B) * A == C * A);
Assert::IsTrue(A * C == A * (B + A));
Assert::IsTrue(A * (A + B) / A == C);
Assert::IsTrue((C + B) / A == C / A + B / A);
Assert::IsTrue((A + B) - B == A);
Assert::IsTrue(A == (A - B) + B);
Assert::IsTrue((A + B) - (C - A) == A);
Assert::IsTrue(A + B + B + A == C + C - B + B - (A + A) + A + A);
Assert::IsTrue((A * B)[1] == (C / A)[4] + (C / A)[0]);
}
#endif
#ifdef AUFGABE2
// Aufgabe 2
TEST_METHOD(VectorScalar) {
Vector<double, 5> A({ 1, 2, 3, 4, 5 });
Vector<double, 5> B({ 0.5, 1.0, 1.5, 2.0, 2.5 });
Vector<double, 5> C({ 2, 3, 4, 5, 6 });
Vector<double, 5> D({ 3, 3, 3, 3, 3 });
Vector<double, 5> E({ 3, 1, -1, -3, -5 });
Vector<double, 5> F({ 2, 2, 2, 2, 2 });
auto G = A * 0.5;
auto H = 0.5 * A;
Assert::IsTrue(G == B);
Assert::IsTrue(H == B);
Assert::IsTrue(B == G);
Assert::IsTrue(B == H);
Assert::IsTrue(A / 2.0 == B);
Assert::IsTrue((2.0 / A)[3] == B[0]);
Assert::IsTrue(B == A / 2.0);
Assert::IsTrue(B[1] == (2.0 / A)[1]);
Assert::IsTrue(A + 1.0 == C);
Assert::IsTrue(1.0 + A == C);
Assert::IsTrue(C == A + 1.0);
Assert::IsTrue(C == 1.0 + A);
Assert::IsTrue(C - 1.0 == A);
Assert::IsTrue((5.0 - A)[1] == C[1]);
Assert::IsTrue(A == C - 1.0);
Assert::IsTrue(C[0] == (5.0 - A)[2]);
auto e = (A + C + E) / 3.0;
Assert::IsTrue(e == F);
auto f = A + D;
A = f;
Assert::IsTrue(e == D);
A[1] = 0;
Assert::IsFalse(e == D);
}
// Aufgabe 2
TEST_METHOD(ExprScalar) {
Vector<double, 5> A({ 1, 2, 3, 4, 5 });
Vector<double, 5> B({ 1, 4, 9, 16, 25 });
Vector<double, 5> C({ 2, 6, 12, 20, 30 });
Vector<double, 5> D({ 1, 1, 1, 1, 1 });
Assert::IsTrue(A + B + B + A == 2.0 * C);
Assert::IsTrue(C * 2.0 == (B + B) + (A + A));
Assert::IsTrue(3.0 * (A + B) - (B + A) * 2.0 == C);
Assert::IsTrue(3.0 + (A + B) - 3.0 == C);
Assert::IsTrue(2.0 * (C - B) / 2.0 + B == (A * 4.0 + 4.0 * B) / 4.0);
Assert::IsTrue((A + B) / C == D);
Assert::IsTrue((((A + B) / C) * 9.0)[3] == B[2]);
Assert::IsTrue(B[4] == (25.0 * ((C + B) / A) / 11.0)[4]);
}
#endif
#ifdef AUFGABE3
// Aufgabe 3
TEST_METHOD(Sum) {
Vector<double, 5> A({ 1, 2, 3, 4, 5 });
Assert::IsTrue(15 == sum(A));
Assert::IsTrue(30 == sum(2.0 * A));
Assert::IsTrue(30 == sum(A * 2.0));
Assert::IsTrue(55 == sum(A * A));
Assert::IsTrue(14 == sum(A, 1));
Assert::IsTrue(28 == sum(2.0 * A, 1));
Assert::IsTrue(28 == sum(A * 2.0, 1));
Assert::IsTrue(54 == sum(A * A, 1));
Assert::IsTrue(5 == sum(A, 1, 3));
Assert::IsTrue(10 == sum(2.0 * A, 1, 3));
Assert::IsTrue(10 == sum(A * 2.0, 1, 3));
Assert::IsTrue(13 == sum(A * A, 1, 3));
}
#endif
#ifdef AUFGABE4
// Aufgabe 4
TEST_METHOD(DotProduct) {
Vector<double, 5> A({ 1, 2, 3, 4, 5 });
Vector<double, 5> B({ 1, 4, 9, 16, 25 });
Vector<double, 5> C({ 2, 6, 12, 20, 30 });
auto D = A * *B;
Assert::IsTrue(D == B * *A);
Assert::IsTrue(double(D) == 1.0 + 8 + 27 + 64 + 125);
double d = A * *(A + B);
Assert::IsTrue(d == (B + A) * *A);
d = (B + A) * *A;
Assert::IsTrue(A * *(A + B) == d);
Assert::IsTrue(D * (A + B) / (B * *A) == C);
Assert::IsTrue(D * C - B * (B * *A) == A * (A * *B));
Assert::IsTrue((A * A) * *(B * B) == (A * B) * *(B * A));
Assert::IsTrue(A * *B * 2.0 == 2.0 * B * *A);
d = A * *B * 2.0;
Assert::IsTrue(d == 2.0 * B * *A);
d = 2.0 * B * *A;
Assert::IsTrue(2.0 * B * *A == d);
d = 2.0 + A * *B - 2.0;
Assert::IsTrue(d == B * *A);
}
#endif
#ifdef AUFGABE4_1
TEST_METHOD(DotProduct2) {
Vector<double, 5> A({ 1, 2, 3, 4, 5 });
Vector<double, 5> B({ 1, 4, 9, 16, 25 });
Assert::IsTrue(50625 == A * *(B * (A * *B)));
Assert::IsTrue(50625 == (A * *B) * (A * *B));
}
#endif
};
} | true |
f21910bc5bcea4eb075c9d3c6f5b70303cde2871 | C++ | jordancharest/School-Work | /Data Structures/HOMEWORK/HW3/the_stack.h | UTF-8 | 1,277 | 3.25 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <stdint.h>
#include <vector>
#include <string>
// ==============================================================================
//
// This class supports a limited visualization / printing of the data
// stored on the stack in the range of the addresses currently
// "labeled" and stored in the member variables.
//
// To make the output more readable, this visualization assumes that
// integer "values" will be between -10000 & 10000 and addresses will
// be within +/- 1000*4 (or *8) bytes from any of the labeled
// addresses. Anything else is assumed to be "garbage" (or floating
// point values).
//
class TheStack {
public:
// ACCESSORS
std::string get_label(intptr_t* address) const;
bool is_return_address(intptr_t* address) const;
// MODIFIERS
void clear_labels();
void set_label(intptr_t* address, const std::string& label);
void tag_return_address(intptr_t* address);
// PRINTING!
void print() const;
private:
// PRIVATE REPRESENTATION
std::vector<intptr_t*> labeled_addresses;
std::vector<std::string> labels;
std::vector<intptr_t*> return_addresses;
};
// ==============================================================================
| true |
c79b76a3d3a010e0a8ca5916c48542347e61b714 | C++ | ElhadjBarry/Jeu_Bataille_Navale | /territoireMaritime.cpp | UTF-8 | 385 | 2.828125 | 3 | [] | no_license | #include "territoireMaritime.h"
TerritoireMaritime::TerritoireMaritime() {
init(-1);
}
void TerritoireMaritime::init(int value) {
for(int i=0; i<50; i++)
for(int j=0; j<50; j++){
cell[i][j] = value;
}
}
void TerritoireMaritime::setCell(int x, int y, int value) {cell[x][y] = value;}
int TerritoireMaritime::getCell(int x, int y) {return cell[x][y];}
| true |
103ba0a12d3327cc1d3e5f67d27a50cb7c8eb37d | C++ | icbtbo/zhiku | /code for practice/数据结构OJ练习/2-L.cpp | UTF-8 | 611 | 3.015625 | 3 | [] | no_license | # include <iostream>
# include <string.h>
using namespace std;
int Index(char S[],char T[]){
int i=1,j=1;
while(i<=strlen(S)&&j<=strlen(T))
{
cout<<S[i-1];
if(S[i-1]==T[j-1])
{
++i;++j;
}
else
{
i=i-j+2;
j=1;
}
}
cout<<endl;
if(j==(strlen(T)+1)) return i-strlen(T);
else return 0;
}
int main(){
char a[200],b[200];
char t[200];
int n=3;
memset(a,0,200);
memset(b,0,200);
memset(t,0,200);
while(n--){
cin>>a>>b;
cout<<Index(a,b)<<endl;
}
return 0;
}
| true |
7df43a0b34d18a0069b9e036d96bb72f8a6f33fa | C++ | IvanLazarov1/workspace2 | /8.FunctionHomeExerciseFunctions-2/src/HomeExerciseFunctions-2.cpp | UTF-8 | 2,053 | 3.453125 | 3 | [] | no_license | //============================================================================
// Name : HomeExerciseFunctions-2.cpp
// Author : ty
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <cctype>
#include <cmath>
using namespace std;
double calculateCharges( double );
int main() {
// 5. A parking garage charges a $2.00 minimum fee to park for up to three hours.
// The garage charges an additional $0.50 per hour for each hour or part thereof
// in excess of three hours. The maximum charge for any given 24-hour period is $10.00.
// Assume that no car parks for longer than 24 hours at a time. Write a program that calculates
// and prints the parking charges for each of three customers who parked their cars in this garage yesterday.
double hour;
double currentCharge;
double totalCharges = 0.0;
double totalHours = 0.0;
int first = 1;
cout << fixed;
cout << "Enter the hours parked for 3 cars: ";
for ( int i = 1; i <= 3; i++ )
{
cin >> hour;
totalHours += hour;
if ( first )
{
cout << setw( 5 ) << "Car" << setw( 15 ) << "Hours"
<< setw( 15 ) << "Charge\n";
first = 0;
}
currentCharge = calculateCharges( hour );
totalCharges += currentCharge;
cout << setw( 3 ) << i << setw( 17 ) << setprecision( 1 ) << hour
<< setw( 14 ) << setprecision( 2 ) << currentCharge << "\n";
}
cout << setw( 7 ) << "TOTAL" << setw( 13 ) << setprecision( 1 )
<< totalHours << setw( 14 ) << setprecision( 2 )
<< totalCharges << endl;
return 0;
}
double calculateCharges( double hours ){
double charge;
if ( hours < 3.0 )
charge = 2.0;
else if ( hours < 24.0 )
charge = 2.0 + .5 * ceil( hours - 3.0 );
else
charge = 10.0;
return charge;
}
| true |
acecafda0e7e45796f532a23522293346a9c53fd | C++ | CoolName11/UrchinEngine | /physicsEngine/src/collision/narrowphase/algorithm/gjk/GJKAlgorithm.cpp | UTF-8 | 7,134 | 2.640625 | 3 | [] | no_license | #include "collision/narrowphase/algorithm/gjk/GJKAlgorithm.h"
namespace urchin
{
template<class T> GJKAlgorithm<T>::GJKAlgorithm() :
maxIteration(ConfigService::instance()->getUnsignedIntValue("narrowPhase.gjkMaxIteration")),
relativeTerminationTolerance(ConfigService::instance()->getFloatValue("narrowPhase.gjkRelativeTerminationTolerance")),
minimumTerminationTolerance(ConfigService::instance()->getFloatValue("narrowPhase.gjkMinimumTerminationTolerance")),
percentageIncreaseOfMinimumTolerance(ConfigService::instance()->getFloatValue("narrowPhase.gjkPercentageIncreaseOfMinimumTolerance"))
{
}
template<class T> GJKAlgorithm<T>::~GJKAlgorithm()
{
}
/**
* @param includeMargin Indicate whether algorithm operates on objects with margin
*/
template<class T> std::unique_ptr<GJKResult<T>> GJKAlgorithm<T>::processGJK(const CollisionConvexObject3D &convexObject1,
const CollisionConvexObject3D &convexObject2, bool includeMargin) const
{ //GJK algorithm (see http://mollyrocket.com/849)
//get point which belongs to the outline of the shape (Minkowski difference)
Vector3<T> initialDirection = Vector3<T>(1.0, 0.0, 0.0);
Point3<T> initialSupportPointA = convexObject1.getSupportPoint(initialDirection, includeMargin);
Point3<T> initialSupportPointB = convexObject2.getSupportPoint(-initialDirection, includeMargin);
Point3<T> initialPoint = initialSupportPointA - initialSupportPointB;
Vector3<T> direction = initialPoint.vector(Point3<T>(0.0, 0.0, 0.0));
Point3<T> closestPointOnSimplex = initialPoint;
Simplex<T> simplex;
simplex.addPoint(initialSupportPointA, initialSupportPointB);
simplex.setBarycentric(0, 1.0);
simplex.setClosestPointToOrigin(closestPointOnSimplex);
T minimumToleranceMultiplicator = (T)1.0;
for(unsigned int iterationNumber=0; iterationNumber<maxIteration; ++iterationNumber)
{
Point3<T> supportPointA = convexObject1.getSupportPoint(direction, includeMargin);
Point3<T> supportPointB = convexObject2.getSupportPoint(-direction, includeMargin);
Point3<T> newPoint = supportPointA - supportPointB;
const Vector3<T> &vClosestPoint = -direction; //vector from origin to closest point of simplex
T closestPointSquareDistance = vClosestPoint.dotProduct(vClosestPoint);
T closestPointDotNewPoint = vClosestPoint.dotProduct(newPoint.toVector());
//check termination conditions: new point is not more extreme that existing ones OR new point already exist in simplex
T distanceTolerance = std::max(minimumTerminationTolerance*minimumToleranceMultiplicator, relativeTerminationTolerance*closestPointSquareDistance);
if((closestPointSquareDistance-closestPointDotNewPoint) <= distanceTolerance || simplex.isPointInSimplex(newPoint))
{
if(closestPointDotNewPoint <= 0.0)
{ //collision detected
return std::unique_ptr<GJKResultCollide<T>>(new GJKResultCollide<T>(simplex));
}else
{
return std::unique_ptr<GJKResultNoCollide<T>>(new GJKResultNoCollide<T>(std::sqrt(closestPointSquareDistance), simplex));
}
}
simplex.addPoint(supportPointA, supportPointB);
updateSimplex(simplex);
closestPointOnSimplex = simplex.getClosestPointToOrigin();
direction = closestPointOnSimplex.vector(Point3<T>(0.0, 0.0, 0.0));
minimumToleranceMultiplicator += percentageIncreaseOfMinimumTolerance;
}
#ifdef _DEBUG
logMaximumIterationReach();
#endif
return std::unique_ptr<GJKResultInvalid<T>>(new GJKResultInvalid<T>());
}
/**
* Update the simplex and return closest point to origin on the simplex
* @return Closest point to origin on the simplex
*/
template<class T> void GJKAlgorithm<T>::updateSimplex(Simplex<T> &simplex) const
{
Point3<T> closestPoint(0.0, 0.0, 0.0);
T barycentrics[4];
if(simplex.getSize() == 2)
{ //simplex is a line (1D)
const Point3<T> &pointA = simplex.getPoint(0);
const Point3<T> &pointB = simplex.getPoint(1); //pointB is the last point added to the simplex
closestPoint = LineSegment3D<T>(pointA, pointB).closestPoint(Point3<T>(0.0, 0.0, 0.0), barycentrics);
simplex.setBarycentric(0, barycentrics[0]);
simplex.setBarycentric(1, barycentrics[1]);
}else if(simplex.getSize() == 3)
{ //simplex is a triangle (2D)
const Point3<T> &pointA = simplex.getPoint(0);
const Point3<T> &pointB = simplex.getPoint(1);
const Point3<T> &pointC = simplex.getPoint(2); //pointC is the last point added to the simplex
const Vector3<T> co = pointC.vector(Point3<T>(0.0, 0.0, 0.0));
const Vector3<T> cb = pointC.vector(pointB);
const Vector3<T> ca = pointC.vector(pointA);
const Vector3<T> normalAbc = cb.crossProduct(ca);
closestPoint = Triangle3D<T>(pointA, pointB, pointC).closestPoint(Point3<T>(0.0, 0.0, 0.0), barycentrics);
simplex.setBarycentric(0, barycentrics[0]);
simplex.setBarycentric(1, barycentrics[1]);
simplex.setBarycentric(2, barycentrics[2]);
if(barycentrics[1]==0.0)
{ //remove pointB
simplex.removePoint(1);
}
if(barycentrics[0]==0.0)
{ //remove pointA
simplex.removePoint(0);
}
if(normalAbc.dotProduct(co) <= 0.0)
{ //voronoi region -ABC => ABC
simplex.swapPoints(0, 1); //swap pointA and pointB
}
}else if (simplex.getSize() == 4)
{ //simplex is a tetrahedron (3D)
const Point3<T> &pointA = simplex.getPoint(0);
const Point3<T> &pointB = simplex.getPoint(1);
const Point3<T> &pointC = simplex.getPoint(2);
const Point3<T> &pointD = simplex.getPoint(3); //pointD is the last point added to the simplex
const short voronoiRegionMask = 14; //test all voronoi regions except the one which doesn't include the new point added (pointD)
closestPoint = Tetrahedron<T>(pointA, pointB, pointC, pointD).closestPoint(Point3<T>(0.0, 0.0, 0.0), barycentrics, voronoiRegionMask);
simplex.setBarycentric(0, barycentrics[0]);
simplex.setBarycentric(1, barycentrics[1]);
simplex.setBarycentric(2, barycentrics[2]);
simplex.setBarycentric(3, barycentrics[3]);
if(barycentrics[2]==0.0)
{ //remove pointC
simplex.removePoint(2);
}
if(barycentrics[1]==0.0)
{ //remove pointB
simplex.removePoint(1);
}
if(barycentrics[0]==0.0)
{ //remove pointA
simplex.removePoint(0);
}
}else
{
std::ostringstream oss;
oss << simplex.getSize();
throw std::invalid_argument("Size of simplex unsupported: " + oss.str() + ".");
}
simplex.setClosestPointToOrigin(closestPoint);
}
#ifdef _DEBUG
template<class T> void GJKAlgorithm<T>::logMaximumIterationReach() const
{
Logger::setLogger(new FileLogger());
Logger::logger()<<Logger::prefix(Logger::LOG_WARNING);
Logger::logger()<<"Maximum of iteration reached on GJK algorithm ("<<maxIteration<<")."<<"\n";
Logger::logger()<<" - Relative termination tolerance: "<<relativeTerminationTolerance<<"\n";
Logger::logger()<<" - Minimum termination tolerance: "<<minimumTerminationTolerance<<"\n";
Logger::logger()<<" - Percentage increase of minimum tolerance: "<<percentageIncreaseOfMinimumTolerance<<"\n";
Logger::setLogger(nullptr);
}
#endif
//explicit template
template class GJKAlgorithm<float>;
}
| true |
1260e62794a07808a27de4df240f0feee1f845cd | C++ | albertomila/continous-formation | /C++11Tests/C++11Tests/Samples/Lambdas.h | UTF-8 | 6,133 | 3.234375 | 3 | [] | no_license | #include "stdafx.h"
#include <algorithm>
#include <vector>
#include <functional>
using FilterContainer = std::vector<std::function<bool(int)>>;
using IntFunction = std::function<int(int)>;
bool FiltersFunction(int i)
{
return false;
}
void AddOperationReference(FilterContainer& filters)
{
auto divisor = 4 / 2;
filters.push_back
( // danger!
[&](int value) { return divisor == 2; } // ref to
);
filters.push_back
( // danger!
[&divisor](int value) { return divisor == 2; } // ref to
);
}
void AddOperationCopyValue(FilterContainer& filters)
{
auto divisor = 4 / 2;
filters.push_back
( // danger!
[=](int value) { return divisor == 2; } // ref to
);
}
//[] don't capture anything
//[&] capture a reference
//[=] capture an object
//[myObject] capture an object
//[myVarMemberCopied] capture a variable
class WidgetLambdas {
public:
bool isValidated() const { return true; }
bool isProcessed() const { return true; }
bool isArchived() const { return true; }
void addFilter(FilterContainer& filters) const
{
/*
filters.push_back
(
//it doesn't compile
//error C4573: the usage of 'Widget::divisor' requires the compiler to capture 'this' but the current default capture mode does not allow it
[](int value) { return value % divisor == 0; }
);
*/
/*
filters.push_back
(
//it doesn't compile
//error C3480: 'Widget::divisor': a lambda capture variable must be from an enclosing function scope
[divisor](int value) { return value % divisor == 0; }
);
*/
//ok, copy member
filters.push_back
(
[=](int value) { return value % divisor == 0; }
);
//ok, capture member
filters.push_back
(
[this](int value) { return value % this->divisor == 0; }
);
//ok, capture member
const WidgetLambdas* widget = this;
filters.push_back
(
[widget](int value) { return value % widget->divisor == 0; }
);
//ok, capture variable
int divisorWidget = divisor;
filters.push_back
(
[divisorWidget](int value) { return value % divisorWidget == 0; }
);
//ok, capture variable
filters.push_back
(
[=](int value) { return value % divisorWidget == 0; }
);
//C++14 capture copy member
filters.push_back
(
[divisor2 = divisor](int value) { return value % divisor2 == 0; }
);
}
private:
int divisor; // used in Widget's filter
};
class WidgetInt
{
public:
//ok
void Test1(IntFunction& intFunction)
{
intFunction = { [=](int value) { return value; } };
}
//ok
void Test2(IntFunction& intFunction)
{
intFunction = { [this](int value) { return this->divisor; } };
}
//ok
void Test3(IntFunction& intFunction)
{
int divisorWidget = divisor;
intFunction = { [divisorWidget](int value) { return divisorWidget; } };
}
//ok
void Test4(IntFunction& intFunction)
{
int divisorWidget = divisor;
intFunction = { [=](int value) { return divisorWidget; } };
}
//ok
void Test5(IntFunction& intFunction)
{
intFunction = { [divisor2 = divisor](int value) { return divisor2; } };
}
//KO!!! dangle variable
void Test6(IntFunction& intFunction)
{
int divisorWidget = divisor;
intFunction = { [&](int value) { return divisorWidget; } };
}
void WidgetInt::Init()
{
IntFunction intFunction;
int resultValue = 0;
//ok
Test1(intFunction);
resultValue = intFunction(1);
//ok
Test2(intFunction);
resultValue = intFunction(2);
//ok
Test3(intFunction);
resultValue = intFunction(3);
//ok
Test4(intFunction);
resultValue = intFunction(4);
//ok
Test5(intFunction);
resultValue = intFunction(5);
//KO!!! dangle variable
Test6(intFunction);
resultValue = intFunction(5);
}
private:
int divisor = 99;
};
BEGIN_TEST(TestLambdas)
{
std::vector<int> container;
container.push_back(0);
container.push_back(1);
container.push_back(2);
container.push_back(3);
container.push_back(4);
container.push_back(5);
container.push_back(6);
int minValue = 4;
int maxValue = 10;
std::vector<int>::iterator it = std::find_if( container.begin()
, container.end()
, [minValue, maxValue](int val)
{
return minValue < val && val < maxValue;
}
);
}
{
FilterContainer filters; // filtering funcs
filters.push_back
( // see Item 42 for
[](int value) { return value % 5 == 0; } // info on
);
filters.push_back(&FiltersFunction);
filters.push_back(::FiltersFunction);
filters.push_back(FiltersFunction);
filters[0](1);
filters[1](1);
filters[2](1);
filters[3](1);
AddOperationReference(filters);
AddOperationCopyValue(filters);
}
{
WidgetInt w;
w.Init();
}
{
WidgetLambdas pw;
std::function<bool()> func = [pw = std::move(pw)]
{
return pw.isValidated() && pw.isArchived();
};
bool b1 = func();
}
END_TEST() | true |
dcb2b1a560fa8de728477f66d36cdc7feb40e544 | C++ | ZuoYuShen/Leetcode-record | /Leetcode-code/41.缺失的第一个正数-hash.cpp | UTF-8 | 606 | 3.046875 | 3 | [
"MIT"
] | permissive | /*
* @lc app=leetcode.cn id=41 lang=cpp
*
* [41] 缺失的第一个正数
*/
// @lc code=start
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
for(int i=0; i<nums.size(); i++){
if(nums[i]<=0) nums[i] = nums.size() + 1;
}
for(int i=0; i<nums.size(); i++){
int x = abs(nums[i]);
if(x <= nums.size()){
nums[x-1] = -abs(nums[x-1]);
}
}
for(int i=0; i<nums.size(); i++){
if(nums[i] > 0) return i+1;
}
return nums.size()+1;
}
};
// @lc code=end | true |
c21eb6da343cd41d800f30b59d77ad4f9a4bd0d4 | C++ | yig/graphics101-meshes | /src/halfedge.h | UTF-8 | 5,710 | 3.15625 | 3 | [] | no_license | #ifndef __halfedge_h__
#define __halfedge_h__
#include "mesh.h" // Triangle
#include <map>
namespace graphics101
{
class HalfEdgeTriMesh
{
public:
// We need a signed integer type so we can use -1 for an invalid index.
typedef long Index;
typedef std::vector< Index > Indices;
// A special type that acts like an integer index but requires the
// user to explicitly create from an integer to prevent bugs.
struct HalfEdgeIndex {
HalfEdgeIndex() : value( -1 ) {}
// Mark the constructor from an integer explicit
// so that an integer can't be silently and automatically converted.
// This is the primary additional type safety.
explicit HalfEdgeIndex( const Index& val ) : value( val ) {}
// Automatically convert back to an Index as needed.
inline operator Index& () { return value; }
inline operator const Index& () const { return value; }
// TODO Q: Do we need to write an explicit operator==()?
// operator==( const HalfEdgeIndex& rhs ) { return this->value == rhs.value; }
// Return true if the index is valid, and false otherwise.
bool valid() const { return value >= 0; }
// The value itself.
Index value;
};
typedef std::vector< HalfEdgeIndex > HalfEdgeIndices;
typedef ivec2 Edge;
typedef std::vector< Edge > Edges;
struct HalfEdge
{
// Index into the vertex array for the vertex this half-edge points to.
Index to_vertex;
// Index into the face array for the face of this half-edge.
Index face;
// Index into the edges array for the edge this half-edge is part of.
Index edge;
// The index into the half-edges array of the opposite half-edge.
// Call halfedge() to get the actual HalfEdge struct.
HalfEdgeIndex opposite_he;
// The index into the half-edges array of the next half-edge around the face.
// Call halfedge() to get the actual HalfEdge struct.
HalfEdgeIndex next_he;
HalfEdge() :
to_vertex( -1 ),
face( -1 ),
edge( -1 ),
opposite_he( -1 ),
next_he( -1 )
{}
};
// Build the half-edge data structure from `triangles`.
// Call unordered_edges_from_triangles( triangles ) to get a vector of undirected edges.
void build( const unsigned long num_vertices, const std::vector< Triangle >& triangles, const Edges& edges );
// Clear the data-structure. You can call build() again after this.
void clear();
// Get the HalfEdge struct for an index.
const HalfEdge& halfedge( const HalfEdgeIndex& halfedge_index ) const { return m_halfedges.at( halfedge_index ); }
HalfEdgeIndex outgoing_halfedge_index_for_vertex( const Index vertex_index ) const { return m_vertex_halfedges.at( vertex_index ); }
// Returns the vertex neighbors (as indices) of the vertex 'vertex_index'.
Indices vertex_vertex_neighbors( const Index vertex_index ) const;
// Returns in 'result' the vertex neighbors (as indices) of the vertex 'vertex_index'.
void vertex_vertex_neighbors( const Index vertex_index, Indices& result ) const;
// Returns the valence (number of vertex neighbors) of vertex with index 'vertex_index'.
int vertex_valence( const Index vertex_index ) const;
// Returns the face neighbors (as indices) of the vertex 'vertex_index'.
Indices vertex_face_neighbors( const Index vertex_index ) const;
// Returns in 'result' the face neighbors (as indices) of the vertex 'vertex_index'.
void vertex_face_neighbors( const Index vertex_index, Indices& result ) const;
// Returns whether the vertex with given index is on the boundary.
bool vertex_is_boundary( const Index vertex_index ) const;
// Returns a vector of vertex indices that lie on the boundary of the mesh.
Indices boundary_vertices() const;
// Returns a list of undirected boundary edges (i,j). If (i,j) is in the result, (j,i) will not be.
Edges boundary_edges() const;
// Given the index of a HalfEdge, returns the corresponding directed edge (i,j).
Edge he_index2directed_edge( const HalfEdgeIndex he_index ) const {
const HalfEdge& he = halfedge( he_index );
return Edge( halfedge( he.opposite_he ).to_vertex, he.to_vertex );
}
// Given a directed edge (i,j), returns the index of the 'HalfEdge' in
// halfedges().
HalfEdgeIndex directed_edge2he_index( const Index i, const Index j ) const;
HalfEdgeIndex directed_edge2he_index( const Edge& ij ) const { return directed_edge2he_index( ij[0], ij[1] ); }
private:
std::vector< HalfEdge > m_halfedges;
// Offsets into the 'halfedges' sequence, one per vertex.
HalfEdgeIndices m_vertex_halfedges;
// Offset into the 'halfedges' sequence, one per face.
HalfEdgeIndices m_face_halfedges;
// Offset into the 'halfedges' sequence, one per edge (unordered pair of vertex indices).
HalfEdgeIndices m_edge_halfedges;
// A map from an ordered edge (an std::pair of Index's) to an offset into the 'halfedge' sequence.
typedef std::map< std::pair< Index, Index >, HalfEdgeIndex > directed_edge2halfedge_index_map_t;
// A map from an ordered edge (an std::pair of Index's) to an offset into a different sequence.
typedef std::map< std::pair< Index, Index >, Index > directed_edge2index_map_t;
directed_edge2halfedge_index_map_t m_directed_edge2he_index;
};
void unordered_edges_from_triangles( const std::vector< Triangle >& triangles, HalfEdgeTriMesh::Edges& edges_out );
}
#endif /* __halfedge_h__ */
| true |
d7d15123f718c2fd51df8304bef24bdf580077cb | C++ | SayaUrobuchi/uvachan | /AtCoder/arc090_a.cpp | UTF-8 | 325 | 2.6875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int ary[2][105];
int main()
{
int n, i;
scanf("%d", &n);
for (i=1; i<=n; i++)
{
scanf("%d", &ary[0][i]);
ary[0][i] += ary[0][i-1];
}
for (i=1; i<=n; i++)
{
scanf("%d", &ary[1][i]);
ary[1][i] += max(ary[0][i], ary[1][i-1]);
}
printf("%d\n", ary[1][n]);
return 0;
}
| true |
769cf78a737ec16857f5d2a0bcd626020aefd389 | C++ | wonter/leetcode-solutions | /1529.bulb-switcher-iv.cpp | UTF-8 | 386 | 2.75 | 3 | [] | no_license | /*
* @lc app=leetcode id=1529 lang=cpp
*
* [1529] Bulb Switcher IV
*/
// @lc code=start
class Solution {
public:
int minFlips(string target) {
int ret = 0;
int now = 0;
for (char ch : target) {
if (ch - '0' != now) {
now ^= 1;
ret += 1;
}
}
return ret;
}
};
// @lc code=end
| true |
3d9ee5237fe08d5fd4ec3b12969f64ca4a5699d9 | C++ | JamesShirazian/COOL | /FastInterrupt.cpp | UTF-8 | 3,178 | 3.390625 | 3 | [] | no_license | #include "FastInterrupt.h"
void(*fastInterruptFunction)(void);
void fastInterruptHandler (void) __irq;
/**
* Default constructor: activate EXTINT0 by default and set its priority to 0 which can be alter by "setFunctionToInterrupt"<br>
* <B><br>Example:<br><B><br>
*
* FastInterrupt myInterrupt; <br>
* myInterrupt.setFunctionToInterrupt(do1); <br>
*/
FastInterrupt::FastInterrupt()
{
PINSEL4 |= (1<<20); //Enable the EXTINT0 interrupt
EXTMODE |= (1<<0); //Enable edge sensitive interrupt
EXTPOLAR &= ~(1<<0); //Falling Edge sensitive
VICIntSelect |= (1<<14); //Enable a EXTINT0 Vic Channel as FIQ
VICIntEnable |= (1<<14); //Enable the interrupt channel in the VIC
}
/**
* Second constructor: <br>
* @param PortPin pin: this pin have to set as an "INPUT" and it must be one of below pins: <br>
* - Port2 -> Pin10
* - Port2 -> Pin11
* - Port2 -> Pin12
* - Port2 -> Pin13
* @param void(*function)(void): function which has to execute once the fast interrupt has occur. <br>
* <B><br>Example:<br><B><br>
* PortPin myPin(2,10,"INPUT");<br>
* FastInterrupt myInterrupt(myPin,do1); <br>
*/
FastInterrupt::FastInterrupt(PortPin pin,void(*function)(void))
{
fastInterruptPin=pin.getPinNumber();
if(fastInterruptPin==10)
{
PINSEL4 |= (1<<20); //Enable the EXTINT0 interrupt
VICIntSelect |= (1<<14); //Enable a EXTINT0 Vic Channel as FIQ
VICIntEnable |= (1<<14); //Enable the interrupt channel in the VIC
}
else if(fastInterruptPin==11)
{
PINSEL4 |= (1<<22); //Enable the EXTINT0 interrupt
VICIntSelect |= (1<<15); //Enable a EXTINT0 Vic Channel as FIQ
VICIntEnable |= (1<<15); //Enable the interrupt channel in the VIC
}
else if(fastInterruptPin==12)
{
PINSEL4 |= (1<<24); //Enable the EXTINT0 interrupt
VICIntSelect |= (1<<16); //Enable a EXTINT0 Vic Channel as FIQ
VICIntEnable |= (1<<16); //Enable the interrupt channel in the VIC
}
else if(fastInterruptPin==13)
{
PINSEL4 |= (1<<26); //Enable the EXTINT0 interrupt
VICIntSelect |= (1<<17); //Enable a EXTINT0 Vic Channel as FIQ
VICIntEnable |= (1<<17); //Enable the interrupt channel in the VIC
}
EXTMODE |= (1<<0); //Enable edge sensitive interrupt
EXTPOLAR &= ~(1<<0); //Falling Edge sensitive
fastInterruptFunction=function;
}
/**
* Set new function to fast intrrupt which has already define after impelementing this method the defined interrupt execute the new function once fast interrupt has occur.<br>
* @param void(*function)(void) : function which has to execute once the interrupt has occure.
* <B><br>Example:<br><B><br>
* PortPin myPin(2,10,"INPUT");<br>
* FastInterrupt myInterrupt(myPin,do1); <br>
* myInterrupt.setFunctionToInterrupt(do2);<br>
*/
void FastInterrupt::setFunctionToInterrupt(void(*assginedfunction)(void))
{
fastInterruptFunction=assginedfunction;
}
void fastInterruptHandler (void) __irq
{
fastInterruptFunction();
EXTINT = 0x00000001; //Clear the peripheral interrupt flag
}
| true |
8d9b171b7a72066f588c0cb2b42a6d98adec631b | C++ | rickwebiii/MallocStarter | /include/Malloc.hpp | UTF-8 | 6,734 | 3.1875 | 3 | [] | no_license | #pragma once
#include <signal.h>
#include <atomic>
// You can assume this as your page size. On some OSs (e.g. macOS),
// it may in fact be larger and you'll waste memory due to internal
// fragmentation as a result, but that's okay for this exercise.
constexpr size_t pageSize = 4096;
class MMapObject {
// The size of the allocated contiguous pages (i.e. the size passed to mmap)
size_t m_mmapSize;
// If the type is an arena, the size of each item in the arena. If a big alloc,
// should be zero.
size_t m_arenaSize;
// Debug counter for asserting we freed all the pages we were supposed to.
// Thread safe and you can ignore it. It's for tests and seeing how many
// outstanding pages there are.
static std::atomic<size_t> s_outstandingPages;
public:
MMapObject(const MMapObject& other) = delete;
MMapObject() = delete;
/**
* The number of contiguous bytes in this mmap allocation.
*/
size_t mmapSize() {
return m_mmapSize;
}
/**
* If the type of this mmap overlay is an arena, this is the size of its items.
* If a single allocation, this is zero.
*/
size_t arenaSize() {
return m_arenaSize;
}
/**
* This function should call mmap to allocate a contiguous set of pages with
* the passed size. If the caller is intending to use this region as an arena,
* they should set arenaSize to the size of its items.
*
* If this is a large allocation, the caller should set arenaSize to 0.
*/
static MMapObject* alloc(size_t size, size_t arenaSize) {
s_outstandingPages++;
// TODO: mmap allocation code
return nullptr;
}
/**
* This function should deallocate the passed pointer by calling munmap.
* The passed pointer may not be at the start of the memory region, but will
* be withing it, so you'll need to calculate the start of the MMapObject* ptr,
* passing that as start of the region to unmap and ptr->mmapSize() as its length.
*
* Recall that Arenas will never be larger than the OS page size and BigAllocs
* always return a pointer to just after the MMapObject header, so you can
* jump back to the nearest multiple of page size and that will be the MMapObject*.
*/
static void dealloc(void* obj) {
size_t old = s_outstandingPages--;
// If there previously 0 pages, then we goofed and tried to free more pages
// than we allocated. This is a serious bug, so sigtrap and your debugger
// can break on this line. If not debugging, you'll get a SIGTRAP message
// and your program will exit.
if (old == 0) {
raise(SIGTRAP);
}
// TODO: munmap deallocation code
}
/**
* Returns the number of pages outstanding that have not been collected.
* Don't touch this.
*/
static size_t outstandingPages() {
return s_outstandingPages.load();
}
};
class BigAlloc : public MMapObject {
// This inherits from MMapObject, so it also has the mmapSize and arenSize
// members as well.
char m_data[0];
public:
BigAlloc(const BigAlloc& other) = delete;
BigAlloc() = delete;
/**
* This method should allocate a single large contiguous block of memory using
* MMapObject::alloc(). You then need to treat that pointer as a BigAlloc*
* and return the address of the allocation *after* the header.
*
* The returned address must be 64-bit aligned.
*/
static void* alloc(size_t size) {
// TODO: allocate the BigAlloc.
return nullptr;
}
};
// This is the data overlay for your Arena allocator.
// It inherits from MMapObject, and thus has a size_
class Arena : public MMapObject {
// This inherits from MMapObject, so it also has the mmapSize and arenSize
// members as well.
// You'll need some means of tracking the number of freed items in this arena
// in a thread-safe manner. That should go here.
// mything thing = stuff;
// A pointer to the next free address in the arena.
char* m_next;
// This might look kind of weird as it's size is zero, but this serves as a surrogate
// location to start of the arena's allocation slots. That is &this->m_data[0] is a pointer
// to the first allocation slot, &this->m_data[arenaSize()] is a pointer to the second
// and so forth.
//
// Note, if you put any data members in this class, you must put them *before* this.
// Additionally, you need to ensure this address is 64-bit aligned, so you need appropriate
// padding or to ensure the sizes of your previous members ensures this happens before this.
//
// If sizeof(Arena) % 8 == 0, you should be good.
char m_data[0];
public:
/**
* Creates an arena with items of the given size. You should allocate with
* MMapObject::alloc() and coerce the result into an Arena*.
*/
static Arena* create(uint32_t itemSize) {
// TODO: create and initialize the arena.
return nullptr;
}
/**
* Allocates an item in the arena and returns its address. Returns null if you
* have already exceeded the bounds of the arena.
*/
void* alloc() {
// TODO: return a pointer to an item in this arena. We should return nullptr
// if there are no more slots in which to allocate data.
return nullptr;
}
/**
* Marks one of the items in the arena as freed. Returns true if this arena
* has no more allocation slots and everything is free'd.
*/
bool free() {
// TODO: actually free an item the arena.
return false;
}
/**
* Whether or not this arena can hold more items.
*/
bool full() {
// TODO: acutally compute full()
return false;
}
/**
* Returns a pointer to the next free item in the arena.
*/
char* next() {
return m_next;
}
};
class ArenaStore {
/**
* A set of arenas with the following sizes:
* 0: 8 bytes
* 1: 16 bytes
* 2: 32 bytes
* ...
* 8: 1024 bytes
*/
Arena* m_arenas[9]; // Default initializer for pointer is nullptr
public:
/**
* Allocates `bytes` bytes of data. If the data is too large to fit in an arena,
* it will be allocated using BigAlloc.
*/
void* alloc(size_t bytes) {
// TODO: implement alloc
return nullptr;
}
/**
* Determines the allocation type for the given pointer and calls
* the appropriate free method.
*/
void free(void* ptr) {
// TODO: implement free.
}
};
void* myMalloc(size_t n);
void myFree(void* ptr); | true |
86c8be546ce5af40b8b73196c39400b48d576a3b | C++ | izyakacman/hw12 | /check_tensor.cpp | UTF-8 | 1,079 | 2.515625 | 3 | [] | no_license | #include "check_tensor.h"
#include "tf_classifier.h"
#include <sstream>
#include <fstream>
using namespace std;
using namespace mnist;
bool ReadFeatures(std::istream& stream, Classifier::features_t& features)
{
std::string line;
std::getline(stream, line);
features.clear();
std::istringstream linestream{line};
double value;
while (true)
{
linestream.get(); // read ','
linestream >> value;
if(!linestream) break;
features.push_back(value);
}
return stream.good();
}
float GetTensorAccuracy(const char* model, const char* test_file)
{
auto clf = TfClassifier{model, 28, 28};
auto features = TfClassifier::features_t{};
std::ifstream test_data{test_file};
if(!test_data) return -1;
float right_answer = 0;
float all_answer = 0;
for(;; ++all_answer)
{
size_t y_true;
test_data >> y_true;
if(!ReadFeatures(test_data, features))
break;
auto y_pred = clf.predict(features);
if(y_true == y_pred) ++right_answer;
}
return right_answer / all_answer;
} | true |
11d16fe7e9d384789e6c53c3d21b0c9be8eda8ff | C++ | Sairei/PacMan | /ghost.cpp | UTF-8 | 534 | 2.515625 | 3 | [] | no_license | #include "ghost.h"
Ghost::Ghost(QString skin) : Entity(skin)
{
QPixmap pixmap("../PacMan/graphics_pacman/Affraid_ghost.png");
setVitesse(1);
}
void Ghost::setSpawnPoint(QPoint spawn_point){
m_spawn_point = spawn_point;
}
void Ghost::nextIAMove(Graph *graph_control, Entity *e) {
QPoint pos_ghost = current_tile_pos();
int next_move_ghost = graph_control->next_random_move(pos_ghost.x(),pos_ghost.y(),direction());
setDirection(next_move_ghost);
}
QPoint Ghost::spawnPoint(){
return m_spawn_point;
}
| true |
c531526f6a0c443758c045992523d725c3301263 | C++ | Signez/tpinsa-croisedrefs | /Code/Parseur.cpp | UTF-8 | 3,482 | 2.75 | 3 | [] | no_license | /*************************************************************************
Parseur - Analyse un fichier pour y trouver des identificateurs C++
-------------------
début : 19 nov. 2010
copyright : (C) 2010 par ssignoud et tpatel
*************************************************************************/
// Comme autorisé (après demande) par les professeurs en séance de TP,
// ces fichiers sources utilisent la norme d'écriture Doxygen/Javadoc en
// lieu et place du « Guide de Style INSA » original.
// Ses conseils et ses principes de formatages (retours à la ligne et
// informations algorithmiques complémentaires) sont cependant conservés.
//===[ Réalisation de la classe <Parseur> (fichier Parseur.cpp) ]===
//================================================================ INCLUDE
//-------------------------------------------------------- Include système
using namespace std;
#include <iostream>
#include <string>
#include <cctype>
//------------------------------------------------------ Include personnel
#include "Parseur.h"
//================================================================= PUBLIC
/**
* @algorithm Cet algorithme est disponible dans le dossier de
* Spécification.
*/
pair<string, int>* Parseur::NextIdent()
{
char c;
bool estDansIdentif = false;
string buffer = "";
int nbreCar = 0;
// Tant qu'il reste quelque chose à lire dans le fichier
while(*fichier) {
fichier->get(c);
if(c == '\n') {
// Mise à jour du numéro de ligne à chaque retour chariot
currentLine++;
}
if((isalnum(c) || c == '_') && estDansIdentif) {
nbreCar++;
if(nbreCar > 256) {
// Cas où l'identifiant est trop grand : il est ignoré
buffer = "";
estDansIdentif = false;
nbreCar = 0;
} else {
// Tout va bien : on ajoute le caractère au buffer
buffer += c;
}
} else if ( (!isalnum(c) && c != '_') && estDansIdentif) {
// On vient de terminer un identifiant : on le retourne
estDansIdentif = false;
return new pair<string, int>(buffer, currentLine);
} else if((isalpha(c) || c == '_') && !estDansIdentif) {
// On découvre un nouveau caractère de début : on démarre
// l'enregistrement de le buffer
buffer = c;
estDansIdentif = true;
nbreCar = 1;
}
}
// Plus rien à lire : le fichier est terminé. On retourne une
// chaîne vide pour indiquer cet état de fait
return new pair<string, int>("", -1);
} //----- Fin de NextIdent
//------------------------------------------------- Surcharge d'opérateurs
// Aucune : ifstream ne supporte pas la copie.
//-------------------------------------------- Constructeurs - destructeur
Parseur::Parseur(string fileName) :
currentLine(1)
{
#ifdef MAP
cout << "Appel au constructeur de <Parseur>" << endl;
#endif
fichier = new ifstream(fileName.c_str());
} //----- Fin de Parseur
Parseur::~Parseur()
{
#ifdef MAP
cout << "Appel au destructeur de <Parseur>" << endl;
#endif
fichier->close();
delete fichier;
} //----- Fin de ~Parseur
//================================================================== PRIVE
//----------------------------------------------------- Méthodes protégées
| true |
0b85f64e20e3ba9cac3fe0b8717dca5991d24f87 | C++ | ymarkovitch/libpcomn | /pcomn_cmdline/usage.cpp | UTF-8 | 10,840 | 3.015625 | 3 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //------------------------------------------------------------------------
// ^FILE: usage.c - functions to print the usage of a CmdLine
//
// ^DESCRIPTION:
// This file contains the functions that are used to print the
// command-line usage of a command that is represented by a CmdLine
// object.
//
// ^HISTORY:
// 01/09/92 Brad Appleton <bradapp@enteract.com> Created
//
// 03/01/93 Brad Appleton <bradapp@enteract.com>
// - Added cmd_description field to CmdLine
//-^^---------------------------------------------------------------------
#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include "cmdline.h"
#include "states.h"
#include "fifolist.h"
CMDL_MS_IGNORE_WARNING(4244 4267 4800)
static const int PRINT_LMARGIN = 2 ;
static const int PRINT_MAXCOLS = 79 ;
static int term_columns()
{
return PRINT_MAXCOLS ;
}
//-------
// ^FUNCTION: CmdLine::get_usage_level
//
// ^SYNOPSIS:
// CmdLine::CmdUsageLevel CmdLine::get_usage_level()
//
// ^PARAMETERS:
// NONE.
//
// ^DESCRIPTION:
// Gets the usage_level that tells us how "verbose" we should be
// when printing usage-messages. This usage_level is recorded in
// the environment variable $USAGE_LEVEL. This variable may have the
// following values:
//
// 0 : Dont print usage at all.
// 1 : Print a terse usage message (command-line syntax only).
// 2 : Print a verbose usage message (include argument descriptions).
//
// If $USAGE_LEVEL is not defined or is empty, then the default
// usage_level is 2.
//
// ^REQUIREMENTS:
//
// ^SIDE-EFFECTS:
// None.
//
// ^RETURN-VALUE:
// The usage level to use.
//
// ^ALGORITHM:
// Read the usage_level from the environment and return it.
//-^^----
CmdLine::CmdUsageLevel
CmdLine::get_usage_level() const
{
if (cmd_usage_level != DEFAULT_USAGE)
return cmd_usage_level ;
long level;
char * end_scan, * level_str = ::getenv("USAGE_LEVEL");
if (level_str == NULL) return VERBOSE_USAGE ;
if (*level_str == '\0') return NO_USAGE ;
level = ::strtol(level_str, &end_scan, 0);
if (end_scan == level_str) return VERBOSE_USAGE ;
switch(level) {
case 0 : return NO_USAGE ;
case 1 : return TERSE_USAGE ;
default: return VERBOSE_USAGE ;
}
}
//-------
// ^FUNCTION: CmdLine::print_synopsis
//
// ^SYNOPSIS:
// unsigned CmdLine::print_synopsis(syntax, os, cols)
//
// ^PARAMETERS:
// CmdLine::CmdLineSyntax syntax;
// -- the syntax to use (long-option, short-option, or both)
// when printing the synopsis.
//
// std::ostream & os;
// -- where to print.
//
// int cols;
// -- the maximum width of a line.
//
// ^DESCRIPTION:
// Print a command-line synopsis (the command-line syntax).
// The synopsis should be printed to "os" using the desired syntax,
// in lines that are no more than "cols" characters wide.
//
// ^REQUIREMENTS:
//
// ^SIDE-EFFECTS:
// Prints on "os".
//
// ^RETURN-VALUE:
// The length of the longest argument-buf that was printed.
//
// ^ALGORITHM:
// It's kind of complicated so follow along!
//-^^----
unsigned
CmdLine::print_synopsis(CmdLine::CmdLineSyntax syntax,
std::ostream & os,
int cols) const
{
static char usg_prefix[] = "Usage: ";
unsigned ll, positionals, longest = 0;
// first print the command name
os << usg_prefix << cmd_name ;
ll = (cmd_name ? ::strlen(cmd_name) : 0) + (sizeof(usg_prefix) - 1);
// set margin so that we always start printing arguments in a column
// that is *past* the command name.
//
unsigned margin = ll + 1;
// print option-syntax followed by positional parameters
int first;
char buf[256] ;
for (positionals = 0 ; positionals < 2 ; positionals++) {
first = 1;
CmdArgListListIter list_iter(cmd_args);
for (CmdArgList * alist = list_iter() ; alist ; alist = list_iter()) {
CmdArgListIter iter(alist);
for (CmdArg * cmdarg = iter() ; cmdarg ; cmdarg = iter()) {
unsigned len, pl;
// don't display hidden arguments
if (cmdarg->syntax() & CmdArg::isHIDDEN) continue;
if (!positionals && (cmdarg->syntax() & CmdArg::isPOS)) continue;
if (positionals && !(cmdarg->syntax() & CmdArg::isPOS)) continue;
// figure out how wide this parameter is (for printing)
pl = len = fmt_arg(cmdarg, buf, sizeof(buf), syntax, VERBOSE_USAGE);
if (! len) continue;
if (cmdarg->syntax() & CmdArg::isLIST) pl -= 4 ; // " ..."
if (! (cmdarg->syntax() & CmdArg::isREQ)) pl -= 2 ; // "[]"
if (pl > longest) longest = pl;
// Will this fit?
if ((long)(ll + len + 1) > (cols - first)) {
os << char('\n') ;
os.width(margin);
os << "" ; // No - start a new line;
ll = margin;
} else {
os << char(' ') ; // Yes - just throw in a space
++ll;
}
ll += len;
os << buf;
first = 0;
} //for each cmdarg
} //for each arg-list
} //for each parm-type
os << std::endl ;
return longest ;
}
//-------
// ^FUNCTION: CmdLine::print_descriptions
//
// ^SYNOPSIS:
// unsigned CmdLine::print_descriptions(syntax, os, cols, longest)
//
// ^PARAMETERS:
// CmdLine::CmdLineSyntax syntax;
// -- the syntax to use (long-option, short-option, or both)
// when printing the synopsis.
//
// std::ostream & os;
// -- where to print.
//
// int cols;
// -- the maximum width of a line.
//
// unsigned longest;
// -- value returned by print_synopsis.
//
// ^DESCRIPTION:
// Print a command argument descriptions (using the command-line syntax).
// The descriptions should be printed to "os" using the desired syntax,
// in lines that are no more than "cols" characters wide.
//
// ^REQUIREMENTS:
// "longest" should correspond to a value returned by print_synopsis
// that used the same "cmd" and syntax.
//
// ^SIDE-EFFECTS:
// Prints on "os".
//
// ^RETURN-VALUE:
// None.
//
// ^ALGORITHM:
// Print the description for each argument.
//-^^----
void
CmdLine::print_descriptions(CmdLine::CmdLineSyntax syntax,
std::ostream & os,
int cols,
unsigned longest) const
{
static const unsigned argarray_size = 128 ;
typedef const CmdArg *argarray[argarray_size] ;
struct local {
static int copy_args(CmdArgListList *arglist, bool positional, argarray &argv)
{
unsigned argc = 0 ;
CmdArgListListIter list_iter(arglist) ;
for (CmdArgList * alist = list_iter() ; argc < argarray_size && alist ; alist = list_iter()) {
CmdArgListIter iter(alist) ;
for (CmdArg * cmdarg = iter() ; cmdarg ; cmdarg = iter()) {
// don't display hidden arguments
if ((cmdarg->syntax() & CmdArg::isHIDDEN) ||
!positional != !(cmdarg->syntax() & CmdArg::isPOS)) continue ;
const char * const description = cmdarg->description() ;
if (description && *description)
argv[argc++] = cmdarg ;
} //for each cmdarg
} //for each arg-list
return argc ;
}
static bool less_args(const CmdArg *left, const CmdArg *right)
{
return left->char_name() == right->char_name()
?
left->keyword_name() != right->keyword_name() &&
(!left->keyword_name() || (right->keyword_name() && strcmp(left->keyword_name(), right->keyword_name()) < 0))
:
(unsigned char)(left->char_name() - 1) < (unsigned char)(right->char_name() - 1) ;
}
} ;
static const char arghead[] = "Options/Arguments:\n" ;
int has_args = 0 ;
for (int is_positional = 0 ; is_positional <= 1 ; ++is_positional) {
argarray argv ;
const int argcnt = local::copy_args(cmd_args, is_positional, argv) ;
std::sort(argv + 0, argv + argcnt, local::less_args) ;
char title_buf[256] ;
char defval_str[512] = "[ default: " ;
static const char defval_end[] = " ]" ;
char * const defval_buf = strchr(defval_str, 0) ;
const size_t defval_sz = sizeof defval_str - (defval_buf - defval_str) - (sizeof defval_end - 1) ;
const unsigned indent = longest + 2 ;
for (int n = 0 ; n < argcnt ; ++n)
if (fmt_arg(argv[n], title_buf, sizeof title_buf, syntax, TERSE_USAGE)) {
if (!has_args++)
os << arghead ;
strindent(os, cols, PRINT_LMARGIN, title_buf, indent, argv[n]->description()) ;
// Output default value, if nonzero
if (argv[n]->valstr(defval_buf, defval_sz, CmdArg::VALSTR_DEFNOZERO)) {
strcat(defval_buf, defval_end) ;
strindent(os, cols, PRINT_LMARGIN, NULL, indent, defval_str) ;
}
}
}
}
//-------
// ^FUNCTION: CmdLine::usage - print command-usage
//
// ^SYNOPSIS:
// void CmdLine::usage(os, usage_level);
//
// ^PARAMETERS:
// std::ostream & os;
// -- where to print.
//
// CmdLine::CmdUsageLevel usage_level;
// -- verboseness to use.
//
// ^DESCRIPTION:
// Print the usage for the given CmdLine object on "os".
//
// ^REQUIREMENTS:
//
// ^SIDE-EFFECTS:
// Prints on "os".
//
// ^RETURN-VALUE:
// None.
//
// ^ALGORITHM:
// - get the usage level.
// - determine which syntax to use
// - get the max-columns for "os".
// - print synopsis if required.
// - print descriptions if required.
//-^^----
std::ostream &CmdLine::usage(std::ostream & os, CmdUsageLevel usage_level) const
{
// get user-specified usage-level
// (if status is zero this must be an explicit request so force verbose)
//
if (usage_level == DEFAULT_USAGE) usage_level = get_usage_level();
if (usage_level == NO_USAGE) return os;
// determine syntax to use
const CmdLineSyntax cmd_syntax = usage_syntax() ;
// get screen size (dont know how to do this yet)
const int max_cols = term_columns() - 1 ;
// print command-line synopsis
unsigned longest = print_synopsis(cmd_syntax, os, max_cols) ;
if (usage_level == TERSE_USAGE) return os;
// now print the short command description, if there is one
if (*description())
strindent(os, max_cols, 0, "", 0, description());
// now print argument descriptions
print_descriptions(cmd_syntax, os << '\n', max_cols, longest) ;
// now print the full description, if there is one
if (*full_description())
strindent(os << '\n', max_cols, 0, "", 0, full_description());
return os;
}
std::ostream &CmdLine::usage(CmdUsageLevel usage_level) const
{
return usage(*cmd_err, usage_level);
}
| true |
2eab2722db31d7bcf5d100a64f36332ba6d5f9ea | C++ | fpagliughi/cpp_redis | /includes/cpp_redis/builders/integer_builder.hpp | UTF-8 | 773 | 2.515625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <cpp_redis/builders/builder_iface.hpp>
#include <cpp_redis/reply.hpp>
#include <stdint.h>
namespace cpp_redis {
namespace builders {
class integer_builder : public builder_iface {
public:
//! ctor & dtor
integer_builder(void);
~integer_builder(void) = default;
//! copy ctor & assignment operator
integer_builder(const integer_builder&) = delete;
integer_builder& operator=(const integer_builder&) = delete;
public:
//! builder_iface impl
builder_iface& operator<<(std::string&);
bool reply_ready(void) const;
reply get_reply(void) const;
//! getter
int64_t get_integer(void) const;
private:
int64_t m_nbr;
char m_negative_multiplicator;
bool m_reply_ready;
reply m_reply;
};
} //! builders
} //! cpp_redis
| true |
d454d4c8b02defd2def715579412c2300ad3d4fa | C++ | hehuaiyucn/Algorithm_2020 | /HundredFowlsMoneys_problem.cpp | UTF-8 | 561 | 3.171875 | 3 | [] | no_license | #include<stdio.h>
// 我国古代数学家张丘建在《算经》一书中提出的数学问题:
// 鸡翁一值钱五,鸡母一值钱三,鸡雏三值钱一。
// 百钱买百鸡,问鸡翁、鸡母、鸡雏各几何?
void hundredFowlsMoneys() {
int x, y, z;
for (x = 0; x <= 20; x++) {
for (y = 0; y <= 33; y++) {
z = 100 - x - y;
if (z % 3 == 0 && 5 * x + 3 * y + z / 3 == 100) {
printf("������%d,��ĸ��%d,������%d\n", x, y, z);
}
}
}
}
//int main() {
// hundredFowlsMoneys();
// return 0;
//} | true |
d2ba48e187936d65e8b4bdccef05f095c942eff0 | C++ | Lawendt/tilemap-ai | /Broke/Particle.h | UTF-8 | 592 | 2.796875 | 3 | [] | no_license | #pragma once
#include "Pulse.h"
namespace Law
{
class Particle : public Law::GameObject
{
public:
Particle(int Rotation, double LastingTime, Pulse *pulse, float width, float height, sf::Vector2f aceleration, sf::Vector2f force, sf::VertexArray m_vertices,
sf::Texture *m_texture) :GameObject(width, height, aceleration, force, m_vertices, m_texture){
this->lastingTime = LastingTime;
this->pulse = pulse;
this->Rotation = Rotation;
};
~Particle();
bool update(float delta, double time);
private:
int Rotation;
double lastingTime;
Law::Pulse *pulse;
};
}
| true |
5f8971359e319b6c193155ad55e06d27d6c13fcb | C++ | aditrio/joki-tugas-cpp | /while/while-8.cpp | UTF-8 | 558 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
// program sewa mobil
long harga = 256000;
long total_harga = 0;
int hari;
int i = 1;
cout << "harga sewa : Rp.256.000" << endl;
cout << "--------------------------" << endl;
cout << "masukan jumlah hari : ";
cin >> hari;
while(true) {
total_harga+=harga;
if (i == hari)
{
cout << "--------------------------" << endl;
cout << "total harga sewa : Rp." << total_harga << endl;
break;
}
i++;
}
return 0;
}
| true |
832480b524b9d7275d41c7c3f1843d4f6c3c1c29 | C++ | andreparker/spiralengine | /GameEngine/Gfx/VertexFormatImpl.hpp | UTF-8 | 1,367 | 2.8125 | 3 | [] | no_license | /*!
*/
#ifndef VERTEX_FORMAT_IMPL_HPP
#define VERTEX_FORMAT_IMPL_HPP
#include <boost/cstdint.hpp>
#include <boost/tuple/tuple.hpp>
#include "../Core/Sp_DataTypes.hpp"
namespace Spiral
{
namespace Impl
{
struct VertexFormat
{
VertexFormat():type( VF_INVALID ){}
enum
{
VF_INVALID = -1,
VF_V3, ///< 3 component vertices xyz
VF_V3T2 ///< xyz t,s texture coords
};
enum
{
VFS_V3 = 3 * sizeof(SpReal),
VFS_V3T2 = 5 * sizeof(SpReal)
};
typedef boost::tuples::tuple< SpReal, SpReal, SpReal, SpReal, SpReal > V3T2_Storage;
boost::int32_t GetType()const
{
return type;
}
static VertexFormat Create_V3()
{
return VertexFormat( VF_V3 );
}
static VertexFormat Create_V3T2()
{
return VertexFormat( VF_V3T2 );
}
static void SetV3T2Data( SpReal* aryData, const V3T2_Storage& data )
{
// vertex x,y,z
aryData[ 0 ] = boost::tuples::get< 0 >( data );
aryData[ 1 ] = boost::tuples::get< 1 >( data );
aryData[ 2 ] = boost::tuples::get< 2 >( data );
// texure s,t
aryData[ 3 ] = boost::tuples::get< 3 >( data );
aryData[ 4 ] = boost::tuples::get< 4 >( data );
}
private:
boost::int32_t type;
VertexFormat( boost::int32_t type_ ):
type( type_ ){}
};
}
typedef Impl::VertexFormat VertexFormat;
}
#endif | true |
81ad8b4e98acd0279f3bce35673a88649c7bca7a | C++ | okoks9011/problem_solving | /algospot/ch30/promises.cc | UTF-8 | 1,801 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int kInf = 987654321;
vector<vector<int>> floyd(const vector<vector<int>>& adj_ori) {
vector<vector<int>> adj(adj_ori);
int v = adj.size();
for (int i = 0; i < v; ++i)
adj[i][i] = 0;
for (int k = 0; k < v; ++k) {
for (int i = 0; i < v; ++i) {
for (int j = 0; j < v; ++j)
adj[i][j] = min(adj[i][j], adj[i][k]+adj[k][j]);
}
}
return adj;
}
void InsertEdge(vector<vector<int>>* adj_ptr,
int a, int b, int c) {
auto& adj = *adj_ptr;
int v = adj.size();
adj[a][b] = c;
adj[b][a] = c;
for (int i = 0; i < v; ++i) {
adj[i][a] = min(adj[i][a], adj[i][b]+adj[b][a]);
adj[i][b] = min(adj[i][b], adj[i][a]+adj[a][b]);
adj[a][i] = min(adj[a][i], adj[a][b]+adj[b][i]);
adj[b][i] = min(adj[b][i], adj[b][a]+adj[a][i]);
}
for (int i = 0; i < v; ++i) {
for (int j = 0; j < v; ++j) {
adj[i][j] = min(adj[i][j], adj[i][a]+adj[a][j]);
adj[i][j] = min(adj[i][j], adj[i][b]+adj[b][j]);
}
}
}
void Solve() {
int v, m, n;
cin >> v >> m >> n;
vector<vector<int>> adj(v, vector<int>(v, kInf));
for (int i = 0; i < m; ++i) {
int a, b, c;
cin >> a >> b >> c;
adj[a][b] = min(adj[a][b], c);
adj[b][a] = min(adj[a][b], c);
}
auto dist = floyd(adj);
int result = 0;
for (int i = 0; i < n; ++i) {
int a, b, c;
cin >> a >> b >> c;
if (dist[a][b] > c)
InsertEdge(&dist, a, b, c);
else
++result;
}
cout << result << endl;
}
int main() {
int c;
cin >> c;
for (int i = 0; i < c; ++i)
Solve();
}
| true |
271623b2ba659396a61e27936fa9dc5a70d52fb4 | C++ | budelphine/_cpp_modules | /day01/ex06/Weapon.hpp | UTF-8 | 276 | 2.828125 | 3 | [] | no_license | #ifndef WEAPON_H
# define WEAPON_H
# include <iostream>
# include <string>
# include <iomanip>
class Weapon {
private:
std::string type_;
public:
Weapon();
Weapon(std::string type);
std::string &getType();
void setType(std::string type);
};
#endif
| true |
f15c43015aa74bc58f5f0a2ab32343d7fd6ff723 | C++ | serk12/SRGGE | /src/Scene.cpp | UTF-8 | 5,096 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #include "Debug.h"
#include <cmath>
#define GLM_FORCE_RADIANS
#include "PLYReader.h"
#include "Scene.h"
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "TileMapLoader.h"
#include <GL/glut.h>
Scene::Scene() {}
Scene::~Scene() {
for (auto &m : meshes) {
delete m;
}
meshes.clear();
}
void Scene::init(const std::string &fn, CullingMethod cm) {
cullingPolicy = cm;
bPolygonFill = true;
filename = fn;
basicProgram.initShaders("shaders/basic.vert", "shaders/basic.frag");
player.init();
std::string formatFile =
std::string(&filename[filename.size() - 3], &filename[filename.size()]);
if (formatFile == "ply") {
loadMesh();
} else if (formatFile == "txt") {
loadTileMap();
}
}
void Scene::loadMesh() {
std::string formatFile =
std::string(&filename[filename.size() - 3], &filename[filename.size()]);
if (formatFile == "ply") {
loadMesh(filename, next_pos);
next_pos.x = (int(next_pos.x) + 1) % 2;
next_pos.z = (int(next_pos.z) + int(next_pos.x == 0));
} else {
// this should not happen
std::cerr << "filename is a txt" << std::endl;
}
}
void Scene::loadMesh(const std::string &fn, glm::vec3 pos) {
TriangleMesh *mesh = new TriangleMesh(pos);
meshes.push_front(mesh);
PLYReader reader;
bool bSuccess = reader.readMesh(fn, *mesh);
if (bSuccess)
mesh->sendToOpenGL(basicProgram);
}
void Scene::loadTileMap() {
TileMapModels tilemap = TileMapLoader::instance().load(filename);
int i = -tilemap.size() / 2;
for (auto t : tilemap) {
int j = -tilemap[0].size() / 2;
for (std::string m : t) {
if (m != TileMapLoader::EMPTY) {
if (m != TileMapLoader::WALL) {
loadMesh(TileMapLoader::GROUND, glm::vec3(i, -1.5f, j));
}
if (m != TileMapLoader::GROUND) {
loadMesh(m, glm::vec3(i, -1.0f, j));
}
}
++j;
}
++i;
}
}
void Scene::unloadMesh() {
if (meshes.size() > 0) {
TriangleMesh *mesh = meshes.back();
meshes.pop_back();
next_pos.x = (int(next_pos.x) - 1) % 2;
next_pos.z = (int(next_pos.z) - 1);
}
}
void Scene::update(int deltaTime) { player.update(deltaTime); }
bool Scene::viewCulling(const TriangleMesh &mesh) {
auto frustum = player.getFrustum();
for (auto &p : frustum) {
if (glm::dot(glm::vec3(p), mesh.getPoss()) + p.w + mesh.getRadius() <= 0)
return false;
}
return true;
}
bool Scene::occlusionCulling(const TriangleMesh &mesh) { return true; }
int Scene::getQttyTriangles() const { return qttyTriangles; }
bool Scene::cullingTest(const TriangleMesh &mesh) {
switch (cullingPolicy) {
default:
case NONE:
return true;
case VIEW:
return viewCulling(mesh);
case OCCLUSION:
return occlusionCulling(mesh);
case ALL:
return viewCulling(mesh) && occlusionCulling(mesh);
}
}
void Scene::render() {
if (meshes.size() > 0) {
basicProgram.use();
basicProgram.setUniformMatrix4f("projection", player.getProjectionMatrix());
basicProgram.setUniformMatrix4f("view", player.getViewMatrix());
basicProgram.setUniform1i("bLighting", bPolygonFill ? 1 : 0);
basicProgram.setUniform4f("color", 0.9f, 0.9f, 0.95f, 1.0f);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
qttyTriangles = 0;
for (auto &mesh : meshes) {
if (cullingTest(*mesh)) {
qttyTriangles += mesh->getTriangleSize();
basicProgram.setUniformMatrix4f("model", mesh->getModelMatrix());
if (!bPolygonFill) {
basicProgram.setUniform4f("color", 1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(0.5f, 1.0f);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
mesh->render();
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_POLYGON_OFFSET_FILL);
basicProgram.setUniform4f("color", 0.0f, 0.0f, 0.0f, 1.0f);
}
mesh->render();
}
}
}
}
void Scene::keyEvent(int key, int specialkey, bool pressed) {
if (pressed) {
std::string formatFile =
std::string(&filename[filename.size() - 3], &filename[filename.size()]);
if (formatFile == "ply") {
if (key == '+')
loadMesh();
else if (key == '-')
unloadMesh();
else if ((key >= '0') && (key <= '9')) {
int num = int(key) - int('0');
while (meshes.size() != num) {
if (meshes.size() > num) {
unloadMesh();
} else {
loadMesh();
}
}
}
}
if (specialkey == GLUT_KEY_F1) {
bPolygonFill = !bPolygonFill;
}
}
player.keyEvent(key, specialkey, pressed);
}
void Scene::mouseMove(int x, int y, const glm::ivec2 &lastMousePos,
bool *mouseButtons) {
player.mouseMove(x, y, lastMousePos, mouseButtons);
}
void Scene::resize(int width, int height) { player.resize(width, height); }
| true |
467bb3ee481f96a6b664158c6b0960ac43078e5f | C++ | SpookyDreamer/Intersect2 | /UIsrc/MyException.h | UTF-8 | 912 | 3.21875 | 3 | [] | no_license | #pragma once
#include<exception>
#include<iostream>
using namespace std;
//customized exception class 'myException'
class WrongFormatException :public exception
{
public:
WrongFormatException() :exception("ERROR! The file contents are in the wrong format. Please check the file contents.\n")
{
}
};
class UnableToConstructException :public exception
{
public:
UnableToConstructException() :exception("ERROR! Since the two points given coincide, we cannot construct a line.\n")
{
}
};
class CoordinateOutOfRangeException :public exception
{
public:
CoordinateOutOfRangeException() :exception("ERROR! Both horizontal and vertical values should be within (-100000, 100000).\n")
{
}
};
class InfiniteIntersectionPointsException :public exception
{
public:
InfiniteIntersectionPointsException() :exception("ERROR!There are infinite points of intersection between geometric objects .\n")
{
}
}; | true |
e313e206d1328dfeaf1af6c824640f86b1d6029e | C++ | ltx6/helloworld | /计科191-14119210-李曈轩-第01次实验/01-1.cpp | GB18030 | 1,121 | 3.109375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
cout << "100ڵ£" << endl;
int i,j;
int cnt1=0;
int cnt2 = 0;
for (i=2;i<100;i++) {
for (j=1;j<=i;j++) {
if (i%j==0) {
cnt1++;
}
}
if (cnt1== 2) {
cout << i<<" \t";
cnt2++;
}
cnt1 = 0;
if (cnt2 == 10)
cout << endl;
}
int iint;
cout << "һ:"<<endl;
cin >> iint;
for (i = 1;i <= iint;i++) {
if (iint%i == 0) {
cnt1++;
}
}
if (cnt1 == 2) {
cout << "" << endl;
}
else {
cout << "" << endl;
}
char whethercontinue;
cout << "ǷҪжy-ǣn-"<<endl;
cin >> whethercontinue;
cnt1 = 0;
while (whethercontinue != 'n') {
cout << "һ:" << endl;
cin >> iint;
for (i = 1;i <= iint;i++) {
if (iint%i == 0) {
cnt1++;
}
}
if (cnt1 == 2) {
cout << "" << endl;
}
else {
cout << "" << endl;
}
cout << "ǷҪжy-ǣn-" << endl;
cin >> whethercontinue;
cnt1 = 0;
}
system("pause");
return 0;
} | true |
09e6804e6fa54a9f42194c3f59345e12b0179b4a | C++ | samuelbohl/CP | /project euler/problem4.cpp | UTF-8 | 409 | 3.203125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool is_palindrome(int x){
string str = to_string(x);
int n = str.length();
for(int i = 0; i < n/2; ++i){
if(str[i] != str[n-i-1]) return false;
}
return true;
}
int main(){
int maxp = 0;
for(int i = 999; i >= 100; --i){
for(int j = 999; j >= 100; --j){
if(is_palindrome(i*j)){
maxp = max(maxp, i*j);
}
}
}
cout << maxp;
return 0;
} | true |
cbc11d0a7aaf06599023dc796759d896523895c8 | C++ | Tuchakage/The-Coin-Hunter | /GTEClib/include/Line.h | UTF-8 | 2,674 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Model.h"
class CLine : public CModel
{
public:
float Length; // length from starting point along the x-axis
float Width;
CLine() : CModel() { Color.Set( CColor::Green()); Length=0; Width=2.0f; }
CLine(float x, float y, float z, float length, const CColor& color=CColor::Green()) : CModel()
{
Position.x=x; Position.y=y; Position.z=z;
Length=length;
minx=0; maxx=length;
miny=maxy=0;
minz=maxz=0;
Width=2.0f;
Color.Set( color);
}
CLine(CVector pos, float length, const CColor& color=CColor::Green()) : CModel()
{
Position=pos;
Length=length;
minx=0; maxx=length;
miny=maxy=0;
minz=maxz=0;
Width=2.0f;
Color.Set( color);
}
CLine(CVector pos1, CVector pos2, const CColor& color=CColor::Green()) : CModel()
{
Position=pos1;
CVector v=pos2-pos1;
Length=v.Length();
SetRotationV(v);
minx=0; maxx=Length;
miny=maxy=0;
minz=maxz=0;
Width=2.0f;
Color.Set( color);
}
void SetPositionV(CVector pos1, CVector pos2)
{
Position=pos1;
CVector v=pos2-pos1;
Length=v.Length();
SetRotationV(v);
minx=0; maxx=Length;
miny=maxy=0;
minz=maxz=0;
}
void SetWidth( float w) { Width=w; }
void SetLength(float length) { Length=length; }
virtual void Draw(CGraphics* g)
{
glColor4f( Color.R, Color.G, Color.B, Color.A);
glLineWidth( Width);
glPushMatrix();
glTranslatef( Position.x, Position.y, Position.z); // transformation to world coordinates
glRotatef( Rotation.x, 1, 0, 0 ); // rotation around x-axis
glRotatef( Rotation.y, 0, 1, 0 ); // rotation around y-axis
glRotatef( Rotation.z, 0, 0, 1 );
glTranslatef(localPosition.x, localPosition.y, localPosition.z);
glScalef( Scale, Scale, Scale);
glBegin(GL_LINES);
glVertex3f( 0, 0, 0);
glVertex3f( Length, 0,0);
glEnd();
glPopMatrix();
}
virtual CModel* Clone()
{
// create new model
CLine* m = new CLine();
m->isCloned=true;
m->Position=Position;
m->Color.Set( Color);
m->visible=visible;
m->localPosition=localPosition;
m->Width=Width;
m->Length=Length;
if (childNode != NULL) m->childNode=childNode->Clone();
return m;
}
virtual bool HitTest(CModel *pModel)
{
CVector v=GetRotationV();
v.Normalized();
// --- inside start or end point? -----
if (pModel->HitTest( Position)) return true;
if (pModel->HitTest( Position+v*Length)) return true;
// check points along the line for every other units
for (float n=0.0f; n < Length; n+=2.0f)
{
if (pModel->HitTest( Position+(v*n))) return true;
}
return false;
}
};
| true |
fb48ca0aff04580caaccfc0cdc3c81cf53121207 | C++ | bashu22tiwari/Apna-College | /OOPS Concepts/static.cpp | UTF-8 | 483 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
class Student{
public:
int rollNumber;
int age;
static int totalStudents;
Student()
{
totalStudents += 1;
}
};
int Student :: totalStudents = 0 ;
int main()
{
Student s1;
Student s2;
Student s3;
Student s4;
Student s5;
Student s6;
Student s7;
Student s8;
cout << Student :: totalStudents << endl;
} | true |
b467f5ad3ac772d451063d4364a6084b1b8f154e | C++ | gauravjaat/Phonebook | /project.cpp | UTF-8 | 7,657 | 2.984375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class conDetails{
public:
long long int mob;
long long int regCode;
int speed=0;
};
class avlNode
{
public:
int asc;
multimap<string,conDetails> s;
avlNode *l;
avlNode *r;
int h;
};
avlNode *newnode(int key,string sname,conDetails D)
{
avlNode *n= new avlNode;
n->asc=key;
n->s.insert(make_pair(sname,D));
n->r=NULL;
n->l=NULL;
n->h=1;
return n;
}
int max(int a,int b)
{
return (a > b)? a : b;
}
int height(avlNode *n)
{
if(n==NULL)
return 0;
return n->h;
}
avlNode* rotateR(avlNode *n)
{
avlNode *x=n->l;
avlNode *t2=x->r;
x->r=n;
n->l=t2;
n->h= max(height(n->l),height(n->r)) + 1;
x->h= max(height(x->l),height(x->r)) + 1;
return x;
}
avlNode *rotateL(avlNode *n)
{
avlNode *x=n->r;
avlNode *t2=x->l;
x->l=n;
n->r=t2;
n->h = 1 + max(height(n->l),height(n->r));
x->h = 1 + max(height(x->l),height(x->r));
return x;
}
int getbalance(avlNode *n)
{
if(n==NULL)
return 0;
return height(n->l) - height(n->r);
}
int searchInsert(avlNode *n,int val,string sname,conDetails D)
{
while(n!=NULL)
{
if(n->asc==val)
{
n->s.insert(make_pair(sname,D));
return 0;
}
else
{
if(val >= n->asc)
return searchInsert(n->r,val,sname,D);
else
return searchInsert(n->l,val,sname,D);
}
}
return 1;
}
int searchCon(avlNode *n,string sname)
{
int val=(int)sname[0];
while(n!=NULL)
{
if(n->asc==val)
{
for(auto i=n->s.begin();i!=n->s.end();i++)
{
if(i->first==sname)
{
cout<<i->first<<"\t\t|\t\t"<<i->second.mob<<endl;
}
}
return 0;
}
else
{
if(val >= n->asc)
return searchCon(n->r,sname);
else
return searchCon(n->l,sname);
}
}
return 1;
}
void speed(avlNode *n,long long int f,int x)
{
if(n!=NULL)
{
speed(n->l,f,x);
for(auto i=n->s.begin();i!=n->s.end();i++)
{
if((i->second.regCode)==f)
{
i->second.speed=x;
cout<<" Speed Dial added successfully \n";
return;
}
}
speed(n->r,f,x);
}
}
void callspeed(avlNode *n,int x)
{
if(n!=NULL)
{
callspeed(n->l,x);
for(auto i=n->s.begin();i!=n->s.end();i++)
{
if((i->second.speed)==x)
{
cout<<i->first<<"\t|\t"<<i->second.mob<<"\t|\t"<<i->second.regCode<<endl;
return;
}
}
callspeed(n->r,x);
}
}
avlNode *insertNode(avlNode *tempnode,int key,string sname,conDetails D)
{
if(tempnode==NULL)
return newnode(key,sname,D);
if(key > tempnode->asc)
{
tempnode->r=insertNode(tempnode->r,key,sname,D);
}
else if(key < tempnode->asc)
tempnode->l=insertNode(tempnode->l,key,sname,D);
else
return tempnode;
tempnode->h=max(height(tempnode->l),height(tempnode->r)) + 1;
int b=getbalance(tempnode);
if(b>1 && key < tempnode->l->asc)
return rotateR(tempnode);
if(b<-1 && key > tempnode->r->asc)
return rotateL(tempnode);
if(b>1 && key > tempnode->l->asc)
{
tempnode->l=rotateL(tempnode->l);
return rotateR(tempnode);
}
if(b<-1 && key < tempnode->r->asc)
{
tempnode->r=rotateR(tempnode->r);
return rotateL(tempnode);
}
return tempnode;
}
void printin(avlNode *root)
{
if(root!=NULL)
{
printin(root->l);
cout<<(char)root->asc<<endl;
for(auto i=root->s.begin();i!=root->s.end();i++)
cout<<i->first<<"\t|\t"<<i->second.mob<<"\t|\t"<<i->second.regCode<<endl;
printin(root->r);
}
}
avlNode *insertion(avlNode *root,string sname,conDetails D)
{
static long long int code=0;
D.regCode=++code;
char temp=sname[0];
int key=(int)temp;
int res=searchInsert(root,key,sname,D);
if(res==1)
root=insertNode(root,key,sname,D);
return root;
}
int edit(avlNode *n,string sname,conDetails D,avlNode *root)
{
long long int x;
string s;
int val=(int)sname[0];
while(n!=NULL)
{
if(n->asc==val)
{
for(auto i=n->s.begin();i!=n->s.end();i++)
if(i->first==sname)
cout<<i->first<<"\t\t|\t\t"<<i->second.mob<<endl;
cout<<"Enter number : ";
cin>>x;
for(auto i=n->s.begin();i!=n->s.end();i++)
{
if((i->first==sname) && (i->second.mob==x))
{
cout<<"Enter new name : ";
std::getline(std::cin >> std::ws, s);
cout<<"Enter new Number :";
cin>>D.mob;
root=insertion(root,s,D);
n->s.erase(i);
return 0;
}
}
}
else
{
if(val >= n->asc)
return edit(n->r,sname,D,root);
else
return edit(n->l,sname,D,root);
}
}
return 1;
}
int del(avlNode *n,string sname,conDetails D,avlNode *root)
{
long long int x;
string s;
int val=(int)sname[0];
while(n!=NULL)
{
if(n->asc==val)
{
for(auto i=n->s.begin();i!=n->s.end();i++)
if(i->first==sname)
cout<<i->first<<"\t\t|\t\t"<<i->second.mob<<endl;
cout<<"Enter number : ";
cin>>x;
for(auto i=n->s.begin();i!=n->s.end();i++)
{
if((i->first==sname) && (i->second.mob==x))
{
n->s.erase(i);
return 0;
}
}
}
else
{
if(val >= n->asc)
return del(n->r,sname,D,root);
else
return del(n->l,sname,D,root);
}
}
return 1;
}
int main()
{
conDetails person;
avlNode *root=NULL;
string temp_name;
int choice,flag=0,flag1,x;
cout<<"* PHONEBOOK *"<<endl;
do
{
cout<<"\n\n\n";
cout<<"0. Show contacts"<<endl
<<"1. Add Contact"<<endl
<<"2. Edit Contact"<<endl
<<"3. Delete Contact"<<endl
<<"4. Search"<<endl
<<"5. Add Speed Dial"<<endl
<<"6. Speed Dial"<<endl
<<"7. Quit" <<endl<<endl
<<"Your choice...";
cin >> choice;
switch(choice)
{
case 0:
cout<< "Showing Contacts\n"<<endl;
cout<<"Name \t"<<"|"<<"\tMobile Number"<<"\t|\t"<<"RegCode"<<endl;
printin(root);
if(root==NULL)
cout << "No contacts found!" << endl;
break;
case 1:
cout<<" Name : ";
std::getline(std::cin >> std::ws, temp_name);
cout<<"Mobile no. : ";
cin>>person.mob;
root=insertion(root,temp_name,person);
break;
case 2:
cout<<"Enter contact name to be edited : ";
std::getline(std::cin >> std::ws, temp_name);
edit(root,temp_name,person,root);
break;
case 3:
cout<<"Enter contact name to be Deleted : ";
std::getline(std::cin >> std::ws, temp_name);
del(root,temp_name,person,root);
break;
case 4:
cout<<"Enter Name to be searched : ";
std::getline(std::cin >> std::ws, temp_name);
flag=searchCon(root,temp_name);
if(flag==1)
cout<<"No such contact exists "<<endl;
break;
case 5:
cout<<"Name \t"<<"|"<<"\tMobile Number"<<"\t|\t"<<"RegCode"<<endl;
printin(root);
cout<<"Enter RegCode for Speed Dial : ";
cin>>flag1;
cout<<"Enter Speed Dial priority : ";
cin>>x;
speed(root,flag1,x);
break;
case 6:
cout<<"Enter Speed Dial : ";
cin>>flag1;
callspeed(root,flag1);
break;
case 7:
cout << "Bye Bye" << endl;
break;
}
} while(choice!=7);
return 0;
}
| true |
e37314a2891383f29702052f06b055e19f5bce20 | C++ | phongvcao/CP_Contests_Solutions | /cpp/Codeforces/101-150/148A_Insomnia_cure.cc | UTF-8 | 1,106 | 3.15625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main(int argc, char **argv) {
// Read the lines
std::string line;
long long int lineNumArr[] = { 0, 0, 0, 0, 0 };
int idx = 0;
while (std::getline(std::cin, line)) {
std::stringstream ss(line);
ss >> lineNumArr[idx++];
if (idx == 5) break;
}
bool damagedArr[lineNumArr[4]];
for (unsigned int i = 0; i != sizeof(damagedArr)/sizeof(bool); ++i) {
damagedArr[i] = false;
}
for (unsigned int i = 0; i != sizeof(lineNumArr)/sizeof(long long int) - 1; ++i) {
if (sizeof(damagedArr)/sizeof(bool) >= lineNumArr[i]) {
for (unsigned int j = lineNumArr[i] - 1; j <= sizeof(damagedArr)/sizeof(bool); j += lineNumArr[i]) {
damagedArr[j] = true;
}
}
}
// Count the number of damagedDragons
long long int damagedCount = 0;
for (unsigned int i = 0; i != sizeof(damagedArr)/sizeof(bool); ++i) {
if (damagedArr[i]) ++damagedCount;
}
std::cout << damagedCount;
return 0;
}
| true |
a95c82a0e66fd4f02f46b6b0ea54fce594cd51d6 | C++ | bmendli/politech-labs-cpp | /common/test-circle.cpp | UTF-8 | 3,728 | 3.109375 | 3 | [] | no_license | #include <stdexcept>
#include <iostream>
#include <cmath>
#include <boost/test/auto_unit_test.hpp>
#include "circle.hpp"
BOOST_AUTO_TEST_SUITE(TestForCircle)
const double INACCURACY = 0.001;
BOOST_AUTO_TEST_CASE(immutabilityRadiusAfterMovingCenter)
{
maschenko::Circle test_circle({15, 15}, 5);
const double radius = test_circle.getRadius();
test_circle.move({50, 50});
BOOST_CHECK_CLOSE(test_circle.getRadius(), radius, INACCURACY);
}
BOOST_AUTO_TEST_CASE(immutabilityRadiusAfterMovingOnDxAndDy)
{
maschenko::Circle test_circle({15, 15}, 5);
const double radius = test_circle.getRadius();
test_circle.move(10, 10);
BOOST_CHECK_CLOSE(test_circle.getRadius(), radius, INACCURACY);
}
BOOST_AUTO_TEST_CASE(immutabilityAreaAfterMovingCenter)
{
maschenko::Circle test_circle({15, 15}, 5);
const double area = test_circle.getArea();
test_circle.move({50, 50});
BOOST_CHECK_CLOSE(test_circle.getArea(), area, INACCURACY);
}
BOOST_AUTO_TEST_CASE(immutabilityAreaAfterMovingOnDxAndDy)
{
maschenko::Circle test_circle({15, 15}, 5);
const double area = test_circle.getArea();
test_circle.move(10, 10);
BOOST_CHECK_CLOSE(test_circle.getArea(), area, INACCURACY);
}
BOOST_AUTO_TEST_CASE(AreaScalingIncrease)
{
maschenko::Circle test_circle {{15, 15}, 5};
const double area = test_circle.getArea();
const double increase_number = 3;
test_circle.scale(increase_number);
BOOST_CHECK_CLOSE(test_circle.getArea(), increase_number * increase_number * area, INACCURACY);
}
BOOST_AUTO_TEST_CASE(AreaScalingDecrease)
{
maschenko::Circle test_circle {{15, 15}, 5};
const double area = test_circle.getArea();
const double decrease_number = 0.25;
test_circle.scale(decrease_number);
BOOST_CHECK_CLOSE(test_circle.getArea(), area * decrease_number * decrease_number, INACCURACY);
}
BOOST_AUTO_TEST_CASE(ThrowExceptionAfterScale)
{
maschenko::Circle test_circle {{15, 15}, 5};
BOOST_CHECK_THROW(test_circle.scale(-10), std::invalid_argument);
}
BOOST_AUTO_TEST_CASE(ThrowExceptionDueIncorrectRadius)
{
BOOST_CHECK_THROW(maschenko::Circle test_circle({15, 15}, -5), std::invalid_argument);
}
BOOST_AUTO_TEST_CASE(immutabilityCenterAfterRotating)
{
maschenko::Circle circle({10, 10}, 20);
const maschenko::point_t center = circle.getCenter();
circle.rotate(M_PI / 2);
BOOST_CHECK_CLOSE(center.x, circle.getCenter().x, INACCURACY);
BOOST_CHECK_CLOSE(center.y, circle.getCenter().y, INACCURACY);
}
BOOST_AUTO_TEST_CASE(immutabilityAreaAfterRotating)
{
maschenko::Circle circle({10, 10}, 20);
const double area = circle.getArea();
circle.rotate(M_PI / 2);
BOOST_CHECK_CLOSE(area, circle.getArea(), INACCURACY);
}
BOOST_AUTO_TEST_CASE(immutabilityFrameRectAfterRotating360)
{
maschenko::Circle circle({10, 10}, 30);
const double width = circle.getFrameRect().width;
const double height = circle.getFrameRect().height;
circle.rotate(2 * M_PI);
BOOST_CHECK_CLOSE(width, circle.getFrameRect().width, INACCURACY);
BOOST_CHECK_CLOSE(height, circle.getFrameRect().height, INACCURACY);
}
BOOST_AUTO_TEST_CASE(swapSidesOfFrameRectAfterRotating90)
{
maschenko::Circle circle({10, 10}, 20);
const double width = circle.getFrameRect().width;
const double height = circle.getFrameRect().height;
circle.rotate(M_PI / 2);
BOOST_CHECK_CLOSE(width, circle.getFrameRect().height, INACCURACY);
BOOST_CHECK_CLOSE(height, circle.getFrameRect().width, INACCURACY);
}
BOOST_AUTO_TEST_CASE(correctWorkingMethodGetCenter)
{
maschenko::point_t center = {10, 10};
maschenko::Circle circle(center, 20);
BOOST_CHECK_CLOSE(center.x, circle.getCenter().x, INACCURACY);
BOOST_CHECK_CLOSE(center.y, circle.getCenter().y, INACCURACY);
}
BOOST_AUTO_TEST_SUITE_END()
| true |
e8ed7d3b0e4b06a9833d3d3a9f1b168da4ed05f2 | C++ | pavelsimo/ProgrammingContest | /hackerank/isthisabinarysearchtree2.cpp | UTF-8 | 562 | 3.0625 | 3 | [] | no_license | /* ========================================================================
$File:
$Date:
$Creator: Pavel Simo
======================================================================== */
bool checkBST(Node *root, int min, int max) {
if (root == NULL)
return true;
if (root->data < min || root->data > max)
return false;
return checkBST(root->left, min, root->data - 1)
&& checkBST(root->right, root->data + 1, max);
}
bool checkBST(Node* root)
{
bool res = checkBST(root, 0, 100002);
return res;
}
| true |
f48865111cf8dae64aca479b58528bae55d8289b | C++ | mjbriggs/DatalogEvaluator | /parameter.h | UTF-8 | 476 | 2.734375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
#include "tokType.h"
using namespace std;
class parameter{
private:
tokType type;
string typeStr;
string parameterStr;
vector <string> parameters;
//might need a vector for parameter contents
public:
parameter();
string toString();
void setTypeStr(tokType typeIn);
void setParameter(string parameterIn);
vector <string> returnParameters();
};
| true |
8df68bb851c8c230fc9f03508156754a235d2bbc | C++ | Plantaquatix/Driver-analysis | /code/traclus/traclus/Trajectory.cpp | UTF-8 | 872 | 2.796875 | 3 | [] | no_license | // Trajectory.cpp : implementation file
//
#include "Trajectory.h"
#include <iomanip>
// CTrajectory
CTrajectory::CTrajectory()
{
m_trajectoryId = -1;
m_nDimensions = 2;
m_nPoints = 0;
m_nPartitionPoints = 0;
}
CTrajectory::CTrajectory(int id, int nDimensions)
{
m_trajectoryId = id;
m_nDimensions = nDimensions;
m_nPoints = 0;
m_nPartitionPoints = 0;
}
CTrajectory::~CTrajectory()
{
m_nPoints = 0;
}
// CCluster member functions
bool CTrajectory::WritePartitionPts(ofstream& outFile)
{
outFile << (int) m_trajectoryId << ' ' << (int)m_nPartitionPoints << ' ';
for (int i = 0; i < (int)m_partitionPointArray.size(); i++)
{
outFile << fixed << setprecision(1);
outFile << m_partitionPointArray[i].GetCoordinate(0) << ' ' << m_partitionPointArray[i].GetCoordinate(1) << ' ';
}
outFile << endl;
return true;
}
// CTrajectory member functions
| true |
4647d73f8fda482154b70183a8951f4e1751407f | C++ | Gaurav07Robin/worldLineSim | /src/Entities/human.cpp | UTF-8 | 2,978 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <graphMat/iterators.hpp>
#include "Entities/human.hpp"
#include "world.hpp"
#include "db/database.hpp"
std::optional<Entity_Point> Human::getPrimaryPos() const
{
return this->curr_pos;
}
void Human::simulateExistence()
{
this->should_wander = true;
this->has_been_paused = false;
while (this->should_wander && this->parent_world->is_world_running())
{
LOGGER::log_msg("[{} #{}] moving from {}", mName, this->_id, this->curr_pos.point_coord);
graphMat::NeighbourIterator<Box> iter(this->curr_pos.graph_box);
auto random_number_of_loops = rand() % 4;
do {
++iter; // ie. skip the current box
} while (random_number_of_loops-- > 0);
for (; iter ; ++iter)
{
auto box_ptr = iter.operator->();
if ( ! iter->getData().hasEntities()) {
this->curr_pos.graph_box->getDataRef().remEntity(this);
this->curr_pos.graph_box = box_ptr;
coord increment_coord = iter._getIncrementCoords();
if (curr_pos.graph_box != iter.center_box) {
// if it's not the center box we passed to initialiser, then it is EITHER FRONT_FACING or BACK_FACING
increment_coord.mZ = (curr_pos.graph_box->FRONT_FACING == iter.center_box) ? 1 : -1;
}
this->curr_pos.point_coord += increment_coord;
this->curr_pos.graph_box->getDataRef().addEntity(this);
break;
}
}
std::this_thread::sleep_for(statics::UNIT_TIME * TIME_DIFF_PER_MOVE );
}
this->has_been_paused = true;
}
void Human::pauseExistence()
{
if (!should_wander) return;
this->should_wander = false;
while (!this->has_been_paused) {} // we keep checking until it's stopped
}
Human::Human(World_Ptr const world, Gender gender): Human(world, db::getRandomName(gender, _id), gender) {}
Human::Human(World_Ptr const world, const std::string& name, Gender gender):
Entity(Entity_Types::HUMAN),
parent_world(world),
curr_pos(nullptr, world->world_plot.getRandomCoord()),
gender(gender),
mName(name)
{
LOGGER::log_msg("{} [#{}] is here... Location: {}", mName, this->_id, this->curr_pos.point_coord);
this->curr_pos.graph_box = this->parent_world->get_box(curr_pos.point_coord);
assert(curr_pos.graph_box != nullptr); // remove this assert after tests written that getRandomCoord() always returns correct one
}
Human::Human(World_Ptr const world, const HumanState& prev_state):
Entity(Entity_Types::HUMAN),
parent_world(world),
curr_pos(nullptr, prev_state.location),
gender(prev_state.gender),
mName(db::getNameFromId(prev_state.old_id))
{
LOGGER::log_msg("#{} born ... Location: {}", mName, this->_id, this->curr_pos.point_coord);
this->curr_pos.graph_box = this->parent_world->get_box(curr_pos.point_coord);
assert(curr_pos.graph_box != nullptr);
}
Human::~Human()
{
this->pauseExistence();
}
HumanState* Human::_get_current_state() const
{
return new HumanState(this);
}
HumanState::HumanState(const Human* human):
EntityState(Entity_Types::HUMAN),
location(human->curr_pos.point_coord),
old_id(human->_id),
gender(human->gender)
{}
| true |
bf7a62fe8d577c7ff003a3c75f5c351b6b6f10c4 | C++ | wenqicao/algorithm-sec2 | /13_13.cpp | UTF-8 | 1,048 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
bool find_all_substring_handler(string& str, unordered_map<string,int>& dict, int start, int unitsize, int numofword){
unordered_map<string,int> cur_dict;
for(int i=0;i<numofword;i++){
string cur_word = str.substr(start+i*unitsize,unitsize);
if(dict.find(cur_word)==dict.end()){
return false;
}
cur_dict[cur_word]++;
auto it = dict.find(cur_word);
if(cur_dict[cur_word]>it->second){
return false;
}
}
return true;
}
vector<int> find_all_substring(vector<string>& L, string str){
vector<int> res;
unordered_map<string, int> dict;
for(string s : L){
dict[s]++;
}
int unitsize = L.front().size();
int numofword = L.size();
for(int i=0;i + unitsize*numofword <=str.size();i++){
if(find_all_substring_handler(str,dict,i,unitsize,numofword)){
res.emplace_back(i);
}
}
return res;
}
int main(){
vector<string> in = {"aa","bb","cc","dd"};
auto res = find_all_substring(in,"aaccbbdd");
for(int x: res){
cout<<x<<" ";
}
} | true |
b657743756b4e8c4428cb08c1cf3a5a78290c845 | C++ | jeacevedo92/SecondPartialHPC | /SobelFIlter/CPU/c++/SobelFilter.cpp | UTF-8 | 4,426 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<malloc.h>
//#include <cv.h>
//#include <highgui.h>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
unsigned char clamp(int value){//porque cuando se hace la convolución pueden salir números fuera del rango de unsigned char
if(value < 0)
value = 0;
else
if(value > 255)
value = 255;
return (unsigned char)value;
}
void imprime(unsigned char *A,int filas, int columnas){//imprime los pixeles, 0..255
for (int i = 0; i < filas; i++) {
for (int j = 0; j < columnas; j++) {
cout<<((int)A[(i * columnas) + j])<<" ";//le hacemos un cast para que me muestre los numeros y no los caracteres
}
cout<<endl;
}
}
void convolucion(unsigned char *imagen, int mascara[3][3], int filas, int columnas, unsigned char *resultado){
for(int i = 0; i < filas; i++){
for(int j = 0; j < columnas; j++){//hacemos el recorrido por cada pixel
int suma = 0;
int aux_cols = j - 1, aux_rows = i - 1;
for(int k = 0; k < 3; k++){//mask_rows
for(int l = 0; l < 3; l++){//mask_cols
if((aux_rows >= 0 && aux_cols >= 0) && (aux_rows < filas && aux_cols < columnas))
suma += mascara[k][l]*imagen[(aux_rows*columnas)+ aux_cols];
aux_cols++;
}
aux_rows++;
aux_cols = j - 1;
}
resultado[(i * columnas) + j] = clamp(suma);
}
}
}
void Union(unsigned char *img_resultado, unsigned char *resultado_Gx, unsigned char *resultado_Gy, int filas, int columnas){
for(int i = 0; i < filas; i++){
for(int j = 0; j < columnas; j++){
img_resultado[(i * columnas) + j] = sqrt(pow(resultado_Gx[(i * columnas) + j],2) + pow(resultado_Gx[(i * columnas) + j],2));
}
}
}
int main(int argc, char **argv){
unsigned char *img_gray;
unsigned char *G, *resultado_Gx , *resultado_Gy;//imagenes para la convolucion
int Mascara_X[3][3], Mascara_Y[3][3];
char* imageName = argv[1];
Mat image;
//times
clock_t start, end;
double time_used;
image = imread(imageName, 1);
if(argc !=2 || !image.data){
printf("No image Data \n");
return -1;
}
Size s = image.size();//sacamos los atributos de la imagen
int width = s.width;
int height = s.height;
int size = sizeof(unsigned char)*width*height;//para la imagen en escala de grises
start = clock();
//La pasamos a escala de grises con Opencv
Mat gray_image_opencv;//Esta es la que le vamos a aplicar el filtro Sobel
gray_image_opencv.create(height,width,CV_8UC1);
cvtColor(image, gray_image_opencv, CV_BGR2GRAY);//pasamos la imagen que se lee a escala de grises
img_gray = gray_image_opencv.data;//queda con el mismo height y weight de la imagen normal
//imshow("Escala de grises",gray_image_opencv);
resultado_Gx = (unsigned char*)malloc(size);
resultado_Gy = (unsigned char*)malloc(size);
G = (unsigned char*)malloc(size);
Mascara_X[0][0]=-1;Mascara_X[0][1]=0;Mascara_X[0][2]=1;
Mascara_X[1][0]=-2;Mascara_X[1][1]=0;Mascara_X[1][2]=2;
Mascara_X[2][0]=-1;Mascara_X[2][1]=0;Mascara_X[2][2]=1;
Mascara_Y[0][0]=-1;Mascara_Y[0][1]=-2;Mascara_Y[0][2]=-1;
Mascara_Y[1][0]=0;Mascara_Y[1][1]=0;Mascara_Y[1][2]=0;
Mascara_Y[2][0]=1;Mascara_Y[2][1]=2;Mascara_Y[2][2]=1;
convolucion(img_gray, Mascara_X, height, width, resultado_Gx);
convolucion(img_gray, Mascara_Y, height, width, resultado_Gy);
Union(G,resultado_Gx,resultado_Gy,height,width);
end = clock();
time_used = ((double) (end - start)) /CLOCKS_PER_SEC;
//printf ("%ld %s %lf \n",sze,imageName,time_used);
printf ("%lf \n",time_used);
//Mat resultado;
//resultado.create(height,width,CV_8UC1);
//resultado.data = G;
//imshow("Sobel",resultado);
//imwrite("./ImageSobelc.jpg",resultado);
//waitKey(0);
//Se libera memoria
free(G);
free(resultado_Gx);
free(resultado_Gy);
return 0;
}
| true |
e2ee82cf3d1789e495a7c851ac143b19813cd11a | C++ | Reitermaniac/AutomaticNightLight | /driver/button/Button.cpp | UTF-8 | 1,405 | 2.625 | 3 | [] | no_license | #ifdef SETTING_BUTTON
void Button::begin()
{
pinMode(BUTTON_TOGGLE_COLOR_PIN, INPUT_PULLUP);
pinMode(BUTTON_TOGGLE_ON_OFF_PIN, INPUT_PULLUP);
pinMode(BUTTON_SENSOR_PIN, INPUT_PULLUP);
pinMode(BUTTON_PERM_PIN, INPUT_PULLUP);
pinMode(BUTTON_PERM_ON_PIN, INPUT_PULLUP);
pinMode(BUTTON_PERM_OFF_PIN, INPUT_PULLUP);
buttonShortlyPressed = false;
buttonPressTime = 0;
}
void Button::getButtonInput()
{
if(!buttonShortlyPressed)
{
if(digitalRead(BUTTON_TOGGLE_COLOR_PIN) == LOW)
{
DEBUG_PRINTLN("Button Color");
mode.setOperationMode(COLOR);
buttonShortlyPressed = true;
buttonPressTime = millis();
}
if(digitalRead(BUTTON_TOGGLE_ON_OFF_PIN) == LOW)
{
DEBUG_PRINTLN("Button ON/OFF");
mode.setOperationMode(POWER);
buttonShortlyPressed = true;
buttonPressTime = millis();
}
if(digitalRead(BUTTON_SENSOR_PIN) == LOW)
{
DEBUG_PRINTLN("Button Sensor");
mode.setOperationMode(AUTO);
buttonShortlyPressed = true;
buttonPressTime = millis();
}
if(digitalRead(BUTTON_PERM_PIN) == LOW)
{
DEBUG_PRINTLN("Button Perm");
mode.setOperationMode(PERM);
buttonShortlyPressed = true;
buttonPressTime = millis();
}
}
else
{
if((millis() - buttonPressTime) >= TIME_BETWEEN_BUTTON_PRESS_MS)
{
buttonShortlyPressed = false;
}
}
}
#endif
| true |
7a625b286367d22679e0152ee3af0c434c7c055b | C++ | bufenceto/PuG | /core/graphics/src/win32_window.cpp | UTF-8 | 2,509 | 2.546875 | 3 | [] | no_license | #include "win32_window.h"
namespace pug {
namespace graphics {
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
Window* Window::Create(const std::string& a_title, const vmath::Int2& a_size)
{
Win32Window* window = new Win32Window();
window->Initialize(a_title, a_size);
return window;
}
PUG_RESULT Win32Window::Initialize(const std::string& a_title, const vmath::Int2& a_size)
{
m_size = a_size;
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;// | CS_NOCLOSE;
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.cbClsExtra = 0; // No extra class data
wc.cbWndExtra = sizeof(void*) + sizeof(int); // Make room for one pointer
wc.hInstance = GetModuleHandle(NULL);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL; // No background
wc.lpszMenuName = NULL; // No menu
wc.lpszClassName = "DirectXWindowClass";
// Load user-provided icon if available
wc.hIcon = LoadIcon(GetModuleHandle(NULL), "GLFW_ICON");
if (!wc.hIcon)
{
// No user-provided icon found, load default icon
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
}
if (!RegisterClass(&wc))
{
// Failed to register window class
return PUG_RESULT_PLATFORM_ERROR;
}
// Calculate full window size (including borders)
DWORD m_style = WS_OVERLAPPEDWINDOW;
RECT rect = { 0, 0, a_size.x, a_size.y };
AdjustWindowRect(&rect, m_style, FALSE);
uint32_t width = rect.right - rect.left;
uint32_t height = rect.bottom - rect.top;
int x = (GetSystemMetrics(SM_CXSCREEN) - rect.right) / 2 + rect.left;
int y = (GetSystemMetrics(SM_CYSCREEN) - rect.bottom) / 2 + rect.top;
m_hwnd = CreateWindow(
wc.lpszClassName,
a_title.c_str(),
m_style,
x, y,
width, height,
0, 0,
GetModuleHandle(0),
nullptr);
if (m_hwnd == NULL)
{
return PUG_RESULT_PLATFORM_ERROR;
}
ShowWindow(m_hwnd, 1);
return PUG_RESULT_OK;
}
void Win32Window::Destroy()
{
}
void Win32Window::DispatchMessages()
{
MSG msg;
while (PeekMessage(&msg, m_hwnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
void Win32Window::SetTitle(const std::string& a_title)
{
SetWindowText(m_hwnd, a_title.c_str());
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
}
} | true |
84230dc64acc334524c09d9ef92757668bc2e408 | C++ | allisterke/cpp-training-lab | /practise/binary_indexed_tree.cpp | UTF-8 | 1,083 | 2.9375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using LL = long long int;
class BinaryIndexedTree {
private:
vector<int> tree;
public:
BinaryIndexedTree(int capacity) : tree(capacity + 1) {
}
void update(int index, int val) {
int diff = val - (query(index) - query(index-1));
while(index < tree.size()) {
tree[index] += diff;
index += (index & (-index));
}
}
int query(int end) {
int sum = 0;
while (end > 0) {
sum += tree[end];
end -= (end & (-end));
}
return sum;
}
};
int main() {
int n = 20;
vector<int> nums(n);
for(auto &n : nums) {
n = rand() % 20;
}
BinaryIndexedTree bit(n);
for(int i = 0; i < nums.size(); ++ i) {
bit.update(i+1, nums[i]);
}
vector<pair<int, int>> ranges{{1,3}, {4,8}, {2, 20}, {7, 17}};
for(auto &r : ranges) {
assert(accumulate(nums.begin() + (r.first - 1), nums.begin() + r.second, 0) == bit.query(r.second) - bit.query(r.first - 1));
}
return 0;
}
| true |
3e90612a59e092a9e4e23b2ba2419518d5d63cea | C++ | Ythnam/C-Users-PhilippeJ-WorkspaceCPP-FrameWorkFloue | /FrameWorkFloue/Fuzzy/NotMinus1.h | ISO-8859-1 | 460 | 2.671875 | 3 | [] | no_license | /*
* NotMinus1.h
*
* Created on: 2 fvr. 2016
* Author: PhilippeJ
*/
#ifndef NOTMINUS1_H_
#define NOTMINUS1_H_
#include "Not.h"
namespace fuzzy {
template<class T>
class NotMinus1: public Not<T> {
public:
virtual ~NotMinus1() {};
T evaluate(core::Expression<T>*) const;
};
template<class T>
T NotMinus1<T>::evaluate(core::Expression<T>* e) const {
T ev = e->evaluate();
return 1 - ev;
}
}
#endif /* NOTMINUS1_H_ */
| true |