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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1a5ff418d9c9e2279471f86ac63faa3c1e04f49f | C++ | liuyaqiu/LeetCode-Solution | /386-Lexicographical-Numbers.cpp | UTF-8 | 1,246 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
/*
* Lexicographical Numbers
*
* Given an integer n, return 1 - n in lexicographical order.
*
* For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
*
* Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
*
*
*/
int getLen(int n) {
return floor(log10(n)) + 1;
}
int cut(int n) {
n /= 10;
while(n % 10 == 9)
n /= 10;
if(n == 0)
return n;
else
return n + 1;
}
vector<int> lexicalOrder(int n) {
vector<int> res;
if(n < 1)
return res;
int num = 1;
int len = getLen(n);
while(num != 0) {
if(num > n) {
num = cut(num);
}
else {
res.push_back(num);
if(getLen(num) < len) {
num *= 10;
}
else {
if(num % 10 == 9)
num = cut(num);
else
num += 1;
}
}
}
return res;
}
int main() {
int n;
cin >> n;
vector<int> res = lexicalOrder(n);
for(auto item: res)
cout << item << " ";
cout << endl;
return 0;
}
| true |
7ded95aebcb754e339ac4a3b112532bf669bb043 | C++ | aetrnm/CPPBinaryTree | /BinaryTreeProject/Cell.h | UTF-8 | 383 | 3.1875 | 3 | [] | no_license | #pragma once
class Cell {
public:
Cell(int value);
int get_value() const;
void add(int value);
bool contains(int value);
Cell* find_and_remove_min_cell_in_sub_tree();
Cell* remove_in_sub_tree(int value);
void print_sub_tree() const;
int get_height_of_sub_tree() const;
private:
int value_;
Cell* left_cell;
Cell* right_cell;
Cell* find_cell_by_value(int value);
};
| true |
06993df276e6264075349764ec0eb99e098269b3 | C++ | Ablustrund/PATCode | /PAT_B/PAT_B1084.CPP | UTF-8 | 485 | 2.546875 | 3 | [
"BSD-2-Clause"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int d, n;
int main()
{
scanf("%d%d", &d, &n);
string str = "0";
str[0] += d;
for (int i = 0; i < n-1; i++)
{
string tempStr = "";
int j = 0, k = 0;
while(j < str.size())
{
while(k < str.size() && str[j] == str[k]) k++;
tempStr += str[j] + to_string(k - j);
j = k;
}
str = tempStr;
}
printf("%s\n", str.c_str());
return 0;
} | true |
a90ce3d4cccf5d5d2d125ee55e16a447b3ac28fb | C++ | CYChack/KUDAEDEM | /KUDAMCHIM/KUDAMCHIM/main.cpp | UTF-8 | 951 | 2.5625 | 3 | [] | no_license | #include <iostream>
void main() {
int a = 0, b = 0, c = 0, d = 0, e = 0;
std::cout << "lubish teplo? 1-da, 2-net";
std::cin >> a;
std::cout << "Hochesh na more? 1-da, 2-net";
std::cin >> b;
std::cout << "Hochesh v gorbI? 1-da, 2-net";
std::cin >> c;
std::cout << "za legalayz? 1-da, 2-net";
std::cin >> d;
std::cout << "mnogo deneg? 1-da, 2-net";
std::cin >> e;
if (a == 1 && b == 1 && c == 1 && d == 1 && e == 1)
std::cout << "edb v KAZAHSTAN";
else
if (a == 2 && b == 2 && c == 2 && d == 2 && e == 2)
std::cout << "vali v Koryajmu";
else
if (a == 1 && b == 2 && c == 2 && d == 1 && e == 1)
std::cout << "doroga v Amsterdam)";
else
if (a == 1 && b == 1 && c == 2 && d == 2 && e == 1)
std::cout << "cheshi na Bali";
else
if (a == 2 && b == 2 && c == 1 && d == 2 && e == 2)
std::cout << "avtostopom do Norvegii";
else
std::cout << "ostavaysya doma";
} | true |
8af18f860bed04e568ccbcabbadc630f2bd2e02c | C++ | perryiv/generic_scene_graph | /source/GSG/Tools/Visitors/Callbacks/Const.cpp | UTF-8 | 4,593 | 2.578125 | 3 | [
"MIT"
] | permissive |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2021, Perry L Miller IV
// All rights reserved.
// MIT License: https://opensource.org/licenses/mit-license.html
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Scene visitor that simply calls registered functions.
//
///////////////////////////////////////////////////////////////////////////////
#include "GSG/Tools/Visitors/Callbacks/Const.h"
#include "GSG/Scene/Nodes/Groups/Transform.h"
#include "GSG/Scene/Nodes/Shapes/Geometry.h"
#include "Usul/Tools/NoThrow.h"
#include <functional>
namespace GSG {
namespace Tools {
namespace Visitors {
namespace Callbacks {
// Add the boilerplate code.
GSG_IMPLEMENT_VISITOR_CLASS ( Const )
///////////////////////////////////////////////////////////////////////////////
//
// Constructor.
//
///////////////////////////////////////////////////////////////////////////////
Const::Const() : BaseClass(),
_transformCallbackBefore(),
_transformCallbackAfter(),
_groupCallbackBefore(),
_groupCallbackAfter(),
_geometryCallback(),
_shapeCallback(),
_nodeCallback()
{
}
///////////////////////////////////////////////////////////////////////////////
//
// Destructor.
//
///////////////////////////////////////////////////////////////////////////////
Const::~Const()
{
USUL_TOOLS_NO_THROW ( 1609779504, std::bind ( &Const::_destroyConst, this ) );
}
///////////////////////////////////////////////////////////////////////////////
//
// Destroy this instance.
//
///////////////////////////////////////////////////////////////////////////////
void Const::_destroyConst()
{
_transformCallbackBefore = nullptr;
_transformCallbackAfter = nullptr;
_groupCallbackBefore = nullptr;
_groupCallbackAfter = nullptr;
_geometryCallback = nullptr;
_shapeCallback = nullptr;
_nodeCallback = nullptr;
}
///////////////////////////////////////////////////////////////////////////////
//
// Call the function if it is valid.
//
///////////////////////////////////////////////////////////////////////////////
namespace Details
{
template < class CallbackType, class NodeType >
inline void call ( CallbackType cb, const NodeType &node, Const::PropertyMap &props )
{
if ( cb )
{
cb ( node, props );
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Visit the node.
//
///////////////////////////////////////////////////////////////////////////////
void Const::visit ( const GSG::Scene::Nodes::Groups::Transform &trans, PropertyMap &props )
{
Details::call ( _transformCallbackBefore, trans, props );
BaseClass::visit ( trans, props );
Details::call ( _transformCallbackAfter, trans, props );
}
void Const::visit ( const GSG::Scene::Nodes::Groups::Group &group, PropertyMap &props )
{
Details::call ( _groupCallbackBefore, group, props );
BaseClass::visit ( group, props );
Details::call ( _groupCallbackAfter, group, props );
}
void Const::visit ( const GSG::Scene::Nodes::Shapes::Geometry &geom, PropertyMap &props )
{
Details::call ( _geometryCallback, geom, props );
BaseClass::visit ( geom, props );
}
void Const::visit ( const GSG::Scene::Nodes::Shapes::Shape &shape, PropertyMap &props )
{
Details::call ( _shapeCallback, shape, props );
BaseClass::visit ( shape, props );
}
void Const::visit ( const GSG::Scene::Nodes::Node &node, PropertyMap &props )
{
Details::call ( _nodeCallback, node, props );
BaseClass::visit ( node, props );
}
///////////////////////////////////////////////////////////////////////////////
//
// Set the callbacks.
//
///////////////////////////////////////////////////////////////////////////////
void Const::setTransformCallback ( TransformCallback cb, When when )
{
if ( BEFORE_TRAVERSAL == when )
{
_transformCallbackBefore = cb;
}
else if ( AFTER_TRAVERSAL == when )
{
_transformCallbackAfter = cb;
}
}
void Const::setGroupCallback ( GroupCallback cb, When when )
{
if ( BEFORE_TRAVERSAL == when )
{
_groupCallbackBefore = cb;
}
else if ( AFTER_TRAVERSAL == when )
{
_groupCallbackAfter = cb;
}
}
void Const::setGeometryCallback ( GeometryCallback cb )
{
_geometryCallback = cb;
}
void Const::setShapeCallback ( ShapeCallback cb )
{
_shapeCallback = cb;
}
void Const::setNodeCallback ( NodeCallback cb )
{
_nodeCallback = cb;
}
} // namespace Callbacks
} // namespace Visitors
} // namespace Tools
} // namespace GSG
| true |
f33f6f44a34be4731b22e1ac1b19ea975eb16569 | C++ | sanchitahuja/CollegeCodes | /4th Semester/Operating Systems Lab/06_Multilevel.cpp | UTF-8 | 6,874 | 2.78125 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
struct pq
{
int pno;
int at,bt,ct,tat,wt,rt,st;
struct pq* nextp;
}*tmp1,*tmp2,*tmp3;
struct pq *q1=NULL;
struct pq *q2=NULL;
struct pq *q3=NULL;
struct pq *q4=NULL;
struct pq *qd=NULL;
struct pq *nwnd=NULL;
int pnum=1;
int currt=0;
int insertq1(int arr,int bur)
{
nwnd=(struct pq*)malloc(sizeof(struct pq));
nwnd->pno=pnum++;
nwnd->at=arr;
nwnd->bt=bur;
nwnd->ct=0;
nwnd->rt=0;
nwnd->tat=0;
nwnd->wt=0;
nwnd->st=0;
tmp2=q1;
if(q1==NULL)
{
nwnd->nextp=NULL;
q1=nwnd;
return 1;
}
while((tmp2->nextp!=NULL)&&(nwnd->at>=tmp2->at))
{
tmp1=tmp2;
tmp2=tmp2->nextp;
}
if((tmp2==q1)&&(nwnd->at>=tmp2->at))
{
q1->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
if((tmp2==q1)&&(nwnd->at<tmp2->at))
{
nwnd->nextp=q1;
q1=nwnd;
return 1;
}
if(nwnd->at<tmp2->at)
{
nwnd->nextp=tmp2;
tmp1->nextp=nwnd;
return 1;
}
if(tmp2->nextp==NULL)
{
tmp2->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
return 0;
}
int insertq2(int arr,int bur)
{
nwnd=(struct pq*)malloc(sizeof(struct pq));
nwnd->pno=pnum++;
nwnd->st=0;
nwnd->at=arr;
nwnd->bt=bur;
nwnd->ct=0;
nwnd->rt=0;
nwnd->tat=0;
nwnd->wt=0;
tmp2=q2;
if(q2==NULL)
{
nwnd->nextp=NULL;
q2=nwnd;
return 1;
}
while((tmp2->nextp!=NULL)&&(nwnd->at>=tmp2->at))
{
tmp1=tmp2;
tmp2=tmp2->nextp;
}
if((tmp2==q2)&&(nwnd->at>=tmp2->at))
{
q2->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
if((tmp2==q2)&&(nwnd->at<tmp2->at))
{
nwnd->nextp=q2;
q2=nwnd;
return 1;
}
if(nwnd->at<tmp2->at)
{
nwnd->nextp=tmp2;
tmp1->nextp=nwnd;
return 1;
}
if(tmp2->nextp==NULL)
{
tmp2->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
return 0;
}
int insertq3(int arr,int bur)
{
nwnd=(struct pq*)malloc(sizeof(struct pq));
nwnd->pno=pnum++;
nwnd->at=arr;
nwnd->bt=bur;
nwnd->ct=0;
nwnd->rt=0;
nwnd->tat=0;
nwnd->st=0;
nwnd->wt=0;
tmp2=q3;
if(q3==NULL)
{
nwnd->nextp=NULL;
q3=nwnd;
return 1;
}
while((tmp2->nextp!=NULL)&&(nwnd->at>=tmp2->at))
{
tmp1=tmp2;
tmp2=tmp2->nextp;
}
if((tmp2==q3)&&(nwnd->at>=tmp2->at))
{
q3->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
if((tmp2==q3)&&(nwnd->at<tmp2->at))
{
nwnd->nextp=q3;
q3=nwnd;
return 1;
}
if(nwnd->at<tmp2->at)
{
nwnd->nextp=tmp2;
tmp1->nextp=nwnd;
return 1;
}
if(tmp2->nextp==NULL)
{
tmp2->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
return 0;
}
int insertq4(int arr,int bur)
{
nwnd=(struct pq*)malloc(sizeof(struct pq));
nwnd->pno=pnum++;
nwnd->at=arr;
nwnd->bt=bur;
nwnd->st=0;
nwnd->ct=0;
nwnd->rt=0;
nwnd->tat=0;
nwnd->wt=0;
tmp2=q4;
if(q4==NULL)
{
nwnd->nextp=NULL;
q4=nwnd;
return 1;
}
while((tmp2->nextp!=NULL)&&(nwnd->at>=tmp2->at))
{
tmp1=tmp2;
tmp2=tmp2->nextp;
}
if((tmp2==q4)&&(nwnd->at>=tmp2->at))
{
q4->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
if((tmp2==q4)&&(nwnd->at<tmp2->at))
{
nwnd->nextp=q4;
q4=nwnd;
return 1;
}
if(nwnd->at<tmp2->at)
{
nwnd->nextp=tmp2;
tmp1->nextp=nwnd;
return 1;
}
if(tmp2->nextp==NULL)
{
tmp2->nextp=nwnd;
nwnd->nextp=NULL;
return 1;
}
return 0;
}
int insertqd(int prno,int art,int but,int compt,int strt)
{
printf("\nInsertqd executed");
nwnd=(struct pq*)malloc(sizeof(struct pq));
nwnd->pno=prno;
nwnd->at=art;
nwnd->bt=but;
nwnd->ct=compt;
nwnd->tat=compt-nwnd->at;
nwnd->wt=nwnd->tat-nwnd->bt;
nwnd->rt=nwnd->wt;
nwnd->st=strt;
nwnd->nextp=NULL;
tmp2=qd;
if(qd==NULL)
{
nwnd->nextp=NULL;
qd=nwnd;
return 1;
}
while(tmp2->nextp!=NULL)
{
tmp2=tmp2->nextp;
}
tmp2->nextp=nwnd;
return 1;
}
int disp1()
{
tmp1=q1;
while(tmp1!=NULL)
{
printf(" %d ",tmp1->pno);
tmp1=tmp1->nextp;
}
}
int disp2()
{
tmp1=q2;
while(tmp1!=NULL)
{
printf(" %d ",tmp1->pno);
tmp1=tmp1->nextp;
}
}
int disp3()
{
tmp1=q3;
while(tmp1!=NULL)
{
printf(" %d ",tmp1->pno);
tmp1=tmp1->nextp;
}
}
int disp4()
{
tmp1=q4;
while(tmp1!=NULL)
{
printf(" %d ",tmp1->pno);
tmp1=tmp1->nextp;
}
}
int dispfq()
{
tmp1=qd;
while(tmp1!=NULL)
{
printf("|%d P%d %d|->",tmp1->st,tmp1->pno,tmp1->ct);
tmp1=tmp1->nextp;
}
tmp1=qd;
printf("\nProcess no.\t|Arrival Time\t|Burst Time\t|Completion Time\t|Turn Around Time\t|Wait Time\t|Response Time|");
while(tmp1!=NULL)
{
printf("\nP%d\t\t|%d\t\t|%d\t\t|%d\t\t\t|%d\t\t\t|%d\t\t\t|%d\t\t|\n",tmp1->pno,tmp1->at,tmp1->bt,tmp1->ct,tmp1->tat,tmp1->wt,tmp1->rt);
tmp1=tmp1->nextp;
}
}
int execu()
{
//printf("\nInside Exec");
int s=0;
if(q1!=NULL)
{
//printf("\nINside q1");
// printf("%d",q1->bt);
if(q1->at<=currt)
{
s=currt;
currt+=q1->bt;
insertqd(q1->pno,q1->at,q1->bt,currt,s);
//printf("\nBack in q1");
q1=q1->nextp;
return 1;
}
}
if(q2!=NULL)
{
//printf("\nINside q1");
// printf("%d",q1->bt);
s=currt;
if(q2->at<=currt)
{
currt+=q2->bt;
insertqd(q2->pno,q2->at,q2->bt,currt,s);
//printf("\nBack in q1");
q2=q2->nextp;
return 1;
}
}
if(q3!=NULL)
{
//printf("\nINside q1");
// printf("%d",q1->bt);
if(q3->at<=currt)
{
s=currt;
currt+=q3->bt;
insertqd(q3->pno,q3->at,q3->bt,currt,s);
//printf("\nBack in q1");
q3=q3->nextp;
return 1;
}
}
if(q4!=NULL)
{
//printf("\nINside q1");
// printf("%d",q1->bt);
if(q4->at<=currt)
{
s=currt;
currt+=q4->bt;
insertqd(q4->pno,q4->at,q4->bt,currt,s);
//printf("\nBack in q1");
q4=q4->nextp;
return 1;
}
}
currt+=1;
return 0;
}
int main()
{
int ch=1,art=0,but=0,qno=0;
while(true)
{
printf("\n\nEnter Your Choice\n1. Enter a new Process\n2. Execute all the processes\n3. Exit\n");
scanf("%d",&ch);
if(ch==1)
{
printf("\nP%d-------------",pnum);
printf("\nEnter the Arrival time : ");
scanf("%d",&art);
printf("\nEnter the Burst time : ");
scanf("%d",&but);
printf("\nEnter the process queue[1=> Highest P., 4=> Lowest P.] :");
scanf("%d",&qno);
if(qno==1)
{
insertq1(art,but);
}
else if(qno==2)
{
insertq2(art,but);
}
else if(qno==3)
{
insertq3(art,but);
}
else if(qno==4)
{
insertq4(art,but);
}
else
printf("\nInvalid Queue Number");
currt=0;
}
else if(ch==2)
{
printf("\n");
disp1();
printf("\n");
disp2();
printf("\n");
disp3();
printf("\n");
disp4();
printf("\nExecuting all the processes\n\n");
//printf("\n%d %d %d %d",q1,q2,q3,q4);
while((q1!=NULL)||(q2!=NULL)||(q3!=NULL)||(q4!=NULL))
{
//printf("\nInside While");
//dispfq();
//printf("\n%d %d %d %d",q1,q2,q3,q4);
//printf("%d",execu());
//printf("\nBack Inside While");
execu();
}
printf("\n");
dispfq();
//exec();
}
else if(ch==3)
{
break;
}
else
{
printf("\nINVALID CHOICE!!!\n Re-Enter");
}
}
return 1;
}
| true |
a3d22ca790980071c85b6c4f15885a2b18d075bb | C++ | DBurden1997/Elemental | /Elemental/ECS/Modifiers/headers/Modifier.hpp | UTF-8 | 966 | 3.09375 | 3 | [] | no_license | //
// Modifier.hpp
// Elemental
//
// Created by Dylan Burden on 2018-08-22.
// Copyright © 2018 Elemental. All rights reserved.
//
#ifndef Modifier_hpp
#define Modifier_hpp
#include <string>
class Modifier {
public:
//Constructor
Modifier( unsigned long ownerId, std::string stat, std::string precedence );
//Getters and setters
unsigned long getOwnerId() { return ownerId; }
std::string getStat() { return stat; }
std::string getPrecedence() { return precedence; }
void setPlacement( int placement ) { vectorPlacement = placement; }
int getPlacement() { return vectorPlacement; }
private:
//The id of the owner entity
unsigned long ownerId;
//The stat this modifier affects
std::string stat;
//The precedence of the modifier ( order in which it is applied )
std::string precedence;
//The space within the vector it is in
int vectorPlacement;
};
#endif /* Modifier_hpp */
| true |
ac2ea79071c23cb908c77b19810e5c57d7faa985 | C++ | diego3/ludum-game-engine | /LudumGameEngine/Src/Components/TransformComponent.h | UTF-8 | 965 | 2.859375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <SDL.h>
#include "../../Libs/glm/glm/ext/vector_float2.hpp"
#include "../Core/Component.h"
#include "../Core/Game.h"
class TransformComponent : public Component
{
public:
glm::vec2 position;
glm::vec2 velocity;
int width;
int height;
int scale;
SDL_Rect box;
bool showBox;
TransformComponent(int posX, int posY, int velX, int velY, int w, int h, int s)
{
position = glm::vec2(posX, posY);
velocity = glm::vec2(velX, velY);
width = w;
height = h;
scale = s;
box = {posX, posY, w*s, h*s};
showBox = false;
}
void Initialize() override
{
}
void Render() override {
if (showBox) {
SDL_SetRenderDrawColor(Game::renderer, 0, 255, 0, 255);
SDL_RenderDrawRect(Game::renderer, &box);
}
}
void Update(float deltaTime) override
{
position += velocity * deltaTime;
if (showBox) {
box.x = (int)position.x - Game::camera.x;
box.y = (int)position.y - Game::camera.y;
}
};
}; | true |
a8c60e4faeab0c25905bfa856e8e0e3db7d7ba7e | C++ | Ziyadnaseem/Hackerblocks-practice | /BFS - Shortest Path1.cpp | UTF-8 | 1,326 | 3.015625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Graph {
private:
map<long long int, list<long long int>> adjList;
public:
Graph(long long int n)
{
for (long long int i = 1; i <= n; i++)
{
adjList[i].push_back(0);
}
}
void addEdge(long long int u, long long int v)
{
adjList[u].push_back(v);
adjList[v].push_back(u);
}
void bfsShortestPath(long long int src, long long int n, long long int m)
{
queue<long long int>q;
map<long long int, long long int>distance;
map<long long int, bool>visited;
for (long long int i = 1; i <= n; i++)
{
distance[i] = -1;
}
q.push(src);
distance[src] = 0;
while (q.empty() == false)
{
long long int temp = q.front();
q.pop();
for (auto element : adjList[temp])
{
if (distance[element]==-1)
{
distance[element] = distance[temp] + 1;
q.push(element);
}
}
}
for(long long int i=1;i<=n;i++){
if(i!=src){
cout<<(distance[i]==-1?(-1):(distance[i]*6))<<" ";
}
}
cout<<endl;
}
};
int main()
{
long long int q;
cin >> q;
while (q--)
{
long long int n, m;
cin >> n >> m;
Graph g(n);
for (long long int i = 0; i < m; i++)
{
long long int u, v;
cin >> u >> v;
g.addEdge(u, v);
}
long long int src;
cin >> src;
g.bfsShortestPath(src, n, m);
}
return 0;
}
| true |
ca8e199488950b84480618eb1afa0ec8ddad6c1e | C++ | kanukam/School-Projects | /CS202-COMPUTER-PROGRAMMING-II-master/proj9/Node.h | UTF-8 | 871 | 3.453125 | 3 | [] | no_license | #ifndef NODE_H_
#define NODE_H_
#include "DataType.h"
class Node{
friend class NodeQueue; //allows direct accessing of link and data from class NodeList
public:
Node() :
m_next( NULL )
{
}
Node(const DataType & data, Node * next = NULL) :
m_next( next ),
m_data( data )
{
}
Node(const Node & other) :
m_next( other.m_next ),
m_data( other.m_data )
{
}
DataType & data(){ //gets non-const reference, can be used to modify value of underlying data
//return const_cast<DataType &>(static_cast<const Node &>(*this).getData()); //an alternative implementation, just for studying reference
return m_data;
}
const DataType & data() const{ //gets const reference, can be used to access value of underlying data
return m_data;
}
private:
Node * m_next;
DataType m_data;
};
#endif //NODE_H_
| true |
9376c1a52f4b4d0a28f0f6dae422f3929cdb1cd5 | C++ | blizmax/wage-engine | /engine/memory/reference.h | UTF-8 | 1,756 | 2.921875 | 3 | [] | no_license | #pragma once
#include <cstddef>
#include <assert.h>
namespace wage { namespace memory {
template <typename T, typename IndexType = uint32_t>
class Reference {
public:
class Source {
public:
virtual bool valid(Reference ref) = 0;
virtual void destroy(Reference ref) = 0;
virtual T* get(Reference ref) = 0;
};
static const IndexType OutOfBounds = static_cast<IndexType>(-1);
Reference() : Reference(nullptr, OutOfBounds, 0) {
}
Reference(Source* source, IndexType index, size_t version) : _source(source), _index(index), _version(version) {
}
virtual ~Reference() {}
inline bool valid() {
return _source && _source->valid(*this);
}
virtual void destroy() {
_source->destroy(*this);
};
virtual T* get() {
return _source->get(*this);
}
operator bool() {
return valid();
}
T* operator->() {
assert(valid());
return get();
}
const T* operator->() const {
return const_cast<Reference*>(this)->operator->();
}
T& operator*() {
assert(valid());
return *get();
}
const T& operator*() const {
return const_cast<Reference<T, IndexType>*>(this)->operator*();
}
bool operator==(const Reference& other) const {
return _source == other._source && _index == other._index;
}
bool operator!=(const Reference& other) const {
return !operator==(other);
}
inline const Source* source() const {
return _source;
}
inline IndexType index() const {
return _index;
}
inline size_t version() const {
return _version;
}
private:
Source* _source;
IndexType _index;
size_t _version;
};
} } | true |
31a8aab3fb92431b5c8b106a917c45d9353f313d | C++ | DongHaiYuan/Database-System-Implementation | /Phase3/Source/RelOp.cc | UTF-8 | 23,812 | 2.734375 | 3 | [] | no_license | #include "RelOp.h"
// SelectPipe
typedef struct params{
Pipe *inPipe;
Pipe *outPipe;
CNF *selOp;
DBFile *inFile;
Record *literal;
int *keepMe;
int numAttsInput;
int numAttsOutput;
} params;
void *SelectPipe::selectPipe(void *arg) {
params *sp = (params *) arg;
cout<<"created thread"<<endl;
Record *tmpRecord = new Record();
ComparisonEngine cmp;
while(sp->inPipe->Remove(tmpRecord)) {
if(cmp.Compare(tmpRecord, sp->literal, sp->selOp)) { // compares record with CNF, if true puts it into outPipe
sp->outPipe->Insert(tmpRecord);
}
}
delete tmpRecord;
sp->outPipe->ShutDown();
}
void SelectPipe::Run (Pipe &inPipe, Pipe &outPipe, CNF &selOp, Record &literal){
cout<<"called run"<<endl;
params* sp = new params;
sp->inPipe = &inPipe;
sp->outPipe = &outPipe;
sp->selOp = &selOp;
sp->literal = &literal;
pthread_create(&thread, NULL, selectPipe,(void*) sp);
}
void SelectPipe::WaitUntilDone () {
pthread_join (thread, NULL);
}
void SelectPipe::Use_n_Pages (int runlen) {
this->nPages = runlen;
}
// SelectFile
void *SelectFile::selectFile(void *arg) {
params *sp = (params *) arg;
Record *tmpRecord = new Record();
//cout<<"call to sf"<<endl;
ComparisonEngine cmp;
//cout<<sp->inFile<<endl;//addr
sp->selOp->Print();
while(sp->inFile->GetNext(*tmpRecord)) {
//cout<<"read"<<endl;
if(cmp.Compare(tmpRecord, sp->literal, sp->selOp)) { // compares record with CNF, if true puts it into outPipe
cout<<"found"<<endl;
sp->outPipe->Insert(tmpRecord);
}
}
delete tmpRecord;
sp->outPipe->ShutDown();
}
void SelectFile::Run (DBFile &inFile, Pipe &outPipe, CNF &selOp, Record &literal) {
cout<<"called run"<<endl;
params* sp = new params;
sp->inFile = &inFile;
sp->outPipe = &outPipe;
sp->selOp = &selOp;
sp->literal = &literal;
pthread_create(&thread, NULL, selectFile,(void*) sp);
}
void SelectFile::WaitUntilDone () {
pthread_join (thread, NULL);
}
void SelectFile::Use_n_Pages (int runlen) {
this->nPages = runlen;
}
// Project
void *Project::project(void *arg) {
params *sp = (params *) arg;
Record *tmpRcd = new Record;
while(sp->inPipe->Remove(tmpRcd)) {
tmpRcd->Project(sp->keepMe, sp->numAttsOutput, sp->numAttsInput);
sp->outPipe->Insert(tmpRcd);
}
sp->outPipe->ShutDown();
delete tmpRcd;
//return;
}
void Project::Run (Pipe &inPipe, Pipe &outPipe, int *keepMe,
int numAttsInput, int numAttsOutput) {
params* sp = new params;
sp->inPipe = &inPipe;
sp->outPipe = &outPipe;
sp->keepMe = keepMe;
sp->numAttsInput = numAttsInput;
sp->numAttsOutput = numAttsOutput;
pthread_create(&thread, NULL, project, sp);
}
void Project::WaitUntilDone () {
pthread_join (thread, NULL);
}
void Project::Use_n_Pages (int n) {
this->nPages = n;
}
// Duplicate Removal
void *DuplicateRemoval::duprem(void *arg){
DuplicateRemoval *dr = (DuplicateRemoval *) arg;
dr->DoDuplicateRemoval();
return NULL;
}
void DuplicateRemoval::DoDuplicateRemoval(){
OrderMaker *om = new OrderMaker(this->mySchema);
cout <<"duplicate removal on ordermaker: "; om->Print();
// Attribute *atts = this->mySchema->GetAtts();
// loop through all of the attributes, and list as it is
// cout <<"distince on ";
// om->Print(); cout <<endl;
if(!om)
cerr <<"Can not allocate ordermaker!"<<endl;
Pipe sortPipe(1000);
// int runlen = 50;//temp...
BigQ *bigQ = new BigQ(*(this->inPipe), sortPipe, *om, nPages);
ComparisonEngine cmp;
Record *tmp = new Record();
Record *chk = new Record();
if(sortPipe.Remove(tmp)) {
//insert the first one
bool more = true;
while(more) {
more = false;
Record *copyMe = new Record();
copyMe->Copy(tmp);
this->outPipe->Insert(copyMe);
while(sortPipe.Remove(chk)) {
if(cmp.Compare(tmp, chk, om) != 0) { //equal
tmp->Copy(chk);
more = true;
break;
}
}
}
}
// sortPipe.ShutDown();
this->outPipe->ShutDown();
}
void DuplicateRemoval::Run(Pipe &inPipe, Pipe &outPipe, Schema &mySchema) {
this->inPipe = &inPipe;
this->outPipe = &outPipe;
this->mySchema = &mySchema;
pthread_create(&thread,NULL,duprem,this);
}
void DuplicateRemoval::WaitUntilDone () {
pthread_join(thread,NULL);
}
void DuplicateRemoval::Use_n_Pages (int n) {
this->nPages = n;
}
/*class Join : public RelationalOp {
public:
void Run (Pipe &inPipeL, Pipe &inPipeR, Pipe &outPipe, CNF &selOp, Record &literal) { }
void WaitUntilDone () { }
void Use_n_Pages (int n) { }
};*/
void Join::Run (Pipe &inPipeL, Pipe &inPipeR, Pipe &outPipe, CNF &selOp, Record &literal) {
this->inPipeL = &inPipeL;
this->inPipeR = &inPipeR;
this->outPipe = &outPipe;
this->selOp = &selOp;
this->literal = &literal;
pthread_create(&thread,NULL,jswpn,this);
}
void* Join::jswpn(void* arg){
Join *j = (Join *) arg;
j->join();
}
void Join::join(){
/*OrderMaker *omL = new OrderMaker();
OrderMaker *omR = new OrderMaker();
if(selOp->GetSortOrders(*omL,*omR)==0){}
else{
Pipe *OL = new Pipe(100);
Pipe *OR = new Pipe(100);
BigQ L = BigQ (*inPipeL, *OL, *omL, nPages);
BigQ R = BigQ (*inPipeR, *OR, *omR, nPages);
Record *RL = new Record();
Record *RR = new Record();
int resultL = OL->Remove(RL);
int resultR = OR->Remove(RR);
while(resultL&&resultR){
}
}
*/
Pipe *LO = new Pipe(100);
Pipe *RO = new Pipe(100);
OrderMaker *omL = new OrderMaker();
OrderMaker *omR = new OrderMaker();
ComparisonEngine compEng;
int sortMergeFlag = selOp->GetSortOrders(*omL, *omR);
// if sort merge flag != 0 perform SORT-MERGE JOIN
if (sortMergeFlag != 0) {
// sort left pipe
BigQ L(*inPipeL, *LO, *omL, this->nPages);
// sort right pipe
BigQ R(*inPipeR, *RO, *omR, this->nPages);
Record RL;
Record *RR = new Record();
vector<Record*> mergeVector; // to store records with same value of join attribute
int isLeftPipeEmpty = LO->Remove(&RL);
int isRightPipeEmpty = RO->Remove(RR);
int numLeftAttrs = RL.getNumAttrs();
int numRightAttrs = RR->getNumAttrs();
// array used as input to merge record function
int attrsToKeep[numLeftAttrs + numRightAttrs];
int k = 0;
for (int i = 0; i < numLeftAttrs; i++) {
attrsToKeep[k++] = i;
}
for (int i = 0; i < numRightAttrs; i++) {
attrsToKeep[k++] = i;
}
Record mergedRecord;
int mergedRecCount = 0;
// get records from left output pipe and right output pipe
while (isLeftPipeEmpty != 0 && isRightPipeEmpty != 0) {
int orderMakerAnswer = compEng.Compare(&RL, omL, RR, omR);
// if left and right record are equal on join attributes
if (orderMakerAnswer == 0) {
for (int i = 0; i < mergeVector.size(); i++) {
delete mergeVector[i];
mergeVector[i] = NULL;
}
mergeVector.clear();
// get all matching records (on join attr) in vector
while (orderMakerAnswer == 0 && isRightPipeEmpty != 0) {
mergeVector.push_back(RR);
RR = new Record();
isRightPipeEmpty = RO->Remove(RR);
if (isRightPipeEmpty != 0) {
orderMakerAnswer = compEng.Compare(&RL, omL, RR, omR);
}
}
// compare left Rec with first from vector
orderMakerAnswer = compEng.Compare(&RL, omL, mergeVector[0], omR);
// compare left Rec with all records from vector
while (orderMakerAnswer == 0 && isLeftPipeEmpty != 0) {
for (int i = 0; i < mergeVector.size(); i++) {
mergedRecord.MergeRecords(&RL, mergeVector[i], numLeftAttrs, numRightAttrs, attrsToKeep, numLeftAttrs + numRightAttrs, numLeftAttrs);
outPipe->Insert(&mergedRecord);
mergedRecCount++;
}
//Take next Record from left pipe;
isLeftPipeEmpty = LO->Remove(&RL);
orderMakerAnswer = compEng.Compare(&RL, omL, mergeVector[0], omR);
}
}
// take next from left pipe if it is smaller , else take next from right pipe
else if (orderMakerAnswer < 0) {
isLeftPipeEmpty = LO->Remove(&RL);
}
else {
isRightPipeEmpty = RO->Remove(RR);
}
}
cout << "Total Records Merged :: " << mergedRecCount << endl;
}
// BLOCK NESTED LOOP JOIN - if no suitable order maker found
else {
int mergedRecCount = 0;
char fileName[200];
int x = rand();
sprintf(fileName, "rightRelation_bnj.tmp%d", x);
DBFile rightRelationFIle;
Record RR;
rightRelationFIle.Create(fileName, heap, NULL);
//Add entire right relation to a temporary dbFile
while (inPipeR->Remove(&RR)) {
rightRelationFIle.Add(RR);
}
rightRelationFIle.Close();
vector<Record*> leftRelationVector;
int numPagesAllocatedForLeft = 0;
Page pageForLeftRecords;
Record leftRecord;
Record* rec = new Record();
// Remove records from left pipe in units of block ( block is n - 1 pages)
int isLeftRecordPresent = inPipeL->Remove(&leftRecord);
bool isPipeEnded = false;
int isRecordAdded;
while (isLeftRecordPresent || isPipeEnded) {
// Start reading left Record into a page
if (isLeftRecordPresent) {
isRecordAdded = pageForLeftRecords.Append(&leftRecord);
}
// when page is full or pipe is empty
if (isRecordAdded == 0 || isPipeEnded) {
// increment number of pages used
numPagesAllocatedForLeft++;
// flush records of the page into vector
while (pageForLeftRecords.GetFirst(rec)) {
leftRelationVector.push_back(rec);
rec = new Record();
}
//For block nested loop join, n-1 pages of left relation are joined with each record of right relation
// start reading right relation from file when n - 1 buffer pages are full OR pipe is empty
if (numPagesAllocatedForLeft == this->nPages - 1 || isPipeEnded) {
rightRelationFIle.Open(fileName);
rightRelationFIle.MoveFirst();
Record rightRec;
int isRightRecPresent = rightRelationFIle.GetNext(rightRec);
Record mergedRecord;
int numLeftAttrs = leftRelationVector[0]->getNumAttrs();
int numRightAttrs = rightRec.getNumAttrs();
int attrsToKeep[numLeftAttrs + numRightAttrs];
int k = 0;
for (int i = 0; i < numLeftAttrs; i++) {
attrsToKeep[k++] = i;
}
for (int i = 0; i < numRightAttrs; i++) {
attrsToKeep[k++] = i;
}
// while right relation file has next record
while (isRightRecPresent != 0) {
for (int i = 0; i < leftRelationVector.size(); i++) {
int isAccepted = compEng.Compare(leftRelationVector[i], &rightRec, literal, selOp);
// merge records when the cnf is accepted
if (isAccepted != 0) {
mergedRecord.MergeRecords(leftRelationVector[i], &rightRec, numLeftAttrs, numRightAttrs, attrsToKeep, numLeftAttrs + numRightAttrs, numLeftAttrs);
outPipe->Insert(&mergedRecord);
mergedRecCount++;
}
}
isRightRecPresent = rightRelationFIle.GetNext(rightRec);
}
rightRelationFIle.Close();
// flush the vector
numPagesAllocatedForLeft = 0;
for (int i = 0; i < leftRelationVector.size(); i++) {
delete leftRelationVector[i];
leftRelationVector[i] = NULL;
}
leftRelationVector.clear();
// exit loop is pipe is empty
if (isPipeEnded)
break;
}
}
isLeftRecordPresent = inPipeL->Remove(&leftRecord);
if (isLeftRecordPresent == 0) {
isPipeEnded = true;
}
}
cout << "Total Records Merged :: " << mergedRecCount << endl;
remove(fileName);
}
// shut down output pipe after join is complete
outPipe->ShutDown();
}
void Join::WaitUntilDone () {
pthread_join(thread,NULL);
}
void Join::Use_n_Pages (int n) {
this->nPages = n;
}
void Sum::doSum() {
cout << "Starting Summation" << endl;
//struct RunParams* params = (struct RunParams*) parameters;
int intSum = 0;
double doubleSum = 0.0;
int intAttrVal = 0;
double doubleAttrVal = 0.0;
Record rec;
Function *function = function;
Type type;
while (inPipe->Remove(&rec)) {
// get value and type of the particular attribute to be summed
type = function->Apply(rec, intAttrVal, doubleAttrVal);
if (type == Int) {
intSum += intAttrVal;
} else {
doubleSum += doubleAttrVal;
}
}
ostringstream result;
string resultSum;
Record resultRec;
// create output record
if (type == Int) {
result << intSum;
resultSum = result.str();
resultSum.append("|");
Attribute IA = {"int", Int};
Schema out_sch("out_sch", 1, &IA);
resultRec.ComposeRecord(&out_sch, resultSum.c_str());
} else {
result << doubleSum;
resultSum = result.str();
resultSum.append("|");
Attribute DA = {"double", Double};
Schema out_sch("out_sch", 1, &DA);
resultRec.ComposeRecord(&out_sch, resultSum.c_str());
}
outPipe->Insert(&resultRec);
outPipe->ShutDown();
}
void* Sum::sspwn(void* arg){
Sum *s = (Sum *) arg;
s->doSum();
}
void Sum::Run(Pipe &inPipe, Pipe &outPipe, Function &computeMe) {
cout << "In Summation Run" << endl;
//struct RunParams* params = (RunParams*) malloc(sizeof (RunParams));
this->inPipe = &inPipe;
this->outPipe = &outPipe;
this->function = &computeMe;
pthread_create(&thread, NULL, sspwn, this);
}
void Sum::WaitUntilDone() {
pthread_join(thread, NULL);
cout << "\n Summation Complete" << endl;
}
void Sum::Use_n_Pages(int n) {
cout << "Setting run length in use n pages : " << n << endl;
this->nPages = n;
}
void GroupBy::doGroupBy() {
/*
cout << "Starting group by" << endl;
//struct RunParams* params = (struct RunParams*) parameters;
Attribute DA = {"double", Double};
Schema out_sch_double("out_sch", 1, &DA);
Attribute IA = {"int", Int};
Schema out_sch_int("out_sch", 1, &IA);
vector<int> groupByOrderAttrs;
vector<Type> groupByOrderTypes;
params->groupbyOrder->GetOrderMakerAttrs(&groupByOrderAttrs, &groupByOrderTypes);
int *projectAttrsToKeep = &groupByOrderAttrs[0];
int numGroupByAttrs = groupByOrderAttrs.size();
int mergeAttrsToKeep[1 + numGroupByAttrs];
mergeAttrsToKeep[0] = 0;
for (int i = 1; i <= numGroupByAttrs; i++) {
mergeAttrsToKeep[i] = i - 1;
}
Pipe *bigqOutPipe = new Pipe(100);
BigQ bigQ(*params->inputPipe, *bigqOutPipe, *params->groupbyOrder, params->runLength);
ComparisonEngine comparator;
int intAttrVal;
double doubleAttrVal;
Type type;
int intSum = 0;
double doubleSum = 0;
Record currRec, nextRec;
int currRecPresent = bigqOutPipe->Remove(&currRec);
int nextRecPresent = currRecPresent;
nextRec.Copy(&currRec);
int numCurrRecAttrs = currRec.getNumAttrs();
while (nextRecPresent) {
int orderMakerAnswer = comparator.Compare(&currRec, &nextRec, params->groupbyOrder);
// Perform summation until there is a mismatch
if (orderMakerAnswer == 0) {
type = params->function->Apply(nextRec, intAttrVal, doubleAttrVal);
if (type == Int) {
intSum += intAttrVal;
} else {
doubleSum += doubleAttrVal;
}
nextRecPresent = bigqOutPipe->Remove(&nextRec);
}
// create output tuple when there is a mismatch
else {
ostringstream result;
string resultSum;
Record groupSumRec;
// create output record
if (type == Int) {
result << intSum;
resultSum = result.str();
resultSum.append("|");
groupSumRec.ComposeRecord(&out_sch_int, resultSum.c_str());
} else {
result << doubleSum;
resultSum = result.str();
resultSum.append("|");
groupSumRec.ComposeRecord(&out_sch_double, resultSum.c_str());
}
// Get a record contaning only group by attributes
currRec.Project(projectAttrsToKeep, numGroupByAttrs, numCurrRecAttrs);
// merge the above record with the group Sum Record to get result record
Record resultRec;
resultRec.MergeRecords(&groupSumRec, &currRec, 1, numGroupByAttrs, mergeAttrsToKeep, 1 + numGroupByAttrs, 1);
params->outputPipe->Insert(&resultRec);
currRec.Copy(&nextRec);
intSum = 0;
doubleSum = 0;
}
}
ostringstream result;
string resultSum;
Record groupSumRec;
if(type == Int){
result << intSum;
resultSum = result.str();
resultSum.append("|");
groupSumRec.ComposeRecord(&out_sch_int, resultSum.c_str());
}
else{
result << doubleSum;
resultSum = result.str();
resultSum.append("|");
groupSumRec.ComposeRecord(&out_sch_double, resultSum.c_str());
}
// Get a record containing only group by attributes
currRec.Project(projectAttrsToKeep, numGroupByAttrs, numCurrRecAttrs);
// merge the above record with the group Sum Record to get result record
Record resultRec;
resultRec.MergeRecords(&groupSumRec, &currRec, 1, numGroupByAttrs, mergeAttrsToKeep, 1 + numGroupByAttrs, 1);
params->outputPipe->Insert(&resultRec);
params->outputPipe->ShutDown();*/
}
void* GroupBy::gspwn(void* arg){
GroupBy *g = (GroupBy *) arg;
g->doGroupBy();
}
void GroupBy::Run(Pipe &inPipe, Pipe &outPipe, OrderMaker &groupAtts, Function &computeMe) {
cout << "In Group By Run" << endl;
this->inPipe = &inPipe;
this->outPipe = &outPipe;
this->groupbyOrder = &groupAtts;
this->function = &computeMe;
//this->nPages = runLength;
pthread_create(&thread, NULL, gspwn, this);
}
void GroupBy::WaitUntilDone() {
pthread_join(thread, NULL);
cout << "\n Group By Complete" << endl;
}
void GroupBy::Use_n_Pages(int n) {
cout << "Setting run length in use n pages : " << n << endl;
this->nPages = n;
}
void WriteOut::Run (Pipe &inPipe, FILE *outFile, Schema &mySchema) {}
void WriteOut::WaitUntilDone (){}
void WriteOut::Use_n_Pages (int n){}
| true |
492b7404f742c87ca7db98a2a4a7855f54ebd95e | C++ | Blue12108Rabit/CPPhomework | /Chapter6/6-27.cpp | GB18030 | 751 | 3.65625 | 4 | [] | no_license | #pragma warning(disable : 4996)
#include<iostream>
#include<cstring>
using namespace std;
class employee {
private:
char name[50];
char streetAdd[50];
char city[50];
char postcode[50];
public:
employee(const char* n, const char* s, const char* c, const char* p);
void setname(const char *n);
void display();
};
void employee::setname(const char *n) {
strcpy(name, n);
}
employee::employee(const char* n, const char* s, const char* c, const char* p) {
strcpy(name, n);
strcpy(streetAdd,s);
strcpy(city,c);
strcpy(postcode,p);
}
void employee::display() {
cout << name << " " << streetAdd << " " << city << " " << postcode << endl;
}
int main() {
employee a1("","","Ϸ","230000");
a1.setname("");
a1.display();
} | true |
7e5ef54bda7c582060df93259942a36b955a4fda | C++ | acc-cosc-1337-fall-2018/acc-cosc-1337-fall-2018-ayla00 | /assignments/05-classes-test/invoice_detail_test.cpp | UTF-8 | 1,150 | 2.5625 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "invoice_detail.h"
#include "invoice.h"
#include "invoice_utility.h"
TEST_CASE("test get_extended")
{
InvoiceDetail invoice(10, 10);
REQUIRE(invoice.get_extended_cost() == 100);
}
TEST_CASE("Test")
{
Invoice invoice;
invoice.add_invoice_detail(InvoiceDetail(10, 10);
invoice.add_invoice_detail(InvoiceDetail(5, 5);
invoice.add_invoice_detail(InvoiceDetail(100, 2);
REQUIRE(invoice.get_total() == 325);
}
TEST_CASE("test inv operator overloading")
{
Invoice invoice;
invoice.add_invoice_detail(InvoiceDetail(10, 10);
invoice.add_invoice_detail(InvoiceDetail(5, 5);
invoice.add_invoice_detail(InvoiceDetail(100, 2);
Invoice invoice1;
invoice1.add_invoice_detail(InvoiceDetail(100, 2);
Invoice result = invoice + invoice1;
REQUIRE(result.get_total() == 525);
}
TEST_CASE("test invoice utility")
{
InvoiceUtility invu(25);
invu.add_invoice_detail(InvoiceDetail(100, 1));
REQUIRE(inv.get_total() == 125);
}
TEST_CASE("test invoice_progress get total")
{
InvoiceProgress invp(250);
invp.add_invoice_detail(InvoiceDetail(100, 1));
REQUIRE(inv.get_total() == 150);
} | true |
22538115dc202cf7c378d8ca621b8e0899412690 | C++ | vivekpatel8/code_cpp | /lenth of longest common subsequence.cpp | UTF-8 | 1,121 | 3.046875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int lenthofLCS(string a, string b){
int lena = a.length();
int lenb = b.length();
int grid[100][100] = {0};
for(int i = 1;i<=lena;i++){
for(int j = 1;j<=lenb;j++){
int q = 0;
if(a[i-1] == b[j-1]){
q = 1 + grid[i-1][j-1];
}
else{
q = max(grid[i][j-1] , grid[i-1][j]);
}
grid[i][j] = q;
}
}
cout<<" ";
for(int j = 0;j<lenb;j++)cout<<b[j]<<" ";
cout<<endl;
for(int i = 1;i<=lena;i++){
cout<<a[i-1]<<" ";
for(int j = 1;j<=lenb;j++){
cout<<grid[i][j]<<" ";
}
cout<<endl;
}
return grid[lena][lenb];
}
// using recursion
int f(string a, string b, int lena, int lenb, int i, int j){
if(i >= lena || j >= lenb)return 0;
if(a[i] == b[j]){
return 1 + f(a, b, lena, lenb, i+1, j+1);
}
else{
return max(f(a, b, lena, lenb, i + 1, j), f(a, b, lena, lenb, i, j+1));
}
}
int main(){
string a, b;
cin>>a>>b;
cout<<endl;
//cout<<lengthofLCS(a, b);
int lena = a.length();
int lenb = b.length();
cout<<f(a, b, lena, lenb, 0, 0);
}
| true |
0edb6d62c91f8a9f5854b4a462e86fd01518d511 | C++ | wuli2496/material | /学习资料/竞赛例题解(三)光盘/第五章-综合题例题分析/5.10-最短绳长/permetr.cpp | UTF-8 | 3,017 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<assert.h>
const int MAXN = 100;
const double PI2 = acos(-1.0) * 2.0;
const double EPS = 1e-5;
struct REC{
double x, y, r;
}list[MAXN];
int ptr[2*MAXN];
char flag[MAXN][MAXN];
inline double arctan(const double& dy, const double& dx)
{
double t = atan2(dy, dx);
if (t<0){
t+=PI2;
}
return t;
}
void normalize(double &ang)
{
if (ang<0){
ang+=PI2;
} else if (ang>PI2){
ang-=PI2;
}
assert(ang>=0.0 && ang<=PI2);
}
double distance(REC& a, REC& b)
{
return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
}
double calc(REC& a, REC& b, REC& c)
{
double ret=0.0;
double ang_in, ang_out;
double d, ang, deltaR, l, theta;
ang = arctan(a.y - b.y, a.x - b.x);
d = distance(a, b);
deltaR = a.r - b.r;
assert(d>1e-8);
theta = asin(deltaR/d);
ang_in = ang + theta + PI2/4.0;
// normalize(ang_in);
ang = arctan(c.y - b.y, c.x - b.x);
d = distance(b, c);
deltaR = c.r - b.r;
theta = asin(deltaR/d);
ang_out = ang - theta - PI2/4.0;
if (ang_out<ang_in){
ang_out+=PI2;
}
assert(ang_out - ang_in < PI2+EPS); //impossible wrap around
ret = b.r * (ang_out - ang_in);
l = sqrt( d*d - deltaR*deltaR );
return ret+l;
}
int main()
{
freopen("permetr.in", "r", stdin);
freopen("permetr.out", "w", stdout);
int N, i;
scanf("%d", &N);
// locate the starting point
double ymin=1e50, xmin=1e50;
int ori=-1;
for (i=0; i<N; i++){
scanf("%lf %lf %lf", &list[i].x, &list[i].y, &list[i].r);
if (list[i].y-list[i].r < ymin){
ymin = list[i].y - list[i].r;
xmin = list[i].x;
ori = i;
} else if (list[i].y - list[i].r < ymin+EPS &&
list[i].x < xmin){
xmin = list[i].x;
ori = i;
}
}
int p;
double last = -1.0;
memset(flag, 0, sizeof(flag));
ptr[0] = ori;
// printf("%.3lf %.3lf %.3lf\n", list[ori].x, list[ori].y, list[ori].r);
for (p = 1; ; p++){
int sel = -1;
double amin = 1.0e10, len = -1.0;
double d, deltaR, ang, theta, l;
//printf("%d\n", ptr[p-1]);
for (i=0; i<N; i++){
if (ptr[p-1]==i) continue;
ang = arctan(list[i].y - list[ptr[p-1]].y, list[i].x - list[ptr[p-1]].x);
d = distance(list[i], list[ptr[p-1]]);
deltaR = list[i].r - list[ptr[p-1]].r;
assert(d>1e-8);
if (d<1e-8){
printf("aoao\n");
}
theta = asin(deltaR/d);
ang -= theta;
normalize(ang);
l = sqrt( d*d - deltaR*deltaR );
if (ang<last){
ang += PI2;
}
if (ang < amin - EPS){
amin = ang;
len = l;
sel = i;
} else if(ang < amin+EPS){
if (l > len){
len = l;
sel = i;
}
}
}
assert(sel >= 0);
last = amin;
// printf("%.3lf %.3lf %.3lf\n", list[sel].x, list[sel].y, list[sel].r);
ptr[p] = sel;
if (flag[ptr[p-1]][ptr[p]]){
break;
}
flag[ptr[p-1]][ptr[p]] = 1;
assert(p<2*MAXN-1);///
}
N = p-1;
assert(N>1);
double acc;
acc = calc(list[ptr[N-1]], list[ptr[0]], list[ptr[1]]);
for (i=1; i<N; i++){
acc += calc(list[ptr[i-1]], list[ptr[i]], list[ptr[i+1]]);
}
printf("%.4e\n", acc);
return 0;
}
| true |
b9860cd6eaa398e4934d9eb134dbcc492351d200 | C++ | zy15662UNUK/mooc_cpp | /section8/include/Observer.h | UTF-8 | 324 | 2.828125 | 3 | [] | no_license | #ifndef OBSEVER_H_1
#define OBSEVER_H_1
class Observer
{
private:
/* data */
public:
// 单纯为了编译通过加上大括号
Observer(/* args */) {;};
virtual ~Observer(){;};
// 当被观察对象发生变化时候,通知被观察者调用这个方法
virtual void update(void * pArg) = 0;
};
#endif | true |
bf47c6f89ba5997e5e7fc1bb34bc69cb480789be | C++ | jdavidberger/stencet | /src/tags/VerbatimTag.cc | UTF-8 | 1,940 | 2.703125 | 3 | [
"MIT"
] | permissive | /* Copyright (C) 2012-2013 Justin Berger
The full license is available in the LICENSE file at the root of this project and is also available at http://opensource.org/licenses/MIT. */
#include <stencet/tags/VerbatimTag.h>
#include <stencet/parser.h>
#include <string.h>
namespace stencet {
void VerbatimTag::render(std::ostream& out, ViewContext& vm) const {
out << body;
}
static inline void emit_token(Token t, char c, std::string& b){
b += c;
switch(t){
case OpenVar: b += '{'; break;
case OpenTag: b += '%'; break;
case CloseVar:
case CloseTag: b += '}'; break;
default: break;
}
}
VerbatimTag::VerbatimTag(std::istream& stream, const std::string& content) {
std::string cmdName, blockName;
msscanf(content, "${cmdName} ${blockName}", cmdName, blockName);
assert(cmdName.size());
cmdName = "end" + cmdName;
bool done = false;
char c;
Token token = Val;
do {
token = nextToken(stream, c);
if( OpenTag == token ) {
std::string temp;
temp += "{%";
while(stream.peek() == ' ') temp += (char)stream.get();
bool cmdNameMatch = true;
for(size_t i = 0;i < cmdName.size();i++){
if( stream.peek() != cmdName[i] ) {
cmdNameMatch = false;
break;
}
temp += stream.get();
}
while(stream.peek() == ' ') temp += (char)stream.get();
bool blockNameMatch = true;
for(size_t i = 0;i < blockName.size();i++){
if( stream.peek() != blockName[i] ) {
blockNameMatch = false;
break;
}
temp += stream.get();
}
while(stream.peek() == ' ') temp += (char)stream.get();
bool closeTag =
'%' == (char)stream.get() &&
'}' == (char)stream.peek();
done = blockNameMatch && cmdNameMatch && closeTag;
if(!done) {
body += temp;
stream.unget();
} else {
stream.get(); // Eat the '}'
}
} else if (token != eof) {
emit_token(token, c, body);
}
} while (token != eof);
}
}
| true |
136ad2e8ab8611ab41679edfb6dd06bdfda10bad | C++ | BookmanHan/CalGraph | /Logging.hpp | UTF-8 | 3,437 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Import.hpp"
inline string time_namer()
{
const time_t log_time = time(nullptr);
struct tm* current_time = localtime(&log_time);
stringstream ss;
ss << report_path;
ss << 1900 + current_time->tm_year << ".";
ss << setfill('0') << setw(2) << current_time->tm_mon + 1 << ".";
ss << setfill('0') << setw(2) << current_time->tm_mday << "_";
ss << setfill('0') << setw(2) << current_time->tm_hour << ".";
ss << setfill('0') << setw(2) << current_time->tm_min << ".";
ss << setfill('0') << setw(2) << current_time->tm_sec;
return ss.str();
}
class Logging
{
protected:
ofstream fout;
public:
Logging(const string& base_dir = report_path)
{
fout.open((time_namer() + ".txt").c_str());
const time_t log_time = time(nullptr);
struct tm* current_time = localtime(&log_time);
stringstream ss;
ss << 1900 + current_time->tm_year << "-";
ss << setfill('0') << setw(2) << current_time->tm_mon + 1 << "-";
ss << setfill('0') << setw(2) << current_time->tm_mday << " ";
ss << setfill('0') << setw(2) << current_time->tm_hour << ".";
ss << setfill('0') << setw(2) << current_time->tm_min << ".";
ss << setfill('0') << setw(2) << current_time->tm_sec;
fout << '[' << ss.str() << ']' << '\t' << "Ready.";;
cout << '[' << ss.str() << ']' << '\t' << "Ready.";;
}
Logging& record()
{
const time_t log_time = time(nullptr);
struct tm* current_time = localtime(&log_time);
stringstream ss;
ss << 1900 + current_time->tm_year << "-";
ss << setfill('0') << setw(2) << current_time->tm_mon + 1 << "-";
ss << setfill('0') << setw(2) << current_time->tm_mday << " ";
ss << setfill('0') << setw(2) << current_time->tm_hour << ".";
ss << setfill('0') << setw(2) << current_time->tm_min << ".";
ss << setfill('0') << setw(2) << current_time->tm_sec;
fout << endl;
fout << '[' << ss.str() << ']' << '\t';
cout << endl;
cout << '[' << ss.str() << ']' << '\t';
return *this;
}
Logging& direct_record()
{
const time_t log_time = time(nullptr);
struct tm* current_time = localtime(&log_time);
stringstream ss;
ss << 1900 + current_time->tm_year << "-";
ss << setfill('0') << setw(2) << current_time->tm_mon + 1 << "-";
ss << setfill('0') << setw(2) << current_time->tm_mday << " ";
ss << setfill('0') << setw(2) << current_time->tm_hour << ".";
ss << setfill('0') << setw(2) << current_time->tm_min << ".";
ss << setfill('0') << setw(2) << current_time->tm_sec;
fout << endl;
fout << '[' << ss.str() << ']' << '\t';
return *this;
}
void flush()
{
fout.flush();
cout.flush();
}
void redirect(const string& str_suffix = "")
{
fout.close();
fout.open((time_namer() + str_suffix + ".txt").c_str());
const time_t log_time = time(nullptr);
struct tm* current_time = localtime(&log_time);
stringstream ss;
ss << 1900 + current_time->tm_year << "-";
ss << setfill('0') << setw(2) << current_time->tm_mon + 1 << "-";
ss << setfill('0') << setw(2) << current_time->tm_mday << " ";
ss << setfill('0') << setw(2) << current_time->tm_hour << ".";
ss << setfill('0') << setw(2) << current_time->tm_min << ".";
ss << setfill('0') << setw(2) << current_time->tm_sec;
fout << '[' << ss.str() << ']' << '\t' << "Ready.";;
cout << '[' << ss.str() << ']' << '\t' << "Ready.";;
}
public:
template<typename T>
Logging& operator << (T things)
{
cout << things;
fout << things;
return *this;
}
};
Logging logout;
| true |
3b2ece0fa103492f27c0e5cf7dd0005e6184a370 | C++ | andrzejg123/ProjektPK4 | /Projekt/Projekt/FileNameHelper.cpp | UTF-8 | 4,062 | 2.71875 | 3 | [] | no_license | #include "stdafx.h"
#include "FileNameHelper.h"
std::string FileNameHelper::getTranslationFileName(const LanguageIndicator language)
{
const std::string prefix = "translations/";
std::string name;
const std::string suffix = ".txt";
switch (language) {
case LanguageIndicator::English:
name = "english";
break;
case LanguageIndicator::Polish:
name = "polish";
break;
case LanguageIndicator::Silesian:
name = "sci";
break;
default: name = "en";;
}
return prefix + name + suffix;
}
std::string FileNameHelper::getSoundFileName(const SoundIndicator soundIndicator)
{
const std::string prefix = "sounds/";
std::string name;
const std::string suffix = ".wav";
switch (soundIndicator)
{
case SoundIndicator::ShootArrow:
name = "shoot_arrow";
break;
case SoundIndicator::HitArrow:
name = "hit_arrow";
break;
case SoundIndicator::PlayerGetHit:
name = "player_get_hit";
break;
case SoundIndicator::PlayerDeath:
name = "player_death";
break;
case SoundIndicator::MenuSelectItem:
name = "menu_select_item";
break;
case SoundIndicator::MenuClickItem:
name = "menu_click_item";
break;
default:
name = "shoot_arrow";
}
return prefix + name + suffix;
}
std::string FileNameHelper::getMusicFileName(const MusicIndicator musicIndicator)
{
const std::string prefix = "music/";
std::string name;
const std::string suffix = ".ogg";
switch (musicIndicator)
{
case MusicIndicator::DEFAULT:
name = "default";
break;
case MusicIndicator::MENU:
name = "menu";
break;
default:
name = "default";
}
return prefix + name + suffix;
}
std::string FileNameHelper::getFontFileName(const FontIndicator fontIndicator)
{
const std::string prefix = "fonts/";
std::string name;
const std::string suffix = ".ttf";
switch (fontIndicator)
{
case FontIndicator::Arial:
name = "arial";
break;
default:
name = "arial";
}
return prefix + name + suffix;
}
std::string FileNameHelper::getEnemyFileName(const ObjectIndicator objectIndicator)
{
const std::string prefix = "entities/enemies/";
std::string name;
const std::string suffix = ".txt";
switch (objectIndicator)
{
case ObjectIndicator::RogueArcher:
name = "rogue_archer";
break;
default:
name = "error";
}
return prefix + name + suffix;
}
std::string FileNameHelper::getObjectTextureFileName(const ObjectIndicator objectIndicator)
{
const std::string prefix = "textures/";
std::string name;
const std::string suffix = ".png";
switch (objectIndicator)
{
case ObjectIndicator::RogueArcher:
name = "rogue_archer";
break;
case ObjectIndicator::PlayerWarrior:
name = "player_warrior";
break;
case ObjectIndicator::Chest:
name = "chest";
break;
case ObjectIndicator::Arrow:
name = "arrow";
break;
default: name = "error";
}
return prefix + name + suffix;
}
std::string FileNameHelper::getInterfaceTextureFileName(const InterfaceTextureIndicator textureIndicator)
{
const std::string prefix = "textures/interface/";
std::string name;
const std::string suffix = ".png";
switch (textureIndicator)
{
case InterfaceTextureIndicator::MenuBackground:
name = "menu_background";
break;
case InterfaceTextureIndicator::BackgroundBars:
name = "background_bars";
break;
case InterfaceTextureIndicator::RedBarBig:
name = "red_bar_big";
break;
case InterfaceTextureIndicator::BlueBarSmall:
name = "blue_bar_small";
break;
case InterfaceTextureIndicator::InteractionInfoBackground:
name = "interaction_info_background";
break;
default: name = "error";
}
return prefix + name + suffix;
}
std::string FileNameHelper::getAnimationDataFileName(ObjectIndicator objectIndicator)
{
const std::string prefix = "entities/animations/";
std::string name;
const std::string suffix = ".txt";
switch (objectIndicator)
{
case ObjectIndicator::RogueArcher:
name = "rogue_archer";
break;
case ObjectIndicator::PlayerWarrior:
name = "player_warrior";
break;
case ObjectIndicator::Chest:
name = "chest";
break;
default: name = "error";
}
return prefix + name + suffix;
}
| true |
4578103f3d0b9aab7d8dfa419f229c381d59690e | C++ | martinkro/tutorial-qt | /Beautiful/PP/customcontrol/pushbutton.cpp | UTF-8 | 1,633 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "pushbutton.h"
#include <QPainter>
PushButton::PushButton(QWidget *parent)
: QPushButton(parent)
{
}
PushButton::PushButton(const QString& text, QWidget *parent)
: QPushButton(text,parent)
{
}
void PushButton::paintEvent(QPaintEvent *event)
{
QString pixmapPath;
switch (m_status)
{
case NORMAL:
pixmapPath = m_imagePath;
break;
case HOVER:
pixmapPath = tr("%1_hover").arg(m_imagePath);
break;
case PRESSED:
pixmapPath = tr("%1_pressed").arg(m_imagePath);
break;
default:
pixmapPath = m_imagePath;
break;
}
// draw the button background
QPixmap pixmap(pixmapPath);
QPainter painter(this);
painter.save();
painter.drawPixmap(rect(), QPixmap(pixmapPath));
painter.drawText(this->rect(), Qt::AlignCenter, this->text());
painter.restore();
}
void PushButton::mousePressEvent(QMouseEvent *event)
{
// only when the left button is pressed we force the repaint
if (event->button() == Qt::LeftButton)
{
m_isPressed = true;
m_status = PRESSED;
update();
}
}
void PushButton::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && m_isPressed)
{
m_isPressed = false;
m_status = NORMAL;
emit clicked();
}
}
void PushButton::enterEvent(QEvent* event)
{
m_isPressed = false;
m_status = HOVER;
}
void PushButton::leaveEvent(QEvent* event)
{
m_isPressed = false;
m_status = NORMAL;
}
void PushButton::setButtonBackground(const QString& path)
{
m_imagePath = path;
// resize the button to fit the background picture.
setFixedSize(QPixmap(m_imagePath).size());
} | true |
7d3b02c5e04f5fa9dc0fc761e3227b95811a4db3 | C++ | Sicarim/UmDoYun | /과제제출/API/Mine/Doyun's_Engine/Scene.h | UHC | 628 | 2.59375 | 3 | [] | no_license | #pragma once
#include "GlobalDefine.h"
namespace DoEngine
{
/**
* @brief ӿ Ǵ Scene θ Ŭ
* @details ӿ Ǵ Scene θ Ŭ(߿!!!).Sceneؾ ϴ Լ
*/
class Scene
{
public:
Scene(); //
virtual void Init(HWND hWnd) = 0; //ʱȭ
virtual bool Input(float _fETime) = 0; //ŰԷ
virtual void Update(float _fETime) = 0; //UpdateԼ
virtual void Draw(HDC hdc) = 0; //Draw Լ
virtual void Release() = 0; //Release() Լ
virtual ~Scene(); //Ҹ
};
}
| true |
c9f9a742bf2165e63fccc3af65d7429d81986d45 | C++ | Edean2023/HackingTerroristsForCoffee | /HackingTerroristsForCoffee/Source.cpp | UTF-8 | 3,299 | 3.671875 | 4 | [] | no_license | #include <iostream>
using namespace std;
// functions being declared
// function for the hacked transaction
void hackedTransaction(int& a, int& b);
// function for regular transaction
void regularTransaction(int a, int b);
// function for showing the accounts
void showAccounts(int joe, int terrorists);
/////////////////////////////////////////////////////////////////////////////////////////////
int main() //main function
{
// bank account amounts
// joes account amount
int joesAccount = 325;
// terrorists account amount
int terroristsAccount = 50000;
// show both accounts
showAccounts(joesAccount, terroristsAccount);
// pause so the user can read
system("pause");
cout << "\n/////////////////////////////////////////////" << endl;
// calls the regular transaction function
regularTransaction(joesAccount, terroristsAccount);
cout << "\n/////////////////////////////////////////////" << endl;
// pause so user can read
system("pause");
cout << "\n";
// show both accounts
showAccounts(joesAccount, terroristsAccount);
// pause so user can read
system("pause");
cout << "\n";
cout << "\n/////////////////////////////////////////////" << endl;
// calls hacked transaction function
hackedTransaction(joesAccount, terroristsAccount);
cout << "\n/////////////////////////////////////////////" << endl;
// pause so user can read
system("pause");
cout << "\n";
// calls the show accounts function
showAccounts(joesAccount, terroristsAccount);
// pause so user can read
system("pause");
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////
// This function switches the two funds using references
void hackedTransaction(int& a, int& b) {
// displays message telling the user that the funds are being switched
cout << "Switching funds...\n";
// ints for switching
int Hack = a;
// for switching
a = b;
// completed
b = Hack;
// displays a message telling the user that the transaction is completed
cout << "Transaction Complete.";
// return
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
// this function uses copies to switch
void regularTransaction(int a, int b) {
// displays a message telling the user that the regular transaction is starting
cout << "Starting regular transaction..\n";
// declares the hack
int Hack = a;
// for switching
a = b;
// completed
b = Hack;
// displays a message telling the user that the transaction is completed
cout << "Transaction Complete.";
// return
return;
}
/////////////////////////////////////////////////////////////////////////////////////////////
// prints the balances of both joe and the terrorists
void showAccounts(int joe, int terrorists) {
// displays what the current balances are of both joe and the terrorists
cout << "Current account balances:\n";
// spacer
cout << "__________________________\n";
// display terrorist balance
cout << "Terrorists:==$" << terrorists << endl;
// display joes balance
cout << "Joe:=========$" << joe << endl;
// spacer
cout << "__________________________\n\n";
//return
return;
}
///////////////////////////////////////////////////////////////////////////////////////////// | true |
bbb5c9894660ea1a42b444e2d2289f238d035c9e | C++ | tlanc007/CPP20_Ranges | /JeffGCPPNow2019/30_dropWhile.cpp | UTF-8 | 532 | 3.453125 | 3 | [
"MIT"
] | permissive | /*
30_dropWhile.cpp
*/
#include <iostream>
#include <ranges>
#include <vector>
#include "rangeNamespace.hpp"
namespace view = std::view;
int main()
{
std::vector<int> v { 6, 2, 3, 4, 5, 6 , 7 };
auto is_even = [](int i) { return i % 2 == 0; };
auto print = [](int i) { std::cout << i << " "; };
auto after_leading_evens {
view::drop_while(view::all(v), is_even) |
view::take(2)
};
//execute
rng::for_each(after_leading_evens, print); //prints-> 3 4
std::cout << "\n";
}
| true |
f5d0ce43b8e4a4136e53f19cb5e0e7c00f762de1 | C++ | TheMrKiko/Comp_S1819 | /ast/for_node.h | UTF-8 | 1,089 | 2.625 | 3 | [] | no_license | // $Id: for_node.h,v 1.4 2019/03/21 19:00:02 ist186400 Exp $ -*- c++ -*-
#ifndef __M19_FOR_NODE_H__
#define __M19_FOR_NODE_H__
#include <cdk/ast/expression_node.h>
// include sequence?
namespace m19 {
/**
* Class for describing for-cycle nodes.
*/
class for_node: public cdk::basic_node {
cdk::sequence_node *_init;
cdk::sequence_node *_condition;
cdk::sequence_node *_after;
cdk::basic_node *_block;
public:
inline for_node(int lineno, cdk::sequence_node *init, cdk::sequence_node *condition, cdk::sequence_node *after, cdk::basic_node *block) :
basic_node(lineno), _init(init), _condition(condition), _after(after), _block(block) {
}
public:
inline cdk::sequence_node *init() {
return _init;
}
inline cdk::sequence_node *condition() {
return _condition;
}
inline cdk::sequence_node *after() {
return _after;
}
inline cdk::basic_node *block() {
return _block;
}
void accept(basic_ast_visitor *sp, int level) {
sp->do_for_node(this, level);
}
};
} // m19
#endif
| true |
ec5a13893ee832f2c0e25994c1012fc8e6dda769 | C++ | ejk6218/lv3.1-recovery | /controlSystem/RecoveryBoard/FirmWare/recovery_board_firmware/Core/Src/checkupCode.cpp | UTF-8 | 5,009 | 2.703125 | 3 | [] | no_license | #include "checkupCode.h"
#include "recoveryUtils.h"
#include "main.h"
// test the LED
void ledBlink(){
int i=0;
while(i<5){
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
HAL_Delay(500);
i++;
}
}
// test the speaker
void spkrTest(){
int i=0;
// turn on speaker
HAL_GPIO_WritePin(SPKR_GPIO_Port, SPKR_Pin, GPIO_PIN_SET);
HAL_Delay(2000);
// LED flash to confirm moving to next test
while(i<4){
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
HAL_Delay(500);
i++;
}
}
// test the motor
void motorTest(){
int i=0;
int raw;
// change the direction of the motor
HAL_GPIO_WritePin(DCM_DIR_GPIO_Port, DCM_DIR_Pin, GPIO_PIN_RESET);
// Set the motor pin to on
HAL_GPIO_WritePin(DCM_ON_GPIO_Port, DCM_ON_Pin, GPIO_PIN_SET);
HAL_Delay(5000);
// stop motor
HAL_GPIO_WritePin(DCM_ON_GPIO_Port, DCM_ON_Pin, GPIO_PIN_RESET);
HAL_Delay(1000);
// restart motor
HAL_GPIO_WritePin(DCM_ON_GPIO_Port, DCM_ON_Pin, GPIO_PIN_SET);
// change the direction of the motor
HAL_GPIO_WritePin(DCM_DIR_GPIO_Port, DCM_DIR_Pin, GPIO_PIN_SET);
HAL_Delay(5000);
// turn motor off
HAL_GPIO_WritePin(DCM_ON_GPIO_Port, DCM_ON_Pin, GPIO_PIN_RESET);
// LED flash to confirm moving to next test
while(i<6){
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
HAL_Delay(500);
i++;
}
}
// function to make running the H Bridge easier
void writeLA(int INPUT1, int INPUT2){
GPIO_PinState IN1;
GPIO_PinState IN2;
if(INPUT1){
IN1 = GPIO_PIN_SET;
}
else{
IN1 = GPIO_PIN_RESET;
}
if(INPUT2){
IN2 = GPIO_PIN_SET;
}
else{
IN2 = GPIO_PIN_RESET;
}
HAL_GPIO_WritePin(LA_IN1_GPIO_Port, LA_IN1_Pin, IN1);
HAL_GPIO_WritePin(LA_IN2_GPIO_Port, LA_IN2_Pin, IN2);
}
//test the linear actuator
void testLA(ADC_HandleTypeDef &hadc){
int i=0;
int raw;
// The h-bridge is as follows:
// 1 2
// L L STOP
// H L FORWARD
// L H REVERSE
// H H BRAKE
// stop
writeLA(0, 0);
HAL_Delay(1000);
// forward
writeLA(1, 0);
raw = analogRead(hadc);
// halt
writeLA(0, 0);
raw = analogRead(hadc);
// back
writeLA(0, 1);
raw = analogRead(hadc);
writeLA(0, 0);
// forward again
raw = analogRead(hadc);
writeLA(1, 0);
raw = analogRead(hadc);
// halt
writeLA(0, 0);
raw = analogRead(hadc);
// backward again
writeLA(0, 1);
raw = analogRead(hadc);
// brake
writeLA(1, 1);
raw = analogRead(hadc);
// there's also the potentiometer that needs to be tested
// LED flash to confirm moving to next test
while(i<8){
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
HAL_Delay(500);
i++;
}
}
// test one sensor
void sensorTestSingle(int sensor){
// turn sensors on
HAL_GPIO_WritePin(SENSOR_ON_GPIO_Port, SENSOR_ON_Pin, GPIO_PIN_SET);
// allows us to test either sensor one at a time
if(sensor == 1){
if (HAL_GPIO_ReadPin(SENSOR1_GPIO_Port, SENSOR1_Pin) == GPIO_PIN_SET){
// when the sensor detects HIGH, make the LED blink
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
}
else{
// turn off any other time
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
}
}
else{
// testing sensor 2 now
if (HAL_GPIO_ReadPin(SENSOR2_GPIO_Port, SENSOR2_Pin) == GPIO_PIN_SET){
// when the sensor detects HIGH, make the LED blink
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
}
else{
// turn off any other time
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
}
}
}
// test the sensors and their reading
void sensorTestDouble(){
int sensor1;
int sensor2;
// turn sensors on
HAL_GPIO_WritePin(SENSOR_ON_GPIO_Port, SENSOR_ON_Pin, GPIO_PIN_SET);
sensor1 = HAL_GPIO_ReadPin(SENSOR1_GPIO_Port, SENSOR1_Pin);
sensor2 = HAL_GPIO_ReadPin(SENSOR2_GPIO_Port, SENSOR2_Pin);
// allows us to test either sensor one at a time
if (sensor1 == GPIO_PIN_SET){
// when the sensor detects HIGH, make the LED blink
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
}
else{
// turn off any other time
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
} // testing sensor 2 now
if (sensor2 == GPIO_PIN_SET){
// when the sensor detects HIGH, make the LED blink
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
}
else{
// turn off any other time
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
}
}
// reading the telemetrum signals
void telemetrumTest(){
int i = 0;
GPIO_PinState valueChute;
GPIO_PinState valueDrogue;
valueChute = HAL_GPIO_ReadPin(ISO_CHUTE_GPIO_Port, ISO_CHUTE_Pin);
if(valueChute == GPIO_PIN_SET){
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
}
else{
// turn off any other time
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
}
valueDrogue = HAL_GPIO_ReadPin(ISO_DROGUE_GPIO_Port, ISO_DROGUE_Pin);
if(valueDrogue == GPIO_PIN_SET){
while(i<2){
HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
HAL_Delay(100);
i++;
}
}
else{
// turn off any other time
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
}
}
// full test routine
void testRoutine(){
// running through the above test protocols
}
| true |
d01f582dd33755280b471d96fce414b61c7ecf96 | C++ | christat/inOneWeekend | /src/ch_12/main.cpp | UTF-8 | 4,359 | 2.875 | 3 | [] | no_license | #include <iostream>
#include "camera.h"
#include "dielectric.h"
#include "lambertian.h"
#include "metal.h"
#include "ray.h"
#include "scene.h"
#include "sphere.h"
#include "utils.h"
#include "vec3.h"
Intersectable *random_scene() {
int n = 500;
Intersectable **list = new Intersectable*[n+1];
list[0] = new Sphere(Vec3(0,-1000,0), 1000, new Lambertian(Vec3(0.5, 0.5, 0.5)));
int i = 1;
for (int a = -11; a < 11; a++) {
for (int b = -11; b < 11; b++) {
float choose_mat = drand48();
Vec3 center(a+0.9*drand48(),0.2,b+0.9*drand48());
if ((center-Vec3(4,0.2,0)).length() > 0.9) {
if (choose_mat < 0.8) { // diffuse
list[i++] = new Sphere(center, 0.2, new Lambertian(Vec3(drand48()*drand48(), drand48()*drand48(), drand48()*drand48())));
}
else if (choose_mat < 0.95) { // Metal
list[i++] = new Sphere(center, 0.2,
new Metal(Vec3(0.5*(1 + drand48()), 0.5*(1 + drand48()), 0.5*(1 + drand48())), 0.5*drand48()));
}
else { // glass
list[i++] = new Sphere(center, 0.2, new Dielectric(1.5));
}
}
}
}
list[i++] = new Sphere(Vec3(0, 1, 0), 1.0, new Dielectric(1.5));
list[i++] = new Sphere(Vec3(-4, 1, 0), 1.0, new Lambertian(Vec3(0.4, 0.2, 0.1)));
list[i++] = new Sphere(Vec3(4, 1, 0), 1.0, new Metal(Vec3(0.7, 0.6, 0.5), 0.0));
return new Scene(list,i);
}
// recursive ray tracing call, checks object intersection and material ray scattering.
Vec3 get_color(const Ray &r, Intersectable* scene, int depth) {
Intersection intersection;
if (scene->intersects(r, 0.001, MAXFLOAT, intersection)) {
Ray scattered;
Vec3 attenuation;
if (depth < 50 && intersection.mat_ptr->scatter(r, intersection, attenuation, scattered)) {
return attenuation * get_color(scattered, scene, depth + 1);
}
return Vec3(0, 0, 0);
}
Vec3 unit_direction = r.direction().normalized();
// -1.0 < unit_direction < 1.0; convert to 0.0 < t < 1.0 scale below:
float t = 0.5 * (unit_direction.y() + 1.0);
// color lerp; the more "straight" the direction, the greater the blue contribution.
return (1.0 - t) * Vec3(1.0, 1.0, 1.0) + t * Vec3(0.5, 0.7, 1.0);
}
int main() {
const int nx = 1200;
const int ny = 800;
const int ns = 10;
const int k = 255.99;
// const int list_length = 5;
// Intersectable *list[list_length];
// list[0] = new Sphere(Vec3(0.0, 0.0, -1.0), 0.5, new Lambertian(Vec3(0.1, 0.2, 0.5)));
// list[1] = new Sphere(Vec3(0.0, -100.5, -1.0), 100, new Lambertian(Vec3(0.8, 0.8, 0.0)));
// list[2] = new Sphere(Vec3(1.0, 0.0, -1.0), 0.5, new Metal(Vec3(0.8, 0.6, 0.2), 0.3));
// list[3] = new Sphere(Vec3(-1.0, 0.0, -1.0), 0.5, new Dielectric(1.5));
// list[4] = new Sphere(Vec3(-1.0, 0.0, -1.0), -0.45, new Dielectric(1.5));
//Scene scene(list, list_length);
Intersectable* scene = random_scene();
Vec3 look_from(13, 2, 3);
Vec3 look_to(0, 0, 0);
float dist_to_focus = 10.0;
float aperture = 0.1;
Camera cam(look_from, look_to, 20, float(nx)/float(ny), aperture, dist_to_focus);
std::cout << "P3\n" << nx << " " << ny << "\n255\n";
// "poke" rays through the grid of pixels; top-down, left to right.
for (int j = ny - 1; j >= 0; j--) {
for (int i = 0; i < nx; i++) {
// For each pixel on the screen, ns rays are shot and their
// color contributions averaged, creating an "antialias" blur on shape edges.
Vec3 color(0.0, 0.0, 0.0);
for (int sample = 0; sample < ns; sample++) {
float u = float(i + drand48()) / float(nx);
float v = float(j + drand48()) / float(ny);
Ray r = cam.get_ray(u, v);
Vec3 point = r.point_at(2.0);
color += get_color(r, scene, 0);
}
color /= float(ns);
color = Vec3(sqrt(color[0]), sqrt(color[1]), sqrt(color[2]));
int ir = int(color[0] * k);
int ig = int(color[1] * k);
int ib = int(color[2] * k);
std::cout << ir << " " << ig << " " << ib << "\n";
}
}
} | true |
e28eb3f0969dd8edd80ef9b72357e7fcf9405af1 | C++ | Teemperor/raytracer | /lib/Vec3.h | UTF-8 | 2,343 | 3.53125 | 4 | [
"MIT"
] | permissive | #ifndef RAYTRACER_VEC3_H
#define RAYTRACER_VEC3_H
#include <cmath>
class Vec3 {
public:
typedef double Unit;
private:
Unit X, Y, Z;
public:
Vec3() = default;
Vec3(Unit X, Unit Y, Unit Z) : X(X), Y(Y), Z(Z) {
}
Unit dot(const Vec3 &Other) const {
return X * Other.X + Y * Other.Y + Z * Other.Z;
}
Unit angleBetween(const Vec3 &Other) const {
return std::acos(normalize().dot(Other.normalize()));
}
Vec3 getRandomOther() const {
if (std::abs(normalize().getX() - 1) < 0.1f) {
return Vec3(0, 1, 0);
} else {
return Vec3(1, 0, 0);
}
}
Vec3 rotateAround(const Vec3 &K, Vec3::Unit Angle) const {
// Rodrigues' rotation formula
return *this * std::cos(Angle) + (K.crossProduct(*this)) * std::sin(Angle)
+ K * (K.dot(*this)) * (1 - std::cos(Angle));
}
Vec3 mirrorAt(const Vec3& N) const {
return *this - N * 2.0 * (this->dot(N));
}
Vec3 crossProduct(const Vec3 &B) const {
return Vec3(Y * B.Z - Z * B.Y,
Z * B.X - X * B.Z,
X * B.Y - Y * B.X);
}
Vec3 projection(const Vec3 &B) const {
Vec3::Unit a1 = dot(B.normalize());
return B.normalize() * a1;
}
Vec3 rejection(const Vec3 &B) const {
return *this - projection(B);
}
Unit distance(const Vec3 &O) const {
return (O - *this).length();
}
Unit length() const {
return std::sqrt(X * X + Y * Y + Z * Z);
}
Vec3 operator*(const Unit& F) const {
return Vec3(X * F, Y * F, Z * F);
}
Vec3 operator/(const Unit& F) const {
return Vec3(X / F, Y / F, Z / F);
}
Vec3 operator+(const Vec3& O) const {
return Vec3(X + O.X, Y + O.Y, Z + O.Z);
}
Vec3 operator-(const Vec3& O) const {
return Vec3(X - O.X, Y - O.Y, Z - O.Z);
}
Vec3 operator-() const {
return Vec3(-X, -Y, -Z);
}
Vec3 normalize() const {
auto L = length();
return Vec3(X / L, Y / L, Z / L);
}
Unit getX() const {
return X;
}
void setX(Unit X) {
Vec3::X = X;
}
Unit getY() const {
return Y;
}
void setY(Unit Y) {
Vec3::Y = Y;
}
Unit getZ() const {
return Z;
}
void setZ(Unit Z) {
Vec3::Z = Z;
}
};
inline Vec3 operator*(Vec3::Unit F, const Vec3 &A) {
return A * F;
}
inline Vec3 operator/(Vec3::Unit F, const Vec3 &A) {
return A / F;
}
#endif //RAYTRACER_VEC3_H
| true |
4c098d7c4a1a7ec60b37a9490b87d1b3b61c1071 | C++ | FardMan69420/aimbot-57 | /src/Utils/Misc/Arrays.h | UTF-8 | 946 | 3.375 | 3 | [] | no_license | #ifndef arrays_h
#define arrays_h
/*
* Efficient array allocation and deletion
* minimizing calls to new and delete
*/
template <class T>
class Arrays
{
private:
public:
static T* oneD(int rows)
{
return new T[rows];
}
static T** twoD(int rows, int cols)
{
T** pointers = new T*[rows];
T* allElements = new T[rows * cols];
for(int i = 0; i < rows; i++)
pointers[i] = &allElements[rows * i];
return pointers;
}
static T*** threeD(const int rows, const int cols, const int stacks)
{
T*** pointers = new T**[rows];
T** metapointers = new T*[rows * cols];
T* allElements = new T[rows * cols * stacks];
for(int i = 0; i < stacks; i++)
metapointers[i] = &allElements[rows * cols * i];
for(int i = 0; i < cols; i++)
pointers[i] = &metapointers[rows * i];
// don't THINK we need this anymore...
delete [] metapointers;
return pointers;
}
};
#endif
| true |
8f5ab84072ae5a7283edc1d58b463c67f2e65ad4 | C++ | Akshay-Ravi/Array-4 | /next_permutation.cpp | UTF-8 | 970 | 3.078125 | 3 | [] | no_license | //Time Complexity-O(n)
//Space Complexity-O(1)
//Ran successfully on leetcode
class Solution {
public:
void nextPermutation(vector<int>& nums){
if(nums.empty() || nums.size()==1)
return;
//find the greater number position
int i=nums.size()-1;
int pos;
while(i>0)
{
if(nums[i]>nums[i-1])
{
pos=i-1;
break;
}
i--;
}
//swap the next lowest number with pos
int j;
for(j=nums.size()-1;j>=i;j--)
{
if(nums[j]>nums[pos])
{
swap(nums[j],nums[pos]);
break;
}
}
int last=nums.size()-1;
int first=i;
//reverse from i to size-1
while(first<=last)
{
swap(nums[first],nums[last]);
first++;
last--;
}
}
}; | true |
9964cb3dab6eae62f231df554c78e85d978515e4 | C++ | achillez16/CS_22A | /Midterms/GetScoreTotalWithoutHighLow.cpp | UTF-8 | 2,839 | 3.546875 | 4 | [] | no_license | // Created by Preetesh Barretto on 5/24/20.
//Write a function named “GetScoreTotalWithoutHighLow.cpp” that reads in a
//list of scores until the user enters a negative number. It will add all the given
//scores up and subtract the largest and smallest scores to get a true score total. If
//there are only 2 numbers or less entered, the total will be 0.
//Note: please do not use array or vector class. Please use only local variables to
//keep track the total, highest and lowest.
#include <iostream>
using namespace std;
float GetScoreTotalWithoutHighLow();
int main() {
cout << GetScoreTotalWithoutHighLow() << endl;
}
float GetScoreTotalWithoutHighLow() {
int highest = INT_MIN, smallest = INT_MAX;
float sum, number;
int count = 0;
while (true) {
cout << "Please enter non-negative score: ";
cin >> number;
if (number < 0) {
break;
}
count += 1;
if (count == 1) {
highest = number;
smallest = number;
sum = number;
continue;
}
else {
if (number >= highest) {
highest = number;
} else if (number <= smallest) {
smallest = number;
}
sum = sum + number;
}
}
if (count < 3) {
cout << "The total is: ";
return 0;
}
cout << "Total Sum, Highest, Smallest, Count: " << sum << "," << highest << "," << smallest << "," << (count-2) << endl;
sum = (sum - highest - smallest);
cout << "The total is: ";
return sum;
}
// OUTPUT
///Users/preetesh/CLionProjects/CS_22A/cmake-build-debug/GetScoreTotalWithoutHighLow
//Please enter non-negative score: 20
//Please enter non-negative score: 40
//Please enter non-negative score: 50
//Please enter non-negative score: 80
//Please enter non-negative score: 10
//Please enter non-negative score: -1
//Total Sum, Highest, Smallest, Count: 200,80,10,3
//The total is: 110
//
//Process finished with exit code 0
///Users/preetesh/CLionProjects/CS_22A/cmake-build-debug/GetScoreTotalWithoutHighLow
// Please enter non-negative score: -1
//The total is: 0
//
//Process finished with exit code 0
///Users/preetesh/CLionProjects/CS_22A/cmake-build-debug/GetScoreTotalWithoutHighLow
//Please enter non-negative score: 0
//Please enter non-negative score: 0
//Please enter non-negative score: -1
//The total is: 0
//
//Process finished with exit code 0
///Users/preetesh/CLionProjects/CS_22A/cmake-build-debug/GetScoreTotalWithoutHighLow
//Please enter non-negative score: 0
//Please enter non-negative score: 10
//Please enter non-negative score: 40
//Please enter non-negative score: 50
//Please enter non-negative score: -1
//Total Sum, Highest, Smallest, Count: 100,50,0,2
//The total is: 50
//
//Process finished with exit code 0
| true |
6a4998daef0ac95b7cd36d6182d6f97d08724f89 | C++ | Dblaze47/Problems-Solved---Category-Beginner | /UVA11877.cpp | UTF-8 | 348 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n;
while(cin>>n && n!=0){
int diff = 0, full = 0;
while(n != 0){
n += diff;
full += (n/3);
diff = n%3;
n /= 3;
}
if(diff == 2){full++;};
cout<<full<<endl;
}
return 0;
}
| true |
848b6383eed19058b5434f5f73a9ecdc2cf1893f | C++ | alejandrocoria/MinerDisplay | /TextBox.h | UTF-8 | 1,488 | 2.703125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/Graphics/View.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/Window/Event.hpp>
class TextBox : public sf::Drawable {
public:
TextBox(const sf::Font* font);
void processEvents(const sf::Event& event);
void update(sf::Time time);
void setString(const sf::String& string);
const sf::String& getString() const;
void setPosition(sf::Vector2f position);
void setWidth(int width);
void setCursorPos(int cursorPos, bool selecting = false);
void setSelected(bool set);
protected:
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
private:
void mouseEvent(int x);
void removeSelected();
void updateDrawOffset();
const sf::Font* font;
bool selected = false;
sf::String string;
sf::Time elapsed;
int startSelection = -1;
bool mouseSelecting = false;
int cursor = 0;
mutable sf::Text text;
mutable sf::RectangleShape rectangle;
mutable sf::RectangleShape selectionRect;
mutable sf::VertexArray cursorLine;
mutable sf::VertexArray fadeLines;
mutable sf::View view;
mutable bool dirty = true;
sf::Vector2f position;
int width = 0;
int drawOffset = -2.f;
};
| true |
1420a77039ef870ddbac8ab70bbbed31a47fad8d | C++ | yxinyi/AutoPixelOnline | /BaseEngine/Tcp/Connection.h | GB18030 | 9,179 | 2.546875 | 3 | [] | no_license | #pragma once
#include "asio.hpp"
#include "../../Common/include/tool/Buffer.h"
#include <set>
#include <map>
#include <mutex>
#include "include/tool/UniqueNumberFactory.h"
#include "include/tool/ObjectPool.h"
#include "PakcageList.h"
#include "ServerTypeStruct.h"
const uint64_t g_recv_once_size = 1024;
static uint32_t s_length_statc = sizeof int64_t;
/*
շ: Connection һʱbuffṹ,°ʱ,ԼͷϵǰĹ̶С,Ȼн,ܵİСм¼,
һרĽṹ,ʹڴ?buffṹ,ÿνյʱ,ж,Ƿ˵ǰ,ѽ,аȡ,ֱ
תƱbuff߽ memcpy , һ¼λ,¼ַ.
ͷ: ڽܷ,Լ,Ҫ͵Ϣֱת¼,ֱӽз,ʹö̷߳.
*/
class CConnection {
public:
bool DoSend() {
std::vector<std::shared_ptr<CBuffer>> _local_vec;
{
std::unique_lock<std::mutex> _lock(m_snd_buff_mutex);
if (!m_snd_buff_list.size()) {
m_in_sended = false;
return false;
}
else {
m_in_sended = true;
}
_local_vec.swap(m_snd_buff_list);
}
std::shared_ptr<CBuffer> _snd_buff = CObjectPool<CBuffer>::getInstance()->Get();
for (auto&& _buff_it : _local_vec) {
const uint32_t length = (uint32_t)_buff_it->readableBytes();
_buff_it->prependInt64(length);
_snd_buff->append(_buff_it->peek(), _buff_it->readableBytes());
}
_local_vec.clear();
m_socket.async_write_some(asio::buffer(_snd_buff->peek(), _snd_buff->readableBytes()), [this](asio::error_code err_,
std::size_t size_) {
if (err_) {
printf("async_write_some %d \n", err_.value());
close();
return;
}
DoSend();
});
return true;
}
bool Send(std::shared_ptr<CBuffer> buff_) {
std::unique_lock<std::mutex> _lock(m_snd_buff_mutex);
m_snd_buff_list.push_back(buff_);
return true;
}
bool Recv() {
m_socket.async_read_some(asio::buffer(m_tmp_buff, g_recv_once_size), [this](asio::error_code err_,
std::size_t size_t_) {
if (err_) {
close();
return;
}
//ܵϢ,Ҫȷܳ,Ȼʱеתbuff,ȻжǷѾ,Ѵ,CBuffer,
//¼зַ,ע,m_cur_buffпմ,תеݻʣ,Ƿմ,CBufferݼн
//Ϻȴ첽ȡ
//
m_recv_buff.append(m_tmp_buff, size_t_);
//ʱbuff´ݽ
memset(m_tmp_buff, 0, g_recv_once_size);
uint64_t _packet_length = m_recv_buff.peekInt64();
uint64_t _now_cur_length = m_recv_buff.readableBytes();
//8ֽڵijȱ,ij
while (_packet_length + s_length_statc <= _now_cur_length) {
m_recv_buff.retrieveInt64();
std::string _buff_str = m_recv_buff.retrieveAsString(_packet_length);
std::shared_ptr<CBuffer> _pack_buff = CObjectPool<CBuffer>::getInstance()->Get();
_pack_buff->append(_buff_str.data(), _buff_str.size());
std::shared_ptr<Package> _pack = CObjectPool<Package>::getInstance()->Get(PackageType::Msg, m_conn_id, _pack_buff);
_pack->init(PackageType::Msg, m_conn_id, _pack_buff);
//Ϣ
CPackageMgr::getInstance()->push(_pack);
if (m_recv_buff.readableBytes() >= s_length_statc) {
_packet_length = m_recv_buff.peekInt64();
}
else {
break;
}
_now_cur_length = m_recv_buff.readableBytes();
}
Recv();
});
return true;
}
void close() {
if (m_is_conn) {
std::error_code ignored_ec;
m_socket.cancel();
m_socket.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec);
m_socket.close(ignored_ec);
}
m_is_conn = false;
std::shared_ptr<Package> _pack = CObjectPool<Package>::getInstance()->Get(PackageType::CloseConnect, m_conn_id);
//Ϣ
CPackageMgr::getInstance()->push(_pack);
}
void setConnId(const uint32_t conn_id_) {
m_conn_id = conn_id_;
}
uint32_t getConnId() {
return m_conn_id;
}
bool inSended() {
return m_in_sended;
}
asio::ip::tcp::socket& GetSocket() { return m_socket; }
CConnection(asio::io_service& service_) :m_socket(service_)
{
}
void SetConnNodeType(const NodeType& node_type_) {
m_node_type = node_type_;
}
NodeType GetConnNodeType() {
return m_node_type;
}
bool isConnection() {
return m_is_conn;//&& m_socket.is_open();
}
void ConnectedOK() {
m_is_conn = true;
std::shared_ptr<Package> _pack = CObjectPool<Package>::getInstance()->Get(PackageType::OpenConnect, m_conn_id);
//Ϣ
CPackageMgr::getInstance()->push(_pack);
}
void AcceptOK() {
m_is_conn = true;
std::shared_ptr<Package> _pack = CObjectPool<Package>::getInstance()->Get(PackageType::AcceptConnect, m_conn_id);
//Ϣ
CPackageMgr::getInstance()->push(_pack);
}
~CConnection() {}
std::string getIPStr() {
return remote_ip ;
}
std::string getPortStr() {
return std::to_string(remote_port);
}
std::string getIPPortStr() {
return remote_ip + " : " + std::to_string(remote_port);
}
void setIPStr(const std::string& remote_ip_,const uint16_t remote_port_) {
remote_ip = remote_ip_;
remote_port = remote_port_;
}
private:
NodeType m_node_type;
asio::ip::tcp::socket m_socket;
char m_tmp_buff[g_recv_once_size] = { 0 };
uint32_t m_conn_id = -1;
bool m_is_conn = false;
bool m_in_sended = false;
CBuffer m_recv_buff;
std::string remote_ip = "";
uint16_t remote_port = 0;
std::mutex m_snd_buff_mutex;
std::vector<std::shared_ptr<CBuffer>> m_snd_buff_list;
};
using CConnection_t = std::shared_ptr<CConnection>;
using CConnection_wt = std::weak_ptr<CConnection>;
class CConnectionMgr : public Singleton<CConnectionMgr> {
public:
CConnection_t CreateConnection(asio::io_service& service_, const NodeType& node_type_ = NodeType::Client) {
CConnection_t _tmp_conn = std::make_shared<CConnection>(service_);
const uint32_t _conn_id = m_conn_inc_id++;
_tmp_conn->setConnId(_conn_id);
m_conn_pool[_conn_id] = _tmp_conn;
_tmp_conn->SetConnNodeType(node_type_);
m_nodetype_to_conn[node_type_].insert(_conn_id);
return _tmp_conn;
};
CConnection_t GetConnection(const uint32_t conn_id_) {
if (m_conn_pool.find(conn_id_) == m_conn_pool.end()) {
return nullptr;
}
return m_conn_pool[conn_id_];
}
std::set<uint32_t> GetConnection(const NodeType& node_type_) {
auto _conn_find = m_nodetype_to_conn.find(node_type_);
if (_conn_find == m_nodetype_to_conn.end()) {
return {};
}
return _conn_find->second;
}
CConnection_t GetOnlyOneConnection(const NodeType& node_type_) {
auto _conn_find = m_nodetype_to_conn.find(node_type_);
if (_conn_find == m_nodetype_to_conn.end()) {
return nullptr;
}
if (_conn_find->second.size() != 1) {
return nullptr;
}
return m_conn_pool[*_conn_find->second.begin()];
}
bool CloseConnection(const uint32_t conn_id_) {
auto _conn_find = m_conn_pool.find(conn_id_);
if (_conn_find == m_conn_pool.end()) {
return false;
}
_conn_find->second->close();
return true;
}
bool DelelteConnection(const uint32_t conn_id_) {
auto _conn_find = m_conn_pool.find(conn_id_);
if (_conn_find == m_conn_pool.end()) {
return false;
}
m_nodetype_to_conn[_conn_find->second->GetConnNodeType()].erase(conn_id_);
m_conn_pool.erase(conn_id_);
return true;
}
private:
std::map<uint32_t, CConnection_t> m_conn_pool;
std::map<NodeType, std::set<uint32_t>> m_nodetype_to_conn;
uint32_t m_conn_inc_id = 0;
};
//Api
std::string ApiGetConnectIPPortStr(const uint32_t conn_);
std::string ApiGetConnectIPStr(const uint32_t conn_);
| true |
554c47329223d94f9ac26aea0f00124bd2fcc80c | C++ | evalveny/MP20-21 | /Tema 1/CodiSessions/S5 - Classe Complex/ComplexosOperadors/complex.h | UTF-8 | 485 | 2.65625 | 3 | [] | no_license | #pragma once
class Complex
{
public:
Complex() { m_real = 0; m_img = 0; }
float getReal(); //TO VALIDATE TEST
float getImg(); //TO VALIDATE TEST
void setReal(float pReal); //TO VALIDATE TEST
void setImg(float PImg); //TO VALIDATE TEST
void mostra() const;
Complex suma(const Complex &c) const;
Complex resta(const Complex &c) const;
Complex multiplica(const Complex &c) const;
Complex avaluaOperacio(const char operacio, const Complex& c2) const;
float m_real, m_img;
};
| true |
a11b4310b849d21315de7778e2d20d26f095943a | C++ | MaciejWadowski/cpp | /JIMP_AI/lab_3/smarttree/SmartTree.cpp | UTF-8 | 1,587 | 3.359375 | 3 | [] | no_license | //
// Created by maciej on 31.03.18.
//
#include "SmartTree.h"
using std::unique_ptr;
using std::ostream;
using std::string;
using std::make_unique;
using std::cout;
namespace datastructures{
unique_ptr <SmartTree> CreateLeaf(int value){
auto Leaf = make_unique<SmartTree>();
Leaf->left = nullptr;
Leaf->right = nullptr;
Leaf->value = value;
return Leaf;
}
unique_ptr <SmartTree> InsertLeftChild(unique_ptr<SmartTree> tree, unique_ptr<SmartTree> left_subtree){
if(tree->left == nullptr)
tree->left = std::move(left_subtree);
return tree;
}
unique_ptr<SmartTree> InsertRightChild(unique_ptr<SmartTree> tree, unique_ptr<SmartTree> right_subtree) {
if(tree->right == nullptr)
tree->right = std::move(right_subtree);
return tree;
}
void PrintTreeInOrder(const unique_ptr<SmartTree> &unique_ptr, ostream *out){
if(unique_ptr != nullptr) {
PrintTreeInOrder(unique_ptr->left, out);
*out << unique_ptr->value << ", ";
PrintTreeInOrder(unique_ptr->right, out);
}
}
string DumpTree(const unique_ptr<SmartTree> &tree){
string output = "";
if(tree != nullptr) {
output = "[" + output + std::to_string(tree->value) + " ";
output = output + DumpTree(tree->left);
output = output + " " + DumpTree(tree->right) + "]";
}
else output += "[none]";
return output;
}
unique_ptr <SmartTree> RestoreTree(const string &tree){
}
} | true |
abeaa4bc71b9d56bf03f6ff47ae38e361ed68df3 | C++ | CSUAITeam19/MazeAlgorithm | /DF/MazeBfs.cpp | UTF-8 | 6,850 | 2.578125 | 3 | [] | no_license | #include "class.cpp"
int width, height;//地图的长宽
int startx, starty, endx, endy;
int step = 0;
int flag = 0;
int f = 0;
vector<vector<int>> maze;//迷宫地图数据
vector<vector<int>> vis;//是否访问过和能否访问
vector<vector<int>> cost;//耗费
vector<vector<int>> b;//步数
string path1, path2;//输入输出路径
vector<vector<int>> precost;
queue<Point> openlist;//访问表
vector<Point> pointlist;
int listnumber = 0;
ofstream out;
int caozuo[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
int caozuo2[4][2] = { {1,1},{1,-1},{-1,1},{-1,-1} };
void readin() {
ifstream in(path1);//地图数据地址
in >> width >> height;
maze.resize(width);
vis.resize(width);
cost.resize(width);
b.resize(width);
precost.resize(width);
for (int i = 0; i < width; i++)
{
maze[i].resize(height);
vis[i].resize(height);
cost[i].resize(height);
b[i].resize(height);
precost[i].resize(height);
}
//vector 构造
// cout << width << " " << height << endl;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
in >> maze[i][j];//读入每个格子的数据
if (maze[i][j] == 4) {
startx = i;
starty = j;
b[i][j] = 1;
}
else if (maze[i][j] == 8) {
endx = i;
endy = j;
}
else if (maze[i][j] == 1) {
vis[i][j] = 5;
precost[i][j] = -1;
}
}
}
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
out << setw(5) << left << precost[i][j] << " ";
}
out << endl;
}
// out << startx << " " << starty << endl;
// out << endx << " " << endy << endl;
in.close();//用完后关闭
}
void bfs() {
openlist.push(Point(startx, starty));
vis[startx][starty] = 1;
while (!openlist.empty()) {
int num = 1;
step++;
int x_now = openlist.front().x, y_now = openlist.front().y;
vis[x_now][y_now] = 3;
int cost_now = cost[x_now][y_now];
out << step << ' ';
if (x_now == endx && y_now == endy) {
flag = 1;
out << num << endl;
out << "vis" << ' ' << x_now << ' ' << y_now << ' ' << cost_now << endl;
out << "way" << ':' << ' ';
while (!(x_now == startx && y_now == starty)) {
Point point1(x_now, y_now);
pointlist.push_back(point1);
listnumber++;
for (int i = 0; i < 4; i++) {
int x_next = x_now + caozuo[i][0], y_next = y_now + caozuo[i][1];
if (maze[x_next][y_next] != 1&&b[x_next][y_next]==(b[x_now][y_now]-1)) {
x_now = x_next; y_now = y_next;
f = 1;
break;
}
}
if (f==0) {
for (int i = 0; i < 4; i++) {
int x_next = x_now + caozuo2[i][0], y_next = y_now + caozuo2[i][1];
if (maze[x_next][y_now] != 1 || maze[x_now][y_next] != 1) {
if (maze[x_next][y_next] != 1 && b[x_next][y_next] == b[x_now][y_now] - 1) {
x_now = x_next; y_now = y_next;
break;
}
}
}
}
f = 0;
}
Point point2(startx, starty);
pointlist.push_back(point2);
listnumber++;
out << listnumber << endl;
for (int i = listnumber - 1; i >= 0; i--) {
out << pointlist[i].x << ' ' << pointlist[i].y << endl;
}
cout << "find it!" << endl;
break;
}
for (int i = 0; i < 4; i++) {//这里是上左下右
int x_next = x_now + caozuo[i][0], y_next = y_now + caozuo[i][1];
if (vis[x_next][y_next] == 1) {
num++;
}
if (maze[x_next][y_next] != 1 && vis[x_next][y_next] == 0) {
num++;
}
}
for (int i = 0; i < 4; i++) {//这里是上左下右(斜)
int x_next = x_now + caozuo2[i][0], y_next = y_now + caozuo2[i][1];
if (maze[x_next][y_now] != 1 || maze[x_now][y_next] != 1) {
if (vis[x_next][y_next] == 1) {
num++;
}
if (maze[x_next][y_next] != 1 && vis[x_next][y_next] == 0) {
num++;
}
}
}
out << num << endl;
out << "vis" << ' ' << x_now << ' ' << y_now << ' ' << cost_now << endl;
for (int i = 0; i < 4; i++) {//这里是上左下右
int x_next = x_now + caozuo[i][0], y_next = y_now + caozuo[i][1];
if (vis[x_next][y_next] == 1) {
cost[x_next][y_next] = min(cost[x_next][y_next], cost_now + 10);
out << "cost " << x_next << " " << y_next << " " << cost[x_next][y_next] << endl;
}
if (maze[x_next][y_next] != 1 && vis[x_next][y_next] == 0) {
cost[x_next][y_next] = cost_now + 10;
b[x_next][y_next] = b[x_now][y_now] + 1;
openlist.push(Point(x_next, y_next));
out << "add" << ' ' << x_next << ' ' << y_next << ' ' << cost[x_next][y_next] << endl;
vis[x_next][y_next] = 1;
}
}
for (int i = 0; i < 4; i++) {//这里是上左下右(斜)
int x_next = x_now + caozuo2[i][0], y_next = y_now + caozuo2[i][1];
if (maze[x_next][y_now] != 1 || maze[x_now][y_next] != 1) {
if (vis[x_next][y_next] == 1) {
cost[x_next][y_next] = min(cost[x_next][y_next], cost_now + 14);
out << "cost " << x_next << " " << y_next << " " << cost[x_next][y_next] << endl;
}
if (maze[x_next][y_next] != 1 && vis[x_next][y_next] == 0) {
cost[x_next][y_next] = cost_now + 14;
b[x_next][y_next] = b[x_now][y_now] + 1;
openlist.push(Point(x_next, y_next));
out << "add" << ' ' << x_next << ' ' << y_next << ' ' << cost[x_next][y_next] << endl;
vis[x_next][y_next] = 1;
}
}
}
openlist.pop();//拓展完队首出队
}
}
int main(int argc, char* argv[])
{
path1 = argv[1];
path2 = argv[2];
out = ofstream(path2);
readin();
bfs();
if (flag == 0) {
out << "way" << ' ' << -1 << endl;
}
out.close();
} | true |
08c1cdad5979a081e728fd143307df1020795c15 | C++ | kcwzzz/KCW | /cocos/Project 모음/170908/Classes/CEnemyrAniBox.cpp | UTF-8 | 3,990 | 2.578125 | 3 | [] | no_license | #include "cocos2d.h"
#include "CActorAniBox.h"
#include "Define.h"
#include "GameScene.h"
void CActorAniBox::CreateAniBox(string tAniName, Vec2 tVec, int tWidth, int tHeight, float tSetDelay)
{
this->CreateTexture(tAniName, tWidth, tHeight);
this->SetPosition(tVec);
this->CreateAniMoveDown(tWidth, tHeight, tSetDelay);
this->CreateAniMoveUp(tWidth, tHeight, tSetDelay);
this->CreateAniMoveLeft(tWidth, tHeight, tSetDelay);
this->CreateAniMoveRight(tWidth, tHeight, tSetDelay);
}
void CActorAniBox::SetScene(Node *tpNode)
{
mpScene = tpNode;
}
void CActorAniBox::Build()
{
mpScene->addChild(mpSprite, 10);
}
void CActorAniBox::CreateTexture(string tAniName, int tWidth, int tHeight)
{
mAniName = tAniName;
mpTexture = Director::getInstance()->getTextureCache()->addImage(mAniName);
mpSprite = Sprite::createWithTexture(mpTexture, Rect(0, 0, tWidth, tHeight));
}
void CActorAniBox::SetPosition(Vec2 tVec)
{
mVec = tVec;
mpSprite->setPosition(mVec);
}
void CActorAniBox::CreateAniMoveDown(int tWidth, int tHeight, float tSetDelay)
{
mpAnimationDown = Animation::create();
mpAnimationDown->setDelayPerUnit(tSetDelay);
for (int i = 0; i < 3;i++)
{
int column = i % 3;
int row = i / 3;
mpAnimationDown->addSpriteFrameWithTexture(
mpTexture,
Rect(column * tWidth, row * tHeight, tWidth, tHeight));
}
mpAnimateDown = Animate::create(mpAnimationDown);
mpAnimateDown->retain();
RepeatForeverDown = RepeatForever::create(mpAnimateDown);
RepeatForeverDown->retain();
}
void CActorAniBox::CreateAniMoveUp(int tWidth, int tHeight, float tSetDelay)
{
mpAnimationUp = Animation::create();
mpAnimationUp->setDelayPerUnit(tSetDelay);
for (int i = 9; i < 12;i++)
{
int column = i % 3;
int row = i / 3;
mpAnimationUp->addSpriteFrameWithTexture(
mpTexture,
Rect(column * tWidth, row * tHeight, tWidth, tHeight));
}
mpAnimateUp = Animate::create(mpAnimationUp);
mpAnimateUp->retain();
RepeatForeverUp = RepeatForever::create(mpAnimateUp);
RepeatForeverUp->retain();
}
void CActorAniBox::CreateAniMoveLeft(int tWidth, int tHeight, float tSetDelay)
{
mpAnimationLeft = Animation::create();
mpAnimationLeft->setDelayPerUnit(tSetDelay);
for (int i = 3; i < 6;i++)
{
int column = i % 3;
int row = i / 3;
mpAnimationLeft->addSpriteFrameWithTexture(
mpTexture,
Rect(column * tWidth, row * tHeight, tWidth, tHeight));
}
mpAnimateLeft = Animate::create(mpAnimationLeft);
mpAnimateLeft->retain();
RepeatForeverLeft = RepeatForever::create(mpAnimateLeft);
RepeatForeverLeft->retain();
}
void CActorAniBox::CreateAniMoveRight(int tWidth, int tHeight, float tSetDelay)
{
mpAnimationRight = Animation::create();
mpAnimationRight->setDelayPerUnit(tSetDelay);
for (int i = 6; i < 9;i++)
{
int column = i % 3;
int row = i / 3;
mpAnimationRight->addSpriteFrameWithTexture(
mpTexture,
Rect(column * tWidth, row * tHeight, tWidth, tHeight));
}
mpAnimateRight = Animate::create(mpAnimationRight);
mpAnimateRight->retain();
RepeatForeverRight = RepeatForever::create(mpAnimateRight);
RepeatForeverRight->retain();
}
void CActorAniBox::RunMoveAniUp()
{
mpSprite->runAction(RepeatForeverUp);
}
void CActorAniBox::RunMoveAniDown()
{
mpSprite->runAction(RepeatForeverDown);
}
void CActorAniBox::RunMoveAniLeft()
{
mpSprite->runAction(RepeatForeverLeft);
}
void CActorAniBox::RunMoveAniRight()
{
mpSprite->runAction(RepeatForeverRight);
}
void CActorAniBox::CreateAniDamaged()
{
}
void CActorAniBox::StopMoveAnimation()
{
mpSprite->stopAction(RepeatForeverUp);
mpSprite->stopAction(RepeatForeverDown);
mpSprite->stopAction(RepeatForeverLeft);
mpSprite->stopAction(RepeatForeverRight);
}
void CActorAniBox::RunAttack()
{
}
void CActorAniBox::Show()
{
mpSprite->setVisible(true);
}
void CActorAniBox::Hide()
{
mpSprite->setVisible(false);
}
void CActorAniBox::UnBuild()
{
mpScene->removeChild(mpSprite);
}
void CActorAniBox::Damaged()
{
}
Sprite* CActorAniBox::GetSprite()
{
return mpSprite;
} | true |
605890bef5988868cbd140864b4dc82c3f3bbe8c | C++ | 4roring/KK1_Eternal_Crusade | /KK1_Tool/Code/NavTri.cpp | UTF-8 | 2,404 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include "NavTri.h"
#include "NavPoint.h"
#include "Transform.h"
NavTri::NavTri(LPDIRECT3DDEVICE9 ptr_device)
: ptr_device_(ptr_device)
{
}
NavTri::~NavTri()
{
Release();
}
HRESULT NavTri::Initialize(const std::array<NavPoint*, 3>& nav_point_array)
{
const int max_point = nav_point_array.size();
for(int i = 0; i < max_point; ++i)
nav_point_array_[i] = nav_point_array[i]->ClonePoint();
D3DXCreateLine(ptr_device_, &ptr_line_);
ptr_line_->SetAntialias(TRUE);
return S_OK;
}
void NavTri::Update(float delta_time)
{
Matrix mat_view, mat_proj;
ptr_device_->GetTransform(D3DTS_VIEW, &mat_view);
ptr_device_->GetTransform(D3DTS_PROJECTION, &mat_proj);
for(int i=0; i<3;++i)
{
viewport_nav_point_[i] = nav_point_array_[i]->transform()->position();
viewport_nav_point_[i].y += 0.1f;
D3DXVec3TransformCoord(&viewport_nav_point_[i], &viewport_nav_point_[i], &mat_view);
if (viewport_nav_point_[i].z <= 0.f)
viewport_nav_point_[i].z = 0.f;
D3DXVec3TransformCoord(&viewport_nav_point_[i], &viewport_nav_point_[i], &mat_proj);
}
viewport_nav_point_[3] = viewport_nav_point_[0];
}
void NavTri::Render()
{
ptr_line_->SetWidth(5.f);
ptr_line_->Begin();
switch (option_)
{
case 0:
ptr_line_->DrawTransform(viewport_nav_point_, 4, nullptr, D3DXCOLOR(1.f, 0.f, 0.f, 1.f));
break;
case 1:
ptr_line_->DrawTransform(viewport_nav_point_, 4, nullptr, D3DXCOLOR(1.f, 0.f, 1.f, 1.f));
break;
case 2:
ptr_line_->DrawTransform(viewport_nav_point_, 4, nullptr, D3DXCOLOR(1.f, 1.f, 0.f, 1.f));
break;
default:
break;
}
ptr_line_->End();
}
void NavTri::Release()
{
for (auto& nav_point : nav_point_array_)
nav_point->Release();
Engine::Safe_Release(ptr_line_);
}
NavTri * NavTri::Create(LPDIRECT3DDEVICE9 ptr_device, const std::array<NavPoint*, 3>& nav_point_array)
{
NavTri* ptr_nav_tri = new NavTri(ptr_device);
if (FAILED(ptr_nav_tri->Initialize(nav_point_array)))
{
Engine::Safe_Delete(ptr_nav_tri);
assert(!"NavTri Create Failed");
}
return ptr_nav_tri;
}
bool NavTri::PickNavMesh(const Vector3 & ray_pos, const Vector3 & ray_dir)
{
BOOL is_hit_tri = D3DXIntersectTri(&nav_point_array_[0]->transform()->position()
, &nav_point_array_[1]->transform()->position()
, &nav_point_array_[2]->transform()->position()
, &ray_pos, &ray_dir, nullptr, nullptr, nullptr);
if (TRUE == is_hit_tri) return true;
return false;
}
| true |
a5949930b15cfb29fe8aac7f14520160ef55d12b | C++ | colinmaher/comsc200 | /Week4/PayRoll.h | UTF-8 | 448 | 2.890625 | 3 | [] | no_license | #ifndef PAYROLL_H
#define PAYROLL_H
#include <iostream>
using namespace std;
class PayRoll{
private:
double payRate;
double hrs;
public:
//constructors
PayRoll(){ payRate = 0; hrs = 0; };
PayRoll(double r, double h){payRate = r; hrs = h;}
//mutators
void setHours(double h){ hrs = h; }
void setRate(double r){ payRate = r; }
//feature functions
double getTotal(){ return hrs*payRate;}
};
#endif | true |
d0d12b395e02e9aeece4f5b1de6c7d795048e91f | C++ | fmi-lab/up-2018-kn-group3-sem | /Exercises/Exercise 6/kontrolno1variantBzad3.cpp | UTF-8 | 405 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
int main(){
int N;
cin>>N;
double x,y;
double maxX, minX, maxY, minY;
for(int i = 0; i<N; i++){
cin>>x>>y;
if(i==0){
maxX = minX = x;
maxY = minY = y;
} if(x>maxX){
maxX = x;
} if(x<minX){
minX = x;
} if(y<maxY){
maxY = y;
} if(y<minY){
minY = y;
}
}
cout<<pow(max(abs(maxX - minX), abs(maxY - minY)), 2);
} | true |
b79c122ad444a31720f9b9430e73b307d04b9e52 | C++ | 0sk4r/Uwr | /Algorytmy_i_struktury_danych/3podejscie/C/main.cpp | UTF-8 | 3,945 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <climits>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long tab[1000010];
long long massa[1000010];
int solutions[1000010];
int ans_max[1000010], ans_min[1000010];
// memset(tab, 0, sizeof(tab));
// memset(ans_max, 0, sizeof(ans_max));
// memset(ans_min, 0, sizeof(ans_min));
vector<pair<int, int>> monets;
long long total_mass, num_monets;
cin >> total_mass;
cin >> num_monets;
for (long i = 0; i <= total_mass; i++)
{
// tab[i] = 0;
ans_max[i] = 0;
ans_min[i] = 0;
}
int value, mass;
for (long i = 0; i < num_monets; i++)
{
cin >> value >> mass;
monets.push_back(make_pair(value, mass));
}
tab[0] = 0;
massa[0] = 0;
for (long weight = 1; weight <= total_mass; weight++)
{
// cout << "weight "<< weight << endl;
for (long unsigned int j = 0; j < monets.size(); j++)
{
pair<int, int> monet = monets[j];
if (monet.second <= weight)
{
long long new_val = tab[weight - monet.second] + monet.first;
// cout << "masa: " << massa[weight - monet.second] + monet.second << endl;
if (tab[weight] < new_val && massa[weight - monet.second] + monet.second == weight)
{
tab[weight] = new_val;
massa[weight] = massa[weight - monet.second] + monet.second;
solutions[weight] = j;
}
}
}
}
// for(int i=0; i<=total_mass; i++){on sa
// cout << tab[i] << endl;
// }
long long max_val = tab[total_mass];
long k = total_mass;
if (max_val != 0)
{
while (k > 0)
{
pair<int, int> monet = monets[solutions[k]];
ans_max[solutions[k]] += 1;
k -= monet.second;
}
}
// ===============================================================
for (long i = 0; i <= total_mass; i++)
{
tab[i] = LLONG_MAX;
}
// memset(tab, LONG_MAX, sizeof(tab));
tab[0] = 0;
for (long weight = 1; weight <= total_mass; weight++)
{
for (long unsigned int j = 0; j < monets.size(); j++)
{
pair<int, int> monet = monets[j];
if (monet.second <= weight)
{
if (tab[weight - monet.second] != LLONG_MAX)
{
long long new_val = tab[weight - monet.second] + monet.first;
if (tab[weight] > new_val && massa[weight - monet.second] + monet.second == weight)
{
tab[weight] = new_val;
massa[weight] = massa[weight - monet.second] + monet.second;
solutions[weight] = j;
}
}
}
}
}
// for(int i=0; i<=total_mass; i++){on sa
// cout << tab[i] << endl;
// }
long long min_val = tab[total_mass];
k = total_mass;
if (min_val != LLONG_MAX)
{
while (k > 0)
{
pair<int, int> monet = monets[solutions[k]];
ans_min[solutions[k]] += 1;
k -= monet.second;
}
}
//========================================================
if (max_val != 0 && min_val != LLONG_MAX)
{
cout << "TAK" << endl;
cout << min_val << endl;
for (int i = 0; i < num_monets; i++)
{
cout << ans_min[i] << " ";
}
cout << endl;
cout << max_val << endl;
for (int i = 0; i < num_monets; i++)
{
cout << ans_max[i] << " ";
}
}
else
{
cout << "NIE" << endl;
return 0;
}
return 0;
} | true |
d9379aa7b1579eaac344b43cda9523479d2101cd | C++ | ErsaSatriaPradana/P4-Febry-Dwi-Firianto | /Jobsheet 1 C++.cpp | UTF-8 | 444 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main (){
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"NAMA : Ersa Satria Pradana\n";
cout<<"NIM : 8\n";
cout<<"KELOMPOK : 10\n";
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
int nim[8]={0,4,7,8,9};
cout<<"Nim ke-1 adalah "<<nim[0]<<endl;
cout<<"Nim ke-2 adalah "<<nim[1]<<endl;
cout<<"Nim ke-3 adalah "<<nim[2]<<endl;
cout<<"Nim ke-4 adalah "<<nim[3]<<endl;
cout<<"Nim ke-5 adalah "<<nim[4]<<endl;
}
| true |
62e8b4cbd653285c15516e5c1303ad0d5143c9ad | C++ | SaberDa/CPP_Basic_Projects_WareHouse | /MyDocker/src/main.cpp | UTF-8 | 533 | 2.5625 | 3 | [] | no_license |
#include <iostream>
#include "docker.hpp"
int main(int argc, char** argv) {
std::cout << "...start container" << std::endl;
docker::container_config config;
// Container config
// ...
config.host_name = "mydocker";
config.root_dir = "./image";
config.ip = "192.168.0.100"; // Container IP
config.bridge_name = "docker0";
config.bridge_ip = "192.168.0.1";
docker::container container(config); // Generate container according to config
container.start();
std::cout << "stop container..." << std::endl;
return 0;
}
| true |
cf0369880252286e218d74d15240fc70c30a7a3d | C++ | mosesmccabe/C-review-2- | /Structure/basicUseOfStruct.cpp | UTF-8 | 1,373 | 4 | 4 | [] | no_license | /* Moses Peace Mccabe
This program demonstrates the use of structures
(UseOfStruct.cpp)
*/
#include <iostream>
#include <string>
using namespace std;
struct PayRoll
{
int empNumber; // Employee number
string name; // Enployee name
double hours; // Hours worked
double payRate; // Hourly payRate
double grossPay; // Gross pay
};
int main()
{
PayRoll employee; // employee is a Payroll structure
// Get the employee's number:
cout << "Enter the employee's number: ";
cin >> employee.empNumber;
cin.ignore();
// Get the employee's name
cout << "Enter the employee's name ";
getline(cin, employee.name);
// Get the hours work by the employee
cout << "How many hours did the employee work? ";
cin >> employee.hours;
// Get the employee pay rate
cout << "What is the emplayee hourly payrate? ";
cin >> employee.payRate;
// calculate the employee's gross pay
employee.grossPay = employee.hours * employee.payRate;
// Display the employee data
cout << "Here is the employee's payroll data:\n"
<< "Name: " << employee.name
<< "\nNumber: " << employee.empNumber
<< "\nHours Work: " << employee.hours
<< "\nHourly payRate: " << employee.payRate
<< "\nGross Pay: $" << employee.grossPay << "\n";
return 0;
} | true |
cd3fc29b0d711c7f6a5ad7920c68c98d5f2da9ec | C++ | logsniper/learningCpp | /nameHiddenWhenOverloading.cpp | UTF-8 | 443 | 3.53125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class base{
public:
void f(){ cout<<"base::f()"<<endl; }
void f(int){ cout<<"base::f(int)"<<endl; }
void f(char){ cout<<"base::f(char)"<<endl; }
};
class child : public base{
public:
void f(int){ cout<<"child::f(int)"<<endl; }
void f(double){ cout<<"child::f(double)"<<endl; }
};
int main(){
child c;
c.f(1);
c.f(0.1);
// c.f();
c.f('c');// cast char to int
}
| true |
8a7fda814617ffbf765f8a657754cc6fc5dbeeeb | C++ | adamleonardhubble/Game-Engine-Development | /Solution/engine/enginecode/include/independent/rendering/model.h | UTF-8 | 709 | 3.03125 | 3 | [] | no_license | #pragma once
namespace Engine
{
class Model
{
public:
//! Constructor
Model() : vertices(nullptr), indices(nullptr), verticesSize(0), indicesSize(0) {}
//! Destructor
~Model()
{
delete vertices;
vertices = nullptr;
delete indices;
indices = nullptr;
delete posVertices;
posVertices = nullptr;
}
float* vertices; //!< Pointer to the verices of the model being loaded
unsigned int* indices; //!< Pointer to the indices of the model being loaded
unsigned int verticesSize; //!< The number of values of the vertices being loaded
unsigned int indicesSize; //!< The number of values of the indices being loaded
float* posVertices;
unsigned int posVerticesSize;
};
} | true |
f7c3fcdcdc0738a96b32e89a56deb4dc2c9c9851 | C++ | phresnel/ICalLib | /include/rfc3986.hh | UTF-8 | 2,987 | 2.5625 | 3 | [
"MIT"
] | permissive | #ifndef RFC3986_HH_INCLUDED_20190201
#define RFC3986_HH_INCLUDED_20190201
// -- URI (RFC 3986) Parser Helpers. ------------------------------------
// [RFC 3986](https://tools.ietf.org/html/rfc3986)
#include <iosfwd>
#include <string>
#include <optional>
inline namespace rfc3986 {
using std::string;
using std::optional;
using std::nullopt;
struct Authority {
optional<string> userinfo;
string host;
optional<string> port;
};
inline std::string to_string(Authority const &v) {
return (v.userinfo ? (*v.userinfo + '@') : (string(""))) +
v.host + ":" +
(v.port ? (":" + *v.port) : (string("")));
}
struct Uri {
string scheme;
string hier_part;
optional<string> query;
optional<string> fragment;
};
inline std::string to_string(Uri const &v) {
return v.scheme + ":" +
v.hier_part +
(v.query ? ("?" + *v.query) : (string(""))) +
(v.fragment ? ("#" + *v.fragment) : (string("")));
}
optional<string> read_gen_delims(std::istream &is);
optional<string> read_sub_delims(std::istream &is);
optional<string> read_reserved(std::istream &is);
optional<string> read_unreserved(std::istream &is);
optional<string> read_pct_encoded(std::istream &is);
optional<string> read_pchar(std::istream &is);
optional<string> read_segment(std::istream &is);
optional<string> read_segment_nz(std::istream &is);
optional<string> read_segment_nz_nc_single(std::istream &is);
optional<string> read_segment_nz_nc(std::istream &is);
optional<string> read_path_abempty(std::istream &is);
optional<string> read_path_absolute(std::istream &is);
optional<string> read_path_noscheme(std::istream &is);
optional<string> read_path_rootless(std::istream &is);
optional<string> read_path_empty(std::istream &is);
optional<string> read_path(std::istream &is);
optional<string> read_port(std::istream &is);
optional<string> read_reg_name(std::istream &is);
optional<string> read_IPv4address(std::istream &is);
optional<string> read_dec_octet(std::istream &is);
optional<string> read_IPv6address(std::istream &is);
optional<string> read_ls32(std::istream &is);
optional<string> read_h16(std::istream &is);
optional<string> read_IP_literal(std::istream &is);
optional<string> read_IPvFuture(std::istream &is);
optional<string> read_host(std::istream &is);
optional<string> read_userinfo(std::istream &is);
optional<Authority> read_authority(std::istream &is);
optional<string> read_relative_part(std::istream &is);
optional<string> read_URI_reference(std::istream &is);
optional<string> read_fragment(std::istream &is);
optional<string> read_query(std::istream &is);
optional<string> read_hier_part(std::istream &is);
optional<Uri> read_URI(std::istream &is);
optional<string> read_absolute_URI(std::istream &is);
optional<string> read_relative_ref(std::istream &is);
std::ostream& operator<<(std::ostream& os, Uri const &v);
}
#endif //RFC3986_HH_INCLUDED_20190201
| true |
d59e29895d6aa36eabd0763cc7df1dc4d96ed7c4 | C++ | yuri410/rpg | /external/DirectXShaderCompiler/tools/clang/test/CXX/class.derived/class.virtual/p3-0x.cpp | UTF-8 | 4,380 | 2.96875 | 3 | [
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s
namespace Test1 {
struct B {
virtual void f(int);
};
struct D : B {
virtual void f(long) override; // expected-error {{'f' marked 'override' but does not override any member functions}}
void f(int) override;
};
}
namespace Test2 {
struct A {
virtual void f(int, char, int);
};
template<typename T>
struct B : A {
// FIXME: Diagnose this.
virtual void f(T) override;
};
template<typename T>
struct C : A {
virtual void f(int) override; // expected-error {{does not override}}
};
}
namespace Test3 {
struct A {
virtual void f(int, char, int);
};
template<typename... Args>
struct B : A {
virtual void f(Args...) override; // expected-error {{'f' marked 'override' but does not override any member functions}}
};
template struct B<int, char, int>;
template struct B<int>; // expected-note {{in instantiation of template class 'Test3::B<int>' requested here}}
}
namespace Test4 {
struct B {
virtual void f() const final; // expected-note {{overridden virtual function is here}}
};
struct D : B {
void f() const; // expected-error {{declaration of 'f' overrides a 'final' function}}
};
}
namespace PR13499 {
struct X {
virtual void f();
virtual void h();
};
template<typename T> struct A : X {
void f() override;
void h() final;
};
template<typename T> struct B : X {
void g() override; // expected-error {{only virtual member functions can be marked 'override'}}
void i() final; // expected-error {{only virtual member functions can be marked 'final'}}
};
B<int> b; // no-note
template<typename T> struct C : T {
void g() override;
void i() final;
};
template<typename T> struct D : X {
virtual void g() override; // expected-error {{does not override}}
virtual void i() final;
};
template<typename...T> struct E : X {
void f(T...) override;
void g(T...) override; // expected-error {{only virtual member functions can be marked 'override'}}
void h(T...) final;
void i(T...) final; // expected-error {{only virtual member functions can be marked 'final'}}
};
// FIXME: Diagnose these in the template definition, not in the instantiation.
E<> e; // expected-note {{in instantiation of}}
template<typename T> struct Y : T {
void f() override;
void h() final;
};
template<typename T> struct Z : T {
void g() override; // expected-error {{only virtual member functions can be marked 'override'}}
void i() final; // expected-error {{only virtual member functions can be marked 'final'}}
};
Y<X> y;
Z<X> z; // expected-note {{in instantiation of}}
}
namespace MemberOfUnknownSpecialization {
template<typename T> struct A {
struct B {};
struct C : B {
void f() override;
};
};
template<> struct A<int>::B {
virtual void f();
};
// ok
A<int>::C c1;
template<> struct A<char>::B {
void f();
};
// expected-error@-13 {{only virtual member functions can be marked 'override'}}
// expected-note@+1 {{in instantiation of}}
A<char>::C c2;
template<> struct A<double>::B {
virtual void f() final;
};
// expected-error@-20 {{declaration of 'f' overrides a 'final' function}}
// expected-note@-3 {{here}}
// expected-note@+1 {{in instantiation of}}
A<double>::C c3;
}
namespace DiagnosticsQOI {
struct X {
virtual ~X();
virtual void foo(int x); // expected-note {{hidden overloaded virtual function}}
virtual void bar(int x); // expected-note 2 {{hidden overloaded virtual function}}
virtual void bar(float x); // expected-note 2 {{hidden overloaded virtual function}}
};
struct Y : X {
void foo(int x, int y) override; // expected-error {{non-virtual member function marked 'override' hides virtual member function}}
void bar(double) override; // expected-error {{non-virtual member function marked 'override' hides virtual member functions}}
void bar(long double) final; // expected-error {{non-virtual member function marked 'final' hides virtual member functions}}
};
template<typename T>
struct Z : T {
static void foo() override; // expected-error {{only virtual member functions can be marked 'override'}}
};
}
| true |
c7cdc70421a46332c5821f8be0a97785208afca3 | C++ | rpuntaie/c-examples | /cpp/types_is_trivially_copyable.cpp | UTF-8 | 778 | 3.125 | 3 | [
"MIT"
] | permissive | /*
g++ --std=c++20 -pthread -o ../_build/cpp/types_is_trivially_copyable.exe ./cpp/types_is_trivially_copyable.cpp && (cd ../_build/cpp/;./types_is_trivially_copyable.exe)
https://en.cppreference.com/w/cpp/types/is_trivially_copyable
*/
#include <iostream>
#include <type_traits>
struct A {
int m;
};
struct B {
B(B const&) {}
};
struct C {
virtual void foo();
};
struct D {
int m;
D(D const&) = default; // -> trivially copyable
D(int x): m(x+1) {}
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_trivially_copyable<A>::value << '\n';
std::cout << std::is_trivially_copyable<B>::value << '\n';
std::cout << std::is_trivially_copyable<C>::value << '\n';
std::cout << std::is_trivially_copyable<D>::value << '\n';
}
| true |
65425e588e21c889289f53622adb64253a3f86b3 | C++ | john801205/practice | /UVa/11218/11218.cpp | UTF-8 | 1,519 | 3.234375 | 3 | [] | no_license | #include <bitset>
#include <iostream>
#include <vector>
struct Group
{
int a, b, c, s;
Group(int a, int b, int c, int s): a(a), b(b), c(c), s(s) {}
};
int DFS(const std::vector<Group> &groups,
const std::vector<Group>::size_type start,
std::bitset<9> &people,
const int score)
{
if (people.all())
return score;
int max_score = -1;
for (auto i = start; i < groups.size(); i++)
{
if (people.test(groups[i].a)
or people.test(groups[i].b)
or people.test(groups[i].c))
continue;
people.set(groups[i].a);
people.set(groups[i].b);
people.set(groups[i].c);
auto current_score = DFS(groups, i+1, people, score + groups[i].s);
if (current_score > max_score)
max_score = current_score;
people.reset(groups[i].a);
people.reset(groups[i].b);
people.reset(groups[i].c);
}
return max_score;
}
int main(void)
{
int cases = 1;
int number_of_combinations;
while (std::cin >> number_of_combinations
and number_of_combinations != 0)
{
std::vector<Group> groups;
for (int i = 0; i < number_of_combinations; i++)
{
int a, b, c, s;
std::cin >> a >> b >> c >> s;
// change index from 1-9 to 0-8
a--;
b--;
c--;
groups.emplace_back(a, b, c, s);
}
std::bitset<9> people;
std::cout << "Case " << cases << ": " << DFS(groups, 0, people, 0) << '\n';
cases++;
}
return 0;
}
| true |
7ffe63fe26d97ce56bd442abafaa47574ccb6976 | C++ | polpo/espweather | /espweather.ino | UTF-8 | 5,922 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <ESP8266WiFi.h>
#include <ArduinoOTA.h>
#include <JsonStreamingParser.h>
#include "WeatherListener.h"
#include "icons.h"
#include "constants.h"
// spin while connecting to WiFi
const char spinner[] = {'/', '-', 0b11111011, 0b11111110};
void load_icon(const uint8_t icon[]) {
for (uint8_t c = 0; c < 8; c++) {
Serial.printf("\031");
Serial.printf("%c", c);
for (uint8_t d = 0; d < 8; d++) {
Serial.printf("%c", icon[(c * 8) + d]);
}
}
}
void print_icon_pt1() {
// Position cursor to upper left of screen
Serial.printf("\014");
Serial.printf("\200\201\202\203");
}
void print_icon_pt2() {
Serial.printf("\204\205\206\207 ");
}
void scroll_string(String &daily_str, String &weekly_str) {
bool is_daily = true;
String *str = &daily_str;
unsigned long start_time = millis();
int len = str->length();
int pos = 0;
while (true) {
ArduinoOTA.handle();
if (pos == 0) {
// Beginning of string
// Position cursor to start of scroll area
Serial.printf("\021\004\001");
if (is_daily) {
Serial.print("Today: ");
} else {
Serial.print("Coming up: ");
}
delay(1500);
}
// Position cursor to start of scroll area
Serial.printf("\021\004\001");
Serial.print(str->substring(pos, pos+12));
++pos;
delay(200);
if (pos == 1) {
delay(2000);
} else if (pos >= len - 12) {
// End of string
pos = 0;
if (is_daily) {
str = &weekly_str;
} else {
str = &daily_str;
}
len = str->length();
is_daily = !is_daily;
delay(2000);
}
// Break after scrolling for 1 hour
// TODO handle millis() overflow (70 days)
if (millis() - start_time > 3600000) {
break;
}
}
}
void setup() {
WiFi.mode(WIFI_STA);
// FIXME -- WiFi.begin is buggy. Work around: https://github.com/esp8266/Arduino/issues/2186
if (WiFi.status() != WL_CONNECTED) { // FIX FOR USING 2.3.0 CORE (only .begin if not connected)
WiFi.begin(ssid, password); // connect to the network
}
uint8_t spinner_index = 0;
// Initialize Crystalfontz display
Serial.begin(19200, SERIAL_8N1);
delay(1000);
// Reset display
Serial.printf("\032\032");
delay(2000);
// Set display contrast
Serial.printf("\017F");
// Hide cursor
Serial.printf("\004");
// Scroll off
Serial.printf("\024");
// Wrap off
Serial.printf("\030");
delay(1000);
// Associate with wifi
Serial.printf("Connecting to\r\n%s... ", ssid);
while (WiFi.status() != WL_CONNECTED) {
Serial.printf("\010%c", spinner[spinner_index++ % 4]);
delay(250);
}
Serial.printf("\014Connected! IP:\r\n");
IPAddress ip = WiFi.localIP();
Serial.printf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
delay(2000);
ArduinoOTA.setPassword("espweather");
ArduinoOTA.onStart([]() {
Serial.println("\014OTA Start");
});
ArduinoOTA.onEnd([]() {
Serial.print("\014OTA End");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("\014Progress: %u%%", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("\014OTA Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("\014Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("\014Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("\014Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("\014Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("\014End Failed");
});
ArduinoOTA.begin();
}
void loop() {
JsonStreamingParser parser;
WeatherListener listener;
ArduinoOTA.handle();
Serial.printf("\014Fetching url\r\n");
WiFiClientSecure client;
if (client.connect("api.darksky.net", 443)) {
Serial.printf("\014Connected\r\n");
} else {
Serial.printf("\014Error fetching");
delay(9999999);
}
client.printf("GET /forecast/%s/%s?exclude=currently,hourly,minutely,alerts,flags HTTP/1.1\r\n", api_key, latlong);
client.printf("Host: api.darksky.net\r\n");
client.printf("Connection: close\r\n");
client.printf("\r\n");
delay(10);
Serial.printf("\014Reading");
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.printf(".");
if (line == "\r") {
break;
}
}
Serial.printf("\014Parsing response\r\n");
parser.setListener(&listener);
while (client.connected()) {
parser.parse(client.read());
}
if (listener.icon == "snow") {
load_icon(snow);
} else if (listener.icon == "clear-day" || listener.icon == "clear-night") {
load_icon(clear_day); // TODO make icon for night
} else if (listener.icon == "party-cloudy-day" || listener.icon == "party-cloudy-night") {
load_icon(partly_cloudy_day); // TODO make icon for night
} else if (listener.icon == "fog") {
load_icon(cloudy); // TODO make icon for fog
} else if (listener.icon == "cloudy") {
load_icon(cloudy);
} else if (listener.icon == "wind") {
load_icon(wind);
} else if (listener.icon == "rain") {
load_icon(rain);
} else if (listener.icon == "sleet") {
load_icon(snow); // TODO make icon for sleet
} else {
load_icon(clear_day);
}
print_icon_pt1();
Serial.printf("%c %d\036\001\200 ", 0b11011110, listener.temperatureMax);
Serial.printf("%c %d\036\001\200\r\n", 0b11100000, listener.temperatureMin);
print_icon_pt2();
// Replace unicode degree symbol with blank. TODO handle multibyte degree symbol
// ("\036\001\200") while scrolling
listener.summary_daily.replace("°", "");
listener.summary_weekly.replace("°", "");
// Replace en dash with hyphen
listener.summary_daily.replace("–", "-");
listener.summary_weekly.replace("–", "-");
scroll_string(listener.summary_daily, listener.summary_weekly);
}
| true |
c2ef6c0cc2fbdf43143014f13730d4990a4948c0 | C++ | primenumber/LSmethod | /solver.cpp | UTF-8 | 1,108 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "solver.hpp"
#include <cmath>
#include <iostream>
#include <thread>
#include <future>
namespace math {
Real eps = 1.0;
Vector CGLSMethod(const SpMat &mat, const Vector &vec) {
Vector r = trans_mv(mat, vec);
Vector x(r.size());
Vector p, d, t;
std::future<Real> sqn_r_f = std::async(std::launch::async, sqnorm, std::ref(r));
d = vec;
p = r;
t = mat * p;
Real sqn_r = sqn_r_f.get();
for (int i = 0; i < 3000; ++i) {
if ((i % 10) == 0) std::cerr << i;
Real alpha = sqn_r / sqnorm(t);
fma(x, alpha, p);
fma(d, -alpha, t);
Vector old_r = r;
r = trans_mv(mat, d);
Real diff = abs(r);
if (diff < eps) break;
if ((i % 10) == 0) {
Vector err = mat * x - vec;
Real nd = abs(err) / sqrt(vec.size());
Real av = average(err);
Real mx = alpha * max(p);
std::cerr << ' ' << diff << ' ' << nd << ' ' << av << ' ' << mx << '-' << '\r';
}
Real old_sqn_r = sqn_r;
sqn_r = sqnorm(r);
Real beta = sqn_r / old_sqn_r;
p = r + beta * p;
t = mat * p;
}
std::cerr << '\n';
return x;
}
} // namespace math
| true |
41353d20af53c8b5d2d98812bd5110859cd32b38 | C++ | btcup/sb-admin | /exams/2558/02204111/1/midterm/2_2_713_5820501110.cpp | UTF-8 | 1,074 | 3.125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main ()
{
char A,a,B,b,C,c,wa,flr;
int h,w,d,pa,pb,pc;
float va,vb,vc;
cout << "Welcome to The Fantastic Tiles!!" << endl;
cout << "Please enter room size in meter (H x W x D) : ";
cin >> h >> w >> d ;
cout << "Please select floor tile. . .(A/B/C): ";
cin >> flr ;
if (flr=='A' || flr=='a')
{ va = 0.3*0.3 ;
pa = 55 ;
}
else if (flr=='B' || flr=='b')
{ vb = 0.45*0.45 ;
pb = 80 ;
}
else { vc = 0.6*0.6 ;
pc = 90 ;
}
cout << endl;
cout << "Please select wall tile. . .(A/B/C): ";
cin >> wa ;
if (wa=='A' || wa=='a')
{ va = 0.2*0.2 ;
pa = 17 ;
}
else if (wa=='B' || wa=='b')
{ vb = 0.2*0.3 ;
pb = 32 ;
}
else { vc = 0.3*0.3 ;
pc = 50 ;
}
cout << endl;
cout << " - - - - - - - " << endl;
cout << "Number of floor tile : " ;
cout << "Number of wall";
system ("pause");
return 0 ;
}
| true |
7c2d5e2612f1d4056cfed83a624fef316a1556c0 | C++ | rie1010/multi-h | /MultiH/MultiH/moduls/feature_detection/EllipticKeyPoint.cpp | UTF-8 | 2,617 | 2.671875 | 3 | [] | no_license | #define _USE_MATH_DEFINES
#include <cmath>
#include "EllipticKeyPoint.h"
EllipticKeyPoint::EllipticKeyPoint() : cv::KeyPoint()
{
this->transformation = cv::Mat_<double>::eye(2,2);
}
EllipticKeyPoint::~EllipticKeyPoint()
{
}
EllipticKeyPoint::EllipticKeyPoint(const EllipticKeyPoint& ekp) : cv::KeyPoint(ekp)
{
this->transformation = ekp.transformation.clone();
this->ownAffinity = ekp.ownAffinity.clone();
}
EllipticKeyPoint::EllipticKeyPoint(const cv::KeyPoint& kp, const cv::Mat_<double> Ai) : cv::KeyPoint(kp)
{
double rad = kp.size;;
CV_Assert( rad );
double angle = M_PI * (double)kp.angle/180.;
double alpha = cos(angle) * rad;
double beta = sin(angle) * rad;
cv::Mat M(2, 2, CV_64F);
double* m = M.ptr<double>();
m[0] = alpha;
m[1] = -beta;
m[2] = beta;
m[3] = alpha;
this->transformation = M.clone(); // asszem ez visz a fícsör szpészbe, de lehet hogy az inverze?! nem hiszem...
// apply Ai (utolso elotti egyenlet a pdfben)
this->pt = applyAffineHomography(Ai, this->pt);
cv::Mat_<double> Ai_block22 = Ai.colRange(0,2);
this->transformation = Ai_block22 * this->transformation;
}
cv::Point2d EllipticKeyPoint::applyAffineHomography(const cv::Mat_<double>& H, const cv::Point2d& pt)
{
return cv::Point2d(((H(0, 0)*pt.x + H(0, 1)*pt.y + H(0, 2))), ((H(1, 0)*pt.x + H(1, 1)*pt.y + H(1, 2))));
}
void EllipticKeyPoint::convert( const std::vector<cv::KeyPoint>& src, std::vector<EllipticKeyPoint>& dst )
{
/* if( !src.empty() )
{
dst.resize(src.size());
for( size_t i = 0; i < src.size(); i++ )
{
dst[i] = EllipticKeyPoint( src[i] );
}
}*/
}
void EllipticKeyPoint::convert( const std::vector<EllipticKeyPoint>& src, std::vector<cv::KeyPoint>& dst )
{
/*if( !src.empty() )
{
// TODO
dst.resize(src.size());
for( size_t i = 0; i < src.size(); i++ )
{
cv::Size_<double> axes = src[i].getAxes();
double rad = sqrt(axes.height*axes.width);
dst[i] = cv::KeyPoint(src[i].pt, 2*rad );
}
}*/
}
// solveQuadratic needed...
/*cv::Size_<double> EllipticKeyPoint::getAxes() const
{
auto ellipse = getEllipse();
double a = ellipse[0], b = ellipse[1], c = ellipse[2];
double ac_b2 = a*c - b*b;
double x1, x2;
solveQuadratic(1., -(a+c), ac_b2, x1, x2);
double width = double(1./sqrt(x1));
double height = double(1./sqrt(x2));
return cv::Size_<double>(width, height);
}
cv::Scalar EllipticKeyPoint::getEllipse() const
{
return cv::Scalar(transformation(0,0), transformation(1,0), transformation(1,1));
}*/ | true |
240d895862f5f504211cff1dac2b6b71114cafae | C++ | seddon-software/cplusplus | /A4_Boost/DateTime/11.TimeIterators.cpp | UTF-8 | 717 | 3.265625 | 3 | [] | no_license | #include "boost/date_time/posix_time/posix_time.hpp"
#include <iostream>
using namespace std;
int main()
{
using namespace boost::posix_time;
using namespace boost::gregorian;
//get the current time from the clock -- one second resolution
ptime now = second_clock::local_time();
//Get the date part out of the time
date today = now.date();
date tommorrow = today + days(1);
ptime tommorrow_start(tommorrow); //midnight
time_duration remaining = tommorrow_start - now;
cout << "Time left till midnight: " << remaining << endl;
//iterator adds by one hour
for(time_iterator iterator(now, hours(1)); iterator < tommorrow_start; ++iterator)
{
cout << *iterator << endl;
}
}
| true |
3f71eaacbb6ebf3a6265f1d5d29d5d51bba33eb7 | C++ | AnneLivia/Competitive-Programming | /Online Judges/URI/2750/main.cpp | UTF-8 | 505 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n[16];
for ( int i = 0; i < 16; i++)
n[i] = i;
cout << "---------------------------------------\n";
cout << "| decimal | octal | Hexadecimal |\n";
cout << "---------------------------------------\n";
for(int i = 0; i < 16; i++) {
printf("| %2d | %2o | %X |\n",n[i],n[i],n[i]);
}
cout << "---------------------------------------\n";
return 0;
}
| true |
9ba82f856a7ab3af5bf5c0ca2f427a23fc1969a7 | C++ | p4ajst/avoiding | /avoiding/GameSource/Object/Character.h | UTF-8 | 1,760 | 2.75 | 3 | [] | no_license | // ------------------------------------------------------------------------------------------------ //
// @ file : Character.h //
// @ brief : キャラクターに関するクラス //
// @ date : 2017/06/25 //
// @ author : Madoka Nakajima //
// @ note : //
// ------------------------------------------------------------------------------------------------ //
/* 多重インクルードの防止 */
#pragma once
/* ヘッダファイルのインクルード */
// 自作ヘッダファイル
#include "Actor.h"
#include "../Stage/Map.h"
/* クラス宣言 */
class Character :public Actor
{
/* メンバ変数 */
private:
// 速度
DirectX::SimpleMath::Vector3 mVelocity;
// 歩数
int mStepCount;
// マップの情報
std::shared_ptr<Map> mMap;
// 移動中であるか
bool mIsMoving;
// 出発点
DirectX::SimpleMath::Vector3 mSource;
// 目的地
DirectX::SimpleMath::Vector3 mDestination;
// 移動割合
int mMoveRate;
/* メンバ関数 */
public:
// コンストラクタ
Character() = default;
// デストラクタ
~Character() = default;
// 初期化
void Initialize(int sx, int sz);
// 移動
void Move(int ox,int oz,int sx,int sz);
// 落下
void Fall();
// 設定
void SetVel(DirectX::SimpleMath::Vector3 vel) { mVelocity = vel; }
// 取得
DirectX::SimpleMath::Vector3 GetVel() { return mVelocity; }
int GetCount() { return mStepCount; }
};
| true |
43356ba955da46c6e99753f36ef537cf7477449b | C++ | manhtung001/Datastructure-Algorithm-PTIT | /contest/Contest2/bai26.cpp | UTF-8 | 470 | 3 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void Try(string s, int k, string &max){
if(k==0) return;
int n=s.length();
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(s[i]<s[j]){
swap(s[i], s[j]);
if(s.compare(max)>0) max=s;
Try(s, k-1, max);
swap(s[i], s[j]);
}
}
}
}
int main(){
int t; cin>>t;
while(t--){
int k; cin>>k;
string s;cin>>s;
string max=s;
Try(s, k, max);
cout<<max<<endl;
}
}
| true |
095c5b2cefce16511d82e65527a6ba15237c4f3d | C++ | russellgrim/6_axis_arm | /Main/Joint.cpp | UTF-8 | 1,317 | 3.21875 | 3 | [] | no_license |
#include "Joint.h"
//--------------------------- Joints ---------------------------
Joint::Joint (int attachTo , int homeAngle) :
pin(attachTo),
homePosition(homeAngle) {}
void Joint::setup() {
servo.attach(pin);
servo.write(homePosition);
currentPosition = homePosition;
}
void Joint::loop() {
// Serial.print("isMoving = "); Serial.println(isMoving);
if (isMoving == true) {
updateNextStep ();
moveToNextStep ();
}
}
int Joint::updateNextStep () {
if (stepNum >= numOfSteps) {
currentPosition = nextPosition;
isMoving = false;
Serial.println("movement finished");
} else {
nextStep = currentPosition + stepNum * stepSize;
Serial.print("nextStep ="); Serial.println(nextStep);
Serial.print("stepNum ="); Serial.println(stepNum);
stepNum ++;
}
}
void Joint::moveToNextStep () {
servo.write(nextStep);
}
void Joint::setNextPosition (int _nextPosition , int _numOfSteps ) {
Serial.println("setting nextPosition to ");Serial.println(_nextPosition);
isMoving = true;
nextPosition = _nextPosition;
numOfSteps = _numOfSteps;
stepNum = 0;
Serial.print("isMoving = "); Serial.println(isMoving);
stepSize = (nextPosition - currentPosition)/(numOfSteps - 1);
Serial.print("stepsize ="); Serial.println(stepSize);
}
| true |
e121ffe3cc15ac942add4dfc7144175b0209cfa3 | C++ | Omar6re/Online-Judges | /Codeforces/263A - BeautifulMatrix.cpp | UTF-8 | 854 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main (){
int t = 4;
int z[t];
int x[t];
int w[t];
int y[t];
int g[t];
int i;
int b;
int c;
int r1;
int r2;
int r;
b = 0;
c = 0;
r1 = 0;
r2 = 0;
r = 0;
i = 0;
for (i = 0; i < 5; i++){
cin >> z[i];
if (z[i] != 0){
b = i;
c = 0;
}
}
for (i = 0; i < 5; i++){
cin >> x[i];
if (x[i] != 0){
b = i;
c = 1;
}
}
for (i = 0; i < 5; i++){
cin >> w[i];
if (w[i] != 0){
b = i;
c = 2;
}
}
for (i = 0; i < 5; i++){
cin >> y[i];
if (y[i] != 0){
b = i;
c = 3;
}
}
for (i = 0; i < 5; i++){
cin >> g[i];
if (g[i] != 0){
b = i;
c = 4;
}
}
if (b == 2 && c == 2){
cout << 0;
return 0;
} else {
r1 = 2 - b;
r2 = 2 - c;
r1 = abs (r1);
r2 = abs (r2);
r = r1 + r2;
cout << r;
return 0;
}
}
| true |
20eeb52a73c91846dacde0a630ae7ba3708f8170 | C++ | chengwuxinlin/EE553-CPP | /session07/testreadbmp.cc | UTF-8 | 2,366 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
#if 0
template<typename T>
void read(istream& f, T& val) {
f.read((char*)&val, sizeof(T));
// TODO: flip if bigendian
}
#endif
void read(istream& f, uint32_t& val) {
f.read((char*)&val, sizeof(int));
// TODO: flip if bigendian
}
void read(istream& f, uint16_t& val) {
f.read((char*)&val, sizeof(uint16_t));
// TODO: flip if bigendian
}
class BMPHeader {
public:
uint16_t type;
uint32_t size;
uint16_t reserved1;
uint16_t reserved2;
uint32_t off_bits;
uint32_t size2; // size of the data w * h * sizeperpixel
uint32_t width;
uint32_t height;
uint16_t planes;
uint16_t bitCount; // 24?
uint32_t compression; // FALSE
uint32_t imageSize; //???
uint32_t xPixelsPerMeter; // everything past here don't care...
uint32_t yPixelsPerMeter;
uint32_t clrUsed;
uint32_t clrImportant;
public:
BMPHeader(ifstream& f) {
read(f, type);
read(f, size);
read(f, reserved1);
read(f, reserved2);
read(f, off_bits);
read(f, size2); // size of the data w * h * sizeperpixel
read(f, width);
read(f, height);
read(f, planes);
read(f, bitCount); // 24?
read(f, compression); // FALSE
read(f, imageSize); //???
read(f, xPixelsPerMeter); // everything past here don't care...
read(f, yPixelsPerMeter);
read(f, clrUsed);
read(f, clrImportant);
}
friend ostream& operator <<(ostream& s, const BMPHeader& b) {
return s << b.type << ' ' <<
b.size << ' ' <<
b.reserved1 << ' ' <<
b.reserved2 << ' ' <<
b.off_bits << ' ' <<
b.size2 << ' ' << // size of the data w * h * sizeperpixel
b.width << ' ' <<
b.height << ' ' <<
b.planes << ' ' <<
b.bitCount << ' ' << // 24?
b.compression << ' ' << // FALSE
b.imageSize << ' ' << //???
b.xPixelsPerMeter << ' ' << // everything past here don't care...
b.yPixelsPerMeter << ' ' <<
b.clrUsed << ' ' <<
b.clrImportant;
}
};
#if 0
class Bitmap {
private:
int width, height;
uint32_t* pixels;
};
#endif
int main() {
ifstream f("red10x10.bmp", ios::binary);
BMPHeader bh(f);
cout << bh;
cout << hex;
const int width = 10, height = 10;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
uint32_t color = 0; // R G B A read as B G R
f.read( ((char*)&color) + 1, 3);
cout << color << ' ';
}
cout << "\n";
}
}
| true |
756b3191740c450c1b62f00a33a38f23bce97eb2 | C++ | LaelRodrigues/Atividade7 | /src/questao03/main3.cpp | UTF-8 | 664 | 2.96875 | 3 | [] | no_license | /**
* @file main3.cpp
* @brief Codigo fonte de teste da funcao que calcula o
* valor de uma determinada expressao escrita na
* notacao polonesa inversa
* presente no aquivo imprime.h
* @author LaelRodrigues (laelRodrigues7@gmail.com)
* @since 08/06/2017
* @date 08/06/2017
*/
#include <iostream>
using std::cout;
using std::endl;
#include "rpn.h"
/** @brief Funcao principal */
int main(int argc, char* argv[]) {
if(argc < 2){
cout << "Erro: a expressao nao foi digitada." << endl;
return EXIT_FAILURE;
}
int result = calcValorExpressao(argc, argv);
cout << "O valor resultante da expressao e: " << result << endl;
return EXIT_SUCCESS;
return 0;
} | true |
9533dd443a5c889c64acd8c6e4e670c37cf38e4b | C++ | YueLeeGitHub/algorithm | /leetcode/number/xor/1738.cpp | UTF-8 | 915 | 3.109375 | 3 | [] | no_license | // https://leetcode-cn.com/problems/find-kth-largest-xor-coordinate-value/
// Created by admin on 2021/5/19.
// 前缀异或+优先队列
class Solution {
public:
int kthLargestValue(vector<vector<int>>& matrix, int k) {
int m,n;
m = matrix.size();
n = matrix[0].size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
// 小顶堆,存大一半的
priority_queue<int, vector<int>, greater<int>> small_heap;
for(int i=1;i<=m;++i){
for(int j=1;j<=n;++j){
dp[i][j]=dp[i][j-1]^dp[i-1][j]^dp[i-1][j-1]^matrix[i-1][j-1];
if(small_heap.size()<k){
small_heap.push(dp[i][j]);
}else if(small_heap.top()<dp[i][j]){
small_heap.push(dp[i][j]);
small_heap.pop();
}
}
}
return small_heap.top();
}
}; | true |
6accd190ea984191cb82e7a913de68d165fbae22 | C++ | wallabra/xhack | /src/matrix.cpp | UTF-8 | 1,991 | 3.375 | 3 | [
"MIT"
] | permissive | #include <assert.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstdio>
using std::setw;
#include "matrix.h"
Matrix::Matrix(unsigned short rows, unsigned short cols, double* data) {
this->rows = rows;
this->cols = cols;
this->data = new double[rows * cols];
if (data != 0)
std::copy(data, data + this->rows * this->cols, this->data);
}
double* Matrix::get(unsigned short col, unsigned short row) {
if (col == 0 && row == 0) return this->data;
return this->data + (row * this->cols + col);
}
double Matrix::getn(unsigned short col, unsigned short row) {
if (col == 0 && row == 0) return *this->data;
return this->data[row * this->cols + col];
}
void Matrix::setn(unsigned short col, unsigned short row, double n) {
if (col == 0 && row == 0) this->data[0] = n;
this->data[row * this->cols + col] = n;
}
Matrix Matrix::T() {
Matrix res(this->cols, this->rows);
for (unsigned short r = 0; r < this->rows; r++)
for (unsigned short c = 0; c < this->cols; c++)
*(res.get(r, c)) = this->getn(c, r);
return res;
}
void Matrix::print() {
for (unsigned short r = 0; r < this->rows; r++) {
std::cout << "| ";
for (unsigned short c = 0; c < this->cols; c++)
std::cout << setw(13) << this->getn(c, r) << "; ";
std::cout << "|" << std::endl;
}
// debug purposes
printf(" DATA ARRAY ADDRESS = %p\n", this->data);
std::cout << std::endl;
}
Matrix Matrix::operator* (Matrix B) {
assert(this->cols == B.rows);
Matrix res(this->rows, B.cols, 0);
for (unsigned short r1 = 0; r1 < this->rows; r1++)
for (unsigned short r2 = 0; r2 < B.cols; r2++) {
double prod = 0;
for (unsigned short i = 0; i < this->cols; i++)
prod += this->getn(i, r1) * B.getn(r2, i);
res.setn(r2, r1, prod);
}
return res;
}
Matrix::~Matrix() {
delete[] this->data;
}
| true |
a0fc4cc0e1348a09f3efcf0052c122677df48495 | C++ | barongeng/vSLAM-2 | /cpp/tf.cpp | UTF-8 | 2,016 | 3.140625 | 3 | [] | no_license | /// Matrix operations
// All the matrices are saved in OpenGL-compatible 4x4 matrices (column-major order)
#include "tf.h"
#include <math.h>
#define PI 3.141592653589793
// 2D matrix element intexing
#define I(m,row,col) m[row + col*4]
// Switch some axes, ROS -> our algorithm
double axes[] = {0,0,1,0 , -1,0,0,0 , 0,-1,0,0 , 0,0,0,1};
// ... and back
double invaxes[] = {0,-1,0,0 , 0,0,-1,0 , 1,0,0,0 , 0,0,0,1};
// Correct the angle offset of /omnicam. So that the robot rides in the direction
// of the z-axis. This works atleast for the czech robot.
const double alpha = 54 * PI/180; // 54 deg., something to do with the pentagonal shape of the camera rig
double rotm[] = {cos(alpha),sin(alpha),0,0 , -sin(alpha),cos(alpha),0,0 , 0,0,1,0 , 0,0,0,1};
// ...and back.
double invrotm[] = {cos(-alpha),sin(-alpha),0,0 , -sin(-alpha),cos(-alpha),0,0 , 0,0,1,0 , 0,0,0,1};
/// Left multiplication.
// In pseudocode: m = ml * m
static void lmult(double *m, double *ml)
{
double tmp[16] = {};
for (int row = 0; row < 4; row++)
for (int col = 0; col < 4; col++)
for (int k = 0; k < 4; k++)
I(tmp,row,col) += I(ml,row,k) * I(m,k,col);
for (int i = 0; i < 16; i++)
m[i] = tmp[i];
}
/// Right multiplication.
// In pseudocode: m = m * mr
static void rmult(double *m, double *mr)
{
double tmp[16] = {};
for (int row = 0; row < 4; row++)
for (int col = 0; col < 4; col++)
for (int k = 0; k < 4; k++)
I(tmp,row,col) += I(m,row,k) * I(mr,k,col);
for (int i = 0; i < 16; i++)
m[i] = tmp[i];
}
/// Convert an OpenGL matrix from a ROS coordinate system to a sensible one.
// The sensible one is the one used by my Haskell code :)
// All matrices are in the GL format: {col1,col2,col3,col4}
void to_my_coords(double *m)
{
lmult(m, invrotm);
lmult(m, axes);
rmult(m, rotm);
rmult(m, invaxes);
}
/// Convert an OpenGL matrix from our represintation to the ROS coordinate system
void from_my_coords(double *m)
{
lmult(m, invaxes);
lmult(m, rotm);
rmult(m, axes);
rmult(m, invrotm);
}
| true |
030c3f72772af2dfbbcd4b5bb9b88d86bebb5c8a | C++ | FoolingBears101/Example_1 | /TODO1/remoteControl/remoteControl.ino | UTF-8 | 2,480 | 2.796875 | 3 | [] | no_license | #include <ArduinoJson.h>
#include <Arduino.h>
#include <analogWrite.h>
#include "OneWire.h"
#include "DallasTemperature.h"
#define TRUE 1
#define FALSE 0
String receivedStr;
// Numero de pins a modifié suivant votre carte.
// les pins actuels correspond au branchement pour une carte ESP32 clone(chinois)
const int tempPin = 32;
const int redLedPin = 5;
const int blueLedPin = 17;
const int lightSensorPin = 14;
OneWire oneWire(tempPin);
DallasTemperature tempSensor(&oneWire);
StaticJsonDocument<200> jsonBuffer;
DeserializationError JsonError;
void setup() {
Serial.begin(9600);
tempSensor.begin();
pinMode(redLedPin, OUTPUT);
pinMode(blueLedPin, OUTPUT);
}
void loop() {
float t; // variable qui va recevoir la valeur du capteur de temperature
int lightSensor; // capteur de lumiére
int redState = LOW, blueState = LOW;
int command = 99;
tempSensor.requestTemperaturesByIndex(tempPin);
t = tempSensor.getTempCByIndex(0);
lightSensor = analogRead(lightSensorPin); // read analog input : light
Serial.print(F("{\n\"temperature\": \"")) ;
Serial.print(t);
Serial.print(F("\",\n\"light\": \""));
Serial.print(String(lightSensor));
Serial.print(F("\",\n\"greenLed\": \"" ));
Serial.print(String(blueState));
Serial.print(F("\",\n\"redLed\": \"" ));
Serial.print(String(redState));
Serial.print(F("\",\n}\n")) ;
while(Serial.available() > 0) {
receivedStr = Serial.readStringUntil('\n');
}
Serial.print(receivedStr);
JsonError = deserializeJson(jsonBuffer,receivedStr);
command = jsonBuffer["command"];
Serial.println(command);
if ((command != 99) and (command == 1)) // using the command instruction found in the JSON file received,
// determine which LED to light up
{
blueState = HIGH; // room is hot
redState = LOW;
} else if ((command != 99) and (command == 2))
{
blueState = LOW; // room is cold
redState = HIGH;
} else if ((command == 99) or JsonError)
{
blueState = HIGH; // never recieved any signal or json parser error
redState = HIGH;
} else {
blueState = LOW; // in the perfect range of temperature
redState = LOW;
}
digitalWrite(blueLedPin, blueState);
digitalWrite(redLedPin, redState);
delay(5000);
}
| true |
1bf4fa1eaca35ab3bec9f110e464d6a5c0a77844 | C++ | Kewth/OJStudy | /hdu869_1002.cpp | UTF-8 | 2,119 | 2.875 | 3 | [] | no_license | #if 0
2019.08.23
由于 a 是个排列,对于每个 a[i] = x 设 b[x] = i 。
修改操作相当于删掉一个点,在 b 上就是令 b[x] = INF 。
询问操作就是找到不小于 k 的最小 x 满足 b[x] > r 。
先不考虑修改,处理询问,发现一次二分后问题转换为 rmq ,
具体地,二分 x 判断答案是否在 [k, x] 内,那么 check 就是求 b[k:x] 的最大值。
用线段树维护最大值的话,不仅能解决这个问题,还能轻松处理修改。
但是套上二分是 O(log^2n) 的。
考虑使用 ST 表,虽然 ST 表不支持修改,但是对于修改操作有其他处理方法。
把删掉的点加入到 set 里边,那么询问中二分时直接把上界设为大于 k 的最小删除数即可。
#endif
#include <cstdio>
#include <set>
#include <vector>
#define debug(...) fprintf(stderr, __VA_ARGS__)
inline int input() { int x; scanf("%d", &x); return x; }
const int maxn = 500005, maxk = 20;
int st[maxn][maxk];
int a[maxn];
int highbit[maxn << 1];
int num[maxn];
int query(int l, int r) {
int x = highbit[(r - l) + 1];
return std::max(st[l][x], st[r - (1 << x) + 1][x]);
}
int main() {
int T = input();
while(T --) {
int n = input(), q = input();
for(int i = 1; i <= n; i ++) {
num[i] = input();
st[num[i]][0] = a[num[i]] = i;
}
for(int k = 0; k < maxk and (1 << k) <= n; k ++)
for(int i = (1 << k); i < (1 << (k + 1)); i ++)
highbit[i] = k;
for(int k = 1; k < maxk and (1 << k) <= n; k ++)
for(int i = 1; i <= n; i ++)
st[i][k] = std::max(st[i][k - 1], st[i + (1 << (k - 1))][k - 1]);
int ans = 0;
std::set<int> erase;
erase.insert(n + 1);
while(q --) {
int typ = input();
if(typ == 1) {
int pos = input() ^ ans;
erase.insert(num[pos]);
}
else if(typ == 2) {
int R = input() ^ ans, k = input() ^ ans;
int l = k, r = *erase.lower_bound(k);
while(l < r) {
int mid = (l + r) >> 1;
/* debug("%d-%d: %d\n", k, mid, query(k, mid)); */
if(query(k, mid) <= R)
l = mid + 1;
else
r = mid;
}
printf("%d\n", ans = l);
}
}
}
}
| true |
d8078778c981bc089986cc2993dc8efcc9dabd14 | C++ | venusshum/MakeMe | /Sketches/140611-shakeTemp/MakeMe3/TemperatureLEDs.ino | UTF-8 | 1,325 | 3.109375 | 3 | [] | no_license | float baseTemp = 0;
void TemperatureLEDs() {
uint16_t r, b, g;
//int t;
float t;
int TBLUE = baseTemp;
int TRED = baseTemp + 5;
int TRANGE = TRED - TBLUE;
for (int i=0;i<100; i++)
t = (i*t + getTemp())/(i+1);
// Choose the next point in RGB space by temperature - this is a
// linear scale that maps from pure blue for the coldest to pure
// red for the hottest, with intermediate temperatures
// represented by the appropriate mixture of blue and red.
//
// We constrain the temperature so that the lowest temperature we
// represent is TBLUE and the highest is TRED. MAX_BRIGHTNESS is
// the maximum we can set an LED channel to.
//
r = (constrain(t - TBLUE, 0, TRANGE) * 255) / TRANGE;
b = (constrain(TRED - t, 0, TRANGE) * 255) / TRANGE;
// Now set the colour of the all the LEDs appropriately.
analogWrite(ledB, 255-b);
analogWrite(ledR, 255-r);
}
int getTemp(){
ADCSRA |= (1 << ADSC); //Start temperature conversion
while (bit_is_set(ADCSRA, ADSC)); //Wait for conversion to finish
byte low = ADCL;
byte high = ADCH;
int temperature = (high << 8) | low; //Result is in kelvin
return temperature - 273;
}
void setBaseTemp(){
for (int i=0;i<500; i++)
baseTemp = (i*baseTemp + getTemp())/(i+1);
}
| true |
b9a85dcb505cd48ec878a316bbff4a687d9a8d33 | C++ | rahul-ramadas/leetcode | /find-minimum-in-rotated-sorted-array/Solution.13518195.cpp | UTF-8 | 628 | 2.96875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int findMin(vector<int> &num) {
int low = 0;
int high = num.size() - 1;
while (low < high)
{
if (num[low] < num[high])
{
return num[low];
}
int middle = low + (high - low) / 2;
if (num[middle] >= num[low])
{
low = middle + 1;
}
else // if (num[middle] < num[low])
{
high = middle;
}
}
return num[low];
}
};
| true |
270321a1e451b31ad23abe7d7292842598f28a77 | C++ | sidorovis/cpp_craft_1013 | /solutions/max_kaskevich/6/tests/multicast_communication_tests/udp_listener_tests.cpp | UTF-8 | 1,794 | 2.515625 | 3 | [] | no_license | #include "test_registrator.h"
#include <udp_listener.h>
#include <cstring>
namespace multicast_communication
{
namespace tests_
{
namespace detail
{
void service_thread( boost::asio::io_service& service );
}
}
}
void multicast_communication::tests_::detail::service_thread( boost::asio::io_service& service )
{
service.run();
}
void multicast_communication::tests_::udp_listener_tests()
{
BOOST_CHECK_NO_THROW
(
boost::asio::io_service service;
udp_listener uw( service, "224.0.0.0", 50000, []( const std::string& str) -> void {} );
);
{
boost::mutex mtx;
boost::condition_variable cond;
bool callback_checked = false;
boost::asio::io_service service;
udp_listener uw( service, "224.0.0.0", 50000, [&]( const std::string& str) -> void {
BOOST_CHECK_EQUAL( strcmp( str.c_str(), "hello world" ), 0 );
callback_checked = true;
cond.notify_one();
} );
const std::string buffer( "hello world" );
boost::asio::ip::udp::endpoint endpoint( boost::asio::ip::address::from_string( "224.0.0.0" ), 50000 );
boost::asio::ip::udp::socket socket( service, endpoint.protocol() );
boost::thread receive_messages( boost::bind( detail::service_thread, boost::ref( service ) ) );
socket.send_to( boost::asio::buffer( buffer ), endpoint );
boost::unique_lock< boost::mutex > lock( mtx );
auto timeout = boost::chrono::milliseconds( 2000 );
while ( !callback_checked && cond.wait_for( lock, timeout ) == boost::cv_status::no_timeout )
{}
service.stop();
receive_messages.join();
BOOST_CHECK_EQUAL( callback_checked, true );
}
}
| true |
f40d48794d299ed08038cd23fcc510bdcc152993 | C++ | LuisRGameloft/PubBus | /test/MessageBusTest.cpp | UTF-8 | 1,899 | 3.21875 | 3 | [
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | #include "catch.hpp"
#include <PubBus/Message.hpp>
#include <PubBus/MessageBus.hpp>
TEST_CASE("Adding subscriber returns a valid SubscriberHandle", "[MessageBus]")
{
// Arrange
class DummyMessage : public pub::Message
{
};
pub::MessageBus bus;
// Act
pub::SubscriberHandle handle = bus.subscribe<DummyMessage>([](DummyMessage msg) {});
// Assert
REQUIRE(bus.validate<DummyMessage>(handle) == true);
}
TEST_CASE("Adding different message subscribers returns valid handles", "[MessageBus]")
{
// Arrange
class DummyMessageOne : public pub::Message
{
};
class DummyMessageTwo : public pub::Message
{
};
pub::MessageBus bus;
// Act
pub::SubscriberHandle handle_one = bus.subscribe<DummyMessageOne>([](DummyMessageOne msg) {});
pub::SubscriberHandle handle_two = bus.subscribe<DummyMessageTwo>([](DummyMessageTwo msg) {});
// Assert
REQUIRE(bus.validate<DummyMessageOne>(handle_one) == true);
REQUIRE(bus.validate<DummyMessageTwo>(handle_two) == true);
}
TEST_CASE("Validating subscribers for different messages returns false", "[MessageBus]")
{
// Arrange
class DummyMessageOne : public pub::Message
{
};
class DummyMessageTwo : public pub::Message
{
};
pub::MessageBus bus;
// Act
pub::SubscriberHandle handle_one = bus.subscribe<DummyMessageOne>([](DummyMessageOne msg) {});
pub::SubscriberHandle handle_two = bus.subscribe<DummyMessageTwo>([](DummyMessageTwo msg) {});
// Assert
REQUIRE(bus.validate<DummyMessageOne>(handle_two) == false);
REQUIRE(bus.validate<DummyMessageTwo>(handle_one) == false);
}
TEST_CASE("Publishing message calls subscriber", "[MessageBus]")
{
// Arrange
class DummyMessage : public pub::Message
{
};
bool called = false;
pub::MessageBus bus;
DummyMessage msg;
bus.subscribe<DummyMessage>([&called](DummyMessage msg) { called = true; });
// Act
bus.publish(msg);
// Assert
REQUIRE(called == true);
}
| true |
5dac4515747697d5f264434aa677b5dce00dafdd | C++ | iamdatyoung1/EnginesProjectFull | /EnginesProject/EnginesProject/Engine/Camera/Camera.cpp | UTF-8 | 2,599 | 3.046875 | 3 | [] | no_license | #include "Camera.h"
#include "../Core/CoreEngine.h"
Camera::Camera(): position(glm::vec3()), fieldOfView(0.0f), forward(glm::vec3()), up(glm::vec3()),
right(glm::vec3()), worldUp(glm::vec3()), nearPlane(0.0f), farPlane(0.0f),
yaw(0.0f), pitch(0.0f), perspective(glm::mat4()), orthographic(glm::mat4()), view(glm::mat4())
{
fieldOfView = 45.0f;
forward = glm::vec3(0.0f, 1.0f, 0.0f);
up = glm::vec3(0.0f, 1.0f, 0.0f);
worldUp = up;
nearPlane = 2.0f;
farPlane = 50.0f;
//if this was set to 0 then it will be pointed to the right
yaw = -90.0f;
//direction of camera looking up and down
pitch = 0.0f;
perspective = glm::perspective(fieldOfView,
CoreEngine::GetInstance()->GetScreenWidth() /
CoreEngine::GetInstance()->GetScreenHeight(),
nearPlane, farPlane);
//left and right plane
orthographic = glm::ortho(0.0f, CoreEngine::GetInstance()->GetScreenWidth(),
0.0f, CoreEngine::GetInstance()->GetScreenHeight(), -1.0f, 1.0f);
UpdateCameraVectors();
}
Camera::~Camera()
{
if (lightsources.size() > 0) {
//This will create temp local var
//auto means will auto set key type
//auto is not needed but do it anyways
for (auto m : lightsources) {
delete m;
m = nullptr;
}
lightsources.clear();
}
}
void Camera::SetPosition(glm::vec3 position_)
{
position = position_;
UpdateCameraVectors();
}
void Camera::SetRotation(float yaw_, float pitch_)
{
yaw = yaw_;
pitch = pitch_;
UpdateCameraVectors();
}
void Camera::AddLightSources(LightSource* lightsources_)
{
lightsources.push_back(lightsources_);
}
glm::mat4 Camera::GetView() const
{
return view;
}
glm::mat4 Camera::GetOrthographic() const
{
return orthographic;
}
glm::vec3 Camera::GetPosition() const
{
return position;
}
glm::mat4 Camera::GetPerspective() const
{
return perspective;
}
std::vector<LightSource*> Camera::GetLightsources() const
{
return lightsources;
}
void Camera::UpdateCameraVectors()
{
//update for all
//humans like to think in degrees but computers like to use radians *VERY IMPORTENT*
//always convert to radians *VERY IMPORTENT*
forward.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
forward.y = sin(glm::radians(pitch));
forward.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
forward = glm::normalize(forward);
right = glm::normalize(glm::cross(forward, worldUp));
up = glm::normalize(glm::cross(right, forward));
//this will always keep looking at targets direction
view = glm::lookAt(position, position + forward, up);
}
| true |
3d680db87daf20a0e1c2a22bdf14df965b9fdda7 | C++ | angelgomezsa/Cplusplus | /Dubtes/Consolidation 3/ex10-3.cc | UTF-8 | 4,447 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
struct Enviament {
string dni;
string exer;
int temps;
string res;
};
struct exercici {
string nom;
int temps;
string res;
};
struct alums {
string dni;
vector<exercici> exer;
};
typedef vector<Enviament> Historia;
typedef vector<alums> Alumnes;
void mesenviaverds(const Alumnes& classP1) {
int maxenverd, maxexverd, maxexvermell,maxexdif, maxtemps, pos1, pos2, pos3, pos4, pos5;
maxenverd = maxexverd = maxexvermell = maxexdif = maxtemps = pos1 = pos2 = pos3 = pos4 = pos5 = 0;
for (int i = 0;i<int(classP1.size());i++) {
int cverd = 0; // comptador de verds per cada alumne
int uverd = 0; // comptador de verds unics per cada alumne
int uvermell = 0; // comptador de vermells per cada alumne
int countex = 0; // comptador de exercicis diferents intentats per cada alumne
vector<string> exverd;
vector<string> exvermell;
vector<string> exdif;
for (int j=0;j<int(classP1[i].exer.size());j++) {
if (classP1[i].exer[j].res == "verd") {
cverd++;
// verds unics
bool found = false;
for (int k=0;k<int(exverd.size());k++) {
if (classP1[i].exer[j].nom == exverd[k]) found = true;
}
if (not found) {
exverd.push_back(classP1[i].exer[j].nom);
uverd++;
}
}
if (classP1[i].exer[j].res == "vermell") {
bool found = false;
for (int k=0;k<int(exverd.size());k++) {
if (classP1[i].exer[j].nom == exvermell[k]) found = true;
}
if (not found) {
exvermell.push_back(classP1[i].exer[j].nom);
uvermell++;
}
}
bool found = false;
for (int k=0;k<int(exdif.size());k++) {
if (classP1[i].exer[j].nom == exdif[k]) found = true;
}
if (not found) {
exdif.push_back(classP1[i].exer[j].nom);
countex++;
}
if (classP1[i].exer[j].temps > maxtemps) {
maxtemps = classP1[i].exer[j].temps;
pos5 = i;
}
}
// verds totals
if (cverd > maxenverd) {
maxenverd = cverd;
pos1 = i;
}
else if (cverd == maxenverd) {
if (classP1[i].dni < classP1[pos1].dni) pos1 = i;
}
// verds unics
if (uverd > maxexverd) {
maxexverd = uverd;
pos2 = i;
}
else if (uverd == maxexverd) {
if (classP1[i].dni < classP1[pos2].dni) pos2 = i;
}
// vermells unics
if (uvermell > maxexvermell) {
maxexvermell = uvermell;
pos3 = i;
}
else if (uvermell == maxexvermell) {
if (classP1[i].dni < classP1[pos3].dni) pos3 = i;
}
// exercicis intentats
if (countex > maxexdif) {
maxexdif = countex;
pos4 = i;
}
else if (countex == maxexdif) {
if (classP1[i].dni < classP1[pos4].dni) pos4 = i;
}
}
if (maxenverd > 0) cout << "alumne amb mes enviaments verds: " << classP1[pos1].dni << " (" << maxenverd << ')' << endl;
else if (maxenverd == 0) cout << "alumne amb mes enviaments verds: -" << endl;
if (maxexverd > 0) cout << "alumne amb mes exercicis verds: " << classP1[pos2].dni << " (" << maxexverd << ')' << endl;
else if (maxexverd == 0) cout << "alumne amb mes exercicis verds: -" << endl;
if (maxexvermell > 0) cout << "alumne amb mes exercicis vermells: " << classP1[pos3].dni << " (" << maxexvermell << ')' << endl;
else if (maxexvermell == 0) cout << "alumne amb mes exercicis vermells: -" << endl;
if (maxexdif > 0) cout << "alumne amb mes exercicis intentats: " << classP1[pos4].dni << " (" << maxexdif << ')' << endl;
else if (maxexvermell == 0) cout << "alumne amb mes exercicis intentats: -" << endl;
if (maxtemps > 0) cout << "alumne que ha fet l'ultim enviament: " << classP1[pos5].dni << endl;
else if (maxtemps == 0) cout << "alumne que ha fet l'ultim enviament: -" << endl;
}
void parse(const Historia& P1, Alumnes& classP1) {
for (int i=0;i<int(P1.size());i++) {
for (int j = 0;j<int(classP1.size());j++) {
if (P1[i].dni == classP1[j].dni) {
exercici ex;
ex.nom = P1[i].exer;
ex.temps = P1[i].temps;
ex.res = P1[i].res;
classP1[j].exer.push_back(ex);
}
}
}
}
int main() {
int n;
cin >> n;
Historia P1(n);
Alumnes classP1;
for (int i = 0;i<n;i++) {
cin >> P1[i].dni >> P1[i].exer >> P1[i].temps >> P1[i].res;
bool found = false;
for (int j=0;j<int(classP1.size());j++) {
if (P1[i].dni == classP1[j].dni) found = true;
}
if (not found) {
alums alumne;
alumne.dni = P1[i].dni;
classP1.push_back(alumne);
}
}
parse(P1,classP1);
mesenviaverds(classP1);
}
| true |
22bcd1c652a2756417bebc39a686984347c7a3b7 | C++ | shaih/HElib | /include/helib/timing.h | UTF-8 | 4,114 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | /* Copyright (C) 2012-2020 IBM Corp.
* This program is 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. See accompanying LICENSE file.
*/
/**
* @file timing.h
* @brief Utility functions for measuring time
*
* This module contains some utility functions for measuring the time that
* various methods take to execute. To use it, we insert the macro
* HELIB_TIMER_START at the beginning of the method(s) that we want to time and
* HELIB_TIMER_STOP at the end, then the main program needs to call the function
* setTimersOn() to activate the timers and setTimersOff() to pause them.
* To obtain the value of a given timer (in seconds), the application can
* use the function getTime4func(const char *fncName), and the function
* printAllTimers() prints the values of all timers to an output stream.
*
* Using this method we can have at most one timer per method/function, and
* the timer is called by the same name as the function itself (using the
* built-in macro \_\_func\_\_). We can also use the "lower level" methods
* startFHEtimer(name), stopFHEtimer(name), and resetFHEtimer(name) to add
* timers with arbitrary names (not necessarily associated with functions).
**/
#ifndef HELIB_TIMING_H
#define HELIB_TIMING_H
#include <helib/NumbTh.h>
#include <helib/multicore.h>
namespace helib {
class FHEtimer;
void registerTimer(FHEtimer* timer);
unsigned long GetTimerClock();
//! A simple class to accumulate time
class FHEtimer
{
public:
const char* name;
const char* loc;
// THREADS: these need to be atomic
HELIB_atomic_ulong counter;
HELIB_atomic_long numCalls;
FHEtimer(const char* _name, const char* _loc) :
name(_name), loc(_loc), counter(0), numCalls(0)
{
registerTimer(this);
}
void reset();
double getTime() const;
long getNumCalls() const;
};
// backward compatibility: timers are always on
inline void setTimersOn() {}
inline void setTimersOff() {}
inline bool areTimersOn() { return true; }
const FHEtimer* getTimerByName(const char* name);
void resetAllTimers();
//! Print the value of all timers to stream
void printAllTimers(std::ostream& str = std::cerr);
// return true if timer was found, false otherwise
bool printNamedTimer(std::ostream& str, const char* name);
//! \cond FALSE (make doxygen ignore these classes)
class auto_timer
{
public:
FHEtimer* timer;
unsigned long amt;
bool running;
auto_timer(FHEtimer* _timer) :
timer(_timer), amt(GetTimerClock()), running(true)
{}
void stop()
{
amt = GetTimerClock() - amt;
timer->counter += amt;
timer->numCalls++;
running = false;
}
~auto_timer()
{
if (running)
stop();
}
};
//! \endcond
// NOTE: the STOP functions below are not really needed,
// but are provided for backward compatibility
#define HELIB_STRINGIFY(x) #x
#define HELIB_TOSTRING(x) HELIB_STRINGIFY(x)
#define HELIB_AT __FILE__ ":" HELIB_TOSTRING(__LINE__)
#define HELIB_stringify_aux(s) #s
#define HELIB_stringify(s) HELIB_stringify_aux(s)
#define HELIB_TIMER_START \
static helib::FHEtimer _local_timer(__func__, HELIB_AT); \
helib::auto_timer _local_auto_timer(&_local_timer)
#define HELIB_TIMER_STOP _local_auto_timer.stop()
#define HELIB_NTIMER_START(n) \
static helib::FHEtimer _named_local_timer##n(#n, HELIB_AT); \
helib::auto_timer _named_local_auto_timer##n(&_named_local_timer##n)
#define HELIB_NTIMER_STOP(n) _named_local_auto_timer##n.stop();
} // namespace helib
#endif // ifndef HELIB_TIMING_H
| true |
8f45c854169fe69a91b2032702d7c12128e70d76 | C++ | BigBang019/Code_Library | /hdu/hdu_4347.cpp | UTF-8 | 3,054 | 2.515625 | 3 | [] | no_license | /*
KDTREE
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
const int K = 6;
int di;
struct NODE{
ll d[K];
//vector<ll> d;
bool operator < (const NODE & a) const {
return d[di] < a.d[di];
}
bool operator > (const NODE & a) const {
return a < (*this);
}
} point[N]; //起点从0开始
priority_queue<pair<ll, NODE> > q;
namespace KDTREE{
NODE tree[N << 2];
int son[N << 2];
int k;
ll square(ll x)
{
return x * x;
}
void build(int x,int l,int r,int dim=0){//[l,r]
di = dim % k;
if (l>r)
return;
son[x] = r - l;
son[2 * x] = son[2 * x + 1] = -1;
int mid = l + r >> 1;
nth_element(point + l, point + mid, point + r + 1);
tree[x] = point[mid];
build(x * 2, l, mid - 1, dim + 1);
build(x * 2 + 1, mid + 1, r, dim + 1);
}
void build(int l,int r){
build(1, l, r, 0);
}
void queryK(int x,NODE o,int m,int dim=0){
if (son[x]==-1)
return;
int di = dim % k;
pair<ll, NODE> now(0,tree[x]);
for (int i = 0; i < k;i++)
now.first += square(tree[x].d[i] - o.d[i]); //计算当前节点的距离
int xx = 2 * x, yy = 2 * x + 1;
bool flag = 0;
if (o.d[di]>=tree[x].d[di]) //先递归潜力大的分支
swap(xx, yy);
if (~son[xx]) //如果xx存在
queryK(xx, o, m, dim + 1);
if (q.size()<m)
q.push(now), flag = 1;
else{
if (now.first<q.top().first)
q.pop(), q.push(now);
if (square(o.d[di]-tree[x].d[di]) < q.top().first)//当前维数来看有潜力比队列中的小
flag = 1;
}
if (~son[yy] && flag) //如果yy存在并且有潜力
queryK(yy, o, m, dim + 1);
}
void queryK(NODE o,int m){
queryK(1, o, m, 0);
}
}
NODE ans[100];
int n, kk;
int main(){
while (scanf("%d%d",&n,&kk)!=EOF)
{
KDTREE::k = kk;
for (int i = 0; i < n;i++)
{
for (int j = 0; j < kk;j++)
{
ll x;
scanf("%lld",&x);
point[i].d[j] = x;
//point[i].d.push_back(x);
}
}
KDTREE::build(0, n - 1);
int t, m;
scanf("%d",&t);
for (int i = 1; i <= t;i++)
{
NODE o;
for (int j = 0; j < kk;j++)
{
ll z;
scanf("%lld",&z);
o.d[j] = z;
//o.d.push_back(z);
}
scanf("%d",&m);
KDTREE::queryK(o,m);
int j = 0;
while (!q.empty()) {
ans[j++] = q.top().second;
q.pop();
}
printf("the closest %d points are:\n", m);
for (int j = m - 1; j >= 0;j--)
for (int l = 0; l < kk;l++)
printf("%d%c",ans[j].d[l],l==kk-1?'\n':' ');
}
}
return 0;
}
| true |
f9b77e1d01c695788858412b18c1924c24610557 | C++ | lk16/squared | /src/bots/bot_random.cpp | UTF-8 | 377 | 2.515625 | 3 | [] | no_license | #include "bots/bot_random.hpp"
REGISTER_BOT(random);
bot_random::bot_random()
{
set_name("random");
}
void bot_random::do_move(const board* in, board* out)
{
board moves[32];
board* moves_end = in->get_children(moves);
*out = moves[rand() % (moves_end - moves)];
output() << "bot_" << get_name() << " picked a move.\n";
}
void bot_random::on_new_game()
{
}
| true |
100c6736f3b0c98561b19069afb09779f3c64d94 | C++ | samanseifi/Tahoe | /tahoe/src/primitives/globalmatrix/DiagonalMatrixT.cpp | UTF-8 | 8,894 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | /* $Id: DiagonalMatrixT.cpp,v 1.22 2011/12/01 21:11:40 bcyansfn Exp $ */
/* created: paklein (03/23/1997) */
#include "DiagonalMatrixT.h"
#include <iostream>
#include <iomanip>
#include "toolboxConstants.h"
#include "iArrayT.h"
#include "ElementMatrixT.h"
#include "StringT.h"
#include "ofstreamT.h"
#include "CommunicatorT.h"
using namespace Tahoe;
/* constructor */
DiagonalMatrixT::DiagonalMatrixT(ostream& out, int check_code, AssemblyModeT mode,
const CommunicatorT& comm):
GlobalMatrixT(out, check_code, comm),
fIsFactorized(false)
{
try { SetAssemblyMode(mode); }
catch (ExceptionT::CodeT) { throw ExceptionT::kBadInputValue; }
}
/* copy constructor */
DiagonalMatrixT::DiagonalMatrixT(const DiagonalMatrixT& source):
GlobalMatrixT(source),
fMatrix(source.fMatrix),
fMode(source.fMode),
fIsFactorized(source.fIsFactorized)
{
}
/* set assemble mode */
void DiagonalMatrixT::SetAssemblyMode(AssemblyModeT mode)
{
/* set */
fMode = mode;
/* check */
if (fMode != kNoAssembly &&
fMode != kDiagOnly &&
fMode != kAbsRowSum) throw ExceptionT::kGeneralFail;
}
/* set the internal matrix structure.
* NOTE: do not call Initialize() equation topology has been set
* with AddEquationSet() for all equation sets */
void DiagonalMatrixT::Initialize(int tot_num_eq, int loc_num_eq, int start_eq)
{
/* inherited */
GlobalMatrixT::Initialize(tot_num_eq, loc_num_eq, start_eq);
/* allocate work space */
fMatrix.Dimension(fLocNumEQ);
fIsFactorized = false;
}
/* set all matrix values to 0.0 */
void DiagonalMatrixT::Clear(void)
{
/* inherited */
GlobalMatrixT::Clear();
/* clear data */
fMatrix = 0.0;
fIsFactorized = false;
}
/* add element group equations to the overall topology.
* NOTE: assembly positions (equation numbers) = 1...fNumEQ
* equations can be of fixed size (iArray2DT) or
* variable length (RaggedArray2DT) */
void DiagonalMatrixT::AddEquationSet(const iArray2DT& eqset)
{
#pragma unused(eqset)
// no equation data needed
}
void DiagonalMatrixT::AddEquationSet(const RaggedArray2DT<int>& eqset)
{
#pragma unused(eqset)
// no equation data needed
}
/* assemble the element contribution into the LHS matrix - assumes
* that elMat is square (n x n) and that eqnos is also length n.
* NOTE: assembly positions (equation numbers) = 1...fNumEQ */
void DiagonalMatrixT::Assemble(const ElementMatrixT& elMat, const ArrayT<int>& eqnos)
{
if (elMat.Format() == ElementMatrixT::kDiagonal)
{
/* from diagonal only */
const double* pelMat = elMat.Pointer();
int inc = elMat.Rows() + 1;
int numvals = eqnos.Length();
for (int i = 0; i < numvals; i++)
{
int eq = eqnos[i];
/* active dof */
if (eq-- > 0) fMatrix[eq] += *pelMat;
pelMat += inc;
}
}
else
{
/* assemble modes */
switch (fMode)
{
case kDiagOnly:
{
/* assemble only the diagonal values */
for (int i = 0; i < eqnos.Length(); i++)
if (eqnos[i] > 0)
fMatrix[eqnos[i] - 1] += elMat(i,i);
break;
}
case kAbsRowSum:
{
/* copy to full symmetric */
if (elMat.Format() == ElementMatrixT::kSymmetricUpper)
elMat.CopySymmetric();
/* assemble sum of row absolute values */
int numrows = eqnos.Length();
for (int i = 0; i < numrows; i++)
if (eqnos[i] > 0)
{
const double* prow = elMat.Pointer(i);
double sum = 0.0;
for (int j = 0; j < numrows; j++)
{
sum += fabs(*prow);
prow += numrows;
}
fMatrix[eqnos[i] - 1] += sum;
}
break;
}
default:
cout << "\n DiagonalMatrixT::Assemble: cannot assemble mode: " << fMode << endl;
throw ExceptionT::kGeneralFail;
}
}
}
void DiagonalMatrixT::Assemble(const ElementMatrixT& elMat, const ArrayT<int>& row_eqnos,
const ArrayT<int>& col_eqnos)
{
/* pick out diagonal values */
for (int row = 0; row < row_eqnos.Length(); row++)
for (int col = 0; col < col_eqnos.Length(); col++)
if (row_eqnos[row] == col_eqnos[col])
{
int eqno = row_eqnos[row] - 1;
if (eqno > -1)
fMatrix[eqno] += elMat(row, col);
}
}
void DiagonalMatrixT::Assemble(const nArrayT<double>& diagonal_elMat, const ArrayT<int>& eqnos)
{
#if __option(extended_errorcheck)
/* dimension check */
if (diagonal_elMat.Length() != eqnos.Length()) throw ExceptionT::kSizeMismatch;
#endif
for (int i = 0; i < eqnos.Length(); i++)
{
int eqno = eqnos[i] - 1;
if (eqno > -1)
fMatrix[eqno] += diagonal_elMat[i];
}
}
/* fetch values */
void DiagonalMatrixT::DisassembleDiagonal(dArrayT& diagonals,
const nArrayT<int>& eqnos) const
{
#if __option(extended_errorcheck)
/* dimension check */
if (diagonals.Length() != eqnos.Length()) throw ExceptionT::kSizeMismatch;
#endif
for (int i = 0; i < eqnos.Length(); i++)
{
/* ignore requests for inactive equations */
int eq = eqnos[i];
if (eq-- > 0)
diagonals[i] = fMatrix[eq];
else
diagonals[i] = 0.0;
}
}
/* number scope and reordering */
GlobalMatrixT::EquationNumberScopeT DiagonalMatrixT::EquationNumberScope(void) const
{
return kLocal;
}
bool DiagonalMatrixT::RenumberEquations(void) const { return false; }
/* assignment operator */
DiagonalMatrixT& DiagonalMatrixT::operator=(const DiagonalMatrixT& rhs)
{
/* no copies of self */
if (this == &rhs) return *this;
/* inherited */
GlobalMatrixT::operator=(rhs);
fMatrix = rhs.fMatrix;
fMode = rhs.fMode;
fIsFactorized = rhs.fIsFactorized;
return *this;
}
/** return a clone of self */
GlobalMatrixT* DiagonalMatrixT::Clone(void) const
{
DiagonalMatrixT* new_mat = new DiagonalMatrixT(*this);
return new_mat;
}
/* matrix-vector product */
void DiagonalMatrixT::Multx(const dArrayT& x, dArrayT& b) const
{
b = x;
if (fIsFactorized)
b /= fMatrix;
else
b *= fMatrix;
}
/* vector-matrix-vector product */
double DiagonalMatrixT::MultmBn(const dArrayT& m, const dArrayT& n) const
{
#if __option(extended_errorcheck)
if (m.Length() != fMatrix.Length() || n.Length() != fMatrix.Length())
ExceptionT::SizeMismatch("DiagonalMatrixT::MultmBn");
#endif
const double* pm = m.Pointer();
const double* pn = n.Pointer();
const double* pM = fMatrix.Pointer();
int length = fMatrix.Length();
double mBn = 0.0;
for (int i = 0; i < length; i++)
mBn += (*pm++)*(*pM++)*(*pn++);
return mBn;
}
/**************************************************************************
* Protected
**************************************************************************/
/* precondition matrix */
void DiagonalMatrixT::Factorize(void)
{
/* quick exit */
if (fIsFactorized)
return;
else {
double* pMatrix = fMatrix.Pointer();
/* inverse of a diagonal matrix */
bool first = true;
for (int i = 0; i < fLocNumEQ; i++)
{
/* check for zero pivots */
if (fabs(*pMatrix) > kSmall)
*pMatrix = 1.0/(*pMatrix);
else
{
if (first)
{
cout << "\n DiagonalMatrixT::Factorize: WARNING: skipping small pivots. See out file."
<< endl;
fOut << "\n DiagonalMatrixT::Factorize: small pivots\n";
fOut << setw(kIntWidth) << "eqn"
<< setw(OutputWidth(fOut, pMatrix)) << "pivot" << '\n';
first = false;
}
fOut << setw(kIntWidth) << i+1
<< setw(OutputWidth(fOut, pMatrix)) << *pMatrix << '\n';
}
/* next */
pMatrix++;
}
/* flush */
if (!first) fOut.flush();
/* set flag */
fIsFactorized = true;
}
}
/* solution driver */
void DiagonalMatrixT::BackSubstitute(dArrayT& result)
{
/* checks */
if (result.Length() != fLocNumEQ || !fIsFactorized) throw ExceptionT::kGeneralFail;
double* presult = result.Pointer();
double* pMatrix = fMatrix.Pointer();
for (int i = 0; i < fLocNumEQ; i++)
*presult++ *= *pMatrix++;
}
/* check functions */
void DiagonalMatrixT::PrintAllPivots(void) const
{
if (fCheckCode != GlobalMatrixT::kAllPivots)
return;
fOut << "\nAll pivots:\n\n";
fOut << fMatrix << "\n\n";
}
void DiagonalMatrixT::PrintZeroPivots(void) const
{
if (fCheckCode != GlobalMatrixT::kZeroPivots) return;
int d_width = OutputWidth(fOut, fMatrix.Pointer());
int firstline = 1;
for (int i = 0; i < fLocNumEQ; i++)
{
double pivot = fMatrix[i];
if (pivot < kSmall)
{
if (firstline)
{
fOut << "\nZero or negative pivots:\n\n";
firstline = 0;
}
fOut << setw(kIntWidth) << i + 1;
fOut << setw(d_width) << pivot << '\n';
}
}
if (!firstline) fOut << '\n';
}
void DiagonalMatrixT::PrintLHS(bool force) const
{
if (!force && fCheckCode != GlobalMatrixT::kPrintLHS) return;
/* output stream */
StringT file = fstreamT::Root();
file.Append("DiagonalMatrixT.LHS.", sOutputCount);
if (fComm.Size() > 1) file.Append(".p", fComm.Rank());
ofstreamT out(file);
out.precision(14);
/* write non-zero values in RCV format */
for (int i = 0; i < fLocNumEQ; i++)
out << i+1 << " " << i+1 << " " << fMatrix[i] << '\n';
/* increment count */
sOutputCount++;
}
| true |
cf3b63f14e09b43508932012f5399c6dd4f9cc0e | C++ | macielbarbosa/UVa | /prova3/a.cpp | UTF-8 | 549 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
long double calculado [5001];
long double fibonacci (int n) {
if (calculado[n] != -1) return calculado[n];
calculado[n] = fibonacci(n-1) + fibonacci(n-2);
return calculado[n];
}
int main () {
int n;
calculado[0] = 0;
calculado[1] = 1;
for(int i=2; i<5001; i++){
calculado[i] = -1;
}
while (scanf("%d",&n)!=EOF) {
cout << "The Fibonacci number for " << n << " is " << fibonacci(n) << endl;
}
return 0;
}
| true |
fd27bbfedf057d161fe373de073fbc5d7444676d | C++ | AnishKumarAkGk/Laptop_projects_Arduino | /Http_Thingspeak/Http_Thingspeak.ino | UTF-8 | 1,595 | 2.546875 | 3 | [] | no_license |
#include <ESP8266WiFi.h>
// Wi-Fi Settings
const char* ssid = ""; // your wireless network name (SSID)
const char* password = ""; // your Wi-Fi network password
WiFiClient client;
// ThingSpeak Settings
const int channelID = 489907;// write channelID key for your ThingSpeak
String writeAPIKey = ""; // write API key for your ThingSpeak Channel
const char* server = "api.thingspeak.com";
const int postingInterval = 3 * 1000; // post data every 20 seconds
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
int i=30;
void loop() {
if (client.connect(server, 80)) {
// Measure Signal Strength (RSSI) of Wi-Fi connection
long rssi = WiFi.RSSI();
// Construct API request body
String body = "field1=";
body += String(rssi);
Serial.print("RSSI: ");
Serial.println(rssi);
client.println("POST /update HTTP/1.1");
client.println("Host: api.thingspeak.com");
client.println("Connection: close");
client.println("X-THINGSPEAKAPIKEY: " + writeAPIKey);
client.println("Content-Type: application/x-www-form-urlencoded");
client.println("Content-Length: " + String(body.length()));
client.println("");
client.print(body);
Serial.println("[Response:]");
while (client.connected())
{
if (client.available())
{
String line = client.readStringUntil('\n');
Serial.println(line);
}
}
}
client.stop();
// wait and then post again
delay(postingInterval);
i+=1;
}
| true |
0f6ee27fa8656bc22a20d9b8f6c75ae276f17cb8 | C++ | Minusie357/Algorithm | /BackjoonAlgorithm/4344. 평균은 넘겠지.cpp | UTF-8 | 496 | 2.59375 | 3 | [
"Unlicense"
] | permissive | //#include <stdio.h>
//
//int main()
//{
// int c;
// scanf("%d", &c);
//
// int scores[1000];
// while (c--)
// {
// int n;
// scanf("%d", &n);
//
// int sum = 0;
// for (int i = 0; i < n; ++i)
// {
// scanf("%d", &scores[i]);
// sum += scores[i];
// }
//
// double avg = sum / (double)n;
// int num_avg_upper = 0;
//
// for (int i = 0; i < n; ++i)
// num_avg_upper += scores[i] > avg ? 1 : 0;
//
// printf("%.3lf%%\n", (num_avg_upper / (double)n) * 100);
// }
// return 0;
//} | true |
fa622a5f24e63f14431be3b4573239825292f76f | C++ | harshp8l/deep-learning-lang-detection | /data/train/cpp/7b95cac5059aebb7379553888f0bee952ba3c763Chunk.cpp | UTF-8 | 2,631 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include "../Block/Block.hpp"
#include "Chunk.hpp"
#include "ChunkManager.hpp"
#include "LocalChunkSystem.hpp"
#define DEBUG_GRAPH
bool Chunk::isStrictelyInside(const sf::Vector3i & blockPosition)
{
return blockPosition.x > 0 && blockPosition.y > 0 && blockPosition.z > 0 &&
blockPosition.x < SIZE_1 && blockPosition.y < SIZE_1 && blockPosition.z < SIZE_1;
}
Chunk::Chunk() : mPosition(), mNeedRebuild(false), mIsModified(false)
{
mData = new ChunkData();
}
void Chunk::reset() {
mPosition.x=mPosition.y=mPosition.z=0x7FFFFFFF;
mIsModified = false;
}
const ChunkCoordinate & Chunk::getPosition() const
{
return mPosition;
}
void Chunk::setPosition(const ChunkCoordinate &position)
{
mPosition = position;
}
bool Chunk::rebuild()
{
if (hasData() && mNeedRebuild) {
const LocalChunkSystem local(*mManager, this);
mData->rebuild(local);
mNeedRebuild = false;
return true;
}
return false;
}
void Chunk::draw(const MeshDetail detail) const
{
#ifdef DEBUG_GRAPH
glDisable(GL_LIGHTING);
if (!hasData())
glBegin(GL_POINTS);
else
glBegin(GL_LINES);
if (!hasData())
glColor3f(1,.7,1);
else
glColor3f(.7,detail,detail/2.0);
glVertex3f(0,0,0);glVertex3f(Chunk::SIZE ,0,0);
glVertex3f(0,0,0);glVertex3f(0,Chunk::SIZE,0);
glVertex3f(0,0,0);glVertex3f(0,0,Chunk::SIZE);
glVertex3f(Chunk::SIZE,Chunk::SIZE,Chunk::SIZE);glVertex3f(Chunk::SIZE,0,Chunk::SIZE);
glVertex3f(Chunk::SIZE,Chunk::SIZE,Chunk::SIZE);glVertex3f(0,Chunk::SIZE,Chunk::SIZE);
glVertex3f(Chunk::SIZE,Chunk::SIZE,Chunk::SIZE);glVertex3f(Chunk::SIZE,Chunk::SIZE,0);
glVertex3f(Chunk::SIZE,0,0);glVertex3f(Chunk::SIZE,Chunk::SIZE,0);
glVertex3f(Chunk::SIZE,0,0);glVertex3f(Chunk::SIZE,0,Chunk::SIZE);
glVertex3f(Chunk::SIZE,0,Chunk::SIZE);glVertex3f(0,0,Chunk::SIZE);
glVertex3f(0,Chunk::SIZE,0);glVertex3f(Chunk::SIZE,Chunk::SIZE,0);
glVertex3f(0,Chunk::SIZE,0);glVertex3f(0,Chunk::SIZE,Chunk::SIZE);
glVertex3f(0,Chunk::SIZE,Chunk::SIZE);glVertex3f(0,0,Chunk::SIZE);
glEnd();
glEnable(GL_LIGHTING);
#endif
if (hasData())
mData->getMesh().draw(detail);
}
void Chunk::load()
{
// load from file or generate
mManager->loadChunk(this);
}
void Chunk::beginSet(bool playerAction)
{
mIsModified = playerAction;
}
void Chunk::endSet()
{
//rebuild();
mNeedRebuild = true;
}
void Chunk::setOne(const BlockCoordinate &pos, Block & block)
{
beginSet(true);
set(pos, block);
endSet();
}
void Chunk::unload()
{
// TODO : implement persistence
}
Chunk::~Chunk()
{
if (mData != 0)
delete mData;
}
| true |
6d8481524e818db9d227a6d89c9fa9fe90ece782 | C++ | tongyuantongyu/image-resampler | /Source/Utilities/vnImageBlock.cpp | UTF-8 | 2,258 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | #include "vnImageBlock.h"
VN_STATUS vnConvertBlock(CONST VN_PIXEL_BLOCK& pSrc, VN_IMAGE_FORMAT destFormat,
VN_PIXEL_BLOCK* pDest) {
if (VN_PARAM_CHECK) { if (!pDest) { return vnPostError(VN_ERROR_INVALIDARG); } }
//
// (!) Note: this function is written to support aliased conversion. That is, conversions where pSrc
// and pDest are aliases of the same block.
//
//
// Our next step is to copy over the block channel data with proper conversions for the
// (potential) precision change.
//
VN_IMAGE_PRECISION destPrecision = (VN_IS_FLOAT_FORMAT(destFormat))
? VN_IMAGE_PRECISION_FLOAT
: VN_IMAGE_PRECISION_FIXED;
//
// Note that we store the destination channel count but do not take it into consideration
// when performing the channel conversion. In this way we allow zero values to propagate from
// the source to destination in the event of a channel count mismatch.
//
if (pSrc.uiPrecision == destPrecision) {
//
// Same precision, simply copy over the data and format
//
memcpy(pDest->uiChannelBytes, pSrc.uiChannelBytes, 32);
}
//
// Conversion between fixed/float format
//
else {
if (VN_IMAGE_PRECISION_FLOAT == destPrecision) {
//
// fixed -> float, we perform a normalizing scale
//
for (UINT8 i = 0; i < 4; i++) {
if (pSrc.iChannelData[i] < 0) {
pDest->fChannelData[i] = ((FLOAT64)-1 * pSrc.iChannelData[i] / VN_MIN_INT32);
}
else { pDest->fChannelData[i] = (FLOAT64)pSrc.iChannelData[i] / VN_MAX_INT32; }
pDest->fChannelData[i] = vnClipRange64(pDest->fChannelData[i], -1.0, 1.0);
}
}
else {
//
// float -> fixed, we perform a truncating scale
//
FLOAT64 fTempChannels[4] = {0};
for (UINT8 i = 0; i < 4; i++) {
fTempChannels[i] = vnClipRange64(pSrc.fChannelData[i], -1.0f, 1.0f);
if (fTempChannels[i] < 0) {
pDest->iChannelData[i] = (INT64)((FLOAT64)-1.0 * fTempChannels[i] * VN_MIN_INT32);
}
else { pDest->iChannelData[i] = (INT64)((FLOAT64)fTempChannels[i] * VN_MAX_INT32); }
}
}
}
pDest->uiChannelCount = VN_IMAGE_CHANNEL_COUNT(destFormat);
pDest->uiPrecision = destPrecision;
return VN_SUCCESS;
}
| true |
64949d048a5b7bf2dc87564110e4fd343e95b3a9 | C++ | pelmenka/120_bomberman | /render/shader.cpp | UTF-8 | 2,266 | 2.5625 | 3 | [] | no_license | #include <GL/glew.h>
#include <stdio.h>
#include <assert.h>
#include <memory.h>
#include "shader.h"
#include "../log.h"
shader::shader()
{
shaders[0] = 0;
shaders[1] = 0;
program = -1;
}
shader::~shader()
{
if(program == -1) return;
unbind();
glDetachShader(program, shaders[0]);
glDetachShader(program, shaders[1]);
glDeleteShader(shaders[0]);
glDeleteShader(shaders[1]);
glDeleteProgram(program);
}
bool shader::addShader(bool shad, const char* path)
{
int types[2] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER};
if(shaders[shad]) glDeleteShader(shaders[shad]);
FILE *src = fopen(path, "rt");
if(!src) return 0;
fseek(src, 0, 2);
int lenth = ftell(src);
assert(lenth);
fseek(src, 0, 0);
char *source = new char[lenth];
memset(source, 0, lenth);
fread(source, 1, lenth, src);
fclose(src);
shaders[shad] = glCreateShader(types[shad]);
const char *s = source;
glShaderSource(shaders[shad], 1, &s, 0);
_log::out("compiling shader -> ", 0);
_log::out(path);
glCompileShader(shaders[shad]);
delete [] source;
checkErrors(shad);
return 1;
}
void shader::compile()
{
program = glCreateProgram();
glAttachShader(program, shaders[0]);
glAttachShader(program, shaders[1]);
glLinkProgram(program);
int lenth;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &lenth);
if(lenth)
{
char *mess = new char[lenth];
glGetProgramInfoLog(program, lenth, 0, mess);
_log::out(mess);
delete [] mess;
}
}
bool shader::load(const char *vert, const char *frag)
{
if(addShader(0, vert) && addShader(1, frag))
{
compile();
return 1;
}
return 0;
}
void shader::bind()
{
glUseProgram(program);
}
void shader::unbind()
{
glUseProgram(0);
}
void shader::checkErrors(GLuint i)
{
int log = 0;
glGetShaderiv(shaders[i], GL_COMPILE_STATUS, &log);
if(!log)
{
glGetShaderiv(shaders[i], GL_INFO_LOG_LENGTH, &log);
if(i) _log::out("fragment shader:");
else _log::out("vertex shader:");
char *mess = new char[log];
glGetShaderInfoLog(shaders[i], log, 0, mess);
_log::out(mess);
delete [] mess;
}
}
| true |
b67a6e7c9ad2e95d9795ac7bbaea0a41e423833c | C++ | s-bond/Miscellaneous-Codes | /4/its a murder.cpp | UTF-8 | 753 | 2.546875 | 3 | [] | no_license | /* ~
* Siddharth Maloo
*/
#include <iostream>
#include <cstring>
/////////////////
#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define ULL unsigned long long int
#define Max 1000001
/////////////////
using namespace std;
ULL tree[Max], a[Max];
ULL read(int idx){
ULL sum = 0;
while (idx > 0){
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}
void update(ULL idx , ULL val){
while (idx <= Max){
tree[idx] += val;
idx += (idx & -idx);
}
}
int main () {
int i, t, n, x;
ULL c=0;
scanf("%d",&t);
while ( t-- ){
scanf("%d",&n);
FOR(i,0,n)
scanf("%llu",a+i);
FOR(i,0,n) {
if(a[i]!=0){
c += read(a[i]-1);
update(a[i],a[i]);}
}
printf("%llu\n",c);
memset(tree,0,sizeof(tree));
c=0;
}
return 0;
} | true |
520db78c75bd885288fe18d0961cb7520e0875a5 | C++ | Iristudio/Iris-c | /源码/079类和对象的练习.cpp | GB18030 | 648 | 3.53125 | 4 | [] | no_license | #include<iostream>
using namespace std;
//еԺΪͳһΪ Ա
// Ա Ա
//Ϊ Ա Ա
class stu {
public:
string stu_name;
int stu_code;
void setname(string name) {
stu_name = name;
}
void setcode(int code) {
stu_code = code;
}
void showstu() {
cout << "ѧ:" << stu_name << " ѧ:" << stu_code << endl;
}
};
int main() {
stu s1;
//cout << "" << endl;
//cin >> s1.name;
//cout << "ѧ" << endl;
//cin >> s1.code;
s1.setname("");
s1.setcode(521);
s1.showstu();
system("pause");
return 0;
}
| true |
d2cb043f9c57344c82ef63191a6c8370f552108f | C++ | jleun1403/BOJ_CPP | /Q14709.cpp | UTF-8 | 473 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
scanf("%d", &n);
vector<pair<int, int>> v;
for (int i = 0 ; i <n ; i++) {
int a, b;
cin >> a>> b;
if (a > b)
swap(a, b);
v.push_back(make_pair(a, b));
}
sort(v.begin(), v.end());
vector<pair<int, int>> t(3);
t[0] = {1, 3};
t[1] = {1, 4};
t[2] = {3, 4};
if (v == t) {
printf("Wa-pa-pa-pa-pa-pa-pow!");
}
else printf("Woof-meow-tweet-squeek");
return 0;
} | true |
78145e37dc79a68c864051e9fb359d9ef28cb57d | C++ | ashish1508/ds-algo | /binarysearch/smallerOrEqualElements.cpp | UTF-8 | 542 | 3.59375 | 4 | [] | no_license | // finding last. element less tha or equal to B
int Solution::solve(vector<int> &A, int B) {
int lo=0,n=A.size(),hi=n-1,mid;
while(lo<=hi){
mid=lo+(hi-lo)/2;
if(A[mid]<=B) lo=mid+1;
if(A[mid]>B) hi=mid-1;
}
return hi+1;
}
// finding first element greater than B
int Solution::solve(vector<int> &A, int B) {
int lo=0,n=A.size(),hi=n-1,mid;
while(lo<hi){
mid=lo+(hi-lo)/2;
if(A[mid]<=B) lo=mid+1;
if(A[mid]>B) hi=mid;
}
if(A[lo]<=B) return lo+1;
return lo;
}
| true |
b1287944aa88c5b34aac52c68637ed68d43dc0eb | C++ | ailyanlu/ACM_Code | /HDU/HDU_4584.cpp | UTF-8 | 1,733 | 2.5625 | 3 | [] | no_license | /**
* @file HDU_4584.cpp
* @brief 水题,枚举1A!
* @author FinalTheory
* @version 0.1
* @date 2013-08-13
*/
#if defined(__GNUC__)
#pragma GCC optimize ("O2")
#endif
#if defined(_MSC_VER)
#pragma comment(linker, "/STACK:36777216")
#endif
#include <iostream>
#include <algorithm>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <cctype>
#include <climits>
#include <ctime>
#include <vector>
#include <set>
#include <stack>
#include <sstream>
#include <queue>
#include <iomanip>
#define CLR(arr,val) memset(arr,val,sizeof(arr))
using namespace std;
char map[110][110];
const int INF = 0x3f3f3f3f;
int dist( int x1, int y1, int x2, int y2 )
{
return abs( x1 - x2 ) + abs( y1 - y2 );
}
int main()
{
std::ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen( "in.txt", "r", stdin );
//freopen( "out.txt", "w", stdout );
clock_t program_start, program_end;
program_start = clock();
#endif
int M, N, x1, y1, x2, y2, res_x1, res_y1, res_x2, res_y2;
while ( scanf("%d %d", &M, &N) && M + N )
{
for ( int i = 0; i < M; ++i )
scanf("%s", map[i]);
int res = INF;
for ( x1 = 0; x1 < M; ++x1 )
for ( y1 = 0; y1 < N; ++y1 )
for ( x2 = 0; x2 < M; ++x2 )
for ( y2 = 0; y2 < N; ++y2 )
{
if ( map[x1][y1] == 'H' && map[x2][y2] == 'C' )
if ( dist( x1, y1, x2, y2 ) < res )
{
res = dist( x1, y1, x2, y2 );
res_x1 = x1;
res_x2 = x2;
res_y1 = y1;
res_y2 = y2;
}
}
printf("%d %d %d %d\n", res_x1, res_y1, res_x2, res_y2);
}
#ifndef ONLINE_JUDGE
program_end = clock();
cerr << "Time consumed: " << endl << ( program_end - program_start ) << " MS" << endl;
#endif
}
| true |
a4155ca444070ba570496eee31f1e5e1313382e7 | C++ | mmi366127/Online_Judge | /zerojudge/b963 GIIA v.s. 死亡之握/b963 GIIA v.s. 死亡之握.cpp | UTF-8 | 906 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
char s[100];
int n, m;
int to_num(char c) {
if('A' <= c && c <= 'Z') {
return 10 + c - 'A';
}
if('a' <= c && c <= 'z') {
return 10 + c - 'a';
}
return c - '0';
}
char to_char(int x) {
if(x >= 10) {
return 'A' + x - 10;
}
return x + '0';
}
int main() {
while(~scanf("%d%s", &n, s)) {
int idx = 0, tmp = 0, temp = 0;
for(int i = 0; s[i]; i++) {
tmp = tmp * n + to_num(s[i]);
}
scanf("%d%s", &n, s);
for(int i = 0; s[i]; i++) {
temp = temp * n + to_num(s[i]);
}
scanf("%d", &m);
tmp += temp;
while(tmp) {
s[idx++] = to_char(tmp % m);
tmp /= m;
}
while(--idx >= 0) putchar(s[idx]);
putchar('\n');
}
return 0;
}
| true |
a903c35b506329d68bdf3a47af5085d0e8cbceb7 | C++ | Cl0v1s/IUT-sta | /Sta/HardEnemy.h | UTF-8 | 1,592 | 3.265625 | 3 | [] | no_license | #ifndef HARDENEMY_H
#define HARDENEMY_H
#include <string>
#include <sstream>
#include <math.h>
#include "EntityEnemy.h"
#include "EntityPlayer.h"
class HardEnemy : public EntityEnemy
{
public:
/** \brief HardEnemy
* Créer un nouvel enemi présentant une difficulté de niveau trois
* \param int x position x de l'entité
* \param int y position y del'entité
* \param int level index du niveau courant
* \param EntityPlayer* pointeur vers le joueur 1 afin de récupérer ses informations (qui sont identiques à celles du joueur 2)
*
*/
HardEnemy(int x, int y, int level, EntityPlayer *player);
/** \brief update
* Met à jour les informations de l'entité
* \param entities std::vector<Attack*>& Liste des attaques en cours afin de pouvoir potentiellement y ajouter une nouvelle.
* \return void
*
*/
void update(std::vector<Attack*> &entities);
/** \brief fire
* Permet à l'entité de tirer
* \param entities std::vector<Attack*>& Liste des attaques en cours afin de pouvoir y ajouter une nouvelle attaque.
* \return void
*
*/
bool fire(std::vector<Attack*> &entities);
/** \brief toString
* Retourne un string contenant l'ensemble des informations sur l'entité
* \return std::string informations
*
*/
std::string toString() const;
/** \brief collidWith
* Retourne si l'ennemi est en collision avec l'entité passée en paramètre
* \param other Entity&
* \return bool
*
*/
bool collidWith(Entity &other);
};
#endif
| true |
49f5739da18ff7944dd7676e23c152c473ae8cc5 | C++ | dongguadan/playsdk | /dgdplaysdk/scopelock.h | UTF-8 | 897 | 2.859375 | 3 | [] | no_license | #ifdef WIN32
#pragma once
#include <Windows.h>
class CCriticalSection
{
CCriticalSection(const CCriticalSection &refCritSec);
CCriticalSection &operator=(const CCriticalSection &refCritSec);
CRITICAL_SECTION m_CritSec;
public:
CCriticalSection()
{
InitializeCriticalSection(&m_CritSec);
};
~CCriticalSection()
{
DeleteCriticalSection(&m_CritSec);
};
void Lock()
{
EnterCriticalSection(&m_CritSec);
};
void Unlock()
{
LeaveCriticalSection(&m_CritSec);
};
};
class CScopeLock
{
CScopeLock(const CScopeLock &refAutoLock);
CScopeLock &operator=(const CScopeLock &refAutoLock);
protected:
CCriticalSection *m_pLock;
public:
CScopeLock(CCriticalSection *plock)
{
m_pLock = plock;
m_pLock->Lock();
};
~CScopeLock()
{
m_pLock->Unlock();
};
};
#endif
| true |
d4cca8a829e6d25a3112398a8f7640b3fb55fb6a | C++ | tingpan/dxsimhair | /HairSim/wrColorGenerator.cpp | UTF-8 | 813 | 2.984375 | 3 | [] | no_license | #include "precompiled.h"
#include "wrColorGenerator.h"
#include "wrMath.h"
wrColorGenerator::wrColorGenerator()
{
}
wrColorGenerator::~wrColorGenerator()
{
}
void wrColorGenerator::genRandLightColor(float* output)
{
for (int i = 0; i < 3; i++)
output[i] = 0.5 + 0.5 * randf();
}
void wrColorGenerator::genRandSaturatedColor(float* output)
{
for (int i = 0; i < 3; i++)
output[i] = randf();
float minval = 1.0f, maxval = 0.0f;
int minIdx = 0, maxIdx = 0;
for (int i = 0; i < 3; i++)
{
if (output[i] < minval)
{
minval = output[i];
minIdx = i;
}
if (output[i] > maxval)
{
maxval = output[i];
maxIdx = i;
}
}
output[minIdx] = 0.0f;
output[maxIdx] = 1.0f;
}
| true |
97ed67956c7c108fe6d5e3286c392fd241889f93 | C++ | hydrogen69/Probelm-solved | /UVA/11152/18058329_AC_20ms_0kB.cpp | UTF-8 | 443 | 2.5625 | 3 | [] | no_license |
#include<stdio.h>
#include<math.h>
#define pi 2*acos(0)
int main()
{
double a,b,c,i,j;
double s,r1,r2,triangle,circum,inscribed;
while(scanf("%lf%lf%lf",&a,&b,&c)==3)
{
s=(a+b+c)/2;
triangle=sqrt(s*(s-a)*(s-b)*(s-c));
r1=((a*b*c)/sqrt((a+b+c)*(b+c-a)*(c+a-b)*(a+b-c)));
r2=triangle/s;
circum=(pi*pow(r1,2))-triangle;
inscribed=(pi*pow(r2,2));
triangle=triangle-inscribed;
printf("%.4f %.4f %.4f\n",circum,triangle,inscribed);
}
return 0;
}
| true |
ef2644b5c7fd491de620c3bcf77d6ff21d702ab5 | C++ | snailbaron/buzz-legacy | /src/res_cache.hpp | UTF-8 | 1,274 | 2.6875 | 3 | [] | no_license | #ifndef _RES_CACHE_HPP_
#define _RES_CACHE_HPP_
#include <list>
#include <map>
#include <string>
#include <memory>
#include "res_handle.hpp"
#include "resource.hpp"
#include "resource_file.hpp"
typedef std::list<std::shared_ptr<ResHandle>> ResHandleList;
typedef std::map<std::string, std::shared_ptr<ResHandle>> ResHandleMap;
class ResCache
{
public:
ResCache(const unsigned int sizeMb, ResourceFile *resFile);
~ResCache();
bool Init() { return m_file->Open(); }
std::shared_ptr<ResHandle> GetHandle(Resource *r);
void Flush();
protected:
// List of resource handles, in least-recently-used order
ResHandleList m_lru;
// Resource handle map for resource lookup
ResHandleMap m_resources;
ResourceFile *m_file;
unsigned int m_cacheSize; // total memory size for cache
unsigned int m_allocated; // amount of memory allocated
std::shared_ptr<ResHandle> Find(Resource *r);
const void * Update(std::shared_ptr<ResHandle> handle);
std::shared_ptr<ResHandle> Load(Resource *r);
void Free(std::shared_ptr<ResHandle> handle);
bool MakeRoom(unsigned int size);
char * Allocate(unsigned int size);
void FreeOneResource();
void MemoryHasBeenFreed(unsigned int size);
};
#endif
| true |
d615754dbd780df0b84dab82dad4b09457773389 | C++ | NanlinW/NanlinCode | /exercise_11_9/Date.h | GB18030 | 495 | 3.046875 | 3 | [] | no_license | #include<iostream>//ͷļ
using namespace std; //c++
class Date
{
friend std::ostream& operator<<(std::ostream&, Date&);//
friend std::istream& operator>>(std::istream&, Date&); //
public:
Date();//յĹ캯
Date(int y, int m, int d);
void setDate(int y, int m, int d);
int getyear()
{
return year;
}
void addDay();
void subtractDay();
void print();
private:
int year;
int day;
int month;
};
| true |
183cab270d87f086b9ebe1b572eddf60e91a9642 | C++ | andrenho/perminal | /.old/cpp/emulator/cursor.h | UTF-8 | 572 | 2.796875 | 3 | [] | no_license | #ifndef CURSOR_H
#define CURSOR_H
#include "config.h"
#include "chars.h"
struct P {
int x, y;
inline bool operator<(P const& other) const {
return ((x<<16) + y) < ((other.x<<16) + other.y);
}
inline bool operator==(P const& other) const {
return other.x == x && other.y == y;
}
};
class Cursor {
public:
Cursor() : x(0), y(0) {}
operator P() const { return P{x, y}; }
Color color() const;
int x, y;
enum { INVISIBLE, VISIBLE, VERY_VISIBLE } intensity = VISIBLE;
};
#endif
// vim: ts=4:sw=4:sts=4:expandtab
| true |
7e5169b449230cd619d96f9e76fcf8aa616f10bb | C++ | cli851/noi | /1065.cpp | UTF-8 | 187 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int m,n;
int sum=0;
cin>>m>>n;
for(int i=m;i<=n;i++){
if(i%2!=0){
sum+=i;
}
}
cout<<sum;
return 0;
}
| true |
bcea01a0d77cfe44e7a8fbd758ab063d8cd6828e | C++ | hank08tw/poj | /3046.cpp | UTF-8 | 957 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
long long dp_first[1000001];
long long dp_second[1000001];
int a[1001];
const int mod=1e6;
int t,A,s,b,tmp;
int main(){
scanf("%d %d %d %d",&t,&A,&s,&b);
memset(a,0,sizeof(a));
memset(dp_first,0,sizeof(dp_first));
memset(dp_second,0,sizeof(dp_second));
for(int i=0;i<A;i++){
scanf("%d",&tmp);
a[tmp]++;
}
for(int i=0;i<=A;i++){
dp_first[i]= a[1]>=i ? 1 : 0;
}
for(int i=2;i<=t;i++){
dp_second[0]=1;
dp_second[1]=i;
for(int j=2;j<=A;j++){
if((j-1-a[i])>=0){
dp_second[j]=(dp_second[j-1]+dp_first[j]-dp_first[j-1-a[i]])%mod;//+mod保證dp_second[j]是正數
}else{
dp_second[j]=(dp_second[j-1]+dp_first[j])%mod;
}
}
for(int j=0;j<=A;j++){
dp_first[j]=dp_second[j];
}
}
int ans=0;
for(int i=s;i<=b;i++){
ans=(ans+dp_first[i])%mod;
}
cout << (ans+mod)%mod << endl;//也可以最後再加
}
| true |
d636760c630f250483e072ac6c5882269cd61520 | C++ | kkimmm/Cpp-Program | /MyBinaryTree/bt.cpp | GB18030 | 1,213 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct BiNode
{
char data;
BiNode *lchild, *rchild;
};
void CreatBiTree(BiNode *&T)
{
char ch;
ch = getchar();
if (ch== '#')//עʹ''""
T = NULL;
else
{
T = new BiNode;
T->data = ch;
CreatBiTree(T->lchild);
CreatBiTree(T->rchild);
}
}
//
void PreOrderTraverse(BiNode *&T)
{
if (T)
{
cout << T->data;
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
//
void MidOrderTraverse(BiNode *&T)
{
if (T)
{
MidOrderTraverse(T->lchild);
cout << T->data;
MidOrderTraverse(T->rchild);
}
}
//
void LastOrderTraverse(BiNode *&T)
{
if (T)
{
LastOrderTraverse(T->lchild);
LastOrderTraverse(T->rchild);
cout << T->data;
}
}
int main()
{
BiNode *T;
cout << "please input a binary tree(using PreOrder), input # means null or leaf node" << endl;
CreatBiTree(T);
cout << "using PreOrder we have the binary tree:" << endl;
PreOrderTraverse(T);
cout << endl;
cout << "using MidOrder we have the binary tree:" << endl;
MidOrderTraverse(T);
cout << endl;
cout << "using LastOrder we have the binary tree:" << endl;
LastOrderTraverse(T);
cout << endl;
return 0;
} | true |