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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
00db65754fefa27afd0ed38cfbde904f305f6a5d | C++ | vehar/la10cee | /src/DBThread.cpp | UTF-8 | 5,517 | 2.625 | 3 | [] | no_license | #include "DBThread.h"
DBThread::DBThread(StatMaps* statMaps, const string& dbConnectionOptions)
: m_statMaps(statMaps)
{
m_lastStatOutput = time(NULL);
m_dbConnection = new connection(dbConnectionOptions);
}
DBThread::~DBThread()
{
stop();
}
bool DBThread::run()
{
cerr << "<DBThread>\tStarting" << endl;
try
{
// ************** Lock here
{
AutoLock lock(&m_runningLock);
m_running = true;
}
// ************** Unlock here
while(true) {
// stop processing if required
{
AutoLock lock(&m_runningLock);
if(m_running == false) {
break;
}
}
// only output stats every x seconds
sleep(30);
cerr << "*********************************************************" << endl;
vector<string>* totalStatsKeys = m_statMaps->m_totalStats.keys();
auto_ptr<vector<string> > totalStatsKeysAP(totalStatsKeys);
for(vector<string>::iterator i = totalStatsKeys->begin(); i != totalStatsKeys->end(); i++) {
cerr << time(NULL) << ":" << *i << "\t:" << m_statMaps->m_totalStats[*i] << endl;
}
vector<u_int>* totalPortStatsKeys = m_statMaps->m_totalPortStats.keys();
auto_ptr<vector<u_int> > totalPortStatsKeysAP(totalPortStatsKeys);
for(vector<u_int>::iterator i = totalPortStatsKeys->begin(); i != totalPortStatsKeys->end(); i++) {
cerr << time(NULL) << ":" << *i << "\t:" << m_statMaps->m_totalPortStats[*i] << endl;
}
/*
for(TotalStatsByIp_t::iterator i = m_totalStatsByIp.begin(); i != m_totalStatsByIp.end(); i++) {
cerr << time(NULL) << ":" << i->first << "\t:" << i->second << endl;
}
*/
/*
for(ConnectionStats_t::iterator i = m_connectionStats.begin(); i != m_connectionStats.end(); i++) {
TCPConnection* curConnection = i->second;
cerr << time(NULL) << ":"
<< curConnection->sourceIP() << ":" << curConnection->sourcePort()
<< ":"
<< curConnection->destinationIP() << ":" << curConnection->destinationPort()
<< ":"
<< curConnection->bytesIn()
<< ":"
<< curConnection->bytesOut()
<< endl;
}
*/
cerr << "----------------------------------------------------------" << endl;
vector<IPTCPPort>* connectionsKeys = m_statMaps->m_connections.keys();
auto_ptr<vector<IPTCPPort> > connectionsKeysAP(connectionsKeys);
for(vector<IPTCPPort>::iterator portIterator = connectionsKeys->begin(); portIterator != connectionsKeys->end(); portIterator++) {
IPTCPPort ipPort = *portIterator;
TCPConnection* curConnection = m_statMaps->m_connections.find(ipPort);
stringstream ss;
ss << ipPort.ipA() << ":" << ipPort.portA() << ":" << ipPort.ipB() << ":" << ipPort.portB()
<< ":" << curConnection->bytesIn() << ":" << curConnection->bytesOut()
<< ":" << curConnection->connectionState()
;
cerr << ss.str() << endl;
}
cerr << "*********************************************************" << endl;
cerr << "1.1" << endl;
StatsTransactor st(m_statMaps);
cerr << "1.1.1:m_dbConnection (" << m_dbConnection << ")" << endl;
cerr << "1.2:m_dbConnection is open (" << m_dbConnection->is_open() << ")" << endl;
//m_dbConnection->activate();
cerr << "1.3:m_dbConnection is open (" << m_dbConnection->is_open() << ")" << endl;
m_dbConnection->perform(st);
cerr << "1.4" << endl;
}
}
catch(Exception& e)
{
cerr << "location [" << e.getLocation() << "] error [" << e.getError() << "]" << endl;
// abort();
}
cerr << "<DBThread>\tprocessing complete" << endl;
return(true);
}
StatsTransactor::StatsTransactor(StatMaps* statMaps)
: m_statMaps(statMaps)
{
}
void StatsTransactor::operator()(work &work) {
vector<IPTCPPort>* connectionsKeys = m_statMaps->m_connections.keys();
auto_ptr<vector<IPTCPPort> > connectionsKeysAP(connectionsKeys);
for(vector<IPTCPPort>::iterator portIterator = connectionsKeys->begin(); portIterator != connectionsKeys->end(); portIterator++) {
IPTCPPort ipPort = *portIterator;
TCPConnection* curConnection = m_statMaps->m_connections.find(ipPort);
stringstream ss;
ss
<< "insert into connection_pair ("
<< "ipA, portA, ipB, portB, start_date, end_date, state, data_in, data_out, packets_in, packets_out) "
<< "values ("
<< "'" << ipPort.ipA() << "'"
<< ", " << ipPort.portA()
<< ", " << "'" << ipPort.ipB() << "'"
<< ", " << ipPort.portB()
<< ", " << "CURRENT_TIMESTAMP"
<< ", " << "CURRENT_TIMESTAMP"
<< ", " << curConnection->connectionState()
<< ", " << curConnection->bytesIn()
<< ", " << curConnection->bytesOut()
<< ", " << curConnection->packetsIn()
<< ", " << curConnection->packetsOut()
<< ")"
;
cerr << "executing SQL (" << ss.str() << ")" << endl;
work.exec(ss.str());
if((curConnection->connectionState() == STATE_CLOSED) || (curConnection->connectionState() == STATE_RESET)) {
m_closedConnections.push_back(ipPort);
}
}
}
void StatsTransactor::on_commit() {
cerr << "(StatsTransactor::on_commit)-*** CALLED ***" << endl;
for(vector<IPTCPPort>::iterator i = m_closedConnections.begin(); i != m_closedConnections.end(); i++) {
m_statMaps->m_connections.remove(*i);
}
}
/*
create table connection_pair (
id serial not null primary key
,ipA text not null
,portA int not null
,ipB text not null
,portB int not null
,start_date timestamp not null
,end_date timestamp not null
,state text not null
,data_in int not null default 0
,data_out int not null default 0
,packets_in int not null default 0
,packets_out int not null default 0
);
*/
| true |
37c0d8dac17d1953c3cfe25d48e9dd182287bdb3 | C++ | paperfrog1228/Algorithm | /Baekjoon/6603_로또.cpp | UTF-8 | 646 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
int k,lotto[15],visit[15],ans[7],cnt=-1;
void Lotto(int i){
if(visit[i])
return;
visit[i]++;
cnt++;
ans[cnt]=lotto[i];
if(cnt<6)
for(int j=i;j<=k;j++)
Lotto(j);
else{
for(int i=1;i<=6;i++)
printf("%d ",ans[i]);
printf("\n");
}
visit[i]=0;
cnt--;
}
bool Test(){
scanf("%d",&k);
if(k==0)
return true;
for(int i=1;i<=k;i++)
scanf("%d",&lotto[i]);
Lotto(0);
return false;
}
int main(){
while(1){
if(Test())
return 0;
printf("\n");
}
}
| true |
5ee96fd1a5c139148a0a77944a5ca58699ffaf8b | C++ | dandaso/uds_loadtester | /src/uds_loadtest.cpp | UTF-8 | 2,919 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <boost/progress.hpp>
#include <boost/timer.hpp>
#include <boost/program_options.hpp>
#include <boost/thread/mutex.hpp>
#ifdef BOOST_ASIO_HAS_LOCAL_SOCKETS
using boost::asio::local::stream_protocol;
#else
#error THIS_PLATFORM_IS_NOT_SUPPORTED_LOCAL_SOCKETS
#endif
class progress_bar{
private:
boost::progress_display bar;
boost::mutex io_mutex;
public:
static const long COMPLETE = -1;
progress_bar(long _max) : bar(_max) {};
inline long increment() {
boost::mutex::scoped_lock lock(io_mutex);
return bar.expected_count() <= bar.count() ? COMPLETE : ++bar;
}
};
void run(std::string message, progress_bar *bar, std::string end_point) {
boost::asio::io_service io_service;
stream_protocol::socket s(io_service);
try {
s.connect(stream_protocol::endpoint(end_point));
char response[1024];
while(bar->increment() != bar->COMPLETE) {
boost::asio::write(s, boost::asio::buffer(message));
boost::asio::read(s,
boost::asio::buffer(response, 1024),
boost::asio::transfer_at_least(4));
}
s.close();
} catch(std::exception const& e) {
std::cerr << e.what() << std::endl;
return;
}
}
int main(int argc, char** argv) {
namespace po = boost::program_options;
int num_of_requests = 1000000;
int num_of_currencies = 4;
std::string message = "test";
std::string sock;
po::options_description desc("Options");
desc.add_options()
("help,h", "Display usage information (this message)")
("requests,n", po::value<int>(&num_of_requests), "Number of requests to perform")
("concurrency,c", po::value<int>(&num_of_currencies), "Number of multiple requests to make")
("sock,s", po::value<std::string>(&sock), "Path to unix domain socket")
("message,m", po::value<std::string>(&message), "Send message to socket");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
std::cout << desc << std::endl;
return 1;
}
if (vm.count("help")) {
std::cout << desc << std::endl;
return 1;
}
progress_bar bar(num_of_requests);
boost::timer t;
boost::thread_group thread_group;
for (int i = 0; i < num_of_currencies; ++i) {
thread_group.create_thread(boost::bind(&run, message, &bar, sock));
}
thread_group.join_all();
double elapsed_time = t.elapsed();
double qps = static_cast<double>(num_of_requests) / elapsed_time;
std::cout << "Concurrency Level: " << num_of_currencies << std::endl;
std::cout << "Num of requests: " << num_of_requests << std::endl;
std::cout << "Time taken for tests: " << elapsed_time << " sec" << std::endl;
std::cout << "Requests per second: " << qps << " req/sec" << std::endl;
return 0;
}
| true |
eebfa0003be43843064793a516c422f89b276c03 | C++ | PPXComputer/study | /graph1.h | GB18030 | 13,971 | 3.234375 | 3 | [] | no_license | /* ļ洢йؼͼĴ
*ʵֹͼڽӱ( ά List_[0]={ 2,3 3,4 } ʾ 0--2 Ϊ Ȩֵ3 0---3ΪȨֵ4 ʺϡͼ ȱظ¼ )
*ע ڽ̲ ڽӱ ıʾ vector<list<T>> List List[0] ={ 2->3->4 }ʾ 02 3 4
*ڽӾ(Matrix[3][4]=2 ʾ3---4 ΪȨֵ 2 ȨֵΪ INT_MAX ʾûб ʺϳͼ Ǿ洢Խʡռ )
* ڽӾ ȱ߽ vector<list< T>> list List List[0] ={ 2->3->4 }ʾ 2 3 4 0
* ʮ ǽ vector<(out< T> ,in<T >) > > in out һ а ڽӱдǰ ӵ
* Ľڵ Ϊȹϵ Ӷ ڽӱһ O(N+M) N Mڵ
*ʵBFS breath first search
*÷visited[] ȳʼ ȫΪ0 visited[3]=1 ʾ 3 ѱ(ɶλȷ)
*ڽӾڽӱ Ϊ1 ߵĽȫһ
*ʵDFS depth fisrt search ѡ ߵĵ ηʶеĵ Ϊ ظ ()
* BFSķʵĽڵɿΪ һ Ϊ
*!!!עDijKstra㷨floyd㷨 ǸȨͼ
*DijKstra㷨·㷨 constr[] ·side[]
* constr constrڵĵ㰴Ȩֵside[] (ûڽӵ )
*ѡsideСȨֵĵ constr constrӵ ˢ side[] ظ ֱյ
*
*floyd㷨 ֮· Դ·
* ȹ D ͼڽӾ D[2][3]=9 ʾ 23 ֱͨ ȨֵΪ9 INT_MAXͨ
*P ת ( A->B Ȩֵ Ϊ ʱ C A->C->B =9 <10 CΪת
* һʹ Ȩֵ Ǵ˵ Ϊת ) p[2][3 ]= 1 ʾתϵΪ 2->1->3 1ʹ 2 ->3ȨֵͼС
*Pʵ Ϊ 1. ȽP Dʼ A,B֮б P[A][B]=A Ϊ -1
*2. Դ A C D D[C][A]+D[D][A] <D[C][D] zD[C][D]=D[C][A]+D[D][A] (˴Ϊ) P[C][D]=A
*3. E C D P[C][E]+p[D][E] <p[C][E] zP[C][D]=E(˴Ϊ) ظ2 ֱж㶼
*
* P鱣Ϣ· P[A][B]=C ʾ·ΪA->C->BȨֵΪ D[C][A]+D[D][A]
*
*!!!ע Prim kruskal (㷨Ҫ· )
*Prim constr[] constrдŵٽ ȨֵСķconstr ظ˹ ֱеĶ(N -1 )
*Krsukal ÿ¼ȨֵСı ظ˹ ֱеĶ(N -1 )
*!!!!!ļȱ
* ʹô STL ³ڴռƫ
* Ʋ : vertexes ַ ʾ Ϣ ܷ Ȩֵ ̶ȹ
*2018-09-20 ʱ23:36
*/
#ifndef GRAPH1_H
#define GRAPH1_H
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<set>
#include<utility>
#include<memory>
#include<tuple>
using std::cin;
using std::cout;
using std::shared_ptr;
using std::vector;
using std::make_shared;
using std::queue;
using std::pair;
using std::set;
using std::string;
constexpr auto INTmax = 6555;//ڽӾȨֵֵ;
using Matrix = vector<vector<int>>;//ͱ
using List_ = vector<vector<pair<int, int>>>;//ڽӱ ... ȱ
//ڽӱͱ
//ͼȨͼ ʹٽӱ洢
class Graph
{
public:
Graph() = default;
void creat();
void print()
{
BFSTraverse();
DFSTraverse();
}
Graph &operator=(const Graph&) = delete;
~Graph() = default;
private:
string vertexes;//еĶ ַ
Matrix matrix;//ڽӾ
List_ List;//ڽӱ pair һǽ ڶȨֵ
int numVertexes = 0;//
int numEdges = 0;//
void BFS(vector<int>&);//Breath First Search 㷨
void DFS(vector<int>&, int);//Depth First Search 㷨
void BFSTraverse();//BFSȫ
void DFSTraverse();//DFSȫ
//BFSķʵĽڵɿΪ һ Ϊ
void unweighted(int&);//ȨͼĵԴ· ΪͼȨ Դ˷ ĬϽȨֵΪ1
void DijKstra(int &);//Ȩͼ·㷨 ÿν·ѡʱʹŽ
//ͼͨͼ û
vector<pair<int, int>> tree;//ʾΪ· tree[1]={2,3}ʾ 2---3·
//С ʵִͨ ʵȨֵС ԵĽ
//IJ ڶе± Ϊ
void Prim(int &);//ӵ㷨
void Kruskal();// ӱ߷ kruskal㷨СÿѡȡСı ֱȫ¼
void check_site(int &);//
};
inline void Graph::creat()
{//ע͵ĴԭĴ
cout << "붥ͱ";
//numVertexes = 8; numEdges=5;
cin >> numVertexes >> numEdges;
cout << "붥Ϣ붥(ַ)";
//붥붥
//vertexes = "abcdefgh";
cin >> vertexes;
/* ʾ ͨ ӳʼvector ʱռ
for (int i = 0; i < numVertexes; ++i)
{
vector<int>retemp;//Ԥռ
for (int p = 0; p < numVertexes; ++p)
{
retemp.push_back(INTmax);
}
matrix.push_back(retemp);//ȷʼ
}*/
matrix.reserve(numVertexes);//ʼռС
cout << "ͼ Ӧ± i,j Ȩֵ";
int weghit1 = 0; int j = 0; int i = 0;
for (int p1 = 0; p1 < numEdges; ++p1)
{
cin >> i >> j >> weghit1;
matrix[i][j] = weghit1;
matrix[j][i] = weghit1;//ΪN*NľԳ
}
//ռ Ҫ䶯̬List.reserve(numVertexes);
//ɨڽӾһ ڽӱ
List.reserve(numEdges);
for (int p1 = 0; p1 < numEdges; ++p1)
for (int p2 = 0; p2 < numEdges; ++p2)
{
int matemp = matrix[p1][p2];
if (matemp != INTmax)
List[p1].push_back(std::make_pair(p2, matemp));//Խ???
}
}
inline void Graph::BFS(vector<int>&visited)
{
//öʵڲ
queue<int> contianer;
//1ʾѾ
for (int i = 0; i < numVertexes; i++)//ɨ Ӧ
{
if (visited[i] == 0)//ûзѹ
{
visited[i] = 1;
cout << vertexes[i];//ӡ
contianer.push(vertexes[i]);
while (!contianer.empty())
{
auto temp = contianer.front();
contianer.pop();
//ɨһн жûзʵĽ
for (int j = 0; j < numVertexes; ++j)
{
if (matrix[i][j] != INTmax && !visited[j])
{
visited[j] = 1;
cout << vertexes[j];//ӡ
contianer.push(vertexes[j]);
}
}
}
}
}
}
inline void Graph::DFS(vector<int>&visited, int site)
{
// ײǽͷ
visited[site] = 1;
int j = 0;
cout << vertexes[site];//ӡ
for (; j < numVertexes; ++j)
{
if (matrix[site][j] != INTmax && !visited[j])//Ϊڽӵ ûбʹ
DFS(visited, j);//һڵ
}
}
inline void Graph::BFSTraverse()
{
vector<int> visited;//ʱ־
for (auto sd = numVertexes; sd > 0; --sd)
{//0ʾ δ
visited.push_back(0);//ȫʼ
}
cout << "DFSı";
BFS(visited);
cout << std::endl;
}
inline void Graph::DFSTraverse()
{
vector<int> visited;//ʱ־
for (auto sd = numVertexes; sd > 0; --sd)
{//0ʾ δ
visited.push_back(0);//ȫʼ
}
cout << "DFSı";
for (int i = 0; i < numVertexes; ++i)
{
if (!visited[i])
DFS(visited, i);
}
cout << std::endl;
}
inline void Graph::unweighted(int& i)
{ //Ĭԭ Ϊvertexe[ i ]
check_site(i);
vector<int> dist;//distance ʼΪ-1ʾδʵĽ ԭΪ0 Ȩֵ1
//dist[] ֵʾ ԭľ
for (int s = 0; s < numVertexes; ++s)
{
dist.push_back(-1);
}
vector<int> path;// ӦǶ± path[0]=1ʾΪ V1~~V0
for (int s = 0; s < numVertexes; ++s)
{
path.push_back(-1);
}
queue<int> container;//Ӧ±
container.push(i);
while (!container.empty())
{
auto temp = container.front();//浱ǰ±
for (int i = 0; i < numVertexes; ++i)
{
auto sd = matrix[temp][i];
if (sd != INTmax)//ڵ
if (dist[sd] == -1)
{
dist[sd] = dist[temp] + 1;//+Ȩֵ1
path[sd] = temp;
}
}
}
cout << "ӦֵΪ";
for (auto s : dist) { cout << s; }cout << std::endl;
cout << "·Ϊ";
for (auto s : path) { cout << s; }//ӡϢ
}
inline void Graph::DijKstra(int & i)
{
//Ϊ̰㷨 ÿѡ·
//1.. ѹ
// 2...ѡ Ԫص ̵ⲿ ѹ ֱⲿ
//3... ˢⲿ ظ 2
check_site(i);
vector<int> visited;//ʱ־
for (auto sd = numVertexes; sd > 0; --sd)
{//0ʾ δ
visited.push_back(0);//ȫʼ
}
vector<int>container(vertexes[i]);// 洢ֵʾΪ
visited[i] = 1;//
vector<int>path;//Ӧ path[1]=2; container[1]ʾĽ Ȩֵ Ϊ2
for (int i = 0; i < numVertexes; ++i) {
path.push_back(0);
}
while (true)
{
int min = INTmax; int sentry = 0;
for (auto j : container)
for (int i = 0; i < numVertexes; ++i)
{
if (matrix[j][i] < min&&visited[i] != 0)
{
min = matrix[j][i];
sentry = i;//¼ȨֵСĽ
path[j] = i;//ʾ J ~~ I
}
}
if (min != INTmax)//С
{
visited[sentry] = 1;
container.push_back(sentry);
}
else break;
}
for (auto sd : container) { cout << sd; }
for (auto sd : path) { cout << sd; }
}
inline void Graph::Prim(int & i)
{
//ΪN N-1 ·
// еı еĽ(ͼͨ)
//ȨֵС(˲DijKstra㷨 ѡһΪÿ¼С )
check_site(i);
vector<int> visited;//ʱ־
for (auto sd = numVertexes; sd > 0; --sd)
{//0ʾ δ
visited.push_back(0);//ȫʼ
}
vector<int>container(vertexes[i]);// 洢ֵʾΪ
visited[i] = 1;//
while (container.size() != numVertexes)//ж ˳
{
int min = INTmax; int sentry = 0; int sign = 0;
for (auto j : container)
for (int i = 0; i < numVertexes; ++i)
{
if (matrix[j][i] < min&&visited[i] != 0)
{
min = matrix[j][i];
sign = j;//¼ʼ±
sentry = i;//¼ȨֵСĽ
}
}
if (min != INTmax)//С
{
visited[sentry] = 1;
container.push_back(sentry);
tree.push_back({ sign,sentry });//ѹ·
}
else { cout << ""; break; }
}
}
inline void Graph::Kruskal()
{
//ÿ¼ȨֵСı ֱΪ N-1߾
//ʵСֵɾ ӦʹС ɻóʱĸӶ
List;//ڽӱ
set<std::tuple<int, int, int>> container;//ǰint int ʾһ ΪȨֵ
for (int i = 0; i < numEdges; ++i)
for (int size = 0; size < List.size(); ++size)
{
int temp = 0; int temp2 = 0;//ʱ ͬһ set Сķǰ
if (size < List[i][size].first) {
temp = size; temp2 = List[i][size].first;
}
else
{
temp2 = size; temp = List[i][size].first;
}
container.insert(std::make_tuple(temp, temp2, List[i][size].second));
}
//ȨֵǰȨֵСߵļ
std::sort(container.begin(), container.end(),
//lambdaʽ
[](std::tuple<int, int, int > & lhs, std::tuple<int, int, int >& rhs)
{
if (std::get<2>(lhs) < std::get<2>(rhs))return true;
else return false; //ȨֵȽ
}
);
if (container.size() < numEdges - 1)cout << "С";
}
inline void Graph::check_site(int &i)
{
int size = vertexes.size();
if (i<0 || i>size - 1) {
try
{
throw i;
}
catch (const int&)
{
cout << "IJ";
cin >> i;
}
}
}
#endif // !GRAPH1_H
| true |
f4e917b5cac334edb254ef62b55cf8e4fe48b0ad | C++ | ThorbenQuast/RepellingInteractionTrajectory | /integral.cc | UTF-8 | 4,120 | 2.90625 | 3 | [] | no_license | //compile and run:
//g++ integral.cc -o integral.out && ./integral.out
#include <iostream>
#include <cmath>
double c = 299792458.0; //speed of light in m/s
double m_e = 0.511*10e-3; //electron mass in keV
double pi = 3.1415926535897;
double deg_to_rad = (pi/180);
double invGev_to_m2 = 0.389379*pow(10, -3) * pow(10, -28);
/**********/
//parameterisation of the structure function
double p0_pdf_a = 1.42334682e+03;
double p1_pdf_a = 8.13911499e+00;
double p2_pdf_a = -6.44188039e-01;
double p0_pdf_kappa = -5.27385445e+02;
double p1_pdf_kappa = 5.24698650e+02;
double p2_pdf_kappa = 1.98072582e+00;
double p3_pdf_kappa = 3.66260610e-03;
double l_pdf = 0.35;
double a(double x) {
double logx10 = log(x)/log(10.0);
return 0.1 + p0_pdf_a * exp(-p1_pdf_a * ((p2_pdf_a-logx10)+ exp(-(p2_pdf_a - logx10))));
};
double kappa(double x) {
double logx10 = log(x)/log(10.0);
return p0_pdf_kappa + p1_pdf_kappa * pow(((1-logx10)*p2_pdf_kappa), p3_pdf_kappa);
}
double xpdf(double x, double t) {
return a(x)*pow(2*log(t/l_pdf),kappa(x));
};
/**********/
double eta_q(double theta) {
return -log(tan(theta/2));
};
//cross section formula
double d2sigma_dthetaq_dt(double bjorken_x, double t) {
if (bjorken_x <= 0 || bjorken_x > 1) return 0.0;
if (t < 3.5) return 0.0;
return xpdf(bjorken_x, t)/(bjorken_x * pow(t,2));
};
//checked with Christian's "get_x" function --> same result
double get_x(double eta_q, double Q2, double s, double Ep, double Ee) {
return Q2/(2.*s) + sqrt(pow(Q2/(2.*s), 2) + Q2/s * Ee/Ep * exp(2*eta_q));
}
/**********/
//differentials to be multiplied to the integrand
double get_dx_detaq(double eta_q, double Q2, double s, double Ep, double Ee) {
return Q2/s * Ee/Ep * exp(2*eta_q) / sqrt(pow(Q2/(2*s), 2) + Q2/s * Ee/Ep * exp(2*eta_q));
} //cross-checked with Wolfram alpha
double get_detaq_dx(double theta_q) {
return -1./tan(theta_q/2.) / pow(cos(theta_q/2.), 2) / 2.; //note: equivalent to -/sin(theta)
}
/**********/
int main(int argc, char* argv[]){
//machine parameters
double Ep = 1.0; //proton's mass is 1GeV
double Ee = 60.; //electron energy is set to 60GeV
//boost energies into cm frame
double pe = sqrt((Ee*Ee - m_e*m_e)); // momentum of electron
double beta = pe / (Ee + Ep); // beta of boost into CMS system
double gamma = pow(1 - pow(beta,2), -0.5);
Ep = Ep * gamma; // energy of proton in CMS
Ee = (Ee - beta * pe) * gamma; // energy of electron in CMS
double s = 4 * Ep * Ee;
int N_granularity = 20000; //number of steps, adjust here.
double Q2, Q2_start; Q2 = Q2_start = 3.5; //minimum momentum transfer in DIS
double theta_q, theta_q_start; theta_q = theta_q_start = 0.01*deg_to_rad; //no scattering into the beam-pipe
double dQ2 = (pow(Ee, 2) - Q2)/N_granularity;
double dtheta_q = (180.*deg_to_rad-2*theta_q_start) / N_granularity;
//integrate as function of theta and Q2
double integral = 0.;
//test cout:
Q2 = 10.;
theta_q = 2.6;
double _eta_q_test = eta_q(theta_q);
double x_test = get_x(_eta_q_test, Q2, s, Ep, Ee);
std::cout<<"Comparison with Christian: Q2 = "<< Q2<<" theta_q = "<<theta_q<<" --> "<<d2sigma_dthetaq_dt(x_test, Q2) * fabs(get_dx_detaq(_eta_q_test, Q2, s, Ep, Ee)) * fabs(get_detaq_dx(theta_q)) * pow(1./137, 2) * (1./(4.*pi)) * invGev_to_m2*pow(10, 28)<<std::endl;
theta_q = theta_q_start;
//integral is approximated as a sum of all the rectangles
for (int i=0; i<N_granularity; i++) {
theta_q = theta_q + dtheta_q;
Q2 = Q2_start;
for (int j=0; j<N_granularity; j++) {
Q2 = Q2 + dQ2;
double _eta_q = eta_q(theta_q);
double x = get_x(_eta_q, Q2, s, Ep, Ee);
integral = integral + d2sigma_dthetaq_dt(x, Q2) * fabs(get_dx_detaq(_eta_q, Q2, s, Ep, Ee)) * fabs(get_detaq_dx(theta_q)) * dtheta_q * dQ2;
}
}
integral = pow(1./137, 2) * (1./(4.*pi)) * integral * invGev_to_m2;
std::cout<<"Integrated cross section: "<<integral<<" m2 = "<<integral*pow(10, 28+12)<< "pb" <<std::endl;
return 0;
}
| true |
8b59a2b92165771bb4a981a1a2dbe2bcb96b17f8 | C++ | Slava/competitiveProgramming | /more-source/2010-2011/Karaganda_camp_7_8/solutions/7.3/c.cpp | UTF-8 | 281 | 2.65625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int n,next,temp,counter=0;
cin>>n;
cin>>next;
for(int i=1; i<n; i++) {
cin>>temp;
if(next==temp) {counter++;}
next=temp;
}
cout<<counter;
return 0;
} | true |
87f77c73011fbd601c5c84287a5c4e0b708494c6 | C++ | edrummon/NetBeans | /AccCpp/Acc10ArraysPointers/main.cpp | UTF-8 | 2,848 | 3.40625 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Instinct212
*
* Created on May 26, 2014, 7:52 PM
*/
#include <fstream>
#include <cstring>
#include "median.h"
#include "stringList.h"
using std::string; using std::ifstream;
using std::cout; using std::endl;
using std::cin; using std::cerr;
using std::copy; using std::vector;
using std::find_if;
int* pointer_to_static() {
static int x;
return &x;
}
int* pointer_to_dynamic() {
return new int(42);
}
char* duplicateChars(const char* p) {
size_t size = strlen(p) + 1;
char* result = new char[size];
copy(p, p+size, result);
return result;
}
string letter_grade(double grade) {
static const int numbers[] = {97, 94, 90, 87, 84, 80, 77, 74, 70, 60, 0};
static const char* const letters[] = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "F"};
static const size_t ngrades = sizeof(numbers)/sizeof(*numbers);
for (size_t i = 0; i < ngrades; ++i) {
if (grade >= numbers[i])
return letters[i];
}
return "?/?/?";
}
bool space(char c) {return isspace(c);}
bool not_space(char c) {return !isspace(c);}
void split(const string& str, StringList& strList) {
typedef string::const_iterator iter;
iter i = str.begin();
while (i != str.end()) {
i = find_if(i, str.end(), not_space);
iter j = find_if(i, str.end(), space);
if (i != j)
strList.addString(string(i, j));
i = j;
}
}
int main(int argc, char** argv) {
double checkGrade;
cin >> checkGrade;
cout << letter_grade(checkGrade) << "\n\n";
string fileString = "fileToRead.txt";
ifstream file(fileString.c_str());
string s;
while (getline(file, s))
cout << s << endl;
//if main was given args which are file paths
int failCount = 0;
if (argc > 1) {
for (int i = 0; i < argc; ++i) {
ifstream in(argv[i]);
if (in) {
string str;
while (getline(in, str))
cout << str << endl;
} else {
cerr << "Cannot open file " << argv[i] << endl;
++failCount;
}
}
}
//testing template median for array/vector
int p[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "\narray median: " << median<int>(p, p + 10) << endl;
vector<int> vec = {24, 645, 876, 5342, 123, 543, 765, 978, 564, 243, 654, 867, 543, 234, 642, 784, 52};
cout << "vector median: " << median<int>(vec.begin(), vec.end()) << endl;
//testing StringList class
string anotherString;
StringList newStrList;
while (getline(cin, anotherString))
split(anotherString, newStrList);
newStrList.printList();
return failCount;
} | true |
f736989cf8b2e493b7c60439361e4f530380daf1 | C++ | yistabraq/pcsc-cenxfs-bridge | /XFS/Logger.h | UTF-8 | 944 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef PCSC_CENXFS_BRIDGE_XFS_Logger_H
#define PCSC_CENXFS_BRIDGE_XFS_Logger_H
#pragma once
#include <sstream>
// Для WFMOutputTraceData.
#include <xfsadmin.h>
namespace XFS {
/** Перенаправляет весь вывод в XFS трассу. Логгирование осуществляется в деструкторе.
*/
class Logger {
std::ostringstream ss;
public:
Logger() { ss << "[PCSC] "; }
~Logger() { WFMOutputTraceData((LPSTR)ss.str().c_str()); }
public:
template<typename T>
Logger& operator<<(T value) { ss << value; return *this; }
Logger& operator<<(const char* value) {
if (value) {
ss << '"' << value << '"';
} else {
ss << "NULL";
}
return *this;
}
};
} // namespace XFS
#endif // PCSC_CENXFS_BRIDGE_XFS_Logger_H | true |
51d087fdf29df06d63825c5cb257c1072b1cc206 | C++ | everything411/BIT_Exercises | /乐学/计算理论与算法2020/符号三角形问题.cpp | UTF-8 | 1,231 | 2.625 | 3 | [
"Unlicense"
] | permissive | #include <iostream>
#include <cstring>
using namespace std;
int sum;
int half;
int n;
int p[30][30];
void backtrack(int t, int c)
{
if (c > half || t * (t - 1) / 2 - c > half)
{
return;
}
if (t > n)
{
sum++;
return;
}
for (int i = 0; i < 2; i++)
{
p[1][t] = i;
for (int j = 2; j <= t; j++)
{
p[j][t - j + 1] = p[j - 1][t - j + 1] ^ p[j - 1][t - j + 2];
c += p[j][t - j + 1];
}
backtrack(t + 1, c + i);
for (int j = 2; j <= t; j++)
{
c -= p[j][t - j + 1];
}
}
}
int anstable[] = {1, 0, 0, 4, 6, 0, 0, 12, 40, 0, 0, 171, 410, 0, 0, 1896, 5160, 0, 0, 32757, 59984, 0, 0, 431095, 822229, 0, 0, 5804913};
int main(int argc, char const *argv[])
{
while (~scanf("%d", &n))
{
if (n > 10)
{
printf("%d\n", anstable[n]);
continue;
}
sum = 0;
memset(p, 0, sizeof(p));
half = (n + 1) * n / 2;
if (half % 2 == 1)
{
puts("0");
}
else
{
half /= 2;
backtrack(1, 0);
printf("%d\n", sum);
}
}
return 0;
}
| true |
4390d2ff0027b00fc49801be764e4ee6f0682fa3 | C++ | jorgeblnz/DrumIlluminator | /DumIlluminatorFunctions.cpp | UTF-8 | 2,955 | 3.28125 | 3 | [] | no_license | /***************************************************
* Colección de Funciones para Arduino
* Archivo: DumIlluminatorFunctions.cpp
* Autor: Jorge Ignacio Balanz Pino
* Fecha: mayo de 2016
* Descripción: Colección de funciones que me
facilitarán las tareas de programación.
*
****************************************************/
#include "DumIlluminatorFunctions.h"
/***************************************************
* ESCRIBIR EN EL DISPLAY
* La librería LiquidCrystal_I2C.h no escribe
* cadenas de caracteres (strings) ni números
* enteros: sólo el primer carácter/dígito.
* Estas funciones escriben el número/string
* al completo.
****************************************************/
/**
* Función que escribe una cadena de caracteres completa (o
* lo que entre en la línea) en el display.
* @param lcd Objeto LiquidCrystal_I2C (LCD con interfaz I2C) convenientemente creado e inicializado.
* @param txt Cadena de caracteres a escribir.
* @param line Fila del display donde escribirá (la primera es la 0).
* @param pos Posición (columna) dentro de la línea donde empieza a escribir.
*/
void LCDwriteText(LiquidCrystal_I2C lcd, String txt, int line, int pos){
char buff[17];
int i;
txt.toCharArray(buff,17);
if(line>0)
line=1;
if(line<1)
line=0;
lcd.setCursor(pos,line);
for(i=0; i+pos<17 && buff[i]!='\0'; i++){
lcd.print(buff[i]);
}
//lcd.close();
}
//Hasta 24 caracteres en una línea(luego salta)
/**
* Función que escribe una cadena de caracteres completa (hasta
* 24 caracteres sin saltar de línea) en el display con scroll.
* El texto se va mostrando en la pantalla con movimiento.
*
* @param lcd Objeto LiquidCrystal_I2C (LCD con interfaz I2C) convenientemente creado e inicializado.
* @param txt Cadena de caracteres a escribir.
* @param line Fila del display donde escribirá (la primera es la 0).
* @param cols Número de caracteres (columnas) que tiene una línea (para empezar a escribir).
*/
void LCDwriteTextScroll(LiquidCrystal_I2C lcd, String txt, int line, int cols){
char buff[127];
unsigned int i;
txt.toCharArray(buff,txt.length()+1);
if(line>0)
line=1;
if(line<1)
line=0;
lcd.setCursor(cols,line);
// ponemos el display con scroll automático:
lcd.autoscroll();
for(i=0; i<txt.length() && buff[i]!='\0'; i++){
lcd.print(buff[i]);
delay(50);
}
// quitamos el scrolling automático:
lcd.noAutoscroll();
}
/**
* Función que escribe un número entero completo (o
* lo que entre en la línea) en el display.
* @param lcd Objeto LiquidCrystal_I2C (LCD con interfaz I2C) convenientemente creado e inicializado.
* @param value Número entero (long) a escribir.
* @param line Fila del display donde escribirá (la primera es la 0).
* @param pos Posición (columna) dentro de la línea donde empieza a escribir.
*/
void LCDwriteNumber(LiquidCrystal_I2C lcd, long value, int line, int pos){
LCDwriteText(lcd,String(value,DEC),line,pos);
}
| true |
eb3dc77a4cf392b5f471f3e15cd7c5f7da4cc9fb | C++ | velenk/CPP | /C++Primer/3.2.3count_punctuation.cpp | UTF-8 | 394 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout; using std::endl;
int main() {
string s("Hello World!!!");
decltype(s.size()) punct_count = 0;
//Statistic the number of punctuation characters in s.
for (auto c : s) {
if (ispunct(c))
punct_count++;
}
cout << punct_count << " punctuation characters in " << s << endl;
return 0;
}
| true |
22364b6dce643080b5a209333c1310207d3b6d39 | C++ | eagle-deep-blue/mobile_base_modelling | /src/perception/perception_lidar_node.cpp | UTF-8 | 2,119 | 2.75 | 3 | [] | no_license | /*
* perception_laser_scan.cpp
*
* Created on: Dec 7, 2017
* Author: solomon
*/
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
void callbackLaser(const sensor_msgs::LaserScanConstPtr& msg);
int main(int argc, char** argv) {
ros::init(argc, argv, "perception_laser_scan_node");
ros::NodeHandle handle;
ros::Subscriber sub = handle.subscribe("scan", 10, callbackLaser);
ros::spin();
return 0;
}
float radian2degree(float radian) {
return radian / M_PI * 180;
}
float degree2radian(float degree) {
return degree / 180.0 * M_PI;
}
void callbackLaser(const sensor_msgs::LaserScanConstPtr& msg) {
ROS_INFO("scan retrieved!");
float dlt = 30;
float angle_bn1 = degree2radian(-90 - 30);
float angle_bn2 = degree2radian(-90 + 30);
for (int k = 0; k < msg->ranges.size(); k++) {
float angle = msg->angle_min + k * msg->angle_increment;
if (angle > angle_bn1 && angle < angle_bn2) {
ROS_INFO_STREAM(
"["<< k << "] -> [" << angle << "] -> [" << msg->ranges[k] << "]");
}
}
/*
int idx_bn1 = -(msg->angle_min - angle_bn1) / msg->angle_increment;
int idx_bn2 = -(msg->angle_min - angle_bn2) / msg->angle_increment;
ROS_INFO_STREAM("index range[" << idx_bn1 << "," << idx_bn2 << "]");
for (int k = 0; k > idx_bn1 && k < idx_bn2; k++) {
ROS_INFO_STREAM("[" << k << "] -> [" << msg->ranges[k] << "]");
}*/
/*
ROS_INFO_STREAM(
"laser stream received with [" << msg->ranges.size() << "] elements");
ROS_INFO_STREAM("laser frame -> [" << msg->header.frame_id << "]");
int size = (msg->angle_max - msg->angle_min) / msg->angle_increment;
std::cout << "angle gap size -> [" << size << "]\n";
ROS_INFO_STREAM(
"angle -> min [" << msg->angle_min/M_PI * 180 << "] v.s. max [" << msg->angle_max/M_PI * 180 << "] at res. [" << msg->angle_increment << "]");
float threshold_dist = 0.3;
for (int k = 0; k < msg->ranges.size(); k++) {
if (msg->ranges[k] < threshold_dist) {
ROS_INFO_STREAM(
"near object -> dist [" << msg->ranges[k] << "] at angle [" << radian2degree(msg->angle_min + msg->angle_increment * k )<< "]");
}
}*/
return;
}
| true |
3a27a127267c509b526b9b1d8d7dc8d03f597c2b | C++ | roddehugo/utc | /lo21/td4/UTProfiler.cpp | ISO-8859-1 | 4,446 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "UTProfiler.h"
#include <fstream>
#include <sstream>
//UVManager* UVManager::instanceUnique = 0; //
UVManager::Handler UVManager::handler=Handler();
ostream& operator<<(ostream& f, const UV& uv){
return f<<uv.getCode()<<", "<<uv.getCategorie()<<", "<<uv.getNbCredits()<<" credits, "<<uv.getTitre();
}
istream& operator>>(istream& f, Categorie& cat){
string str;
f>>str;
if (str=="CS") cat=CS;
else
if (str=="TM") cat=TM;
else
if (str=="SP") cat=SP;
else
if (str=="TSH") cat=TSH;
else {
ostringstream e;
e<<"erreur, lecture categorie : "<<str<<" n'est pas une categorie traitee";
throw UTProfilerException(e.str());
}
return f;
}
ostream& operator<<(ostream& f, const Categorie& cat){
switch(cat){
case CS: f<<"CS"; break;
case TM: f<<"TM"; break;
case SP: f<<"SP"; break;
case TSH: f<<"TSH"; break;
default: throw UTProfilerException("erreur, categorie non traitee");
}
return f;
}
UVManager::UVManager(const string& f):uvs(0),nbUV(0),nbMaxUV(0),file(f),modification(false){
}
void UVManager::load(const string& f){
if (f!="") this->~UVManager();
file=f;
ifstream fin(file.c_str()); // open file
if (!fin) throw UTProfilerException("erreur, lors de l'ouverture du fichier d'UV");
char tmp[256];
while (!fin.eof()&&fin.good()){
fin.getline(tmp,256); // get code
if (fin.bad()) throw UTProfilerException("erreur, fichier d'UV, lecture code UV");
string code=tmp;
fin.getline(tmp,256); // get titre
string titre=tmp;
if (fin.bad()) throw UTProfilerException("erreur, fichier d'UV, lecture titre UV");
fin.getline(tmp,256); // get nbCredits
if (fin.bad()) throw UTProfilerException("erreur, fichier d'UV, lecture nb credits UV");
unsigned int nbCredits;
istringstream isn(tmp);
isn>>nbCredits;
if (isn.bad()) throw UTProfilerException("erreur, fichier d'UV, lecture nb credits UV");
fin.getline(tmp,256); // get categorie
istringstream is(tmp);
Categorie cat;
is>>cat;
if (is.bad()) throw UTProfilerException("erreur, fichier d'UV, lecture categorie UV");
ajouterUV(code,titre,nbCredits,cat);
if (fin.peek()=='\r') fin.ignore();
if (fin.peek()=='\n') fin.ignore();
}
fin.close(); // close file
modification=false;
}
void UVManager::addItem(UV* uv){
if (nbUV==nbMaxUV){
UV** newtab=new UV*[nbMaxUV+10];
for(unsigned int i=0; i<nbUV; i++) newtab[i]=uvs[i];
nbMaxUV+=10;
UV** old=uvs;
uvs=newtab;
delete[] old;
}
uvs[nbUV++]=uv;
}
void UVManager::ajouterUV(const string& c, const string& t, unsigned int nbc, Categorie cat){
if (trouverUV(c)) {
ostringstream str;
str<<"erreur, UVManager, UV "<<c<<" deja existante";
throw UTProfilerException(str.str());
}else{
UV* newuv=new UV(c,t,nbc,cat);
addItem(newuv);
modification=true;
}
}
UV* UVManager::trouverUV(const string& c)const{
for(unsigned int i=0; i<nbUV; i++)
if (c==uvs[i]->getCode()) return uvs[i];
return 0;
}
UV& UVManager::getUV(const string& code){
UV* uv=trouverUV(code);
if (!uv) throw UTProfilerException("erreur, UVManager, UV inexistante");
return *uv;
}
const UV& UVManager::getUV(const string& code)const{
return const_cast<UVManager*>(this)->getUV(code);
// on peut aussi dupliquer le code de la mthode non-const
}
void UVManager::save(const string& f){
file=f;
// maj du fichier d'UV
ofstream fout(file.c_str(),ofstream::trunc); // toutes les UVs existantes sont crases
for(unsigned int i=0; i<nbUV; i++){
fout<<uvs[i]->getCode()<<"\n";
fout<<uvs[i]->getTitre()<<"\n";
fout<<uvs[i]->getNbCredits()<<"\n";
fout<<uvs[i]->getCategorie()<<"\n";
cout<<*uvs[i]<<"\n";
}
fout.close();
}
UVManager::~UVManager(){
if(file!="") save(file);
for(unsigned int i=0; i<nbUV;i++) delete uvs[i];
delete [] uvs;
file="";
}
/*
UVManager::UVManager(const UVManager& um):nbUV(um.nbUV),nbMaxUV(um.nbMaxUV), uvs(new UV*[um.nbUV]){
for(unsigned int i=0; i<nbUV; i++) uvs[i]=new UV(*um.uvs[i]);
}
UVManager& UVManager::operator=(const UVManager& um){
if (this==&um) return *this;
this->~UVManager();
for(unsigned int i=0; i<um.nbUV; i++) addItem(new UV(*um.uvs[i]));
return *this;
}*/
| true |
d4000a3b135b2d814145582fbf23dc456ed4bf58 | C++ | DCubix/another-engine | /src/rendering/framebuffer.cpp | UTF-8 | 5,412 | 2.5625 | 3 | [] | no_license | #include "framebuffer.h"
#include <iostream>
namespace ae {
void FrameBuffer::free() {
if (m_id) {
glDeleteFramebuffers(1, &m_id);
m_id = 0;
}
if (m_rboID) {
glDeleteRenderbuffers(1, &m_rboID);
m_rboID = 0;
}
m_colorAttachments.clear();
}
void FrameBuffer::create(uint32 width, uint32 height, uint32 depth) {
m_width = width;
m_height = height;
m_depth = depth;
glGenFramebuffers(1, &m_id);
}
void FrameBuffer::color(TextureTarget type, TextureFormat format, uint32 mip, uint32 layer) {
glBindFramebuffer(GL_FRAMEBUFFER, m_id);
std::unique_ptr<Texture> tex = std::make_unique<Texture>();
tex->setSize(m_width, m_height);
tex->bind();
tex->wrap(TextureWrap::Clamp, TextureWrap::Clamp);
tex->filter(TextureFilter::LinearMipLinear, TextureFilter::Linear);
tex->setData(nullptr, format);
if (type == TextureTarget::CubeMap) {
tex->setCubeMapData(nullptr, format, CubeMapSide::CubeMapNX);
tex->setCubeMapData(nullptr, format, CubeMapSide::CubeMapNY);
tex->setCubeMapData(nullptr, format, CubeMapSide::CubeMapNZ);
tex->setCubeMapData(nullptr, format, CubeMapSide::CubeMapPX);
tex->setCubeMapData(nullptr, format, CubeMapSide::CubeMapPY);
tex->setCubeMapData(nullptr, format, CubeMapSide::CubeMapPZ);
} else {
tex->setData(nullptr, format);
}
SavedColorAttachment sca;
sca.format = format;
sca.target = type;
sca.mip = mip;
m_savedColorAttachments.push_back(sca);
std::vector<GLenum> db;
uint32 att = m_colorAttachments.size();
for (uint32 i = 0; i < att + 1; i++) {
db.push_back(GL_COLOR_ATTACHMENT0 + i);
}
GLenum atc = GL_COLOR_ATTACHMENT0 + att;
switch (type) {
case TextureTarget::Texture1D:
glFramebufferTexture1D(GL_FRAMEBUFFER, atc, GLenum(type), tex->id(), mip);
break;
case TextureTarget::Texture2D:
glFramebufferTexture2D(GL_FRAMEBUFFER, atc, GLenum(type), tex->id(), mip);
break;
case TextureTarget::Texture3D:
glFramebufferTexture3D(GL_FRAMEBUFFER, atc, GLenum(type), tex->id(), mip, layer);
break;
default:
glFramebufferTexture(GL_FRAMEBUFFER, atc, tex->id(), mip);
break;
}
glDrawBuffers(db.size(), db.data());
m_colorAttachments.push_back(std::move(tex));
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void FrameBuffer::depth() {
if (m_depthAttachment) {
return;
}
glBindFramebuffer(GL_FRAMEBUFFER, m_id);
std::unique_ptr<Texture> tex = std::make_unique<Texture>();
tex->setSize(m_width, m_height);
tex->bind();
tex->wrap(TextureWrap::Clamp, TextureWrap::Clamp);
tex->filter(TextureFilter::Nearest, TextureFilter::Nearest);
tex->setData(nullptr, TextureFormat::Depthf);
glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D,
tex->id(),
0
);
m_depthAttachment = std::move(tex);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void FrameBuffer::stencil() {
if (m_stencilAttachment) {
return;
}
glBindFramebuffer(GL_FRAMEBUFFER, m_id);
std::unique_ptr<Texture> tex = std::make_unique<Texture>();
tex->setSize(m_width, m_height);
tex->bind();
tex->wrap(TextureWrap::Clamp, TextureWrap::Clamp);
tex->filter(TextureFilter::Nearest, TextureFilter::Nearest);
tex->setData(nullptr, TextureFormat::R);
glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_STENCIL_ATTACHMENT,
GL_TEXTURE_2D,
tex->id(),
0
);
m_stencilAttachment = std::move(tex);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void FrameBuffer::renderBuffer(
TextureFormat storage,
Attachment attachment
) {
if (m_rboID != 0) {
return;
}
m_renderBufferStorage = storage;
auto fmt = intern::getTextureFormat(storage);
glGenRenderbuffers(1, &m_rboID);
glBindFramebuffer(GL_FRAMEBUFFER, m_id);
glBindRenderbuffer(GL_RENDERBUFFER, m_rboID);
glRenderbufferStorage(GL_RENDERBUFFER, std::get<0>(fmt), m_width, m_height);
glFramebufferRenderbuffer(
GL_FRAMEBUFFER,
attachment,
GL_RENDERBUFFER,
m_rboID
);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
glDeleteRenderbuffers(1, &m_rboID);
m_rboID = 0;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void FrameBuffer::drawBuffer(uint32 index) {
glDrawBuffer(GL_COLOR_ATTACHMENT0 + index);
}
void FrameBuffer::resetDrawBuffers() {
std::vector<GLenum> db;
int32 att = m_colorAttachments.size();
for (int i = 0; i < att; i++) {
db.push_back(GL_COLOR_ATTACHMENT0 + i);
}
glDrawBuffers(db.size(), db.data());
}
void FrameBuffer::blit(
int sx0, int sy0, int sx1, int sy1,
int dx0, int dy0, int dx1, int dy1,
ClearBufferMask mask,
TextureFilter filter)
{
glBlitFramebuffer(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, mask, GLenum(filter));
}
void FrameBuffer::bind(FrameBufferTarget target, Attachment readBuffer) {
m_bound = target;
glGetIntegerv(GL_VIEWPORT, m_viewport);
glBindFramebuffer(target, m_id);
glViewport(0, 0, m_width, m_height);
if (target == FrameBufferTarget::ReadFrameBuffer) {
glReadBuffer(readBuffer);
}
}
void FrameBuffer::unbind(bool resetViewport) {
glBindFramebuffer(m_bound, 0);
if (resetViewport) {
glViewport(
m_viewport[0],
m_viewport[1],
m_viewport[2],
m_viewport[3]
);
}
}
void FrameBuffer::clear(ClearBufferMask mask, float r, float g, float b, float a) {
glClearColor(r, g, b, a);
glClear(mask);
}
} | true |
ad479105126e7c701dbdc8bc07be616f65bd9d86 | C++ | helloketty1028/sky.github.io | /CrowdedHospital/CrowdedHospital/main.cpp | UTF-8 | 4,235 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include "hospital.hpp"
using namespace std;
Hospital* CreateHospital();
void InitBedLayout(Hospital *hospital);
PatientType InputPatientType();
void CinClear();
int main(int argc, const char * argv[]) {
auto *hospital = CreateHospital();
InitBedLayout(hospital);
hospital->PrintBedLayout();
bool flag_covid = false;
bool flag_measles = false;
while (true) {
cout << endl;
PatientType type = InputPatientType();
cout << (type == kCovidPatient ? "Covid patient" : "Measles patient") << endl;
Patient *patient = new Patient(type);
if (hospital->AcceptPatient(patient)) {
hospital->AddPatient(patient);
cout << "* patient(" << patient->num << ") Check in to bed ("
<< patient->bed->get_row() << ',' << patient->bed->get_column() << ")"
<< endl;
cout << "----- flag_covid="<< flag_covid << ", flag_measles=" <<flag_measles << endl;
flag_covid = false;
flag_measles = false;
} else {
hospital->AcceptPatientFailed(patient);
cout << "* No suitable bed can be allocated to this new patient(" << patient->num << ")"
<< endl;
if (patient->IsCovidPatient()) {
flag_covid = true;
} else if (patient->IsMeaslesPatient()) {
flag_measles = true;
}
cout << "flag_covid="<< flag_covid << ", flag_measles=" <<flag_measles << endl;
if (flag_covid && flag_measles) {
cout << endl << "Exit the program!!!" << endl;
break;
}
}
hospital->PrintBedUsed();
}
delete hospital;
return 0;
}
// Create hospital object
Hospital* CreateHospital() {
int columns;
int rows;
while (true) {
cout << "Please enter the number of rows and columns of beds, format:Rows Cols (which can be any number between 2 and 1000):" << endl;
cout << "> ";
cin >> rows >> columns;
CinClear();
if (rows >= 2 && rows <= 1000 && columns >= 2 && columns <= 1000) {
cout << "rows: " << rows << ", columns: " << columns << endl << endl;
break;
}
cout << "Input errors, please re-enter!" << endl << endl;
}
return new Hospital(rows, columns);
}
// Set the bed layout
void InitBedLayout(Hospital *hospital) {
int rows = hospital->rows;
int columns = hospital->columns;
cout << "Please enter the bed layout," << columns << " beds per row," << rows << " row in total, V : anti-viral,B : anti-bacterial:" << endl;
int width = rows < 10 ? 1 : (rows < 100 ? 2 : (rows < 1000 ? 3 : 4));
for (int row = 0; row < rows; row++) {
cout << "row #" << setw(width) << setfill('0') << row + 1 << "> ";
bool is_valid = true;
for (int column = 0; column < columns; column++) {
char ch;
cin >> ch;
Bed &bed = hospital->GetBed(row, column);
if (ch == 'v' || ch == 'V') {
bed.set_type(kAntiViralBed);
} else if (ch == 'b' || ch == 'B') {
bed.set_type(kAntiBacterialBed);
} else {
is_valid = false;
break;
}
}
CinClear();
if (!is_valid) {
row--;
cout << "Input errors, please re-enter!" << endl;
}
}
}
PatientType InputPatientType() {
while (true) {
cout << "Please enter the type of inpatient: Covid (C) patients and Measles (M) patients:" << endl;
cout << "#> ";
char ch;
cin >> ch;
if (ch == 'c' || ch == 'C') {
return kCovidPatient;
} else if (ch == 'm' || ch == 'M') {
return kMeaslesPatient;
}
cout << "Input errors, please re-enter!" << endl << endl;
}
}
// Clear the input buffer
void CinClear() {
cin.clear();
string junk;
getline(cin, junk);
// cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
| true |
a458d2a4917bf1124f5a7b3e2437d4878f05255c | C++ | pcatrina/CPP | /Module05/ex00/main.cpp | UTF-8 | 507 | 2.625 | 3 | [] | no_license | #include <iostream>
#include "Bureaucrat.hpp"
int main()
{
try
{
Bureaucrat putin("Vova");
putin.inc();
std::cout<<putin;
}
catch (std::exception & e)
{
std::cerr<<e.what()<<std::endl;
}
try
{
Bureaucrat putin("Vova");
putin.dec();
std::cout<<putin;
}
catch (std::exception & e)
{
std::cerr<<e.what()<<std::endl;
}
try
{
Bureaucrat Chinush("Sechin");
Chinush.inc();
std::cout<<Chinush;
}
catch (std::exception & e)
{
std::cerr<<e.what()<<std::endl;
}
return 0;
}
| true |
9db30b7668ff278a732dc096f1efe8d50c535857 | C++ | pmackle/Monopoly | /Property.h | UTF-8 | 1,832 | 2.640625 | 3 | [] | no_license | #ifndef CPPHOARDING_PROPERTY_H
#define CPPHOARDING_PROPERTY_H
#include <string>
//#include "Player.h"
#include "Space.h"
class Property : public Space
{
public:
Property(int index, std::string type, std::string name, int setID,
int intrasetID, int propertyCost, int houseCost, int hotelCost,
int rent, int rentWithHouse, int rentWithHotel, Board* board);
void AuctionProperties(std::vector <Player>& players, Board& board, int newPosition);
//int buyUpgrade(Player& player, Board& board, const Rules& rulebook);
int sellUpgradesAvoidBankruptcy(Player& player, Board& board, const Rules& rulebook);
int sellUpgradesAvoidBankruptcyNoPrint(Player& player, Board& board, const Rules& rulebook);
int rentMult(const Rules& rulebook, int newPosition, Board& board);
virtual int getSetID() const;
virtual int getIntrasetID() const;
virtual std::string getName() const;
virtual int getPropertyCost() const;
virtual int getHouseCost() const;
virtual int getHotelCost() const;
virtual int getRent() const;
virtual int getRentWithHouse() const;
virtual int getRentWithHotel() const;
virtual Player& getOwner();
virtual int getSalary() const;
virtual void activate(Player& activatingPlayer) override;
// virtual void display() override;
virtual void setOwner(const Player& player);
//std::string upgrades;
//int numUpgrades;
private:
int setID;
int intrasetID;
int propertyCost;
int houseCost;
int hotelCost;
int rent;
int rentWithHouse;
int rentWithHotel;
Player owner;
};
#endif //CPPHOARDING_PROPERTY_H | true |
5b035aec9d8411b5cb222729f62c6c0e296a576d | C++ | wiidev/usbloadergx | /source/network/URL_List.cpp | UTF-8 | 2,661 | 2.625 | 3 | [] | no_license | /****************************************************************************
* URL List Class
* for USB Loader GX
* by dimok
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gctypes.h>
#include "URL_List.h"
URL_List::URL_List(const char * url)
{
Links = NULL;
urlcount = 0;
if (!IsNetworkInit())
{
urlcount = -1;
return;
}
struct download file = {};
downloadfile(url, &file);
if (file.size <= 0)
{
urlcount = -2;
return;
}
u32 cnt = 0;
char temp[1024];
Links = (Link_Info *) malloc(sizeof(Link_Info));
if (!Links)
{
MEM2_free(file.data);
urlcount = -3;
return;
}
memset(&Links[urlcount], 0, sizeof(Link_Info));
while (cnt < file.size)
{
if (file.data[cnt] == '"' && file.data[cnt - 1] == '=' && file.data[cnt - 2] == 'f' && file.data[cnt - 3]
== 'e' && file.data[cnt - 4] == 'r' && file.data[cnt - 5] == 'h')
{
u32 cnt2 = 0;
cnt++;
while (file.data[cnt] != '"' && cnt2 < 1024)
{
temp[cnt2] = file.data[cnt];
cnt2++;
cnt++;
}
temp[cnt2] = '\0';
Links = (Link_Info *) realloc(Links, (urlcount + 1) * sizeof(Link_Info));
if (!Links)
{
for (int i = 0; i == urlcount; i++)
{
delete Links[i].URL;
Links[i].URL = NULL;
}
free(Links);
Links = NULL;
MEM2_free(file.data);
urlcount = -4;
break;
}
memset(&(Links[urlcount]), 0, sizeof(Link_Info));
Links[urlcount].URL = new char[cnt2 + 1];
if (!Links[urlcount].URL)
{
for (int i = 0; i == urlcount; i++)
{
delete Links[i].URL;
Links[i].URL = NULL;
}
free(Links);
Links = NULL;
MEM2_free(file.data);
urlcount = -5;
break;
}
snprintf(Links[urlcount].URL, cnt2 + 1, "%s", temp);
if (strncmp(Links[urlcount].URL, "https://", strlen("https://")) != 0)
Links[urlcount].direct = false;
else Links[urlcount].direct = true;
urlcount++;
}
cnt++;
}
MEM2_free(file.data);
}
URL_List::~URL_List()
{
for (int i = 0; i == urlcount; i++)
{
delete Links[i].URL;
Links[i].URL = NULL;
}
if (Links != NULL)
{
free(Links);
Links = NULL;
}
}
char * URL_List::GetURL(int ind)
{
if (ind > urlcount || ind < 0 || !Links || urlcount <= 0)
return NULL;
else return Links[ind].URL;
}
int URL_List::GetURLCount()
{
return urlcount;
}
static int ListCompare(const void *a, const void *b)
{
Link_Info *ab = (Link_Info*) a;
Link_Info *bb = (Link_Info*) b;
return strcasecmp((char *) ab->URL, (char *) bb->URL);
}
void URL_List::SortList()
{
qsort(Links, urlcount, sizeof(Link_Info), ListCompare);
}
| true |
4a852d102e30298cf5f8f49a8be7c401efd53997 | C++ | Allyrax/Bomberman | /Server.cpp | UTF-8 | 3,779 | 3.25 | 3 | [] | no_license | #include "thread.h"
#include "socketserver.h"
#include <stdlib.h>
#include <time.h>
#include <list>
#include <pthread.h>
#include <vector>
#include <string>
class GameThread: public Thread {
private:
Socket sP1;
Socket sP2;
int* grimReaper;
public:
GameThread(Socket const & sPa, Socket const & sPb, int* grimReaper): Thread(true), sP1(sPa), sP2(sPb), grimReaper(grimReaper) {};
long ThreadMain(void) {
std::string message = "";
BePolite();
try {
//send a start message to both players
ByteArray player1("player1,0,0,");
ByteArray player2("player2,0,0,");
sP1.Write(player1);
sP2.Write(player2);
while(*grimReaper) {
//read the data from the client
ByteArray byteMessage;
FlexWait waiter(2, &sP1, &sP2);
Blockable * result = waiter.Wait();
if (result == &sP1) {
int read = sP1.Read(byteMessage);
if(read == -1) {
std::cout << "Error detected" << std::endl;
break;
} else if (read == 0) {
std::cout << "Client disconnected" << std::endl;
break;
}
//send the data from player 2 to player1
sP2.Write(byteMessage);
}
if (result == &sP2) {
int read = sP2.Read(byteMessage);
if(read == -1) {
std::cout << "Error detected" << std::endl;
break;
} else if (read == 0) {
std::cout << "Client disconnected" << std::endl;
break;
}
//send the data from player 1 to player2
sP1.Write(byteMessage);
}
if (byteMessage.ToString() == "quit") {
message = "quit";
std::cout << "Client has quit the game" << std::endl;
}
}
std::cout << "While you're dying I'll be still alive" << std::endl;
}
catch(...) {
std::cout << "Caught unexpected exception " << std::endl;
}
};
};
class ServerThread: public Thread {
private:
int* grimReaper;
std::vector<GameThread*>* threadSalesman;
public:
ServerThread(int* grimReaper, std::vector<GameThread*>* threadSalesman): grimReaper(grimReaper), threadSalesman(threadSalesman) {};
long ThreadMain(void) {
BePolite();
std::cout << "I am a server!" << std::endl;
try {
//set the port number
int port = 2003;
//create the Server Socket
SocketServer socketButler(port);
int socketCounter = 0;
while(*grimReaper){
//wait for a connection and create a new socket
Socket socketPlayer1(socketCounter++);
socketPlayer1 = socketButler.Accept();
Socket socketPlayer2(socketCounter++);
socketPlayer2 = socketButler.Accept();
//create a new thread
threadSalesman->push_back( new GameThread(socketPlayer1, socketPlayer2, grimReaper));
(*threadSalesman)[threadSalesman->size() - 1]->Start();
}
}
catch(...) {
std::cout << "Caught unexpected exception " << std::endl;
}
std::cout << "I'm making a note here: HUGE SUCCESS." << std::endl;
}
};
int main(void)
{
try
{
//create a vector to hold the threads
std::vector<GameThread*> threadSalesman;
//if this changes to 0 a thread has asked the server to die
int grimReaper = 1;
//create a thread to hold the server
ServerThread theServer(&grimReaper, &threadSalesman);
//start the server thread
theServer.Start();
//check if the thread should die twice a second
std::string message = "";
while (message != "quit") {
std::cin >> message;
}
//kill the server thread
grimReaper = 0;
theServer.Stop();
std::cout << threadSalesman.size() << std::endl;
for(int i=0; i<threadSalesman.size(); i++) {
threadSalesman[i]->Stop();
delete threadSalesman[i];
}
std::cout << threadSalesman.size();
}
catch(...)
{
std::cout << "Caught unexpected exception" << std::endl;
}
}
| true |
cf3ceab68a09773229805a6d52d1bddb869e19d9 | C++ | eputh/using-multi-dimensional-arrays | /magic-square.hpp | UTF-8 | 1,343 | 3.6875 | 4 | [] | no_license | //
// Name: Emily PUth
// ID: 28239807
//
// The Magic Square program reads a given file and
// determines whether the grid contained in the file
// is a Lo Shu Magic Square. A Lo Shu Magic Square
// 3 X 3 grid (1) contains the numbers 1 through 9 exactly
// once AND (2) has a sum of 15 for each row, each column
// and each diagonal.
#ifndef MAGIC_SQUARE_HPP_
#define MAGIC_SQUARE_HPP_
#include <iostream>
#include <fstream>
// Prints the grid's contents
void printGrid(int arr[][3]);
// Checks if all the numbers in the grid are
// between 1 and 9
bool hasValidNumbers(int arr[][3]);
// Returns the sum of the values in the specified row
int getRowTotal(int arr[][3], int whichRow);
// Returns the sum of the values in the specified column
int getColumnTotal(int arr[][3], int whichCol);
// Returns the sum of the values going diagonally left or right
int getDiagonalTotal(int arr[][3], std::string direction);
// Takes a row, column, or diagonal as a
// parameter and checks if the ints add
// up to 15, as they are supposed to (Lu
// Shu Magic Square rule)
bool addsUpToFifteen(int arg[]);
// Takes a filename as a parameter, opens the
// file, inserts the file data into a two-dimensional
// array, and checks whether the grid is a Lu Shu
// Magic Square
bool isMagicSquare(std::string filename);
#endif /* MAGIC_SQUARE_HPP_ */
| true |
e54588523aeb311d920dbe8068f4ed03eb3df6ab | C++ | NEITGNART/LeetCode | /179. Largest Number Solution1.cpp | UTF-8 | 409 | 3.0625 | 3 | [] | no_license | class Solution {
public:
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), [](int x, int y) {
string sx = to_string(x);
string sy = to_string(y);
return sx + sy > sy + sx;
});
string res;
for (auto num : nums)
res += to_string(num);
return res[0] == '0' ? "0" : res;
}
};
| true |
ee1916d9a1186edcc0a1475b1fee2d4cf56674ad | C++ | puer99miss/Xapiand | /src/geospatial/convex.h | UTF-8 | 4,169 | 2.671875 | 3 | [
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"GPL-1.0-or-later",
"BSD-3-Clause"
] | permissive | /*
* Copyright (c) 2015-2018 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include "circle.h"
// Intersection of circles.
class Convex : public Geometry {
enum class Sign : uint8_t {
MIXED = 0b0000,
POS = 0b0001,
NEG = 0b0010,
ZERO = 0b0011,
};
std::vector<Circle> circles;
Sign sign;
bool simplified;
int insideVertex(const Cartesian& v) const noexcept;
bool intersectCircles(const Constraint& bounding_circle) const;
TypeTrixel verifyTrixel(const Cartesian& v0, const Cartesian& v1, const Cartesian& v2) const;
void lookupTrixel(const Cartesian& v0, const Cartesian& v1, const Cartesian& v2, std::string name, trixel_data& data, uint8_t level) const;
void lookupTrixel(const Cartesian& v0, const Cartesian& v1, const Cartesian& v2, uint64_t id, range_data& data, uint8_t level) const;
public:
Convex()
: Geometry(Type::CONVEX),
sign(Sign::ZERO),
simplified(true) { }
Convex(Convex&& convex) noexcept
: Geometry(std::move(convex)),
circles(std::move(convex.circles)),
sign(std::move(convex.sign)),
simplified(std::move(convex.simplified)) { }
Convex(const Convex& convex)
: Geometry(convex),
circles(convex.circles),
sign(convex.sign),
simplified(convex.simplified) { }
~Convex() = default;
Convex& operator=(Convex&& convex) noexcept {
Geometry::operator=(std::move(convex));
circles = std::move(convex.circles);
sign = std::move(convex.sign);
simplified = std::move(convex.simplified);
return *this;
}
Convex& operator=(const Convex& convex) {
Geometry::operator=(convex);
circles = convex.circles;
sign = convex.sign;
simplified = convex.simplified;
return *this;
}
bool operator<(const Convex& convex) const noexcept {
return circles < convex.circles;
}
bool operator==(const Convex& convex) const noexcept {
return circles == convex.circles;
}
template <typename T, typename = std::enable_if_t<std::is_same<Circle, std::decay_t<T>>::value>>
void add(T&& circle) {
sign = static_cast<Convex::Sign>(static_cast<uint8_t>(sign) & static_cast<uint8_t>(circle.constraint.sign));
circles.push_back(std::forward<T>(circle));
simplified = false;
}
void add(const Convex& convex) {
circles.reserve(circles.size() + convex.circles.size());
for (const auto& circle : convex.circles) {
circles.push_back(circle);
}
simplified = false;
}
void add(Convex&& convex) {
circles.reserve(circles.size() + convex.circles.size());
for (auto& circle : convex.circles) {
circles.push_back(std::move(circle));
}
simplified = false;
}
void reserve(size_t new_cap) {
circles.reserve(new_cap);
}
bool empty() const noexcept {
return circles.empty();
}
const std::vector<Circle>& getCircles() const noexcept {
return circles;
}
void simplify() override;
std::string toWKT() const override;
std::string to_string() const override;
std::vector<std::string> getTrixels(bool partials, double error) const override;
std::vector<range_t> getRanges(bool partials, double error) const override;
std::vector<Cartesian> getCentroids() const override;
};
| true |
75cdf909bb543572003592774c35f40e5ed8a9b2 | C++ | export-default/uva-problems | /src/591.cpp | UTF-8 | 723 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <vector>
// https://uva.onlinejudge.org/external/5/591.html
int main() {
int n;
int set = 0;
while (std::cin >> n && n != 0) {
int tmp;
std::vector<int> vec;
int mid = 0;
for (int i = 0; i < n; ++i) {
std::cin >> tmp;
vec.push_back(tmp);
mid += tmp;
}
mid /= vec.size();
int moves = 0;
for (const int &i : vec) {
if (i > mid) {
moves += (i - mid);
}
}
std::cout << "Set #" << (++set) << std::endl;
std::cout << "The minimum number of moves is " << moves << "." << std::endl;
std::cout << std::endl;
}
}
| true |
06005f52eb67b176750773a261e925a2f99df6a5 | C++ | AlexanderRusak/DevIncubator | /HW2/HW Task1.cpp | UTF-8 | 740 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
/* int numbers[]={1,2,3,4,5};
for(int i=0;i<5;i++){
cout<<i+1<<endl;
}*/
/* int numbers[]={-2,-1,0,1,2};
for(int i = 0; i < 5 ; i++){
cout<<i-2<<endl;
}*/
/* int numbers[]={-2,0,2,4,6};
for(int i = 0; i < 5 ; i++){
cout<<2*i-2<<endl;
}*/
/* int numbers[]={5,4,3,2,1};
for(int i=5;i>0;i--){
cout<<i<<endl;
}*/
int numbers[]={5, 2 ,-1 ,-4 ,-7};
int neg=3,iter;
for(int i=5;i>0;i--){
cout<<iter-3<<endl;
iter=i;
iter++;
}
/* int numbers[]={1,4,9,16,25};
for(int i=0;i<5;i++){
cout<<pow(i+1,2)<<endl;
}*/
/* int numbers[]={1,2,4,7,11};
int prev=1;
for(int i=0; i<5;i++){
prev=i+prev;
cout<<prev<<endl;
}*/
return 0;
}
| true |
3aed4d8f347146fd888d6a3878bec0af29dc60c6 | C++ | AndrePim/Test_RFID | /src/main.cpp | UTF-8 | 3,483 | 2.578125 | 3 | [] | no_license | /*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*/
#include <Arduino.h>
#include <SPI.h>
#include <MFRC522.h> // Библиотека для RFID
#define SS_PIN 10 // Определение пина SDA
#define RST_PIN 9 // Определение пина RST
MFRC522 mfrc522(SS_PIN, RST_PIN); // Создание экземпляра класса MFRC522
void setup()
{
Serial.begin(9600); // Инициализация последовательного соединения и задание скорости передачи данных в бит/с(бод)
SPI.begin(); // Инициализация шины SPI
mfrc522.PCD_Init(); // Инициализация MFRC522
Serial.println("Approximate your card to the reader..."); // Вывод надписи "Приложите вашу карту к плате"
Serial.println(); // Пропуск строки
}
void loop()
{
// Поиск новых карт:
if (!mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Выбор одну из карт:
if (!mfrc522.PICC_ReadCardSerial())
{
return;
}
// Показание UID на мониторе порта:
Serial.print("UID tag :"); // Вывод надписи "UID tag: "
String content = "";
// Вывод UID тега в шестнадцатеричном формате
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println(); // Пропуск строки
Serial.print("Message : "); // Вывод надписи "Message: "
content.toUpperCase(); // Преобразование в верхний регистр, если это возможно
// Номер UID тега, которому разрешён доступ
if (content.substring(1) == "96 E1 33 53")
{
Serial.println("Authorized access"); // Вывод надписи "Доступ открыт"
Serial.println(); // Пропуск строки
delay(3000); // Задержка 3с
}
else
{
Serial.println("Access denied"); // Вывод надписи "Запрос на доступ отклонен"
delay(3000); // Задержка 3с
}
}
| true |
47522f696528b488faab1dacb135ea8e24222104 | C++ | hopeyouguessmyname/progs | /210601.cpp | UTF-8 | 2,813 | 3.5625 | 4 | [] | no_license | //decorator
#include <iostream>
#include <string>
/* Standardowy nieudekorowany samochod */
class Samochod
{
protected:
std::string samochod;
double wartosc;
public:
Samochod()
{
std::cout<<"Samochod()";
samochod = "Samochod podstawowy";
wartosc=0;
}
virtual ~Samochod(){};
virtual std::string about() { std::cout<<"Samochod.about()";return samochod; }
virtual double cena() { return wartosc; }
};
/* abstrakcyjny dekorator */
class Dekorator : public Samochod
{
public:
virtual std::string about() { std::cout<<"Dekorator.about()";return "hmm"; }
};
/* teraz mamy 2 przykladowe marki samochodow */
class Mercedes : public Samochod
{
public:
Mercedes():Samochod()
{
std::cout<<"Mercedes()";
samochod = "Mercedes";
wartosc=500000;
}
};
class Fiat : public Samochod
{
public:
Fiat():Samochod()
{
std::cout<<"Fiat()";
samochod = "Fiat";
wartosc=100000;
}
};
/* czas na same dodatki */
class Klimatyzacja : public Dekorator
{
Samochod *car;
public:
Klimatyzacja(Samochod *samochod):Dekorator() { std::cout<<"Klimatyzacja()";car = samochod; }
std::string about() { std::cout<<"Klimatyzacja.about()";return car->about() + " + klimatyzacja"; }
double cena() { return car->cena()+1111; }
};
class OponyZimowe : public Dekorator
{
Samochod *car;
public:
OponyZimowe(Samochod *samochod):Dekorator() { std::cout<<"OponyZimowe";car = samochod; }
std::string about() { std::cout<<"OponyZimowe.about()";return car->about() + " + opony zimowe"; }
/* niech ceny beda takie same */
double cena() { return car->cena() + 31234; }
};
int main()
{
Samochod *s1 = new Mercedes();
Samochod *s2 = new Fiat();
std::cout<<"\nBez wyposazenia"<<std::endl;
std::cout<<s1->about()<<" "<<s1->cena()<<std::endl;
std::cout<<s2->about()<<" "<<s2->cena()<<std::endl;
//dodajemy po klimie
s1 = new Klimatyzacja(s1);
s2 = new Klimatyzacja(s2);
std::cout<<"\nZ Klima"<<std::endl;
std::cout<<s1->about()<<" "<<s1->cena()<<std::endl;
std::cout<<s2->about()<<" "<<s2->cena()<<std::endl;
// i opony
s1 = new OponyZimowe(s1);
s2 = new OponyZimowe(s2);
std::cout<<"\nZ oponami"<<std::endl;
std::cout<<s1->about()<<" "<<s1->cena()<<std::endl;
std::cout<<s2->about()<<" "<<s2->cena()<<std::endl;
s1 = new OponyZimowe(s1);
s2 = new OponyZimowe(s2);
std::cout<<"\nZ oponami"<<std::endl;
std::cout<<s1->about()<<" "<<s1->cena()<<std::endl;
//od razu tworzymy wyposazony samochod
std::cout<<"\nPelne wyposazenie"<<std::endl;
Samochod *s3 = new OponyZimowe( new Klimatyzacja( new Mercedes()));
Samochod *s3 = new OponyZimowe( new Klimatyzacja( new Fiat()));
std::cout<<s3->about()<<" "<<s3->cena()<<std::endl;
return 0;
}
| true |
03cdf861330dbf0420407605f9bd41d27a53d8e0 | C++ | dleybz/PIC10B | /4.Eight-Queens-Problem/EightQueensApp.cpp | UTF-8 | 987 | 3.375 | 3 | [] | no_license | /*
Daniel Leybzon PIC 10B Intermediate Programming
ID: 804503913 Spring 2015
Email: dannyleybzon@gmail.com
Section:
Honesty Pledge:
I, Daniel Leybzon, pledge that this is my own independent work, which conforms to the guideliens of academic honesty as described in the course syllabus.
List of known bugs:
*/
#include "EightQueensProblem.h"
using namespace std;
int main(){
char quit;
int row;
EightQueensProblem object;
do{
cout << "*************************** Eight Queens Problem *************************** \n \n" << "Position the first queen on the chessboard: \n \n" << "Enter the row for the first queen (from 1 to 8): ";
cin >> row;
if (object.start_game(row)){
cout << "From the position (" << row << ", 1), the EightQueensProblem has solution: \n";
object.display_board(cout);
}else{
cout << "Nah";
}
cout << "\n \n" << "Finished? Type 'q' to quit or any other key to try again:";
cin >> quit;
}while(quit != 'q');
cout << "Thanks for playing.";
return 0;
}; | true |
767a9d2ae94dd986438ceb62ada422d29266cc10 | C++ | xumenger/xumenger.github.shit | /C++Test/书本上的作业题、代码等/2上机作业/06.06.13构造一个函数将输入的两个字符串连接在一起,并且用new去找到一个新的地址去存储新的字符串/未命名1.cpp | WINDOWS-1252 | 596 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include <cstring>
#include <cassert>
using namespace std;
char* cat(const char* str1,const char* str2)
{
assert(str1!=NULL && str2!=NULL);
int len1=strlen(str1);
int len2=strlen(str2);
char *str=new char(len1+len2+1);
if(str==NULL)
cout<<"ڴʧ\n";
strcpy(str,str1);
strcpy(str+len1,str2);
assert(strlen(str)==len1+len2);
return str;
}
int main()
{
char str1[]="pefect ";
char str2[]="world";
char* str=cat(str1,str2);
cout<<str<<endl;
delete str;
system("pause");
return 0;
}
| true |
b1947d360f03a4c8d5d4f4bb57f015a91ad99d4d | C++ | yongduek/myGraphics | /2/src/myGL.h | UTF-8 | 4,449 | 2.953125 | 3 | [] | no_license | #include <vector>
#include <math.h>
#include <iostream>
using namespace std;
typedef unsigned char uchar;
struct mPointf {
float x, y;
mPointf(float xx=0, float yy=0) : x(xx), y(yy) {}
};
struct mPointi {
int x, y;
mPointi(int xx=0, int yy=0) : x(xx), y(yy) {}
};
struct mColor {
uchar r, g, b;
mColor (uchar rr=0, uchar gg=0, uchar bb=0) : r(rr), g(gg), b(bb) { }
};
//struct PointColor : public Pointi, public mColor {};
struct PointColor {
mPointi p;
mColor c;
PointColor(mPointi pp=mPointi(0,0), mColor cc=mColor(0,0,0)) { p=pp; c=cc; }
};
struct mWindow {
float l, r, b, t;
void set(float ll, float rr, float bb, float tt) {l=ll, r=rr, b=bb, t=tt;}
};
const mColor mR(255,0,0), mG(0,255,0), mB(0,0,255);
#define myPOINTS 0
#define myLINE_LOOP 1
#define myLINE_STRIP 2
struct myCanvas {
uchar *pixels; // RGB
const int width=800, height=600;
const int bpp = 3;
mWindow viewport;
bool flagViewport = false;
mWindow worldWindow;
bool flagWorldWindow = false;
float A, B, C, D; // window2viewport transform
void init ()
{
pixels = new uchar[width*height*3];
for (int i=0; i<height; i++)
for (int j=0; j<width; j++)
for (int k=0; k<bpp; k++)
pixels[bpp*(width*i + j) + k] = 0;
viewport.set (0, width, 0, height);
worldWindow.set (0, width, 0, height);
computeABCD();
}
void setViewport(float ll, float rr, float bb, float tt) {
viewport.set (ll,rr,bb,tt);
computeABCD();
}
void setWorldWindow(float ll, float rr, float bb, float tt) {
worldWindow.set (ll,rr,bb,tt);
computeABCD();
}
void computeABCD() {
A = (viewport.r - viewport.l)/(worldWindow.r-worldWindow.l);
B = viewport.l - A * worldWindow.l;
C = (viewport.t - viewport.b)/(worldWindow.t-worldWindow.b);
D = viewport.b - C * worldWindow.b;
}
vector<mPointi> getPixelCoordinates(vector<mPointf>& vec) {
vector<mPointi> vi;
for (int i=0; i<vec.size(); i++)
vi.push_back( mPointi(roundf(A*vec[i].x+B), roundf(C*vec[i].y+D) ) );
return vi;
}
void draw (int type, vector<mPointf>& vec) {
vector<mPointi> vi = getPixelCoordinates(vec);
if (type==myLINE_STRIP) {
//std::cerr << "drawing myLINE_STRIP" << std::endl;
for (int i=1; i<vec.size(); i++)
drawLine (vi[i-1], vi[i]);
}
}
void draw (int type, vector<mPointf>& vec, vector<mColor>& vcolor) {
vector<mPointi> vi = getPixelCoordinates(vec);
if (type==myLINE_STRIP) {
for (int i=1; i<vec.size(); i++)
drawLine (vi[i-1], vi[i], vcolor[i-1], vcolor[i]);
}
}
mColor randomColor();
void drawPixel(int x0, int y0, uchar r, uchar g, uchar b);
void drawPixel(int x0, int y0, mColor c);
void drawLineX (int x1, int y1, int x2, int y2, mColor c1, mColor c2);
void drawLineY (int x1, int y1, int x2, int y2, mColor c1, mColor c2);
void drawLine (int x1, int y1, int x2, int y2, mColor c1=mR, mColor c2=mB);
void drawLine (mPointi p1, mPointi p2, mColor c1=mR, mColor c2=mB);
void drawLineX (vector<PointColor>& pcv,
int x1, int y1, int x2, int y2, mColor c1, mColor c2);
void drawLineY (vector<PointColor>& pcv,
int x1, int y1, int x2, int y2, mColor c1, mColor c2);
void drawLine (vector<PointColor>& pcv,
int x1, int y1, int x2, int y2, mColor c1=mR, mColor c2=mB);
void drawTriangle (int x1, int y1, int x2, int y2, int x3, int y3,
mColor c1=mR, mColor c2=mG, mColor c3=mB);
void drawTriangle (mPointi p1, mPointi p2, mPointi p3,
mColor c1=mR, mColor c2=mG, mColor c3=mB);
void drawTriangleFill (int x1, int y1, int x2, int y2, int x3, int y3,
mColor c1=mR, mColor c2=mG, mColor c3=mB);
void drawTriangleFill (mPointi p1, mPointi p2, mPointi p3,
mColor c1=mR, mColor c2=mG, mColor c3=mB);
void drawCircle (int x0, int y0, int r, mColor c1, int nSplit);
void drawCircleFilled (int x0, int y0, int r, mColor c1=mR, int nSplit=30);
};
float lip (int x, int r1, int r2, int x1, int x2);
mColor lip (int x, mColor c1, mColor c2, int x1, int x2);
// EOF // | true |
6beea93ae3d7837f7606c9ed5ea74f435620ac4b | C++ | 6gales/CompTech | /CompTech/SpellChecker/BruteForce.cpp | UTF-8 | 496 | 2.828125 | 3 | [] | no_license | #include "BruteForce.h"
std::multimap <size_t, std::string> BruteForce::checkWord(const std::string &source)
{
const size_t editDistance = editDistFormula(source.size());
std::string tmp;
std::multimap <size_t, std::string> suggestions;
while (dictionary.good())
{
dictionary >> tmp;
size_t dist = LevenshteinDistance(source, tmp);
if (dist <= editDistance)
suggestions.insert({ dist, tmp });
}
dictionary.clear();
dictionary.seekg(0, std::ios::beg);
return suggestions;
} | true |
346c7a44d0b25b4ccd0591629718a96ea2f1a832 | C++ | Lyuekiller/Pressurelog | /Pressurelog.h | UTF-8 | 683 | 2.546875 | 3 | [] | no_license | #ifndef LOG_H
#define LOG_H
#include <QDate>
#include <QTime>
class Pressurelog
{
public:
Pressurelog();
void setDate(QDate date);
void setTime(QTime time);
void setSand_ratio(double sand_ratio);
void setSand_concentration(double sand_concentration);
void setPressure(double pressure);
void setDisplacement(double displacement);
QDate getDate();
QTime getQTime();
double getSand_ratio();
double getSand_concentration();
double getPressure();
double getDisplacement();
private:
QDate date;
QTime time;
double sand_ratio;
double sand_concentration;
double pressure;
double displacement;
};
#endif // LOG_H
| true |
66d7cd342f5c31d159c77a93c9e0d934bcc0940d | C++ | matze999/MathX | /pi/scanner/SkipScanner.h | UTF-8 | 1,862 | 2.546875 | 3 | [] | no_license | #ifndef _SKIPSCANNER_H_
#define _SKIPSCANNER_H_
#include "../operator/Repeat.h"
#include "../scanner/Scanner.h"
namespace pi {
class skip_scanner_tag {};
template <class Parser, class Scanner = pi::Scanner>
class SkipScanner: private skip_scanner_tag
{
typedef _::repeat_p <Parser, 0, -1> SkipParser;
public:
typedef typename Scanner::Iterator Iterator;
typedef Scanner BaseScanner;
SkipScanner (const Parser &parser = Parser()):
skip_parser (parser)
{
}
SkipScanner (Scanner &scanner): skip_parser (Parser())
{
operator= (scanner);
}
SkipScanner& operator= (Scanner &scan)
{
if ((Scanner*) this != &scan) scanner = &scan;
skip();
return *this;
}
void pop_front()
{
scanner->pop_front();
skip();
}
char front() const
{
return scanner->front();
}
Iterator begin()
{
return scanner->begin();
}
void begin (Iterator& p)
{
scanner->begin (p);
}
bool empty() const
{
return scanner->empty();
}
void skip() const
{
TRC_DEBUG (scanner) << "call skip parser" << mgo::endl;
int level = TRC_LEVEL;
TRC_LEVEL = min (level, 3);
skip_parser.parse (*scanner, fn::no_action());
TRC_LEVEL = level;
}
operator bool() const
{
return !empty();
}
void invalidate (const char * msg = "")
{
scanner->invalidate (msg);
}
ErrorInfo& getErrorInfo()
{
return scanner->getErrorInfo();
}
operator BaseScanner& ()
{
return *scanner;
}
template <class Parser>
void addMessage(PARSING_ERROR, const Parser &parser)
{
scanner->addMessage(PARSING_ERROR, parser);
}
private:
SkipParser skip_parser;
mutable Scanner *scanner;
};
} // namespace pi
#endif
| true |
3d7209aa9d575c049abcd5068b21eb86a1bc2638 | C++ | gjbr5/othello | /localgame.cpp | UTF-8 | 1,526 | 3.078125 | 3 | [] | no_license | #include "localgame.h"
#include <QDebug>
#include <QMessageBox>
#include <cstdlib>
#include <ctime>
LocalGame::LocalGame(BoardModel* bm, PanelModel* pm, Player* player1, Player* player2)
: Game(bm, pm)
, black(player1)
, white(player2)
{
}
LocalGame::~LocalGame()
{
delete black;
delete white;
}
void LocalGame::run()
{
std::srand(std::time(nullptr));
if (std::rand() % 2) {
black->setTeam(Team::BLACK);
white->setTeam(Team::WHITE);
qInfo() << "Player1 is BLACK, Player2 is WHITE";
} else {
Player* tmp = black;
black = white;
white = tmp;
black->setTeam(Team::BLACK);
white->setTeam(Team::WHITE);
qInfo() << "Player2 is BLACK, Player1 is WHITE";
}
turn = Team::BLACK;
while (true) {
// Check Next Legal Move
BitBoard placeable = board.allLegalMove(turn);
if (placeable.none()) { // Pass
qInfo() << (turn == Team::BLACK ? "Pass: Black" : "Pass: White");
changeTurn();
placeable = board.allLegalMove(turn);
if (placeable.none()) // Game Over
break;
}
// Set Next Disk
size_t nextDisk = turn == Team::BLACK ? black->nextDisk(board) : white->nextDisk(board);
qInfo().nospace() << "Disk = " << nextDisk << "(" << nextDisk / 8 << ", " << nextDisk % 8 << ")";
board.setDisk(nextDisk, turn);
updateModel();
changeTurn();
}
// Game Over
gameOver();
}
| true |
966f04217eb827e6776f3b57cb4d29388437d525 | C++ | Omargw/CPP-iHUB | /session1.cpp | UTF-8 | 4,140 | 3.3125 | 3 | [] | no_license | // Example program
#include <iostream>
#include <string>
using namespace std;
// constants
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
cout << "Hello world \a " << endl;
// printf("Hello world \n");
// Escape sequence
/*
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
*/
// Datatypes and Variables
/*
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t
*/
// Datatypes Modifiers
/*
signed
unsigned
short
long
*/
// Datatypes Size
// sizeof(type)
cout << "int size: " << sizeof(int) << endl;
cout << "float size: " << sizeof(float) << endl;
cout << "char size: " << sizeof(char) << endl;
cout << "bool size: " << sizeof(bool) << endl;
cout << "double size: " << sizeof(double) << endl;
cout << "void size: " << sizeof(void) << endl;
cout << "wchar_t size: " << sizeof(wchar_t) << endl;
// constants
const int x = 10;
const float PI = 3.14;
// Operators
/*
1- Arithmetic Operators
2- Relational Operators
3- Logical Operators
4- Bitwise Operators
6- Misc Operators
*/
// 1- Arithmetic
/*
+ Adds two operands
- Subtracts second operand from the first
* Multiplies both operands
/ Divides numerator by de-numerator
% Modulus Operator and remainder of after an integer division
++ Increment operator, increases integer value by one
-- Decrement operator, decreases integer value by one
*/
int A = 10;
int B = 20;
int C;
C = A + B;
cout << "A + B will give " << C << endl;
cout << "A - B will give " << A - B << endl;
cout << "A * B will give " << A * B << endl;
cout << "B / A will give " << A / B << endl;
cout << "B % A will give " << A % B << endl;
cout << "A++ will give " << A++ << endl;
cout << "A-- will give " << A-- << endl;
// 2- Relational Operators
/*
== equal to
!= not equal to
> greater than
< smaller than
>= greater than or equal
<= smaller than or equal
*/
cout << "A == B will give " << (A == B) << endl;
cout << "A != B will give " << (A != B) << endl;
cout << "A > B will give " << (A > B) << endl;
cout << "A > B will give " << (A < B) << endl;
cout << "A >= B will give " << (A >= B) << endl;
cout << "A <= B will give " << (A <= B) << endl;
// 3- Logical Operators
/*
&& Called Logical AND operator.
|| Called Logical OR Operator.
! Called Logical NOT Operator.
*/
bool X = 1 , Y = 0;
cout << "X && Y will give " << (X && Y) << endl;
cout << "X || Y will give " << (X || Y) << endl;
cout << "!X will give " << !x << endl;
// 4- Bitwise Operators
/*
AND OR XOR NOT
p q p & q p | q p ^ q ~p
0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0
*/
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;
c = a & b; // 12 = 0000 1100
cout << "a & b - Value of c is : " << c << endl ;
c = a | b; // 61 = 0011 1101
cout << "a | b - Value of c is: " << c << endl ;
c = a ^ b; // 49 = 0011 0001
cout << "a ^ b - Value of c is: " << c << endl ;
c = ~a; // -61 = 1100 0011
cout << "~a - Value of c is: " << c << endl ;
c = a << 2; // 240 = 1111 0000
cout << "a << 2 - Value of c is: " << c << endl ;
c = a >> 2; // 15 = 0000 1111
cout << "a >> 2 - Value of c is: " << c << endl ;
// Decision Making (Control flow)
return 0;
}
| true |
f63c7496a6525c442f5ed80ff9016f4c2652b971 | C++ | BoostGSoC18/Advanced-Intrusive | /include/boost/graph/HLD/hld_ds.hpp | UTF-8 | 4,345 | 3.109375 | 3 | [
"BSL-1.0"
] | permissive | namespace boost{
namespace graph{
/*!
<ul>
<li>This is the main class which contains all the methods related to Heavy light decomposition.</li>
<li>This is a very popular decomposition because it has many applications in solving tree based problems.</li>
<li>With this decomposition we can travel between any 2 nodes in tree with just O(log(N)) chains.</li>
</ul>
*/
template<typename Graph>
class HLD
{
private:
int chainNo=0;
int *subtree,*visit,*chainHead,*chainPos,*chainInd,*chainSize,*heavy_child;
private:
typedef typename graph_traits<Graph>::adjacency_iterator adj_itr;
void subtreesize(int cur,Graph &graph)
{
visit[cur]=1;
adj_itr ai,ai_end;
for (boost::tie(ai, ai_end) = adjacent_vertices(cur, graph);ai != ai_end; ++ai)
{
if(visit[*ai]!=1)
{
subtreesize(*ai,graph);
subtree[cur]+=subtree[*ai];
}
}
subtree[cur]++;
}
void hld_impl(int cur,Graph &graph)
{
if(chainHead[chainNo] == -1)
{
chainHead[chainNo]=cur;
}
visit[cur]=1;
chainInd[cur] = chainNo;
chainPos[cur] = chainSize[chainNo];
chainSize[chainNo]++;
int ind = -1,mai = -1;
adj_itr ai,ai_end;
for (boost::tie(ai, ai_end) = adjacent_vertices(cur, graph);ai != ai_end; ++ai)
{
if(visit[*ai]!=1 && subtree[*ai] > mai)
{
mai = subtree[*ai];
ind = *ai;
}
}
if(ind >= 0)
{
hld_impl( ind,graph );
heavy_child[cur]=ind;
}
for (boost::tie(ai, ai_end) = adjacent_vertices(cur, graph);ai != ai_end; ++ai)
{
if(visit[*ai]!=1 && *ai != ind)
{
chainNo++;
hld_impl(*ai,graph);
}
}
}
public:
/*!
<ul>
<li> This function decomposes the input tree into chains by selecting heavy child.
</li>
</ul>
\param root root of input tree
\param num_nodes total number of vertices in input tree
\param graph input tree
\return Nothing
<p> </p>
<b> Complexity: </b> O(N)
*/
HLD(int root,int num_nodes,Graph &graph)
{
subtree=(int*)malloc((num_nodes+1)*sizeof(int));
chainHead=(int*)malloc((num_nodes+1)*sizeof(int));
chainPos=(int*)malloc((num_nodes+1)*sizeof(int));
chainInd=(int*)malloc((num_nodes+1)*sizeof(int));
chainSize=(int*)malloc((num_nodes+1)*sizeof(int));
visit=(int*)malloc((num_nodes+1)*sizeof(int));
heavy_child=(int*)malloc((num_nodes+1)*sizeof(int));
for(int i=0;i<num_nodes;i++)
{
chainHead[i]=-1;
subtree[i]=0;
visit[i]=0;
heavy_child[i]=-1;
}
subtreesize(root,graph);
for(int i=0;i<num_nodes;i++)
{
visit[i]=0;
}
hld_impl(root,graph);
}
/*!
<ul>
<li> This function gives the head node of the chain to which input node belongs to.
</li>
</ul>
\param node a vertex from input graph
\return head vertex of chain to which input node belongs to.
<p> </p>
<b> Complexity: </b> O(1) - constant time
*/
int get_chain_head(int node)
{
int chain=chainInd[node];
return chainHead[chain];
}
/*!
<ul>
<li> This function gives the size of the chain to which input node belongs to.
</li>
</ul>
\param node a vertex from input graph
\return size of chain to which input node belongs to.
<p> </p>
<b> Complexity: </b> O(1) - constant time
*/
int get_chain_size(int node)
{
int chain=chainInd[node];
return chainSize[chain];
}
/*!
<ul>
<li> This function gives the heavy child of input node.
</li>
</ul>
\param node a vertex from input graph
\return if input node is leaf node returns -1 else returns heavy child of input node.
<p> </p>
<b> Complexity: </b> O(1) - constant time
*/
int get_heavy_child(int node)
{
int child=heavy_child[node];
return child;
}
};
}
}
| true |
4d6628e324817c0a1a060ff045f433a911ebba16 | C++ | dayeondev/AlgoStudy | /etc/10886_cute.cpp | UTF-8 | 296 | 2.75 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int n;
int t = 0, f = 0;
int main(void){
cin >> n;
int tmp;
for(int i = 0; i < n; i++){
cin >> tmp;
if(tmp) t++;
else f++;
}
if(t < f) cout << "Junhee is not cute!";
else cout << "Junhee is cute!";
}
| true |
5fa7d2f85615d37a738e5d5e915b7234a0f54ac2 | C++ | EricPolman/Micro-Machines-in-3D | /Code/RaceManager.cpp | UTF-8 | 4,782 | 2.65625 | 3 | [] | no_license | #include "RaceManager.h"
#include <iostream>
#include "TextRenderer.h"
#include <sstream>
#include "Boat.h"
#include "Camera.h"
using namespace GameLayer;
RaceManager::~RaceManager(void)
{
m_waypoints.clear();
m_racerData.clear();
}
void RaceManager::Init()
{
TextRenderer::GetInstance()->AddString("lapcounter", "Lap: 1 of 4", "andes-28");
TextRenderer::GetInstance()->AddString("timer", "0 seconds", "andes-28");
TextRenderer::GetInstance()->AddString("wrongdir", "Wrong direction", "andes-28");
TextRenderer::GetInstance()->AddString("finished", "Finished in some time", "andes-50");
//Sounds->Pause();
m_countDown = std::unique_ptr<CountDown>(new CountDown());
//m_countDown->Translate(100, 100);
}
void RaceManager::Update(float a_fDeltaTime)
{
std::stringstream sstr;
std::string str;
if(m_countDown.get() != nullptr)
{
m_countDown->Update(a_fDeltaTime);
if(m_countDown->m_bDestroyMe)
m_countDown.reset();
}
switch(m_raceState)
{
default:
case RaceState::STARTING:
m_fCountDownTimer += a_fDeltaTime;
if(m_fCountDownTimer > 4)
{
SetState(RaceState::RUNNING);
}
break;
case RaceState::RUNNING:
{
sstr << "Lap: " << (m_racerData.begin()->second.lapNumber + 1);
sstr << " of 4";
str = sstr.str();
TextRenderer::GetInstance()->UpdateString("lapcounter", str);
sstr.str("");
sstr << "Time: " << (int)m_racerData.begin()->second.raceTime / 60 << ":";
if((int)m_racerData.begin()->second.raceTime % 60 < 10)
sstr << "0";
sstr << ((int)m_racerData.begin()->second.raceTime % 60) << "";
str = sstr.str();
TextRenderer::GetInstance()->UpdateString("timer", str);
for(auto i = m_racerData.begin(); i != m_racerData.end(); i++)
{
if(i->second.lapNumber + 1 > 4)
m_raceState = RaceState::ENDED;
if(!i->second.finished)
{
i->second.raceTime += a_fDeltaTime;
}
}
}
break;
case RaceState::PAUSED:
break;
case RaceState::ENDED:
sstr << "Finished in: " << (int)m_racerData.begin()->second.raceTime / 60 << ":";
if((int)m_racerData.begin()->second.raceTime % 60 < 10)
sstr << "0";
sstr << ((int)m_racerData.begin()->second.raceTime % 60) << "";
str = sstr.str();
char* lap = const_cast<char*>(str.c_str());
TextRenderer::GetInstance()->UpdateString("finished", str);
break;
}
}
void RaceManager::Draw()
{
switch(m_raceState)
{
default:
case RaceState::STARTING:
{
}
break;
case RaceState::RUNNING:
{
if(m_racerData.size() > 0)
{
TextRenderer::GetInstance()->DrawString("lapcounter", Vector2(10,10));
TextRenderer::GetInstance()->DrawString("timer", Vector2(10,50));
auto nextWaypoint = m_waypoints.begin();
for(;nextWaypoint != m_waypoints.end(); nextWaypoint++)
{
if(*nextWaypoint == m_racerData.begin()->second.currentWaypoint)
{
nextWaypoint++;
break;
}
}
if(nextWaypoint == m_waypoints.end())
nextWaypoint = m_waypoints.begin();
Boat* racerOne = (Boat*)m_racerData.begin()->first;
if((Camera::GetInstance()->m_direction).Dot((*nextWaypoint)->GetPosition() - racerOne->GetPosition()) < 0)
{
TextRenderer::GetInstance()->DrawString("wrongdir", Vector2(20,600 - 48));
}
}
}
break;
case RaceState::PAUSED:
break;
case RaceState::ENDED:
{
TextRenderer::GetInstance()->DrawString("finished", Vector2(70,280));
}
break;
}
}
void RaceManager::AddWaypoint(Waypoint* a_waypoint)
{
m_waypoints.push_back(a_waypoint);
}
void RaceManager::ProcessWaypointHit(Waypoint* a_waypoint, Entity* a_entity)
{
if(a_entity->GetType() == EntityType::RACER)
{
int curWaypoint = 0;
for(; curWaypoint < m_waypoints.size(); curWaypoint++ )
{
if(a_waypoint == m_waypoints[curWaypoint])
break;
}
int targetPrevious =
(curWaypoint == 0 ? m_waypoints.size()-1 : curWaypoint-1);
if(m_racerData[a_entity].currentWaypoint == m_waypoints[targetPrevious])
{
if(a_waypoint == m_waypoints[0])
{
m_racerData[a_entity].lapNumber++;
SpawnMines();
}
m_racerData[a_entity].currentWaypoint = a_waypoint;
}
else if(m_racerData[a_entity].currentWaypoint == nullptr)
{
m_racerData[a_entity].currentWaypoint = a_waypoint;
}
}
}
void RaceManager::AddMineSpawner(MineSpawner* a_pSpawner)
{
m_mineSpawners.push_back(a_pSpawner);
}
void RaceManager::SpawnMines()
{
for(auto i = m_mineSpawners.begin(); i != m_mineSpawners.end(); i++)
{
(*i)->Spawn();
}
} | true |
44a0a86f7b582ee71b46dd12e71515daaa6e534e | C++ | AparAhuja/COL216_Lab | /A3/main.cpp | UTF-8 | 18,601 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
using namespace std;
string file_path = "/Users/aparahuja/Desktop/IITD/COL216 - Arch/COL216_Lab/A3/A3/input.txt";
int PC = 0;
int PARTITION = 0;
int memory[1048576];
string decimalToHexadecimal(long long a) {
string ans = "";
map<int, string> hex{ {0,"0"},{1,"1"},{2,"2"},{3,"3"},{4,"4"},{5,"5"},{6,"6"},{7,"7"},{8,"8"},{9,"9"},{10,"a"},{11,"b"},{12,"c"},{13,"d"},{14,"e"},{15,"f"} };
if(a < 0) { a += 4294967296; }
for(int i = 0; i < 8; i ++) {
int dig = a % 16;
a /= 16;
ans = hex[dig] + ans;
}
return ans;
}
bool isInteger(string s) {
int len = s.length();
if (len == 0) return false;
for (int i = 0; i < len; i++) {
if (s.at(i) < '0' || s.at(i) > '9') { return false; }
}
return true;
}
struct REGI {
//INSTRUCTION COUNT
//int ins_cnt_add, ins_cnt_sub...
// check lower case and upper case
map<string, int> ins_map = { {"add", 0}, {"sub", 1}, {"mul", 2},{"beq", 3},{"bne", 4},{"slt", 5},{"j", 6},{"lw", 7},{"sw", 8},{"addi", 9} };
map<string, int> reg_map = { {"$zero", 0}, {"$at", 1}, {"$v0", 2}, {"$v1", 3}, {"$a0", 4}, {"$a1", 5}, {"$a2",6}, {"$a3", 7}, {"$t0", 8}, {"$t1", 9}, {"$t2", 10},
{"$t3", 11}, {"$t4", 12}, {"$t5", 13}, {"$t6", 14}, {"$t7", 15}, {"$s0", 16}, {"$s1", 17}, {"$s2", 18}, {"$s3", 19}, {"$s4", 20}, {"$s5", 21},
{"$s6", 22}, {"$s7", 23}, {"$t8", 24}, {"$t9", 25}, {"$k0", 26}, {"$k1", 27}, {"$gp", 28}, {"$ap", 29}, {"$fp", 30}, {"$ra", 31} };
int ins_cnt[10], reg[32];
int cycle_cnt = 0;
// constructor for initialization
REGI() {
for (int i = 0; i < 32; i++)
reg[i] = 0;
for (int i = 0; i < 10; i++)
ins_cnt[i] = 0;
}
void print_reg_file() {
cout << "Register file contents after " << cycle_cnt << " clock cycles:\n";
int j = 1;
for (auto i = reg_map.begin(); i != reg_map.end(); i++) {
cout << (i->first) << ": " << decimalToHexadecimal(reg[(i->second)]);
if (j % 5 == 0 || j == 32) cout << "\n";
else
cout << ", ";
j++;
}
}
void execution_stats() {
cout << "Total clock cycles: " << cycle_cnt << "\n\n";
cout << "Number of instructions executed for each type are given below:-\n"
for (auto i = ins_map.begin(); i != ins_map.end(); i++) {
cout << (i->first) << ": " << ins_cnt[(i->second)] << "\n";
}
}
int labelToAddr(string label) {
// if label is integer return else hash
if (isInteger(label))
return stoi(label);
else
return reg_map[label];
}
bool add(int dest, int src1, int src2) {
long long sum = reg[src1] + reg[src2];
if (sum > 2147483647 || sum < -2147483648) {
cout << "Error: Arithmetic Overflow. Program terminating!\n\n";
return false;
}
else {
reg[dest] = sum;
stat_update(0);
return true;
}
}
bool sub(int dest, int src1, int src2) {
long long diff = reg[src1] - reg[src2];
if (diff > 2147483647 || diff < -2147483648) {
cout << "Error: Arithmetic Overflow. Program terminating!\n\n";
return false;
}
else {
reg[dest] = diff;
stat_update(1);
return true;
}
}
bool mul(int dest, int src1, int src2) {
long long prod = reg[src1] * reg[src2];
if (prod > 2147483647 || prod < -2147483648) {
cout << "Error: Arithmetic Overflow. Program terminating!\n\n";
return false;
}
else {
reg[dest] = prod;
stat_update(2);
return true;
}
}
void beq(int src1, int src2, int jumpby) {
if (src1 == src2) {
PC += 4 + 4 * jumpby;
}
else PC += 4;
stat_update(3);
}
void bne(int src1, int src2, int jumpby) {
if (src1 != src2) {
PC += 4 + 4 * jumpby;
}
else PC += 4;
stat_update(4);
}
void slt(int dest, int src1, int src2) {
reg[dest] = (reg[src1] < reg[src2]) ? 1 : 0;
stat_update(5);
}
void j(int jumpto) {
PC = 4 * jumpto;
stat_update(6);
}
void lw(int dest, int offset, int src) {
// check if address is valid
reg[dest] = memory[src + 4*offset];
stat_update(7);
}
void sw(int src, int offset, int dest) {
// check if address is valid
memory[dest + 4*offset] = reg[src];
stat_update(8);
}
bool addi(int dest, int src, int adds) {
long long sum = reg[src] + adds;
if (sum > 2147483647 || sum < -2147483648) {
cout << "Error: Arithmetic Overflow. Program terminating!\n\n";
return false;
}
else {
reg[dest] = sum;
stat_update(9);
return true;
}
}
void stat_update(int ins_code) {
cycle_cnt++;
ins_cnt[ins_code]++;
}
};
bool simulator(REGI rf) {
int ins_code;
bool flag;
while (PC < PARTITION) {
//{"add", 0}, { "sub", 1 }, { "mul", 2 }, { "beq", 3 }, { "bne", 4 }, { "slt", 5 }, { "j", 6 }, { "lw", 7 }, { "sw", 8 }, { "addi", 9 }
ins_code = memory[PC];
switch (ins_code) {
case 0:
flag = rf.add(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
if (flag) PC += 4;
else return flag;
break;
case 1:
flag = rf.sub(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
if (flag) PC += 4;
else return flag;
break;
case 2:
flag = rf.mul(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
if (flag) PC += 4;
else return flag;
break;
case 3:
rf.beq(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
break;
case 4:
rf.bne(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
break;
case 5:
rf.slt(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
PC += 4;
break;
case 6:
rf.j(memory[PC + 1]);
break;
case 7:
rf.lw(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
PC += 4;
break;
case 8:
rf.sw(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
PC += 4;
break;
case 9:
flag = rf.addi(memory[PC + 1], memory[PC + 2], memory[PC + 3]);
if (flag) PC += 4;
else return flag;
break;
}
rf.print_reg_file():
}
// PC >= PARTITION, so execution is complete
return true;
}
pair<vector<string>, bool> parseInstruction(string instruction) {
vector<string> args;
int len = instruction.length();
int arg_count = 0, i = 0;
bool isInstruction = false;
string code = "", arg1 = "", arg2 = "", arg3 = "";
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, true);
else {
while (i < len && instruction.at(i) != ' ' && instruction.at(i) != ',') {
code = code + instruction[i];
i++;
}
if (code.length() == 0) {
return make_pair(args, false);
}
else {
args.push_back(code);
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, false);
else {
arg_count++;
while (i < len && instruction.at(i) != ' ' && instruction.at(i) != ',') {
arg1 = arg1 + instruction[i];
i++;
}
if (arg1.length() == 0)
return make_pair(args, false);
else {
args.push_back(arg1);
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, true);
else {
if (instruction.at(i) = ',') i++;
arg_count++;
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, false);
while (i < len && instruction.at(i) != ' ' && instruction.at(i) != ',' && instruction.at(i) != '(') {
arg2 = arg2 + instruction[i];
i++;
}
if (arg2.length() == 0)
return make_pair(args, false);
else {
args.push_back(arg2);
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, true);
else {
if (instruction.at(i) = ',') {
i++;
arg_count++;
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, false);
while (i < len && instruction.at(i) != ' ' && instruction.at(i) != ',') {
arg3 = arg3 + instruction[i];
i++;
}
if (arg3.length() == 0)
return make_pair(args, false);
else {
args.push_back(arg3);
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, true);
else return make_pair(args, false);
}
}
else {
if (instruction.at(i) == '(') {
i++;
arg_count++;
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, false);
while (i < len && instruction.at(i) != ')') {
arg3 = arg3 + instruction[i];
i++;
}
if (arg3.length() == 0)
return make_pair(args, false);
else {
args.push_back(arg3);
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, true);
else return make_pair(args, false);
}
}
else {
while (i < len && instruction.at(i) != ' ') {
arg3 = arg3 + instruction[i];
i++;
}
if (arg3.length() == 0)
return make_pair(args, false);
else {
args.push_back(arg3);
while (i < len && instruction.at(i) = ' ') i++;
if (i == len)
return make_pair(args, true);
else return make_pair(args, false);
}
}
}
}
}
}
}
}
}
}
}
//add line to memory
bool addToMemory(string line, REGI rf, int line_number) {
vector<string> args;
bool flag;
long i = 0, len = line.length();
/*while(true){
string x = "";
while(i < len && (line.at(i) == ' ' || line.at(i) == ',' || line.at(i) == '(')) { i++; }
while(i < len && line.at(i) != ' ' && line.at(i) != ',' && line.at(i) != ')' && line.at(i) != '(') { x += line[i]; i++; }
while(i < len && (line.at(i) == ' ' || line.at(i) == ',' || line.at(i) == ')')) { i++; }
if(x.length() != 0) args.push_back(x);
if(i == len){break;}
}*/
pair<vector<string>, bool> Pair = parseInstruction(line);
args = Pair.first;
flag = Pair.second;
if (!flag) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
return false;
}
else {
if (args.size() == 0)
return true;
else {
if (len == 0) { return true; }
if (rf.ins_map.find(args[0]) == rf.ins_map.end()) { cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n"; return false; }
int ins = rf.ins_map[args[0]];
memory[PC] = ins;
len = args.size();
//jump
if (ins == 6) {
if (len != 2) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
return false;
}
else {
if (!isInteger(args[1])) { cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n"; return false; }
else {
int addr = stoi(args[1]);
if (addr >= PARTITION / 4 || addr < 0) { cout << "Invalid Address ERROR: At line number: " << line_number << ": " << "\n"; return false; }
memory[PC + 1] = stoi(args[1]);
}
}
}
//add sub mul slt
else if (ins == 0 || ins == 1 || ins == 2 || ins == 5) {
if (len != 4) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
return false;
}
else {
if (rf.reg_map.find(args[1]) == rf.reg_map.end() || rf.reg_map.find(args[2]) == rf.reg_map.end() || rf.reg_map.find(args[3]) == rf.reg_map.end()) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
return false;
}
else {
memory[PC + 1] = rf.reg_map[args[1]];
memory[PC + 2] = rf.reg_map[args[2]];
memory[PC + 3] = rf.reg_map[args[3]];
}
}
}
//beq bne addi
else if (ins == 3 || ins == 4 || ins == 9) {
if (len != 4) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
}
else {
if (rf.reg_map.find(args[1]) == rf.reg_map.end() || rf.reg_map.find(args[2]) == rf.reg_map.end() || !isInteger(args[3])) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
}
else {
memory[pc + 1] = rf.reg_map[args[1]];
memory[pc + 2] = rf.reg_map[args[2]];
memory[pc + 3] = stoi(args[3]);
}
}
}
//sw lw
else {
if (len != 4) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
}
else {
if (rf.reg_map.find(args[1]) == rf.reg_map.end() || !isInteger(args[2]) || rf.reg_map.find(args[3]) == rf.reg_map.end()) {
cout << "SYNTAX ERROR: At line number: " << line_number << ": " << line << "\n";
}
else {
memory[pc + 1] = rf.reg_map[args[1]];
memory[pc + 2] = stoi(args[2]);
memory[pc + 3] = rf.reg_map[args[3]];
}
}
}
}
}
PC += 4;
}
int main(int argc, const char* argv[]) {
ifstream infile(file_path);
//File error
if (!infile.is_open()) {
cout << "ERROR: Unable to open file. Program terminating!\n";
return 0;
}
REGI rf;
string line;
int line_number = 1;
bool flag;
//read line by line
while (getline(infile, line)) {
//process and store each instruction in memory
flag = addToMemory(line, rf, line_number);
if (!flag) {
cout << "Program terminating!\n";
return 0;
}
line_number++;
}
PARTITION = PC;
PC = 0;
simulator(rf);
infile.close();
//for (int i = 1; i <= 12; i++) { cout << memory[i - 1] << " ";if (i % 4 == 0) { cout << "\n"; } }
//cout<<decimalToHexadecimal(-2);
//rf.print_reg_file();
//rf.execution_stats();
//addToMemory(" add $t1, $t2 ( 345t ) ", rf);
return 0;
}
| true |
9007bea7209a9db30bde93f4946326a8ca166bb8 | C++ | ren082215/LeetCode | /src/cpp/0150-evaluateReversePolishNotation.cpp | UTF-8 | 567 | 2.984375 | 3 | [] | no_license | class Solution {
public:
int evalRPN(vector<string>& tokens) {
int op = (int)tokens.size() - 1;
return helper(tokens, op);
}
int helper(vector<string>& tokens, int& op) {
string str = tokens[op];
if (str != "+" && str != "-" && str != "*" && str != "/") return stoi(str);
int num1 = helper(tokens, --op);
int num2 = helper(tokens, --op);
if (str == "+") return num2 + num1;
if (str == "-") return num2 - num1;
if (str == "*") return num2 * num1;
return num2 / num1;
}
};
| true |
0c93f18fcc7153a58db7fc2cd64edde2d18a1fba | C++ | darcyliu/mlpack | /src/mlpack/methods/ann/performance_functions/sse_function.hpp | UTF-8 | 1,540 | 2.9375 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* @file sse_function.hpp
* @author Marcus Edel
*
* Definition and implementation of the sum squared error performance function.
*/
#ifndef MLPACK_METHODS_ANN_PERFORMANCE_FUNCTIONS_SSE_FUNCTION_HPP
#define MLPACK_METHODS_ANN_PERFORMANCE_FUNCTIONS_SSE_FUNCTION_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The sum squared error performance function measures the network's performance
* according to the sum of squared errors.
*/
class SumSquaredErrorFunction
{
public:
/**
* Computes the sum squared error function.
*
* @param network Network type of FFN, CNN or RNN
* @param target Target data.
* @param error same as place holder
* @return sum of squared errors.
*/
template<typename DataType, typename... Tp>
static double Error(const std::tuple<Tp...>& network,
const DataType& target,
const DataType &error)
{
return Error(std::get<sizeof...(Tp) - 1>(network).OutputParameter(),
target, error);
}
/**
* Computes the sum squared error function.
*
* @param input Input data.
* @param target Target data.
* @return sum of squared errors.
*/
template<typename DataType>
static double Error(const DataType& input,
const DataType& target,
const DataType&)
{
return arma::sum(arma::square(target - input));
}
}; // class SumSquaredErrorFunction
} // namespace ann
} // namespace mlpack
#endif
| true |
d6f257b02c6c8531387df7864ab35d7a9a7849ff | C++ | SX-CPP/sci_computing_cpp_wi2019 | /exercises/solution/sheet5/exercise3a.hh | UTF-8 | 2,194 | 3.703125 | 4 | [] | no_license | #pragma once
#include <cassert>
#include <vector>
struct Matrix1
{
// Default initialization
// NOTE:
// - The keyword `= default` means: use the default implementation for that function.
// - The default implementation of the default constructor is: default-construct all
// members of the class.
Matrix1() = default;
// Initialize the Matrix1
Matrix1(std::size_t r, std::size_t c, double value = 0.0);
// Return the (i,j)th entry of the matrix
// NOTE:
// - implemented inline (keyword `inline` not necessary)
// - Functions with just 1 line could be implemented "inline" in the class
double access(std::size_t i, std::size_t j) const
{
return rows[i][j];
}
// Mutable access to the entry (i,j) of the matrix
// NOTE: The only differences to the const access are
// 1. return type is reference
// 2. function is not const.
// NOTE: implemented inline (keyword `inline` not necessary)
double& access(std::size_t i, std::size_t j)
{
return rows[i][j];
}
// Access by the bracket operator
// NOTE:
// - implemented inline (keyword `inline` not necessary)
// - The additional indirection by the call to `access` does not count, if
// that function is inlined by the compiler.
double operator()(std::size_t i, std::size_t j) const
{
return access(i,j);
}
// An additional useful function is the *mutable* access to the data
// NOTE: implemented inline (keyword `inline` not necessary)
double& operator()(std::size_t i, std::size_t j)
{
return access(i,j);
}
// Accumulated plus operator
Matrix1& operator+=(Matrix1 const& rhs);
// The data of the matrix: row vectors
std::vector<std::vector<double>> rows;
};
// Add the two matrices A and B and return the sum
// NOTE:
// - Here, the first argument is taken by value, since we need to create a copy anyway
// - An alternative signature would be (Matrix1 const& lhs, Matrix1 const& rhs)
// - Always try to implement the binary operators in terms of the compound assignment operators!
// - keyword `inline` is necessary, since implemented in a header file
inline Matrix1 operator+(Matrix1 lhs, Matrix1 const& rhs)
{
return lhs += rhs;
}
| true |
8d39b9d16a3969425c45c5bf3e3b3efd74404c42 | C++ | carlosngo/pseudocode | /res/question_9.cpp | UTF-8 | 1,345 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
void printF(int fontSize){
for(int i = 0; i<fontSize; i++){
cout << "*";
}
cout << endl;
cout << "*";
cout << endl;
for (int j = 0; j < fontSize -1; j++){
cout << "*";
}
cout << endl;
for(int i = 0; i<fontSize-2; i++){
cout << "*" << endl;
}
}
void printT(int fontSize){
int space = fontSize/2;
for(int i = 0; i<fontSize; i++){
cout << "*";
}
cout << endl;
for(int i = 0; i<fontSize-1; i++){
for(int j = 0; j<space; j++){
cout << " ";
}
cout << "*" << endl;
}
}
void printL(int fontSize){
for(int i = 0; i<fontSize-1; i++){
cout << "*" << endl;
}
for(int i = 0; i<fontSize; i++){
cout << "*";
}
}
int main()
{
char c;
int fontSize;
cout << "Enter char: ";
cin >> c;
if(c != 'F' && c != 'T' && c != 'L'){
cout << "Please only enter characters F, T, or L" << endl;
} else{
cout << "Enter font size: ";
cin >> fontSize;
if(fontSize<5){
cout << "Font size must be 5 or greater";
} else {
if(c == 'F'){
printF(fontSize);
} else if(c == 'T'){
printT(fontSize);
} else if (c == 'L'){
printL(fontSize);
}
}
}
} | true |
bfc2b80e030442b127736c8513c2a09abee770b1 | C++ | ooeyusea/OEngine2D | /src/OEngine2D/system/FileSystem.cpp | UTF-8 | 492 | 2.75 | 3 | [
"MIT"
] | permissive | #include "FileSystem.h"
#include <fstream>
namespace oengine2d {
bool FileSystem::Init() {
return true;
}
void FileSystem::Release() {
}
bool FileSystem::ReadFile(const std::string& path, std::string& buffer) {
std::ifstream file(path, std::ios::ate | std::ios::binary);
if (!file.is_open()) {
return false;
}
size_t fileSize = (size_t)file.tellg();
buffer.resize(fileSize);
file.seekg(0);
file.read(buffer.data(), fileSize);
file.close();
return true;
}
} | true |
aad0754322ad8acf065f15423a002a670d7ec9b9 | C++ | DongjunLim/algorithm_study | /프로그래머스/큰수 만들기.cpp | UTF-8 | 620 | 3.109375 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
using namespace std;
string solution(string number, int k) {
string answer = "";
int leng = number.length() - k;
int idx = 0;
int count = 0;
char max;
while (k > 0 && answer.length() < leng) {
max = number[idx];
for (int i = idx; i < idx + k; i++) {
if (max < number[i + 1]) {
max = number[i + 1];
count = i + 1;
}
}
answer.push_back(max);
k = k - (count - idx);
idx = count + 1;
count = idx;
}
if (answer.length() < leng) {
for (int j = idx; j < number.length(); j++)
answer.push_back(number[j]);
}
return answer;
} | true |
17282f32bf491c773f25b3cca14e8976d5d4d7bf | C++ | juanjp600/pge | /Src/Graphics/Texture/TextureOGL3.cpp | UTF-8 | 4,724 | 2.546875 | 3 | [
"Zlib"
] | permissive | #include "../GraphicsOGL3.h"
#include <stdlib.h>
using namespace PGE;
static int getCompressedFormat(Texture::CompressedFormat fmt) {
switch (fmt) {
using enum Texture::CompressedFormat;
case BC1: { return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; }
case BC2: { return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; }
case BC3: { return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; }
case BC4: { return GL_COMPRESSED_RED_RGTC1; }
case BC5: { return GL_COMPRESSED_RG_RGTC2; }
case BC6: { return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB; }
case BC7: { return GL_COMPRESSED_RGBA_BPTC_UNORM_ARB; }
default: { throw Exception("Invalid compressed format"); }
}
}
static void textureImage(int width, int height, const byte* buffer, Texture::Format fmt) {
GLint glInternalFormat;
GLenum glFormat;
GLenum glPixelType;
switch (fmt) {
using enum Texture::Format;
case RGBA64: {
glInternalFormat = GL_RGBA16;
glFormat = GL_RGBA;
glPixelType = GL_UNSIGNED_SHORT;
} break;
case RGBA32: {
glInternalFormat = GL_RGBA8;
glFormat = GL_RGBA;
glPixelType = GL_UNSIGNED_BYTE;
} break;
case R32F: {
glInternalFormat = GL_DEPTH_COMPONENT32F;
glFormat = GL_DEPTH_COMPONENT;
glPixelType = GL_FLOAT;
} break;
case R8: {
glInternalFormat = GL_R8;
glFormat = GL_RED;
glPixelType = GL_UNSIGNED_BYTE;
} break;
default: {
throw Exception("Invalid format");
}
}
glTexImage2D(GL_TEXTURE_2D, 0, glInternalFormat, width, height, 0, glFormat, glPixelType, buffer);
GLenum glError = glGetError();
PGE_ASSERT(glError == GL_NO_ERROR, "Failed to create texture (" + String::from(width) + "x" + String::from(height) + "; GLERROR: " + String::from(glError) + ")");
}
static void applyTextureParameters(bool rt) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, rt ? GL_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, rt ? GL_NEAREST : GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY, rt ? 1.f : 4.f);
}
TextureOGL3::TextureOGL3(Graphics& gfx, int w, int h, Format fmt) : Texture(w, h, true, fmt), resourceManager(gfx) {
((GraphicsOGL3&)gfx).takeGlContext();
glTexture = resourceManager.addNewResource<GLTexture>();
textureImage(w, h, nullptr, fmt);
applyTextureParameters(true);
/*glGenFramebuffers(1,&glFramebuffer);
glBindFramebuffer(GL_FRAMEBUFFER,glFramebuffer);*/
glDepthbuffer = resourceManager.addNewResource<GLDepthBuffer>(w, h);
//glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, glDepthbuffer);
GLenum glError = glGetError();
PGE_ASSERT(glError == GL_NO_ERROR, "Failed to create texture (GLERROR: " + String::from(glError) + ")");
}
TextureOGL3::TextureOGL3(Graphics& gfx, int w, int h, const byte* buffer, Format fmt, bool mipmaps) : Texture(w, h, false, fmt), resourceManager(gfx) {
((GraphicsOGL3&)gfx).takeGlContext();
glTexture = resourceManager.addNewResource<GLTexture>();
textureImage(w, h, buffer, fmt);
if (mipmaps) { glGenerateMipmap(GL_TEXTURE_2D); }
applyTextureParameters(false);
GLenum glError = glGetError();
PGE_ASSERT(glError == GL_NO_ERROR, "Failed to create texture (GLERROR: " + String::from(glError) + ")");
}
TextureOGL3::TextureOGL3(Graphics& gfx, const std::vector<Mipmap>& mipmaps, CompressedFormat fmt) : Texture(mipmaps[0].width, mipmaps[0].height, false, fmt), resourceManager(gfx) {
((GraphicsOGL3&)gfx).takeGlContext();
glTexture = resourceManager.addNewResource<GLTexture>();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, (GLint)(mipmaps.size() - 1));
for (GLint i : Range((GLint)mipmaps.size())) {
glCompressedTexImage2D(GL_TEXTURE_2D, i, getCompressedFormat(fmt),
mipmaps[i].width, mipmaps[i].height, 0, (GLsizei)mipmaps[i].size, mipmaps[i].buffer);
}
applyTextureParameters(false);
GLenum glError = glGetError();
PGE_ASSERT(glError == GL_NO_ERROR, "Failed to create texture (GLERROR: " + String::from(glError) + ")");
}
GLuint TextureOGL3::getGlTexture() const {
return glTexture;
}
/*GLuint TextureOGL3::getGlFramebuffer() const {
return glFramebuffer;
}*/
GLuint TextureOGL3::getGlDepthbuffer() const {
return glDepthbuffer;
}
void* TextureOGL3::getNative() const {
return (void*)&glTexture;
}
| true |
c1f352c75b5052adbf7755a701f27a3d3bf8cc10 | C++ | drleq/CppDicom | /DicomTest/dicom_test/data/URTest.cpp | UTF-8 | 2,366 | 2.65625 | 3 | [
"MIT",
"BSL-1.0"
] | permissive | #include "dicomtest_pch.h"
#include "CppUnitTestFramework.hpp"
#include "dicom/data/UR.h"
#include "dicom/Tags.h"
#include "dicom_test/data/detail/constants.h"
using namespace std;
using namespace dicom;
using namespace dicom::data;
namespace {
struct URTest {};
}
namespace dicom_test::data {
TEST_CASE(URTest, Construction) {
// UR()
UR ur0;
REQUIRE(ur0.Empty());
// UR(const uri&)
uri value("http://localhost:1234/ping");
UR ur1(value);
REQUIRE(!ur1.Empty());
REQUIRE_EQUAL(ur1.Value(), value);
// UR(uri&&)
UR ur2(move(value));
REQUIRE(!ur2.Empty());
REQUIRE_EQUAL(ur2.Value(), ur1.Value());
REQUIRE(value.Value().empty());
// UR(const UR&)
UR ur3(ur2);
REQUIRE(!ur3.Empty());
REQUIRE_EQUAL(ur3.Value(), ur2.Value());
// UR(UR&&)
UR ur4(move(ur2));
REQUIRE(!ur4.Empty());
REQUIRE_EQUAL(ur4.Value(), ur3.Value());
REQUIRE(ur2.Empty());
}
//------------------------------------------------------------------------------------------------------------
TEST_CASE(URTest, Equality_SingleValue) {
UR ur1("http://localhost:1234/ping1");
UR ur2("http://localhost:1234/ping2");
REQUIRE(ur1 == &ur1);
REQUIRE(ur1 != &ur2);
REQUIRE(ur2 != &ur1);
REQUIRE(ur1 < &ur2);
REQUIRE(ur1 <= &ur2);
REQUIRE(ur2 > &ur1);
REQUIRE(ur2 >= &ur1);
}
//------------------------------------------------------------------------------------------------------------
TEST_CASE(URTest, Empty) {
UR ur1;
REQUIRE(ur1.Empty());
UR ur2{uri{}};
REQUIRE(ur2.Empty());
UR ur3("http://localhost:1234/ping");
REQUIRE(!ur3.Empty());
}
//------------------------------------------------------------------------------------------------------------
TEST_CASE(URTest, Copy) {
uri value("http://localhost:1234/ping");
UR us_orig(value);
std::unique_ptr<VR> vr_copy(us_orig.Copy());
REQUIRE(static_cast<bool>(vr_copy));
auto us_copy = dynamic_cast<UR*>(vr_copy.get());
REQUIRE(us_copy != nullptr);
REQUIRE(us_orig.Value() == us_copy->Value());
REQUIRE(us_orig == us_copy);
}
} | true |
8666be07b6f7c0947f7f1b71956c3762b3a47549 | C++ | uc4w6c/CompetitiveProgramming | /tutorial/3.04/main.cpp | UTF-8 | 348 | 3.125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Book {
string name;
int price;
};
int main() {
vector<Book> books;
books.push_back({ "アルゴリズムとデータ構造", 4000 });
books.push_back({ "リーダブルコード", 2000 });
for (Book book: books) {
cout << book.name << ", " << book.price << endl;
}
}
| true |
e27ae0a1691969e4335af32da72afe65ab48ba4d | C++ | byebye/TimeGuard | /timeguardgui/timelimit.h | UTF-8 | 1,017 | 2.859375 | 3 | [] | no_license | #ifndef TIMELIMIT_H
#define TIMELIMIT_H
#include <QObject>
#include <QTime>
#include <QStringList>
class TimeLimit : public QObject
{
Q_OBJECT
public:
explicit TimeLimit(QObject *parent = 0);
TimeLimit(int timeSeconds, QObject *parent = 0);
TimeLimit(QString timeString, QObject *parent = 0);
TimeLimit(QTime qtime, QObject *parent = 0);
TimeLimit(const TimeLimit &timeLimit, QObject *parent = 0);
int getTimeRemaining() const;
TimeLimit convertToWeeklyTimeRemaining(int daysInWeek = 7);
TimeLimit convertToMonthlyTimeRemaining(int daysInMonth);
void setTimeRemaining(int timeLimit);
bool isTimeOut();
TimeLimit secondsElapsed(int seconds);
int fromString(QString timeString);
QString toString();
QString toString(int timeSeconds);
bool operator<(const TimeLimit &that) const;
TimeLimit & operator=(TimeLimit rhs);
signals:
public slots:
private:
int timeRemaining;
enum SecondMultipliers { DAY = 24*60*60, HOUR = 60*60, MINUTE = 60, SECOND = 1 };
};
#endif // TIMELIMIT_H
| true |
4add26fd2ae1dfa2a017d40b27911a22843b2a70 | C++ | ybouret/upsylon | /src/main/y/geometry/iso2d/coordinate.cpp | UTF-8 | 2,156 | 2.734375 | 3 | [] | no_license | #include "y/geometry/iso2d/coordinate.hpp"
#include "y/type/block/zset.hpp"
namespace upsylon {
namespace geometry {
namespace Iso2D {
Coordinate:: Coordinate(const unit_t I,
const unit_t J,
const short Q) throw() :
i(I), j(J), q(Q)
{
}
Coordinate:: ~Coordinate() throw()
{
_bzset(i);
_bzset(j);
_bzset(q);
}
Coordinate:: Coordinate( const Coordinate &_ ) throw() :
i( _.i ),
j( _.j ),
q( _.q )
{
}
void Coordinate:: __run(hashing::function &H) const throw()
{
H.run_type(i);
H.run_type(j);
H.run_type(q);
}
void Coordinate:: __sto( unit_t *target ) const throw()
{
assert(target);
target[0] = i;
target[1] = j;
target[2] = q;
}
int Coordinate:: Compare(const Coordinate &lhs, const Coordinate &rhs) throw()
{
unit_t L[3], R[3];
lhs.__sto(L);
rhs.__sto(R);
return comparison::increasing_lexicographic(L,R,3);
}
bool operator==(const Coordinate &lhs, const Coordinate &rhs) throw()
{
return (lhs.i==rhs.i) && (lhs.j==rhs.j) && (lhs.q==rhs.q);
}
bool operator!=(const Coordinate &lhs, const Coordinate &rhs) throw()
{
return (lhs.i!=rhs.i) || (lhs.j!=rhs.j) || (lhs.q!=rhs.q);
}
std::ostream & operator<<(std::ostream &os,const Coordinate&c)
{
os << '(' << c.i << ',' << c.j << ':' << c.q << ')';
return os;
}
bool operator<(const Coordinate &lhs, const Coordinate &rhs) throw()
{
return Coordinate::Compare(lhs,rhs) < 0;
}
}
}
}
| true |
52875d6a585559cd0cb76c59e3d8a74a5e66a452 | C++ | wovert/CTutorials | /C++/函数对象/函数对象/main.cpp | UTF-8 | 487 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <string>
using namespace std;
void test01() {
vector<int> v;
v.push_back(8);
v.push_back(2);
v.push_back(3);
v.push_back(5);
v.push_back(1);
v.push_back(3);
sort(v.begin(), v.end(), greater<int>());
for_each(v.begin(), v.end(), [](int val) {cout << val << endl; });
}
// 普通函数进行适配
void myprint(int val) {
cout << val << " ";
}
int main() {
test01();
return 0;
} | true |
e0991c4bf34b52166084f154722f30f72002887a | C++ | TheRolfFR/YellowSubmarine | /Sensors/HumiditySensor.h | UTF-8 | 536 | 2.640625 | 3 | [] | no_license | #ifndef H_HUMI_SENSOR
#define H_HUMI_SENSOR
#include "Sensor.h"
class HumiditySensor: public Sensor<float> {
public:
HumiditySensor(): Sensor<float>(HumiditySensorType) {}
HumiditySensor(std::string name): Sensor<float>(HumiditySensorType, name) {}
HumiditySensor(const HumiditySensor& o) : Sensor<float>(o) {}
HumiditySensor &operator=(HumiditySensor& o) {
Sensor::operator=(o);
return *this;
}
SensorData getData();
float aleaGenVal();
std::string print();
};
#endif | true |
82075292905d1cf36196781d6ad6ddcc4fe729fc | C++ | IritaSee/LearningArchive | /qwerty.cpp | UTF-8 | 342 | 2.65625 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
int main()
{
bool hasil;
int x;
char nama[50];//karena nama
cout<<"nama: "; gets(nama);//karena char
cout<<"nilai: "; cin>>x;
hasil = x > 70;//definisi boolean
if (hasil)
cout<<x<<"\nalhamdulillah "<<nama<<" lulus ";
else
cout<<x<<"\nGUOBLOG!";
getch(;
}
| true |
535643f71bf6a3d041def5f34088f4124079e2ca | C++ | CJHMPower/Fetch_Leetcode | /data/Submission/323 Number of Connected Components in an Undirected Graph/Number of Connected Components in an Undirected Graph_1.cpp | UTF-8 | 1,358 | 2.953125 | 3 | [] | no_license | //-*- coding:utf-8 -*-
// Generated by the Fetch-Leetcode project on the Github
// https://github.com/CJHMPower/Fetch-Leetcode/
// 323 Number of Connected Components in an Undirected Graph
// https://leetcode.com//problems/number-of-connected-components-in-an-undirected-graph/description/
// Fetched at 2018-07-24
// Submitted 3 months ago
// Runtime: 13 ms
// This solution defeats 19.44% cpp solutions
class Solution {
public:
int num_visit = 0;
void DFS(vector<vector<int>>& adjects, vector<bool>& visited, int start) {
visited[start] = true;
num_visit++;
for (int i = 0; i < adjects[start].size(); i++) {
if (visited[adjects[start][i]] != true) {
DFS(adjects, visited, adjects[start][i]);
}
}
}
int countComponents(int n, vector<pair<int, int>>& edges) {
if (n == 0) {
return 0;
}
vector<bool> visited(n, false);
vector<vector<int>> adjects(n, vector<int>());
for (int i = 0; i < edges.size(); i++) {
adjects[edges[i].first].push_back(edges[i].second);
adjects[edges[i].second].push_back(edges[i].first);
}
int ret = 1;
DFS(adjects, visited, 0);
while (num_visit < n) {
ret++;
for (int i = 1; i < n; i++) {
if (visited[i] != true) {
DFS(adjects, visited, i);
break;
}
}
}
return ret;
}
}; | true |
702b588a546717011d93cf39e7ea1e75df179238 | C++ | liuxw7/ipc-pubsub | /lib/Subscriber.h | UTF-8 | 1,248 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
struct msghdr;
namespace ipc_pubsub {
struct IPCMessage {
public:
static std::shared_ptr<IPCMessage> Create(size_t vecLen, const struct msghdr& msgh);
IPCMessage(std::string_view meta, uint8_t* ptr, size_t len, int fd)
: metaData(meta), blobPtr(ptr), blobSize(len), mFd(fd) {}
~IPCMessage();
const std::string_view Contents() const {
return std::string_view(reinterpret_cast<char*>(blobPtr), blobSize);
}
const std::string_view MetaData() const { return std::string_view(metaData); }
private:
// small amount of data informing the meaning of the larger blob
std::string metaData;
// large chunk of memory mapped / shared memory data
uint8_t* blobPtr;
size_t blobSize;
// File Descriptor of Shared Memory
int mFd = -1;
};
class Subscriber {
public:
Subscriber(std::function<void(std::shared_ptr<IPCMessage>)> callback);
~Subscriber();
void WaitForShutdown();
int mFd;
std::thread mReadThread;
std::function<void(std::shared_ptr<IPCMessage>)> mCallback;
int mShutdownFd = -1;
};
} // namespace ipc_pubsub
| true |
5446e62cdcf5d9c461b36c408f6fd73744d45e1d | C++ | smdi17/Laboratornie-raboty | /LR8/LR8/LR8.cpp | UTF-8 | 3,999 | 2.96875 | 3 | [] | no_license | // LR8.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
using namespace std;
void chislo()
{
int number;
cout << "Введите пятизначное число" << endl; //Ввод числа
cin >> number;
for (int i = 0; i < 5; i++) // цикл с выводом числа и его деление без остатка
{
cout << number % 10 << endl;
number = number / 10;
}
cout << endl;
}
void registr() //Изменение регистра буквы
{
char c; //Вводимая буква
cout << "Введите латинскую букву в нижнем регистре:" << endl;
cin >> c;
c -= 32; //Изменение значения буквы по таблице ASCII
cout << "Буква в верхнев регистре: " << c << endl; //Вывод
}
void sredarifm() //Подсчёт среденго арифметического массива
{
const int razmer = 10; //Размер массива
int sum = 0; //Переменная для подсчёта суммы элементов массива
int array[razmer]; //Массив
for (int i = 0; i < razmer; i++) //Заполнение массива случайными числами
array[i] = rand() % 35;
cout << "Массив: " << endl; //Вывод массива
for (int i = 0; i < razmer; i++)
cout << array[i] << ' ';
cout << endl;
for (int i = 0; i < razmer; i++) //Подсчёт суммы всех элементов массива
sum += array[i];
cout << "Среднее арифметическое массива = " << double(sum) / razmer << endl; // Вывод среднего арифметического
}
int main()
{
setlocale(LC_ALL, "RUS");
chislo();
cout << endl;
registr();
cout << endl;
sredarifm();
system("pause");
}
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
| true |
9702df88528908c011c5fa606bc7bdd9e56f2762 | C++ | Zzhc3321/cpp | /模板/Linklist.h | WINDOWS-1252 | 785 | 3.140625 | 3 | [] | no_license | #include "Node.h"
template<class T>
class Linklist{
private:
Node<T>*front,*rear;
Node<T>*prevPtr,*currPtr;
int size;
int position;
Node<T> *newNode(const T&item,Node<T> *ptrNext=NULL);
void freeNode(Node<T>*p);
void copy(const Linklist<T>&L);
public:
Linklist();
Linklist(const Linklist<T> &L);
~Linklist();
Linklist<T> & operator = (const Linklist<T>&L);//ظֵ
int getSize() const;
bool isEmpty()const;
void reset(int pos=0);
void next();
bool endOfList() const;
int currentPosition() const;
void insertFront(const T&item);
void insertRear(const T&item);
void insertAt(const T*item);
void insetAfeter(const T&item);
T deleteFront();
void deleteCurrent();
T& data();
const T&data() const;
void clear;
};
| true |
b9bd4c036372298125ab74acdaa6341dd735b65b | C++ | wonbae/Algorithm | /BOJ/BOJ_10815/BOJ_10815.cpp | UTF-8 | 889 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
// freopen("input.txt", "rt", stdin);
int N, M, lt = 0, rt, mid, num;
cin>>N;
vector<int> v(N);
for(int i = 0; i < N; i++){
cin>>v[i];
}
sort(v.begin(), v.end());
cin>>M;
for(int i = 0; i < M; i++){
lt = 0;
rt = N - 1;
bool ok = false;
cin>>num;
while(lt <= rt){
mid = (lt + rt) / 2;
if(v[mid] == num){
cout<<1<<" ";
ok = true;
break;
}else if(v[mid] > num){
rt = mid - 1;
}else if(v[mid] < num){
lt = mid + 1;
}
}
if(!ok){
cout<<0<<" ";
}
}
return 0;
} | true |
9e40b374fce0eae9d818a0bb3c5a8819f3799d5d | C++ | evanchime/visualStudioProjects | /Projects/chapter_1_tab/chapter_1_tab/chapter_1_tab.cpp | ISO-8859-1 | 5,504 | 2.84375 | 3 | [] | no_license | // chapter_1_tab.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
/*
* Exercise 1-20
* Write a program detab that replaces tabs in the input
* with the proper number of blanks to space to the next tab stop.
* Assume a fixed set of tab stops, say every n columns.
* Should n be a variable or a symbolic parameter?
*/
#include <stdio.h>
#include <stdlib.h>
//#include<string.h>
#include<iostream>
#include<vector>
#include<string>
#include<new>
#include<memory>
#include<bitset>
#include<fstream>
#include<sstream>
#include<map>
#include<set>
//#include"Text_Query.h"
#include<algorithm>
#include<iterator>
#include<exception>
//#include"Sales_data.h"
#include<functional>
using std::cout;
using std::endl;
using namespace std;
#define MAXL 1000
#define TRUE 1
#define FALSE 0
int line(char s[], int lim);
void detab(char src[], char tar[], int Tabwidth, int Tabstart);
/*qsort:sort v[left]...v[right] into increasing order */
void qsort(void * v[], int left, int right, int(*comp)(void *, void *))
{
int i, last;
void swap(void * v[], int, int);
if (left >= right) /* do nothing if array contains */
return; /* fewer than two elements */
swap(v, left, (left + right) / 2);
last = left;
for (i = left + 1; i <= right; i++)
if ((*comp)(v[i], v[left]) < 0)
swap(v, ++last, i);
swap(v, left, last);
qsort(v, left, last, comp);
qsort(v, last + 1, right, comp);
}
void swap(void * v[], int i, int j)
{
void * temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
int main(int argc, char *argv[])
{
/* // ordinary entab version
int i;
int c, col, blanks, numtabs;
col = blanks = 0;
while ((c = getchar()) != EOF) {
if (c == ' ') {
blanks = blanks + 1;
col = col + 1;
}
else {
if (blanks == 1)
putchar(' ');
else if (blanks > 1) {
numtabs = col / TABWIDTH - (col - blanks) / TABWIDTH;
for (i = 0; i < numtabs; ++i)
putchar('\t');
if (numtabs >= 1)
blanks = col - (col / TABWIDTH)*TABWIDTH;
for (i = 0; i < blanks; ++i)
putchar(' ');
}
blanks = 0;
putchar(c);
col = col + 1;
if (c == '\n')
col = 0;
}
}*/
/* // entab version that takes argument from command line
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
# define MAX_TABS 7
int i, j, TABWIDTH;
int c, col, blanks, numtabs, m, n, arg_count, k, Tab_array[MAX_TABS];
col = blanks = m = n = k = 0;
arg_count = argc;
while( *++argv && --arg_count > 0)
{
switch(**argv)
{
case '-':
m = atoi(*argv + 1);
break;
case '+':
n = atoi(*argv + 1);
break;
default:
Tab_array[k++] = atoi(*argv);
break;
}
}
Tab_array[k] = '\0';
k = 0;
argv -= argc; //temp;
TABWIDTH = ((argc > 1) ? (n ? n : Tab_array[k++]) : 8);
while ((c = getchar()) != EOF) {
if (c == ' ') {
blanks = blanks + 1;
col = col + 1;
}
else
{
if (blanks == 1)
putchar(' ');
else if (blanks > 1)
{
int Adjustments = (col / TABWIDTH)*TABWIDTH;
numtabs = col / TABWIDTH - (col - (blanks + m)) / TABWIDTH;
for(j = 0; j < Adjustments - (col - (blanks + m)); ++j)
putchar(' ');
if (numtabs >= 1)
blanks = col - Adjustments;
for (i = 0; i < blanks; ++i)
putchar(' ');
}
blanks = 0;
putchar(c);
col = col + 1;
if (c == '\n')
{
col = 0;
if ((argc > 1) && !n)
{
if (!(TABWIDTH = Tab_array[k++]))
{
printf(" no more tab stops in argument ");
break;
}
}
}
}
}
return EXIT_SUCCESS;
}
*/
/*# define MAX_TABS 7
char s[MAXL];
char tar[MAXL * MAXL];
int m, n, arg_count, k, i, TABWIDTH, Tab_array[MAX_TABS];
m = n = k = 0;
arg_count = argc;
while (*++argv && --arg_count > 0)
{
switch (**argv)
{
case '-':
m = atoi(*argv + 1);
if (!m)
{
printf("invalid column start");
return 0;
}
break;
case '+':
n = atoi(*argv + 1);
if (!n)
{
printf("invalid column stop");
return 0;
}
break;
default:
Tab_array[k++] = atoi(*argv);
break;
}
}
Tab_array[k] = '\0';
k = 0;
argv -= argc;
TABWIDTH = n ? n : (Tab_array[k] ? Tab_array[k++] : 8);
while (line(s, MAXL) > 0 )
{
if ((TABWIDTH * strlen(s)) < strlen(tar))
{
detab(s, tar, TABWIDTH, m);
/*if (argc > 1)
{
if (!*++argv)
{
printf(" no more tab stops in argument ");
break;
}
}*/
/*printf("%s", tar);
if((argc > 1) && !n && !m)
{
if (!(TABWIDTH = Tab_array[k++]))
{
printf(" no more tab stops in argument ");
break;
}
}
}
else
{
printf(" string too large for tab stop ");
}
}*/
char *s[4] = { "aaa", "bbb", "ccc", "ddd"};
qsort((void **)s, 0, 3, (int (*)(void *, void*))strcmp);
for (auto x = begin(s); x != end(s); )
cout << *(x++) << endl;
return EXIT_SUCCESS;
}
int line(char s[], int lim) {
char c;
int i = 0;
while ((c = getchar()) != EOF && c != '\n' && i < lim - 1) {
s[i++] = c;
}
if (c == '\n') {
s[i++] = '\n';
}
s[i] = '\0';
return i;
}
void detab(char src[], char tar[], int Tabwidth, int Tabstart)
{
int i, j, spacew;
//int j = 0;
//int spacew;
char c;
for (i = 0, j = 0; (c = src[i]) != '\0'; i++) {
if (c != '\t') {
tar[j++] = c;
}
else {
spacew = Tabwidth - (j - Tabstart) % Tabwidth;
while (spacew-- > 0) {
tar[j++] = '-';
}
}
}
tar[j] = '\0';
}
| true |
d381301adf00c674935e9a50203a553bc9fc841d | C++ | pablo-jenne/Cpp | /project_CPP/draw.cpp | UTF-8 | 5,494 | 2.796875 | 3 | [] | no_license | #include "draw.h"
bool Draw::getGameover() const
{
return gameover;
}
bool Draw::Snoepje1() const
{
return snoepje1;
}
bool Draw::Snoepje2() const
{
return snoepje2;
}
bool Draw::Snoepje3() const
{
return snoepje3;
}
bool Draw::EERSTE_SNOEPJE() const
{
return eerste_snoepje;
}
void Draw :: setup()
{
gameover = false;
eerste_snoepje = true;
snoepje1 = false;
snoepje2 = false;
snoepje3 = false;
dir = STOP;
x = WIDTH/2; // hier zal de snake starten
y = HEIGHT/2;
fruitx = rand() % WIDTH;
fruity = rand() % HEIGHT;
}
void Draw :: draw()
{
Font::clearScreen();
for(unsigned short i = 0; i<WIDTH+2; i++)
{
cout << "#";
}
cout<<endl;
for(unsigned short i = 0; i<HEIGHT; i++)
{
for(unsigned short j = 0; j<WIDTH; j++)
{
if(j==0)
{
cout<<"#";
}
if(i == y && j == x)
{
cout<<"O";
}
else if(i == fruity&& j == fruitx)
{
if(snoepje1 == true || eerste_snoepje == true)
{
Font::setColor( 0x0A );
cout<<"F";
Font::setColor(0x0F);
}
if(snoepje2 == true)
{
Font::setColor( 0x0B );
cout<<"F";
Font::setColor(0x0F);
}
if(snoepje3 == true)
{
Font::setColor( 0x0E );
cout<<"F";
Font::setColor(0x0F);
}
}
else
{
bool print = false;
for(unsigned short k = 0; k< ntail; k++)
{
if(tailx[k] == j && taily[k] == i)
{
cout << "o";
print = true;
}
}
if(!print)
{
cout<<" ";
}
}
if(j==WIDTH-1)
{
cout<<"#";
}
}
cout<<endl;
}
for(unsigned short i =0; i<HEIGHT+2; i++) // plus 2 doen anders wordt het raster niet goed getekend
{
cout << "#";
}
cout<<endl;
cout<< "Jouw score is:" << score <<endl;
}
void Draw:: input()
{
if(_kbhit())
{
switch(_getch()) // movements
{
case 'f':
dir = LEFT;
break;
case 'h':
dir = RIGHT;
break;
case 't':
dir = UP;
break;
case 'g':
dir = DOWN;
break;
case 'a':
gameover = true;
break;
}
}
}
void Draw:: logic()
{
unsigned short prevx = tailx[0];
unsigned short prevy = taily[0];
unsigned short prev2x, prev2y;
tailx[0] = x;
taily[0] = y;
for(unsigned short i =1; i<ntail; i++) // i op 1 laten beginnen anders wordt de eerste tail niet goed getekend
{
prev2x = tailx[i];
prev2y = taily[i];
tailx[i] = prevx;
taily[i] = prevy;
prevx = prev2x;
prevy = prev2y;
}
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if(x > WIDTH || x < 0 || y > HEIGHT || y < 0 )
{
gameover = true;
}
for(unsigned short i = 0; i < ntail; i++)
{
if(tailx[i] == x && taily[i] == y)
{
gameover = true;
}
}
if(x == fruitx && y == fruity)
{
eerste_snoepje = false;
srand (time(NULL));
unsigned char random_getal = rand() % 3 + 1; // nummer tussen 1 en 3
switch(random_getal) {
case 1:
score = score + 10;
fruitx = rand() % WIDTH;
fruity = rand() % HEIGHT;
ntail++;
snoepje1 = true;
snoepje2 = false;
snoepje3 = false;
case 2:
score = score + 10;
fruitx = rand() % WIDTH;
fruity = rand() % HEIGHT;
ntail--;
snoepje1 = false;
snoepje2 = true;
snoepje3 = false;
case 3:
score = score + 10;
fruitx = rand() % WIDTH;
fruity = rand() % HEIGHT;
ntail = ntail + 2;
snoepje1 = false;
snoepje2 = false;
snoepje3 = true;
}
}
}
| true |
22d2f8299a6b5f82f0240fac80d3c61446e21e61 | C++ | suzyli123/leetcode | /cpp/328. Odd Even Linked List.cpp | UTF-8 | 1,453 | 3.609375 | 4 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode *odd = NULL, *even = NULL, *odd_head = NULL, *even_head = NULL, *temp;
while(head != NULL){
if(head->val%2 == 0){
if(even == NULL){
temp = head;
head = head->next;
temp->next = NULL;
even_head = temp;
even = even_head;
}
else{
even->next = head;
even = even->next;
head = head->next;
even->next = NULL;
}
}
else{
if(odd == NULL){
temp = head;
head = head->next;
temp->next = NULL;
odd_head = temp;
odd = odd_head;
}
else{
odd->next = head;
odd = odd->next;
head = head->next;
odd->next = NULL;
}
}
}
if(odd_head == NULL)
return even_head;
else{
odd->next = even_head;
return odd_head;
}
}
};
| true |
ea3cd0ff3a8b3a4643ed81e1d8c6054d9b25a17f | C++ | HTDPNJ/leiShuZuDeXunLian | /类数组的训练/myArray.h | UTF-8 | 273 | 2.625 | 3 | [] | no_license | #pragma once
#include<iostream>
using namespace std;
class Array {
private:
int m_length;
int *m_space;
public:
Array();
Array(int a);
Array(const Array& obj);
~Array();
public:
void setData(int index,int value);
int getData(int index);
int length();
protected:
}; | true |
df0fa13e5e07c4fe7c0babb5d1047ee79fc1b426 | C++ | HappyRa1n/Sort | /Counting_Sort/counting_sort.cpp | UTF-8 | 525 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void Sort(int* mas, int k, int n) {
int* c = new int[k + 1];
for (int i = 0; i < k + 1; i++)
c[i] = 0;
for (int i = 0; i < n; i++)
c[mas[i]]++;
int tmp = 0;
for (int i = 0; i < k + 1; i++) {
while (c[i] > 0) {
mas[tmp++] = i;
c[i]--;
}
}
delete[] c;
}
int main()
{
int n;
cin >> n;
int* mas = new int[n];
for (int i = 0; i < n; i++)
cin >> mas[i];
int k;//max number;
cin >> k;
Sort(mas, k, n);
for (int i = 0; i < n; i++)
cout << mas[i] << " ";
} | true |
84da41ba9e0de8e0563abb2b4c30c392f133c61e | C++ | cedi/cryptopals | /libcryptopals/src/Hexadecimal.cpp | UTF-8 | 1,092 | 3.140625 | 3 | [] | no_license | #include <stdexcept>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstdint>
#include "Hexadecimal.hpp"
#include "Utils.hpp"
using namespace std;
const string Hexadecimal::table = "0123456789ABCDEF";
string Hexadecimal::encode(const string& input)
{
vector<uint8_t> vec;
for(char c : input)
{
vec.push_back(static_cast<uint8_t>(c));
}
return encode(Utils::strToByteVec(input));
}
string Hexadecimal::encode(const vector<uint8_t>& input)
{
stringstream ss;
ss << hex << setfill('0');
for(size_t i = 0; input.size() > i; ++i)
{
ss << setw(2) << static_cast<unsigned int>(input[i]);
}
return ss.str();
}
vector<uint8_t> Hexadecimal::decode(const string& input)
{
if((input.length() % 2) != 0)
{
throw runtime_error("String is not valid length ...");
}
vector<uint8_t> output;
size_t cnt = input.length() / 2;
for(size_t i = 0; cnt > i; ++i)
{
uint32_t s = 0;
stringstream ss;
ss << hex << input.substr(i * 2, 2);
ss >> s;
output.push_back(static_cast<uint8_t>(s));
}
return output;
}
| true |
3e87a4c08b408e6bfc36a0f85c76dcc250a3702a | C++ | rainlee/itint5 | /13-maxTreePathSum.cpp | GB18030 | 862 | 3.515625 | 4 | [] | no_license | /*
Ķ(벻Ҫڴж)
struct TreeNode {
int val;
vector<TreeNode*> children; //ýĶӽ
};
*/
// rootβ·ֵ
// ¼rootУrootβ֧
int maxTreePathSumRec(TreeNode *root, int &maxp)
{
if (!root)
return 0;
int max1 = 0,max2 = 0; // ¼֧
for (int i = 0; i < root->children.size(); ++i)
{
int tmp = maxTreePathSumRec(root->children[i], maxp);
if (tmp > max1)
{
max2 = max1;
max1 = tmp;
}
else if (tmp > max2)
max2 = tmp;
}
maxp = max(maxp, root->val + max1 + max2);
return root->val + max1;
}
int maxTreePathSum(TreeNode *root) {
int maxp = 0;
maxTreePathSumRec(root, maxp);
return maxp;
} | true |
e91a353787f71188d3f728e384f8202eaaf2bc29 | C++ | samarjeet/cses | /src/rectangleCutting.cpp | UTF-8 | 1,078 | 2.65625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
typedef long long ll;
#define INF 1e7
int main(int argc, char** argv){
int a, b;
std::cin >> a >> b;
/*
// Approch : Greedy algorithm : incorrect
int min, max;
if (a<b){
min = a; max=b;
}
else {
min=b; max=a;
}
int steps=0;
while(min != max){
int a1 = max - min;
if (a1 < min) {
max = min;
min = a1;
}
else {
max = a1;
}
++steps;
}
std::cout << steps << std::endl;
*/
std::vector<std::vector<int>> dp(a+1, std::vector<int>(b+1, 0));
for (int i=1; i <= a; ++i){
for (int j=1; j <= b; ++j){
if (i^j)
dp[i][j] = 1e9;
for (int k=1; k < i; ++k)
dp[i][j] = std::min(dp[i][j], dp[i-k][j] + dp[k][j]+1);
for (int k=1; k < j; ++k)
dp[i][j] = std::min(dp[i][j], dp[i][j-k] + dp[i][k]+1);
}
}
std::cout << dp[a][b] << "\n";
return 0;
} | true |
026878b43d0e0f1149bca8b79371e1988e2248ac | C++ | pjdu/STM32duino_LED_Matrix | /sketch_jan07a_arduino_json_newline_test/mserial.ino | UTF-8 | 1,828 | 2.609375 | 3 | [] | no_license | #include "mserial.h"
/*
* 这个串口以"行"为单位进行处理 即 \n
* 用在stm32上适合,Arduino 未必
*/
char serial_cache[SERIAL_CACHE];//常驻内存,提高性能
byte CRC8( char *data, int len)
{
byte crc = 0x00;
while (len--)
{
byte extract = *data++;
for (byte tempI = 8; tempI; tempI--)
{
byte sum = (crc ^ extract) & 0x01;
crc >>= 1;
if (sum) {
crc ^= 0x8C;
}
extract >>= 1;
}
}
return crc;
}
void init_serial()
{
Serial.begin(BAUDRATE);
Serial.setTimeout(30000); //30 秒
}
#if 0 //实验串口是否是 Serial.read稳定还是 Serial.readByteUtil 稳定,事实是差不多,主要是要做校验
void Serial_process()
{
unsigned char inByte;
if(Serial.available()>0)
{
inByte = Serial.read();
if(inByte != 0x0a)
{
mserial_add_byte(&ms1,inByte);
}
else if(inByte == 0x0a)
{
lisp_return(&ms1);// 先返回CRC较验,此地返回一新行的newlisp代码,可被newlisp的exec截获,然后eval-string,不影响下面json的任何输出
serial_parse_json(ms1.buffer);
reset_mserial(&ms1);
}
}
}
#else
//这是旧的方式,效率不怎么样,出错率太高了
void Serial_process(CONFIG*cfg)
{
int total_read;
String topnt;
if(Serial.available() > 0)
{
total_read = Serial.readBytesUntil('\n',serial_cache,SERIAL_CACHE-1);
total_read = total_read > (SERIAL_CACHE-1)?(SERIAL_CACHE-1):total_read;
serial_cache[total_read] = '\0';
//crc较验在*_parse_*之前,返回结果
topnt = "(setq mcu_ret ";
topnt+=CRC8(serial_cache,total_read);
topnt+= ")";
Serial.println(topnt);
if( serial_parse_json(serial_cache) == -1)
{
serial_parse_eqled(serial_cache,cfg);
}
}
}
#endif
| true |
00670b5dd59114a57583532208b3dfeb539c9e36 | C++ | RodH257/Node.net | /v8/spikes/filetest.cc | UTF-8 | 4,448 | 2.703125 | 3 | [
"MIT"
] | permissive | #include <v8.h>
// atlstr lets us use CString
#include <atlstr.h>
#using <System.Net.dll>
#using <mscorlib.dll>
#using <System.dll>
// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const v8::String::Utf8Value& value) {
return *value ? *value : "<string conversion failed>";
}
using namespace v8;
// .net System namespace - we end up with conflicting String typenames
// using namespace System;
// x is a value that we want to expose to js
int x;
// XGetter/setter are functions wired up as accessors called when accessing
// js global variable `x' - done for testing
Handle<Value> XGetter(Local<String> property,
const AccessorInfo& info) {
return Integer::New(x);
}
void XSetter(Local<String> property, Local<Value> value,
const AccessorInfo& info) {
x = value->Int32Value();
}
/**
* FunctionCallback is wired up to the javascript `puts()' function.
* we want to use this for doing sys.puts() node API call
*/
v8::Handle<v8::Value> FunctionCallback(const v8::Arguments& args) {
// not sure why we would need a handle scope.. the shell.cc example
// does it this way, but it seems to work without it.. probably has
// to do with automatic GC when exiting the function here..
// without it we migh be leaking handles
HandleScope handle_scope;
// convert first arg to cstring
v8::String::Utf8Value str(args[0]);
const char* cstr = ToCString(str);
// use c to print to console
printf( "%s\n", cstr );
/* Use Console.WriteLine() to print
System::String^ text = gcnew System::String( cstr, 0, lstrlen( cstr ) );
System::Console::WriteLine( text );
*/
return v8::Undefined();
}
// create http listener instance
v8::Handle<v8::Value> createServerCallback(const v8::Arguments& args) {
// System::Net::HttpListener^ listener = gcnew System::Net::HttpListener();
System::String^ string = gcnew System::String( "newstring" );
Handle<ObjectTemplate> server_templ = ObjectTemplate::New();
server_templ.SetAccessor(String::New("x"), GetPointX, SetPointX);
server_templ->SetInternalFieldCount(1);
Local<Object> obj = server_templ->NewInstance();
// pin_ptr<System::Net::HttpListener^> p = &listener;
pin_ptr<System::String^> p = &string;
obj->SetInternalField(0, External::New( p ));
return obj;
}
Handle<Value> GetPointX(Local<String> property,
const AccessorInfo &info) {
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
void* ptr = wrap->Value();
int value = static_cast<Point*>(ptr)->x_;
return Integer::New(value);
}
int main(int argc, char* argv[]) {
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// set up the javascript context with the 'x' global object
Handle<ObjectTemplate> global_templ = ObjectTemplate::New();
global_templ->SetAccessor(String::New("x"), XGetter, XSetter);
Handle<FunctionTemplate> putstemplate = FunctionTemplate::New( FunctionCallback );
global_templ->Set(String::New("puts"), putstemplate);
Handle<FunctionTemplate> createservertemplate = FunctionTemplate::New( createServerCallback );
global_templ->Set( String::New("createServer"), putstemplate );
Persistent<Context> context = Context::New(NULL, global_templ);
// Enter the created context for compiling and
// running the hello world script.
Context::Scope context_scope(context);
// read js file in from filesystem....
char* fileArg = argv[1];
System::String^ fileName = gcnew System::String( fileArg, 0, lstrlen(fileArg) );
System::String^ fileContents;
System::IO::StreamReader^ streamReader = gcnew System::IO::StreamReader( fileName );
fileContents = streamReader->ReadToEnd();
streamReader->Close();
// Create a string containing the JavaScript source code.
CString str3( fileContents);
Handle<String> source = String::New( str3 );
// Compile the source code.
Handle<Script> script = Script::Compile(source);
Handle<Script> script2 = Script::Compile(String::New("clientCode();"));
// Run the script to get the result.
Handle<Value> result = script->Run();
Handle<Value> result2 = script2->Run();
// Dispose the persistent context.
context.Dispose();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
System::Console::WriteLine( "CLR Working" );
return 0;
}
| true |
33f02b0c69355823a2e6961268f5feebed34c268 | C++ | WalterGoedecke/ceres | /Walter-togo/projects-togo/tut/EricLee/C++/HW10-Netflix/Library.h | UTF-8 | 702 | 3.015625 | 3 | [] | no_license | /**
* @author E.S.Boese
* @version Fall 2014
* project #2
*/
#ifndef LIBRARY_H
#define LIBRARY_H
#include "User.h"
#include "Book.h"
class Library
{
private:
std::vector<Book> bookList;
std::vector<User> userList;
/*
std::vector<string> authorList;
std::vector<string> titleList;
std::vector<string> idList;
std::vector<string> ratingsList;
*/
public:
//Constructor.
Library(std::string book_list_file, std::string user_list_file);
//Member functions.
void readInBookList(std::string filename);
void readUserFile(std::string filename);
void printUsers();
void printBooks();
void printAverageBookRatings();
};
#endif
| true |
8b5ce21356814a7874de302a8c935cb2ca707c04 | C++ | msatul1305/codechef-beginner-solutions | /removeNonSmallAlphabets.cpp | UTF-8 | 340 | 3.28125 | 3 | [] | no_license | #include<iostream>
using namespace std;
main()
{
string s;
getline(cin,s);
cout<<"original string= "<<s<<" with length= "<<s.size()<<endl;
for(int i=0;i<s.size();i++)
{
if(s[i]<'a'||s[i]>='z')
{
s[i]=NULL;
}
}
cout<<"changed string removing all non small alphabets= "<<s<<" with length= "<<s.size()<<endl;
}
| true |
4555d2d9f8a59b81320e4416ba0adde50f36cad3 | C++ | TaylorClark/PrimeTime | /Base/DynamicBuffer.h | UTF-8 | 2,849 | 3.484375 | 3 | [
"MIT"
] | permissive | //=================================================================================================
/*!
\file IUpdatable.h
Base Library
Updatable Interface Header
\author Taylor Clark
\date May 13, 2006
This header contains the interface definition for the updatable base class.
*/
//=================================================================================================
#pragma once
#ifndef __DynamicBuffer_h
#define __DynamicBuffer_h
#include "Base/Types.h"
#include <malloc.h>
//-------------------------------------------------------------------------------------------------
/*!
\class DynamicBuffer
\brief Represents an object that can store a dynamic amount of data in memory
*/
//-------------------------------------------------------------------------------------------------
class DynamicBuffer
{
private:
/// The number of bytes of data stored in the buffer
uint32 m_ByteOffset;
/// The number of bytes allocated by the buffer
uint32 m_BufferSize;
/// The current offset, within the buffer, of one byte past the last written byte
/// The buffer
uint8* m_pBuffer;
public:
/// The default constructor
DynamicBuffer() : m_ByteOffset( 0 ),
m_BufferSize( 0 ),
m_pBuffer( 0 )
{}
/// The destructor
~DynamicBuffer()
{
Free();
}
// Free the internal data
void Free()
{
if( m_pBuffer )
delete [] m_pBuffer;
m_pBuffer = 0;
m_BufferSize = 0;
m_ByteOffset = 0;
}
/// Write data to the buffer
void Write( void* pData, uint32 numBytes )
{
// If there is no buffer size then allocate the initial buffer
if( !m_pBuffer )
{
uint32 initialSize = numBytes * 4;
m_pBuffer = (uint8*)malloc( (size_t)initialSize );
}
// If the buffer is too small
if( (m_ByteOffset + numBytes) > m_BufferSize )
{
// Calculate the new buffer size
uint32 newBufferSize = m_BufferSize + numBytes + 1024;
// Allocate a new buffer
uint8* pNewBuffer = (uint8*)realloc( m_pBuffer, newBufferSize );
// If the allocation failed
if( !pNewBuffer )
throw( "Failed to allocate buffer, out of memory" );
// Store the new buffer
m_pBuffer = pNewBuffer;
m_BufferSize = newBufferSize;
}
// Write the data
memcpy_s( m_pBuffer + m_ByteOffset, (m_BufferSize - m_ByteOffset), pData, numBytes );
m_ByteOffset += numBytes;
}
/// Get the buffer pointer
void* GetBuffer() { return m_pBuffer; }
/// Get the number of bytes written to the buffer
uint32 GetDataSize() const { return m_ByteOffset; }
/// Release the buffer and allow the caller to manage the memory
void* Release()
{
// Reallocate the memory down to the minimum amount needed
void* pRetVal = realloc( m_pBuffer, m_ByteOffset );
// Clear the internals
m_BufferSize = 0;
m_ByteOffset = 0;
m_pBuffer = 0;
// Return the buffer
return pRetVal;
}
};
#endif // __DynamicBuffer_h | true |
0d63602160049ddf059d1fdb3ea2bfbc67c4bd5b | C++ | dreamer-dead/myxml | /src/myxml.hpp | UTF-8 | 10,691 | 2.703125 | 3 | [] | no_license | #if defined _MSC_VER && _MSC_VER >= 1300
#pragma once
#endif
#if !defined __HDR_MYXML_HPP__
#define __HDR_MYXML_HPP__
/* need for
XML_T macro
myxml::char_t type
*/
#include "config.hpp"
/*
need for
std::basic_string<>
*/
#include <string>
/*
need for
std::pair<>
*/
#include <utility>
/*
need for
std::list<>
*/
#include <list>
namespace myxml
{
/*
forward declaration of classes
*/
class node;
class document;
class element;
class comment;
class attribute;
class text;
class declaration;
class unknown;
typedef std::pair< int, int > position_t;
/*
basic string type for library
*/
typedef std::basic_string< char_t > string_t;
/*
xpath_string typedef
*/
//typedef basic_xpath_string/* < char_t > */ xpath_string;
/*
.base for all classes, contain position info
and some additional user data
.contain virtual destructor
now disabled position info and user data
*/
struct xml_base
{
//position_t pos_;
//void * user_data_;
xml_base()
//: pos_( -1, -1 ), user_data_(NULL) {}
{}
virtual ~xml_base() {}
};
/*
this context describes state for currently parsed document
*/
struct parsing_context
{
position_t pos; /* current parsing pos */
bool skip_whitespace; /* skip white spaces in text elements ? */
parsing_context( int r, int c ) : pos( r, c ), skip_whitespace(false) {}
};
#define VIS_DEF_IMPL {}
//#define VIS_DEF_IMPL = 0;
struct base_visitor
{
virtual void visit( node * ) VIS_DEF_IMPL
virtual void visit( document * ) VIS_DEF_IMPL
virtual void visit( element * ) VIS_DEF_IMPL
virtual void visit( comment * ) VIS_DEF_IMPL
virtual void visit( attribute * ) VIS_DEF_IMPL
virtual void visit( text * ) VIS_DEF_IMPL
virtual void visit( declaration * ) VIS_DEF_IMPL
virtual void visit( unknown * ) VIS_DEF_IMPL
virtual ~base_visitor() = 0 {};
};
#undef VIS_DEF_IMPL
class node : public xml_base
{
public :
enum node_type
{
type_node,
type_document,
type_element,
type_comment,
type_attribute,
type_text,
type_declaration,
type_unknown
};
const string_t& value() const { return this->value_; }
void value( const char_t * val_ ) { this->value_.assign( val_ ); }
void value( const string_t& val_ ) { this->value_ = val_; }
node * parent( void ) { return this->parent_; }
const node * parent( void ) const { return this->parent_; }
node * next( void ) { return this->next_; }
const node * next( void ) const { return this->next_; }
node * prev( void ) { return this->prev_; }
const node * prev( void ) const { return this->prev_; }
node * first_child( void ) { return this->first_child_; }
const node * first_child( void ) const { return this->first_child_; }
node * first_child( const string_t& cond ) { return this->find_next( this->first_child_, cond ); }
node * last_child( void ) { return this->last_child_; }
const node * last_child( void ) const { return this->last_child_; }
document * get_document( void ) { return this->document_; }
const document * get_document( void ) const { return this->document_; }
void append_child( node * n );
void append_before_child( node * n, node * before );
void append_after_child( node * n, node * after );
void delete_child( node * n );
node * find( const string_t& path );
void find( const string_t& path, std::list< node * >& res );
virtual node_type type() = 0;
virtual const char_t * parse( const char_t * str, parsing_context& ctx ) = 0;
virtual void print_out( FILE * ) = 0;
virtual ~node();
template < typename T >
static inline T * cast( node * n )
{
if ( n->type() == T::ntype )
return static_cast< T* >( n );
else
return NULL;
}
virtual void visit( base_visitor * v ) { v->visit( this ); }
protected :
explicit node( const string_t& val_ );
explicit node( document * doc );
node( const string_t& val_, node * parent );
const char_t * document_set_error( const string_t& desc );
void set_parent( node * parent ) { this->parent_ = parent; }
void set_next( node * next ) { this->next_ = next; }
void set_prev( node * prev ) { this->prev_ = prev; }
void set_first_child( node * ch ) { this->first_child_ = ch; }
void set_last_child( node * ch ) { this->last_child_ = ch; }
node * find_next( node * n, const string_t& cond );
node * find_prev( node * n, const string_t& cond );
void correct_tails();
string_t value_;
private :
document * document_;
node
*parent_,
*first_child_,
*last_child_,
*next_,
*prev_;
};
namespace detail
{
template < node::node_type NType >
struct type_mixin : node
{
static const node::node_type ntype = NType;
virtual node_type type() { return ntype; }
explicit type_mixin( const string_t& val_ ) : node(val_) {}
explicit type_mixin( document * doc ) : node(doc) {}
type_mixin( const string_t& val_, node * parent ) : node(val_, parent) {}
};
}
class element : public detail::type_mixin<node::type_element>
{
typedef detail::type_mixin<node::type_element> base_type;
public :
element() : base_type( XML_T("") ), text_( NULL ) {}
explicit element( document * doc ) : base_type( doc ), text_( NULL ) {}
attribute& insert( const attribute& attr );
attribute * first_attribute();
attribute * find_attribute( const string_t& name );
text * get_text() const { return this->text_; }
virtual const char_t * parse( const char_t * /* str */, parsing_context& );
virtual void print_out( FILE * );
protected :
const char_t * read_tag( const char_t * str, int& closed );
const char_t * read_attributes( const char_t * str, parsing_context&, int& closed );
const char_t * read_inner( const char_t * str, parsing_context& );
void append_text( text * text_node );
virtual void visit( base_visitor * v ) { v->visit( this ); }
private :
std::list< attribute > attributes_;
text * text_;
};
class comment : public detail::type_mixin<node::type_comment>
{
typedef detail::type_mixin<node::type_comment> base_type;
virtual void visit( base_visitor * v ) { v->visit( this ); }
public :
comment() : base_type( XML_T("") ) {}
explicit comment( document * doc ) : base_type( doc ) {}
virtual const char_t * parse( const char_t * /* str */, parsing_context& );
virtual void print_out( FILE * );
};
class attribute : public detail::type_mixin<node::type_attribute>
{
friend class element;
typedef detail::type_mixin<node::type_attribute> base_type;
virtual void visit( base_visitor * v ) { v->visit( this ); }
public :
attribute() : base_type( XML_T("") ) {}
explicit attribute( document * doc ) : base_type( doc ) {}
const string_t& name() const { return this->name_; }
virtual const char_t * parse( const char_t * /* str */, parsing_context& );
virtual void print_out( FILE * );
private :
string_t name_;
};
class text : public detail::type_mixin<node::type_text>
{
typedef detail::type_mixin<node::type_text> base_type;
virtual void visit( base_visitor * v ) { v->visit( this ); }
public :
text() : base_type( XML_T("") ) {}
explicit text( document * doc ) : base_type( doc ) {}
virtual const char_t * parse( const char_t * str, parsing_context& );
virtual void print_out( FILE * );
};
class declaration : public detail::type_mixin<node::type_declaration>
{
typedef detail::type_mixin<node::type_declaration> base_type;
virtual void visit( base_visitor * v ) { v->visit( this ); }
public :
declaration() : base_type( XML_T("") ) {}
explicit declaration( document * doc ) : base_type( doc ) {}
const string_t& version() const { return this->version_; }
const string_t& encoding() const { return this->encoding_; }
const string_t& standalone() const { return this->standalone_; }
virtual const char_t * parse( const char_t * /* str */, parsing_context& );
virtual void print_out( FILE * );
private :
string_t version_;
string_t encoding_;
string_t standalone_;
};
class unknown : public detail::type_mixin<node::type_unknown>
{
typedef detail::type_mixin<node::type_unknown> base_type;
virtual void visit( base_visitor * v ) { v->visit( this ); }
public :
unknown() : base_type( XML_T("") ) {}
explicit unknown( document * doc ) : base_type( doc ) {}
virtual const char_t * parse( const char_t * str, parsing_context& );
virtual void print_out( FILE * );
};
class document : public detail::type_mixin<node::type_document>
{
typedef detail::type_mixin<node::type_document> base_type;
public :
#if defined _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4355)
#endif
document()
: base_type(this), skip_spaces_(false)
{ clear_error(); }
explicit document( const string_t& file_name)
: base_type(file_name, this), skip_spaces_(false)
{ clear_error(); }
#if defined _MSC_VER
//# pragma warning(default: 4355)
# pragma warning(pop)
#endif
bool load( const string_t& file_name );
bool load();
bool save();
bool save( const string_t& file_name );
bool load_xml( const string_t& xml );
const string_t& get_error() const { return this->error_desc_; }
bool skip_spaces() const { return this->skip_spaces_; }
void skip_spaces( bool skip ) { this->skip_spaces_ = skip; }
element * create_element() { return this->create< element >(); }
attribute * create_attribute() { return this->create< attribute >(); }
text * create_text() { return this->create< text >(); }
comment * create_comment() { return this->create< comment >(); }
declaration * create_declaration() { return this->create< declaration >(); }
unknown * create_unknown() { return this->create< unknown >(); }
virtual const char_t * parse( const char_t * str, parsing_context& );
virtual void print_out( FILE * );
private :
friend class node;
friend class element;
virtual void visit( base_visitor * v ) { v->visit( this ); }
node * identify( const char_t *str, parsing_context& );
const char_t * set_error( const string_t& desc, int code );
void clear_error();
template < typename T >
inline T * create()
{
return new T( this );
}
private :
string_t error_desc_;
int error_code_;
bool skip_spaces_;
};
}
#endif /* __HDR_MYXML_HPP__ */
| true |
e4f2ae2a8b0260949a4f458c870d119ddb4f209f | C++ | RitchieLab/PLATO | /method_lib/mdrpdt/foldproduction.cpp | UTF-8 | 3,989 | 2.703125 | 3 | [] | no_license | //
// C++ Implementation: sibshipfoldproduction
//
// Description:
//
//
// Author: <>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "foldproduction.h"
#include <iomanip>
#include <sstream>
namespace MdrPDT {
using namespace std;
/**
* @brief performs the production, filling out the data pointed to by data
*/
void FoldProduction::BuildXVFolds(char *data, std::vector<FamilyRecord> famRecords, int totalDSPs, Utility::Random& rnd) {
families = famRecords;
//Time to shuffle the families...kinda. We want them sorted according to
//their DSP count, but we want them mixed up otherwise.So, we need to
//shuffle them first, then do the sort (which doesn't guarantee order
//past the DSP Count)
random_shuffle(families.begin(), families.end(), rnd);
//Now just a sort, using our < operator
sort(families.begin(), families.end());
buckets.clear();
buckets.resize(foldCount);
//This should guarantee that the very first one is considered worth saving
foldScore = totalDSPs;
//A perfect score has exactly the same number in each bucket
perfectScore = totalDSPs % foldCount;
if (perfectScore > 0 && perfectScore < famRecords[famRecords.size() - 1].dspCount)
perfectScore = famRecords[famRecords.size() - 1].dspCount;
//Start the search
BuildXVFolds(0, 0, buckets, rnd);
//Populate the array
std::vector<FoldBucket>::iterator itr = bestArrangement.begin();
std::vector<FoldBucket>::iterator end = bestArrangement.end();
int fold = 0;
while (itr != end) {
itr->WriteFoldToArray(fold++, data);
itr++;
}
}
bool FoldProduction::BuildXVFolds(int fIdx, int bIdx, BucketArray folds, Utility::Random& rnd) {
bool perfectSolutionFound = false;
uint attempts = 0;
assert(fIdx < (int)families.size());
FamilyRecord currRecord = families[fIdx++];
folds[bIdx].AddFamily(currRecord);
sort(folds.begin(), folds.end());
//Check to see if we have exhausted our population;
if (fIdx < (int)families.size()) {
while (!perfectSolutionFound && (int)attempts<foldCount) {
//If we failed last time, there is no point in pushing the same number again
if (attempts == 0 || !(folds[attempts].dspCount == folds[attempts-1].dspCount))
//check to make sure we don't have a perfect solution
perfectSolutionFound = BuildXVFolds(fIdx, attempts, folds, rnd);
attempts++;
}
}
else {
//We have reached a potential solution, so let's evaluate it and see if we should keep it
//The vector should already be sorted in ascending order...so...
unsigned int score = folds[foldCount - 1].dspCount - folds[0].dspCount;
// for (uint i = 1; i< foldCount; i++)
// score += folds[i].dspCount - folds[i-1].dspCount;
//Let's check to see if it's better than a previous score
if ((int)score < foldScore) {
foldScore = score;
bestArrangement = folds;
}
perfectSolutionFound = (int)score <= perfectScore;
}
return perfectSolutionFound;
}
void FoldProduction::GenerateReport(std::ostream& os) {
os<<"\n\nFold Selection Details: \n";
os<<setw(25)<<"Number of Folds: "<<foldCount<<"\n";
os<<setw(25)<<"Perfect Score: "<<perfectScore<<"\n";
os<<setw(25)<<"Final Score: "<<foldScore;
if (foldScore == perfectScore)
os<<" Perfect!\n";
else
os<<"\n";
os<<setw(25)<<"Solutions Observed: "<<solutionsObserved<<"\n";
std::vector<FoldBucket>::iterator itr = bestArrangement.begin();
std::vector<FoldBucket>::iterator end = bestArrangement.end();
int foldID=0;
while (itr != end) {
stringstream ss;
os<<"Fold "<<++foldID<<": Total Families: "<<itr->families.size()<<"\n";
os<<"Individual Contributions: ";
ss<<"Pedigree IDs: ";
for (uint n=0; n<itr->families.size(); n++) {
ss<<" "<<itr->families[n].pedigreeID;
os<<" "<<itr->families[n].dspCount;
}
os<<"\n"<<ss.str()<<"\n";
itr++;
}
os<<endl;
//We used to display the individuals, but I'm not sure how we'd do that right now....
//Maybe a series of X's where the individual was part of the slice?
}
}
| true |
de5a67cd1c298ab7a34d110ef201c418ac3f6e47 | C++ | commondude/edu | /fiit_graphs_algo/2 Stalker/Stalker_error_branch.cpp | UTF-8 | 1,621 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
using namespace std;
ifstream in("input.txt");
ofstream out("output.txt");
int n,k,i,j,roads,start_building,finish_building;
int main(){
if (in.is_open())
{
in>>n;
in>>k;
cout<<n<<"\n";
cout<<k<<"\n";
vector<vector<string>> v(k+1,vector<string>(n,""));
cout<<"Vector size "<<v.size()<<"\n";
for(i=0;i<k;i++){
in>>roads;
cout << "Number of roads " <<roads<< '\n';
for(j=0;j<roads;j++){
in>>start_building;
in>>finish_building;
cout << "Road from " <<start_building<<" to "<<finish_building<< '\n';
start_building-=1;
finish_building-=1;
//Добавляем дуги между вершинами в текущей карте
if(v[i][start_building].find((char)finish_building)==string::npos){
v[i][start_building]+=to_string(finish_building);
// std::cout << "sdf " << to_string(finish_building)<<'\n';
}
if(v[i][finish_building].find((char)start_building)==string::npos){
v[i][finish_building]+=to_string(start_building);
}
}
}
cout << "Input done!" << '\n';
// Вывод графа
for (i=0;i<k;i++){
cout << "Map №" <<i<< '\n';
for(j=0;j<n;j++){
cout << "Vertex №" <<j<<" has roads to "<<v[i][j]<< '\n';
}
}
}
else{
std::cout << "File not found!" << '\n';
}
in.close();
out.close();
}
| true |
f1480fd61769ef46f858ab15cb00021952080332 | C++ | QuRyu/CS232 | /project7/assembler/assembler.cpp | UTF-8 | 1,960 | 2.890625 | 3 | [] | no_license | /**
* Qingbo Liu
* A simple machine code translator
*/
#include <map>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ios>
using namespace std;
map<string, string> tokens = {{"Load", "0000"}, {"Store", "0001"},
{"Jump", "0010"}, {"Branch", "001100"}, {"Call", "001101"},
{"Return", "001110"}, {"Exit", "001111"}, {"Push","0100"},
{"Pop", "0101"}, {"Output", "0110"}, {"Input", "0111"},
{"Add", "1000"}, {"Subtract", "1001"}, {"And", "1010"},
{"Or", "1011"}, {"ExOr", "1100"}, {"Shift", "1101"},
{"Rotate", "1110"}, {"Move", "1111"},
{"Zero", "00"}, {"Overflow", "01"}, {"Neg", "10"}, {"Carry", "11"},
{"RA", "000"}, {"RB", "001"}, {"RC", "010"}, {"RD", "011"},
{"RE", "100"}, {"SP", "101"}, {"PC", "110"}, {"CR", "111"}};
int main(int argc, char **argv) {
if (argc > 2 || argc <= 1)
cout << "please give one argument" << endl;
ifstream fin(argv[1]);
ofstream fout(string(argv[1]) + ".mif");
string s, token;
int line = 0;
fout << "DEPTH = 256;" << endl
<< "WIDTH = 16;" << endl
<< "ADDRESS_RADIX = HEX;" << endl
<< "DATA_RADIX = BIN;" << endl
<< "CONTENT" << endl
<< "BEGIN" << endl;
while (getline(fin, s)) {
istringstream iss(s);
stringstream oss;
oss << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << line++;
oss << " : ";
while (iss >> token) {
if (tokens.find(token) != tokens.end())
oss << tokens[token];
else
oss << token;
}
oss << ";";
fout << oss.str() << endl;
}
if (line < 255) {
stringstream oss;
oss << std::setw(2) << std::hex << std::uppercase <<
"[" << line << "..FF] : 1111111111111111;";
fout << oss.str() << endl;
}
fout << "END" << endl;
}
| true |
f196417192def97e644564f637061ab80cfe4a1f | C++ | Blubcharge/The-Great-Escape | /ZombieArena/ZombieArena/TextureHolder.cpp | UTF-8 | 986 | 3.125 | 3 | [] | no_license | #include "stdafx.h"
#include "TextureHolder.h"
//include assert feature
#include <assert.h>
TextureHolder* TextureHolder::m_s_Instance = nullptr;
TextureHolder::TextureHolder()
{
assert( m_s_Instance == nullptr );
m_s_Instance = this;
}
Texture & TextureHolder::GetTexture(string const & filename)
{
// get a referance to m_Textures using m_s_Instance
auto& m = m_s_Instance->m_Textures;
//auto is the equivalent of map<string,Texture>
//create an iterator to hold a key-value-pair (kvp) and search for the kvp using passed in filename
auto keyValuePair = m.find(filename);
//auto is equivalent of map<string,texture>::iterator
//did we find a match
if (keyValuePair != m.end())
{
//found kvp, return texture which is second of part of kvp
return keyValuePair->second;
}
else
{
//filename not found
//crate a new kvp using filename
auto& texture = m[filename];
//load texture from filename
texture.loadFromFile(filename);
return texture;
}
}
| true |
807c08fafc77fdf8e4133d285679893c491b0cef | C++ | gromchek/glconsole | /CommandArgs.cpp | UTF-8 | 674 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "CommandArgs.h"
#include <sstream>
CommandArgs::CommandArgs( std::string_view command )
{
Tokenize( command );
}
void CommandArgs::Tokenize( std::string_view command )
{
constexpr std::string_view delims( " " );
size_t first = 0;
while( first < command.size() || argc >= MAX_ARGS )
{
const auto second = command.find_first_of( delims, first );
if( first != second )
{
argv[argc].append( command.substr( first, second - first ) );
argc++;
}
if( second == std::string_view::npos || argc >= MAX_ARGS )
{
break;
}
first = second + 1;
}
}
| true |
f592a6e6db96d2c344517e6ce04c9cd3c6964c73 | C++ | dseerutt/7Wonders | /7Wonders/7Wonders/openings.hpp | UTF-8 | 3,297 | 3.203125 | 3 | [] | no_license | #ifndef __OPENINGS_HPP__
#define __OPENINGS_HPP__
#include "allocator.hpp"
#include <vector>
#include "display_node.hpp"
namespace mcts
{
class openings
{
allocator alloc_;
node* root_;
const unsigned int nb_visits_before_expansion_;
void copy(node* src, node* dst, allocator& alloc) const;
template <typename Game>
void expand(Game& game, node* n, uint16_t move, int value);
public:
template <typename Game>
openings(const Game& game, unsigned int nb_visits_before_expansion = 2);
void copy_to(node* root, allocator& alloc) const;
template <typename Game>
void update(Game& game, const std::vector<uint16_t>& moves, int value);
friend std::ostream& operator<<(std::ostream& os, const openings& op);
};
template <typename Game>
openings::openings(const Game& game, unsigned int nb_visits_before_expansion) : nb_visits_before_expansion_(nb_visits_before_expansion)
{
root_ = alloc_.allocate(1);
unsigned int nb_children = game.number_of_moves();
node* children = alloc_.allocate(nb_children);
for (unsigned int i = 0; i < nb_children; ++i)
{
node* child = children + i;
child->get_statistics_ref().count = 1;
child->get_statistics_ref().value = 0;
}
}
template <typename Game>
void openings::expand(Game& game, node* n, uint16_t move, int value)
{
unsigned int count = n->get_statistics().count;
if (count >= nb_visits_before_expansion_)
{
unsigned int nb_children = game.number_of_moves();
node* children = alloc_.allocate(nb_children);
for (unsigned int i = 0; i < nb_children; ++i)
{
node* child = children + i;
child->get_statistics_ref().count = 1;
child->get_statistics_ref().value = 0;
}
n->set_children(children);
n->set_number_of_children(nb_children);
children[move].update(value);
}
}
template <typename Game>
void openings::update(Game& game, const std::vector<uint16_t>& moves, int value)
{
node* pred = nullptr;
node* current = root_;
int k = 0;
while (true)
{
current->update(value);
value = -value;
if (current->is_leaf()) break;
uint16_t m = moves[k++];
game.play(m);
pred = current;
current = current->get_children() + m;
if (current->is_proven())
{
if (current->is_lost()) pred->set_won();
else
{
const uint16_t nb_children = pred->get_number_of_children();
node* const children = pred->get_children();
bool all_won = true;
for (uint16_t i = 0; i < nb_children; ++i)
{
node* child = children + i;
if (!child->is_won())
{
all_won = false;
break;
}
}
if (all_won) pred->set_lost();
}
return;
}
}
if (!game.end_of_game())
{
expand(game, current, moves[k], value);
}
else
{
if (value == 1) current->set_won();
else if (value == -1)
{
current->set_lost();
if (pred != nullptr) pred->set_won();
}
}
}
}
#endif
| true |
deecfb2a908db0ecc04e0c422d2c506138c4308a | C++ | Priyadarshanvijay/Codingblocks-2018 | /week2/ArraysWavePrintRowWise.cc.cpp | UTF-8 | 998 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
void inputArray(int arr[][10],int column,int row)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
cin >> arr[j][i];
}
}
}
void outputArray(int arr[][10],int column,int row)
{
bool startFromTop = true;
bool startFromBottom = false;
for(int i=0;i<row;i++)
{
if(startFromTop)
{
for(int j=0;j<column;j++)
{
cout << arr[j][i] << ", ";
}
startFromTop = !startFromTop;
startFromBottom = !startFromBottom;
}
else if(startFromBottom)
{
for(int j=column-1;j>=0;j--)
{
cout << arr[j][i] << ", ";
}
startFromTop = !startFromTop;
startFromBottom = !startFromBottom;
}
}
cout<<"END"<<endl;
}
int main()
{
int arr[10][10]={ };
int row;
int column;
cin>>row;
cin>>column;
inputArray(arr,column,row);
outputArray(arr,column,row);
return 0;
} | true |
fab3e6609ab526b71d6d8299d725d14e8dd2655e | C++ | mrc-ide/covfefe | /src/base_model.Dispatcher.cpp | UTF-8 | 34,665 | 2.71875 | 3 | [
"MIT"
] | permissive |
#include "base_model.Dispatcher.h"
#include "probability.h"
using namespace std;
//------------------------------------------------
// default constructor for Dispatcher class
Dispatcher::Dispatcher() {
// objects for sampling from probability distributions
sampler_age_stable = Sampler(age_stable, 1000);
sampler_age_death = Sampler(age_death, 1000);
sampler_duration_acute = vector<Sampler>(n_duration_acute);
for (int i=0; i<n_duration_acute; ++i) {
sampler_duration_acute[i] = Sampler(duration_acute[i], 1000);
}
sampler_duration_chronic = vector<Sampler>(n_duration_chronic);
for (int i=0; i<n_duration_chronic; ++i) {
sampler_duration_chronic[i] = Sampler(duration_chronic[i], 1000);
}
// events are enacted using scheduler objects. New events (e.g. infection) are
// generated in the current time step, and future events (e.g. transition to
// blood-stage) are scheduled for future time steps using these objects. This
// avoids the need to loop through every host in every time step, as we only
// need to modify the hosts for which we have scheduled events.
//
// some scheduled events may need to be modified - for example, if a host
// randomly seeks treatment on second innoculation then this will shorten the
// duration of all innoculations, meaning the scheduled recovery time of the
// first innoculation must be changed. For this reason, hosts also contain a
// record of their own event timings, which can be used to locate the
// corresponding records in the scheduler objects.
schedule_death = vector<set<int>>(max_time+1);
schedule_status_update = vector<vector<pair<int, int>>>(max_time+1);
schedule_infective_start_acute = vector<vector<pair<int, int>>>(max_time+1);
schedule_infective_start_chronic = vector<vector<pair<int, int>>>(max_time+1);
schedule_infective_acute_chronic = vector<vector<pair<int, int>>>(max_time+1);
schedule_infective_stop_acute = vector<vector<pair<int, int>>>(max_time+1);
schedule_infective_stop_chronic = vector<vector<pair<int, int>>>(max_time+1);
// counts of host types
H_total = sum(H_vec);
H = H_vec;
Sh = H;
Lh = vector<int>(n_demes);
Ah = vector<int>(n_demes);
Ch = vector<int>(n_demes);
// other quantities to keep track of
EIR = vector<double>(n_demes);
// initialise single population of human hosts over all demes. This is
// preferable to using separate vectors of hosts for each deme, as this would
// mean moving hosts around due to migration. With a single static population
// we can simply change the "deme" attribute of a host to represent migration
hosts = vector<Host>(H_total);
// for each deme, store the integer index of all hosts in that deme
host_vec = vector<vector<int>>(n_demes);
host_infective_vec = vector<vector<int>>(n_demes);
int tmp1 = 0;
for (int k=0; k<n_demes; ++k) {
host_vec[k] = seq_int(tmp1, tmp1+H[k]-1);
tmp1 += H[k];
}
// initialise hosts
next_host_ID = 0;
for (int k=0; k<n_demes; ++k) {
for (int i=0; i<H[k]; i++) {
int this_host = host_vec[k][i];
// draw age from demography distribution
int age_years = sampler_age_stable.draw() - 1;
int extra_days = sample2(1, 365);
int age_days = age_years*365 + extra_days;
// draw duration of life from demography distribution looking forward from
// current age. This is tricky, as we must account for the fact that if we
// are already part way into an age group we have a reduced probability of
// dying within that age group.
int life_days = 0;
double prop_year_remaining = 1 - extra_days/365.0;
double prob_die_this_year = life_table[age_years]*prop_year_remaining;
if (rbernoulli1(prob_die_this_year) || age_years == (n_age-1)) {
life_days = age_years*365 + sample2(extra_days, 365);
} else {
for (int i=(age_years+1); i<n_age; ++i) {
if (rbernoulli1(life_table[i])) {
life_days = i*365 + sample2(1, 365);
break;
}
}
}
// convert to final birth and death days
int birth_day = -age_days;
int death_day = life_days - age_days;
if (death_day == 0) { // in the unlikely even that due to die on day zero, delay death by one day
death_day++;
}
// initialise host
hosts[this_host] = Host(max_innoculations);
hosts[this_host].reset(next_host_ID++, k, birth_day, death_day);
// schedule death
if (death_day <= max_time) {
schedule_death[death_day].insert(this_host);
}
}
}
// seeding infections are de novo, and do not stem from a mosquito. Hence we
// need a "null" mosquito to carry out this infection. This null mosquito will
// be recorded in the infection history using -1 values
Mosquito null_mosquito;
// seed initial infections
for (int k=0; k<n_demes; ++k) {
reshuffle(host_vec[k]);
for (int i=0; i<seed_infections[k]; i++) {
int this_host = host_vec[k][i];
new_infection(this_host, null_mosquito, 0);
// update prob_infection_index
if (hosts[this_host].prob_infection_index < (n_prob_infection-1)) {
hosts[this_host].prob_infection_index++;
}
}
}
// initialise population of mosquitoes in all demes. An infective mosquito
// consists of three values: 1) the ID of the host that infected it, 2) the
// number of observable infections in that host at the time of biting, 3) the
// time the mosquito became infected by that host. If the infective mosquito
// ever bites a new host and passes on the infection, these values will be
// written to the infection history record, thereby providing a link between
// the original host and the newly infected host.
//
// typically a large number of mosquitoes become infected each time step, but
// most of them die before making it through the lag phase (the extrinsic
// incubation period). To avoid creating a large number of infective
// mosquitoes that die before they could pass on infection, we instead draw
// the number of infective mosquitoes that die at each day of the lag phase,
// and only mosquitoes that make it all the way through without dying are
// instantiated. The mosquitoes that die in the lag phase must re-enter the
// population of susceptible mosquitoes on their day of death (i.e. we assume
// constant mosquito population size). Ev_death stores the number of deaths of
// infective mosquitoes at each day of the lag phase going forward until day
// v. These deaths will be added back into the susceptible pool on that day.
// Ev_mosq stores the full details of infective mosquitoes that are due to
// emerge from the lag phase at each day going forward. These infective
// mosquitoes will be added to Iv_mosq on that day. Both Ev_death and Ev_mosq
// are implemented as ring-buffers, meaning they wrap around. ringtime stores
// the current index of the ring-buffer, which wraps back round to 0 once it
// hits v days. Ev_death, Ev_mosq and Iv_mosq are duplicated over all demes.
// The same ringtime is used for all demes.
Ev_death = vector<vector<int>>(n_demes, vector<int>(v));
Ev_mosq = vector<vector<vector<Mosquito>>>(n_demes, vector<vector<Mosquito>>(v));
Iv_mosq = vector<vector<Mosquito>>(n_demes);
ringtime = 0;
// initialise counts of mosquito types
Sv = M_vec;
Lv = vector<int>(n_demes);
Iv = vector<int>(n_demes);
// objects for storing daily counts etc.
if (output_daily_counts) {
H_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
Sh_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
Lh_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
Ah_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
Ch_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
Sv_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
Lv_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
Iv_store = vector<vector<int>>(n_demes, vector<int>(max_time+1));
EIR_store = vector<vector<double>>(n_demes, vector<double>(max_time+1));
// counts at time 0
for (int k=0; k<n_demes; ++k) {
H_store[k][0] = H[k];
Sh_store[k][0] = Sh[k];
Lh_store[k][0] = Lh[k];
Sv_store[k][0] = Sv[k];
}
}
// initialise objects for storing age distributions
if (output_age_distributions) {
vector<vector<vector<int>>> tmp_mat_int = vector<vector<vector<int>>>(n_demes, vector<vector<int>>(n_output_age_times, vector<int>(n_age)));
vector<vector<vector<double>>> tmp_mat_double = vector<vector<vector<double>>>(n_demes, vector<vector<double>>(n_output_age_times, vector<double>(n_age)));
H_age_store = tmp_mat_int;
Sh_age_store = tmp_mat_int;
Lh_age_store = tmp_mat_int;
Ah_age_store = tmp_mat_int;
Ch_age_store = tmp_mat_int;
inc_Lh_age_store = tmp_mat_double;
inc_Ah_age_store = tmp_mat_double;
}
// misc
prob_h_infectious_bite = 0;
}
//------------------------------------------------
// human new infection
void Dispatcher::new_infection(int this_host, Mosquito &mosq, int t) {
// update cumulative innoculations, irrespective of whether this innoculation
// passes the next series of checks
hosts[this_host].cumulative_n_innoculations++;
// get next free innoculation slot. If none free then return without creating
// new innoculation
int this_slot = 0;
for (int i=0; i<max_innoculations; ++i) {
if (!hosts[this_host].innoc_active[i]) {
break;
}
this_slot++;
}
if (this_slot == max_innoculations) {
return;
}
// update deme counts
int this_deme = hosts[this_host].deme;
if (hosts[this_host].get_n_asexual() == 0) {
Sh[this_deme]--;
}
if (hosts[this_host].n_latent == 0) {
Lh[this_deme]++;
}
// update host counts
hosts[this_host].n_latent++;
// add new innoculation and reset other categories
hosts[this_host].innoc_active[this_slot] = true;
hosts[this_host].innoc_status[this_slot] = Latent;
hosts[this_host].innoc_status_prev_update_time[this_slot] = 0;
hosts[this_host].innoc_status_next_update_time[this_slot] = t+u;
hosts[this_host].innoc_infective_start_acute[this_slot] = 0;
hosts[this_host].innoc_infective_start_chronic[this_slot] = 0;
hosts[this_host].innoc_infective_acute_chronic[this_slot] = 0;
hosts[this_host].innoc_infective_stop_acute[this_slot] = 0;
hosts[this_host].innoc_infective_stop_chronic[this_slot] = 0;
// schedule status update
if (t+u <= max_time) {
schedule_status_update[t+u].emplace_back(this_host, this_slot);
}
// get ID of this infection
//int infection_ID = hosts[host_index].cumulative_n_innoculations;
// add to infection history
//if (output_infection_history) {
//vector<int> tmp = {host.ID, host.deme, infection_ID, mosq.host_ID, mosq.host_infections, mosq.infection_time};
//push_back_multiple(history_infection, tmp);
//}
}
//------------------------------------------------
// latent transition to acute infection
void Dispatcher::latent_acute(int this_host, int this_slot, int t) {
// get host properties
int this_deme = hosts[this_host].deme;
int this_death_day = hosts[this_host].death_day;
// update status
hosts[this_host].innoc_status[this_slot] = Acute;
// update status update time
int duration = sampler_duration_acute[hosts[this_host].duration_acute_index].draw() + 1;
hosts[this_host].innoc_status_prev_update_time[this_slot] = hosts[this_host].innoc_status_next_update_time[this_slot];
hosts[this_host].innoc_status_next_update_time[this_slot] = t + duration;
// update duration_acute_index
if (hosts[this_host].duration_acute_index < (n_duration_acute-1)) {
hosts[this_host].duration_acute_index++;
}
// update infectivity_acute_index
if (hosts[this_host].infectivity_acute_index < (n_infectivity_acute-1)) {
hosts[this_host].infectivity_acute_index++;
}
// schedule status update
if (t+duration <= max_time && t+duration < this_death_day) {
schedule_status_update[t+duration].emplace_back(this_host, this_slot);
}
// update infective status
hosts[this_host].innoc_infective_start_acute[this_slot] = t+g;
// schedule infective update
if (t+g <= max_time && t+g < this_death_day) {
schedule_infective_start_acute[t+g].emplace_back(this_host, this_slot);
}
// update host counts
hosts[this_host].n_latent--;
hosts[this_host].n_acute++;
// update deme counts
if (hosts[this_host].n_latent == 0) {
Lh[this_deme]--;
}
if (hosts[this_host].n_acute == 1) {
Ah[this_deme]++;
}
}
//------------------------------------------------
// latent transition to chronic infection
void Dispatcher::latent_chronic(int this_host, int this_slot, int t) {
// get host properties
int this_deme = hosts[this_host].deme;
int this_death_day = hosts[this_host].death_day;
// update status
hosts[this_host].innoc_status[this_slot] = Chronic;
// update status update time
int duration = sampler_duration_chronic[hosts[this_host].duration_chronic_index].draw() + 1;
hosts[this_host].innoc_status_prev_update_time[this_slot] = hosts[this_host].innoc_status_next_update_time[this_slot];
hosts[this_host].innoc_status_next_update_time[this_slot] = t + duration;
// update duration_chronic_index
if (hosts[this_host].duration_chronic_index < (n_duration_chronic-1)) {
hosts[this_host].duration_chronic_index++;
}
// update infectivity_chronic_index
if (hosts[this_host].infectivity_chronic_index < (n_infectivity_chronic-1)) {
hosts[this_host].infectivity_chronic_index++;
}
// schedule status update
if (t+duration <= max_time && t+duration < this_death_day) {
schedule_status_update[t+duration].emplace_back(this_host, this_slot);
}
// update infective status
hosts[this_host].innoc_infective_start_chronic[this_slot] = t+g;
// schedule infective update
if (t+g <= max_time && t+g < this_death_day) {
schedule_infective_start_chronic[t+g].emplace_back(this_host, this_slot);
}
// update host counts
hosts[this_host].n_latent--;
hosts[this_host].n_chronic++;
// update deme counts
if (hosts[this_host].n_latent == 0) {
Lh[this_deme]--;
}
if (hosts[this_host].n_chronic == 1) {
Ch[this_deme]++;
}
}
//------------------------------------------------
// acute transition to chronic infection
void Dispatcher::acute_chronic(int this_host, int this_slot, int t) {
// get host properties
int this_deme = hosts[this_host].deme;
int this_death_day = hosts[this_host].death_day;
// update status
hosts[this_host].innoc_status[this_slot] = Chronic;
// update status update time
int duration = sampler_duration_chronic[hosts[this_host].duration_chronic_index].draw() + 1;
hosts[this_host].innoc_status_prev_update_time[this_slot] = hosts[this_host].innoc_status_next_update_time[this_slot];
hosts[this_host].innoc_status_next_update_time[this_slot] = t + duration;
// update duration_chronic_index
if (hosts[this_host].duration_chronic_index < (n_duration_chronic-1)) {
hosts[this_host].duration_chronic_index++;
}
// schedule status update
if (t+duration <= max_time && t+duration < this_death_day) {
schedule_status_update[t+duration].emplace_back(this_host, this_slot);
}
// update infective status
hosts[this_host].innoc_infective_acute_chronic[this_slot] = t+g;
// schedule infective update
if (t+g <= max_time && t+g < this_death_day) {
schedule_infective_acute_chronic[t+g].emplace_back(this_host, this_slot);
}
// update host counts
hosts[this_host].n_acute--;
hosts[this_host].n_chronic++;
// update deme counts
if (hosts[this_host].n_acute == 0) {
Ah[this_deme]--;
}
if (hosts[this_host].n_chronic == 1) {
Ch[this_deme]++;
}
}
//------------------------------------------------
// acute transition to recovery
void Dispatcher::acute_recover(int this_host, int this_slot, int t) {
// get host properties
int this_deme = hosts[this_host].deme;
int this_death_day = hosts[this_host].death_day;
// update status
hosts[this_host].innoc_status[this_slot] = Inactive;
// update status update time (no more updates)
hosts[this_host].innoc_status_prev_update_time[this_slot] = hosts[this_host].innoc_status_next_update_time[this_slot];
hosts[this_host].innoc_status_next_update_time[this_slot] = 0;
// update infective status
hosts[this_host].innoc_infective_stop_acute[this_slot] = t+g;
// schedule infective update
if (t+g <= max_time && t+g < this_death_day) {
schedule_infective_stop_acute[t+g].emplace_back(this_host, this_slot);
}
// update host counts
hosts[this_host].n_acute--;
// update deme counts
if (hosts[this_host].get_n_asexual() == 0) {
Sh[this_deme]++;
}
if (hosts[this_host].n_acute == 0) {
Ah[this_deme]--;
}
}
//------------------------------------------------
// chronic transition to recovery
void Dispatcher::chronic_recover(int this_host, int this_slot, int t) {
// get host properties
int this_deme = hosts[this_host].deme;
int this_death_day = hosts[this_host].death_day;
// update status
hosts[this_host].innoc_status[this_slot] = Inactive;
// update status update time (no more updates)
hosts[this_host].innoc_status_prev_update_time[this_slot] = hosts[this_host].innoc_status_next_update_time[this_slot];
hosts[this_host].innoc_status_next_update_time[this_slot] = 0;
// update infective status
hosts[this_host].innoc_infective_stop_chronic[this_slot] = t+g;
// schedule infective update
if (t+g <= max_time && t+g < this_death_day) {
schedule_infective_stop_chronic[t+g].emplace_back(this_host, this_slot);
}
// update host counts
hosts[this_host].n_chronic--;
// update deme counts
if (hosts[this_host].get_n_asexual() == 0) {
Sh[this_deme]++;
}
if (hosts[this_host].n_chronic == 0) {
Ch[this_deme]--;
}
}
//------------------------------------------------
// update age incidence vectors
void Dispatcher::update_age_incidence(int this_host, int this_deme, int output_age_time_index, int t) {
// get host properties
int age_days = t - hosts[this_host].birth_day;
int age_years = floor(age_days/365.0);
double this_prob_infection = prob_infection[hosts[this_host].prob_infection_index];
double this_prob_acute = prob_acute[hosts[this_host].prob_acute_index];
// update raw number of hosts
H_age_store[this_deme][output_age_time_index][age_years]++;
// if host susceptible
if (hosts[this_host].get_n_innoculations() == 0) {
// update incidence of infection
inc_Lh_age_store[this_deme][output_age_time_index][age_years] += prob_h_infectious_bite*this_prob_infection;
// update incidence of acute disease
inc_Ah_age_store[this_deme][output_age_time_index][age_years] += prob_h_infectious_bite*this_prob_infection*this_prob_acute;
}
}
//------------------------------------------------
// run simulation
void Dispatcher::simulate() {
//-------- TODO - MIGRATION --------
// loop through daily time steps
int output_age_time_index = 0;
for (int t=1; t<=max_time; t++) {
// loop through demes
for (int k=0; k<n_demes; ++k) {
//-------- MOSQUITO EVENTS --------
// update ring buffer index
ringtime = (ringtime == v-1) ? 0 : ringtime+1;
// move Ev into Iv
if (Ev_mosq[k][ringtime].size() > 0) {
int delta_Ev = int(Ev_mosq[k][ringtime].size());
Lv[k] -= delta_Ev;
Iv[k] += delta_Ev;
push_back_multiple(Iv_mosq[k], Ev_mosq[k][ringtime]);
Ev_mosq[k][ringtime].clear();
}
// deaths in Iv
int death_Iv = rbinom1(int(Iv_mosq[k].size()), prob_v_death);
for (int i=0; i<death_Iv; i++) {
int rnd1 = sample2(0, int(Iv_mosq[k].size())-1);
quick_erase(Iv_mosq[k], rnd1);
}
// draw number of new infections
double rate_v_bite_infective = a*host_infective_vec[k].size()/double(H[k]); // rate of mosquito biting infective hosts
double prob_v_bite_infective_or_death = 1 - exp(-(rate_v_bite_infective + mu)); // probability of mosquito biting infective host or dying in Sv state (competing hazards)
double prob_v_bite_infective = rate_v_bite_infective/(rate_v_bite_infective + mu); // relative probability of mosquito biting infective host vs. dying
int v_bite_infective_or_death = rbinom1(Sv[k], prob_v_bite_infective_or_death); // number of mosquito biting infective hosts or dying in Sv state
int v_bite_infective = rbinom1(v_bite_infective_or_death, prob_v_bite_infective); // number of mosquito biting infective hosts
// update counts with Lv and Iv deaths. Once lag stage deaths have been
// moved into Sv, reset this entry
Sv[k] += Ev_death[k][ringtime] + death_Iv;
Lv[k] -= Ev_death[k][ringtime];
Iv[k] -= death_Iv;
Ev_death[k][ringtime] = 0;
// loop through bites on infective hosts
for (int i=0; i<v_bite_infective; ++i) {
// choose host at random
int rnd1 = sample2(0, host_infective_vec[k].size()-1);
int this_host = host_infective_vec[k][rnd1];
// determine whether infectious bite is successful
bool host_acute = (hosts[this_host].n_acute > 0);
double prob_infective = 0;
if (host_acute) {
prob_infective = infectivity_acute[hosts[this_host].infectivity_acute_index];
} else {
prob_infective = infectivity_chronic[hosts[this_host].infectivity_chronic_index];
}
if (rbernoulli1(prob_infective)) {
// update Sv and Lv
Sv[k]--;
Lv[k]++;
// the majority of new mosquito infections will die in lag phase.
// Schedule these deaths to move back into Sv in future steps.
// Otherwise add to Ev_mosq
int v_time_death = rgeom1(prob_v_death) + 1;
if (v_time_death <= v) {
Ev_death[k][(ringtime+v_time_death) % v]++;
} else {
int this_n = 1; // TODO //hosts_infective[rnd1].n_bloodstage + hosts_infective[rnd1].n_infective;
Ev_mosq[k][ringtime].emplace_back(this_host, this_n, t);
}
}
}
//-------- NEW HUMAN EVENTS AND STORE INCIDENCE --------
// get number of new infectious bites on humans
EIR[k] = a*Iv_mosq[k].size()/double(H[k]);
prob_h_infectious_bite = 1 - exp(-EIR[k]); // probability of new infectious bite per host
int h_infectious_bite = rbinom1(H[k], prob_h_infectious_bite); // total number of new infectious bites
// update complete age distributions of incidence
if (output_age_distributions) {
if (output_age_times[output_age_time_index] == t) {
for (int i=0; i<H[k]; ++i) {
int this_host = host_vec[k][i];
update_age_incidence(this_host, k, output_age_time_index, t);
}
}
}
// apply new infectious bites
for (int i=0; i<h_infectious_bite; i++) {
// choose host at random
int rnd1 = sample2(0, H[k]-1);
int this_host = host_vec[k][rnd1];
// determine whether infectious bite is successful
double host_prob_infection = prob_infection[hosts[this_host].prob_infection_index];
if (rbernoulli1(host_prob_infection)) {
// choose mosquito at random and carry out infection
int rnd2 = sample2(0, int(Iv_mosq[k].size())-1);
new_infection(this_host, Iv_mosq[k][rnd2], t);
}
// update b_index irrespective of whether infection successful
if (hosts[this_host].prob_infection_index < (n_prob_infection-1)) {
hosts[this_host].prob_infection_index++;
}
}
} // end loop through demes
//-------- SCHEDULED HUMAN EVENTS --------
// scheduled deaths
for (auto it = schedule_death[t].begin(); it != schedule_death[t].end(); ++it) {
int this_host = *it;
int this_home_deme = hosts[this_host].deme;
int this_deme = hosts[this_host].deme;
// update deme counts
if (hosts[this_host].get_n_asexual() > 0) {
Sh[this_deme]++;
}
if (hosts[this_host].n_latent > 0) {
Lh[this_deme]--;
}
if (hosts[this_host].n_acute > 0) {
Ah[this_deme]--;
}
if (hosts[this_host].n_chronic > 0) {
Ch[this_deme]--;
}
// drop from infective list if necessary
if (hosts[this_host].get_n_infective() > 0) {
host_infective_vec[this_deme].erase(remove(host_infective_vec[this_deme].begin(), host_infective_vec[this_deme].end(), this_host));
}
// draw life duration from demography distribution
int life_years = sampler_age_death.draw() - 1;
int life_days = life_years*365 + sample2(1, 365);
int death_day = t + life_days;
hosts[this_host].reset(next_host_ID++, this_home_deme, t, death_day);
// schedule new death
if (death_day <= max_time) {
schedule_death[death_day].insert(this_host);
}
}
// scheduled status updates
for (auto it = schedule_status_update[t].begin(); it != schedule_status_update[t].end(); ++it) {
int this_host = it->first;
int this_slot = it->second;
// switch depending on current status
switch (hosts[this_host].innoc_status[this_slot]) {
// latent become acute or chronic
case Latent: {
// draw whether becomes acute or chronic
double host_prob_acute = prob_acute[hosts[this_host].prob_acute_index];
bool become_acute = rbernoulli1(host_prob_acute);
// update prob_acute_index
if (hosts[this_host].prob_acute_index < (n_prob_acute-1)) {
hosts[this_host].prob_acute_index++;
}
// apply transition
if (become_acute) {
latent_acute(this_host, this_slot, t);
} else {
latent_chronic(this_host, this_slot, t);
}
break;
}
// acute phase become chronic or recover
case Acute: {
// draw whether recovers or becomes chronic
bool become_chronic = rbernoulli1(prob_AC);
// split method between chronic disease and recovery
if (become_chronic) {
acute_chronic(this_host, this_slot, t);
} else {
acute_recover(this_host, this_slot, t);
}
break;
}
// chronic recover
case Chronic: {
chronic_recover(this_host, this_slot, t);
break;
}
default:
break;
} // end switch
} // end status updates
// evaluate new acute infective
for (auto it = schedule_infective_start_acute[t].begin(); it != schedule_infective_start_acute[t].end(); ++it) {
int this_host = it->first;
int this_deme = hosts[this_host].deme;
// update counts
hosts[this_host].n_infective_acute++;
// if newly infective then add to infectives list
if (hosts[this_host].get_n_infective() == 1) {
host_infective_vec[this_deme].push_back(this_host);
}
}
// evaluate new chronic infective
for (auto it = schedule_infective_start_chronic[t].begin(); it != schedule_infective_start_chronic[t].end(); ++it) {
int this_host = it->first;
int this_deme = hosts[this_host].deme;
// update counts
hosts[this_host].n_infective_chronic++;
// if newly infective then add to infectives list
if (hosts[this_host].get_n_infective() == 1) {
host_infective_vec[this_deme].push_back(this_host);
}
}
// evaluate acute infective become chronic
for (auto it = schedule_infective_acute_chronic[t].begin(); it != schedule_infective_acute_chronic[t].end(); ++it) {
int this_host = it->first;
// update counts
hosts[this_host].n_infective_acute--;
hosts[this_host].n_infective_chronic++;
}
// evaluate recovery of acute infective
for (auto it = schedule_infective_stop_acute[t].begin(); it != schedule_infective_stop_acute[t].end(); ++it) {
int this_host = it->first;
int this_slot = it->second;
int this_deme = hosts[this_host].deme;
// update counts
hosts[this_host].n_infective_acute--;
// re-activate this slot
hosts[this_host].innoc_active[this_slot] = false;
// if no longer infective then drop from infectives list
if (hosts[this_host].get_n_infective() == 0) {
host_infective_vec[this_deme].erase(remove(host_infective_vec[this_deme].begin(), host_infective_vec[this_deme].end(), this_host));
}
}
// evaluate recovery of chronic infective
for (auto it = schedule_infective_stop_chronic[t].begin(); it != schedule_infective_stop_chronic[t].end(); ++it) {
int this_host = it->first;
int this_slot = it->second;
int this_deme = hosts[this_host].deme;
// update counts
hosts[this_host].n_infective_chronic--;
// re-activate this slot
hosts[this_host].innoc_active[this_slot] = false;
// if no longer infective then drop from infectives list
if (hosts[this_host].get_n_infective() == 0) {
host_infective_vec[this_deme].erase(remove(host_infective_vec[this_deme].begin(), host_infective_vec[this_deme].end(), this_host));
}
}
//-------- STORE RESULTS --------
// store daily counts etc.
if (output_daily_counts) {
for (int k=0; k<n_demes; ++k) {
H_store[k][t] = H[k];
Sh_store[k][t] = Sh[k];
Lh_store[k][t] = Lh[k];
Ah_store[k][t] = Ah[k];
Ch_store[k][t] = Ch[k];
Sv_store[k][t] = Sv[k];
Lv_store[k][t] = Lv[k];
Iv_store[k][t] = Iv[k];
EIR_store[k][t] = EIR[k];
}
}
// update complete age distributions
if (output_age_distributions) {
if (output_age_times[output_age_time_index] == t) {
for (int k=0; k<n_demes; ++k) {
// loop through all hosts
for (int i=0; i<H[k]; ++i) {
int this_host = host_vec[k][i];
int age_days = t - hosts[this_host].birth_day;
int age_years = floor(age_days/365.0);
// update susceptible prevalence
if (hosts[this_host].get_n_innoculations() == 0) {
Sh_age_store[k][output_age_time_index][age_years]++;
}
// update latent prevalence
if (hosts[this_host].n_latent > 0) {
Lh_age_store[k][output_age_time_index][age_years]++;
}
// update acute prevalence
if (hosts[this_host].n_acute > 0) {
Ah_age_store[k][output_age_time_index][age_years]++;
}
// update chronic prevalence
if (hosts[this_host].n_chronic > 0) {
Ch_age_store[k][output_age_time_index][age_years]++;
}
}
// divide incidence by number of hosts per age bin
for (int i=0; i<n_age; ++i) {
inc_Lh_age_store[k][output_age_time_index][i] /= H_age_store[k][output_age_time_index][i];
inc_Ah_age_store[k][output_age_time_index][i] /= H_age_store[k][output_age_time_index][i];
}
}
// update output_age_time_index
if (output_age_time_index < (output_age_times.size()-1)) {
output_age_time_index++;
}
}
}
} // end time loop
}
/*
//------------------------------------------------
// carry out migration
void Dispatcher::migrate() {
// schedule hosts to move from deme k1 to deme k2
for (int k1=0; k1<demes; k1++) {
for (int k2=0; k2<demes; k2++) {
if (k1==k2 || delta_mig[k1][k2]==0) {
continue;
}
// loop through all migration events
for (int i=0; i<delta_mig[k1][k2]; i++) {
// calculate probability migration event is in non-infective vs. infective host
int n_noninf = hosts_noninfective[k1].size();
int n_inf = hosts_infective[k1].size();
double prob_h_migration_noninf = n_noninf/double(n_noninf+n_inf); // proportion of migrations in non-infetive hosts
// migration in either non-infective or infective
int host_ID;
if (rbernoulli1(prob_h_migration_noninf)) { // schedule non-infective to move
int rnd1 = sample2(0, hosts_noninfective[k1].size()-1);
host_ID = hosts_noninfective[k1][rnd1];
mig_noninf_hosts[k1][k2].push_back(host_ID);
hosts_noninfective[k1].erase(hosts_noninfective[k1].begin()+rnd1);
} else { // schedule infective to move
int rnd1 = sample2(0, hosts_infective[k1].size()-1);
host_ID = hosts_infective[k1][rnd1];
mig_inf_hosts[k1][k2].push_back(host_ID);
hosts_infective[k1].erase(hosts_infective[k1].begin()+rnd1);
}
// if host infected then add migration event to infection history
if (output_infection_history) {
int nb = hosts[host_ID].n_latent + hosts[host_ID].n_bloodstage + hosts[host_ID].n_infective;
if (nb>0) {
vector<int> tmp = {host_ID, hosts[host_ID].deme, k2};
push_back_multiple(history_migration, tmp);
}
}
// change deme of migrant
hosts[host_ID].deme = k2;
}
}
}
// update non-infective and infective lists with new hosts
for (int k1=0; k1<demes; k1++) {
for (int k2=0; k2<demes; k2++) {
if (k1==k2 || delta_mig[k1][k2]==0) {
continue;
}
push_back_multiple(hosts_noninfective[k2], mig_noninf_hosts[k1][k2]);
push_back_multiple(hosts_infective[k2], mig_inf_hosts[k1][k2]);
mig_noninf_hosts[k1][k2].clear();
mig_inf_hosts[k1][k2].clear();
}
}
}
*/
| true |
ba8de9600b1151ff1df7c36c4f27cb7168fb43a1 | C++ | kakaxi1100/utopia | /SFML/practice/Framework/Framework/Animation.h | UTF-8 | 865 | 2.84375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <memory>
#include "AnimationFrame.h"
class Animation
{
public:
Animation() = default;
Animation(unsigned int frameRate);
Animation(unsigned int frameRate, int loop);
~Animation() = default;
void addFrame(std::shared_ptr<AnimationFrame> frame);
void setLoop(int loop);
void play();
void stop();
void pause();
void gotoAndPlay(unsigned int frameIndex);
void gotoAndPlay(std::string frameName);
void gotoAndStop(unsigned int frameIndex);
void gotoAndStop(std::string frameName);
void gotoAndPause(unsigned int frameIndex);
void gotoAndPause(std::string frameName);
void update(float dt);
private:
void render();
private:
unsigned int mIndex = 0;
int mLoop = 0;
bool mIsPlaying = true;
unsigned int mFrameRate;
float mWave;
float mDuration = 0;
std::vector<std::shared_ptr<AnimationFrame>> mFrames;
}; | true |
41535fd7624f0e4f52c0db9d4eaa43e1563e3d74 | C++ | CarloDubini/Proyecto-Diciembre | /siete_y_media_vfinal.cpp | ISO-8859-1 | 18,240 | 2.546875 | 3 | [] | no_license | /*
Eduardo Abad Ibarrola
Carlo Dubini Marqus
*/
#include <iostream>
#include <fstream>
#include <list>
#include <istream>
#include <string>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
using namespace std;
const int HUMANO = 1;
const int MAQUINA = 2;
const int MAX = 8;
const int TAMBARAJA = 40;
typedef int tCartasPorAparecer[MAX];
typedef int tMazoCartas[TAMBARAJA];
typedef struct
{
int cont;
tMazoCartas cartas;
}tConjuntoCartas;
int menu();
void cargarOpcion(int opcion);
void cargarFichero(ifstream & fich_entrada, string & nombre_fich);
int generarMaxCartas(int max_cartas);
int determinaGanador(double puntosJugador, double puntosMaquina);
void ejecutarModoA(ifstream & fich_entrada, double & puntosJugador, double & puntosMaquina, int & ganador);
double modoA(ifstream & fich_entrada, int max_cartas);
double Valores(int carta_robada);
void mostrarGanador(int ganador);
void ejecutarModoB(ifstream & fich_entrada, double & puntosMaquina, double & puntosJugador, int & ganador);
double modoBhumano(ifstream & fich_entrada, int max_cartas, double puntosJugador);
double modoBmaquina(ifstream & fich_entrada, int max_cartas, double puntosJugador);
void ejecutarModoC(ifstream& fich_entrada, tCartasPorAparecer & cartas_restantes, string & nombre_fich, double & puntosJugador, double & puntosMaquina, int& ganador);
void modoChumano(ifstream & fich_entrada, tCartasPorAparecer cartas, double & puntos);
void modoCmaquina(ifstream & fich_entrada, tCartasPorAparecer cartas, double puntosJugador, double & puntos);
void iniciarPorAparecer(ifstream & fich_entrada, tCartasPorAparecer cartas);
void reducirCartasMazo(tCartasPorAparecer cartas, int & carta_robada);
void inicializa(tConjuntoCartas & cartas);
void sacar(tConjuntoCartas & mazo, int & carta);
void incluir(tConjuntoCartas & mazo, int & carta);
void crearMazo(tConjuntoCartas & mazo);
void mostrarMazo(tConjuntoCartas & mazo);
void barajar(tConjuntoCartas & mazo);
void ejecutarModoD(tCartasPorAparecer& cartas_restantes, double & puntosJugador, double & puntosMaquina, int & ganador, int & num_partida);
void modoDhumano(tConjuntoCartas& mazo, tCartasPorAparecer cartas, tConjuntoCartas& cartasHumano, double& puntos);
void modoDmaquina(tConjuntoCartas& mazo, tCartasPorAparecer cartas, double puntosJugador, tConjuntoCartas& cartasMaquina, double& puntos);
bool comprobarPuntosJug(double puntosJugador, double puntos);
void iniciarCartasRestantes_D(const tConjuntoCartas & mazo, tCartasPorAparecer cartas_restantes);
bool Seguir();
void compararCartas(const tConjuntoCartas & cartasMaquina, const tCartasPorAparecer cartas_restantes, int & ganador);
bool esProbablePasarse(double puntosMaquina, const tCartasPorAparecer cartas);
void guardarResultado(ofstream & fich_partida, tConjuntoCartas & cartasJugador, double & puntosJugador, tConjuntoCartas& cartasMaquina, double& puntosMaquina, int & ganador, int &num_partida);
void mostrarCartas(tConjuntoCartas& cartas);
int main()
{
int opcion;
srand(time(NULL));
opcion = menu();
cargarOpcion(opcion);
system("pause");
return 0;
}
void cargarOpcion(int opcion)
{
int ganador = 0, carta = 0, num_partida = 0;
double puntosJugador = 0, puntosMaquina = 0;
string nombre_fich;
tCartasPorAparecer cartas_restantes;
while (opcion != 0)
{
puntosJugador = 0, puntosMaquina = 0;
if (opcion == 4)
{
ejecutarModoD(cartas_restantes, puntosJugador, puntosMaquina, ganador, num_partida);
}
else
{
ifstream fich_entrada;
if (opcion == 1)
{
cargarFichero(fich_entrada, nombre_fich);
ejecutarModoA(fich_entrada, puntosJugador, puntosMaquina, ganador);
}
if (opcion == 2)
{
cargarFichero(fich_entrada, nombre_fich);
ejecutarModoB(fich_entrada, puntosMaquina, puntosJugador, ganador);
}
if (opcion == 3)
{
ejecutarModoC(fich_entrada, cartas_restantes, nombre_fich, puntosJugador, puntosMaquina, ganador);
}
fich_entrada.close();
}
opcion = menu();
}
}
int generarMaxCartas(int max_cartas)
{
max_cartas = 3 + rand() % 3;
return max_cartas;
}
int determinaGanador(double puntosJugador, double puntosMaquina)
{
int ganador = 0, ganador_aleatorio = 0;
while (ganador != 2 && ganador != 1)
{
if (puntosJugador < 7.5 && puntosMaquina < 7.5)
{
if (puntosJugador > puntosMaquina)
{
ganador = HUMANO;
}
if (puntosJugador < puntosMaquina)
{
ganador = MAQUINA;
}
}
else if (puntosJugador > 7.5 && puntosMaquina > 7.5)
{
if (puntosJugador < puntosMaquina)
{
ganador = HUMANO;
}
if (puntosJugador > puntosMaquina)
{
ganador = MAQUINA;
}
}
else if (puntosMaquina > 7.5 && puntosJugador < 7.5)
{
ganador = HUMANO;
}
else if (puntosMaquina < 7.5 && puntosJugador > 7.5)
{
ganador = MAQUINA;
}
else if (puntosJugador == 7.5 && puntosMaquina != 7.5)
{
ganador = HUMANO;
}
else if (puntosMaquina == 7.5 && puntosJugador != 7.5)
{
ganador = MAQUINA;
}
else if (puntosJugador == puntosMaquina)
{
cout << "Como se ha obtenido la misma puntuacion el ganador se decidira aleatoriamente." << endl;
ganador_aleatorio = 1 + rand() % 2;
if (ganador_aleatorio == 1)
{
ganador = HUMANO;
}
else
{
ganador = MAQUINA;
}
}
}
return ganador;
}
double modoA(ifstream & fich_entrada, int max_cartas)
{
int cont = 0, carta;
double puntos_loc = 0, valor = 0;
while (cont < max_cartas)
{
fich_entrada >> carta;
valor = Valores(carta);
cout << "Ha cogido un: " << carta << endl;
puntos_loc = puntos_loc + valor;
cont++;
}
return puntos_loc;
}
void ejecutarModoA(ifstream & fich_entrada, double & puntosJugador, double & puntosMaquina, int & ganador)
{
int max_cartas = 0;
max_cartas = generarMaxCartas(max_cartas);
puntosJugador = modoA(fich_entrada, max_cartas);
cout << "El jugador tiene: " << puntosJugador << endl;
puntosMaquina = modoA(fich_entrada, max_cartas);
cout << "La maquina tiene: " << puntosMaquina << endl;
ganador = determinaGanador(puntosJugador, puntosMaquina);
mostrarGanador(ganador);
}
//-----------------------------------------ModoB------------------------------------------------
void ejecutarModoB(ifstream & fich_entrada, double & puntosMaquina, double & puntosJugador, int & ganador)
{
int max_cartas = 0;
max_cartas = generarMaxCartas(max_cartas);
puntosJugador = modoBhumano(fich_entrada, max_cartas, puntosJugador);
puntosMaquina = modoBmaquina(fich_entrada, max_cartas, puntosJugador);
ganador = determinaGanador(puntosJugador, puntosMaquina);
mostrarGanador(ganador);
}
double modoBhumano(ifstream & fich_entrada, int max_cartas, double puntosJugador)
{
bool seguir = true;
int carta_robada = 0;
for (int i = 0; i <= max_cartas && seguir && puntosJugador <= 7.5; i++)
{
fich_entrada >> carta_robada;
puntosJugador += Valores(carta_robada);
cout << "El jugador ha robado un " << carta_robada << " y tiene " << puntosJugador << endl;
seguir = Seguir();
}
return puntosJugador;
}
double modoBmaquina(ifstream & fich_entrada, int max_cartas, double puntosJugador)
{
bool plantarse = false;
int carta = 0, i = 0;
double puntos = 0, valor = 0;
while (i <= max_cartas && puntos < 7.5)
{
fich_entrada >> carta;
valor = Valores(carta);
puntos += valor;
cout << "La maquina ha robado un " << carta << " y tiene " << puntos << endl;
plantarse = comprobarPuntosJug(puntosJugador, puntos);
}
return puntos;
}
bool Seguir()
{
int opcion;
bool seguir = true;
cout << "Desea seguir robando: (1- robar;0- plantarse)" << endl;
cin >> opcion;
while (opcion < 0 || opcion > 1)
{
cout << "introduzca opcion correcta: ";
cin >> opcion;
}
seguir = opcion;
return seguir;
}
bool comprobarPuntosJug(double puntosJugador, double puntos)
{
bool plantarse = false;
if (puntosJugador > 7.5 && 7.5 > puntos || puntosJugador < puntos && puntos < 7.5) { plantarse = true; }
return plantarse;
}
//-----------------------------------------ModoC------------------------------------------------
void ejecutarModoC(ifstream& fich_entrada, tCartasPorAparecer & cartas_restantes, string & nombre_fich, double & puntosJugador, double & puntosMaquina, int& ganador)
{
int cartas_jugador, cartas_maquina;
cargarFichero(fich_entrada, nombre_fich);
iniciarPorAparecer(fich_entrada, cartas_restantes);
fich_entrada.close();
fich_entrada.open(nombre_fich);
modoChumano(fich_entrada, cartas_restantes, puntosJugador);
cartas_jugador = 40 - (cartas_restantes[0] + cartas_restantes[1] + cartas_restantes[2] + cartas_restantes[3] + cartas_restantes[4] + cartas_restantes[5] + cartas_restantes[6] + cartas_restantes[7]);
modoCmaquina(fich_entrada, cartas_restantes, puntosJugador, puntosMaquina);
cartas_maquina = 40 - (cartas_jugador + (cartas_restantes[0] + cartas_restantes[1] + cartas_restantes[2] + cartas_restantes[3] + cartas_restantes[4] + cartas_restantes[5] + cartas_restantes[6] + cartas_restantes[7]));
ganador = determinaGanador(puntosJugador, puntosMaquina);
mostrarGanador(ganador);
}
void modoChumano(ifstream& fich_entrada, tCartasPorAparecer cartas_restantes, double & puntos)
{
int carta_robada = 0;
bool seguir = true;
while (seguir)
{
fich_entrada >> carta_robada;
puntos += Valores(carta_robada);
cout << "El jugador ha robado un " << carta_robada << " y tiene " << puntos << endl;
reducirCartasMazo(cartas_restantes, carta_robada);
seguir = Seguir();
}
}
void modoCmaquina(ifstream & fich_entrada, tCartasPorAparecer cartas, double puntosJugador, double & puntos)
{
int carta_robada;
bool pasarse = false;
while (!pasarse && puntos < 7.5 && puntosJugador >= puntos)
{
fich_entrada >> carta_robada;
puntos += Valores(carta_robada);
cout << "La maquina ha robado un " << carta_robada << " y tiene " << puntos << endl;
reducirCartasMazo(cartas, carta_robada);
if (!pasarse && puntos > puntosJugador)
{
pasarse = true;
}
if (puntos == puntosJugador)
{
pasarse = esProbablePasarse(puntos, cartas);
}
}
}
void iniciarPorAparecer(ifstream & fich_entrada, tCartasPorAparecer cartas_restantes)
{
int leer_cartas_mazo = 0;
for (int i = 0; i < MAX; i++)
{
cartas_restantes[i] = 0;
}
fich_entrada >> leer_cartas_mazo;
while (!fich_entrada.eof())
{
if (leer_cartas_mazo > 7)
{
cartas_restantes[0] += 1;
}
else
{
cartas_restantes[leer_cartas_mazo] += 1;
}
fich_entrada >> leer_cartas_mazo;
}
}
bool esProbablePasarse(double puntosMaquina, const tCartasPorAparecer cartas_restantes)
{
int sacar = 0, n;
double probabilidad = 0, s_parcial = 0, s_total = 0;
bool probab_mayor_50 = false;
if (puntosMaquina <= 7.5)
{
s_total = cartas_restantes[0] + cartas_restantes[1] + cartas_restantes[2] + cartas_restantes[3] + cartas_restantes[4] + cartas_restantes[5] + cartas_restantes[6] + cartas_restantes[7];
if (puntosMaquina >= 0 && puntosMaquina < 1)
{
probabilidad = 0;
}
else if (puntosMaquina == 7.5)
{
probabilidad = 1;
}
else if (puntosMaquina >= 1 && puntosMaquina < 7.5)
{
n = 8 - trunc(puntosMaquina);
if (n >= trunc(puntosMaquina) || n < trunc(puntosMaquina))
{
sacar = n;
}
for (int i = sacar; i <= 7.5; i++)
{
s_parcial += cartas_restantes[i];
}
probabilidad = s_parcial / s_total;
}
if (probabilidad >= 0.5)
{
probab_mayor_50 = true;
}
}
return probab_mayor_50;
}
//-------------------------------------------ModoD---------------------------------------------
void ejecutarModoD(tCartasPorAparecer& cartas_restantes, double & puntosJugador, double & puntosMaquina, int & ganador, int & num_partida)
{
tConjuntoCartas mazo;
tConjuntoCartas cartasHumano;
tConjuntoCartas cartasMaquina;
ofstream fich_partida;
crearMazo(mazo);
iniciarCartasRestantes_D(mazo, cartas_restantes);
mostrarMazo(mazo);
modoDhumano(mazo, cartas_restantes, cartasHumano, puntosJugador);
modoDmaquina(mazo, cartas_restantes, puntosJugador, cartasMaquina, puntosMaquina);
if (puntosMaquina == puntosJugador)
{
cout << "Como se ha obtenido la misma puntuacion, ganara el que menos cartas haya robado. Si hay mismo numero de cartas, se decidira ganador aleatoriamente." << endl;
compararCartas(cartasMaquina, cartas_restantes, ganador);
}
else
{
ganador = determinaGanador(puntosJugador, puntosMaquina);
}
mostrarGanador(ganador);
guardarResultado(fich_partida, cartasHumano, puntosJugador, cartasMaquina, puntosMaquina, ganador, num_partida);
}
void modoDhumano(tConjuntoCartas& mazo, tCartasPorAparecer cartas_restantes, tConjuntoCartas & cartasHumano, double& puntos)
{
bool seguir = true;
int carta_robada = 0;
cartasHumano.cont = 0;
tConjuntoCartas &cartas = cartasHumano;
while (seguir)
{
sacar(mazo, carta_robada);
incluir(cartas, carta_robada);
puntos += Valores(carta_robada);
cout << "Cartas: ";
mostrarCartas(cartas);
reducirCartasMazo(cartas_restantes, carta_robada);
seguir = Seguir();
}
}
void modoDmaquina(tConjuntoCartas& mazo, tCartasPorAparecer cartas_restantes, double puntosJugador, tConjuntoCartas& cartasMaquina, double& puntos)
{
int carta_robada = 0;
bool pasarse = false;
cartasMaquina.cont = 0;
tConjuntoCartas &cartas = cartasMaquina;
while (!pasarse && puntos < puntosJugador)
{
sacar(mazo, carta_robada);
incluir(cartas, carta_robada);
puntos += Valores(carta_robada);
reducirCartasMazo(cartas_restantes, carta_robada);
if (puntos >= puntosJugador)
{
pasarse = true;
}
if (puntos == puntosJugador)
{
pasarse = esProbablePasarse(puntos, cartas_restantes);
}
}
cout << "Las cartas de la maquina son: ";
mostrarCartas(cartas);
}
void inicializa(tConjuntoCartas & mazo)
{
int cantidad = 1;
mazo.cont = 0;
for (int i = 0; i < 28; i++)
{
mazo.cartas[i] = cantidad;
if (i == 3 || i == 7 || i == 11 || i == 15 || i == 19 || i == 23)
{
cantidad++;
}
mazo.cont++;
}
cantidad = 10;
for (int i = mazo.cont; i < TAMBARAJA; i++)
{
mazo.cartas[i] = cantidad;
if (i == 31 || i == 35)
{
cantidad++;
}
mazo.cont++;
}
}
void sacar(tConjuntoCartas & mazo, int & carta_robada)
{
int i = mazo.cont - 1;
carta_robada = mazo.cartas[i];
mazo.cartas[TAMBARAJA - 1 - i];
mazo.cont -= 1;
}
void incluir(tConjuntoCartas & cartas, int & carta_robada)
{
int i = cartas.cont;
cartas.cartas[i] = carta_robada;
cartas.cont += 1;
}
void crearMazo(tConjuntoCartas & mazo)
{
inicializa(mazo);
barajar(mazo);
}
void barajar(tConjuntoCartas & mazo)
{
int i1 = 0, i2 = 0, aux;
i1 = rand() % 39;
i2 = rand() % 39;
if (i1 == i2)
{
i1 = rand() % 39;
i2 = rand() % 39;
}
else
{
for (int i = 0; i < TAMBARAJA; i++)
{
aux = mazo.cartas[i1];
mazo.cartas[i1] = mazo.cartas[i2];
mazo.cartas[i2] = aux;
i1 = rand() % 39;
i2 = rand() % 39;
}
}
}
void mostrarMazo(tConjuntoCartas & mazo)
{
for (int i = 0; i < TAMBARAJA; i++)
{
cout << mazo.cartas[i] << " ";
}
cout << endl;
}
void iniciarCartasRestantes_D(const tConjuntoCartas & mazo, tCartasPorAparecer cartas_restantes)
{
int leer_cartas_mazo;
for (int i = 0; i < MAX; i++) { cartas_restantes[i] = 0; }
for (int i = 0; i < mazo.cont; i++)
{
leer_cartas_mazo = mazo.cartas[i];
if (leer_cartas_mazo > 7)
{
cartas_restantes[0] += 1;
}
else if (leer_cartas_mazo >= 0 && leer_cartas_mazo <= 7)
{
cartas_restantes[leer_cartas_mazo] += 1;
}
}
}
void guardarResultado(ofstream & fich_partida, tConjuntoCartas & cartasJugador, double & puntosJugador, tConjuntoCartas& cartasMaquina, double& puntosMaquina, int & ganador, int& num_partida)
{
string nombre_partida;
nombre_partida = "partida" + to_string(num_partida) + ".txt";
fich_partida.open(nombre_partida);
if (!fich_partida.is_open())
{
cout << "No se ha guardado la partida." << endl;
}
else
{
fich_partida << "Numero de partida: " << num_partida << endl;
if (ganador == 1)
{
fich_partida << "Ganador: Humano" << endl;
}
else
{
fich_partida << "Ganador: Maquina" << endl;
}
fich_partida << "Humano. Puntos: " << puntosJugador << endl;
fich_partida << "Cartas: ";
for (int i = 0; i < cartasJugador.cont; i++)
{
fich_partida << cartasJugador.cartas[i] << " ";
}
fich_partida << endl;
fich_partida << "Maquina. Puntos: " << puntosMaquina << endl;
fich_partida << "Cartas: ";
for (int i = 0; i < cartasMaquina.cont; i++)
{
fich_partida << cartasMaquina.cartas[i] << " ";
}
fich_partida << endl;
}
num_partida++;
fich_partida.close();
}
void mostrarCartas(tConjuntoCartas& cartas)
{
for (int i = 0; i < cartas.cont; i++)
{
cout << cartas.cartas[i] << " ";
}
cout << endl;
}
//-------------------------------------------otras----------------------------------------------------
int menu() {
int opcion;
cout << "1.- Jugar modo A" << endl;
cout << "2.- Jugar modo B" << endl;
cout << "3.- Jugar modo C" << endl;
cout << "4.- Jugar modo D" << endl;
cout << "0.- Salir" << endl;
cin >> opcion;
while (opcion < 0 || opcion > 5) {
cout << "Opcion erronea.";
cin >> opcion;
}
return opcion;
}
void cargarFichero(ifstream & fich_entrada, string & nombre_fich)
{
cout << "Introduce nombre del mazo: ";
cin >> nombre_fich;
fich_entrada.open(nombre_fich);
while (!fich_entrada.is_open())
{
cout << "Error de lectura de mazo. Reinsertelo: ";
cin >> nombre_fich;
fich_entrada.open(nombre_fich);
}
}
double Valores(int carta_robada)
{
double valor = 0;
if (carta_robada > 0 && carta_robada <= 7) { valor = carta_robada; }
if (carta_robada > 9 && carta_robada < 13) { valor = 0.5; }
return valor;
}
void mostrarGanador(int ganador)
{
if (ganador == 1)
{
cout << "Ha ganado el jugador." << endl;
}
else
{
cout << "Ha ganado la maquina." << endl;
}
}
void reducirCartasMazo(tCartasPorAparecer cartas_restantes, int & carta_robada)
{
if (carta_robada > 7)
{
cartas_restantes[0] -= 1;
}
else
{
cartas_restantes[carta_robada] -= 1;
}
}
void compararCartas(const tConjuntoCartas & cartasMaquina, const tCartasPorAparecer cartas_restantes, int & ganador)
{
int cartasjugador, cartas_sobrantes = 0;
for (int i = 0; i < MAX; i++)
{
cartas_sobrantes += cartas_restantes[i];
}
cartasjugador = 40 - cartas_sobrantes + cartasMaquina.cont;
if (cartasjugador < cartasMaquina.cont)
{
ganador = HUMANO;
}
else if (cartasjugador > cartasMaquina.cont)
{
ganador = MAQUINA;
}
} | true |
a24820dc07375b1f6d90c69a9d9a04136459d063 | C++ | sikeking/AtcoderBeginingContest | /ABC128/B.cpp | UTF-8 | 486 | 2.96875 | 3 | [] | no_license |
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int N;
cin >> N;
vector <pair<string, int> > S[N];
for(int i = 0;i < N;i++){
cin >> S[i].first >> S[i].second;
}
/*
for(int i = 0;i < N;i++){
if(min > S[i].first){
min = S[i].first;
}
}
*/
sort(S.first.begin(), S.first.end());
for(int i = 0; i < N; i++){
cout << S[i].first << S[i].second << endl;
}
} | true |
5102d1827b32e3245b1fcb81cf054ab25a56634a | C++ | VarickQ/ACM | /HaveDone/大二暑假练习/第七场多校联合比赛解题报告+数据+标程/第七场多校联合比赛解题报告+数据+标程/Water World I/forcecode_0.cpp | UTF-8 | 2,540 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
#include<memory.h>
#define EPS 1e-6
#define PI acos(-1)
int n,i,j,k,maxi,iszero;
double angle,h[10005],th[10005],unitL,currH,tmph,sum;
struct TPoint{
double x,y;
}s,t,c;
double cross(const TPoint &a,const TPoint &b,const TPoint &c){
return (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);
}
double dis_p2_seg(TPoint &c,TPoint &a,TPoint &b){
double x,y,z;
x = (a.x - c.x) * (a.x - c.x) + (a.y - c.y) * (a.y - c.y);
y = (b.x - c.x) * (b.x - c.x) + (b.y - c.y) * (b.y - c.y);
z = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
//if(x+z-y<0 || y+z-x<0)return sqrt(x<y?x:y);
return fabs(cross(c,a,b)/sqrt(z));
}
int main(){
freopen("data.in", "r", stdin);
freopen("forcedata_0.out", "w", stdout);
while(scanf("%d%lf",&n,&angle)!=EOF){
s.x = 0;
s.y=0;
if(angle>=0)for(i=0;i<n;i++)scanf("%lf",&h[i]);
else for(i=n-1;i>=0;i--)scanf("%lf",&h[i]);
angle = fabs(angle);
if(angle ==0){//
unitL=0;
iszero = 1;
}else{
unitL = tan(angle/180.0*PI);
iszero = 0;
}
t.x = 10000*cos(angle/180.0*PI);
t.y = -10000*sin(angle/180.0*PI);
maxi = 0;
for(i=0;i<n;i++){
c.x = i+1;
c.y=h[i];
th[i] = dis_p2_seg(c,s,t);
if(th[i]>=th[maxi])maxi = i;//
}
i = 0;
sum = 0;
while(i<maxi){
for(j=i+1;j<=maxi;j++)
if(th[j]>=th[i]){//
currH = h[i];
for(k=i+1;k<=j;k++){
currH -= unitL;
if(currH>=h[k]){//
sum+=currH-h[k]+unitL*0.5;
}else if(currH+unitL>=h[k]){//
tmph = currH+unitL-h[k];
if(!iszero)sum+=tmph*tmph/unitL*0.5;
}
}
i = j;
break;
}
}
i = n-1;
while(i>maxi){
for(j=i-1;j>=maxi;j--)
if(th[j]>=th[i]){//
currH = h[i];
for(k=i;k>j;k--){
sum+=currH-h[k]+unitL*0.5;
currH += unitL;
}
i = j;
break;
}
}
printf("%.2lf\n",sum);
}
}
| true |
30781f3aa716ed835ba2848dda66d52bc90d17b3 | C++ | apfitzen/Wireframes-Calc | /Wireframes Calc/Optimization.cpp | UTF-8 | 4,816 | 2.703125 | 3 | [] | no_license | //
// Optimization.cpp
// Wireframes Calc 4
//
// Created by Aaron Pfitzenmaier on 1/3/15.
// Copyright (c) 2015 Aaron Pfitzenmaier. All rights reserved.
//
#include <vector>
#include <ctime>
#include <cmath>
#include "Optimization.h"
#include "Compound.h"
#include "Frame.h"
#include "Utilities.h"
#include "Polyhedron.h"
double computeCompoundWidth(const Compound& compound,double edgeDistCheckFactor)
{
//clock_t count=0;
int polyNum=compound.getNumberOfPolyhedra();
std::vector<Frame> frames;
for (int i=0;i<polyNum;i++)
{
frames.push_back(compound.makeFrame(i));
}
int edgeNum=frames.at(0).getEdgeNum();
double upperBound=frames.at(0).getFrameWidth();
double lowerBound=0.0;
//clock_t t;
//t = clock();
//cache edge-edge distances and use the smallest pair to calculate an upper bound on the frame width
double smallestDist=100000.0;
EdgeID smallestDistPair={0,0,0,0};
std::vector<double> edgeDistances;
for (int i=0;i<polyNum;i++)
{
for (int j=i+1;j<polyNum;j++)
{
for (int k=0;k<edgeNum;k++)
{
for (int m=0;m<edgeNum;m++)
{
double edgeDist=segmentSegmentDist(frames.at(i).getFrameEdges()->at(k).getLine(),frames.at(j).getFrameEdges()->at(m).getLine());
edgeDistances.push_back(edgeDist);
if (edgeDist<smallestDist)
{
smallestDist=edgeDist;
smallestDistPair={i,j,k,m};
}
}
}
}
}
//t = clock() - t;
//count+=t;
//clock_t t;
//t = clock();
int f1=std::get<0>(smallestDistPair);
int f2=std::get<1>(smallestDistPair);
int e1=std::get<2>(smallestDistPair);
int e2=std::get<3>(smallestDistPair);
double newUpperBound=computeEdgePairWidth(compound.getPolyhedron(f1),compound.getPolyhedron(f2),e1,e2,lowerBound,upperBound);
if (newUpperBound<upperBound) {upperBound=newUpperBound;}
lowerBound=smallestDist/2.0;
//t = clock() - t;
//count+=t;
//std::cout << upperBound << " " << lowerBound << "\n";
int index=-1;
double currentFrameWidth=upperBound;
for (int i=0;i<polyNum;i++)
{
for (int j=i+1;j<polyNum;j++)
{
for (int k=0;k<edgeNum;k++)
{
for (int m=0;m<edgeNum;m++)
{
//clock_t t;
//t = clock();
index++;
double edgeDist=edgeDistances.at(index);
if (edgeDist>upperBound*edgeDistCheckFactor) //edgeDistCheckFactor is usually 2.0
{
continue;
}
if (!FrameEdge::doFrameEdgesIntersect(frames.at(i).getFrameEdges()->at(k), frames.at(j).getFrameEdges()->at(m)))
{
continue;
}
//t = clock() - t;
//count+=t;
//clock_t t;
//t = clock();
upperBound=computeEdgePairWidth(compound.getPolyhedron(i),compound.getPolyhedron(j),k,m,lowerBound,upperBound);
//t = clock() - t;
//count+=t;
//clock_t t;
//t = clock();
if (upperBound!=currentFrameWidth)
{
currentFrameWidth=upperBound;
for (int i=0;i<polyNum;i++)
{
frames.at(i)=compound.makeFrame(i,upperBound);
}
}
//t = clock() - t;
//count+=t;
}
}
}
}
//printf ("\nIt took me %lu clicks (%f seconds).\n",count,((float)count)/CLOCKS_PER_SEC);
return currentFrameWidth;
}
double computeEdgePairWidth(const Polyhedron* p1,const Polyhedron* p2,int e1,int e2,double lowerBound,double upperBound)
{
int numberOfIterations=20;
for (int i=0;i<numberOfIterations;i++) //binary search real numbers for optimal width
//increase numOfIterations for greater accuracy
{
double check=(upperBound+lowerBound)/2.0;
FrameEdge fe1=p1->makeFrameEdge(e1,check);
FrameEdge fe2=p2->makeFrameEdge(e2,check);
bool isect=FrameEdge::doFrameEdgesIntersect(fe1, fe2);
if (!isect) //frames don't intersect, check too low
{
lowerBound=check;
}
else //frames do intersect, check too high
{
upperBound=check;
}
}
return (upperBound+lowerBound)/2.0;
} | true |
803dfab5521288163f228019d47fc9b23121fc21 | C++ | AndyChiangSH/Assembly-Language-Final-Project | /SICXE/pass1&2_XE.cpp | UTF-8 | 19,954 | 2.734375 | 3 | [] | no_license | // **pass1&2 SIC/XE assembler**
// Author: 4108056005 Andy Chiang
// Time: 2021/06/28
// Line: 790
// Description: This is a program for Assembly-Language and System-Software final project.
// This program can complete pass1 and pass2, then convert source code (assembly language) into object code.
// Input(pass1): source code, opcode table.
// Output(pass1): intermediate file, symbol table.
// Input(pass2): intermediate file, symbol table, opcode table.
// Output(pass2): new source code, object code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SOURCE_FILE "source_XE.txt"
#define OPCODE_FILE "opcode_XE.txt"
#define INTER_FILE "intermediate_XE.txt"
#define SYMTAB_FILE "symbol_table_XE.txt"
#define NEWSRC_FILE "new_source_XE.txt"
#define OBJ_FILE "object_XE.txt"
#define WORD_SIZE 10
#define LINE_SIZE 100
#define SYM_SIZE 100
#define TRECD_SIZE 10
#define MRECD_SIZE 1000
#define REGI_LEN 9
FILE * fsrc;
FILE * fop;
FILE * finter;
FILE * fsym;
FILE * fnew;
FILE * fobj;
int line = 0; // current line in source or intermediate text file
int objLength = 0; // object length from pass1
char REGI[REGI_LEN][3] = {"A", "X", "L", "B", "S", "T", "F", "PC", "SW"};
short REGI_NUM[REGI_LEN] = {0, 1, 2, 3, 4, 5, 6, 8, 9};
int pass1(); // pass1 assembler
int pass2(); // pass2 assembler
int hexToDec(char*); // convert from hexadecimal string to decimail int
unsigned int objectCodeFormat2(int, short, short); // create object code for format2
unsigned int objectCodeFormat3(int, short, short, short, short, short, short, int); // create object code for format3
unsigned int objectCodeFormat4(int, short, short, short, short, short, short, int); // create object code for format4
int main(void) {
printf("=====SIC/XE assembler=====\n\n");
printf("-----pass 1 START-----\n\n");
// start read file for pass1
fsrc = fopen(SOURCE_FILE, "r");
if(fsrc == NULL) {
printf("Error: %s not found...\n", SOURCE_FILE);
exit(-1);
}
fop = fopen(OPCODE_FILE, "r");
if(fop == NULL) {
printf("Error: %s not found...\n", OPCODE_FILE);
exit(-1);
}
finter = fopen(INTER_FILE, "w");
if(finter == NULL) {
printf("Error: %s not found...\n", INTER_FILE);
exit(-1);
}
fsym = fopen(SYMTAB_FILE, "w");
if(fsym == NULL) {
printf("Error: %s not found...\n", SYMTAB_FILE);
exit(-1);
}
if(pass1() != 0) {
printf("Error: error in pass1\n");
exit(-1);
}
// close file for pass1
fclose(fsrc);
fclose(fop);
fclose(finter);
fclose(fsym);
printf("\n-----pass 1 END-----\n\n");
printf("-----pass 2 START-----\n\n");
// start read file for pass2
finter = fopen(INTER_FILE, "r");
if(finter == NULL) {
printf("Error: %s not found...\n", INTER_FILE);
exit(-1);
}
fop = fopen(OPCODE_FILE, "r");
if(fop == NULL) {
printf("Error: %s not found...\n", OPCODE_FILE);
exit(-1);
}
fsym = fopen(SYMTAB_FILE, "r");
if(fsym == NULL) {
printf("Error: %s not found...\n", SYMTAB_FILE);
exit(-1);
}
fnew = fopen(NEWSRC_FILE, "w");
if(fnew == NULL) {
printf("Error: %s not found...\n", NEWSRC_FILE);
exit(-1);
}
fobj = fopen(OBJ_FILE, "w");
if(fobj == NULL) {
printf("Error: %s not found...\n", OBJ_FILE);
exit(-1);
}
if(pass2() != 0) {
printf("Error: error in pass2\n");
exit(-1);
}
// close file for pass2
fclose(finter);
fclose(fop);
fclose(fsym);
fclose(fnew);
fclose(fobj);
printf("\n-----pass 2 END-----\n\n");
system("PAUSE");
return 0;
}
int pass1() {
char SYMTAB_LABEL[SYM_SIZE][WORD_SIZE];
int SYMTAB_ADDR[SYM_SIZE];
char LABEL[WORD_SIZE], OPCODE[WORD_SIZE], FIRST_OPERAND[WORD_SIZE], SECOND_OPERAND[WORD_SIZE], ONE_LINE[LINE_SIZE];
int i, j, startAddr = 0, LOCCTR = 0, symtabTop = 0, optabTop = 0;
line = 1;
// read first line
fscanf(fsrc, "%s\t%s\t%s", LABEL, OPCODE, FIRST_OPERAND);
// start pass1
if(strcmp(OPCODE, "START") == 0) {
startAddr = hexToDec(FIRST_OPERAND);
LOCCTR = startAddr;
// printf("%04X\t%s\t%s\t%s\n", LOCCTR, LABEL, OPCODE, FIRST_OPERAND);
fprintf(finter, "%04X\t%s\t%s\t%s\n", LOCCTR, LABEL, OPCODE, FIRST_OPERAND);
}
else {
printf("Error: No START at first line, in line %d\n", line);
return -1;
}
// load opcode
while(true) {
char c = getc(fop);
if(c == '\n') {
optabTop++;
}
if(c == EOF) {
break;
}
}
optabTop++;
char OPTAB_OP[optabTop][WORD_SIZE];
int OPTAB_CODE[optabTop];
rewind(fop);
for(i = 0; i < optabTop; i++) {
fscanf(fop, "%s%X", OPTAB_OP[i], &OPTAB_CODE[i]);
}
// read next line
line++;
getc(fsrc);
while(true) {
// read label, opcode and operand in one line
short state = 0, e = 0;
bool isSpace = false;
strcpy(LABEL, "");
strcpy(OPCODE, "");
strcpy(FIRST_OPERAND, "");
strcpy(SECOND_OPERAND, "");
strcpy(ONE_LINE, "");
while(true) {
char c = getc(fsrc);
if(c == '\n' || c == EOF) {
break;
}
strncat(ONE_LINE, &c, 1);
if(isSpace) { // span column by space or tab
if(c != ' ' && c != '\t') {
isSpace = false;
}
}
else {
if(state != 2 && (c == ' ' || c == '\t')) {
isSpace = true;
state++;
}
}
if(!isSpace) {
if(state == 0) {
strncat(LABEL, &c, 1);
}
else if(state == 1) {
if(c == '+') {
e = 1;
}
else {
strncat(OPCODE, &c, 1);
}
}
else if(state == 2) {
if(c == '\'') {
state++;
}
else if(c == ',') {
state++;
}
else {
strncat(FIRST_OPERAND, &c, 1);
}
}
else if(state == 3) {
if(c == '\'') {
continue;
}
strncat(SECOND_OPERAND, &c, 1);
}
}
}
// skip comment
if(LABEL[0] == '#') {
continue;
}
// base opcode
if(strcmp(OPCODE, "BASE") == 0) {
// printf("\t%s\n", ONE_LINE);
fprintf(finter, "%04X\t%s\n", LOCCTR, ONE_LINE);
continue;
}
// last line
if(strcmp(OPCODE, "END") == 0) {
// printf("\t%s\n", ONE_LINE);
fprintf(finter, "%04X\t%s\n", LOCCTR, ONE_LINE);
objLength = LOCCTR-startAddr;
break;
}
// write intermediate file
// printf("%04X\t%s\n", LOCCTR, ONE_LINE);
fprintf(finter, "%04X\t%s\n", LOCCTR, ONE_LINE);
// add label and address into symbol table
if(strcmp(LABEL, "") != 0) {
// check duplicate label
for(i = 0; i < symtabTop; i++) {
if(strcmp(LABEL, SYMTAB_LABEL[i]) == 0) {
printf("Error: duplicate label '%s', in line %d\n", LABEL, line);
return -1;
}
}
strcpy(SYMTAB_LABEL[symtabTop], LABEL);
SYMTAB_ADDR[symtabTop] = LOCCTR;
symtabTop++;
}
// calculate next location counter
bool isFoundOP = false;
for(i = 0; i < optabTop; i++) {
// search opcode in optable
if(strcmp(OPCODE, OPTAB_OP[i]) == 0) {
isFoundOP = true;
break;
}
}
if(isFoundOP) { // instruction
bool isFoundREGI = false;
for(j = 0; j < REGI_LEN; j++) {
if(strcmp(FIRST_OPERAND, REGI[j]) == 0) {
isFoundREGI = true;
break;
}
}
if(isFoundREGI) {
LOCCTR += 2;
}
else if(e == 0) {
LOCCTR += 3;
}
else {
LOCCTR += 4;
}
}
else if(strcmp(OPCODE, "BYTE") == 0) { // a byte
// length of operand
int length = 0;
for(i = 0; i < WORD_SIZE; i++) {
if(SECOND_OPERAND[i] == '\0') {
break;
}
length++;
}
if(strcmp(FIRST_OPERAND, "C") == 0) { // one character one byte
LOCCTR += length;
}
else if(strcmp(FIRST_OPERAND, "X") == 0) { // two hexadecimal one byte
LOCCTR += (length+1)/2;
}
else {
printf("Error: invalid byte type '%c', in line %d\n", FIRST_OPERAND[0], line);
return -1;
}
}
else if(strcmp(OPCODE, "WORD") == 0) { // a word
LOCCTR += 3;
}
else if(strcmp(OPCODE, "RESB") == 0) { // reserve byte
LOCCTR += atoi(FIRST_OPERAND);
}
else if(strcmp(OPCODE, "RESW") == 0) { // reserve word
LOCCTR += 3*atoi(FIRST_OPERAND);
}
else {
printf("Error: invalid opcode '%s', in line %d\n", OPCODE, line);
return -1;
}
line++;
}
printf("%s complete!\n", INTER_FILE);
// show symbol table & write symbol table file
for(i = 0; i < symtabTop; i++) {
// printf("%s\t%04X\n", SYMTAB_LABEL[i], SYMTAB_ADDR[i]);
fprintf(fsym, "%s\t%04X\n", SYMTAB_LABEL[i], SYMTAB_ADDR[i]);
}
for(i = 0; i < REGI_LEN; i++) {
// printf("%s\t%04X\n", SYMTAB_LABEL[i], SYMTAB_ADDR[i]);
fprintf(fsym, "%s\t%d\n", REGI[i], REGI_NUM[i]);
}
printf("%s complete!\n", SYMTAB_FILE);
return 0;
}
int pass2() {
char LABEL[WORD_SIZE], OPCODE[WORD_SIZE], FIRST_OPERAND[WORD_SIZE], SECOND_OPERAND[WORD_SIZE], ONE_OPERAND[WORD_SIZE*2], ONE_LINE[LINE_SIZE];
int i, j, startAddr = 0, LOCCTR = 0, symtabTop = 0, optabTop = 0, BASE = 0, PC = 0;
line = 1;
// read first line
fscanf(finter, "%X%s%s%X", &LOCCTR, LABEL, OPCODE, &startAddr);
// start pass2
if(strcmp(OPCODE, "START") == 0) {
PC = startAddr;
// printf("%04X\t%s\t%s\t%d\n", PC, LABEL, OPCODE, startAddr);
fprintf(fnew, "%04X\t%s\t%s\t%X\n", PC, LABEL, OPCODE, startAddr);
// printf("H%-6s%06s%06X\n", LABEL, OPERAND, objLength);
fprintf(fobj, "H%-6s%06X%06X\n", LABEL, startAddr, objLength);
}
else {
printf("Error: No START at first line, in line %d\n", line);
return -1;
}
// load opcode
while(true) {
char c = getc(fop);
if(c == '\n') {
optabTop++;
}
if(c == EOF) {
break;
}
}
optabTop++;
char OPTAB_OP[optabTop][WORD_SIZE];
int OPTAB_CODE[optabTop];
rewind(fop);
for(i = 0; i < optabTop; i++) {
fscanf(fop, "%s%X", OPTAB_OP[i], &OPTAB_CODE[i]);
}
// load symbol table
while(true) {
char c = getc(fsym);
if(c == '\n') {
symtabTop++;
}
if(c == EOF) {
break;
}
}
char SYMTAB_LABEL[symtabTop][WORD_SIZE];
int SYMTAB_ADDR[symtabTop];
rewind(fsym);
for(i = 0; i < symtabTop; i++) {
fscanf(fsym, "%s\t%X", SYMTAB_LABEL[i], &SYMTAB_ADDR[i]);
}
// read next line
int objNum = 0, objLen = 0;
char textRecord[TRECD_SIZE*15];
char modiRecord[MRECD_SIZE];
strcpy(textRecord, "");
strcpy(modiRecord, "");
line++;
while(true) {
char c = getc(finter);
if(c == '\t') {
break;
}
}
while(true) {
// read location counter, label, opcode and operand in one line
int state = 0;
short N = 1, I = 1, X = 0, B = 0, P = 0, E = 0, format = 0;
strcpy(LABEL, "");
strcpy(OPCODE, "");
strcpy(FIRST_OPERAND, "");
strcpy(SECOND_OPERAND, "");
strcpy(ONE_OPERAND, "");
strcpy(ONE_LINE, "");
LOCCTR = PC;
while(true) {
char c = getc(finter);
if(c == '\n' || c == EOF) {
break;
}
if(c == '\t') {
state++;
}
else if(state == 0) {
strncat(LABEL, &c, 1);
}
else if(state == 1) {
if(c == '+') { // format 4
E = 1;
}
else {
strncat(OPCODE, &c, 1);
}
}
else if(state == 2) {
if(c == '#') { // immediate addressing
N = 0;
I = 1;
}
else if(c == '@') { // indirect addressing
N = 1;
I = 0;
}
else if(c == '\'') { // BYTE two operand
state++;
}
else if(c == ',') { // two operand
state++;
}
else {
strncat(FIRST_OPERAND, &c, 1);
}
}
else if(state == 3) {
if(c != '\'') {
strncat(SECOND_OPERAND, &c, 1);
}
}
if(state < 2) {
strncat(ONE_LINE, &c, 1);
}
else if(c != '\t') {
strncat(ONE_OPERAND, &c, 1);
}
}
// read next PC first
char nextPC[WORD_SIZE] = "";
while(true) {
char c = getc(finter);
if(c == '\t' || c == EOF) {
break;
}
strncat(nextPC, &c, 1);
}
PC = hexToDec(nextPC);
// base opcode
if(strcmp(OPCODE, "BASE") == 0) {
bool isFoundBase = false;
for(i = 0; i < symtabTop; i++) {
if(strcmp(FIRST_OPERAND, SYMTAB_LABEL[i]) == 0) {
isFoundBase = true;
break;
}
}
if(isFoundBase) {
BASE = SYMTAB_ADDR[i];
// printf("%s\t%s\n", ONE_LINE, ONE_OPERAND);
fprintf(fnew, "%s\t%s\n", ONE_LINE, ONE_OPERAND);
line++;
continue;
}
else {
printf("Error: undefined base operand \'%s\', in line %d\n", FIRST_OPERAND, line);
return -1;
}
}
// end of intermediate file
if(strcmp(OPCODE, "END") == 0) {
// printf("%s\t%s\n", ONE_LINE, ONE_OPERAND);
fprintf(fnew, "%s\t%s\n", ONE_LINE, ONE_OPERAND);
// printf("%02X%s\n", objLen, textRecord);
fprintf(fobj, "%02X%s\n", objLen, textRecord);
// printf("%s\n", modiRecord);
fprintf(fobj, "%s", modiRecord);
fprintf(fobj, "E%06X\n", startAddr);
break;
}
// search OPCODE in OPTAB
short regi1 = 0, regi2 = 0;
int operAddr = 0, disp = 0;
unsigned int objCode = 0;
bool isFoundOP = false;
for(i = 0; i < optabTop; i++) {
if(strcmp(OPCODE, OPTAB_OP[i]) == 0) {
isFoundOP = true;
break;
}
}
if(isFoundOP) { // instruction
if(strcmp(FIRST_OPERAND, "") != 0) { // if there is an operand
bool isFoundREGI = false;
for(j = 0; j < REGI_LEN; j++) {
if(strcmp(FIRST_OPERAND, REGI[j]) == 0) {
isFoundREGI = true;
regi1 = REGI_NUM[j];
break;
}
}
if(isFoundREGI) {
isFoundREGI = false;
if(strcmp(SECOND_OPERAND, "") != 0) {
isFoundREGI = false;
for(j = 0; j < REGI_LEN; j++) {
if(strcmp(SECOND_OPERAND, REGI[j]) == 0) {
isFoundREGI = true;
regi2 = REGI_NUM[j];
break;
}
}
if(!isFoundREGI) {
printf("Error: unvaild second register name \'%s\', in line %d\n", SECOND_OPERAND, line);
return -1;
}
}
format = 2;
}
else {
// search symbol table for operand
bool isFoundSYM = false;
for(j = 0; j < symtabTop; j++) {
if(strcmp(FIRST_OPERAND, SYMTAB_LABEL[j]) == 0) {
isFoundSYM = true;
break;
}
}
if(isFoundSYM) { // find symbol in symbol table
if(strcmp(SECOND_OPERAND, "X") == 0) {
X = 1;
}
operAddr = SYMTAB_ADDR[j];
disp = operAddr - PC;
if(disp >= -2048 && disp <= 2047) { // PC-relative range
P = 1;
format = 3;
}
else {
disp = operAddr - BASE;
if(disp >= 0 && disp <= 4095) { // Base-relative range
B = 1;
format = 3;
}
else {
if(E == 1) { // direct address: format 4
disp = operAddr;
format = 4;
// append modification record
char temp[10];
sprintf(temp, "M%06X05\n", LOCCTR+1);
strncat(modiRecord, temp, 10);
}
else {
// for SIC
N = 0, I = 0;
format = 3;
}
}
}
}
else { // not find
if(N == 0 && I == 1) { // immediate address (#)
disp = atoi(FIRST_OPERAND);
if(disp >= 0x1000) {
format = 4;
}
else {
format = 3;
}
}
else {
printf("Error: undefined symbol \'%s\', in line %d\n", FIRST_OPERAND, line);
return -1;
}
}
}
}
else { // no operand
operAddr = 0;
format = 3;
}
if(format == 2) {
// create object code
objCode = objectCodeFormat2(OPTAB_CODE[i], regi1, regi2);
// concatenate opcode behind text record
}
else if(format == 3) {
// create object code
objCode = objectCodeFormat3(OPTAB_CODE[i], N, I, X, B, P, E, disp);
}
else {
objCode = objectCodeFormat4(OPTAB_CODE[i], N, I, X, B, P, E, disp);
}
}
else if(strcmp(OPCODE, "BYTE") == 0) { // BYTE
int operLen = 0, tempLen = 0;
if(strcmp(FIRST_OPERAND, "C") == 0) { // character
// get the value inside ''
for(i = 0; i < WORD_SIZE; i++) {
if(SECOND_OPERAND[i] == '\0') {
break;
}
operLen++;
objCode = objCode*0x100 + SECOND_OPERAND[i];
}
format = operLen; // one char one byte
}
else if(strcmp(FIRST_OPERAND, "X") == 0) { // hexadecimal
char hexOPER[WORD_SIZE] = "";
// get the value inside ''
for(i = 0; i < WORD_SIZE; i++) {
if(SECOND_OPERAND[i] == '\0') {
break;
}
operLen++;
}
objCode = hexToDec(SECOND_OPERAND);
format = (operLen+1)/2; // two hex one byte
}
else {
printf("Error: invalid byte type '%s', in line %d\n", FIRST_OPERAND, line);
return -1;
}
}
else if(strcmp(OPCODE, "WORD") == 0) { // WORD
objCode = atoi(FIRST_OPERAND);
format = 3;
}
else if(strcmp(OPCODE, "RESW") == 0 || strcmp(OPCODE, "RESB") == 0) {
// nothing to do
}
else {
printf("Error: undefined opcode \'%s\', in line %d\n", OPCODE, line);
return -1;
}
// write new source file
objLen += format;
char temp[format*2];
if(format == 0) {
// printf("%04X\t%s\t%-15s\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
fprintf(fnew, "%04X\t%s\t%-15s\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
}
else if(format == 1) {
// printf("%04X\t%s\t%-15s%02X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
fprintf(fnew, "%04X\t%s\t%-15s%02X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
sprintf(temp, "%02X", objCode);
}
else if(format == 2) {
// printf("%04X\t%s\t%-15s%04X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
fprintf(fnew, "%04X\t%s\t%-15s%04X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
sprintf(temp, "%04X", objCode);
}
else if(format == 3) {
// printf("%04X\t%s\t%-15s%06X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
fprintf(fnew, "%04X\t%s\t%-15s%06X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
sprintf(temp, "%06X", objCode);
}
else if(format == 4) {
// printf("%04X\t%s\t%-15s%08X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
fprintf(fnew, "%04X\t%s\t%-15s%08X\n", LOCCTR, ONE_LINE, ONE_OPERAND, objCode);
sprintf(temp, "%08X", objCode);
}
// concatenate opcode behind text record
strncat(textRecord, temp, format*2);
// count number of object code
if(objNum == 0) {
// write T and starting address
// printf("T%06X", LOCCTR);
fprintf(fobj, "T%06X", LOCCTR);
}
objNum++;
// max object number is 10 in this case, if over 10, then change to next line
if(objNum == TRECD_SIZE) {
// write length of object code and object code
// printf("%02X", objLen);
// printf("%s\n", textRecord);
fprintf(fobj, "%02X", objLen);
fprintf(fobj, "%s\n", textRecord);
objNum = 0;
objLen = 0;
strcpy(textRecord, "");
}
line++;
}
printf("%s complete!\n", NEWSRC_FILE);
printf("%s complete!\n", OBJ_FILE);
return 0;
}
int hexToDec(char hex[]) {
int i, dec = 0;
for(i = 0; hex[i] != '\0'; i++) {
int val = 0;
if(hex[i] >= '0' && hex[i] <= '9')
{
val = hex[i] - 48;
}
else if(hex[i] >= 'A' && hex[i] <= 'F')
{
val = hex[i] - 65 + 10;
}
else if(hex[i] >= 'a' && hex[i] <= 'f')
{
val = hex[i] - 97 + 10;
}
else {
printf("Error: Wrong hexadecimal format \'%c\', in line %d\n", hex[i], line);
exit(-1);
}
dec = dec*16 + val;
}
return dec;
}
unsigned int objectCodeFormat2(int opcode, short regi1, short regi2) {
// printf("opcode=%02X, regi1 = %d, regi2 = %d\t", opcode, regi1, regi2);
return opcode*0x100 + regi1*0x10 + regi2;
}
unsigned int objectCodeFormat3(int opcode, short N, short I, short X, short B, short P, short E, int disp) {
// printf("opcode=%02X, N=%d, I=%d, X=%d, B=%d, P=%d, E=%d, disp=%03X\t", opcode, N, I, X, B, P, E, disp);
return opcode*0x10000 + N*0x20000 + I*0x10000 + X*0x8000 + B*0x4000 + P*0x2000 + E*0x1000 + (disp&0x00FFF);
}
unsigned int objectCodeFormat4(int opcode, short N, short I, short X, short B, short P, short E, int addr) {
// printf("opcode=%02X, N=%d, I=%d, X=%d, B=%d, P=%d, E=%d, addr=%05X\t", opcode, N, I, X, B, P, E, addr);
return opcode*0x1000000 + N*0x2000000 + I*0x1000000 + X*0x800000 + B*0x400000 + P*0x200000 + E*0x100000 + addr;
}
| true |
3a3b907ac99f4e5cb026bd1fe85ccc75e78849b9 | C++ | TaniyaPeters/BorealEngine | /include/IndexBuffer.h | UTF-8 | 1,041 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
namespace Boreal {
/**
* @brief Allows user to create and manage index buffers
*
* @section Description
*
* The index buffer class allows the user to create, bind, and unbind index buffers. This is used to create models along with the vertex buffer.
*
*/
class IndexBuffer {
public:
/**
* @brief Constructor that initializes the index buffer with a pointer to an array of indexes and the count of indexes in the array
*
* @param [in] indexes A pointer to an array of indexes
* @param [in] indexCount The number of indexes in the array pointed to by the indexes parameter
*
*/
IndexBuffer(unsigned int* indexes, unsigned int indexCount);
/**
* @brief Destructor that deletes the index buffer.
*/
~IndexBuffer();
/**
* @brief Bind function binds the index buffer to the current context
*
*/
void Bind();
/**
* @brief UnBind function unbinds the index buffer from the current context
*
*/
void UnBind();
private:
unsigned int m_EBO; // ID of Element Buffer Object
};
} | true |
d2328dd29fd18209d7e67185cdb037b0f0b1c87b | C++ | wangxiaobai-dd/MyRep | /cpp/TestPythonInvoke/py2cppboostclass.cpp | UTF-8 | 442 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive |
#include <boost/python.hpp>
using namespace boost::python;
class Test
{
public:
int Add(const int x, const int y)
{
return x + y;
}
int Del(const int x, const int y)
{
return x - y;
}
};
BOOST_PYTHON_MODULE(test3)
{
class_<Test>("Testt")
.def("Add", &Test::Add)
.def("Del", &Test::Del);
}
/*
* 两种方法
* test3.Testt.Add(test3.Testt(),1,2)
*
* test = test3.Test()
* test.Add(1,2)
*/
| true |
03bd0910038719f979dd58fb32709620d6470604 | C++ | galin-kostadinov/Software-Engineering | /C++/C++ Fundamentals Sept 2019/05. STRINGS AND STREAMS/codecpp/src/CompareArraysAgain.cpp | UTF-8 | 1,115 | 3.921875 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include<string>
#include<sstream>
#include<vector>
void read(std::vector<int> &numbers, const std::string line) {
std::istringstream lineStream(line);
int currentNumber;
while (lineStream >> currentNumber) {
numbers.push_back(currentNumber);
}
}
bool areEqual(std::vector<int> &firstArr, std::vector<int> &secondArr) {
int sizeFirstArr = (int) firstArr.size();
int sizeSecondArr = (int) secondArr.size();
if (sizeFirstArr != sizeSecondArr) {
return false;
} else {
for (int i = 0; i < sizeFirstArr; ++i) {
if (firstArr[i] != secondArr[i]) {
return false;
}
}
}
return true;
}
int main() {
std::string line;
std::vector<int> firstArray;
std::vector<int> secondArray;
std::getline(std::cin, line);
read(firstArray, line);
std::getline(std::cin, line);
read(secondArray, line);
if (areEqual(firstArray, secondArray)) {
std::cout << "equal" << std::endl;
} else {
std::cout << "not equal" << std::endl;
}
return 0;
} | true |
a4347becc77d7e98ff99055dc330484b6f7d6003 | C++ | jamiemott/Ant | /Validation.cpp | UTF-8 | 1,755 | 3.5 | 4 | [] | no_license | #include "Validation.hpp"
#include <iostream>
#include <string>
#include <sstream>
using std::istringstream;
using std::string;
using std::istream;
using std::cout;
using std::cin;
using std::endl;
using std::getline;
/*This defines the getline() function used to check the user
input. If it can pull in data, convert to an int and there is
no remainder, it passes the data to the inputValidate function.
Citation: www.cplusplus.com/forum/beginner/170685/#msg851160*/
istream& getline(istream& ins, int& n)
{
n = 0;
// Read a line from the user
string s;
if (getline(ins, s))
{
// Get rid of any following whitespace
s.erase(s.find_last_not_of(" \f\n\r\t\v") + 1);
// Convert it to integer
istringstream ss(s);
ss >> n;
// Make sure nothing else is in the stream
if (!ss.eof())
ins.setstate(std::ios::failbit);
}
//Value is used by inputValidate()
return ins;
}
/*This function returns a validated integer choice from the user input.
It takes two integers, representing the lower and upper bounds of the
allowed input and compares the user input to the allowed range. If the
input is incorrect, it asks the user to try again. If getline() cannot
convert the user input to an integer, it also asks them to try again.*/
int inputValidate(int lower, int upper)
{
int userInput = 0; //placeholder for user input
int bottomRange = lower; //integer below acceptable range
int topRange = upper; //integer above acceptable range
while (!getline(cin, userInput) || (userInput < bottomRange) || (userInput > topRange))
{
cin.clear();
cout << "That was invalid. Please enter an integer from " << bottomRange << " to " << topRange << ": ";
}
return userInput;
} | true |
9db1f3c60ef277eec662224b7bde1e760992cb27 | C++ | Robotonics/nikos | /firmware/PlainFFT.cpp | UTF-8 | 5,465 | 2.90625 | 3 | [
"MIT"
] | permissive | /*
PlainFFT Library
No warranty, no claims, just fun
Didier Longueville invenit et fecit October 2010
Modified by Ted Hayes 2011 to use only Hamming windowing to optimize compiled object size.
*/
#include "PlainFFT.h"
#define twoPi 6.28318531
#define fourPi 12.56637061
PlainFFT::PlainFFT(void) {
// Constructor
}
PlainFFT::~PlainFFT(void){
// Destructor
}
uint8_t PlainFFT::revision(void){
return(FFT_LIB_REV);
}
void PlainFFT::compute(double *vReal, double *vImag, uint16_t samples, uint8_t dir) {
// Computes in-place complex-to-complex FFT
// Reverse bits
uint16_t j = 0;
for (uint16_t i = 0; i < (samples - 1); i++) {
if (i < j) {
swap(&vReal[i], &vReal[j]);
swap(&vImag[i], &vImag[j]);
}
uint16_t k = (samples >> 1);
while (k <= j) {
j -= k;
k >>= 1;
}
j += k;
}
// Compute the FFT
double c1 = -1.0;
double c2 = 0.0;
uint8_t l2 = 1;
for (uint8_t l = 0; l < exponent(samples); l++) {
uint8_t l1 = l2;
l2 <<= 1;
double u1 = 1.0;
double u2 = 0.0;
for (j = 0; j < l1; j++) {
for (uint16_t i = j; i < samples; i += l2) {
uint16_t i1 = i + l1;
double t1 = u1 * vReal[i1] - u2 * vImag[i1];
double t2 = u1 * vImag[i1] + u2 * vReal[i1];
vReal[i1] = vReal[i] - t1;
vImag[i1] = vImag[i] - t2;
vReal[i] += t1;
vImag[i] += t2;
}
double z = (u1 * c1) - (u2 * c2);
u2 = (u1 * c2) + (u2 * c1);
u1 = z;
}
c2 = sqrt((1.0 - c1) / 2.0);
if (dir == FFT_FORWARD) c2 = -c2;
c1 = sqrt((1.0 + c1) / 2.0);
}
// Scaling for forward transform
if (dir == FFT_FORWARD) {
for (uint16_t i = 0; i < samples; i++) {
vReal[i] /= samples;
vImag[i] /= samples;
}
}
}
void PlainFFT::complexToMagnitude(double *vReal, double *vImag, uint16_t samples) {
// vM is half the size of vReal and vImag
for (uint8_t i = 0; i < samples; i++) vReal[i] = sqrt((vReal[i]*vReal[i]) + (vImag[i]*vImag[i]));
}
void PlainFFT::windowing(double *vData, uint16_t samples) {
// Weighing factors are computed once before multiple use of FFT
// The weighing function is symetric; half the weighs are recorded
double samplesMinusOne = (double(samples) - 1.0);
for (uint16_t i = 0; i < (samples >> 1); i++) {
double indexMinusOne = double(i);
double ratio = (indexMinusOne / samplesMinusOne);
double weighingFactor = 1.0;
// compute and record weighting factor
weighingFactor = 0.54 - (0.46 * cos(twoPi * ratio));
vData[i] *= weighingFactor;
vData[samples - (i + 1)] *= weighingFactor;
}
}
String PlainFFT::majorPeakFrequency(double *vD, uint16_t samples, double samplingFrequency) {
double amp;
int ind;
String result = "";
double maxY = 2;
double maxY2 = 1;//dikom
double maxY3 = 0;//dik
int IndexOfMaxY = 0;
int IndexOfMaxY2 = 0;//dikom
int IndexOfMaxY3 = 0;//dikom
for (uint16_t i = 1; i < ((samples >> 1) - 1); i++) {
if ((vD[i-1] < vD[i]) && (vD[i] > vD[i+1])) {
if(vD[i] >= maxY3){
maxY3 = vD[i];
IndexOfMaxY3 = i;
}
if(vD[i] >= maxY2){
amp = maxY3;
ind = IndexOfMaxY3;
maxY3 = maxY2;
IndexOfMaxY3 = IndexOfMaxY2;
maxY2 = vD[i];
IndexOfMaxY2 = i;
if (vD[i] >= maxY) {
maxY3 = amp;
IndexOfMaxY3 = ind;
maxY2 = maxY;
IndexOfMaxY2 = IndexOfMaxY;
maxY = vD[i];
IndexOfMaxY = i;
}
}
}
}
double delta1 = 0.5 * ((vD[IndexOfMaxY-1] - vD[IndexOfMaxY+1]) / (vD[IndexOfMaxY-1] - (2.0 * vD[IndexOfMaxY]) + vD[IndexOfMaxY+1]));
double interpolatedX = ((IndexOfMaxY + delta1) * samplingFrequency) / (samples-1);
// retuned value: interpolated frequency peak apex
double delta2 = 0.5 * ((vD[IndexOfMaxY2-1] - vD[IndexOfMaxY2+1]) / (vD[IndexOfMaxY2-1] - (2.0 * vD[IndexOfMaxY2]) + vD[IndexOfMaxY2+1]));
double interpolatedX2 = ((IndexOfMaxY2 + delta2) * samplingFrequency) / (samples-1);
////////////////////////////////////////
double delta3 = 0.5 * ((vD[IndexOfMaxY3-1] - vD[IndexOfMaxY3+1]) / (vD[IndexOfMaxY3-1] - (2.0 * vD[IndexOfMaxY3]) + vD[IndexOfMaxY3+1]));
double interpolatedX3 = ((IndexOfMaxY3 + delta3) * samplingFrequency) / (samples-1);
result = "|" + String(int(interpolatedX)) + "," + String(int(interpolatedX2)) + "," + String(int(interpolatedX3)) + "," + String(int((10*log(maxY)))) + "," + String(int((10*log(maxY2)))) + "," + String(int((10*log(maxY3))));
return(result); //to allaksa ki evala allo return
}
double PlainFFT::majorPeakIndex(double *vD, uint16_t samples, double samplingFrequency) {
double maxY = 0;
int IndexOfMaxY = 0;
for (uint16_t i = 1; i < ((samples >> 1) - 1); i++) {
if ((vD[i-1] < vD[i]) && (vD[i] > vD[i+1])) {
if (vD[i] > maxY) {
maxY = vD[i];
IndexOfMaxY = i;
}
}
}
double delta = 0.5 * ((vD[IndexOfMaxY-1] - vD[IndexOfMaxY+1]) / (vD[IndexOfMaxY-1] - (2.0 * vD[IndexOfMaxY]) + vD[IndexOfMaxY+1]));
double interpolatedX = ((IndexOfMaxY + delta) * samplingFrequency) / (samples-1);
// retuned value: interpolated frequency peak apex
//return(interpolatedX); //to allaksa ki evala allo return
return (IndexOfMaxY);
}
void PlainFFT::printMagnitudes(double *vM, uint16_t samples){
for (uint16_t i = 1; i < ((samples >> 1) - 1); i++) {
Serial.print(vM[i]);
Serial.print("\t");
}
}
/* Private */
void PlainFFT::swap(double *x, double *y) {
double temp = *x;
*x = *y;
*y = temp;
}
uint8_t PlainFFT::exponent(uint16_t value) {
// computes the exponent of a powered 2 value
uint8_t result = 0;
while (((value >> result) & 1) != 1) result++;
return(result);
}
| true |
9905b29c20759301b4f5b7367c546e1a765b2c4e | C++ | ivycorinne/Arduino | /debounceWithTimer/debounceWithTimer.ino | UTF-8 | 3,506 | 3.34375 | 3 | [] | no_license |
int i;
/*
timer de-bounce
When the pushbutton is bouncing, Arduino sees a rapid sequence of
on and off signals.
There are many techniques developed to do de-bouncing.
Here, we will attempt to de-bounce using a timer.
Turn on and off a LED connected to a digital pin, without using
the delay() function. This means that other code can run
at the same time without being interrupted by the LED code.
https://www.arduino.cc/en/Reference/Constants
*/
const int LED = 13; // LED connected to digital pin 13
const int BUTTON = 7; // pushbutton is connected to input pin 7
int val = 0; // store the state of the input pin
int old_val = 0; // stores previous value of 'val'
int state = 0; // stores current state 0 = off and 1 = on
int hold = 0;
// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long lastDebounceTime = 0; // will store last time LED was updated
const long debounceTimer = 500; // interval for button press (milliseconds)
void setup() {
pinMode(LED, OUTPUT); // initialize digital pin 13 as output.
pinMode(BUTTON, INPUT); // initialize pin 7 as input
Serial.begin(9600);
}
void loop() {
val = digitalRead(BUTTON); // read input value and store it
Serial.println(val); // only reads '1' when button is pressed
// check if there was any change
if ((val == HIGH) && (old_val == LOW)) {
// then start the clock
unsigned long currentMillis = millis();
// insert this line here, which uses
// the Arduino clock. millis() returns
// how many milliseconds have passed since
// the board has been reset.
// next, check to see if the time has exceeded our threshhold
// (the difference between the current time and last time we checked)
if (currentMillis - lastDebounceTime > debounceTimer) {
// save the last time the LED was on
lastDebounceTime = currentMillis;
state = 1 - state;
// we removed the delay() function that was here...
}
}
if ((val == HIGH) && (old_val == HIGH)) {
// then start the clock
unsigned long currentMillis = millis();
// insert this line here, which uses
// the Arduino clock. millis() returns
// how many milliseconds have passed since
// the board has been reset.
// next, check to see if the time has exceeded our threshhold
// (the difference between the current time and last time we checked)
if (currentMillis - lastDebounceTime > debounceTimer) {
// save the last time the LED was on
lastDebounceTime = currentMillis;
hold = 1;
// we removed the delay() function that was here...
}
}
old_val = val; // val is now old, let's store it
// check whether input is HIGH (button pressed)
if (state == 1) {
digitalWrite(LED, HIGH); // turn the LED on
}
else if (hold == 1) {
for (i = 0; i < 255; i++) {
analogWrite(LED, i);
delay(10);
}
for (i = 255; i > 0; i--) {
analogWrite(LED, i);
delay(10);
}
hold = 0;
}
else {
digitalWrite(LED, LOW); // turn the LED off
}
}
| true |
c7b0b2e3fab0e3dd0b2a55e0e463c608bfe5f24e | C++ | fredollinger/kscope | /kscope-binary-only-works-on-lucid/include/kregexp.h | UTF-8 | 3,957 | 2.75 | 3 | [] | no_license | /* This file is part of the KDE libraries
Copyright (c) 1999 Torben Weis <weis@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef __kregexp_h__
#define __kregexp_h__
#include "kdelibs_export.h"
class KRegExpPrivate;
/**
* @deprecated
* Please use QRegExp instead.
*
* Regular expression (regexp) matching with back-references.
*
* This was implemented
* because QRegExp did not support back-references. It now does and
* is recommended over KRegExp because of the unicode support and the
* more powerful API.
*
* Back-references are parts of a regexp grouped with parentheses. If a
* string matches the regexp, you can access the text that matched each
* group with the group method. This is similar to regular expressions
* in Perl.
*
* Example:
* \code
* KRegExp ex( "([A-Za-z]+) (.+)" );
* ex.match( "42 Torben Weis" );
* kdDebug() << ex.group(0) << endl;
* kdDebug() << ex.group(1) << endl;
* kdDebug() << ex.group(2) << endl;
* \endcode
* Output:
* \code
* Torben Weis
* Torben
* Weis
* \endcode
*
* Please notice that KRegExp does @em not support unicode.
*
* @author Torben Weis <weis@kde.org>
*/
class KDECORE_EXPORT KDE_DEPRECATED KRegExp
{
public:
/**
* Creates a KRegExp object without a default pattern.
*/
KRegExp();
/**
* Creates a KRegExp object.
* @param _pattern The regular expression to use for matches.
* @param _mode If this is "i", case-insensitive matches will be
* performed.
*/
KRegExp( const char *_pattern, const char *_mode = "" );
~KRegExp();
/**
* Prepare a regular expression for subsequent matches.
* @param _pattern The regular expression to use for matches.
* @param _mode If this is "i", case-insensitive matches will be
* performed.
* @return bool if successful.
*/
bool compile( const char *_pattern, const char *_mode = "" );
/**
* Match a string to the last supplied regexp.
* @param _string the string to match
* @return @p true on match, false otherwise.
*/
bool match( const char *_string );
/**
* Returns a group from the match.
*
* @param _grp May be in the range [0..9]. If @p _grp is 0 then the complete
* matched string is returned.
* @return a grouped substring. A substring may be empty.
* In this case 0 is returned. Otherwise you may @em not
* delete or modify the returned value. In addition the
* returned value becomes invalid after the KRegExp instance
* is deleted or after match() was called again.
*/
const char *group( int _grp );
/**
* The offset of the given group in the string.
* @param _grp May be in the range [0..9]. If @p _grp is 0 then the start offset
* of the complete matched string is returned.
* @return The start offset of the grouped substring.
*/
int groupStart( int _grp );
/**
* The offset of the given group's end in the string.
* @param _grp May be in the range [0..9]. If @p _grp is 0 then the end offset
* of the complete matched string is returned.
* @return The end offset of the grouped substring. The "end offset" is the first
* character after the string.
*/
int groupEnd( int _grp );
private:
KRegExpPrivate *m_pPrivate;
};
#endif
| true |
4a8d96827c7e1af1528da19c138d181b88887c46 | C++ | tectronics/cse167chinook | /HeightMap.cpp | UTF-8 | 12,379 | 2.578125 | 3 | [] | no_license | #include "HeightMap.h"
//const float HeightMap::WATERLEVEL = 80.f;
const float HeightMap::WATERLEVEL = 105.f;
const float HeightMap::SANDLEVEL = 110.f;
const float HeightMap::GRASSLEVEL = 160.f;
const float HeightMap::DIRTLEVEL = 220.f;
const float HeightMap::MAXLEVEL = 256.f;
Vector3 HeightMap::dwater(0,0,100/256.f);
Vector3 HeightMap::water(0,0,256/256.f);
Vector3 HeightMap::sand(240/256.f,230/256.f,140/256.f);
Vector3 HeightMap::grass(0x32/256.f,0x4F/256.f,0x17/256.f);
Vector3 HeightMap::dirt(0x5C/256.f,0x40/256.f,0x33/256.f);
Vector3 HeightMap::snow(1,1,1);
float HeightMap::CITY_LEFT;
float HeightMap::CITY_RIGHT;
float HeightMap::CITY_BACK;
float HeightMap::CITY_FRONT;
float HeightMap::ROAD_LEFT;
float HeightMap::ROAD_RIGHT;
bool HeightMap::ENABLE_QUADTREE = false;
bool HeightMap::RENDER_FLATGREY = false;
bool SCALE_HEIGHT = false;
const int CITY_DIM = 100;
HeightMap::HeightMap(void)
{
rawData = PerlinGen::genNoise();
width = depth = (1 << PerlinGen::DEFAULTDIM) + 1;
scale = (SkyBox::SKYBOXSIZE*1.05)/(width-1.f);
setup();
}
HeightMap::HeightMap(char* fileName)
{
string my_string(fileName);
rawData = PGMLoader::loadPGM(my_string, width, depth);
setup();
}
HeightMap::HeightMap(int dim, int max, float smoothness)
{
rawData = PerlinGen::genNoise( dim, max, smoothness);
width = depth = (1 << dim) + 1;
scale = SkyBox::SKYBOXSIZE/(width-1)*1.01;
setup();
}
void HeightMap::setup()
{
//adjustForCity(); //raise city area
//adjustForRoad(); //raise road area
nVerts = 3*width*depth;
vertices = new float[nVerts];
nIndices = 6*(width-1)*(depth-1);
indices = new int[nIndices];
colors = new float[nVerts];
CITY_LEFT = (width / 2) * scale;
CITY_RIGHT = CITY_LEFT + CITY_DIM;
CITY_BACK = (depth / 2) * scale;
CITY_FRONT = CITY_BACK + CITY_DIM;
ROAD_LEFT = CITY_LEFT + CITY_DIM / 4;
ROAD_RIGHT = ROAD_LEFT + CITY_DIM / 4;
for(int i=0; i<width; i++)
{
for(int j=0; j<depth; j++)
{
int RED_INDEX, GREEN_INDEX, BLUE_INDEX, X_INDEX, Y_INDEX, Z_INDEX;
RED_INDEX = X_INDEX = 3*(i*depth+j);
GREEN_INDEX = Y_INDEX = RED_INDEX + 1;
BLUE_INDEX = Z_INDEX = RED_INDEX + 2;
vertices[X_INDEX] = -scale*(j-(width-1)/2.f);
float cheight = rawData[i*depth+j];
//printf("cheight=%f\n", cheight);
vertices[Y_INDEX] = cheight;
if (SCALE_HEIGHT)
vertices[Y_INDEX] = cheight * scale - WATERLEVEL * (scale - 1);
vertices[Z_INDEX] = -scale*(i-(width-1)/2.f);
float X = i * scale;
float Z = j * scale;
//color coding
if(cheight < WATERLEVEL)
{
//dark -> light water level
colors[RED_INDEX] = 0.f; //(1-cheight/WATERLEVEL)*dwater[0] + (cheight/WATERLEVEL)*water[0]
colors[GREEN_INDEX] = 0.f; //(1-cheight/WATERLEVEL)*dwater[1] + (cheight/WATERLEVEL)*water[1]
colors[BLUE_INDEX] =(1-cheight/WATERLEVEL)*dwater[2] + (cheight/WATERLEVEL)*water[2];
vertices[Y_INDEX] = WATERLEVEL; //flatten to water's surface
} else if(cheight < SANDLEVEL) {
// sand level
colors[RED_INDEX] = (cheight-WATERLEVEL)/SANDLEVEL*grass[0]+(1-(cheight-WATERLEVEL)/SANDLEVEL)*sand[0];
colors[GREEN_INDEX] = (cheight-WATERLEVEL)/SANDLEVEL*grass[1]+(1-(cheight-WATERLEVEL)/SANDLEVEL)*sand[1];
colors[BLUE_INDEX] = (cheight-WATERLEVEL)/SANDLEVEL*grass[2]+(1-(cheight-WATERLEVEL)/SANDLEVEL)*sand[2];
}
else if (X >= CITY_LEFT && X <= CITY_RIGHT && Z >= CITY_BACK && Z <= CITY_FRONT && cheight < GRASSLEVEL)
{
colors[RED_INDEX] = colors[GREEN_INDEX] = colors[BLUE_INDEX] = .3;
}
else if (X >= ROAD_LEFT && X <= ROAD_RIGHT && cheight < DIRTLEVEL) {
colors[RED_INDEX] = colors[GREEN_INDEX] = colors[BLUE_INDEX] = .25;
}
else if(cheight < GRASSLEVEL) {
//grass -> dirt level
colors[RED_INDEX] = (cheight-SANDLEVEL)/GRASSLEVEL*dirt[0]+(1-(cheight-SANDLEVEL)/GRASSLEVEL)*grass[0];
colors[GREEN_INDEX] = (cheight-SANDLEVEL)/GRASSLEVEL*dirt[1]+(1-(cheight-SANDLEVEL)/GRASSLEVEL)*grass[1];
colors[BLUE_INDEX] = (cheight-SANDLEVEL)/GRASSLEVEL*dirt[2]+(1-(cheight-SANDLEVEL)/GRASSLEVEL)*grass[2];
} else if(cheight < DIRTLEVEL) {
//dirt -> snow level
colors[RED_INDEX] = (cheight-GRASSLEVEL)/DIRTLEVEL*snow[0]+(1-(cheight-GRASSLEVEL)/DIRTLEVEL)*dirt[0];
colors[GREEN_INDEX] = (cheight-GRASSLEVEL)/DIRTLEVEL*snow[1]+(1-(cheight-GRASSLEVEL)/DIRTLEVEL)*dirt[1];
colors[BLUE_INDEX] = (cheight-GRASSLEVEL)/DIRTLEVEL*snow[2]+(1-(cheight-GRASSLEVEL)/DIRTLEVEL)*dirt[2];
} else {
//snow
colors[RED_INDEX] = 1.f;
colors[GREEN_INDEX] = 1.f;
colors[BLUE_INDEX] = 1.f;
}//end color coding
}
}
for(int i=0; i<width-1; i++)
{
for(int j=0; j<(depth-1); j++)
{
int topLeft = i*depth+j;
int bottomLeft = (i+1)*depth+j;
int bottomRight = (i+1)*depth+(j+1);
int topRight = i*depth+(j+1);
int start = 6*(i*(depth-1)+j);
indices[start] = topLeft;
indices[start+1] = bottomLeft;
indices[start+2] = bottomRight;
indices[start+3] = topLeft;
indices[start+4] = bottomRight;
indices[start+5] = topRight;
}
}
//tree = new QuadTree(rawData, width);
//quadIndices = tree->generateQuadList();
}
void HeightMap::adjustForCity() {
//raise city area above sea level, if necessary
int cityVerts = CITY_DIM / scale + 1;
int cityLeft = (width/* + CITY_DIM / scale*/) / 2;
int cityTop = (depth/* + CITY_DIM / scale*/) / 2;
/*float lowest = GRASSLEVEL;
for (int i = 0; i < cityVerts; i++)
for (int j = 0; j < cityVerts; j++) {
float h = rawData[(i+cityLeft)*depth + (j+cityTop)];
if (h < lowest)
lowest = h;
}
if (lowest < GRASSLEVEL)
for (int i = 0; i < cityVerts; i++)
for (int j = 0; j < cityVerts; j++)
rawData[(i+cityLeft)*depth + (j+cityTop)] += GRASSLEVEL - lowest;*/
float lowest = SANDLEVEL;
for (int i = 0; i < cityVerts; i++)
for (int j = 0; j < cityVerts; j++) {
int index = (i+cityLeft)*depth + (j+cityTop);
if (rawData[index] < lowest)
rawData[index] = lowest;
}
}
void HeightMap::adjustForRoad() { //doesn't seem to work?
int cityVerts = CITY_DIM / scale + 1;
int roadLeft = width / 2 + cityVerts / 4 + 1;
int roadWidth = cityVerts / 4 + 1;
float lowest = SANDLEVEL;
for (int j = 0; j < depth; j++)
for (int i = 0; i < roadWidth; i++) {
int vertIndex = (i + roadLeft) * depth + j;
if (rawData[vertIndex] < lowest)
rawData[vertIndex] = lowest;
}
}
void HeightMap::draw(Matrix4 &t1)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glMultMatrixf(t1.getPointer());
glDisable(GL_LIGHTING);
TextureManager::unbind();
if (ENABLE_QUADTREE)
drawTree();
else if(RENDER_FLATGREY)
drawBasic();
else
drawAdvanced();
glEnable(GL_LIGHTING);
glPopMatrix();
}
void HeightMap::drawTree() {
//glBegin(GL_QUADS);
//int totalIndices = quadIndices.totalQuads << 2;
//for (int i = 0; i< totalIndices; i++) {
// Vector3 vert = quadIndices.indices[i];
// Vector3 renderVert;
// renderVert.x = (vert.x - width/2) * scale;
// if (SCALE_HEIGHT)
// renderVert.y = (vert.y - WATERLEVEL) * scale;
// else
// renderVert.y = vert.y;
// renderVert.z = (vert.z - depth/2) * scale;
// drawVert(renderVert);
//}
// glEnd();
}
void HeightMap::drawAdvanced()
{
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(3, GL_FLOAT, 0, colors);
glVertexPointer(3, GL_FLOAT, 0, vertices);
// draw
glDrawElements(GL_TRIANGLES, nIndices, GL_UNSIGNED_INT, indices);
// deactivate vertex arrays after drawing
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
}
void HeightMap::drawBasic() {
/* start drawing triangles, each triangle takes 3 vertices */
glBegin(GL_TRIANGLES);
for(int i=0; i<nIndices; i+=3)
for(int j=0; j<3; j++) {
Vector3 vert(vertices[3*indices[i+j]], vertices[3*indices[i+j]+1],vertices[3*indices[i+j]+2]);
Vector3 color(colors[3*indices[i+j]], colors[3*indices[i+j]+1], colors[3*indices[i+j]+2]);
drawVert(vert, color);
}
glEnd();
}
void HeightMap::drawVert(Vector3 vert) {
float cheight = vert.y;
if (SCALE_HEIGHT)
cheight = cheight/ scale + WATERLEVEL;
if (RENDER_FLATGREY) {
float grey = cheight / MAXLEVEL;
glColor3f(grey, grey, grey);
glVertex3f(vert.x, 0, vert.z);
return;
}
if(cheight < WATERLEVEL){
//dark -> light water level
glColor3f(0.f,0.f, (1-cheight/WATERLEVEL)*dwater[2] + (cheight/WATERLEVEL)*water[2]);
} else if(cheight < SANDLEVEL) {
// sand level
glColor3f((cheight-WATERLEVEL)/SANDLEVEL*grass[0]+(1-(cheight-WATERLEVEL)/SANDLEVEL)*sand[0], (cheight-WATERLEVEL)/SANDLEVEL*grass[1]+(1-(cheight-WATERLEVEL)/SANDLEVEL)*sand[1],(cheight-WATERLEVEL)/SANDLEVEL*grass[2]+(1-(cheight-WATERLEVEL)/SANDLEVEL)*sand[2]);
} else if(cheight < GRASSLEVEL) {
//grass -> dirt level
glColor3f((cheight-SANDLEVEL)/GRASSLEVEL*dirt[0]+(1-(cheight-SANDLEVEL)/GRASSLEVEL)*grass[0], (cheight-SANDLEVEL)/GRASSLEVEL*dirt[1]+(1-(cheight-SANDLEVEL)/GRASSLEVEL)*grass[1],(cheight-SANDLEVEL)/GRASSLEVEL*dirt[2]+(1-(cheight-SANDLEVEL)/GRASSLEVEL)*grass[2]);
} else if(cheight < DIRTLEVEL) {
//dirt level
glColor3f((cheight-GRASSLEVEL)/DIRTLEVEL*snow[0]+(1-(cheight-GRASSLEVEL)/DIRTLEVEL)*dirt[0], (cheight-GRASSLEVEL)/DIRTLEVEL*snow[1]+(1-(cheight-GRASSLEVEL)/DIRTLEVEL)*dirt[1],(cheight-GRASSLEVEL)/DIRTLEVEL*snow[2]+(1-(cheight-GRASSLEVEL)/DIRTLEVEL)*dirt[2]);
} else {
//snow
glColor3f(1.f,1.f,1.f);
}
if(cheight < WATERLEVEL)
glVertex3f(vert.x, WATERLEVEL, vert.z);
else
glVertex3f(vert.x, vert.y, vert.z);
}
void HeightMap::drawVert(Vector3 vert, Vector3 color) {
float cheight = vert.y;
if (RENDER_FLATGREY) {
float grey = cheight / MAXLEVEL;
glColor3f(grey, grey, grey);
glVertex3f(vert.x, 0, vert.z);
return;
}
glColor3f(color.x, color.y, color.z);
if(cheight < WATERLEVEL)
glVertex3f(vert.x, WATERLEVEL, vert.z);
else
glVertex3f(vert.x, vert.y, vert.z);
}
float HeightMap::getHeightAt(int x, int z)
{
int j = x/scale + (width-1)/2.0f;
int i = -z/scale + (width-1)/2.0f;
int topLeft = i*depth + j;
float htopLeft = rawData[topLeft]; //top left
if(htopLeft < WATERLEVEL)
htopLeft = WATERLEVEL;
float htopRight = rawData[topLeft + 1]; //top right
if(htopRight < WATERLEVEL)
htopRight = WATERLEVEL;
float hbotLeft = rawData[topLeft + depth]; //bottom left
if(hbotLeft < WATERLEVEL)
hbotLeft = WATERLEVEL;
float hbotRight = rawData[topLeft + depth + 1]; //bottom right
if(hbotRight < WATERLEVEL)
hbotRight = WATERLEVEL;
//find the unit distance of the point from the vertex.
float xFrag = (x/scale) - int(x/scale); //x distance
float zFrag = (z/scale) - int(z/scale); //z distance
if(xFrag < 0) xFrag++;
if(zFrag <= 0) zFrag++;
//printf("xfrag %f\n", xFrag);
//printf("zfrag %f\n", zFrag);
float interpolatedValue = 0;
if(zFrag == 1)
interpolatedValue = xFrag*htopRight + (1-xFrag)*htopLeft;
else if(xFrag+zFrag < 1) //left
interpolatedValue = baryCentric(Vector3(0,1,1), htopLeft, Vector3(0,0,1), hbotLeft, Vector3(1,0,1),hbotRight, xFrag, zFrag);
else //right
interpolatedValue = baryCentric(Vector3(0,1,1), htopLeft, Vector3(1,1,1), htopRight, Vector3(1,0,1),hbotRight, xFrag, zFrag);
//if(interpolatedValue < WATERLEVEL)
// return WATERLEVEL;
if (SCALE_HEIGHT)
return interpolatedValue * scale;
return interpolatedValue;
}
float HeightMap::baryCentric(Vector3 vert1, float hvert1, Vector3 vert2, float hvert2, Vector3 vert3, float hvert3, float x, float y)
{
float g1, g2, g3;
g1 = ((vert2.get(1)-vert3.get(1))*(x-vert3.get(0))+(vert3.get(0)-vert2.get(0))*(y-vert3.get(1))) / ((vert2.get(1)-vert3.get(1))*(vert1.get(0)-vert3.get(0))+(vert3.get(0)-vert2.get(0))*(vert1.get(1)-vert3.get(1)));
g2 = ((vert3.get(1)-vert1.get(1))*(x-vert3.get(0))+(vert1.get(0)-vert3.get(0))*(y-vert3.get(1))) / ((vert3.get(1)-vert1.get(1))*(vert2.get(0)-vert3.get(0))+(vert1.get(0)-vert3.get(0))*(vert2.get(1)-vert3.get(1)));
g3 = 1 - g1 - g2;
return hvert1*g1+hvert2*g2+hvert3*g3;
} | true |
6826b2221632f70c8b015caa2094f164efd052ff | C++ | jeremiemartel/Arduino | /docs/ST/Codes arduino/Grove_Buzzer/Grove_Buzzer.ino | UTF-8 | 1,250 | 3.15625 | 3 | [] | no_license | // Objectif :
// - Emettre une alarme en appuyant sur le bouton "USER"
// - Afficher un message sur le LCD
// Attention : le shield Grove doit être positionné sur 5V (pou le LCD)
// Pour gérer le LCD
#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;
const int BUZZER_PIN = 6; // broche du buzzer D6
const int color = 255; // compposante couleur
void setup()
{
pinMode(BUZZER_PIN, OUTPUT); // Initialisation broche Buzzer
pinMode(USER_BTN,INPUT); // Initialisation broche du bouton utilisateur
lcd.begin(16, 2); // nombre de colonnes et lignes du LCD
lcd.setRGB(0, color, 0); // couleur de fond du LCD : vert
}
void loop()
{
if(digitalRead(USER_BTN) == RESET) // Si le bouton est appuyé
{
// attends jusqu'à ce qu'il soit relâché
while (digitalRead(USER_BTN) == RESET);
lcd.setRGB( color, 0, 0); // couleur de fond du LCD : rouge
lcd.print("Alarm!"); // écrit un message sur le LCD
lcd.display(); // affiche le message
// alarme sur le buzzer
digitalWrite(BUZZER_PIN, HIGH);
delay(analogRead(0));
digitalWrite(BUZZER_PIN, LOW);
delay(analogRead(0));
lcd.setRGB(0, color, 0); // couleur de fond du LCD : vert
lcd.noDisplay(); // cesse d'afficher
}
}
| true |
6527d08e61ec35f4fc0e1ba376d7fe12c5cb9e78 | C++ | sonuishaq67/cprograms | /basic/j.cpp | UTF-8 | 242 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a = { 1, 7, 2, 4, 8, 3 };
qsort(a.begin(), a.end());
for (int i; i < a.size(); i++)
std::cout << a[i] << " ";
return 0;
}
| true |
1937a3d7ec97b1d6e1ba7a2cfa5155e7c167fbe7 | C++ | archetype2142/cpp-projects | /do_while_loop_try_1.cpp | UTF-8 | 502 | 3.3125 | 3 | [] | no_license | // do while
#include <iostream>
using namespace std;
int main()
{
int a = 0; // a is zero
do //then do loop executesok comes back here
{
a++; //a becomes 1
cout << "abc" << endl; // this executes this executes
}
while( a < 7); //lets try samaj aaya? haan tabhi abc 3 baar aaya na yes now tell how many times it will come a is less than 3 is true still true it is like 0 , 1, 2 starts from zero goes till 2 2 is less than 3
return 0;
}//oops we did an infinite loop check for mistakes | true |
ab4c69e6737004e6d4de92226bdf47658c579aef | C++ | junyoung-o/PS-Cpp | /BFS & DFS/1012.cpp | UTF-8 | 1,648 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
#define max_node 51 * 51 + 1
vector<int> graph[max_node];
vector<int> result;
bool is_visit[max_node] = { false, };
bool is_one[max_node] = { false, };
int m, n, k, cnt;
void init();
void set_graph();
void point_one();
void bfs(int node);
int main(void) {
int test_case;
cin >> test_case;
for(int test = 0; test < test_case; test++) {
init();
int local_result = 0;
cin >> m >> n >> k;
set_graph();
for(int i = 0; i < k; i++) {
point_one();
}
for(int i = 0; i < max_node; i++) {
if(is_visit[i] == false && is_one[i] == true) {
bfs(i);
local_result += 1;
}
}
result.push_back(local_result);
}
for(int i = 0; i < result.size(); i++) {
cout << result[i] << endl;
}
return 0;
}
void init() {
for(int i = 0; i < max_node; i++) {
graph[i].clear();
is_visit[i] = false;
is_one[i] = false;
}
m = n = k = 0;
}
void point_one() {
int x, y;
cin >> x >> y;
int node = y * m + (x + 1);
is_one[node] = true;
}
void set_graph() {
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int node = (j + 1) + i * m;
if(j > 0) {
graph[node].push_back(node - 1);
graph[node-1].push_back(node);
}
if(i > 0) {
graph[node].push_back(node - m);
graph[node - m].push_back(node);
}
}
}
}
void bfs(int node) {
if(is_visit[node] == true) {
return;
}
if(is_one[node] == false) {
return;
}
is_visit[node] = true;
for(int i = 0; i < graph[node].size(); i++) {
int next_node = graph[node][i];
if(is_visit[next_node] == false && is_one[next_node] == true) {
bfs(next_node);
}
}
} | true |
63821c007e9f268b049f1043cd137f39b332cdce | C++ | marcinn714/p2p | /applicationLogic/threads/TcpMainService.cpp | UTF-8 | 1,200 | 2.609375 | 3 | [] | no_license | //
// Created by marcin on 16.05.18.
//
#include "TcpMainService.h"
#include "../fileTables/FilesTableReceive.h"
Command * TcpMainService::getCommand(size_t opcode, int socketFd, struct in_addr sendingIp)
{
Command * command = nullptr;
switch(opcode){
case 31: //get file
command = new ReceiveFileTcp(socketFd);
break;
case 30: //get local files table
command = new FilesTableReceive(socketFd, sendingIp);
break;
default:
break;
}
return command;
}
void TcpMainService::tcpServiceLoop()
{
tcpCommunication->createAndConfigureSocket();
Command * command;
int msgsock, opcode;
struct sockaddr_in client;
while (true) {
if ((opcode = tcpCommunication->receiveOpcode(&msgsock, &client)) >= 0) {
command = getCommand(opcode, msgsock, client.sin_addr);
pthread_t thread;
pthread_create(&thread, NULL, Command::commandExeWrapper, static_cast<void *>(command));
pthread_detach(thread);
} else
break;
}
tcpCommunication->closeSocket();
}
void TcpMainService::execute(void)
{
tcpServiceLoop();
} | true |
fd672f58f73df1ff9582c0a547098df385fa5727 | C++ | EchelonBoo/A-E | /A_E/A_E.cpp | UTF-8 | 2,334 | 3.625 | 4 | [] | no_license | // A_E.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include "PriorityQueue.h"
#include <iostream>
#include <string>
using namespace std;
struct Patient {
string name;
int priority;
bool operator < (Patient p1)
{
return p1.priority > priority;
}
bool operator <= (Patient p1)
{
return p1.priority >= priority;
}
bool operator > (Patient p1)
{
return p1.priority < priority;
}
bool operator >= (Patient p1)
{
return p1.priority <= priority;
}
bool operator == (Patient p1)
{
return p1.priority == priority;
}
};
int main()
{
string x = "2";
int y = 0;
/*Patient p1 = { "Bethany",5 };
Patient p2 = { "Rachel",3 };
Patient p3 = { "Mike",5 };
Patient p4 = { "John",2 };
Patient p5 = { "Mary",1 };
Patient p6 = { "Jane",1 };
Patient p7 = { "Tom",3 };
Patient p8 = { "Kim",4 };
Patient p9 = { "Tim",1 };
Patient p10 = { "Shaun",2};*/
Patient p1 = { "Tom",3 };
Patient p2 = { "Mary",4 };
Patient p3 = { "Fred",3 };
Patient p4 = { "Sarah",1 };
Patient p5 = { "Ann",5 };
Patient p6 = { "Mike",4 };
Patient pUser { x , y };
PQType<Patient> pQueue(100); // have to enter a max int
pQueue.Enqueue(p1);
pQueue.Enqueue(p2);
pQueue.Enqueue(p3);
pQueue.Enqueue(p4);
pQueue.Enqueue(p5);
pQueue.Enqueue(p6);
/*pQueue.Enqueue(p7);
pQueue.Enqueue(p8);
pQueue.Enqueue(p9);
pQueue.Enqueue(p10);*/
//pQueue.Print();
int option = 0;
do
{
cout << "\n\n\t\t ******** A & E *********\n\n"
<< "\t\t1. Add Patient to queue.\n"
<< "\t\t2. Call Patient to appointment\n"
<< "\t\t3. Display all patients\n"
<< "\t\t4. Exit\n\n";
cin >> option;
cout << "You have chosen option: " << option << endl;
switch (option) {
case 1:
cout << "\nPlease enter the patients name: \n";
cin >> x;
cout << "\nPlease enter the patients A & E priority:\n";
cin >> y;
pUser.name = x;
pUser.priority = y;
pQueue.Enqueue(pUser); // adds the new user to the priority queue
break;
case 2:
pQueue.Dequeue(pUser); //Removes top item from the queue
break;
case 3:
pQueue.Print(); // prints contents of entire queue.
break;
case 4:
break; // exits program
default:
cout << "Invalid Option. Please choose again.\n";
break;
}
} while (option != 4);
}
| true |
1b6e1bd17af8160f36b0157ea184d2741ed0e3df | C++ | laszlopapai/UAVOnboardController | /UAV/Interact/Magnetometer.cpp | UTF-8 | 1,506 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #include "Magnetometer.h"
#include <Filter/MagnetometerFilter.h>
using namespace IoT::UAV;
Magnetometer::Magnetometer(const float outputFrequency)
: StreamNode<Core::Vector3>([this](auto& dataInfo) { this->run(dataInfo); })
, m_logger(Core::ILogger::getDefault())
, m_outputFrequency(outputFrequency)
, m_acquireDelay(0)
{ }
bool Magnetometer::initialize()
{
if (!m_magnetometer.initialize()) {
m_logger->log(Core::Error, "InputDevice", "Magnetometer initialize failed");
return false;
}
m_logger->log(Core::Info, "InputDevice", "Magnetometer frequency: " + std::to_string(m_magnetometer.getFrequency()));
m_filter = std::make_unique<Device::KalmanFilterVector3>(
0.05f,
0.0f,
0.5f * m_outputFrequency / m_magnetometer.getFrequency(),
0.0f,
1.0f
);
m_acquireDelay = 1e6f / m_magnetometer.getFrequency();
return true;
}
void Magnetometer::run(Core::DataInfo<Core::Vector3>& dataInfo)
{
const auto currentDelay = ellapsed();
if (currentDelay.getMicros() >= m_acquireDelay) {
m_magnetometer.acquire(dataInfo.m_data);
assert(!dataInfo.m_data.isNaN());
m_filter->filter(dataInfo.m_data);
if (currentDelay.getMicros() > m_acquireDelay * 2) {
m_logger->log(Core::Warning, "InputDevice", "Magnetometer delay was " +
std::to_string(currentDelay.getSecs<float>()) + "s. This is " +
std::to_string(currentDelay.getMicros() / m_acquireDelay) +
" times greater than the optimal!");
}
dataInfo.m_propagate = true;
}
else
dataInfo.m_propagate = false;
}
| true |