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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
399fafc168e4c039beb29bfd34f24c11a37b1ce9 | C++ | tistatos/complex-terrain | /include/terrain.h | UTF-8 | 1,938 | 2.65625 | 3 | [] | no_license | /**
* @file terrain.h
* @author Erik Sandrén
* @date 07-08-2016
* @brief Complex terrain
*/
#ifndef __TERRAIN_H__
#define __TERRAIN_H__
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <queue>
class Chunk;
class Camera;
class Terrain {
public:
Terrain();
void initialize(Camera* camera);
void render();
void update();
void pregenerateChunks();
void toggleRenderingBoundingBox() { mRenderBoundingBox = !mRenderBoundingBox; }
const unsigned int getCulledChunks() const { return mCulledChunks; }
const unsigned int getEmptyChunks() const { return mEmptyChunks; }
private:
void createShaders();
void invalidateChunkPositions();
void generateTextures();
void markOutOfBoundChunks();
void updateChunkPositions();
void generateChunks(bool limit);
void buildDensity(Chunk* c);
// method 1
void generateVertices(Chunk* c);
// method 2
bool listTriangles();
void generateVertices2(Chunk* c);
glm::ivec3 getCameraChunk() const;
glm::ivec3 getChunkIndex(const glm::vec3& position) const;
uint32_t getChunkArrayIndex(const glm::vec3& position) const;
// camera
Camera* mCamera;
glm::vec3 mLastCameraPosition;
glm::ivec3 mCameraChunk;
// textures
GLuint mDensityMap;
GLuint mTriTable;
// transform feedback for triangles
GLuint mTriangleListFeedbackObject;
GLuint mTriangleListFeedbackBuffer;
GLuint mTriangleListArrayObject;
// transform feedback for vertices
// GLuint mVertexFeedbackBuffer;
// GLuint mVertexFeedbackObject;
// GLuint mVertexFeedbackArrayObject;
// density generation points
GLuint mGeoVertexArrayObject;
GLuint mGeoBuffer;
// Vertex generation points
GLuint mGenVertexArrayObject;
GLuint mGenBuffer;
// list of all chunks
Chunk* mChunkList;
unsigned int mEmptyChunks;
unsigned int mCulledChunks;
// list of chunks to be generated
std::deque<Chunk*> mChunkLoadQueue;
// bool settings
bool mRenderBoundingBox;
/*glm::vec3* mChunkPositions;*/
};
#endif
| true |
1a26072f5b7e96695d868f908781380281ec37ae | C++ | lena390/webs | /Server/Serv.cpp | UTF-8 | 6,341 | 2.515625 | 3 | [] | no_license | #include "Serv.hpp"
Serv::Serv( void )
{
this->_port = 0;
this->_decodedBody = "";
}
Serv::Serv( int port, Inside & info )
{
this->_port = port;
this->_servInfo = info;
this->_decodedBody = "";
}
Serv::Serv( const Serv& serv )
{
this->_addr = serv._addr;
this->_port = serv._port;
this->_request = serv._request;
this->_servInfo = serv._servInfo;
this->_decodedBody = serv._decodedBody;
}
Serv::~Serv( void )
{
if (this->_request.empty())
return ;
for (std::map<int, std::string>::iterator it = this->_request.begin();
it != this->_request.end(); it++)
this->closeSock(it->first);
this->_port = 0;
this->_decodedBody = "";
}
/**********************************************************
************************GETTERS***************************
*********************************************************/
std::map<int, std::string> & Serv::getRequest ( void )
{
return this->_request;
}
struct sockaddr_in & Serv::getAddress( void )
{
return this->_addr;
}
std::string Serv::decodeChunkedBody( char * oldBody )
{
char *chunkSizeEnd = strstr(oldBody, "\r\n");
char *chunkSize = strcut(oldBody, chunkSizeEnd, chunkSizeEnd - oldBody);
int size = std::atoi(chunkSize);
if (size == 0)
return "EOF";
std::string newBody(chunkSizeEnd + 2, strstr(chunkSizeEnd + 2, "\r\n"));
return newBody;
}
int Serv::init_request( int sock )
{
const char *str = (this->_request[sock]).c_str();
Request_info *request = new Request_info(const_cast<char*>(str));
if ((request->getHeaders()).find("Transfer-Encoding") != request->getHeaders().end() &&
(request->getHeaders())["Transfer-Encoding"] == "chunked")
{
std::string addBody = decodeChunkedBody(request->getBody());
if (addBody != "EOF")
this->_decodedBody += addBody;
else
{
request->setBody(const_cast<char*>((this->_decodedBody).c_str()));
this->_decodedBody = "";
}
}
if (this->_decodedBody == "")
this->_parseRequest[sock] = request;
return 0;
}
/**************************INIT****************************
*************************CONNECT**************************
**************************CLOSE***************************/
int Serv::connectServer(void)
{
int reuse_addr = 1;
int sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
return print_error("socket() error", -1);
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0)
return print_error("setsockopt() error", -2);
this->initServer();
if (bind(sock, (struct sockaddr *)&this->_addr, sizeof(this->_addr)) < 0)
{
close(sock);
return print_error("bind() error", -4);
}
if (listen(sock, SOMAXCONN) < 0)
{
close(sock);
return print_error("listen() error", -5);
}
return sock;
}
void Serv::initServer( void )
{
memset(&this->_addr, 0, sizeof(this->_addr));
this->_addr.sin_family = AF_INET;
if (this->_servInfo.getListen().host == "")
this->_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
else
this->_addr.sin_addr.s_addr = inet_addr(toCharStr(this->_servInfo.getListen().host));
this->_addr.sin_port = htons(this->_port);
}
void Serv::closeSock( int sock )
{
std::map<int, std::string>::iterator it = this->_request.find(sock);
if (it == this->_request.end())
return ;
close(it->first);
this->_request.erase(it);
}
/*************************ACCEPT***************************
************************RECIEVE***************************
*************************SEND*****************************/
int Serv::acceptServer( int sock )
{
int newfd = accept(sock, 0, 0);
if (newfd < 0)
std::cerr << RED << "Error accept()" << RESET << std::endl;
else
{
std::cout << GREEN << "Accept complete()" << RESET << std::endl;
fcntl(newfd, F_SETFL, O_NONBLOCK);
}
return newfd;
}
int Serv::recvServer( int sock )
{
int ret;
char buf[BUF_SIZE];
ret = recv(sock, buf, BUF_SIZE - 1, 0);
if (ret <= 0)
{
if (ret < 0)
std::cerr << RED << "Error recv()" << RESET << std::endl;
else
std::cerr << RED << "Socket close" << RESET << std::endl;
close(sock);
return -1;
}
this->_request[sock] = buf;
std::cout << "Request:" << std::endl;
std::cout << GREEN << "[" << buf << "]" << RESET << std::endl;
return 0;
}
std::stringstream Serv::pages_to_stream(std::string filename)
{
std::string buf = std::to_string(this->_port);
std::stringstream response_body;
std::stringstream res;
std::ifstream in(filename);
if (!in.is_open())
res << "ERROR";
else
{
std::string line;
while(getline(in, line))
{
std::cout << line << std::endl;
response_body << line << std::endl;
}
response_body << "<pre>" << "on port: " << buf << "</pre>" << std::endl;
}
// std::string dirName("");
// DIR *dir = opendir("/");
// dirName = "/" + dirName;
// response_body << "<!DOCTYPE html>\n<html>\n<head>\n<title>" + dirName + "</title>\n</head>\n<body>\n<h1>INDEX</h1>\n<p>\n";
// if (dir == NULL)
// {
// std::cout << RED << "ERROR" << RESET << std::endl;
// return res;
// }
// for(struct dirent *dirEntry = readdir(dir); dirEntry; dirEntry = readdir(dir))
// {
// response_body << "\t\t<p><a href=\"http://" + this->_servInfo.getListen().host + ":" <<
// this->_servInfo.getListen().port << dirName + "/" << std::string(dirEntry->d_name) << "\">" << std::string(dirEntry->d_name) << "</a></p>\n";
// }
// response_body << "</p>\n</body>\n</html>\n";
// response_body << "<a href=\"https://127.0.0.1:8000\\tmp1\">tmp1</a>\r\n";
// response_body << "<a href=\"https://127.0.0.1:8000\\tmp2\">tmp2</a>\r\n";
res << "HTTP/1.1 200 OK\r\n" << "Version: HTTP/1.1\r\n" << "Content-Type: text/html; charset=utf-8\r\n" << "Content-Length: "
<< response_body.str().length() << "\r\n\r\n" << response_body.str();
// closedir(dir);
return res;
}
int Serv::sendServer( int sock )
{
int ret;
Response response;
std::string str = response.write_response(this->_parseRequest[sock], this->_servInfo);// = response.write_response(&request, this->_config);
std::cout << "Response:" << std::endl;
std::cout << GREEN << str << RESET << std::endl;
ret = send(sock, str.c_str(), str.length(), 0);
if (ret < 0)
std::cerr << RED << "Error send()" << RESET << std::endl;
else
std::cout << GREEN << "send() complete" << RESET << std::endl;
this->closeSock(sock);
delete this->_parseRequest[sock];
this->_parseRequest.erase(sock);
return ret;
} | true |
ca287bd7daf114bd6409bea23bfe0a52614f95e0 | C++ | brenomfviana/mago | /src/maze/cell.cpp | UTF-8 | 800 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
This file is part of MAGO.
Copyright (c) 2019 by Breno Viana
MAGO is a free software; you can redistribute it and/or modify it under the
terms of the MIT License.
*/
#include "maze/cell.hpp"
Cell::Cell() {
this->north = true;
this->east = true;
this->south = true;
this->west = true;
}
bool Cell::is_north_wall_standing() {
return this->north;
}
bool Cell::is_west_wall_standing() {
return this->west;
}
bool Cell::is_south_wall_standing() {
return this->south;
}
bool Cell::is_east_wall_standing() {
return this->east;
}
void Cell::knock_down_north_wall() {
this->north = false;
}
void Cell::knock_down_west_wall() {
this->west = false;
}
void Cell::knock_down_south_wall() {
this->south = false;
}
void Cell::knock_down_east_wall() {
this->east = false;
}
| true |
d707ecc41e0a73c7c9b63ad62eb0e1d8e4794988 | C++ | Mrudul-Bhatt/DS-Algo | /Heap/7)MergeKSortedArrays.cpp | UTF-8 | 1,171 | 3.5625 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Triplet
{
int val, aPos, vPos;
Triplet(int v, int ap, int vp)
{
val = v;
aPos = ap;
vPos = vp;
}
};
struct MyCmp
{
bool operator()(Triplet &t1, Triplet &t2)
{
return t1.val > t2.val;
}
};
vector<int> mergeKArrays(vector<vector<int>> arr)
{
vector<int> output;
priority_queue<Triplet, vector<Triplet>, MyCmp> pq;
for (int i = 0; i < arr.size(); i++)
{
Triplet t(arr[i][0], i, 0);
pq.push(t);
}
while (!pq.empty())
{
Triplet curr = pq.top();
pq.pop();
output.push_back(curr.val);
int ap = curr.aPos;
int vp = curr.vPos;
if (vp + 1 < arr[ap].size())
{
Triplet t(arr[ap][vp + 1], ap, vp + 1);
pq.push(t);
}
}
return output;
}
int main()
{
vector<vector<int>> arr{{2, 6, 12},
{1, 9},
{23, 34, 90, 2000}};
vector<int> output = mergeKArrays(arr);
cout << "Merged array is " << endl;
for (auto x : output)
cout << x << " ";
return 0;
}
| true |
1e80e72e017f154d86e79ddf936efd2d7c36b36f | C++ | BreX900/LearningCpp | /classeTipizzate/threeTree.h | UTF-8 | 896 | 2.875 | 3 | [] | no_license | //
// Created by brexm on 05/11/2018.
//
#pragma once
#include <iostream>
template <class T>
class ThreeTree;
template <class T>
std::ostream& operator<<(std::ostream&, const ThreeTree<T>&);
template <class T>
class ThreeTree {
friend std::ostream& operator<<(std::ostream&, const ThreeTree<T>&);
private:
class Nodo{
public:
T info;
Nodo *sx, *cx, *dx;
Nodo(const T& t , Nodo* s=0, Nodo* c=0, Nodo* d=0): info(t), sx(s), cx(c), dx(d) {}
static Nodo* copy(Nodo* r);
static bool search (Nodo* r, const T& t);
};
Nodo* root;
static void destruction(Nodo* r);
public:
ThreeTree();
ThreeTree<T>(const ThreeTree& t);
ThreeTree& operator=(const T& t);
bool operator==(const T& t) const;
~ThreeTree();
void put(const T& t);
bool search(const T& t) const ;
bool operator=(const ThreeTree&) const ;
};
| true |
b70c0fa22c032f505e8baddd4a80316a204a46ae | C++ | andyreimann/gear | /v2.5/GEAR Core/Entity.cpp | UTF-8 | 1,061 | 2.828125 | 3 | [] | no_license | // GEAR 2.5 - Game Engine Andy Reimann - Author: Andy Reimann <andy@moorlands-grove.de>
// (c) 2014 GEAR 2.5
#include "Entity.h"
using namespace G2;
unsigned int Entity::UNINITIALIZED_ENTITY_ID = 0;
unsigned int Entity::LAST_ENTITY_ID = 1;
Entity::Entity()
: mId(++LAST_ENTITY_ID)
{
// register entity?
// or no: entities can hold components
// these components will be connected with the ID! :)
}
Entity::Entity(Entity && rhs)
: mId(UNINITIALIZED_ENTITY_ID)
{
// eliminates redundant code
*this = std::move(rhs); // rvalue property is kept with std::move!
}
Entity& Entity::operator=(Entity && rhs)
{
// 1. Stage: delete maybe allocated resources on target type
if(mId != UNINITIALIZED_ENTITY_ID)
{
ECSManager::getShared().deleteComponentsForEntity(mId);
}
// 2. Stage: transfer data from src to target
mId = rhs.mId;
// 3. Stage: modify src to a well defined state
rhs.mId = UNINITIALIZED_ENTITY_ID;
return *this;
}
unsigned int
G2::Entity::getId() const
{
return mId;
}
G2::Entity::~Entity()
{
ECSManager::getShared().deleteComponentsForEntity(mId);
} | true |
2f4bff4de95281998b79d0f5af37279ddce92208 | C++ | sparshgoyal2014/gfgcodes | /Queuereverse/main.cpp | UTF-8 | 628 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <stack>
using namespace std;
// test
void reverseQueue(queue<int> q){ // it is pass by value // If you do this copy of the whole queue is passed and any changes will remained in the copied queue
if(q.empty()){
return;
}
int x = q.front();
q.pop();
reverseQueue(q);
q.push(x);
while(q.empty() == false){
cout << q.front() << " ";
q.pop();
}
cout << endl;
}
int main() {
queue<int> q;
q.push(5);
q.push(10);
q.push(15);
q.push(20);
q.push(25);
reverseQueue(q);
return 0;
}
| true |
c8b397419082599453f58999417dae7e189ccdc3 | C++ | HotCapuchino/Basics-of-Programming | /Графы/Графы/main.cpp | UTF-8 | 2,708 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include "Graph.h"
#include <fstream>
#include <float.h>
#include "GraphAlgorithms.h"
using namespace std;
int main(void) {
/*Test graph*/
/*Node node1 = Node("Moscow");
Node node2 = Node("Saints Peterburg");
Node node3 = Node("Ekaterinburg");
Node node4 = Node("Irkutsk");
Graph cities = Graph(true, true);
cities.addNode(&node1);
cities.addNode(&node2);
cities.addNode(&node3);
cities.addNode(&node4);
cities.createEdge(&node1, &node2, 3);
cities.createEdge(&node2, &node3, 10);
cities.createEdge(&node1, &node4, 30);
cout << cities << endl;*/
void connectedParts();
void secondTask();
connectedParts();
secondTask();
system("pause");
}
//задача на компоненты связности
void connectedParts() {
GraphAlgorithms graphAlg = GraphAlgorithms();
vector<Node*> all_nodes;
Graph graph = graphAlg.readGraph("TestGraph.txt", all_nodes, false, false);
vector<bool> visited(graph.getNodes().size());
graphAlg.depthSearch(*graph.getNodes().at(0), visited, *graph.getNodes().at(0), graph);
ofstream out;
out.setf(ios::boolalpha);
out.open("out/outputFirstTask.txt");
if (!out.is_open()) {
cout << "Oops! Error occurred while writing to the file!";
return;
}
for (int i = 0; i < visited.size(); i++) {
out << "Node: " << graph.getNodes().at(i)->getName() << " is visited: " << visited.at(i) << endl;
}
for (int i = 0; i < all_nodes.size(); i++) {
delete all_nodes.at(i);
}
all_nodes.clear();
}
// задача на поиск кратчайшего пути
void secondTask() {
vector<Node*> all_nodes;
GraphAlgorithms graphAlg = GraphAlgorithms();
Graph graph = graphAlg.readGraph("dijkstra.txt", all_nodes, true, true);
vector<double> roads(graph.getNodes().size(), DBL_MAX);
roads[0] = 0; // ставим растояние до старотовой вершины равным нулю, в нашем случае старт - вершина № 1, так что и обнуляем первую ячейку
vector<bool> visited(graph.getNodes().size(), false);
int target_index = -1;
for (int i = 0; i < graph.getNodes().size(); i++) {
if (graph.getNodes().at(i)->getName() == "9") {
target_index = i;
break;
}
}
double result = graphAlg.Dijkstra(*graph.getNodes().at(0), *graph.getNodes().at(target_index), graph, roads, visited);
ofstream out;
out.open("out/dijkstraOutput.txt");
if (!out.is_open()) {
cout << "Oops! Error occurred while writing to the file!";
return;
}
out << "The min weight from node" << graph.getNodes().at(0)->getName() << " to " << graph.getNodes().at(target_index)->getName() << " is " << result;
}
| true |
ddefe0e6bcbf512e679be6dd09cfee7b559f12c1 | C++ | lizhanyin/D3D9V2 | /Console/GPShader.cpp | GB18030 | 2,254 | 2.625 | 3 | [
"MIT"
] | permissive | #include "GPShader.h"
GPShader::GPShader(const TCHAR _file[])
{
std::cout << "[" << this << "]" << "GPShader::GPShader()\t" << std::endl;
m_d3dDevice = GetDevice();
lstrcpy(file, _file);
Load();
}
GPShader::~GPShader()
{
std::cout << "[X]" << "[" << this << "]" << "GPShader::~GPShader()\t" << std::endl;
if (mConstTable != nullptr)
{
mConstTable->Release();
}
if (mPixelShader != nullptr)
{
mPixelShader->Release();
}
}
void GPShader::Load()
{
//---------------------------------------------------
LPD3DXBUFFER shader = 0;
LPD3DXBUFFER errorBuffer = 0;
//ɫ
HRESULT hr = D3DXCompileShaderFromFile(file, 0, 0, "main", "ps_2_0", D3DXSHADER_DEBUG, &shader, &errorBuffer, &mConstTable);
if (errorBuffer)
{
MessageBox(NULL, (LPCWSTR)errorBuffer->GetBufferPointer(), 0, 0);
errorBuffer->Release();
}
if (FAILED(hr))
{
MessageBox(NULL, L"D3DXCompileShaderFromFile - failed", 0, 0);
return;
}
//ɫ
hr = m_d3dDevice->CreatePixelShader((DWORD*)shader->GetBufferPointer(), &mPixelShader);
if (FAILED(hr))
{
MessageBox(NULL, L"CreatePixelShader - failed", 0, 0);
return;
}
shader->Release();
}
void GPShader::SetColorToColor(D3DXVECTOR4 _DstColor, D3DXVECTOR4 _SrcColor,float _speed)
{
mDstColor = _DstColor - D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
mSrcColor = _SrcColor - D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f);
speed = _speed;
}
void GPShader::SetPixelShader()
{
//
D3DXMATRIX matWorld;
D3DXMatrixIdentity(&matWorld);
mConstTable->SetMatrix(m_d3dDevice, "matWorld", &matWorld);
//float4 ƽ
mSrcColor.x = addFloat(mDstColor.x, mSrcColor.x);
mSrcColor.y = addFloat(mDstColor.y, mSrcColor.y);
mSrcColor.z = addFloat(mDstColor.z, mSrcColor.z);
mSrcColor.w = addFloat(mDstColor.w, mSrcColor.w);
mConstTable->SetFloatArray(m_d3dDevice, "matTran", (float*)&mSrcColor, 4);
//ʹɫ
m_d3dDevice->SetPixelShader(mPixelShader);
}
bool GPShader::hasMask()
{
if (mSrcColor == mDstColor)
{
return true;
}
return false;
}
float GPShader::addFloat(float df,float sf)
{
if (df == sf){
return sf;
}
float fh = df - sf > 0.0f ? 1.0f : -1.0f;
if (fabs(df - sf) < 0.01f)
{
sf = df;
}
else {
sf = sf + speed * fh;
}
return sf;
}
| true |
c08a17bcf8ccd7a2cd88d6f31c16f4ec29e61985 | C++ | flopp/qubistic | /src/settings.h | UTF-8 | 1,684 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <QtCore/QSettings>
enum class ShapeType
{
Triangles = 1,
Rectangles = 2,
RectanglesRotated = 5,
Circles = 4,
Ellipses = 3,
EllipsesRotated = 7,
Polygons = 8,
Beziers = 6,
Mixed = 0
};
enum class TargetType
{
Steps,
Score
};
class Settings
{
public:
Settings();
void sync();
const ShapeType& shapeType() const { return shapeType_; }
void setShapeType(const ShapeType& shapeType) { shapeType_ = shapeType; }
const TargetType& targetType() const { return targetType_; }
void setTargetType(const TargetType& targetType) { targetType_ = targetType; }
int targetSteps() const { return targetSteps_; }
void setTargetSteps(int targetSteps) { targetSteps_ = targetSteps; }
double targetScore() const { return targetScore_; }
void setTargetScore(double targetScore) { targetScore_ = targetScore; }
const QString& primitiveBinPath() const { return primitiveBinPath_; }
void setPrimitiveBinPath(const QString& primitiveBinPath) { primitiveBinPath_ = primitiveBinPath; }
int extraShapes() const { return extraShapes_; }
void setExtraShapes(int extraShapes) { extraShapes_ = extraShapes; }
private:
QSettings settings_;
ShapeType shapeType_{ShapeType::Triangles};
TargetType targetType_{TargetType::Steps};
int targetSteps_{100};
double targetScore_{95.0};
QString primitiveBinPath_{"primitive"};
int extraShapes_{0};
QList<QPair<ShapeType, QString>> shapeTypeMapping_;
QList<QPair<TargetType, QString>> targetTypeMapping_;
};
| true |
cc3ddc0b0c229b6815d986874bdcbd30df180e1f | C++ | ifish19/CS172-HW3 | /StringSorter.cpp | UTF-8 | 288 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include "StringSorter.h"
using namespace std;
string sort(string& s)
{
string sSorted;
char c;
for(int i = 0; i < 26; i++)
{
c = i + 97;
if(s.find(c) != string::npos)
sSorted.append(1, c);
}
s = sSorted;
return s;
} | true |
19a827106a42033bb3994a1c2458af097c337cc1 | C++ | oblockiy/read-it-and-weep-simply-geometry | /Parallelepiped/Parallelepiped.h | UTF-8 | 698 | 2.546875 | 3 | [] | no_license | #ifndef PARALLELEPIPED_H
#define PARALLELEPIPED_H
#include <QVector>
class Parallelepiped
{
private:
QVector <int> p_ppEdges={0,0,0};
int p_ppV;
int p_ppS;
public:
Parallelepiped(QVector <int> ppEdges, int ppS, int ppV);
void set_PP(QVector <int> ppEdges, int ppS, int ppV);
QVector<int> get_ppEdges() { return p_ppEdges; };
int calc_ppS() { return 2*(p_ppEdges[0]*p_ppEdges[1]+p_ppEdges[0]*p_ppEdges[2]+p_ppEdges[1]*p_ppEdges[2]); };
int calc_ppV() { return p_ppEdges[0]*p_ppEdges[1]*p_ppEdges[2]; };
int calc_ppP() { return 4*p_ppEdges[0] + 4*p_ppEdges[1] + 4*p_ppEdges[2]; };
int calc_ppH() { return p_ppEdges[2]; };
};
#endif // PARALLELEPIPED_H
| true |
e7f1d874fe6ac283ae4b29213198b2a335365c26 | C++ | gloryXmj/ShapeDemo | /Algorithm/FillControl.cpp | UTF-8 | 11,958 | 2.640625 | 3 | [] | no_license | #include "FillControl.h"
#include "PixControl.hpp"
#include "pixshape.h"
#include <QDebug>
#include <stack>
namespace SCAN_LINE_FILL {
FillControl::FillControl()
{
}
FillControl::FillControl(FillControl::Polygon *polygon)
{
this->polyGon = polygon;
}
void FillControl::setPolygon(Mcoder::Polygon *polygon)
{
this->polyGon = polygon;
}
void FillControl::paint(int line_strip)
{
assert(polyGon);
PixShape::Polygon(*(this->polyGon->getPoints()),this->polyGon->getColor(),line_strip);
}
void FillControl::scanLine()
{
assert(polyGon);
if(this->polyGon->getSize() < 3)
{
// 如果小于三个点,则不是多边形,无法填充
qDebug()<<"小于三个点,不是多边形 ";
return ;
}
// 确定扫描线的范围
this->min.copy(*this->polyGon->getPoint(0));
this->max.copy(*this->polyGon->getPoint(0));
int size = this->polyGon->getSize();
for(int i = 0; i < size; i++)
{
Point * temp = this->polyGon->getPoint(i);
if(temp->getX() < min.getX())
{
min.setX(temp->getX());
}
else if(temp->getX() > max.getX())
{
max.setX(temp->getX());
}
if(temp->getY() < min.getY())
{
min.setY(temp->getY());
}
else if(temp->getY() > max.getY())
{
max.setY(temp->getY());
}
}
// 确定了扫描线范围 min.y -> max.y
this->buildEdgeTable();
this->scan();
}
bool FillControl::buildEdgeTable()
{
assert(polyGon);
if(this->polyGon->getSize() < MIN_POINT_SIZE)
{
return false ; // 三条边算不上多边形
}
this->sortedEdgeTable.clear(); // 清空边表
this->edge_horizontal.clear(); // 清空水平边
int ymin = this->min.getY();
int ymax = this->max.getY();
int size_edgeTable = ymax - ymin + 1; //表格大小
this->sortedEdgeTable.resize(size_edgeTable); // 设置边表大小
Point* p_start = this->polyGon->getPoint(0);
Point* p_end;
int size = this->polyGon->getSize(); // 获取有多少个点
for(int i = 1; i<size; i++)
{
p_end = this->polyGon->getPoint(i);
// 第一条边开始
this->addEdgeToTable(p_start, p_end);
p_start = p_end;
}
p_end = this->polyGon->getPoint(0);
this->addEdgeToTable(p_start, p_end);
return true;
}
void FillControl::scan()
{
assert(polyGon);
vector<EdgeS *> edge_active; // 新建活动边表
int y_min = this->min.getY(); // 获得扫描区域的最低端
int size_sortedEdgeTable = this->sortedEdgeTable.size(); // 获得Sorted Edge Table 大小
for(int i = 0; i < size_sortedEdgeTable; i++)
{
int y_scan = y_min + i; // 当前扫描的位置
// 清除已经失效的边
if(!edge_active.empty())
{
vector<EdgeS *>::iterator iter;
for(iter = edge_active.begin() ; iter < edge_active.end(); iter++)
{
EdgeS *temp = *iter;
if(y_scan > temp->ymax)
{
edge_active.erase(iter);
// 防止删除一个点以后,内存位置发生改变,或者删除了最后一个点,导致出现异常
if(!edge_active.empty())
iter = edge_active.begin(); // 从头重新扫描
else
break;
}
}
}
// 将新的线段加入到边表中
if(this->sortedEdgeTable[i] != NULL)
{
vector<EdgeS *> *temp = this->sortedEdgeTable[i];
int size_temp = temp->size();
for(int i = 0; i < size_temp; i++)
{
edge_active.push_back((*temp)[i]);
}
}
// 画当前扫描线
this->printScanLine(edge_active, y_scan); // 画扫描线
}
this->printHorizontalLine(this->edge_horizontal);// 画水平线
}
void FillControl::print()
{
assert(polyGon);
std::cout << "Points:";
int p_size = this->polyGon->getSize();
for(int i = 0; i < p_size; i++)
{
(this->polyGon->getPoint(i))->print();
std::cout << " ";
}
}
void FillControl::addEdgeToTable(Point *p_start, Point *p_end)
{
assert(polyGon);
// 判断哪个点在上方
Point * p_up, *p_down;
//相等的时候表示水平边
if(p_start->getY() == p_end->getY() )
{
// 水平边不加入数组中,加入水平边表中单独处理
this->edge_horizontal.push_back(new Edge(*p_start, *p_end));
return;
}
else if(p_start->getY() > p_end->getY())
{
// p_start 点在上方
p_up = p_start;
p_down = p_end;
}
else /*if(p_start->getY() < p_end->getY())*/
{
// p_end 点在上方
p_up = p_end;
p_down = p_start;
}
// 获得EdgeS数据的重要部分
double dx = 1.0 * (p_up->getX() - p_down->getX()) /
(p_up->getY() - p_down->getY()); // 斜率的倒数
int y_min = (int)p_down->getY(); // 线段最低端y值
double xi = p_down->getX(); // 最下端x值
int y_max = p_up->getY(); // 线段最顶端 y值
// ----------------------每条边 y方向上缩短一点
xi = xi + dx;
y_min = y_min + 1;
int y_id = y_min - this->min.getY(); // 应该插入表中的位置
vector<EdgeS *> * list_temp = this->sortedEdgeTable[y_id];
if(list_temp == NULL)
{
// 如果这个队列为空的话,新建队列
this->sortedEdgeTable[y_id] = list_temp
= new vector<EdgeS *>(); // 新建队列
}
list_temp->push_back(new EdgeS(xi, dx, y_max)); // 将EdgeS插入到队列中
}
void FillControl::printScanLine(vector<EdgeS *> activeEdgeTable, int y)
{
assert(polyGon);
if(activeEdgeTable.empty()){
qDebug() << u8"未画扫描线,y="<<y;
return;
}
list<double> intersection; // 交点
vector<EdgeS*>::iterator iter_activeEdge; // 活动边表的迭代器
for(iter_activeEdge = activeEdgeTable.begin();
iter_activeEdge < activeEdgeTable.end();
iter_activeEdge++)
{
EdgeS *edge_temp = *iter_activeEdge; // 遍历每条边
double xi = edge_temp->xi; // 获取当前 x坐标
edge_temp->xi = edge_temp->xi + edge_temp->dx; // 计算下一次的Xi坐标
intersection.push_back(xi); // 加入相交队列
}
intersection.sort(); // 对交点排序
list<double >::iterator iter = intersection.begin(); // 迭代器
while(iter != intersection.end())
{
double left = *iter; // 左交点
iter++;
if(iter == intersection.end())
{
qDebug() << u8"交点个数为奇数个,交点个数: "<< activeEdgeTable.size()
<<",x:"<<left<<",y:"<<y;
break;
}
double right = *iter; // 右交点
iter++;
/// this->red, this->green, this->blue // 设置颜色
if(left==right) // 如果两条线是重合的,会填一条线
{
return;
}
for(int i =left; i <= right; i++)
WritePixel(i,y,this->polyGon->getColor());
}
}
void FillControl::printHorizontalLine(vector<Edge *> edgeHorizontal)
{
assert(polyGon);
if(edgeHorizontal.empty())
{
return;
}
vector<Edge *>::iterator iter = edgeHorizontal.begin();
while(iter != edgeHorizontal.end())
{
Edge* edge_temp= *iter; // 获得水平边
///设置颜色 this->red, this->green, this->blue
int left = edge_temp->getStart()->getX();
int right = edge_temp->getEnd()->getX();
int y = edge_temp->getStart()->getY();
if(left==right) // 如果两条线是重合的,会填一条线
{
return;
}
for(int i =left; i <= right; i++)
WritePixel(i,y,this->polyGon->getColor());
iter++;
}
}
}
namespace SEED_SCAN_LINE_FILL {
int color_pixel_map[MAX_MAP_WIDTH][MAX_MAP_HEIGHT] = { { 0 } };
int map_width = 0;
int map_height = 0;
FillControl::FillControl()
{
}
FillControl::FillControl(FillControl::Polygon *polygon)
{
this->polyGon = polygon;
}
void FillControl::setPolygon(FillControl::Polygon *polygon)
{
this->polyGon = polygon;
}
void FillControl::paint(int line_strip)
{
assert(polyGon);
PixShape::Polygon(*(this->polyGon->getPoints()),this->polyGon->getColor(),line_strip);
}
void FillControl::ScanLineSeedFill(int x, int y, int new_color, int boundary_color)
{
std::stack<Point> stk;
stk.push(Point(x, y)); //第1步,种子点入站
while(!stk.empty())
{
Point seed = stk.top(); //第2步,取当前种子点
stk.pop();
//第3步,向左右填充
int count = FillLineRight(seed.getX(), seed.getY(), new_color, boundary_color);//向'cf?右'd3?填'cc?充'b3?
int xRight = seed.getX() + count - 1;
count = FillLineLeft(seed.getX() - 1, seed.getY(), new_color, boundary_color);//向'cf?左'd7?填'cc?充'b3?
int xLeft = seed.getX() - count;
//第4步,处理相邻两条扫描线
SearchLineNewSeed(stk, xLeft, xRight, seed.getY() - 1, new_color, boundary_color);
SearchLineNewSeed(stk, xLeft, xRight, seed.getY() + 1, new_color, boundary_color);
}
}
void FillControl::SearchLineNewSeed(std::stack<Point>& stk, int xLeft, int xRight,
int y, int new_color, int boundary_color)
{
int xt = xLeft;
bool findNewSeed = false;
while(xt <= xRight)
{
findNewSeed = false;
while(IsPixelValid(xt, y, new_color, boundary_color) && (xt < xRight))
{
findNewSeed = true;
xt++;
}
if(findNewSeed)
{
if(IsPixelValid(xt, y, new_color, boundary_color) && (xt == xRight))
stk.push(Point(xt, y));
else
stk.push(Point(xt - 1, y));
}
/*向右跳过内部的无效点(处理区间右端有障碍点的情况)*/
int xspan = SkipInvalidInLine(xt, y, xRight, new_color, boundary_color);
xt += (xspan == 0) ? 1 : xspan;
/*处理特殊情况,以退出while(x<=xright)循环*/
}
}
int FillControl::FillLineRight(int x, int y, int new_color, int boundary_color)
{
int xt = x;
while(GetPixelColor(xt, y) != boundary_color)
{
SetPixelColor(xt, y, new_color);
xt++;
}
return xt - x;
}
int FillControl::FillLineLeft(int x, int y, int new_color, int boundary_color)
{
int xt = x;
while(GetPixelColor(xt, y) != boundary_color)
{
SetPixelColor(xt, y, new_color);
xt--;
}
return x - xt;
}
/*点不是边界,而且没有填充过*/
bool FillControl::IsPixelValid(int x, int y, int new_color, int boundary_color)
{
return ( (GetPixelColor(x, y) != boundary_color)
&& (GetPixelColor(x, y) != new_color) );
}
int FillControl::SkipInvalidInLine(int x, int y, int xRight, int new_color, int boundary_color)
{
int xt = x;
while(!IsPixelValid(xt, y, new_color, boundary_color) && (xt < xRight))
{
xt++;
}
return xt - x;
}
int FillControl::GetPixelColor(int x, int y)
{
assert((x >= 0) && (x < MAX_MAP_WIDTH));
assert((y >= 0) && (y < MAX_MAP_HEIGHT));
return color_pixel_map[y][x];
}
void FillControl::SetPixelColor(int x, int y, int color)
{
assert((x >= 0) && (x < MAX_MAP_WIDTH));
assert((y >= 0) && (y < MAX_MAP_HEIGHT));
color_pixel_map[y][x] = color;
}
}
| true |
a3cd6063bf6e5348f6fa10fc247e4ec6f80aaaeb | C++ | MarkiianAtUCU/IPC_Crossplatform | /src/MySharedMemory.cpp | UTF-8 | 4,326 | 2.859375 | 3 | [] | no_license | //
// Created by andriiprysiazhnyk on 12/27/19.
//
#ifdef _WIN32
#include "MySharedMemory.h"
#elif __linux__ || __APPLE__
#include "MySharedMemory.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#endif
bool MySharedMemory::create(size_t size) {
#ifdef _WIN32
this->mapping_size = size;
memoryHandle = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
mapping_size, // maximum object size (low-order DWORD)
key.c_str()); // name of mapping object
if (memoryHandle == NULL)
{
error_message = "Could not create file mapping object\n";
// GetLastError()
return false;
}
this->attach(this->mapping_size);
semaphoreHandle = CreateSemaphore(
NULL, // default security attributes
1, // initial count
1, // maximum count
(key + "SEM").c_str());
if (semaphoreHandle == NULL)
{
error_message = "CreateSemaphore error\n";
return false;
}
return true;
#elif __linux__ || __APPLE__
int fd = shm_open(key.c_str(), O_RDWR | O_CREAT | O_EXCL, 0666);
if (fd == -1) {
error_message = "Error while creating shared memory object\n";
return false;
}
ftruncate(fd, size);
addr = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
error_message = "Error wile mapping a file\n";
return false;
}
mapping_size = size;
sem = sem_open(key.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1);
if (sem == SEM_FAILED) {
error_message = "Error while opening a semaphor\n";
return false;
}
close(fd);
return true;
#endif
}
bool MySharedMemory::attach(size_t size) {
#ifdef _WIN32
this->mapping_size = size;
memoryHandle = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
key.c_str());
if (memoryHandle == NULL)
{
error_message = "Could not attach to file mapping object";
return false;
}
addr = MapViewOfFile(memoryHandle, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
this->mapping_size);
if (addr == NULL)
{
error_message = "Could not map view";
return false;
}
semaphoreHandle = OpenSemaphore(
SEMAPHORE_MODIFY_STATE | SYNCHRONIZE,
FALSE,
(key + "SEM").c_str());
return true;
#elif __linux__ || __APPLE__
int fd = shm_open(key.c_str(), O_RDWR, 0666);
if (fd == -1) {
error_message = "Error while opening shared memory object\n";
return false;
}
addr = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
error_message = "Error wile mapping a file\n";
return false;
}
mapping_size = size;
std::cout << "Hello\n";
sem = sem_open(key.c_str(), O_RDWR);
if (sem == SEM_FAILED) {
error_message = "Error while opening a semaphor\n";
return false;
}
close(fd);
return true;
#endif
}
void* MySharedMemory::data() {
return addr;
}
void MySharedMemory::detach() {
#ifdef _WIN32
UnmapViewOfFile(addr);
#elif __linux__ || __APPLE__
sem_close(sem);
munmap(addr, mapping_size);
sem_unlink(key.c_str());
shm_unlink(key.c_str());
#endif
}
void MySharedMemory::lock() {
#ifdef _WIN32
auto wait_res = WaitForSingleObject(semaphoreHandle, INFINITE);
#elif __linux__ || __APPLE__
sem_wait(sem);
#endif
}
void MySharedMemory::unlock() {
#ifdef _WIN32
ReleaseSemaphore(semaphoreHandle, 1, NULL);
#elif __linux__ || __APPLE__
sem_post(sem);
#endif
}
MySharedMemory::~MySharedMemory() {
#ifdef _WIN32
CloseHandle(memoryHandle);
#elif __linux__ || __APPLE__
detach();
#endif
} | true |
6513b06a78190707b1fe567c91486e71859e11ae | C++ | 4ndrenobr3/EstruturaDeDados | /ponteiro.cpp | UTF-8 | 757 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
struct nodo
{
int num;
struct nodo *prox;
};
nodo *insereFrente(nodo *ptr, int valor);
int main()
{
int c;
nodo *lista=NULL;
//Primeito no
lista = insereFrente(lista, 23);
//Segundo no
lista = insereFrente(lista, 13);
//Terceiro no
lista = insereFrente(lista, 15);
//Quarto no
lista = insereFrente(lista, 18);
//Listando
c=1;
cout<<"\n\nUsando uma estrutura de Repeticao\n";
while(lista)
{
cout<<"\nValor do "<<c<<" o no: "<<lista->num;
lista=lista->prox;
c++;
}
//Liberando
delete lista; lista=0;
cout<<"\n\n";
system("pause");
}
nodo* insereFrente(nodo *ptr, int valor)
{
nodo *temp = new nodo;
temp->num = valor;
temp->prox = ptr;
return temp;
}
| true |
5dff9b435e391c04b97bbb7cf7f7d08ed55d21f0 | C++ | kor-kms/AlgoCode | /기타/14500_테트로미노(백준).cpp | UHC | 3,553 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int ar[500][500];
int ans;
int cou;
int n, m;
void input() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> ar[i][j];
}
}
}
void solve() {
//1
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 3; j++) {
cou = ar[i][j] + ar[i][j + 1] + ar[i][j + 2] + ar[i][j + 3];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 3; i++) {
for (int j = 0; j < m; j++) {
cou = ar[i + 1][j] + ar[i + 2][j] + ar[i + 3][j] + ar[i][j];
ans = max(ans, cou);
}
}
//2
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i][j + 1] + ar[i + 1][j + 1];
ans = max(ans, cou);
}
}
//3
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i + 2][j] + ar[i + 2][j + 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m - 2; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i][j + 1] + ar[i][j + 2];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 2; i++) {
for (int j = 1; j < m; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i + 2][j] + ar[i][j - 1];
ans = max(ans, cou);
}
}
for (int i = 1; i < n; i++) {
for (int j = 2; j < m; j++) {
cou = ar[i][j] + ar[i - 1][j] + ar[i][j - 1] + ar[i][j - 2];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 2; i++) {
for (int j = 1; j < m; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i + 2][j] + ar[i + 2][j - 1];
ans = max(ans, cou);
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < m - 2; j++) {
cou = ar[i][j] + ar[i - 1][j] + ar[i][j + 1] + ar[i][j + 2];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i + 2][j] + ar[i][j + 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m - 2; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i][j + 1] + ar[i][j + 2];
ans = max(ans, cou);
}
}
//4
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i + 1][j + 1] + ar[i + 2][j + 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 1; i++) {
for (int j = 1; j < m - 1; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i][j + 1] + ar[i + 1][j - 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 2; i++) {
for (int j = 1; j < m; j++) {
cou = ar[i][j] + ar[i + 1][j] + ar[i + 1][j - 1] + ar[i + 2][j - 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m - 2; j++) {
cou = ar[i][j] + ar[i + 1][j + 1] + ar[i][j + 1] + ar[i + 1][j + 2];
ans = max(ans, cou);
}
}
//5
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i][j + 1] + ar[i][j + 2] + ar[i + 1][j + 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i][j + 1] + ar[i][j + 2] + ar[i + 1][j + 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i][j + 1] + ar[i][j + 2] + ar[i + 1][j + 1];
ans = max(ans, cou);
}
}
for (int i = 0; i < n - 2; i++) {
for (int j = 0; j < m - 1; j++) {
cou = ar[i][j] + ar[i][j + 1] + ar[i][j + 2] + ar[i + 1][j + 1];
ans = max(ans, cou);
}
}
}
int main() {
input();
solve();
cout << ans << endl;
return 0;
} | true |
8286b1e53639da2912ce48e6694af53931da9afc | C++ | asdzxc55888/DesignPattern_hw | /assignment4/src/main.cpp | UTF-8 | 440 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "io.h"
#include "library.h"
int main(int argc, char **argv) {
Library library;
while (true) {
printInstructions();
std::string instruction;
std::cout << "Input instruction: ";
std::getline(std::cin, instruction, '\n');
std::cout << "\n";
handleInstructions(instruction, library);
// TODO: Handle the input instructions.
}
}
| true |
c3760da3a4cf25939453602b322686de67adf947 | C++ | sonuKumar03/data-structure-and-algorithm | /codeforces/CF78B.cpp | UTF-8 | 333 | 2.859375 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<math.h>
using namespace std;
void solve(){
int n;
cin>>n;
string a ="GBIV";
if(n<7){
cout<<"Wrong!";
}else{
cout<<"ROYGBIV";
}
n = n-7;
for(int i =1;i<=n/4;i++){
cout<<a;
}
n=n%4;
string b ="";
for(int i =0;i<n;i++){
b=b+a[i];
}
cout<<b<<endl;
}
int main(){
solve();
return 0;
} | true |
7b15628192d188034f7c1158b0e117042afb613e | C++ | AmanajasLG/IDJ | /src/Minion.cpp | UTF-8 | 2,743 | 2.640625 | 3 | [] | no_license | #include "../include/Minion.h"
#include "../include/Sprite.h"
#include "../include/Bullet.h"
#include "../include/Game.h"
#include "../include/Collider.h"
#include "../include/Alien.h"
#include <math.h>
Minion::Minion(GameObject &associated, std::weak_ptr<GameObject> alienCenter, float arcOffsetDeg) : Component(associated), alienCenter(alienCenter){
arc = arcOffsetDeg;
Collider *collider = new Collider(associated);
associated.AddComponent(collider);
Sprite *sprite = new Sprite(associated, "assets/img/minion.png");
float scale = (float) rand() / (RAND_MAX) + 1;
if(scale > 1.5)
scale -= 0.5;
sprite->SetScale(scale,scale);
sprite->arc = arcOffsetDeg;
associated.AddComponent(sprite);
std::shared_ptr<GameObject> sharedGO(this->alienCenter.lock());
associated.box.h = sprite->GetHeight();
associated.box.w = sprite->GetWidth();
associated.box.x = sharedGO->box.x - associated.box.w/2;
associated.box.y = sharedGO->box.y - associated.box.h/2;
}
Minion::~Minion(){
}
void Minion::Update(float dt){
if(alienCenter.lock() == nullptr){
return;
}
std::shared_ptr<GameObject> sharedGO(alienCenter.lock());
Sprite *sprite = (Sprite*) associated.GetComponent("Sprite");
Vec2 minionPos = Vec2(130, 0);
arc -= dt*M_PI;
minionPos.GetRotated(arc);
sprite->arc = arc;
Vec2 objPos = objPos.AddVectors(minionPos, Vec2( sharedGO->box.x - associated.box.w/2 + sharedGO->box.w/2, sharedGO->box.y - associated.box.h/2 + sharedGO->box.h/2));
associated.box.x = objPos.x;
associated.box.y = objPos.y;
}
void Minion::Render(){
}
bool Minion::Is(std::string type){
return strcmp(type.c_str(),"Minion") == 0;
}
void Minion::Shoot(Vec2 target){
float adjust;
Vec2 minionPos;
minionPos.x = associated.box.x;
minionPos.y = associated.box.y;
GameObject *go = new GameObject();
go->box.x = minionPos.x ;
go->box.y = minionPos.y ;
if((target.x-minionPos.x) >= 0){
adjust = 0;
}else if((target.x-minionPos.x) <= 0){
adjust = M_PI;
}
Bullet *bullet = new Bullet(*go,
atan((target.y-minionPos.y)/(target.x-minionPos.x))+adjust,
500,
10,
target.Dist2Dots(minionPos,target),
"assets/img/minionbullet2.png",
true,
3);
go->AddComponent(bullet);
State &state = Game::GetInstance().GetCurrentState();
state.AddObject(go);
}
void Minion::NotifyCollision(GameObject &other){
}
| true |
11852d97fb4dfc742c0f44b13e933bcdd9742a90 | C++ | paraagm/StringLibrary | /StringLibrary/string.h | UTF-8 | 1,343 | 3.109375 | 3 | [] | no_license | #pragma once
//#ifdef MSC_VER
//
//#define _CRT_SECURE_NO_WARNINGS
//#pragma warning(disable : 4996)
//
//#endif // MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <cstdlib>
#include <cstring>
#include <locale>
class string
{
char* _str;
size_t _len;
public:
string();
string(const char* c);
string(const string& s);
~string();
const char* get_str () const { return _str; };
//operators
string& operator += (const char* rhs);
const char operator [] (const int index);
string& operator= (const char* rhs);
string& operator= (string& rhs);
//conditional operations
bool operator == (const char* rhs);
bool operator != (const char* rhs);
//conversion operator
operator const char* () const;
//utility functions
size_t length() const { return _len; }
void trim_whitespace();
void to_upper();
void to_lower();
void reverse(size_t start, size_t end);
void reverse_words();
//find and replace
size_t find(const char* str, size_t pos = 0) const;
size_t char_find(const char* chr, size_t pos = 0) const;
size_t char_find(char chr, size_t pos = 0) const;
string substr(size_t pos = 0, size_t len = -1) const;
//modifiers
void swap(string& swap_str);
private:
void reset();
void copy_str(const char* c);
void allocate_str(size_t len);
void shift_left_at(size_t pos);
};
| true |
b06059f698aafeb3090427a0ea5ceb5dd12cd925 | C++ | Zerphed/computer-graphics-course | /2012/assignment_2/code/src/basis/Joint.h | UTF-8 | 618 | 2.65625 | 3 | [] | no_license | #ifndef JOINT_H
#define JOINT_H
#include <vector>
#include <base/Math.hpp>
struct Joint
{
FW::Mat4f transform; // transform relative to its parent
std::vector< Joint* > children; // list of children
// This matrix transforms world space into joint space for the initial ("bind") configuration of the joints.
FW::Mat4f bindWorldToJointTransform;
// This matrix maps joint space into world space for the *current* configuration of the joints.
FW::Mat4f currentJointToWorldTransform;
// Crufty, but best I could come up with right now, tells the idx of the joint in the joint array.
size_t index;
};
#endif
| true |
2012a9d3d371f093115ccb1679a780f3e0dac31d | C++ | DongJinNam/boj | /6679.cpp | UTF-8 | 557 | 2.5625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
std::ios::sync_with_stdio(false);
for (int i = 1000; i < 10000; i++) {
int num = i;
int ans_10 = 0, ans_12 = 0, ans_16 = 0;
int temp = i;
while (temp > 0) {
int rm = temp % 10;
temp /= 10;
ans_10 += rm;
}
temp = i;
while (temp > 0) {
int rm = temp % 12;
temp /= 12;
ans_12 += rm;
}
temp = i;
while (temp > 0) {
int rm = temp % 16;
temp /= 16;
ans_16 += rm;
}
if (ans_10 == ans_12 && ans_12 == ans_16) {
cout << i << "\n";
}
}
return 0;
} | true |
ffb42fdb25260e6a3143f683b2f05d8a7a3c9fc4 | C++ | codingaquarium/ProgrammingCollection | /MySuccess/11503 - Virtual Friends.cpp | UTF-8 | 1,219 | 2.703125 | 3 | [] | no_license | /*
Shiakh Shiam Rahman
UVa : 11503 - Virtual Friends
*/
#include <iostream>
#include "cstdio"
#include "map"
#include "cstring"
#include "string"
using namespace std;
int par[100010];
int find(int r)
{
if(par[r] < 0)
return r;
return par[r]=find(par[r]);
}
int main()
{
freopen("in.txt","r",stdin);
map < string , int > man;
int tc ;
scanf("%d",&tc);
while(tc--)
{
int cas,i=1;
memset(par,-1,sizeof(par));
scanf("%d",&cas);
while(cas--)
{
string s1,s2;
cin>>s1>>s2;
if(!man[s1])
man[s1] = i++;
if(!man[s2])
man[s2] = i++;
int p = find (man[s1]);
int q = find (man[s2]);
if ( p == q ) {
printf ("%d\n", par [p]*-1);
continue;
}
if ( par [p] < par [q] ) {
par [p] += par [q];
par [q] = p;
printf ("%d\n", par [p]*-1);
}
else {
par [q] += par [p];
par [p] = q;
printf ("%d\n", par [q]*-1);
}
}
man.clear();
}
return 0;
}
| true |
6520d75b6953a8598e6b7ca5bc80646c417e9a05 | C++ | thecreatorsir/DailyDSA | /recursion/handshake-problem-using-catalan-number.cpp | UTF-8 | 304 | 2.828125 | 3 | [] | no_license | class Solution{
int sum = 0;
public:
int count(int N){
int n = N/2;
return solve(n);
}
int solve(int n){
if(n==0 || n==1)
return 1;
int sum =0;
for(int i=n-1;i>=0;i--){
sum += solve(i)*solve(n-1-i);
}
return sum;
}
};
| true |
4e9deb9dd7e9dc4e290684e57ea2bf5888384f3f | C++ | mpk934/mediasoup | /worker/src/RTC/RTCP/FeedbackPsTst.cpp | UTF-8 | 1,888 | 2.578125 | 3 | [
"ISC"
] | permissive | #define MS_CLASS "RTC::RTCP::FeedbackPsTstPacket"
// #define MS_LOG_DEV
#include "RTC/RTCP/FeedbackPsTst.hpp"
#include "Logger.hpp"
#include <cstring>
namespace RTC { namespace RTCP
{
/* Class methods. */
template <typename T>
TstItem<T>* TstItem<T>::Parse(const uint8_t* data, size_t len)
{
MS_TRACE();
// data size must be >= header + length value.
if (sizeof(Header) > len)
{
MS_WARN_TAG(rtcp, "not enough space for Tst item, discarded");
return nullptr;
}
Header* header = const_cast<Header*>(reinterpret_cast<const Header*>(data));
return new TstItem(header);
}
template <typename T>
TstItem<T>::TstItem(uint32_t ssrc, uint8_t sequenceNumber, uint8_t index)
{
MS_TRACE();
this->raw = new uint8_t[sizeof(Header)];
this->header = reinterpret_cast<Header*>(this->raw);
// Set reserved bits to zero.
std::memset(this->header, 0, sizeof(Header));
this->header->ssrc = htonl(ssrc);
this->header->sequence_number = sequenceNumber;
this->header->index = index;
}
template <typename T>
size_t TstItem<T>::Serialize(uint8_t* buffer)
{
MS_TRACE();
std::memcpy(buffer, this->header, sizeof(Header));
return sizeof(Header);
}
template <typename T>
void TstItem<T>::Dump()
{
MS_TRACE();
MS_DUMP("<TstItem>");
MS_DUMP(" ssrc : %" PRIu32, this->GetSsrc());
MS_DUMP(" sequence number : %" PRIu32, this->GetSequenceNumber());
MS_DUMP(" index : %" PRIu32, this->GetIndex());
MS_DUMP("</TstItem>");
}
/* Specialization for Tstr class. */
template<>
const FeedbackPs::MessageType TstItem<Tstr>::MessageType = FeedbackPs::TSTR;
/* Specialization for Tstn class. */
template<>
const FeedbackPs::MessageType TstItem<Tstn>::MessageType = FeedbackPs::TSTN;
// Explicit instantiation to have all definitions in this file.
template class TstItem<Tstr>;
template class TstItem<Tstn>;
}}
| true |
ea1b43f34080c5e911a5e15690513d02116da5b7 | C++ | veekay7/xphoton | /Raytracer/MemPool.cpp | UTF-8 | 1,266 | 3.015625 | 3 | [] | no_license | #include "stdafx.h"
#include "MemPool.h"
rtOneWayMemPool::rtOneWayMemPool(UINT blockSize, bool aligned)
{
m_blockSize = blockSize;
m_Aligned = aligned;
}
rtOneWayMemPool::~rtOneWayMemPool()
{
release();
}
void* rtOneWayMemPool::alloc(size_t size)
{
//no blocks, create a new one
if (m_Blocks.size() == 0)
{
rtMemPoolBlock newBlock;
if (m_Aligned)
newBlock.ptr = (char*)_aligned_malloc(m_blockSize, 16);
else
newBlock.ptr = (char*)malloc(m_blockSize);
newBlock.used = size;
m_Blocks.push_back(newBlock);
return newBlock.ptr;
}
//not enough space in block, create a next one
rtMemPoolBlock& block = m_Blocks[m_Blocks.size()-1];
if (m_blockSize < size + block.used)
{
rtMemPoolBlock newBlock;
if (m_Aligned)
newBlock.ptr = (char*)_aligned_malloc(m_blockSize, 16);
else
newBlock.ptr = (char*)malloc(m_blockSize);
newBlock.used = size;
m_Blocks.push_back(newBlock);
return newBlock.ptr;
}
void* ptr = (void*)(((size_t)block.ptr) + block.used);
block.used += size;
return ptr;
}
void rtOneWayMemPool::release()
{
if (m_Aligned)
{
for (int i = 0; i<m_Blocks.size(); i++)
_aligned_free(m_Blocks[i].ptr);
}
else
{
for (int i = 0; i<m_Blocks.size(); i++)
free(m_Blocks[i].ptr);
}
m_Blocks.clear();
} | true |
b1aadb044673eb07abe049ef91a055d464f3e3bb | C++ | ZenEngine3D/ZenEngine | /Engine/ZenApi/ZenBase/Type/Container/zenBaseTypeListIntrusive.h | UTF-8 | 9,707 | 2.796875 | 3 | [
"MIT"
] | permissive | #pragma once
namespace zen { namespace zenType
{
//! @todo 1 Replace most list with dynamic array with pointer.
//=================================================================================================
//! @brief Macro used to add a ListLink to a class.
//! @note Unless wanting to preserve POD of a class, does not need to be used directly creating
//! a class with intrusive list support.
//=================================================================================================
#define zListLinkMember(ListCount) zListLink mLinks[ListCount];
//=============================================================================================
//! @class zListLink
//! @brief Contain infos to reach previous and next item in a list.
//! @detail The templated list object is able to find the object the link belongs too,
//! by knowing the offset between base object address and link member address.
//! @note Bit 0 turned on prev/next pointer when this link object belongs to list root node.
//=============================================================================================
class zListLink
{
public:
zListLink() = default;
zenInline bool IsInList()const;
zenInline bool IsItem()const;
zenInline void Reset();
zenInline zListLink* Next()const;
zenInline zListLink* Prev()const;
protected:
zenInline void SetAsRoot();
zenInline void SetNext(zListLink* inItem);
zenInline void SetPrev(zListLink* inItem);
zenInline void Remove();
zenInline void InsertBefore(zListLink& zenRestrict _NewLink);
zenInline void InsertAfter(zListLink& zenRestrict _NewLink);
zListLink* mpPrev; //!< Pointer to next link
zListLink* mpNext; //!< Pointer to previous link
friend class zListBase;
template<class, unsigned char, class> friend class zList;
template<unsigned char, unsigned char> friend class zListItem;
};
//=================================================================================================
//! @brief Used to add IntrusiveList support in a class.
//! @detail This class preserve the 'trivialness' of a class, meaning that objects using it can
//! still be memcopied without issue.
//! @example Creating a class that can live in 2 different list :
//! class MyClass : public zListItemTrivial<2> {}
//! zList<MyClass, 0> listA;
//! zList<MyClass, 1> listB;
//! @note In the case of a parent class and child class both wanting to be in different list
//! we can use TMultiIndex with a different value to avoid compiler confusion when
//! knowing which mLink member to use. Look at SampleListMultiInheritance() example.
//=================================================================================================
template <unsigned char TListCount=1, unsigned char TMultiIndex=0>
class zListItemTrivial
{
public:
zListItemTrivial() = default;
protected:
zListLinkMember(TListCount);
template<class,unsigned char,class> friend class zList;
};
//=================================================================================================
//! @brief Add IntrusiveList support in a child class through inheritance.
//! @detail Unlike zListItemTrivial, objects using this class are not trivial anymore, because
//! it use a constructor to initialize data to null, and destructor to auto remove items
//! from list it belongs to, when destroyed.
//! @note Should be the main class used for adding list support to a class.
//=================================================================================================
template <unsigned char TListCount=1, unsigned char TMultiIndex=0>
class zListItem : public zListItemTrivial<TListCount, TMultiIndex>
{
public:
zenInline zListItem();
zenInline ~zListItem();
};
//=================================================================================================
//! @class zListBase
//! @brief Double 'intrusive' linked list base class
//! @detail Intrusive list do not require using additional allocation, their list infos is
//! directly included in the object, making it more cache friendly and less heap intensive.
//! Example : look at SampleListIntrusive() for more infos
//=================================================================================================
class zListBase
{
public:
zenInline zListBase();
zenInline virtual ~zListBase();
// Using STL standard naming convention (http://www.cplusplus.com/reference/stl/)
zenInline bool empty()const;
zenInline virtual void clear();
protected:
class Iterator
{
public:
zenInline Iterator(zListLink* _pCurrent);
zenInline Iterator(const Iterator& _Copy);
zenInline bool IsValid()const;
zenInline bool operator==(const Iterator& _Cmp)const;
zenInline bool operator!=(const Iterator& _Cmp)const;
zenInline explicit operator bool()const;
protected:
zListLink* mpCurrent = nullptr;
};
class IteratorConst
{
public:
zenInline IteratorConst(const zListLink* _pCurrent);
zenInline IteratorConst(const IteratorConst& _Copy);
zenInline bool IsValid()const;
zenInline bool operator==(const IteratorConst& _Cmp)const;
zenInline bool operator!=(const IteratorConst& _Cmp)const;
zenInline explicit operator bool()const;
protected:
const zListLink* mpCurrent = nullptr;
};
zListLink mRoot;
};
//=================================================================================================
//! @class zList
//! @brief Double 'intrusive' linked list
//! @detail Made class compatible with STL containers, so std coding technique can be used with it
//! @param TItem - Class of object stored in the list
//! @param TListIdx - Object support being stored in multiple list at the same time,
//! specify which ListIndex this list should use. (Only needed when not 0)
//! @param TLinkAccess -Through consecutive inheritance, it's possible for class to inherit from
//! multiple zListItem, prevent problem by making which one to use explicit.
//! (Needed when ambiguous compile error from multiple zListItem child class)
//! Example here : SampleListMultiInheritance
//=================================================================================================
template<class TItem, unsigned char TListIdx=0, class TLinkAccess=TItem>
class zList : public zListBase
{
public:
class Iterator : public zListBase::Iterator
{
public:
Iterator(){}
Iterator(const Iterator& _Copy);
TItem* Get()const;
TItem& operator*()const { return *Get(); }
TItem* operator->()const {return Get(); }
zenInline Iterator& operator=(const Iterator& _Copy);
zenInline Iterator& operator++();
zenInline Iterator& operator--();
protected:
Iterator(zListLink* _pCurrent);
friend class zList;
};
class IteratorConst: public zListBase::IteratorConst
{
public:
IteratorConst() {}
IteratorConst(const IteratorConst& _Copy);
const TItem* Get()const;
const TItem& operator*()const { return *Get(); }
const TItem* operator->()const { return Get(); }
zenInline IteratorConst& operator=(const IteratorConst& _Copy);
zenInline IteratorConst& operator++();
zenInline IteratorConst& operator--();
protected:
IteratorConst(const zListLink* _pCurrent);
friend class zList;
};
//Using STL container naming convention
zenInline zList& push_front(TItem& _ItemAdd);
zenInline zList& push_back(TItem& _ItemAdd);
zenInline zList& insert(Iterator& _Pos, TItem& _ItemAdd);
zenInline zList& insert(TItem& _ItemPos, TItem& _ItemAdd);
zenInline TItem& front()const;
zenInline TItem& back()const;
zenInline TItem* pop_front();
zenInline TItem* pop_back();
zenInline static void remove(TItem& _ItemRem);
zenInline Iterator begin();
zenInline Iterator end();
zenInline IteratorConst cbegin()const;
zenInline IteratorConst cend()const;
//Non standard STL
zenInline zList& insert_after(Iterator& _Pos,TItem& _ItemAdd);
zenInline zList& insert_after(TItem& _ItemPos,TItem& _ItemAdd);
zenInline zList& insert_before(Iterator& _Pos, TItem& _ItemAdd);
zenInline zList& insert_before(TItem& _ItemPos, TItem& _ItemAdd);
zenInline zList& push_sort(TItem& _ItemAdd);
zenInline TItem* front_check()const;
zenInline TItem* back_check()const;
zenInline static bool IsInList(const TItem& Item);
zenInline static TItem* GetNext(const TItem& Item);
zenInline static TItem* GetPrev(const TItem& Item);
protected:
static TItem* GetItemFromLink(const zListLink& _Link);
};
//=================================================================================================
//! @class zListRefTest
//! @brief Double 'intrusive' linked list with Reference Count awareness
//! @detail Similar to zList, but will increment refcount when item added in list,
//! and decrement when removed
//! @note Only need to override methods than can add or remove an item
//=================================================================================================
template<class TItem,unsigned char TListIdx=0, class TLinkAccess=TItem>
class zListRef: public zList<TItem, TListIdx, TLinkAccess>
{
zenClassDeclare(zListRef, zList)
public:
zenInline virtual ~zListRef();
zenInline virtual void clear();
//Standard STL
zenInline zListRef& push_front(TItem& inItem);
zenInline zListRef& push_back(TItem& inItem);
zenInline zListRef& insert(Iterator& _Pos, TItem& _ItemAdd);
zenInline zListRef& insert(TItem& _ItemPos, TItem& _ItemAdd);
zenInline TItem* pop_front();
zenInline TItem* pop_back();
zenInline static void remove(TItem& _ItemRem);
//Non standard STL
zenInline zListRef& insert_before(TItem& _Item);
};
} } //namespace zen, Type | true |
385993bcea11b8319af9a7c714dabce15679b983 | C++ | mfkiwl/BART | /src/quadrature/quadrature_set.h | UTF-8 | 2,963 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef BART_SRC_QUADRATURE_QUADRATURE_SET_H_
#define BART_SRC_QUADRATURE_QUADRATURE_SET_H_
#include "quadrature/quadrature_set_i.h"
#include "quadrature/utility/quadrature_utilities.h"
namespace bart {
namespace quadrature {
/*! \brief Default implementation of the QuadratureSet.
*
* @tparam dim spatial dimension
*/
template <int dim>
class QuadratureSet : public QuadratureSetI<dim> {
public:
virtual ~QuadratureSet() = default;
bool AddPoint(std::shared_ptr<QuadraturePointI<dim>>);
void SetReflection(std::shared_ptr<QuadraturePointI<dim>>,
std::shared_ptr<QuadraturePointI<dim>>);
std::shared_ptr<QuadraturePointI<dim>> GetBoundaryReflection(
const std::shared_ptr<QuadraturePointI<dim>>& quadrature_point_to_reflect,
problem::Boundary boundary) const override;
std::shared_ptr<QuadraturePointI<dim>> GetReflection(
std::shared_ptr<QuadraturePointI<dim>>) const override;
std::optional<int> GetReflectionIndex(
std::shared_ptr<QuadraturePointI<dim>>) const override;
std::shared_ptr<QuadraturePointI<dim>> GetQuadraturePoint(
QuadraturePointIndex index) const override;
int GetQuadraturePointIndex(
std::shared_ptr<QuadraturePointI<dim>> quadrature_point) const override;
std::set<int> quadrature_point_indices() const override {
return quadrature_point_indices_; };
typename QuadratureSetI<dim>::Iterator begin() override {
return quadrature_point_ptrs_.begin(); };
typename QuadratureSetI<dim>::Iterator end() override {
return quadrature_point_ptrs_.end(); };
typename QuadratureSetI<dim>::ConstIterator cbegin() const override {
return quadrature_point_ptrs_.cbegin(); };
typename QuadratureSetI<dim>::ConstIterator cend() const override {
return quadrature_point_ptrs_.cend(); };
size_t size() const override {return quadrature_point_ptrs_.size(); };
protected:
//! Set of quadrature point indices
std::set<int> quadrature_point_indices_ = {};
//! Set of actual quadrature points
std::set<std::shared_ptr<QuadraturePointI<dim>>,
utility::quadrature_point_compare<dim>> quadrature_point_ptrs_;
//! Mapping of points to their reflections
std::map<std::shared_ptr<QuadraturePointI<dim>>,
std::shared_ptr<QuadraturePointI<dim>>> reflection_map_;
//! Mapping of quadrature point indices to quadrature points
std::map<int, std::shared_ptr<QuadraturePointI<dim>>>
index_to_quadrature_point_map_ = {};
//! Mapping of indices to quadrature point
std::map<std::shared_ptr<QuadraturePointI<dim>>, int>
quadrature_point_to_index_map_ = {};
//! Internal mapping of boundary reflections
mutable std::map<problem::Boundary, std::map<std::shared_ptr<QuadraturePointI<dim>>,
std::shared_ptr<QuadraturePointI<dim>>>>
boundary_reflections_;
};
} // namespace quadrature
} //namespace bart
#endif //BART_SRC_QUADRATURE_QUADRATURE_SET_H_
| true |
8f1d0a0f23a8cb4dde270ce26777c8efdf78f319 | C++ | kaidokert/corona | /include/stm32/stm32h7/device/crc.h | UTF-8 | 5,548 | 2.609375 | 3 | [
"MIT"
] | permissive | #pragma once
////
//
// STM32H7 CRC peripherals
//
///
// CRC: Cryptographic processor
struct stm32h723_crc_t
{
volatile uint32_t DR; // Data register
volatile uint32_t IDR; // Independent Data register
volatile uint32_t CR; // Control register
reserved_t<0x1> _0xc;
volatile uint32_t INIT; // Initial CRC value
volatile uint32_t POL; // CRC polynomial
static constexpr uint32_t DR_RESET_VALUE = 0xffffffff; // Reset value
typedef bit_field_t<0, 0xffffffff> DR_DR; // Data Register
static constexpr uint32_t IDR_RESET_VALUE = 0x0; // Reset value
typedef bit_field_t<0, 0xffffffff> IDR_IDR; // Independent Data register
static constexpr uint32_t CR_RESET_VALUE = 0x0; // Reset value
static constexpr uint32_t CR_RESET = 0x1; // RESET bit
typedef bit_field_t<3, 0x3> CR_POLYSIZE; // Polynomial size
typedef bit_field_t<5, 0x3> CR_REV_IN; // Reverse input data
static constexpr uint32_t CR_REV_OUT = 0x80; // Reverse output data
static constexpr uint32_t INIT_RESET_VALUE = 0x0; // Reset value
typedef bit_field_t<0, 0xffffffff> INIT_CRC_INIT; // Programmable initial CRC value
static constexpr uint32_t POL_RESET_VALUE = 0x0; // Reset value
typedef bit_field_t<0, 0xffffffff> POL_POL; // Programmable polynomial
};
// CRC: Cryptographic processor
struct stm32h742x_crc_t
{
volatile uint32_t DR; // Data register
volatile uint32_t IDR; // Independent Data register
volatile uint32_t CR; // Control register
volatile uint32_t INIT; // Initial CRC value
volatile uint32_t POL; // CRC polynomial
static constexpr uint32_t DR_RESET_VALUE = 0xffffffff; // Reset value
typedef bit_field_t<0, 0xffffffff> DR_DR; // Data Register
static constexpr uint32_t IDR_RESET_VALUE = 0x0; // Reset value
typedef bit_field_t<0, 0xffffffff> IDR_IDR; // Independent Data register
static constexpr uint32_t CR_RESET_VALUE = 0x0; // Reset value
static constexpr uint32_t CR_RESET = 0x1; // RESET bit
typedef bit_field_t<3, 0x3> CR_POLYSIZE; // Polynomial size
typedef bit_field_t<5, 0x3> CR_REV_IN; // Reverse input data
static constexpr uint32_t CR_REV_OUT = 0x80; // Reverse output data
static constexpr uint32_t INIT_RESET_VALUE = 0x0; // Reset value
typedef bit_field_t<0, 0xffffffff> INIT_CRC_INIT; // Programmable initial CRC value
static constexpr uint32_t POL_RESET_VALUE = 0x0; // Reset value
typedef bit_field_t<0, 0xffffffff> POL_POL; // Programmable polynomial
};
template<>
struct peripheral_t<STM32H723, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h723_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H73x, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h723_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H742x, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H743, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H745_CM4, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H745_CM7, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H747_CM4, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H747_CM7, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H750x, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H753, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H755_CM4, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H755_CM7, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H757_CM4, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H757_CM7, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H7A3x, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H7B0x, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
template<>
struct peripheral_t<STM32H7B3x, CRC>
{
static constexpr periph_t P = CRC;
using T = stm32h742x_crc_t;
static T& V;
};
using crc_t = peripheral_t<svd, CRC>;
template<int INST> struct crc_traits {};
template<> struct crc_traits<0>
{
using crc = crc_t;
static constexpr clock_source_t CLOCK = AHB_PERIPH;
template<typename RCC>
static void enable()
{
RCC::V.AHB4ENR |= RCC::T::AHB4ENR_CRCEN;
__asm volatile ("dsb"); // dm00037591 2.1.13
}
template<typename RCC>
static void disable()
{
RCC::V.AHB4ENR &= ~RCC::T::AHB4ENR_CRCEN;
}
template<typename RCC>
static void reset()
{
RCC::V.AHB4RSTR |= RCC::T::AHB4RSTR_CRCRST;
}
};
| true |
f2de5f1cf2c71c57f57cc2b9c401dff862778317 | C++ | shenshengyi/ShenShengYi | /ShenShengYi/UT/UT/School_Test.cpp | UTF-8 | 1,008 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "pch.h"
#include "School_Test.h"
#include <Student.h>
#include <iostream>
using namespace std;
void School_Test::SetUpTestCase(void) {
}
void School_Test::TearDownTestCase(void) {
}
void School_Test::SetUp() {
_shool = STU::School::GetInstance();
}
void School_Test::TearDown() {
STU::School::Release();
}
int add1(int a, int b) {
return a + b;
}
TEST_F(School_Test, GetStudentNum) {
_shool->AddStudent();
int num = _shool->GetStudentNum();
auto result = _shool->FindStudentByClassNum(5);
for (auto student : result) {
cout << student->GetStudentInformation().GetClassNum() << endl;
}
//STU::Student** studentBegin = _shool->StudentIteratorBegin();
//STU::Student** studentEnd = _shool->StudentIteratorEnd();
//int i = 0;
//while (studentBegin != studentEnd) {
// if (nullptr != studentBegin) {
// cout << (*studentBegin)->GetStudentInformation().GetName() << " " << (*studentBegin)->GetStudentInformation().GetClassNum() << endl;
// }
// studentBegin++;
// i++;
//}
}
| true |
b2ecf20593a8df8025497331667a5ae1523b0e8b | C++ | hakimbalestrieri/INF2 | /recueil_d_exercices_inf2/chapitre_07/exercice_09/main.cpp | UTF-8 | 1,642 | 3.5625 | 4 | [] | no_license |
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
class Voiture {
friend void afficherVoiture(const Voiture& voiture);
public:
Voiture(int capacite, float conso) : m_capaciteReservoir(capacite),
m_consoMoyenne(conso) {
m_fuelRestant = capacite;
}
static void setPrixEssence(float newPrice) {
s_prixEssence = newPrice;
}
static float getPrixEssence() {
return s_prixEssence;
}
float coutTrajet(const int kilometres){
return 0.f;
}
private:
static float s_prixEssence;
int m_capaciteReservoir;
float m_consoMoyenne;
float m_fuelRestant;
};
float Voiture::s_prixEssence = 1.5;
void afficherPrixEsssence(const float prix) {
cout << "Prix de l'essence : " << setprecision(2)
<< prix << " Frs" << endl;
}
void afficherVoiture(const Voiture& voiture) {
cout << "Capacite du reservoir [l] \t : " << voiture.m_capaciteReservoir << endl
<< "Consommation moyenne [l/100km]\t : " << voiture.m_consoMoyenne << endl
<< "Nb litre restants \t : " << voiture.m_fuelRestant << endl << endl;
}
void afficherCoutTrajet(float prix){
cout << "Cout du trajet : " << prix << " Frs" << endl;
}
int main() {
afficherPrixEsssence(Voiture::getPrixEssence());
Voiture::setPrixEssence(1.34);
afficherPrixEsssence(Voiture::getPrixEssence());
Voiture v(52, 6.7);
afficherVoiture(v);
afficherCoutTrajet(v.coutTrajet(1000));
afficherVoiture(v);
afficherCoutTrajet(v.coutTrajet(200));
afficherVoiture(v);
return EXIT_SUCCESS;
}
| true |
5053ef4c8023a969b27587f2aaafac5e921612ce | C++ | Ccccaramel/C | /Base/CPP/3-强制类型转换.cpp | UTF-8 | 337 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
// C 中的强制类型转换
int m = 5;
double n = (double)m;
cout << "n:" << n << endl;
// C++ 的扩充,使得强制类型转换执行起来像是调用了函数(推荐使用该方法)
int i = 10;
double j = double(i);
cout << "j:" << j << endl;
} | true |
e55b6c2b41ee5c248120dcfccc7e038142d2d8c3 | C++ | ngc2628/swdev | /cpp/app/main.cpp | UTF-8 | 1,067 | 2.53125 | 3 | [] | no_license |
#include <stdio.h>
#include <stdlib.h>
#include <auxx/auxx.h>
#include <osix/xxstyle.h>
int usage() {
printf ("rgb2int color|r,b,g[,a]\n");
return 0;
}
int main(int argc,char **argv) {
if (argc!=2)
return usage();
char *tok=strtok(argv[1],",");
if (!tok)
return usage();
aux::Asciistr str1,str2;
int base=-1;
mk_ulreal cc=mk_a2ui(tok,&base);
unsigned short rr=0,gg=0,bb=0,aa=255;
tok=strtok(0,",");
if (!tok) {
aux::ui2a(cc,&str1,10);
aux::ui2a(cc,&str2,16);
osix::xxrgba((unsigned int)cc,&rr,&gg,&bb,&aa);
printf ("color=%s[%s] r=%u g=%u b=%u a=%u\n",(const char*)str1,(const char*)str2,rr,gg,bb,aa);
return 0;
}
rr=(unsigned short)cc;
base=-1;
gg=(unsigned short)mk_a2ui(tok,&base);
tok=strtok(0,",");
if (tok) {
base=-1;
bb=(unsigned short)mk_a2ui(tok,&base);
tok=strtok(0,",");
if (tok) {
base=-1;
aa=(unsigned short)mk_a2ui(tok,&base);
}
}
cc=osix::xxcolor(rr,gg,bb,aa);
printf ("color=%lld r=%u g=%u b=%u a=%u\n",cc,rr,gg,bb,aa);
return 0;
}
| true |
6d2ff61d5696a337a6ad79e074e302e673c89085 | C++ | cyb70289/mytests | /memory-order/test2.cc | UTF-8 | 731 | 2.6875 | 3 | [] | no_license | #include <future>
#include <iostream>
#include <thread>
#ifdef __aarch64__
#define mb() __asm__ __volatile__("dmb ish" : : : "memory")
#else
#define mb() __asm__ __volatile__("mfence")
#endif
volatile int x, y;
int f1() {
x = 1;
return y;
}
int f2() {
y = 1;
return x;
}
int main(void) {
long test_count = 0, oo_count = 0;
while (1) {
x = y = 0;
auto fut1 = std::async(f1);
auto fut2 = std::async(f2);
int r1 = fut1.get();
int r2 = fut2.get();
if (r1 == 0 && r2 == 0) {
std::cout << "out of order observed!!!\n";
++oo_count;
}
++test_count;
if (test_count % 10000 == 0) {
std::cout << test_count << ':' << oo_count << '\n';
}
}
return 0;
}
| true |
7677fb8ad77c03b9ebe00fe371538470eb492c99 | C++ | BebeShen/LeetCodePracticeRecords | /Algorithm/1678. Goal Parser Interpretation/Goal Parser Interpretation.cpp | UTF-8 | 542 | 2.796875 | 3 | [] | no_license | class Solution {
public:
string interpret(string command) {
int length = command.length(), p= 0;
string ans = "";
while(p<length){
if(command[p]=='G'){
ans+="G";
p++;
}
else{
if(command[p+1]==')'){
ans+="o";
p+=2;
}
else{
ans+="al";
p+=4;
}
}
}
return ans;
}
}; | true |
eacf0284f35301bd3230867650e0d8d177cad2ca | C++ | Cell-Woworld/cell | /inc/internal/utils/cell_utils.h | UTF-8 | 2,522 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef __cell_utils_h__
#define __cell_utils_h__
#include "IBiomolecule.h"
#include "internal/utils/nlohmann/json.hpp"
#include <iomanip>
BIO_BEGIN_NAMESPACE
String EscapeJSONString(const String& in, bool escape_quote)
{
std::ostringstream o;
for (auto c = in.cbegin(); c != in.cend(); c++) {
switch (*c) {
case '"': {
if (escape_quote)
o << "\\\"";
break;
}
case '\b': o << "\\b"; break;
case '\f': o << "\\f"; break;
case '\n':
o << "\\r\\n";
break;
case '\r': {
if (c + 1 == in.cend() || *(c + 1) != '\n')
o << "\\r\\n";
break;
}
case '\t': o << "\\t"; break;
case '\\': {
if (c + 1 != in.cend())
{
switch (*(c + 1))
{
case '\\':
if (escape_quote)
{
c++;
o << "\\\\\\\\";
}
else
{
c++;
o << "\\" << *c;
}
break;
case '"':
if (escape_quote)
{
c++;
o << "\\\\\\\"";
}
else
{
c++;
o << "\\" << *c;
}
break;
case 'f':
case 'n':
case 'r':
case 't':
if (escape_quote)
{
c++;
o << "\\\\" << *c;
}
else
{
c++;
o << "\\" << *c;
}
break;
case 'u':
{
o << "\\u";
c += 2;
for (int i = 0; i < 4 && c != in.cend(); i++, c++)
{
o << *c;
};
break;
}
default:
if (escape_quote)
{
o << "\\\\";
}
else
{
o << "\\";
}
break;
}
}
else
{
if (escape_quote)
{
o << "\\\\";
}
else
{
o << "\\";
}
}
break;
}
default:
if ('\x00' <= *c && *c <= '\x1f') {
o << "\\u"
<< std::hex << std::setw(4) << std::setfill('0') << (int)*c;
}
else {
o << *c;
}
}
}
return o.str();
}
void EscapeJSON(const String& in, String& out)
{
out = "";
size_t _start_pos = in.find_first_of('\"');
if (_start_pos != String::npos && _start_pos > 0)
out += in.substr(0, _start_pos);
size_t _end_pos = String::npos;
while (_start_pos != String::npos && (_end_pos = in.find_first_of('\"', _start_pos + 1)) != String::npos)
{
if (_end_pos - _start_pos > 1)
out += "\"" + EscapeJSONString(in.substr(_start_pos + 1, _end_pos - _start_pos - 1), false) + "\"";
else
out += "\"\"";
_start_pos = in.find_first_of('\"', _end_pos + 1);
out += in.substr(_end_pos + 1, _start_pos - _end_pos - 1);
}
if (_start_pos != String::npos && _start_pos > 0)
out += in.substr(_start_pos);
}
BIO_END_NAMESPACE
#endif
| true |
c97064293ff7dd4b8cec162cfc213711c5b6bae9 | C++ | dqtweb/aixue2 | / aixue2/WeiWeiClient/thirdparty/Theron/Samples/FallbackHandler/Main.cpp | UTF-8 | 3,159 | 3.296875 | 3 | [
"MIT"
] | permissive | // Copyright (C) by Ashton Mason. See LICENSE.txt for licensing information.
//
// This sample shows how to use a fallback handler to catch unhandled messages.
//
#include <stdio.h>
#include <Theron/Actor.h>
#include <Theron/Address.h>
#include <Theron/Framework.h>
#include <Theron/Receiver.h>
// Trivial actor that ignores all messages, so that any sent to it
// are passed on the fallback handler registered with its owning framework.
class Actor : public Theron::Actor
{
};
// A simple non-trivial test message with some readable data.
struct Message
{
Message(const int a, const float b) : mA(a), mB(b)
{
}
int mA;
float mB;
};
// Simple fallback handler object that logs unhandled messages to stdout.
// Note that this handler is not threadsafe in the sense that if called
// multiple times concurrently (which can happen) then the printf output
// of the different calls will be interleaved. We live with that here, but
// if the class contained member data (for example a log string) then we would
// need to add a critical section to protect access to the shared data.
class FailedMessageLog
{
public:
// This handler is a 'blind' handler which takes the unhandled message as raw data.
inline void Handle(const void *const data, const Theron::uint32_t size, const Theron::Address from)
{
printf("Unhandled message of %d bytes sent from address %d:\n", size, from.AsInteger());
// Dump the message data as hex words.
if (data)
{
const char *const format("[%d] 0x%08x\n");
const unsigned int *const begin(reinterpret_cast<const unsigned int *>(data));
const unsigned int *const end(begin + size / sizeof(unsigned int));
for (const unsigned int *word(begin); word != end; ++word)
{
printf(format, static_cast<int>(word - begin), *word);
}
}
}
};
int main()
{
Theron::Framework framework;
Theron::Receiver receiver;
// Register the custom fallback handler with the framework.
// This handler is executed for any messages that either aren't delivered
// or aren't handled by the actors to which they are delivered.
// The default fallback handler asserts, which is useful but not so pretty
// in an example. So here we show how to register a custom handler.
FailedMessageLog log;
framework.SetFallbackHandler(&log, &FailedMessageLog::Handle);
// Create an actor and send some messages to it, which it doesn't handle.
// The messages are delivered but not handled by the actor, so are
// caught by the log registered as the framework's default fallback message handler.
Theron::ActorRef actor(framework.CreateActor<Actor>());
printf("Sending message (16384, 1.5f) to actor\n");
framework.Send(Message(16384, 1.5f), receiver.GetAddress(), actor.GetAddress());
printf("Sending message (507, 2.0f) to actor\n");
framework.Send(Message(507, 2.0f), receiver.GetAddress(), actor.GetAddress());
return 0;
}
| true |
8bb939a4a000d029ed0b05bfc7051bca14a8b619 | C++ | lineCode/sprout | /source/base/math/quaternion.inl | UTF-8 | 9,859 | 2.9375 | 3 | [] | no_license | #ifndef SU_BASE_MATH_QUATERNION_INL
#define SU_BASE_MATH_QUATERNION_INL
#include "matrix3x3.inl"
#include "quaternion.hpp"
namespace math {
/****************************************************************************
*
* Generic quaternion
*
****************************************************************************/
/*
template<typename T>
Quaternion<T>::Quaternion() {}
template<typename T>
Quaternion<T>::Quaternion(T x, T y, T z, T w) : x(x), y(y), z(z), w(w) {}
template<typename T>
Quaternion<T>::Quaternion(const Matrix3x3<T>& m) {
T trace = m.m00 + m.m11 + m.m22;
T temp[4];
if (trace > T(0)) {
T s = std::sqrt(trace + T(1));
temp[3] = s * T(0.5);
s = T(0.5) / s;
temp[0] = (m.m21 - m.m12) * s;
temp[1] = (m.m02 - m.m20) * s;
temp[2] = (m.m10 - m.m01) * s;
} else {
int i = m.m00 < m.m11 ? (m.m11 < m.m22 ? 2 : 1) : (m.m00 < m.m22 ? 2 : 0);
int j = (i + 1) % 3;
int k = (i + 2) % 3;
T s = std::sqrt(m.m[i * 3 + i] - m.m[j * 3 + j] - m.m[k * 3 + k] + T(1));
temp[i] = s * T(0.5);
s = T(0.5) / s;
temp[3] = (m.m[k * 3 + j] - m.m[j * 3 + k]) * s;
temp[j] = (m.m[j * 3 + i] + m.m[i * 3 + j]) * s;
temp[k] = (m.m[k * 3 + i] + m.m[i * 3 + k]) * s;
}
x = temp[0];
y = temp[1];
z = temp[2];
w = temp[3];
}
template<typename T>
Quaternion<T> Quaternion<T>::operator*(const Quaternion<T>& q) const {
return Quaternion<T>(w * q[0] + x * q[3] + y * q[2] - z * q[1],
w * q[1] + y * q[3] + z * q[0] - x * q[2],
w * q[2] + z * q[3] + x * q[1] - y * q[0],
w * q[3] - x * q[0] - y * q[1] - z * q[2]);
}
template<typename T>
const Quaternion<T> Quaternion<T>::identity(T(0), T(0), T(0), T(1));
template<typename T>
T dot(const Quaternion<T>& a, const Quaternion<T>& b) {
return (a[0] * b[0] + a[1] * b[1]) + (a[2] * b[2] + a[3] * b[3]);
}
template<typename T>
T length(const Quaternion<T>& q) {
return std::sqrt(dot(q, q));
}
template<typename T>
T angle(const Quaternion<T>& a, const Quaternion<T>& b) {
T s = std::sqrt(dot(a, a) * dot(b, b));
return std::acos(dot(a, b) / s);
}
template<typename T>
void set_rotation_x(Quaternion<T>& q, T a) {
q[0] = std::sin(a * T(0.5));
q[1] = T(0);
q[2] = T(0);
q[3] = std::cos(a * T(0.5));
}
template<typename T>
void set_rotation_y(Quaternion<T>& q, T a) {
q[0] = T(0);
q[1] = std::sin(a * T(0.5));
q[2] = T(0);
q[3] = std::cos(a * T(0.5));
}
template<typename T>
void set_rotation_z(Quaternion<T>& q, T a) {
q[0] = T(0);
q[1] = T(0);
q[2] = std::sin(a * T(0.5));
q[3] = std::cos(a * T(0.5));
}
template<typename T>
void set_rotation(Quaternion<T>& q, Vector3<T> const& v, T a) {
const T d = length(v);
const T s = std::sin(a * T(0.5)) / d;
q[0] = v[0] * s;
q[1] = v[1] * s;
q[2] = v[2] * s;
q[3] = cos(a * T(0.5));
}
template<typename T>
void set_rotation(Quaternion<T>& q, T yaw, T pitch, T roll) {
const T half_yaw = yaw * T(0.5);
const T half_pitch = pitch * T(0.5);
const T half_roll = roll * T(0.5);
const T cos_yaw = std::cos(half_yaw);
const T sin_yaw = std::sin(half_yaw);
const T cos_pitch = std::cos(half_pitch);
const T sin_pitch = std::sin(half_pitch);
const T cos_roll = std::cos(half_roll);
const T sin_roll = std::sin(half_roll);
q[0] = cos_roll * sin_pitch * cos_yaw + sin_roll * cos_pitch * sin_yaw;
q[1] = cos_roll * cos_pitch * sin_yaw - sin_roll * sin_pitch * cos_yaw;
q[2] = sin_roll * cos_pitch * cos_yaw - cos_roll * sin_pitch * sin_yaw;
q[3] = cos_roll * cos_pitch * cos_yaw + sin_roll * sin_pitch * sin_yaw;
}
template<typename T>
Quaternion<T> slerp(const Quaternion<T>& a, const Quaternion<T>& b, T t) {
// calc cosine theta
T cosom = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
// adjust signs (if necessary)
Quaternion<T> end = b;
if (cosom < T(0)) {
cosom = -cosom;
end[0] = -end[0]; // Reverse all signs
end[1] = -end[1];
end[2] = -end[2];
end[3] = -end[3];
}
// Calculate coefficients
float sclp;
float sclq;
// 0.0001 -> some epsillon
if (T(1) - cosom > T(0.0001)) {
// Standard case (slerp)
float omega = std::acos(cosom); // extract theta from dot product's cos theta
float sinom = std::sin(omega);
sclp = std::sin((T(1) - t) * omega) / sinom;
sclq = std::sin(t * omega) / sinom;
} else {
// Very close, do linear interpolation (because it's faster)
sclp = T(1) - t;
sclq = t;
}
return Quaternion<T>(sclp * a[0] + sclq * end[0],
sclp * a[1] + sclq * end[1],
sclp * a[2] + sclq * end[2],
sclp * a[3] + sclq * end[3]);
}
*/
/****************************************************************************
*
* Aligned quaternon functions
*
****************************************************************************/
namespace quaternion {
static inline Quaternion create(float3x3 const& m) noexcept {
float const trace = m.r[0][0] + m.r[1][1] + m.r[2][2];
Quaternion temp;
if (trace > 0.f) {
float s = std::sqrt(trace + 1.f);
temp[3] = s * 0.5f;
s = 0.5f / s;
temp[0] = (m.r[2][1] - m.r[1][2]) * s;
temp[1] = (m.r[0][2] - m.r[2][0]) * s;
temp[2] = (m.r[1][0] - m.r[0][1]) * s;
} else {
uint32_t const i = m.r[0][0] < m.r[1][1] ? (m.r[1][1] < m.r[2][2] ? 2u : 1u)
: (m.r[0][0] < m.r[2][2] ? 2u : 0u);
uint32_t const j = (i + 1) % 3;
uint32_t const k = (i + 2) % 3;
float s = std::sqrt(m.r[i][i] - m.r[j][j] - m.r[k][k] + 1.f);
temp[i] = s * 0.5f;
s = 0.5f / s;
temp[3] = (m.r[k][j] - m.r[j][k]) * s;
temp[j] = (m.r[j][i] + m.r[i][j]) * s;
temp[k] = (m.r[k][i] + m.r[i][k]) * s;
}
return temp;
}
static inline float3x3 create_matrix3x3(Quaternion const& q) noexcept {
float const d = dot(q, q);
float const s = 2.f / d;
float const xs = q[0] * s;
float const ys = q[1] * s;
float const zs = q[2] * s;
float3x3 m;
{
float const xx = q[0] * xs;
float const yy = q[1] * ys;
float const zz = q[2] * zs;
m.r[0][0] = 1.f - (yy + zz);
m.r[1][1] = 1.f - (xx + zz);
m.r[2][2] = 1.f - (xx + yy);
}
{
float const xy = q[0] * ys;
float const wz = q[3] * zs;
m.r[0][1] = xy - wz;
m.r[1][0] = xy + wz;
}
{
float const xz = q[0] * zs;
float const wy = q[3] * ys;
m.r[0][2] = xz + wy;
m.r[2][0] = xz - wy;
}
{
float const yz = q[1] * zs;
float const wx = q[3] * xs;
m.r[1][2] = yz - wx;
m.r[2][1] = yz + wx;
}
return m;
}
static inline Quaternion create_rotation_x(float a) noexcept {
return Quaternion(std::sin(a * 0.5f), 0.f, 0.f, std::cos(a * 0.5f));
}
static inline Quaternion create_rotation_y(float a) noexcept {
return Quaternion(0.f, std::sin(a * 0.5f), 0.f, std::cos(a * 0.5f));
}
static inline Quaternion create_rotation_z(float a) noexcept {
return Quaternion(0.f, 0.f, std::sin(a * 0.5f), std::cos(a * 0.5f));
}
static inline Quaternion mul(Quaternion const& a, Quaternion const& b) noexcept {
return Quaternion((a[3] * b[0] + a[0] * b[3]) + (a[1] * b[2] - a[2] * b[1]),
(a[3] * b[1] + a[1] * b[3]) + (a[2] * b[0] - a[0] * b[2]),
(a[3] * b[2] + a[2] * b[3]) + (a[0] * b[1] - a[1] * b[0]),
(a[3] * b[3] - a[0] * b[0]) - (a[1] * b[1] + a[2] * b[2]));
}
static inline Quaternion slerp(Quaternion const& a, Quaternion const& b, float t) noexcept {
// calc cosine theta
float cosom = (a[0] * b[0] + a[1] * b[1]) + (a[2] * b[2] + a[3] * b[3]);
// adjust signs (if necessary)
Quaternion end = b;
if (cosom < 0.f) {
cosom = -cosom;
end[0] = -end[0]; // Reverse all signs
end[1] = -end[1];
end[2] = -end[2];
end[3] = -end[3];
}
// Calculate coefficients
float sclp;
float sclq;
// 0.0001 -> some epsillon
if (1.f - cosom > 0.0001f) {
// Standard case (slerp)
float const omega = std::acos(cosom); // extract theta from dot product's cos theta
float const sinom = std::sin(omega);
sclp = std::sin((1.f - t) * omega) / sinom;
sclq = std::sin(t * omega) / sinom;
} else {
// Very close, do linear interpolation (because it's faster)
sclp = 1.f - t;
sclq = t;
}
return Quaternion(sclp * a[0] + sclq * end[0], sclp * a[1] + sclq * end[1],
sclp * a[2] + sclq * end[2], sclp * a[3] + sclq * end[3]);
}
static inline constexpr Quaternion identity() noexcept {
return Quaternion(0.f, 0.f, 0.f, 1.f);
}
} // namespace quaternion
} // namespace math
#endif
| true |
344c1e7dab952f18a406dfbb0a64f9f09f86f2e1 | C++ | Mutanne/hiworld | /eng_mecat_bkp/Prog2/lista d 25/E_15.cpp | UTF-8 | 614 | 3.3125 | 3 | [
"Unlicense"
] | permissive | #include<iostream>
#include<stdlib.h>
using namespace std;
//fatorial com recursividade
int fat(int n){
if(n>0){
return(n*fat(n-1));
}
else{ return 1; }
}
int main(){
int n,n2;
char sai;
do{
system("color f0");
system("cls");
cout<<"Digite o numero inteiro: ";
cin>>n;
n2=2*n-1;
cout<<"(2*"<<n<<"-1) = "<<n2<<"\n"<<n2<<"! = "<<fat(n2)<<endl;
cout<<"Digite \"C\" p continuar,outra letra para sair: ";
cin>>sai;
}while(sai=='c'||sai=='C');
system("cls");
cout<<"\nAte mais...\n\n";
system("pause");
}
| true |
3d4d51324b78741d1cf0650fe3c5f6dad52e198f | C++ | suyuan945/LeetCode | /378_KthSmallest/378_KthSmallest.cpp | UTF-8 | 3,269 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <functional>
using namespace std;
class Solution // BST 39ms
{
public:
int kthSmallest(vector<vector<int>>& matrix, int k)
{
int n = matrix.size();
int le = matrix[0][0], ri = matrix[n - 1][n - 1];
int mid = 0;
while (le < ri)
{
mid = le + (ri - le) / 2;
int num = 0;
for (int i = 0; i < n; i++)
{
int pos = upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
num += pos;
}
if (num < k)
{
le = mid + 1;
}
else
{
ri = mid;
}
}
return le;
}
};
class SolutionPQ{ // 52ms O(klog(n))
public:
int kthSmallest(vector<vector<int>>& arr, int k){
int n = arr.size(), m = arr[0].size();
priority_queue < pair<int, pair<int, int>>,
vector<pair<int, pair<int, int>>>,
greater < pair<int, pair<int, int>> >> pq;
for (int i = 0; i < n; ++i){
pq.push({ arr[i][0], {i, 0} });
}
int x = k, ans;
while (x--){
const auto t = pq.top(); pq.pop();
ans = t.first;
const int i = t.second.first;
const int j = t.second.second;
if (j != m - 1){
pq.push({ arr[i][j + 1], {i, j + 1} });
}
}
return ans;
}
};
class SolutionHS { // 400+ms O(n^2)
public:
int heapify(vector<vector<int>>& matrix, vector<vector<bool>>& mask){
const int n = matrix.size();
int i = 0, j = 0;
while (true){
int vp = matrix[i][j];
bool havelc = i < n - 1 && mask[i + 1][j];
bool haverc = j < n - 1 && mask[i][j + 1];
if ((!havelc) && (!haverc)){ // no lc no rc
return 0;
} else if(havelc && (!haverc)){ // only have lc
if (matrix[i+1][j] < matrix[i][j]){
swap(matrix[i+1][j], matrix[i][j]);
i = i + 1;
} else{
return 0;
}
} else if((!havelc) && haverc){ // only have rc
if (matrix[i][j + 1] < matrix[i][j]){
swap(matrix[i][j+1], matrix[i][j]);
j = j + 1;
} else{
return 0;
}
} else{ // choose largest
int minst = matrix[i][j];
pair<int, int> minid{ i, j };
if (matrix[i][j + 1] < matrix[i][j]){
minst = matrix[i][j + 1];
minid = { i, j + 1 };
}
if (matrix[i + 1][j] < minst){
minst = matrix[i + 1][j];
minid = { i + 1, j };
}
if (minid != pair<int, int>{i, j}){
swap(matrix[i][j], matrix[minid.first][minid.second]);
i = minid.first;
j = minid.second;
} else{
return 0;
}
}
}
}
int kthSmallest(vector<vector<int>>& matrix, int k) {
const int n = matrix.size();
if (n == 0 || k <= 0 || k > n*n){
return 0;
}
vector<vector<bool>> mask(n, vector<bool>(n, true)); // true in avalible
int i = n-1, j = n-1, res = 0, ii = 1;
while (ii < k){
ii++;
swap(matrix[i][j], matrix[0][0]);
mask[i][j] = false;
heapify(matrix, mask);
if (j == 0){
j = n - 1;
i -= 1;
continue;
}
j -= 1;
}
return matrix[0][0];
}
};
int main(int argc, char *argv[]){
Solution s;
vector<vector<int>> v{ { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };
for (int k = 1; k < 10; ++k)
cout << s.kthSmallest(v, k) << endl;
system("pause");
return 0;
}
| true |
61eab5e3d37a2c4b2f5e19188587c5fe818130ed | C++ | vnesp-donnu/turing | /turing.cpp | UTF-8 | 5,182 | 2.75 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
const int MAX_TIME = 1000;
const int MaxQSize = 100;
const int MaxASize = 100;
const int MaxTapeLen = 10000;
struct DeltaValue {
char newChar;
int newState;
short shift;
bool read(int defaultState, char defaultChar, bool debug) {
newChar = defaultChar;
shift = 0;
newState = defaultState;
char buffer[100];
scanf("%s", buffer);
if (debug)
printf("%d, %c -> %s\n", defaultState, defaultChar, buffer);
char *s = buffer;
if (s[0] == '-' && s[1] == 0) {
newState = -1;
return true;
}
if (*s != ',')
newChar = *s++;
if (*s != ',') {
printf("Invalid char in state %d for char %c", defaultState, defaultChar);
return false;
}
s++;
if (*s != ',') {
shift = (*s == 'R') - (*s == 'L');
s++;
}
if (*s != ',') {
printf("Invalid shift in state %d for char %c", defaultState, defaultChar);
return false;
}
s++;
if (*s) {
if (*s == 'q')
s++;
if (sscanf(s, "%d", &newState) != 1 || newState < 0) {
printf("Invalid state in state %d for char %c", defaultState, defaultChar);
return false;
}
}
// printf("%c,%d,%d\t", newChar, shift, newState);
return true;
}
void print() const {
printf("newChar = '%c', shift = %hd, newState = %d\n", newChar, shift, newState);
}
};
struct Answer {
int pos;
char strip[2 * MaxTapeLen + 1];
void read() {
scanf("%d", &pos);
scanf("%s", strip);
}
};
struct Tape {
char space[2 * MaxTapeLen + 1];
char *strip;
int leftBound, rightBound;
int pos;
Tape() {
strip = space + MaxTapeLen;
}
void read(char emptyChar) {
scanf("%d%d", &leftBound, &rightBound);
for (int i = leftBound; i <= rightBound; i++)
strip[i] = emptyChar;
scanf("%d", &pos);
scanf("%s", strip + pos);
strip[pos + strlen(strip + pos)] = emptyChar;
scanf("%d", &pos);
}
bool check(const Answer& ans) {
int len = strlen(ans.strip);
int shift = pos - ans.pos;
return strncmp(ans.strip, strip + shift, len) == 0;
}
char get() {
return strip[pos];
}
void put(char c) {
strip[pos] = c;
}
bool move(int shift) {
pos += shift;
return (leftBound <= pos && pos <= rightBound);
}
void print() {
for (int i = leftBound; i <= rightBound; i++) {
putchar(strip[i]);
}
putchar('\n');
for (int i = leftBound; i <= rightBound; i++) {
putchar((i==pos) ? '^' : ' ');
}
putchar('\n');
}
};
struct TuringMachine {
int QSize;
int ASize;
char A[MaxASize+1];
DeltaValue delta[MaxQSize][MaxASize];
int invA[256];
Tape tape;
Answer ans;
int state;
void makeinvA() {
for (int i = 0; i < 256; i++)
invA[i] = -1;
unsigned char c;
for (int i = 0; c = A[i], c; i++)
invA[c] = i;
}
bool read(bool debug) {
scanf("%d", &QSize);
scanf("%s", A);
// puts(A);
ASize = strlen(A);
makeinvA();
for (int q = 0; q < QSize; q++)
for (int i = 0; i < ASize; i++)
if (!delta[q][i].read(q, A[i], debug))
return false;
return true;
}
void init() {
state = 0;
}
void readTape() {
tape.read(A[0]);
}
void readAnswer() {
ans.read();
}
bool stepOver(bool debug) {
unsigned char c = tape.get();
if (debug) {
tape.print();
printf("state = %d currentChar = '%c'\n", state, c);
}
int i = invA[c];
if (i < 0 || i >= ASize) {
if (debug)
puts("Unknown char");
return false;
}
const DeltaValue& cur = delta[state][i];
if (debug)
cur.print();
tape.put(cur.newChar);
if (!tape.move(cur.shift)) {
puts("Position out of range");
return false;
}
state = cur.newState;
if (state < 0 || state > QSize) {
puts("Invalid state");
return false;
}
return true;
}
bool run(bool debug) {
int time = 0;
init();
while (0 <= state && state < QSize) {
time++;
if (time > MAX_TIME) {
puts("Time Limit Exceeded");
return false;
}
if (debug)
printf("Turn #%d:\n", time);
if (!stepOver(debug))
return false;
}
return true;
}
void readAndRun(bool debug) {
readTape();
readAnswer();
puts("Ininial Tape");
tape.print();
if (run(debug)) {
puts("Final Tape");
tape.print();
puts(tape.check(ans) ? "OK!" : "Wrong Answer");
}
else
puts("Error!");
puts("");
}
};
TuringMachine machine;
int main(int argc, char** argv) {
if (argc < 3) {
printf("Usage: turing <input_file> <output_file> [option]\n");
printf("Option:\n");
printf(" -d -- output debug information\n");
return -1;
}
if (freopen(argv[1], "r", stdin) == NULL) {
printf("File %s: reading error", argv[1]);
return -1;
}
if (freopen(argv[2], "w", stdout) == NULL) {
printf("File %s: creating error", argv[2]);
return -1;
}
bool debug = argc > 3 && strcmp(argv[3], "-d")==0;
if ( machine.read(debug) ) {
int NTest;
scanf("%d", &NTest);
for (int iTest = 1; iTest <= NTest; iTest++) {
printf("Test %d:\n", iTest);
machine.readAndRun(debug);
}
}
}
| true |
a92c9bda50a05e6d9d84ba40eea8717d3662712b | C++ | oyugibillbrian2017/c-codes | /makingtriangle.cpp | UTF-8 | 219 | 2.796875 | 3 | [] | no_license | // a program which prints hello five times on the screen
#include<iostream>
using namespace std;
main()
{
for(int a=1; a<=3; a++)
{
for( int x=1; x<=a; x++)
{
cout<<" * ";
}
cout<<endl;
}
return 0;
}
| true |
fc620baf1789cc080ab02fa2871bcbafa11abc1f | C++ | thomcc/ivcalc | /src/frontend/flagparser.cc | UTF-8 | 9,196 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "flagparser.hh"
#include <cstdint>
#include <sstream>
//#include <cfloat>
#include <cmath>
#include <algorithm>
namespace flag {
using namespace std;
Flag::Flag() : name(""), usage(""), def_value(""), value(nullptr) {}
Flag::Flag(string name, string usage, shared_ptr<Value> v)
: name(name), usage(usage), def_value(v->str()), value(v) {}
Error DoubleValue::set(string const &v) {
ErrorOr<double> eb = parse(v);
if (eb.good()) {
value = eb.value;
return Error();
} else return Error(eb);
}
Error IntValue::set(string const &v) {
ErrorOr<int> eb = parse(v);
if (eb.good()) {
value = eb.value;
return Error();
} else return Error(eb);
}
Error BoolValue::set(string const &v) {
ErrorOr<bool> eb = parse(v);
if (eb.good()) {
value = eb.value;
return Error();
} else return Error(eb);
}
ErrorOr<bool> BoolValue::parse(string const &s) {
const string trues[] = {
"1", "t", "T", "true", "TRUE", "True", "yes", "YES", "Yes", "y", "Y", "on", "ON", "On"
};
const string falses[] = {
"0", "f", "F", "false", "FALSE", "False", "no", "NO", "No", "n", "N", "off", "OFF", "Off"
};
for (auto const &t : trues) if (s == t) return ErrorOr<bool>(true);
for (auto const &f : falses) if (s == f) return ErrorOr<bool>(false);
return ErrorOr<bool>("SyntaxError: parse_bool");
}
string BoolValue::format(bool b) {
return b ? "true" : "false";
}
class to_s {
private:
ostringstream _ss;
public:
template <typename T> to_s&
operator<<(T const &v) { _ss << v; return *this; }
operator string() const { return _ss.str(); }
};
// can't use >> or atoi, etc. because of the lack of indication of failure.
static ErrorOr<int64_t>
parse_int(string s) {
char *end;
errno = 0;
long l = strtol(s.c_str(), &end, 0);
if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX)
return ErrorOr<int64_t>(to_s() << "Bad integer (overflow): " << s);
if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN)
return ErrorOr<int64_t>(to_s() << "Bad integer (underflow): " << s);
if (s[0] == '\0' || *end != '\0')
return ErrorOr<int64_t>(to_s() << "Bad integer (inconvertible): " << s);
return ErrorOr<int64_t>(l);
}
string IntValue::format(int v) {
return to_s() << v;
}
ErrorOr<int> IntValue::parse(string const &s) {
ErrorOr<int64_t> ei = parse_int(s);
if (ei.bad()) return ErrorOr<int>(ei.msg);
else return ErrorOr<int>(ei.value);
}
ErrorOr<double> parse_f64(string const &s) {
char *end;
errno = 0;
double d = strtod(s.c_str(), &end);
if (errno == ERANGE && d == HUGE_VAL)
return ErrorOr<double>(to_s() << "Bad double (overflow): " << s);
if (errno == ERANGE && d == -HUGE_VAL)
return ErrorOr<double>(to_s() << "Bad double (underflow): " << s);
if (s[0] == '\0' || *end != '\0')
return ErrorOr<double>(to_s() << "Bad double (inconvertible): " << s);
return ErrorOr<double>(d);
}
ErrorOr<double> DoubleValue::parse(string const &s) {
return parse_f64(s);
}
string DoubleValue::format(double v) {
return to_s() << v;
}
vector<Flag> FlagSet::sort_flags(map<string, Flag> const &flgs) const {
vector<string> list;
for (auto const &fp : flgs)
list.push_back(fp.first);
sort(list.begin(), list.end());
vector<Flag> result;
for (auto const &name : list)
result.push_back(flgs.at(name));
return result;
}
Error FlagSet::fail(string const &err) {
fprintf(Output(), "%s\n", err.c_str());
Usage();
return Error(err);
}
string FlagSet::Arg(int n) const {
if (n < 0 || n > args.size()) return "";
return args.at(n);
}
deque<string> FlagSet::Args() const {
return args;
}
int FlagSet::NArgs() const {
return args.size();
}
void FlagSet::Complain(std::string const &complaint) {
fprintf(Output(), "%s: error: ", name.c_str());
fputs(complaint.c_str(), Output());
Usage();
}
ErrorOr<bool> FlagSet::parse_one() {
if (!args.size()) return ErrorOr<bool>(false);
string s = args[0];
if (s.size() == 0 || s[0] != '-' || s.size() == 1)
return ErrorOr<bool>(false);
int ndash = 1;
if (s[1] == '-') {
++ndash;
if (s.size() == 2) {
args.pop_front();
return ErrorOr<bool>(false);
}
}
string name = s.substr(ndash);
if (name.size() == 0 || name[0] == '-' || name[0] == '=')
return fail("Bad Flag syntax: "+s);
args.pop_front();
bool has_value = false;
string value = "";
for (int i = 1; i < name.size(); ++i) { // '=' cant be first
if (name[i] == '=') {
value = name.substr(i+1);
has_value = true;
name = name.substr(0, i);
break;
}
}
auto const &it = formal.find(name); // bug
if (it == formal.end()) {
if (name == "help" || name == "h") { // special case: help message
return fail("help requested");
}
return fail("Flag provided but not defined: -"+name);
}
Flag f = it->second;
if (BoolValue *fv = f.value->as_bool()) { // special case: doesnt need arg
if (has_value) {
Error e = fv->set(value);
if (e.bad())
fail("invalid boolean value "+fv->str()+" for -"+name+": "+e.msg);
} else fv->set("true");
} else {
if (!has_value && args.size() > 0) {
// value is the next arg.
has_value = true;
value = args.front();
args.pop_front();
}
if (!has_value)
return fail("Flag needs an argument: -"+name);
Error e = f.value->set(value);
if (e.bad()) return fail("invalid value '"+value+"' for flag -"+name+": "+e.msg);
}
actual[name] = f;
return ErrorOr<bool>(true);
}
Error FlagSet::Parse() {
parsed = true;
for (;;) {
ErrorOr<bool> seen = parse_one();
if (seen.good() && seen.value) continue;
if (seen.good() && !seen.value) break;
switch (error_handling) {
case ContinueOnError: return seen;
case ExitOnError: exit(2);
case ThrowOnError: throw flag_error(seen);
}
}
return Error();
}
void FlagSet::SetArgs(int argc, char **argv) {
assert(argc != 0);
assert(argv != nullptr);
original_argc = argc;
original_argv = argv;
name = string(argv[0]);
args.clear();
actual.clear();
for (int i = 1; i < argc; ++i)
args.push_back(string(argv[i]));
parsed = false;
}
void FlagSet::SetUsage(function<void(FlagSet&)> fn) {
usage = fn;
}
void FlagSet::Usage() {
if (usage == nullptr) default_usage();
else usage(*this);
}
void FlagSet::VisitAll(function<void(Flag&)> fn) {
for (auto &f : sort_flags(formal)) fn(f);
}
void FlagSet::default_usage() {
fprintf(Output(), "Usage of %s: \n", name.c_str());
PrintDefaults();
}
void FlagSet::PrintDefaults() {
int longest = 0;
VisitAll([this, &longest](Flag &flag) {
const char *fmt = " -%s=%s";
if (flag.value->as_string()) fmt = " -%s='%s'";
size_t len = snprintf(NULL, 0, fmt, flag.name.c_str(), flag.def_value.c_str());
if (len > longest) longest = len;
});
VisitAll([this, longest](Flag &flag) {
const char *fmt = " -%s=%s:";
if (flag.value->as_string()) fmt = " -%s='%s':";
FILE *fp = Output();
size_t len = fprintf(fp, fmt, flag.name.c_str(), flag.def_value.c_str());
fflush(fp);
while (len++ < 4+longest) fputc(' ', fp);
fflush(fp);
fprintf(fp, "%s\n", flag.usage.c_str());
fflush(fp);
// fprintf(Output(), "%s", flag.name.c_str(), flag.def_value.c_str(), flag.usage.c_str());
});
}
void FlagSet::SetOutput(FILE *fp) { out = fp; }
void FlagSet::SetErrorHandling(ErrorHandling eh) {
error_handling = eh;
if (eh == ExitOnError) exit_on_error = true;
}
FlagSet::FlagSet(int argc, char **argv, FILE *fp, ErrorHandling eh)
: usage(nullptr), error_handling(eh), exit_on_error(eh==ExitOnError), out(fp)
{ SetArgs(argc, argv); }
void FlagSet::Var(shared_ptr<Value> v, string name, string usage) {
Flag f(name, usage, v);
auto alreadythere = formal.find(name);
if (alreadythere != formal.end()) {
fprintf(Output(), "%s flag redefined %s\n", this->name.c_str(), name.c_str());
fflush(Output());
throw flag_error("Flag Redefined");
}
formal[name] = f;
}
void FlagSet::Bool(bool &b, string name, string usage) {
shared_ptr<Value> v = static_pointer_cast<Value>(make_shared<BoolValue>(b));
Var(v, name, usage);
}
void FlagSet::Int(int &i, string name, string usage) {
shared_ptr<Value> v = static_pointer_cast<Value>(make_shared<IntValue>(i));
Var(v, name, usage);
}
void FlagSet::String(string &s, string name, string usage) {
shared_ptr<Value> v = static_pointer_cast<Value>(make_shared<StringValue>(s));
Var(v, name, usage);
}
void FlagSet::Double(double &d, string name, string usage) {
shared_ptr<Value> v = static_pointer_cast<Value>(make_shared<DoubleValue>(d));
Var(v, name, usage);
}
FILE *FlagSet::Output() const { return out ? out : stderr; }
bool FlagSet::Parsed() const { return parsed; }
FakeArgs::~FakeArgs() {
if (argv) {
for (size_t i = 0; i < argc; ++i)
if (argv[i]) free(argv[i]);
free(argv);
}
}
FakeArgs::FakeArgs() : argc(0), argv(nullptr) {}
FakeArgs::FakeArgs(FakeArgs const &fa) : argc(fa.argc), argv((char**)calloc(argc+2, sizeof(char*))) {
for (size_t i = 0; i < argc+2; ++i) {
if (fa.argv[i]) argv[i] = strdup(fa.argv[i]);
else argv[i] = nullptr;
}
}
FakeArgs FlagSet::Remaining() const {
deque<string> args = Args();
int n = args.size() + 2;
FakeArgs fa;
fa.argc = n-1;
fa.argv = (char**)calloc(n, sizeof(char*));
args.push_front(name);
for (size_t i = 0; i < args.size(); ++i)
fa.argv[i] = strdup(args.at(i).c_str());
fa.argv[n-1] = 0;
return fa;
}
} | true |
48ec768fd46e7bc3a7917864c4148a990d6f0a2f | C++ | jnannie21/cpp_modules | /module06/ex00/Converter.cpp | UTF-8 | 6,486 | 3.140625 | 3 | [] | no_license | //
// Created by jnannie on 12/27/20.
//
#include "Converter.hpp"
#include <cerrno>
#include <iostream>
static std::string const pseudo[6] = {
"-inff",
"+inff",
"nanf",
"-inf",
"+inf",
"nan"
};
Converter::Converter() {
}
Converter::Converter(Converter const &other) {
*this = other;
}
Converter &Converter::operator=(Converter const &other) {
if (this == &other)
return (*this);
_type = other._type;
_stringValue = other._stringValue;
_intValue = other._intValue;
_floatValue = other._floatValue;
_doubleValue = other._doubleValue;
_charValue = other._charValue;
_decimals = other._decimals;
return (*this);
}
Converter::~Converter() {
}
Converter::Converter(std::string const &stringValue) :
_type(NOTYPE), _stringValue(stringValue), _intValue(0), _floatValue(0.0), _doubleValue(0.0), _charValue('\0'), _decimals(1) {
_parse();
_countDecimals();
}
void Converter::printValues(void) {
if (_type == TYPE_CHAR)
_printChar();
else if (_type == TYPE_INT)
_printInt();
else if (_type == TYPE_FLOAT)
_printFloat();
else if (_type == TYPE_DOUBLE)
_printDouble();
else if (_type == TYPE_PSEUDO)
_printPseudo();
else
throw UnknownTypeException();
}
void Converter::_parse() throw(ConvertionNotPossibleException, OutOfRangeException) {
size_t length = _stringValue.length();
if (!std::isprint(_stringValue[0]) || std::isspace(_stringValue[0]))
throw ConvertionNotPossibleException();
// ******************************************* char
if (length == 1 && !std::isdigit(_stringValue[0]))
{
_charValue = _stringValue[0];
_type = TYPE_CHAR;
return ;
}
// ******************************************* pseudo
for (int i = 0; i < 6; i++)
{
if (_stringValue == pseudo[i])
{
_type = TYPE_PSEUDO;
return ;
}
}
if (_stringValue == "inf")
throw ConvertionNotPossibleException();
char *endptr;
double tempDouble = (strtod(_stringValue.c_str(), &endptr));
errno = 0;
if (errno == ERANGE)
throw OutOfRangeException();
// ******************************************* float
if (_stringValue.find('f') != std::string::npos)
{
size_t pos = _stringValue.find('.');
if (!isdigit(_stringValue[pos + 1]))
throw ConvertionNotPossibleException();
if (*(endptr + 1) != '\0')
throw ConvertionNotPossibleException();
if (tempDouble > std::numeric_limits<float>::max() || tempDouble < std::numeric_limits<float>::lowest())
throw OutOfRangeException();
_floatValue = static_cast<float>(tempDouble);
_type = TYPE_FLOAT;
return ;
}
// ******************************************* double
size_t pos = 0;
if ((pos = _stringValue.find('.')) != std::string::npos)
{
if (!isdigit(_stringValue[pos + 1]))
throw ConvertionNotPossibleException();
if (*endptr != '\0')
throw ConvertionNotPossibleException();
_doubleValue = tempDouble;
_type = TYPE_DOUBLE;
return ;
}
// ******************************************* int
size_t i = 0;
if (_stringValue[i] == '-' || _stringValue[i] == '+')
i++;
while (i < _stringValue.length())
{
if (!std::isdigit(_stringValue[i]))
throw ConvertionNotPossibleException();
i++;
}
if (tempDouble > std::numeric_limits<int>::max() || tempDouble < std::numeric_limits<int>::lowest())
throw OutOfRangeException();
_intValue = static_cast<int>(tempDouble);
_type = TYPE_INT;
}
void Converter::_countDecimals() {
if (_type <= TYPE_INT)
return ;
size_t i = 0;
size_t dot = _stringValue.find('.');
if (dot == std::string::npos)
return ;
dot++;
while (_stringValue[dot])
{
i++;
dot++;
}
if (i == 0)
return ;
_decimals = i;
if (_type == TYPE_FLOAT)
_decimals = i - 1;
}
void Converter::_printChar() {
if (std::isprint(_charValue) && !std::isspace(_charValue))
std::cout << "char: " << _charValue << std::endl;
else
std::cout << "char: " << "Non displayable" << std::endl;
std::cout << "int: " << static_cast<int>(_charValue) << std::endl;
std::cout.precision(_decimals);
std::cout << std::fixed;
std::cout << "float: " << static_cast<float>(_charValue) << "f" << std::endl;
std::cout << "double: " << static_cast<double>(_charValue) << std::endl;
}
void Converter::_printInt() {
if (std::isprint(static_cast<char>(_intValue)))
std::cout << "char: " << static_cast<char>(_intValue) << std::endl;
else
std::cout << "char: " << "Non displayable" << std::endl;
std::cout << "int: " << static_cast<int>(_intValue) << std::endl;
std::cout.precision(_decimals);
std::cout << std::fixed;
std::cout << "float: " << static_cast<float>(_intValue) << "f" << std::endl;
std::cout << "double: " << static_cast<double>(_intValue) << std::endl;
}
void Converter::_printFloat() {
if (std::isprint(static_cast<char>(_floatValue)))
std::cout << "char: " << static_cast<char>(_floatValue) << std::endl;
else
std::cout << "char: " << "Non displayable" << std::endl;
std::cout << "int: " << static_cast<int>(_floatValue) << std::endl;
std::cout.precision(_decimals);
std::cout << std::fixed;
std::cout << "float: " << static_cast<float>(_floatValue) << "f" << std::endl;
std::cout << "double: " << static_cast<double>(_floatValue) << std::endl;
}
void Converter::_printDouble() {
if (std::isprint(static_cast<char>(_doubleValue)))
std::cout << "char: " << static_cast<char>(_doubleValue) << std::endl;
else
std::cout << "char: " << "Non displayable" << std::endl;
std::cout << "int: " << static_cast<int>(_doubleValue) << std::endl;
std::cout.precision(_decimals);
std::cout << std::fixed;
std::cout << "float: " << static_cast<float>(_doubleValue) << "f" << std::endl;
std::cout << "double: " << static_cast<double>(_doubleValue) << std::endl;
}
void Converter::_printPseudo() {
std::cout << "char: " << "impossible" << std::endl;
std::cout << "int: " << "impossible" << std::endl;
if (_stringValue[0] == '-')
{
std::cout << "float: " << "-inff" << std::endl;
std::cout << "double: " << "-inf" << std::endl;
}
else if (_stringValue[0] == '+')
{
std::cout << "float: " << "+inff" << std::endl;
std::cout << "double: " << "+inf" << std::endl;
}
else
{
std::cout << "float: " << "nanf" << std::endl;
std::cout << "double: " << "nan" << std::endl;
}
}
const char *Converter::ConvertionNotPossibleException::what() const throw() {
return ("convertion is not possible");
}
const char *Converter::OutOfRangeException::what() const throw() {
return ("out of range");
}
const char *Converter::UnknownTypeException::what() const throw() {
return ("unknown type");
}
| true |
25141dce46719bf0de05ee888c1a5b0129f3dae5 | C++ | colinsongf/textnet-release | /src/initializer/var_init-inl.hpp | UTF-8 | 1,514 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef TEXTNET_VAR_INIT_INL_HPP_
#define TEXTNET_VAR_INIT_INL_HPP_
#include <mshadow/tensor.h>
#include "./initializer.h"
namespace textnet {
namespace initializer {
template<typename xpu, int dim>
class VarInitializer : public Initializer<xpu, dim>{
public:
VarInitializer(std::map<std::string, SettingV> &setting,
mshadow::Random<xpu>* prnd) {
this->prnd_ = prnd;
SetupInitializer(setting);
}
virtual ~VarInitializer(void) {}
virtual void Require(std::map<std::string, SettingV> &setting) {
// default value, just set the value you want
this->defaults["value"] = SettingV(0.0f);
// require value, set to SettingV(),
// it will force custom to set in config
Initializer<xpu, dim>::Require(setting);
}
virtual void SetupInitializer(std::map<std::string, SettingV> &setting) {
Initializer<xpu, dim>::SetupInitializer(setting);
this->init_type = setting["init_type"].iVal();
value = setting["value"].fVal();
}
virtual void DoInitialize(mshadow::Tensor<xpu, dim> data) {
int init_size = data.shape_.Size();
utils::Check(init_size % 3 == 0, "In VarInit: init_size %% 3 != 0");
float * data_ptr = data.dptr_;
for (int i = 0; i < init_size; i++) {
if (i % 3 == 0) {
data_ptr[i] = this->value;
} else if (i % 3 == 1) {
data_ptr[i] = 0.0f;
} else {
data_ptr[i] = -this->value;
}
}
}
float value;
};
} // namespace initializer
} // namespace textnet
#endif // TEXTNET_VAR_INIT_INL_HPP_
| true |
2bfe7004bb97295c25d0f2d679056edc00e22ad9 | C++ | wgbartley/rgbpongclock-dev | /ClockFaces/wordclock.cpp | UTF-8 | 4,575 | 2.734375 | 3 | [] | no_license | #ifdef FACE_WORDCLOCK
// #define FACE_WORDCLOCK_NUMBER TOTAL_FACE_COUNT
#define TOTAL_FACE_COUNT_NEW TOTAL_FACE_COUNT + 1
#undef TOTAL_FACE_COUNT
#define TOTAL_FACE_COUNT TOTAL_FACE_COUNT_NEW
#undef TOTAL_FACE_COUNT_NEW
//print a clock using words rather than numbers
void word_clock()
{
DEBUGpln("in word_clock");
cls();
char numbers[19][10] = {
"one", "two", "three", "four","five","six","seven","eight","nine","ten",
"eleven","twelve", "thirteen","fourteen","fifteen","sixteen","7teen","8teen","nineteen" };
char numberstens[5][7] = {
"ten","twenty","thirty","forty","fifty" };
// byte hours_y, mins_y; //hours and mins and positions for hours and mins lines
byte hours = Time.hour();
byte mins = Time.minute();
//loop to display the clock for a set duration of SHOWCLOCK
for (int show = 0; show < SHOWCLOCK ; show++) {
bgProcess();
if (mode_changed == 1)
return;
if(mode_quick){
mode_quick = false;
display_date();
#ifdef FACE_WEATHER
quickWeather();
#endif
word_clock();
return;
}
//print the time if it has changed or if we have just come into the subroutine
if ( show == 0 || mins != Time.minute() ) {
bgProcess();
//reset these for comparison next time
mins = Time.minute();
hours = Time.hour();
//make hours into 12 hour format
if (hours > 12){
hours = hours - 12;
}
if (hours == 0){
hours = 12;
}
//split mins value up into two separate digits
int minsdigit = mins % 10;
byte minsdigitten = (mins / 10) % 10;
char str_top[8];
char str_bot[8];
char str_mid[8];
//if mins <= 10 , then top line has to read "minsdigti past" and bottom line reads hours
if (mins < 10) {
strcpy (str_top,numbers[minsdigit - 1]);
strcpy (str_mid,"PAST");
strcpy (str_bot,numbers[hours - 1]);
}
//if mins = 10, cant use minsdigit as above, so soecial case to print 10 past /n hour.
if (mins == 10) {
strcpy (str_top,numbers[9]);
strcpy (str_mid,"PAST");
strcpy (str_bot,numbers[hours - 1]);
}
//if time is not on the hour - i.e. both mins digits are not zero,
//then make top line read "hours" and bottom line ready "minstens mins" e.g. "three /n twenty one"
else if (minsdigitten != 0 && minsdigit != 0 ) {
strcpy (str_top,numbers[hours - 1]);
//if mins is in the teens, use teens from the numbers array for the bottom line, e.g. "three /n fifteen"
if (mins >= 11 && mins <= 19) {
strcpy (str_bot, numbers[mins - 1]);
strcpy(str_mid," ");
//else bottom line reads "minstens mins" e.g. "three \n twenty three"
}
else {
strcpy (str_mid, numberstens[minsdigitten - 1]);
strcpy (str_bot, numbers[minsdigit -1]);
}
}
// if mins digit is zero, don't print it. read read "hours" "minstens" e.g. "three /n twenty"
else if (minsdigitten != 0 && minsdigit == 0 ) {
strcpy (str_top, numbers[hours - 1]);
strcpy (str_bot, numberstens[minsdigitten - 1]);
strcpy (str_mid, " " );
}
//if both mins are zero, i.e. it is on the hour, the top line reads "hours" and bottom line reads "o'clock"
else if (minsdigitten == 0 && minsdigit == 0 ) {
strcpy (str_top,numbers[hours - 1]);
strcpy (str_bot, "O'CLOCK");
strcpy (str_mid, " ");
}
//work out offset to center top line on display.
byte lentop = 0;
while(str_top[lentop]) {
lentop++;
}; //get length of message
byte offset_top;
if(lentop<6){
offset_top = (X_MAX - ((lentop*6)-1)) / 2; //
}
else{
offset_top = (X_MAX - ((lentop - 1)*4)) / 2; //
}
//work out offset to center bottom line on display.
byte lenbot = 0;
while(str_bot[lenbot]) {
lenbot++;
}; //get length of message
byte offset_bot;
if(lenbot<6){
offset_bot = (X_MAX - ((lenbot*6)-1)) / 2; //
}
else{
offset_bot = (X_MAX - ((lenbot - 1)*4)) / 2; //
}
byte lenmid = 0;
while(str_mid[lenmid]) {
lenmid++;
}; //get length of message
byte offset_mid;
if(lenmid<6){
offset_mid = (X_MAX - ((lenmid*6)-1)) / 2; //
}
else{
offset_mid = (X_MAX - ((lenmid - 1)*4)) / 2; //
}
cls();
drawString(offset_top,(lenmid>1?0:2),str_top,(lentop<6?53:51),matrix.Color333(0,1,5));
if(lenmid>1){
drawString(offset_mid,5,str_mid,(lenmid<6?53:51),matrix.Color333(1,1,5));
}
drawString(offset_bot,(lenmid>1?10:8),str_bot,(lenbot<6?53:51),matrix.Color333(0,5,1));
matrix.swapBuffers(false);
}
bgProcess(); //Give the background process some lovin'
delay (50);
}
}
#endif | true |
96e7bae4eaf0895648d443189d582b8984f818fb | C++ | llssyy404/CPP_Standard_Library | /CPP_Standard_Library_4/Deque.cpp | UHC | 1,271 | 3.78125 | 4 | [] | no_license | //-------------------------------------------------------
// C++ ǥ ̺귯
//
// 4. ̳
//
// deque
//-------------------------------------------------------
#include <iostream>
#include <deque>
using namespace std;
struct MyInt {
MyInt(int i) : myInt(i) {}
int myInt;
};
int main()
{
deque<MyInt> myIntDeq;
myIntDeq.push_back(MyInt(5));
myIntDeq.emplace_back(1);
cout << myIntDeq.size() << endl; // 2
deque<int> intDeq;
intDeq.assign({ 1, 2, 3 });
for (auto v : intDeq) cout << v << ' '; // 1 2 3
cout << endl;
intDeq.insert(intDeq.begin(), 0);
for (auto v : intDeq) cout << v << ' '; // 0 1 2 3
cout << endl;
intDeq.insert(intDeq.begin() + 4, 4);
for (auto v : intDeq) cout << v << ' '; // 0 1 2 3 4
cout << endl;
intDeq.insert(intDeq.end(), { 5, 6, 7, 8, 9, 10, 11 });
for (auto v : intDeq) cout << v << ' '; // 0 1 2 3 4 5 6 7 8 9 10 11
cout << endl;
for (auto revIt = intDeq.rbegin(); revIt != intDeq.rend(); ++revIt)
cout << *revIt << ' '; // 11 10 9 8 7 6 5 4 3 2 1 0
cout << endl;
intDeq.pop_back();
for (auto v : intDeq) cout << v << ' '; // 0 1 2 3 4 5 6 7 8 9 10
cout << endl;
intDeq.push_front(-1);
for (auto v : intDeq) cout << v << ' '; // -1 0 1 2 3 4 5 6 7 8 9 10
cout << endl;
} | true |
8a0fa43ec0329b7def98b26263e494772244d473 | C++ | kejhy93/matrix-multiplication | /lib/MatrixMultiplication.h | UTF-8 | 645 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef __MATRIX_MULTIPLICATION_H__
#define __MATRIX_MULTIPLICATION_H__
#include <iostream>
#include "Matrix.h"
class MatrixMultiplication {
public:
virtual ~MatrixMultiplication();
virtual Matrix* multiply(const Matrix& left, const Matrix& right) = 0;
/**
* Verify that matrix multiplcation can be applied.
* true if matrix multiplication can be applied, false otherwise
*/
static bool areMatricesCompatibleForMultiplication ( const Matrix& left, const Matrix& right);
/**
* Linear combination
*/
static double linear_combination ( const Matrix& left, const Matrix& right, const int& row, const int& col);
};
#endif | true |
fb721c30bfa43830f6a5035453f30ab90e4aa8b1 | C++ | FrankXu7/Timer | /Timer.h | UTF-8 | 2,968 | 3.65625 | 4 | [] | no_license | #pragma once
/**************************************************************************************************
* 基于C++的chrono库实现的简单计时器,是一个单例类,精确到毫秒。
*
* @author FrankX
* @date 2021-04-12
**************************************************************************************************/
#include <unordered_map>
#include <chrono>
typedef typename std::tuple<void(*)(long long int), long long int, long long int, long long int> TIMER_ITEM;
/** 封装单个计时器执行需要的数据 */
struct CallData
{
/**
* @brief 计时器回调函数指针,会在每经过 millisec 后执行,在单例对象析构时销毁
* @brief timestamp 执行函数时的时间戳,精确到毫秒
*/
void(*callback)(unsigned long timestamp);
/** 每次回调的时间讲个,单位:毫秒(milliseconds) */
long int millisec;
/** 执行的次数,默认值为-1,表示在单例对象生命周期内不停止 */
long int repeat;
/** 【注释待优化】每次检查周期相差1ms,用以计算是否需要执行当前计时器 */
long int cycle;
};
class Timer
{
public:
Timer();
~Timer();
/**
* @brief 获取计时器单例
* @return
*/
static Timer* GetInstance();
/**
* @brief 添加一个计时器
* @param callback 函数回调,会在析构时删除该指针
* @param millisec 计时器间隔,单位为毫秒(milliseconds)
* @param repeat 执行的次数,默认值-1表示在单例对象生命周期内一直执行
* @return 返回创建好的计时器ID
*/
unsigned int AddTimer(void(*callback)(long long int), long long int millisec, long long int repeat = -1);
/**
* @brief 移除一个计时器
* @param timerId 计时器ID
*/
void RemoveTimer(unsigned int timerId);
/**
* @brief 移除全部计时器
*/
void RemoveAllTimes();
private:
/** 计时器对象单例,项目中的计时器应该统一管理 */
static Timer* instance;
/** 计时器自增量,初始为0,每添加一个计时器,自增1 */
unsigned int timer_id;
/** 计时器是否正在执行 */
bool b_running;
/**
* 允许存在多个不同的计时器,用map来保存它们,对应的数据结构为:
* key: 计时器ID,为创建计时器时 Timer::timer_id 自增后的值
* value: 四元组,结构为:<
* void(*)(unsigned long int) 回调函数指针,参数为当前系统时间精确到毫秒的时间戳;
* long long int 计时器间隔(单位:毫秒 milliseconds);
* long long int 执行的次数(默认值-1表示在单例对象生命周期内一直执行);
* long long int 循环标识(初始为0,自加1,加至 回调间隔 时执行回调);
* >
*/
std::unordered_map<unsigned int, TIMER_ITEM> callbacks;
/**
* @brief 开始执行计时器,在添加计时器和删除计时器时,通过控制 Timer::b_running 来决定是否调用该函数
*/
void Execute();
};
| true |
3b336151fa806f027d743159a8e781294972ef8f | C++ | Handy521/seven-day-become-butterfly | /class_object/Student.cpp | UTF-8 | 456 | 3.140625 | 3 | [] | no_license | #include "Student.h"
void Student::setName(string name)
{
m_strName = name;
}
Student::Student()
{
cout <<"Student"<<endl;
}
Student::Student(const Student &stu)
{
cout<<"Student(const Student& stu)"<<endl;
}
Student::~Student()
{
cout <<"~Student()"<< endl;
}
string Student::getName()
{
return m_strName;
}
void Student::setAge(int Age)
{
m_iAge= Age;
}
int Student::getAge()
{
return m_iAge;
}
void Student::study()
{
cout << "study" << endl;
}
| true |
a37938f5e3abc93f61c6d3e5ea39fcab0c3d7672 | C++ | aochernov/MineSweeperSolver | /MineSweeper/PropositionalFormula.cpp | UTF-8 | 4,052 | 3.140625 | 3 | [] | no_license | #include "PropositionalFormula.h"
int PropositionalFormula::NameCounter;
PropositionalFormula::PropositionalFormula(bool sign, std::string name)
{
Type = VARIABLE;
Sign = sign;
if (name == "0")
{
Sign = !Sign;
Name = "";
}
else if (name == "1")
{
Name = "";
}
else
{
Name = name;
}
}
void PropositionalFormula::negate()
{
Sign = !Sign;
}
PropositionalFormula::FormulaType PropositionalFormula::getType()
{
return Type;
}
bool PropositionalFormula::getSign()
{
return Sign;
}
int PropositionalFormula::getValue()
{
if (Name.empty())
{
return Sign;
}
else
{
return -1;
}
}
std::string PropositionalFormula::getFormula()
{
switch (getValue())
{
case -1:
return (Sign ? Name : ("!" + Name));
case 0:
return "0";
case 1:
return "1";
}
}
PropositionalFormula* PropositionalFormula::getSimplified()
{
return this;
}
std::vector<PropositionalFormula*> PropositionalFormula::getChildren()
{
return { this };
}
std::string PropositionalFormula::getAlias(bool sign)
{
if (Name.empty())
{
if (getType() == VARIABLE)
{
return std::to_string(sign ? Sign : !Sign);
}
else
{
Name = "t" + std::to_string(NameCounter);
NameCounter++;
}
}
return (sign ? Name : ("!" + Name));
}
void PropositionalFormula::resetNameCounter()
{
NameCounter = 1;
}
PropositionalAnd::PropositionalAnd(bool sign) : PropositionalFormula(sign, "1")
{
Defined = false;
Type = AND;
}
void PropositionalAnd::addConjunct(PropositionalFormula* conjunct)
{
if (Defined)
{
return;
}
switch (conjunct->getValue())
{
case -1:
Conjuncts.push_back(conjunct->getSimplified());
break;
case 0:
Defined = true;
Conjuncts.clear();
break;
}
}
std::string PropositionalAnd::getFormula()
{
switch (getValue())
{
case -1:
if (Conjuncts.size() == 1)
{
return (Sign ? Conjuncts[0]->getFormula() : ("!" + Conjuncts[0]->getFormula()));
}
else
{
std::string formula = (Sign ? "(" : "!(") + Conjuncts[0]->getFormula();
for (int i = 1; i < Conjuncts.size(); i++)
{
formula.append(" & " + Conjuncts[i]->getFormula());
}
formula.append(")");
return formula;
}
case 0:
return "0";
case 1:
return "1";
}
}
int PropositionalAnd::getValue()
{
if (Defined)
{
return 0;
}
else if (Conjuncts.size())
{
return -1;
}
else
{
return 1;
}
}
PropositionalFormula* PropositionalAnd::getSimplified()
{
switch (getValue())
{
case -1:
return ((Conjuncts.size() == 1) ? Conjuncts[0] : this);
case 0:
return new PropositionalFormula(true, "0");
case 1:
return new PropositionalFormula(true, "1");
}
}
std::vector<PropositionalFormula*> PropositionalAnd::getChildren()
{
return Conjuncts;
}
PropositionalOr::PropositionalOr(bool sign) : PropositionalFormula(sign, "1")
{
Defined = false;
Type = OR;
}
void PropositionalOr::addDisjunct(PropositionalFormula* disjunct)
{
if (Defined)
{
return;
}
switch (disjunct->getValue())
{
case -1:
Disjuncts.push_back(disjunct->getSimplified());
break;
case 1:
Defined = true;
Disjuncts.clear();
break;
}
}
std::string PropositionalOr::getFormula()
{
switch (getValue())
{
case -1:
if (Disjuncts.size() == 1)
{
return (Sign ? Disjuncts[0]->getFormula() : ("!" + Disjuncts[0]->getFormula()));
}
else
{
std::string formula = (Sign ? "(" : "!(") + Disjuncts[0]->getFormula();
for (int i = 1; i < Disjuncts.size(); i++)
{
formula.append(" | " + Disjuncts[i]->getFormula());
}
formula.append(")");
return formula;
}
case 0:
return "0";
case 1:
return "1";
}
}
int PropositionalOr::getValue()
{
if (Defined)
{
return 1;
}
else if (Disjuncts.size())
{
return -1;
}
else
{
return 0;
}
}
PropositionalFormula* PropositionalOr::getSimplified()
{
switch (getValue())
{
case -1:
return ((Disjuncts.size() == 1) ? Disjuncts[0] : this);
case 0:
return new PropositionalFormula(true, "0");
case 1:
return new PropositionalFormula(true, "1");
}
}
std::vector<PropositionalFormula*> PropositionalOr::getChildren()
{
return Disjuncts;
} | true |
e612e7c6bfb2053dbdccd2538fc889a13c80ab3e | C++ | hamance/AlgoCode | /DataStructure/Bag_Class_Example/Bag.h | UTF-8 | 3,202 | 3.765625 | 4 | [] | no_license | // FILE: Bag.h
// CLASS PROVIDED: Bag
//
// TYPEDEF and MEMBER CONSTANTS for the Bag class:
// typedef ____ value_type
// Bag::value_type is the data type of the items in the bag. It may be
// any of the C++ built-in types (int, char, etc.), or a class with a
// default constructor, an assignment opreator, and operators to test
// for equality (x==y) and non-equality (x != y).
//
// typedef ____ size_type
// Bag::size_type is the data type of any variable that keeps track of
// how many items are in the bag.
//
// static const size_type CAPACITY = ____
// Bag::CAPACITY is the maximum number of items that a bag can hold.
//
//
// CONSTRUCTOR for the Bag class:
// Bag()
// Postcondition: The bag has been initialized as an empty bag.
//
//
// MODIFICATION MEMBER FUNCIONS for the Bag class:
// size_type erase(const value_type& target)
// Postcondition: All copies of target have been removed from the bag.
// The return value is the number of copies removed (which could be zero).
//
// void erase_one(const value_type& target)
// Postcondition: If target was in the bag, then one copy has been
// removed; otherwise the bag is unchanged. A true return value
// indecates that one copy was removed; false indicates that nothing
// was removed.
//
// void insert(const value_type& entry)
// Precondition: size( ) < CAPACITY.
// Postcondition: A new copy of entry has been added to the bag.
//
// void operator +=(const bag& addend)
// Precondition: size( ) + addend.size( ) <= CAPACITY.
// Postcondition: Each item in addend has been added to this bag.
//
// CONSTANT MEMBER FUNCTIONS for the Bag class:
// size_type size( ) const
// Postcondition: The return value is the total number of items in
// the bag.
//
// size_type count(const value_type& target) const
// Postcondition: The return value is number of times target is in the bag.
//
//
// NONMEMBER FUNCTIONS for the Bag class:
// Bag operator +(const bag& b1, const bag& b2)
// Precondition: b1.size( ) + b2.size( ) <= bag::CAPACITY.
// Postcondition: The bag returned is the the union of b1 and b2.
//
//
// VALUE SEMANTICS for the Bag class:
// Assignments and the copy constructor may be used with bag objects.
#ifndef ALGORITHM_BAG_H
#define ALGORITHM_BAG_H
#include <cstdlib> // Provides size_t
class Bag {
public:
// TYPEDEFS and MEMBER CONSTANTS
typedef int value_type;
typedef std::size_t size_type;
static const size_type CAPACITY = 30;
// CONSTRUCTOR
Bag() { used = 0; }
// MODIFICATION MEMBER FUNCTIONS
size_type erase(const value_type& target);
bool erase_one(const value_type& target);
void insert(const value_type& entry);
void operator +=(const value_type& addend);
// CONSTANT MEMBER FUNCTIONS
size_type size() const { return used; }
size_type count(const value_type& target) const ;
private:
value_type data[CAPACITY]; // The array to store items
size_type used; // How much of array is used
};
// NONMEMBER FUNCTIONS for the Bag class
Bag operator + (const Bag& b1, const Bag& b2);
#endif //ALGORITHM_BAG_H
| true |
dc3165f8e4796dc5efd3ed55546cc0f0918e2724 | C++ | jackp83/midioverble | /src/ble/BLEReceiver.cpp | UTF-8 | 2,404 | 2.921875 | 3 | [] | no_license | /*
* BLEReceiver.cpp
*
* Created on: 29 apr 2016
* Author: jack
*/
#include "BLEReceiver.h"
BLEReceiver::BLEReceiver() {
}
BLEReceiver::~BLEReceiver() {
}
/*
* Sets up a Bluetooth Low Energy socket with L2CAP using a low security level
* Returns the socket if succesful otherwise it returns -1
*/
int BLEReceiver::l2cap_le_listen_and_accept() {
int listen_socket;
char remote_address[18];
socklen_t optlen;
struct sockaddr_l2 srcaddr, addr;
struct bt_security btsec;
bdaddr_t tmp_bdaddr_any = {};
listen_socket = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
if (listen_socket < 0) {
perror("Failed to create L2CAP socket");
return -1;
}
/* Set up source address */
memset(&srcaddr, 0, sizeof(srcaddr));
srcaddr.l2_family = AF_BLUETOOTH;
srcaddr.l2_cid = htobs(4);
srcaddr.l2_bdaddr_type = BDADDR_LE_PUBLIC;
bacpy(&srcaddr.l2_bdaddr, &tmp_bdaddr_any);
if (bind(listen_socket, (struct sockaddr *) &srcaddr, sizeof(srcaddr)) < 0) {
perror("Failed to bind L2CAP socket");
close(listen_socket);
return -1;
}
/* Set the security level */
memset(&btsec, 0, sizeof(btsec));
btsec.level = BT_SECURITY_LOW;
if (setsockopt(listen_socket, SOL_BLUETOOTH, BT_SECURITY, &btsec,
sizeof(btsec)) != 0) {
fprintf(stderr, "Failed to set L2CAP security level\n");
close(listen_socket);
return -1;
}
if (listen(listen_socket, 10) < 0) {
perror("Listening on socket failed");
close(listen_socket);
return -1;
}
printf("Waiting for connections\n");
memset(&addr, 0, sizeof(addr));
optlen = sizeof(addr);
accept_socket = accept(listen_socket, (struct sockaddr *) &addr, &optlen);
if (accept_socket < 0) {
perror("Accept failed");
close(listen_socket);
return -1;
}
ba2str(&addr.l2_bdaddr, remote_address);
printf("Connect from %s\n", remote_address);
close(listen_socket);
return accept_socket;
}
/*
* Sends the array through the socket created in the l2cap_le_listen_and_accept() function.
* char* array - the array to send
* int array_size - the size of array.
* Returns 0 if successful and -1 if not successful.
*/
int BLEReceiver::read_data(char *buf,int buf_size) {
int bytes_read = read(accept_socket, buf, buf_size);
if( bytes_read < 0 ) {
perror("Could not read data");
close(accept_socket);
return -1;
}
return 0;
}
void BLEReceiver::set_socket_number(int socket_nr){
accept_socket= socket_nr;
}
| true |
7194f4109fc9bba627899520a237f938f3e4186e | C++ | CIA-hideout/pongstar | /src/textureManager.cpp | UTF-8 | 1,842 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "textureManager.h"
//=============================================================================
// Constructor
//=============================================================================
TextureManager::TextureManager() {
texture = nullptr;
width = 0;
height = 0;
file = nullptr;
graphics = nullptr;
initialized = false; // set true when successfully initialized
}
//=============================================================================
// Destructor
//=============================================================================
TextureManager::~TextureManager() {
SAFE_RELEASE(texture);
}
//=============================================================================
// Initialize TextureManager
//=============================================================================
bool TextureManager::initialize(Graphics *g, const char *f) {
try {
graphics = g; // the graphics object
file = f; // the texture file
hr = graphics->loadTexture(file, TRANSCOLOR, width, height, texture);
if (FAILED(hr)) {
SAFE_RELEASE(texture);
return false;
}
}
catch (...) { return false; }
initialized = true; // set true when successfully initialized
return true;
}
//=============================================================================
// Called when graphics device is lost
//=============================================================================
void TextureManager::onLostDevice() {
if (!initialized)
return;
SAFE_RELEASE(texture);
}
//=============================================================================
// Called when graphics device is reset
//=============================================================================
void TextureManager::onResetDevice() {
if (!initialized)
return;
graphics->loadTexture(file, TRANSCOLOR, width, height, texture);
}
| true |
275d90c6d0e56e968cf61ec70390b796a3e1024b | C++ | ihsuy/CTCI | /chapter16_Moderate/sumSwap.cpp | UTF-8 | 2,601 | 3.390625 | 3 | [] | no_license | #include <math.h>
#include <algorithm>
#include <bitset>
#include <chrono>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
typedef long long ll;
inline int two(int n) {
return 1 << n;
}
inline int test(int n, int b) {
return (n >> b) & 1;
}
inline void set_bit(int& n, int b) {
n |= two(b);
}
inline void unset_bit(int& n, int b) {
n &= ~two(b);
}
inline int last_bit(int n) {
return n & (-n);
}
inline int ones(int n) {
int res = 0;
while (n && ++res)
n -= n & (-n);
return res;
}
template <typename T>
inline void inspect(T& t) {
typename T::iterator i1 = t.begin(), i2 = t.end();
while (i1 != i2) {
std::cout << (*i1) << ' ';
i1++;
}
std::cout << '\n';
}
/////////////////////////////////////////////////////////////
using namespace std;
/*
Sum Swap: Given two arrays of integers,
find a pair of values (one value from each array)
that you can swap to give the two arrays the same sum.
Input: (4, 1, 2, 1, 1, 2) and (3, 6, 3, 3)
Output: (1, 3)
*/
pair<int, int> sumSwap(
const vector<int>& v1,
const vector<int>& v2) { // note that swaping will ONLY cause 2 vectors to
// increase and decrease by
// same amount, i.e. of swapping causes sum(v1) to decrease by A then
// sum(v2) will be increased by A. Assume sum(v1) = s1 and sum(v2) = s2, now
// we want their sum to be the same by swapping that is, we're looking for
// integer A such that s1 + A == s2 - A this can be refactored to A ==
// (s2-s1)/2 now we only need to find a pair of elements {e1, e2} from v1
// and v2 such that e2-e1 == A
int sum1 = accumulate(v1.begin(), v1.end(), 0),
sum2 = accumulate(v2.begin(), v2.end(), 0);
unordered_set<int> v2_set(v2.begin(), v2.end());
int target = (sum2 - sum1);
if (target % 2 != 0) {
cout << "Can't swap to make sum(v1) == sum(v2)\n";
return {0, 0};
}
target /= 2;
for (int i = 0; i < v1.size(); ++i) {
int wanted = target + v1[i];
if (v2_set.count(wanted) != 0) {
return {v1[i], wanted};
}
}
return {0, 0};
}
int main() {
const vector<int> v1{4, 1, 2, 1, 1, 2};
const vector<int> v2{3, 6, 3, 3};
pair<int, int> result = sumSwap(v1, v2);
cout << "(" << result.first << ", " << result.second << ")\n";
return 0;
}
| true |
709fe845fef7774503a13049b8f01c5039614665 | C++ | jwcurnalia/first | /CSIS2610/quasiBST.cc | UTF-8 | 813 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
struct Person {
string name;
int left,right;
};
Person people[10];
int insert(int r,int n) {
if (r == -1)
return n;
if (people[n].name > people[r].name)
people[r].right = insert(people[r].right,n);
else
people[r].left = insert(people[r].left,n);
return r;
}
void inOrder(int r) {
if (r != -1) {
inOrder(people[r].left);
cout << people[r].name << endl;
inOrder(people[r].right);
}
}
int main(void) {
int nPeople=0,root=-1;
while (true) {
cout << "enter a person: ";
cin >> people[nPeople].name;
if (!cin)
break;
people[nPeople].left = -1;
people[nPeople].right = -1;
root = insert(root,nPeople);
nPeople++;
}
cout << "\n\n";
inOrder(0);
return 0;
}
| true |
d16a209851d5d4c8e30cc41ba87ba249d6e5d594 | C++ | yadamit/8th_sem_courses | /PPC_solutions-yadamit/cp3b/cp.cc | UTF-8 | 3,644 | 2.796875 | 3 | [] | no_license | #include "cp.h"
#include<cmath>
#include <new>
#include<cstdlib>
#include <x86intrin.h>
#include<iostream>
typedef float float8_t __attribute__ ((vector_size (8 * sizeof(float))));
static float8_t* float8_alloc(std::size_t n) {
void* tmp = 0;
if (posix_memalign(&tmp, sizeof(float8_t), sizeof(float8_t) * n)) {
throw std::bad_alloc();
}
return (float8_t*)tmp;
}
static inline float8_t swap4(float8_t x) { return _mm256_permute2f128_ps(x, x, 0b00000001); }
static inline float8_t swap2(float8_t x) { return _mm256_permute_ps(x, 0b01001110); }
static inline float8_t swap1(float8_t x) { return _mm256_permute_ps(x, 0b10110001); }
float hsum8(float8_t x){
float sum = 0;
for(int i=0; i<8; i++){
sum += x[i];
}
return sum;
}
void correlate(int ny, int nx, const float* data, float* result) {
// TODO
const int nb = 8;
int na = (ny-1)/nb + 1;
// int nab_v = na_v*nb_v;
float8_t* d = float8_alloc(na*nx);
double mu[ny] = {0};
double std[ny] = {0};
// calculating mean and std for each row
#pragma omp parallel for schedule(static, 1)
for(int row=0; row<ny; row++){
for(int j=0; j<nx; j++){
float tmp;
tmp = (double)data[row*nx+j];
mu[row] += tmp;
std[row] += tmp*tmp;
}
mu[row] /= nx;
std[row] = sqrt(std[row] - nx*mu[row]*mu[row]);
// Note: std above = sqrt(nx)*actual_std
// This saves us from dividing by nx after taking dot product.
}
// copy the data into new vectorized array
#pragma omp parallel for schedule(static, 1)
for(int ja=0; ja<na; ja++){
for(int i=0; i<nx; i++){
for(int kb=0; kb<nb; kb++){
int row = ja*nb+kb;
d[ja*nx + i][kb] = row<ny? ((double)data[row*nx + i] - mu[row])/std[row] : 0;
// d[row*na_v + ka][kb] = (ka*nb_v +kb)<nx? ((float)data[row*nx + ka*nb_v +kb]-mu[row])/std[row] : 0;
}
}
}
#pragma omp parallel for schedule(static, 1)
for(int ia=0; ia<na; ia++){
for(int ja=ia; ja<na; ja++){
float8_t dot000={0}, dot001={0}, dot010={0}, dot011={0}, dot100={0}, dot101={0}, dot110={0}, dot111={0};
for(int k=0; k<nx; k++){
float8_t a000 = d[ia*nx+k];
float8_t b000 = d[ja*nx+k];
float8_t a100 = swap4(a000);
float8_t a010 = swap2(a000);
float8_t a110 = swap2(a100);
float8_t b001 = swap1(b000);
dot000 += a000 * b000;
dot001 += a000 * b001;
dot010 += a010 * b000;
dot011 += a010 * b001;
dot100 += a100 * b000;
dot101 += a100 * b001;
dot110 += a110 * b000;
dot111 += a110 * b001;
}
float8_t dot[8] = {dot000, dot001, dot010, dot011, dot100, dot101, dot110, dot111};
for (int kb = 1; kb < 8; kb += 2) {
dot[kb] = swap1(dot[kb]);
}
// for(int tmp=0; tmp<4; tmp++){
// printf("dot[%d]: %lf, %lf, %lf, %lf\n", tmp, dot[tmp][0], dot[tmp][1], dot[tmp][2], dot[tmp][3]);
// }
for(int ib=0; ib<nb; ib++){
for(int jb=0; jb<nb; jb++){
int i = ia*nb + ib;
int j = ja*nb + jb;
if(i<=j && i<ny && j<ny){
result[i*ny+j] = (float)dot[jb^ib][jb];
}
}
}
}
}
std::free(d);
} | true |
3706ebe06ac10d54c2fcfc9b6c8e7c48a895b0e9 | C++ | sjs108u/OOP | /17.cpp | UTF-8 | 252 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int x, y, tmp;
while(cin >> x >> y){
while(x % y != 0){
tmp = y;
y = x % y;
x = tmp;
}
cout << y << endl;
}
}
| true |
83a92825eadca76907d00f7b9fd0aaef7f706e36 | C++ | yes99/practice2020 | /알고리즘과제/2/functions.cpp | UTF-8 | 8,369 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
// ii >>
// oo <<
struct music
{
int rank;
string name;
string singer;
string album;
int like;
};
void bubblerank(music m[], int n)
{
int flag, i, j;
music t;
for (i = 1; i <= n - 1; i++)
{
flag = 0;
for (j = 0; j < n - i; j++)
{
if (m[j].rank > m[j + 1].rank)
{
t = m[j];
m[j] = m[j + 1];
m[j + 1] = t;
flag = 1;
}
}
if (flag == 0)
{
break;
}
}
}
void bubblename(music m[], int n)
{
int flag, i, j;
music t;
for (i = 1; i <= n - 1; i++)
{
flag = 0;
for (j = 0; j < n - i; j++)
{
if (m[j].name > m[j + 1].name)
{
t = m[j];
m[j] = m[j + 1];
m[j + 1] = t;
flag = 1;
}
}
if (flag == 0)
{
break;
}
}
}
void bubblesinger(music m[], int n)
{
int flag, i, j;
music t;
for (i = 1; i <= n - 1; i++)
{
flag = 0;
for (j = 0; j < n - i; j++)
{
if (m[j].singer > m[j + 1].singer)
{
t = m[j];
m[j] = m[j + 1];
m[j + 1] = t;
flag = 1;
}
}
if (flag == 0)
{
break;
}
}
}
void bubblealbum(music m[], int n)
{
int flag, i, j;
music t;
for (i = 1; i <= n - 1; i++)
{
flag = 0;
for (j = 0; j < n - i; j++)
{
if (m[j].album > m[j + 1].album)
{
t = m[j];
m[j] = m[j + 1];
m[j + 1] = t;
flag = 1;
}
}
if (flag == 0)
{
break;
}
}
}
void bubblelike(music m[], int n)
{
int flag, i, j;
music t;
for (i = 1; i <= n - 1; i++)
{
flag = 0;
for (j = 0; j < n - i; j++)
{
if (m[j].like > m[j + 1].like)
{
t = m[j];
m[j] = m[j + 1];
m[j + 1] = t;
flag = 1;
}
}
if (flag == 0)
{
break;
}
}
}
void heaprank(music m[], int number)
{
int i, j, k;
int c, root;
music temp;
//힙구조로 바꾸자
for(i =1; i <number;i++)
{
c = i;
do
{
root = (c-1)/2;
if(m[root].rank<m[c].rank)
{
temp = m[root];
m[root] = m[c];
m[c] = temp;
}
c = root;
} while (c!=0 );
}
//크기를 줄여가며 반복적으로 힙 구성
for(i = number -1 ; i >=0;i--)
{
temp = m[0];
m[0] = m[i];
m[i]=temp;
int root =0;
int c = 1;
do
{
c = 2 * root +1;
//자식 중에 더 큰값 찾기
if(m[c].rank < m[c+1].rank && c < i-1)
{
c++;
}
//루트보다 자식이 더 크다면 교환
if(m[root].rank < m[c].rank && c<i)
{
temp = m[root];
m[root] = m[c];
m[c]=temp;
}
root = c;
} while (c<i);
}
}
void heapname(music m[], int number)
{
int i, j, k;
int c, root;
music temp;
//힙구조로 바꾸자
for(i =1; i <number;i++)
{
c = i;
do
{
root = (c-1)/2;
if(m[root].name<m[c].name)
{
temp = m[root];
m[root] = m[c];
m[c] = temp;
}
c = root;
} while (c!=0 );
}
//크기를 줄여가며 반복적으로 힙 구성
for(i = number -1 ; i >=0;i--)
{
temp = m[0];
m[0] = m[i];
m[i]=temp;
int root =0;
int c = 1;
do
{
c = 2 * root +1;
//자식 중에 더 큰값 찾기
if(m[c].name < m[c+1].name && c < i-1)
{
c++;
}
//루트보다 자식이 더 크다면 교환
if(m[root].name < m[c].name && c<i)
{
temp = m[root];
m[root] = m[c];
m[c]=temp;
}
root = c;
} while (c<i);
}
}
void heapsinger(music m[], int number)
{
int i, j, k;
int c, root;
music temp;
//힙구조로 바꾸자
for(i =1; i <number;i++)
{
c = i;
do
{
root = (c-1)/2;
if(m[root].singer<m[c].singer)
{
temp = m[root];
m[root] = m[c];
m[c] = temp;
}
c = root;
} while (c!=0 );
}
//크기를 줄여가며 반복적으로 힙 구성
for(i = number -1 ; i >=0;i--)
{
temp = m[0];
m[0] = m[i];
m[i]=temp;
int root =0;
int c = 1;
do
{
c = 2 * root +1;
//자식 중에 더 큰값 찾기
if(m[c].singer < m[c+1].singer && c < i-1)
{
c++;
}
//루트보다 자식이 더 크다면 교환
if(m[root].singer < m[c].singer && c<i)
{
temp = m[root];
m[root] = m[c];
m[c]=temp;
}
root = c;
} while (c<i);
}
}
void heapalbum(music m[], int number)
{
int i, j, k;
int c, root;
music temp;
//힙구조로 바꾸자
for(i =1; i <number;i++)
{
c = i;
do
{
root = (c-1)/2;
if(m[root].album<m[c].album)
{
temp = m[root];
m[root] = m[c];
m[c] = temp;
}
c = root;
} while (c!=0 );
}
//크기를 줄여가며 반복적으로 힙 구성
for(i = number -1 ; i >=0;i--)
{
temp = m[0];
m[0] = m[i];
m[i]=temp;
int root =0;
int c = 1;
do
{
c = 2 * root +1;
//자식 중에 더 큰값 찾기
if(m[c].album < m[c+1].album && c < i-1)
{
c++;
}
//루트보다 자식이 더 크다면 교환
if(m[root].album < m[c].album && c<i)
{
temp = m[root];
m[root] = m[c];
m[c]=temp;
}
root = c;
} while (c<i);
}
}
void heaplike(music m[], int number)
{
int i, j, k;
int c, root;
music temp;
//힙구조로 바꾸자
for(i =1; i <number;i++)
{
c = i;
do
{
root = (c-1)/2;
if(m[root].rank<m[c].rank)
{
temp = m[root];
m[root] = m[c];
m[c] = temp;
}
c = root;
} while (c!=0 );
}
//크기를 줄여가며 반복적으로 힙 구성
for(i = number -1 ; i >=0;i--)
{
temp = m[0];
m[0] = m[i];
m[i]=temp;
int root =0;
int c = 1;
do
{
c = 2 * root +1;
//자식 중에 더 큰값 찾기
if(m[c].rank < m[c+1].rank && c < i-1)
{
c++;
}
//루트보다 자식이 더 크다면 교환
if(m[root].rank < m[c].rank && c<i)
{
temp = m[root];
m[root] = m[c];
m[c]=temp;
}
root = c;
} while (c<i);
}
}
int main()
{
music m[100];
m[0] = {1, "sdfsdf", "dsagsag", "wegwegewg", 15};
m[1] = {15, "gagewgew", "wegewgewg", "ewfwgewg", 23};
m[2] = {13, "rehrehhahreah", "gewgewgwghjh", "gjghgg,gh,gh", 1};
heapsinger(m, 3);
for (int i = 0; i < 3; i++)
{
cout << m[i].rank << "\t" << m[i].name << "\t" << m[i].album << "\t" << m[i].singer << "\t" << m[i].rank << endl;
}
} | true |
bfd1a7574c2d84dd6381c8498263c06735a9ca3c | C++ | hruskraj/advent-of-code-2019 | /01.cpp | UTF-8 | 388 | 3.15625 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
using namespace std;
int calculateFuel(int mass){
return max(mass / 3 - 2, 0);
}
int main(){
int a, out1 = 0, out2 = 0;
while(scanf("%d", &a) == 1){
out1 += calculateFuel(a);
while((a = calculateFuel(a)) != 0){
out2 += a;
}
}
printf("%d\n", out1);
printf("%d\n", out2);
return 0;
}
| true |
e96b9124f11deebed4b63c293829c31a14ec3dfc | C++ | micahthomas/COSC-1410 | /Thomas2.cpp | UTF-8 | 1,596 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | // 1410 Program 2
// Author: Micah Thomas
// TA: Can Cao
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main() {
char ans, ch;
int ans_axle;
float toll;
do {
cout << "\n------------------------------------\n";
cout << " TOLL CALCULATION \n";
cout << "------------------------------------\n\n";
cout << "Does the vehicle have an EZ-TAG?(Y/N): ";
cin >> ans;
if (ans == 'Y' || ans == 'y') {
ans = 'y';
cout << "\n>> Vehicle has EZ-TAG!\n\n";
} else {
cout << "\n>> Vehicle does not have EZ-TAG.\n\n";
}
cout << "How many axles does the vehicle have?: ";
cin >> ans_axle;
cout << "\n>> The vehicle has " << ans_axle << " axle(s)\n\n";
switch (ans_axle) {
case 1:
case 2:
if (ans == 'y')
toll = 1.45;
else
toll = 1.75;
break;
case 3:
if (ans == 'y')
toll = 3.50;
else
toll = 4.00;
break;
case 4:
if (ans == 'y')
toll = 5.25;
else
toll = 6.00;
break;
case 5:
if (ans == 'y')
toll = 7.00;
else
toll = 7.75;
break;
default:
if (ans == 'y')
toll = 8.75;
else
toll = 9.25;
}
cout << ">> Toll Charge: " << setprecision(3) << toll << setprecision(0);
cout << "\n\nDo you wish to try again?(Y/N): ";
cin >> ch;
} while (!(ch == 'n' || ch == 'N'));
}
| true |
46ed317d6c5458aa3d71662a2e68f35812439bb3 | C++ | ch3ny1/CSCI-1113-HW | /Labs/Lab 8/cheny004_8A.cpp | UTF-8 | 255 | 2.515625 | 3 | [] | no_license | // Chenyi Wang
// Lab 8 Warm-up 1
a)
Print '*' for n times.
b)
n < 1
c)
A condition that can terminate the recursion.
d)
Yes. When the base case is not met, n is reduced by 1.
e)
Whether the corresponding actions contain a self-calling statement.
| true |
81711a6a8b6f75deebba9a185c67289344ce0246 | C++ | delmontz/arduino | /Arduino/RGBLED_PRE/RGBLED_PRE.ino | UTF-8 | 679 | 2.8125 | 3 | [] | no_license | #include <Adafruit_NeoPixel.h>
// RGBLEDに出力するピン番号
#define RGBLED_OUTPIN 3
// Arduinoにぶら下がっているRGBLEDの個数
#define NUMRGBLED 1
// RGBLEDのライブラリを生成する(色指定はRGBの並びで行う、LEDの速度は800KHzとする)
Adafruit_NeoPixel RGBLED = Adafruit_NeoPixel(NUMRGBLED, RGBLED_OUTPIN, NEO_RGB + NEO_KHZ800);
void setup()
{
RGBLED.begin() ; // RGBLEDのライブラリを初期化する
RGBLED.setPixelColor(0, RGBLED.Color(0,150,0)); // 適度に明るい緑の色。(R=0,G=150,B=0)
RGBLED.show() ; // LEDにデータを送り出す
}
void loop()
{
}
| true |
712c363a92fdecaac6ebcbad84d38e1e0041ac4a | C++ | dingyaguang117/AOJ | /410 蛇形数组/1.cpp | UTF-8 | 663 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int a[100][100];
int main()
{
int n,i,j,d,s;
while (cin>>n)
{
d=0;
s=0;
for (i=0;i<n;++i)
{
if (d)
{
for (j=0;j<i+1;++j)
{
a[j][i-j]=++s;
}
d=0;
}
else
{
for (j=i;j>=0;--j)
{
a[j][i-j]=++s;
}
d=1;
}
}
for (i=1;i<n;++i)
{
if (d)
{
for (j=i;j<n;++j)
{
a[j][n-j+i-1]=++s;
}
d=0;
}
else
{
for (j=n-1;j>=i;--j)
{
a[j][n-j+i-1]=++s;
}
d=1;
}
}
for (i=0;i<n;++i)
{
for (j=0;j<n;++j)
{
printf("%-3d",a[i][j]);
}
cout<<endl;
}
}
} | true |
45f3d847bf530bcc7ec04d730dc942ca92bdead8 | C++ | aoeasif/ProblemSolving | /UVA/374/9031940_AC_0ms_0kB.cpp | UTF-8 | 549 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int bigMod(int base, int power, int mod) {
if(power == 0) return 1;
if(power % 2 == 1) {
int part1 = base % mod;
int part2 = bigMod(base, power-1, mod);
return (part1 * part2) % mod; ;
}
int eq_part = bigMod(base, power/2, mod);
return (eq_part * eq_part) % mod;
}
int main() {
int b, p, m;
while(scanf("%d %d %d", &b, &p, &m) != EOF) {
int res = bigMod(b, p, m);
printf("%d\n", res);
}
return 0;
} | true |
469e87846dccc181e880cc4e362b474e003a53d7 | C++ | joppimenta/URI-Online-Judge-Exercises | /01 - Iniciante/1080 - Maior e Posição.cpp | UTF-8 | 381 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int v[100];
int maior = 0, posimaior = 0;
for(int i = 0; i<100; i++){
cin >> v[i];
}
for(int i = 0; i <100; i++){
if(v[i] > maior){
maior = v[i];
posimaior = i+1;
}
}
cout << maior << endl;
cout << posimaior << endl;
return 0;
} | true |
1059f79707b0da11d8f112650694b44452fc9c8f | C++ | va-lang/Lab10 | /readpoints.cpp | UTF-8 | 756 | 2.953125 | 3 | [] | no_license | #include "StabbingLine.h"
void readPoints(ifstream& file,Point p1[],int& numPoints){
if(!file.is_open()){
cout<<"File failed to open"<<endl;
}
file>>numPoints;
for (int i=0; i< numPoints; i++){
cout<<p1[i].Pid<<endl;
}
}
int main(){
ifstream file("points.txt");
int Pid,X,Y;
string mystring,Xcord,yCord;
string line;
while(getline(file,line)){
stringstream ss(line);
getline(ss, mystring, ',');
Pid = stoi(mystring);
getline(ss, Xcord,',');
X = stoi(Xcord);
getline(ss,yCord,',');
Y = stoi(yCord);
cout<<"Pid: "<< Pid<<endl;
cout<<"X: "<< X<<endl;
cout<<"Y: "<< Y<<endl;
}
file.close();
Point p1[7];
int E = 7;
readPoints(file,p1,E);
}
| true |
33f6af264e6f8df50b30bf6b54caf70be373ac85 | C++ | DonJohnSmith/c9 | /tund_27_11/inheritance.cpp | UTF-8 | 1,728 | 3.625 | 4 | [] | no_license | #include<vector>
#include <string>
#include <iostream>
using namespace std;
class Shape{
private:
enum tyyp{
KOLMNURK,
RUUT,
RISTKYLIK,
RING
};
tyyp kujundityyp;
int A;
public:
Shape(){
A = 0;
}
virtual int area() = 0;
void getType(){
switch(kujundityyp){
case KOLMNURK: cout << "kolmnurk" << endl;
break;
case RUUT: cout << "ruut" << endl;
break;
case RISTKYLIK: cout << "ristkülik" << endl;
break;
case RING: cout << "ring" << endl;
break;
}
}
friend class Square;
friend class Triangle;
};
class Square : public Shape{
public:
Square(){}
Square(int kylg){
A = kylg;
kujundityyp = RUUT;
}
int area(){
return A*A;
}
};
/*
class Rectangle : public Square{
public:
Rectangle(){
kujundityyp = RISTKYLIK;
}
};
*/
class Triangle : public Shape{
private:
int B;
public:
int area(){
return (A*B)/2;
}
Triangle(int x, int y){
A = x;
B = y;
kujundityyp = KOLMNURK;
}
};
int main(){
vector<Shape*> nimekiri;
Shape *ruut = new Square(5);
nimekiri.push_back(ruut);
Triangle *kolmnurk = new Triangle(4,8);
Shape *kolmnurk2 = new Triangle(2,4);
ruut->getType();
cout << ruut->area() << endl;
kolmnurk2->getType();
cout << kolmnurk2->area() << endl;
} | true |
e0f6e6275b56829b66cf222e8edd7e34c01a4a82 | C++ | sshedbalkar/DigiPen_Projects | /CS582/Project_1/Project_1/learning/subsets.h | UTF-8 | 1,574 | 3.265625 | 3 | [] | no_license | #ifndef SUBSETS_H
#define SUBSETS_H
#include <vector>
#include <iostream>
////////////////////////////////////////////////////////////
class Subsets {
public:
Subsets(unsigned int _size) : size(_size), subset_id(0),stop(false) {
}
bool next(std::vector<unsigned int> & subset ) {
if (stop) { return false; }
//initialize subset according to the subset_id bits
subset.clear();
for (unsigned int i=0;i<size;++i) {
if ( subset_id & (1<<i) ) { //i'th bit is set in subset_id, then
//i is in the subset
subset.push_back(i);
}
}
//PREPARE FOR THE NEXT ITERATION
//increment the subset_id
//stop criteria - stop if subset_id == (2^size)
if ( subset_id++ == 1<<size ) { return false; }
return true;
}
private:
unsigned int size; //up to 32
unsigned int subset_id;
bool stop;
};
#ifdef TEST_SUBSETS_H
//compile
//g++ main-test-subsets.cpp
//run dvolper@main: learning $ ./a.out
//{}
//{0 }
//{1 }
//{0 1 }
//{2 }
//{0 2 }
//{1 2 }
//{0 1 2 }
//{3 }
//{0 3 }
//{1 3 }
//{0 1 3 }
//{2 3 }
//{0 2 3 }
//{1 2 3 }
//{0 1 2 3 }
//{4 }
//{0 4 }
//{1 4 }
//{0 1 4 }
//{2 4 }
//{0 2 4 }
//{1 2 4 }
//{0 1 2 4 }
//{3 4 }
//{0 3 4 }
//{1 3 4 }
//{0 1 3 4 }
//{2 3 4 }
//{0 2 3 4 }
//{1 2 3 4 }
//{0 1 2 3 4 }
int main () {
int size =4;
Subsets subsets_generator(size);
std::vector<unsigned int> subset(size);
do {
std::cout << "{";
for (unsigned int i=0; i<subset.size(); ++i) {
std::cout << subset[i] << " ";
}
std::cout << "}" << std::endl;
} while ( subsets_generator.next(subsets) );
}
#endif
#endif
| true |
a3a9d41547d3aa7f82394cf0da303fbbdefbbdd2 | C++ | ChiapasDeveloper/203-ACM-Problems-Code | /498.cpp | UTF-8 | 1,316 | 3.140625 | 3 | [
"MIT"
] | permissive | /* Problem: Polly the Polynomial UVa 498
Programmer: Md. Mahmud Ahsan
Description: Horner's Rule
Compiled: Visual Studio .Net
Date: 26-12-05
*/
#include <iostream>
#include <cmath>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
const long MX = 1000000;
double horner(int n, double array[], double x){
//horner compute the value of a polynomial of order n
double p;
p = array[n];
for (int i = n-1; i >= 0; --i){
p = p * x + array[i];
}
return p;
}
double array[MX], result;
char str1[MX], str2[MX], *ptr;
int main(){
#ifndef ONLINE_JUDGE
freopen("498.in", "r", stdin);
freopen("498.out", "w", stdout);
#endif
int n, i;
bool space;
while (cin.getline(str1, sizeof(str1))){
cin.getline(str2, sizeof(str2));
space = false;
i = -1;
ptr = strtok(str1, " \t\n");
while (ptr){
++i;
sscanf(ptr, "%lf", &array[i]);
ptr = strtok(NULL, " \t\n");
}
// reverse the order of the coefficients
reverse(array, array + i+1);
ptr = strtok(str2, " \t\n");
while (ptr){
sscanf(ptr, "%d", &n);
result = horner(i, array, n);
if (space)cout << " "; space = true;
//cout << result;
printf ("%.0f", result);
ptr = strtok(NULL, " \t\n");
}
cout << endl;
}
return 0;
} | true |
2622b2763d08d47bf129af68854470089b20982c | C++ | TomkneZ/Dll_Injection | /Dll/dllmain.cpp | UTF-8 | 1,836 | 2.609375 | 3 | [] | no_license | // dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <Windows.h>
#include <process.h>
#include <vector>
#define DLL_EXPORT __declspec(dllexport)
using namespace std;
extern "C" void DLL_EXPORT __stdcall ReplaceStr(DWORD pid, const char* search, const char* replace)
{
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (process)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
MEMORY_BASIC_INFORMATION info;
const size_t searchLength = sizeof(search);
const size_t replaceLength = sizeof(replace);
vector<char> chunk;
char* p = 0;
while (p < si.lpMaximumApplicationAddress)
{
if (VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info) && (info.State == MEM_COMMIT && info.AllocationProtect == PAGE_READWRITE))
{
p = (char*)info.BaseAddress;
chunk.resize(info.RegionSize);
SIZE_T bytesRead;
if (ReadProcessMemory(process, p, &chunk[0], info.RegionSize, &bytesRead))
{
for (size_t i = 0; i < bytesRead; ++i)
{
if (memcmp(search, &chunk[i], searchLength) == 0)
{
char* ref = p + i;
for (int j = 0; j < replaceLength; j++) {
ref[j] = replace[j];
}
ref[replaceLength] = 0;
}
}
}
}
p += info.RegionSize;
}
}
}
const char SEARCHSTR[] = "Original";
const char REPLACESTR[] = "Replaced";
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
DWORD pid = _getpid();
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
ReplaceStr(pid, SEARCHSTR, REPLACESTR);
break;
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
| true |
17fdb3dae8fe549ec60e9f5b84b9453759f96f2a | C++ | zjzdy/Offline-small-search | /history_obj.h | UTF-8 | 1,124 | 2.796875 | 3 | [
"OpenSSL"
] | permissive | #ifndef HISTORY_OBJ_H
#define HISTORY_OBJ_H
#include <QObject>
class history_obj : public QObject
{
Q_OBJECT
Q_PROPERTY(bool img READ img WRITE setImg NOTIFY imgChanged)
Q_PROPERTY(QString str READ str WRITE setStr NOTIFY strChanged)
Q_PROPERTY(QStringList search_type READ search_type WRITE setSearch_type NOTIFY search_typeChanged)
Q_PROPERTY(QString time READ time WRITE setTime NOTIFY timeChanged)
public:
explicit history_obj(QObject *parent = 0);
bool img() const;
void setImg(const bool & img);
QString str() const;
void setStr(const QString & str);
QStringList search_type() const;
void setSearch_type(const QStringList & search_type);
QString time() const;
void setTime(const QString & time);
Q_SIGNALS:
void imgChanged(const bool & img);
void strChanged(const QString & str);
void search_typeChanged(const QStringList & search_type);
void timeChanged(const QString & time);
private:
bool m_img;
QString m_str;
QStringList m_search_type;
QString m_time;
};
#endif // HISTORY_OBJ_H
| true |
6de8d26af0d720b5d5515fd35417a3a1debf4888 | C++ | fascinatingwind/BerkeleyServer | /BerkeleyServer/BerkeleyNetwork/src/SockBase.cpp | UTF-8 | 349 | 2.640625 | 3 | [] | no_license | #include "SockBase.h"
namespace Network {
int SockBase::GetSock() const {
return m_sock_fd;
}
bool SockBase::operator==(const SockBase &other) const {
return m_sock_fd == other.m_sock_fd;
}
bool SockBase::operator==(std::shared_ptr<SockBase> other) const {
return m_sock_fd == other->m_sock_fd;
}
} | true |
8f2c9957c5debeb6b2b10711c70c334274bfd7a1 | C++ | atp867/CSCI262-Ass3 | /activity.cpp | UTF-8 | 10,627 | 3.34375 | 3 | [] | no_license | /*************************************
* CSCI262 Assignment 3
* Intrusion Detection
* activity.cpp :Activity file
* 13/10/2018
* <Anthony Pham - atp867 - 5146562>
* <Daniel Nichols - dn688 - 5728356>
* <Olivia Followes - of767 - 5395707>
*************************************/
/*
Do we need even distribution for all randomness???
Because rand() % n is biased to lower values...
*/
#include "activity.h"
#include <sstream>
#include <cstring>
#include <iomanip>
using namespace std;
//Adds a vehicle to vehicle vector
void activityEngine::pushVehicles(Vehicle sample)
{
vehicleSim.push_back(sample);
}
//Adds a stats object to vehicleStats vector
void activityEngine::pushStats(Stats sample)
{
vehicleStats.push_back(sample);
}
//Sets road parameters from given road
void activityEngine::pushRoad(Road sample)
{
road.length = sample.length;
road.speedLim = sample.speedLim;
road.numParking = sample.numParking;
}
//Returns the road
Road activityEngine::getRoad()
{
return road;
}
//Returns vector of vehicles
std::vector<Vehicle> activityEngine::getVehicles()
{
return vehicleSim;
}
//Generates events for activity engine
void activityEngine::genEvents()
{
std::default_random_engine randEng;//not using seed for predictable testing
int i = 0;
//Iterate through all vehicle types
for(std::vector<Vehicle>::iterator it = vehicleSim.begin(); it != vehicleSim.end(); it++)
{
//Use normal distribution to determine number of vehicles
std::normal_distribution<float> normal(vehicleStats[i].avg, vehicleStats[i].stdDev);
int loop = lround(normal(randEng));
for(int x = 0; x < loop; x++)
{
//Other variable intialised in constructor
Instances temp;
temp.type = i;//associate type by vector index
temp.startTime = (rand() % MINUTESINDAY);//discrete event thus no stats required for generation
std::normal_distribution<float> normalSpeed(vehicleStats[i].speedAvg, vehicleStats[i].speedStdDev);
temp.initSpeed = lround(normalSpeed(randEng));
temp.rego = vehicleSim[i].rego;//Initalise instances rego
for(int k = 0; k < vehicleSim[i].rego.length();k++)//Generate random rego number
{
if(vehicleSim[i].rego[k] =='L')
temp.rego[k] = (rand() % (90-65 + 1) + 65);//random char
else
temp.rego[k] = (rand() % (57-48 + 1) + 48);//random int
}
temp.speed = temp.initSpeed;
while(temp.initSpeed < 1)
{//Vehicles must be moving forward to enter road
std::cerr << "Vehicle " << x << " Type : " << vehicleStats[i].name << " just had speed < 1" << std::endl;
std::normal_distribution<float> normalSpeed(vehicleStats[i].speedAvg, vehicleStats[i].speedStdDev);
temp.initSpeed = lround(normalSpeed(randEng));
temp.speed = temp.initSpeed;
}
temp.endTime = 0;
instances.push_back(temp);
}
i++;
}
}
//Start the activity engine
void activityEngine::startEngine(int days)
{
std::cout << "---------------- Beginning Activity Engine---------------- " << std::endl;
for(int i = 0; i < days; i++) //Simulation main driver loop
{
std::cout << "---------------- DAY " << i << " ----------------" << std::endl;
genEvents();
simDay();
//Statistics recording function here
printInstances(i);
clearInstances();
}
}
//Clears all instances from simulation
void activityEngine::clearInstances()
{
instances.clear();
}
//Simulates a day of activity
void activityEngine::simDay()
{
//std::default_random_engine randEng;
std::random_device rd;
std::mt19937 randEng(rd()); //Seed Mersenne Twist random engine with random number from hardware (more random than default random engine)
int hourClock = 0;
int parkingUsed = 0;
int exited = 0;
int sideExited = 0;
std::cout << " There are " << instances.size() << " instances" << std::endl;
//Simluates each minute of day
for(int i = 0; i < MINUTESINDAY; i++)
{
//Runs on each hour
if(i % 60 == 0)
{
std::cout << "**** Hour " << std::setw(2) << hourClock << "****" <<std::endl;
hourClock++;
}
//Iterates through instances and triggers events
for(std::vector<Instances>::iterator it = instances.begin(); it != instances.end(); it++)
{
if(it->startTime < i && it->endTime == 0)
{
if(it->parked)
it->parkingTime++;
//Vehicle reaches end of road
if(it->curLocation >= road.length)
{
//std::cout << "Vehicle has reached the end!" << std::endl;
it->endTime = i;
it->totalTime = it->endTime - it->startTime - it->parkingTime;
exited++;
}
//Vehicle exits via side road?
if((rand() % MINUTESINDAY) == STREETEXIT && it->endTime == 0)
{
//std::cout << "I have exited" << std::endl;
it->endTime = i;
it->totalTime = it->endTime - it->startTime - it->parkingTime;
sideExited++;
}
//Vehicle is not parked: update location
if(it->startTime < i && it->parked == false && it->endTime ==0)
{
//std::cout << "HELP " << std::endl;
it->curLocation += it->speed/60;//update location if vehicle not parked
}
//Random chance to try and park if isn't parked
if((rand() % MINUTESINDAY) < ISPARKED && parkingUsed < road.numParking && it->parked==false)//probability of parking
{
it->parked = true;
if(!vehicleSim[it->type].parking)
{// vehicle not allowed to park
if(rand() % ISPARKED != 1)//probabilty they park anyway is 1/200
{//bit roundabout...
it->parked = false;
parkingUsed--;
}
else
std::cout << "Not allowed to park but i did it anyway?" << std::endl;
}
//std::cout << "I have parked" <<std::endl;
parkingUsed++;
}
int random = rand() % MINUTESINDAY;
//Random chance to change speed
if(random < CHANGESPEED && it->endTime == 0)
{
//NEED TO FIND A WAY TO LINK TO STATS
if(it->parked)
{
//std::cout << "WAS PARKING" <<std::endl;
it->parked = false;
parkingUsed--;
}
//std::cout << "I have changed speeds" << std::endl;
std::normal_distribution<float> normal(vehicleStats[it->type].speedAvg,vehicleStats[it->type].speedStdDev);
it->speed = lround(normal(randEng));
if(rand() % MINUTESINDAY < CHANGESPEED && it->endTime == 0)
{//Probabilty one crazy boi
std::cout << "Some Boi is Speed !" << std::endl;
it->speed += 100;
}
//std::cout << "MY SPEED NOW IS " << it->speed << std::endl;
}
}
}
}
//Remove vehicles that have not exited at end of day
for(std::vector<Instances>::iterator it = instances.begin(); it != instances.end();)
{
if(it->endTime == 0)
{
instances.erase(it);
}
else
{
it++;
}
}
std::cout << exited << " CARS EXITED" << std::endl;
std::cout << sideExited << " CARS EXITED VIA STREET" << std::endl;
std::cout << "There are " << instances.size() << " instances" << std::endl;
}
//Print vehicle details and stats for all vehicles in simulation
void activityEngine::printVehicles()
{
std::vector<Stats>::iterator iterateStats = vehicleStats.begin();
for(std::vector<Vehicle>::iterator it = vehicleSim.begin(); it != vehicleSim.end(); it++)
{ //each loop is a new line
std::cout << "----------Vehicle-------- " <<std::endl;
std::cout << "Name : " << it->name << std::endl;
std::cout << "Parking : " << it->parking << std::endl;
std::cout << "Rego : " << it->rego << std::endl;
std::cout << "VolWeight : " << it->volWeight << std::endl;
std::cout << "SpeedWeight : " << it->speedWeight << std::endl;
std::cout << "----------Stats-----------" << std::endl;
std::cout << "Name : " << iterateStats->name <<std::endl;
std::cout << "Average : " << iterateStats->avg <<std::endl;
std::cout << "StdDev : " << iterateStats->stdDev <<std::endl;
std::cout << "SpeedAverage : " << iterateStats->speedAvg <<std::endl;
std::cout << "SpeedStdDev : " << iterateStats->speedStdDev <<std::endl;
iterateStats++;
}
}
//Print all current vehicle instances in simulation
void activityEngine::printInstances(int days)
{
char file[13];
std::ostringstream oss;
oss << "day" << days << ".txt";
strcpy(file,(oss.str()).c_str());
std::ofstream fout;
fout.open(file);
std::cout << "Day " << days << " Simulation complete " << std::endl;
std::cout << "Day " << days << " Complete logging data to " << file << std::endl;
for(std::vector<Instances>::iterator it = instances.begin(); it != instances.end(); it++)
{
fout << "******Vehicle******" << std::endl;
fout << "Name : " << vehicleSim[it->type].name << std::endl;
fout << "Rego : " << it->rego << std::endl;
fout << "Type : " << it->type << std::endl;
fout << "Start : " << it->startTime << std::endl;
fout << "ParkingTime : " << it->parkingTime << std::endl;
fout << "Initial Speed : " << it->initSpeed << std::endl;
fout << "Location : " << it->curLocation << std::endl;
fout << "Total : " << it->totalTime << std::endl;
fout << "End : " << it->endTime << std::endl;
}
fout.close();
}
| true |
cab72edda1176149ba3f5f8d37647288429a50bf | C++ | pescoboza/Genesia | /SpriteSheet.h | UTF-8 | 1,407 | 2.703125 | 3 | [] | no_license | #ifndef SPRITE_SHEET_H
#define SPRITE_SHEET_H
#include <unordered_map>
#include <memory>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include "Anim_Base.h"
#include "TextureManager.h"
#include "Utilities.h"
using Animations = std::unordered_map < std::string, std::unique_ptr<Anim_Base>>;
class SpriteSheet {
std::string m_texture;
sf::Sprite m_sprite;
sf::Vector2u m_spriteSize;
sf::Vector2f m_spriteScale;
sf::Vector2f m_sheetPadding;
sf::Vector2f m_spriteSpacing;
Animations m_animations;
Anim_Base* m_animationCurrent;
TextureManager* m_textureManager;
public:
SpriteSheet(TextureManager* t_textureMgr);
~SpriteSheet();
void cropSprite(const sf::IntRect& t_rect);
sf::Vector2u getSpriteSize()const;
sf::Vector2f getSpritePosition()const;
void setSpriteSize(const sf::Vector2u& t_size);
void setSpritePosition(const sf::Vector2f& t_pos);
void setSheetPadding(const sf::Vector2f& t_padding);
void setSpriteSpacing(const sf::Vector2f& t_spacing);
sf::Vector2f getSheetPadding()const;
sf::Vector2f getSpriteSpacing()const;
sf::FloatRect getSpriteBounds()const;
bool loadSheet(const std::string& t_file);
void releaseSheet();
Anim_Base* getCurrentAnim();
bool setAnimation(const std::string& t_name, bool t_play = false, bool t_loop = false);
void update(float t_dt);
void draw(sf::RenderWindow* t_wind);
};
#endif // !SPRITE_SHEET_H | true |
371b2cfeb82e5a0cdac25d00c8f0cbe84f59d43e | C++ | zybin2756/malgorithm | /Tools/sorttesthelper.h | UTF-8 | 1,884 | 3.484375 | 3 | [] | no_license | #ifndef SORTTESTHELPER_H
#define SORTTESTHELPER_H
#include <ctime>
#include <iostream>
#include <string>
#include <cassert>
#include <stdlib.h>
#include <iomanip>
using namespace std;
namespace SortTestHelper {
template<typename T>
bool isSorted(T arr[], int n){
for(int i = 1; i < n; ++i){
if(arr[i] < arr[i-1])
return false;
}
return true;
}
template<typename T>
void sortTest(string name, void (*sort)(T arr[], int n), T arr[], int n){
clock_t start_time = clock();
sort(arr, n);
clock_t end_time = clock();
// assert(SortTestHelper::isSorted(arr, n));
cout << name <<" n:" << n << endl;
cout << fixed << setprecision(8) << ((double)end_time - start_time)/CLOCKS_PER_SEC << " s" << endl;
}
template<typename T>
void printArray(T arr[], int n){
for(int i = 0; i < n; ++i){
cout << arr[i] << " ";
}
cout << endl;
}
int* createRandomArray(int rangeL, int rangeR, int n){
srand(time(NULL));
int* arr = new int[n];
for(int i = 0; i < n; ++i){
arr[i] = rand() % (rangeR - rangeL) + rangeL;
}
return arr;
}
int* crateNealySortArray(int n, int swapTimes){
srand(time(NULL));
int* arr = new int[n];
for(int i = 0; i < n; ++i){
arr[i] = i;
}
while(swapTimes-- > 0){
int s = rand()%n;
int e = rand()%n;
swap(arr[s], arr[e]);
}
return arr;
}
template<typename T>
T* copyArray(T arr[], int n){
T* new_arr = new T[n];
for(int i = 0; i < n ; ++i){
new_arr[i] = arr[i];
}
return new_arr;
}
}
#endif // SORTTESTHELPER_H
| true |
cdc550b8327cd953e4012b21b94e82f71c323927 | C++ | beached/robot | /roomba/tests/cameratest.cpp | UTF-8 | 1,297 | 2.796875 | 3 | [] | no_license | #include <boost/thread.hpp>
#include <cstdlib>
#include <iostream>
#include "camera.h"
#include "opencvimage.h"
int main( int argc, char** argv ) {
const int interval = 1000;
int width = -1;
int height = -1;
if( argc > 1) {
std::stringstream ss;
ss << argv[1];
ss >> width;
ss.str( std::string( ) );
ss.clear( );
ss << argv[2];
ss >> height;
}
std::cout << argv[0] << ": Starting Camera";
if( width > 0 && height > 0 ) {
std::cout << "with a resolution of " << width << "x" << height;
}
std::cout << std::endl;
daw::Camera camera( width, height, true );
// Init camera
for( size_t n=0; n<10; ++n ) {
camera.capture( );
}
camera.startBackgroundCapture( interval );
int count = 0;
while( true ) {
if( camera.hasImage( ) ) {
daw::imaging::OpenCVImage img = camera.image( );
std::cout << "width: " << img.width( ) << " height: " << img.height( ) << std::endl;
std::stringstream ss;
ss << "./cameratest_" << count++ << ".jpg";
const std::string fname = ss.str( );
std::cerr << "Saving to " << fname << std::endl;
cvSaveImage( fname.c_str( ), img.get( ) );
if( count >= 10 ) {
break;
}
}
boost::this_thread::sleep( boost::posix_time::milliseconds( interval ) );
}
camera.stopWaitBackgroundCapture( );
return EXIT_SUCCESS;
}
| true |
ac63b74d0b58b31e22e3a00bb1e7ae97c56c8902 | C++ | Pimed23/UNSA | /CC1_Programs/CC_Teoria/Practica_2/15_MCD.cpp | UTF-8 | 453 | 3.609375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int mcd( int x, int y ) {
if ( y == 0 )
return x;
else
return mcd( y, x % y ); }
int main() {
int a, b;
float r;
cout << "Ingrese el primer numero: " << endl;
cin >> a;
cout << "Ingrese el segundo numero: " << endl;
cin >> b;
if ( a > b )
r = mcd( a, b );
else
r = mcd( b, a );
cout << "El MCD sera: " << r << endl;
return 0;
}
| true |
2d541512f638c6d1298ea96ce39116740880f331 | C++ | akkaze/Excercise | /reduce/reduce.hpp | UTF-8 | 2,289 | 2.625 | 3 | [] | no_license | template <typename T> struct GetType;
template <typename T> struct GetType<T*>
{
typedef T type;
};
template <typename T> struct GetType<volatile T*>
{
typedef T type;
};
template <typename T> struct GetType<T&>
{
typedef T type;
};
template <int I,int N> struct For
{
template <class PointerTuple,class ValTuple>
__device__ static void loadToSmem(const PointerTuple& smem,const ValTuple& val,uint tid)
{
get<I>(val) = get<I>(smem)[tid];
For<I + 1, N>::loadFromSmem(smem, val, id);
}
template <class PointerTuple,class ValTuple,class OpTuple>
__device__ static void merge(const PointerTuple& smem,const ValTuple& val,uint tid,uint delta,const OpTuple& op)
{
typename GetType<typename tuple_element<I,PointerTuple>::type>::type reg = get<I>(smem)[tid + delta];
get<I>(smem)[tid] = get<I>(val) = get<I>(op)(get<I>(val),reg);
For<I + 1,N>::merge(smem,val,tid,delta,op);
}
#if CUDA_ARCH >= 300
template <class PointerTuple,class ValTuple,class OpTuple>
__device__ static void mergeShfl(const ValTuple& val,uint delta,uint width,const OpTuple& op)
{
typename GetType<typename tuple_element<I,ValTuple>::type>::type reg = shfl_down(get<I>(val),delta,width,op);
}
#endif
};
template <int N> struct For<N,N>
{
template <class PointerTuple,class ValTuple>
__device__ __forceinline__ static void loadToSmem(const PointerTuple&,const ValTuple,uint) {}
__device__ __forceinline__ static void loadFromSmem(const PointerTuple&,const ValTuple&,uint) {}
__device__ __forceinline__ template <class PointerTuple&,class ValTuple&,class OpTuple&> {}
#if CUDA_ARCH >= 300
template <class ValTuple,class OpTuple>
__device__ __ __forceinline__ static void mergeShfl(const ValTuple&,uint,uint,const OpTuple&) {}
#endif
};
template <typename T>
__device__ __forceinline__ void loadToSmem(volatile T* smem,T& val,uint tid)
{
smem[tid] = val;
}
template <typename T>
__device__ __forceinline__ void loadFromSmem(volatile T* smem,T& val,uint tid)
{
val = smem[tid];
}
template <typename T,class Op>
__device__ __forceinline__ void merge(volatile T* smem,T& val,uint tid,uint delta,const Op& op)
{
T reg = smem[tid + delta];
smem[tid] = val = op(val,reg);
}
| true |
8488e1636477eb10a3ac7c510edd4b3fa449fd6b | C++ | cubetrain/CubeTrain | /contracts/libc++/upstream/test/std/utilities/memory/temporary.buffer/temporary_buffer.pass.cpp | UTF-8 | 781 | 2.609375 | 3 | [
"NCSA",
"MIT"
] | permissive | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <memory>
// template <class T>
// pair<T*, ptrdiff_t>
// get_temporary_buffer(ptrdiff_t n);
//
// template <class T>
// void
// return_temporary_buffer(T* p);
#include <memory>
#include <cassert>
int main()
{
std::pair<int*, std::ptrdiff_t> ip = std::get_temporary_buffer<int>(5);
assert(ip.first);
assert(ip.second == 5);
std::return_temporary_buffer(ip.first);
}
| true |
123a69ac5beecc0789ef141bda7f0121501b3e98 | C++ | uchihaitachi08/daily_code | /c++/test2.cpp | UTF-8 | 1,007 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
long int increment(long int* count, long int nim,long int i, long int j){
long int c = nim^i^j^(i+j);
if(c == 0){
*count = *count + 1;
}
return c;
}
void printarray(vector<long int>*v){
for(int k=0;k<v->size();k++){
cout<<(*v)[k]<<" ";
}
cout<<endl;
}
void count_sum(vector<long int>*v, long int* count,long int nim){
long int temp, nim_temp = nim;
if(v->size() == 1)
return;
for(int i=0;i<v->size()-1;i++){
//printarray(v);
(*v)[i] = (*v)[i]+(*v)[i+1];
temp = (*v)[i+1];
v->erase(v->begin()+i+1);
nim = increment(count,nim,(*v)[i]-temp,temp);
count_sum(v,count,nim);
(*v)[i] = (*v)[i] - temp;
v->insert(v->begin()+i+1,temp);
nim = nim_temp;
}
return;
}
int main(){
int t;
long int temp,nim = 0,count = 0;
cin>>t;
vector<long int>v;
for(int i=0;i<t;i++){
cin>>temp;
v.push_back(temp);
nim = nim^temp;
}
count_sum(&v,&count,nim);
if(!nim)
count++;
cout<<count<<endl;
return 0;
} | true |
2f483f755d8c24779ceb6880802d03705951fec6 | C++ | m516/8BitSynth | /Instrument.cpp | UTF-8 | 2,011 | 2.875 | 3 | [] | no_license | #include "Arduino.h"
#include "Instrument.h"
Instrument::Instrument(){}
void Instrument::setTimber(float sine, float triangle, float sawtooth, float square, float noise){
for(int i = 0; i < SAMPLE_SIZE; i++){
float fi = float(i)/float(SAMPLE_SIZE);
float sample = 0.0; //-1.0 -> 0, 1.0 -> 256
//Add sin function
sample += sine * sin(fi*2.0*PI);
//Add triangle function
if(sample<SAMPLE_SIZE/2){
sample += triangle*(fi*4.0-1.0);
}else{
sample += triangle*(float(SAMPLE_SIZE-i)*4.0/SAMPLE_SIZE-1.0);
}
//add sawtooth function
sample += sawtooth * (fi * 2.0 - 1.0);
//add square function
if(i<SAMPLE_SIZE/2){
sample += -square;
}else{
sample += square;
}
//add random funtion
sample += noise * (float) random() / 2147483647.0;
//Compress the sample into a byte
_waveform[i] = byte(127.0*sample+127.0);
//_waveform[i] = sin(fi*2.0*PI)*127.0+127.0;
//Generate samples of a sawtooth wave
//_waveform[i] = i;
}
}
void Instrument::setFrequency(int index, float frequency){
_timers[index].setFrequency(frequency);
}
void Instrument::setPitch(int index, float pitch){
_timers[index].setPitch(pitch);
}
void Instrument::enableNote(byte index){
if(~_enabled & 1<<index) _count++;
_enabled |= 1<<index;
}
void Instrument::disableNote (byte index){
if(_enabled & 1<<index) _count--;
_enabled ^= 1<<index;
}
void Instrument::setVolume(byte volume){
_volume = volume;
}
uint8_t Instrument::getSample(){
return (uint8_t) _sample;
}
uint8_t Instrument::update(){
if(_enabled & 1) _sample = _waveform[_timers[0].update()];
else _sample = 0;
if(_enabled & 2) _sample += _waveform[_timers[1].update()];
if(_enabled & 4) _sample += _waveform[_timers[2].update()];
if(_enabled & 8) _sample += _waveform[_timers[3].update()];
/*//Too slow
_sample = 0;
for(_i = 0; _i < NUM_TONES; _i++){
if(_enabled & 1<<_i){
_sample += _timers[_i].update();
}
}
*/
_sample = ((_sample-(128*_count)) >> _volume) + 127;
return (uint8_t) _sample;
}
| true |
07486968c1e937372aff56fd390c30828d408327 | C++ | TalBarYakar/Selection-problem | /project2Adt/BST.h | UTF-8 | 799 | 2.90625 | 3 | [] | no_license | #ifndef _BST_H
#define _BST_H
#include"person.h"
class BSTree
{
private:
int numberOfleaves;
BSTtreeNode *root;
int numberOfComapres;
public:
friend BSTtreeNode;
BSTree();
~BSTree();
BSTtreeNode* find(int key );
void insert(person* newPerson);
person* Delete(person* delPerson);
const int getNumberOfCompares() const;
void printTree() const;
const person* BST(person** parray, int k,int size, int &NumComp);
};
class BSTtreeNode
{
private:
int HowManyNodesSubTree;
person* currPerson;
BSTtreeNode*left, *right;
public:
BSTtreeNode* DeleteRec(int k,int *comp);
void deleteRec();
friend BSTree;
BSTtreeNode(person* ptr);
~BSTtreeNode();
void PrintInorder() const;
void MakeMinArrayFromTree(person** arr, int& i, int& key, int &numcomp);
};
#endif // !_BST_H
| true |
9ded9f69573324653fc4bea0e9552b3f22fc0031 | C++ | GriTRini/study | /ACCELERATED/chap9/score10/main.cpp | UTF-8 | 558 | 3.0625 | 3 | [] | no_license | //
// Created by user on 2021-06-07.
//
#include <vector>
#include <iostream>
#include <algorithm>
#include "student_info.h"
#include "grade.h"
using namespace std;
int main()
{
vector<Student_info> students;
Student_info s;
while(s.read(cin)) {
students.push_back(s);
}
sort(students.begin(), students.end(), ::compare);
vector<Student_info>::const_iterator iter;
for (iter = students.cbegin(); iter != students.cend(); ++iter) {
cout << iter->name() << " : " << iter->grade() << endl;
}
return 0;
} | true |
2516b3d7457086868b135ab9d66ea163f0003886 | C++ | SunInTeo/FMI-OOP | /Seminar/Week 09 Files/Jedi.h | UTF-8 | 713 | 2.96875 | 3 | [] | no_license | #ifndef JEDI_H
#define JEDI_H
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
const std::size_t INITIAL_CAPACITY = 2;
const std::size_t INCREASE_STEP = 2;
class Jedi
{
static int version;
char **skills;
std::size_t size;
std::size_t capacity;
int age;
void copy(const Jedi &other);
void deallocate();
void resize();
public:
Jedi();
Jedi(const Jedi &other);
~Jedi();
void read(const char *filename);
void write(const char *filename);
void setAge(int age);
void addNewSkill(const char *skill);
Jedi &operator=(const Jedi &other);
friend std::ostream &operator<<(std::ostream &out, const Jedi &jedi);
};
#endif | true |
e875c5d998c86f6468cf64ad0fff0557a9464754 | C++ | shyamalschandra/Kinect-6DSlam | /kinect-6dslam-data-recorder/src/Slam.cpp | UTF-8 | 3,993 | 2.515625 | 3 | [] | no_license | /*
* Slam.cpp
* ofxKinect
*
* Created by Minjae Lee on 4/17/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "Slam.h"
// This might change since this is found in trial-error technique
#define INDEX(x, y) (((w) - (x)) + (y) * (w))
inline std::string Slam::to_string(const int t, int width)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(width) << t;
return ss.str();
}
void Slam::init()
{
slam_mode = INACTIVE;
scan_count = 0;
vps.clear();
}
void Slam::toggle()
{
if(slam_mode == INACTIVE)
{
scan_count = 0;
max_box = 0;
slam_mode = RECORD;
std::cout << "Recording..." << std::endl;
}
else if(slam_mode == RECORD)
{
slam_mode = SAVE;
std::cout << "Saving..." << std::endl;
}
}
void Slam::update(ofxKinect &kinect, ofxCvGrayscaleImage &mask)
{
if(slam_mode == RECORD)
{
gen_record(kinect, mask, 640, 480, 1);
}
else if(slam_mode == SAVE)
{
gen_save("", 360);
}
}
void Slam::gen_record(ofxKinect &kinect, ofxCvGrayscaleImage &mask, size_t w, size_t h, size_t step)
{
Points pts;
unsigned char *mask_pixels = mask.getPixels();
for(size_t y = 0; y < h; y += step)
{
for(size_t x = 0; x < w; x += step)
{
size_t i = INDEX(x, y);
if(mask_pixels[i] == 0) continue;
ofxVec3f p = kinect.getWorldCoordinateFor(x, y);
Vector3 v;
v.x = p.x;
v.y = p.y;
v.z = p.z;
int maxp = max(abs(v.x), max(abs(v.y), abs(v.z)));
if(maxp > max_box) max_box = maxp;
pts.push_back(v);
}
}
vps.push_back(pts);
}
void Slam::gen_save(std::string path, float total_deg)
{
// Assume that we turned total_deg with approximately same dt
int j = 0;
float d = total_deg / float(vps.size());
for(float i = 0.0; i < total_deg; i += d)
{
std::string scanname = path + "scan" + to_string(j, 3) + ".3d";
std::string rotname = path + "scan" + to_string(j, 3) + ".pose";
FILE *fd = fopen(scanname.c_str(), "w+");
FILE *fe = fopen(rotname.c_str(), "w+");
if(fd && fe)
{
fprintf(fd, "%dx%d\n", max_box + 1, max_box + 1);
for(size_t k = 0; k < vps[j].size(); k++)
{
float x = vps[j].at(k).x;
float y = vps[j].at(k).y;
float z = vps[j].at(k).z;
fprintf(fd, "%f %f %f\n", x, y, z);
}
fprintf(fe, "0 0 0\n0 %f 0", i);
fclose(fd);
fclose(fe);
}
j++;
}
vps.clear();
slam_mode = INACTIVE;
}
void Slam::alt_init()
{
scan_alt_count = 0;
}
void Slam::alt_gen_scan(ofxKinect &kinect, ofxCvGrayscaleImage &mask, std::string path, size_t w, size_t h, size_t step)
{
std::string scanname = path + "scan" + to_string(scan_alt_count, 3) + ".3d";
FILE *fd = fopen(scanname.c_str(), "w+");
unsigned char *mask_pixels = mask.getPixels();
if(fd)
{
unsigned int maxp = 0;
for(size_t y = 0; y < h; y += step)
{
for(size_t x = 0; x < w; x += step)
{
size_t i = INDEX(x, y);
if(mask_pixels[i] == 0) continue;
ofxVec3f p = kinect.getWorldCoordinateFor(x, y);
Vector3 v;
v.x = p.x;
v.y = p.y;
v.z = p.z;
int reach = max(abs(v.x), max(abs(v.y), abs(v.z)));
if(reach > maxp) maxp = reach;
}
}
fprintf(fd, "%dx%d\n", maxp + 1, maxp + 1);
for(size_t y = 0; y < h; y += step)
{
for(size_t x = 0; x < w; x += step)
{
size_t i = INDEX(x, y);
if(mask_pixels[i] == 0) continue;
ofxVec3f p = kinect.getWorldCoordinateFor(x, y);
Vector3 v;
v.x = p.x;
v.y = p.y;
v.z = p.z;
fprintf(fd, "%f %f %f\n", v.x, v.y, v.z);
}
}
fclose(fd);
scan_alt_count++;
}
}
void Slam::alt_gen_pose(std::string path, float total_deg)
{
int j = 0;
float d = total_deg / float(scan_alt_count);
for(float i = 0.0; i < total_deg; i += d)
{
std::string rotname = path + "scan" + to_string(j, 3) + ".pose";
FILE *fd = fopen(rotname.c_str(), "w+");
if(fd)
{
fprintf(fd, "0 0 0\n0 %f 0", i);
fclose(fd);
}
j++;
}
scan_alt_count = 0;
}
| true |
916642017acb6ab1b983d78cddfa4c91ad160417 | C++ | Arby3k/Sketch-Draw | /CPong.cpp | UTF-8 | 3,322 | 2.546875 | 3 | [] | no_license | #include "stdafx.h"
#include "CPong.h"
#define BUT1 33
#define BUT2 32
CPong::CPong(int windowX, int windowY, int _comport)
{
mCControl.init_com(_comport);
mCanvas = cv::Mat::zeros(cv::Size(windowX, windowY), CV_8UC3);
//cv::imshow("Window-of-Doom", mCanvas);
}
CPong::~CPong()
{
}
void CPong::update()
{
cv::imshow("Window-of-Doom", mCanvas);
mCanvas = cv::Mat::zeros(mCanvas.size(), mCanvas.type());
}
void CPong::draw()
{
static float ballX = 500;
static float ballY = 400;
static float xspeed = -8;
static float yspeed = 8;
static float P2Pos;
float rand = std::rand() % 40 -20;
float rand2 = std::rand() % 40 -20;
static int t = xspeed;
static int u = yspeed;
//rand = rand / 10;
//rand2 = rand / 10;
// Staic Game State Drawn before anything else to keep it "Under" everything else.
static int score1 = 0;
static int score2 = 0;
std::string score1Str = std::to_string(score1);
std::string score2Str = std::to_string(score2);
cv::line(mCanvas, cv::Size(500, 0), cv::Size(500, 800), cv::Scalar(0, 0, 255), 2, CV_AA, 0);
cv::line(mCanvas, cv::Size(0, 0), cv::Size(1000, 0), cv::Scalar(2500, 255, 255), 2, CV_AA, 0);
cv::line(mCanvas, cv::Size(0, 800), cv::Size(1000, 800), cv::Scalar(2500, 255, 255), 2, CV_AA, 0);
cv::putText(mCanvas, "Player 1", cv::Size(100, 50), CV_FONT_HERSHEY_PLAIN, 2, cv::Scalar(100, 255, 100), 2);
cv::putText(mCanvas, "Player 2", cv::Size(700, 50), CV_FONT_HERSHEY_PLAIN, 2, cv::Scalar(100, 255, 100), 2);
cv::putText(mCanvas, score1Str, cv::Size(450, 50), CV_FONT_HERSHEY_PLAIN, 2, cv::Scalar(100, 255, 100), 2);
cv::putText(mCanvas, score2Str, cv::Size(530, 50), CV_FONT_HERSHEY_PLAIN, 2, cv::Scalar(100, 255, 100), 2);
mCControl.get_analog(rawX, rawY);
posY = rawY * .75;
if (posY >= 700) {
posY = 700;
}
if (posY <= 0) {
posY = 0;
}
posX = rawX;
//Player 1 Paddle
cv::rectangle(mCanvas, cv::Size(5, 800-posY), cv::Size(20, 700-posY), cv::Scalar(255, 0, 0), CV_FILLED, CV_AA, 0);
//Ball
ballX = ballX + xspeed;
ballY = ballY + yspeed;
P2Pos = ballY - 50;
std::cout <<"rand:" << rand << "\r";
cv::circle(mCanvas, cv::Point(ballX, ballY), 20, cv::Scalar(150, 150, 150), CV_FILLED, 1, 0);
if (((ballY + 15) > 800) || ((ballY - 15) < 0)) {
yspeed = (yspeed * -1);
}
if (((ballX - 10) < 25) && ((ballY + 5) <= (820 - posY) && (ballY - 5) >= (680 - posY))) {
xspeed = (xspeed * -1);
}
if (((ballX - 10) < 10)){
score2++;
ballX = 500;
ballY = 400;
if (rand < 0) {
xspeed = -t;
}
if (rand > 0) {
xspeed = t;
}
if (rand2 < 0) {
yspeed = -u;
}
if (rand2 > 0) {
yspeed = u;
}
}
//Player 2 Paddle
if (P2Pos >= 700) {
P2Pos = 700;
}
if (P2Pos <= 0) {
P2Pos = 0;
}
cv::rectangle(mCanvas, cv::Size(980, P2Pos), cv::Size(995, P2Pos + 100), cv::Scalar(0, 255, 255), CV_FILLED, CV_AA, 0);
if (((ballX + 10) > 980)) {
xspeed = (xspeed * -1);
}
if (score2 == 5) {
mCanvas = cv::Mat::zeros(mCanvas.size(), mCanvas.type());
cv::imshow("Window-of-Doom", mCanvas);
do {
cv::putText(mCanvas, "You LOST!", cv::Size(300, 400), CV_FONT_HERSHEY_PLAIN, 4, cv::Scalar(100, 255, 100), 2);
cv::imshow("Window-of-Doom", mCanvas);
} while (cv::waitKey(1) != 'q');
score2 = 0;
ballX = 500;
ballY = 400;
xspeed = t;
yspeed = u;
}
} | true |
ed56d9f4639840ee1d6a06253e21f34aea13de00 | C++ | msins/NOS | /lab1a/Auto.cpp | UTF-8 | 1,492 | 3.140625 | 3 | [] | no_license | #include <thread>
#include "logging.h"
#include "random.h"
#include "messages.h"
#include "queues.h"
int main(int argc, char *argv[]) {
int registration = std::stoi(argv[1]);
int direction = std::stoi(argv[2]);
Car car = {registration, direction};
key_t carQueueKey = CAR_QUEUE_KEY;
key_t commandQueueKey = COMMAND_QUEUE_KEY;
int timeToSleep = randomInt(100, 2000);
std::this_thread::sleep_for(std::chrono::milliseconds(timeToSleep));
// connect to a queue which sends requests to semaphore
int carQueueId = connectToQueue(carQueueKey);
// connect to a queue which receives commands from semaphore
int commandQueueId = connectToQueue(commandQueueKey);
// message type is direction of crossing so semaphore could decide which cars to let across
CarMessage message{car.direction + 1, car};
// send request for crossing to the semaphore
addToCarQueue(carQueueId, &message);
log("Automobil " + std::to_string(car.registration) + " ceka na prelazak preko mosta.");
// receive response from the semaphore, message type is registration which is unique
CommandMessage command{};
receiveFromCommandQueue(commandQueueId, &command, car.registration);
log("Automobil " + std::to_string(command.car.registration) + " se popeo na most.");
receiveFromCommandQueue(commandQueueId, &command, car.registration);
log("Automobil " + std::to_string(command.car.registration) + " je presao most.");
return 0;
}
| true |
69f770b079eca76023b5e080fc4357167bcf32ff | C++ | franciscoSoler/nebla | /distribuidos/Duran/ej5/src/IPC/SharedMemory/AbstractSharedMemory.cpp | UTF-8 | 1,974 | 2.8125 | 3 | [] | no_license | #include "AbstractSharedMemory.h"
#include "../IPCException.h"
AbstractSharedMemory::AbstractSharedMemory () {
}
AbstractSharedMemory::~AbstractSharedMemory() {
}
int AbstractSharedMemory::getSharedMemory(char *fileName, int id) {
this->getId(fileName, id, 0666);
return this->attachMemory();
}
int AbstractSharedMemory::createSharedMemory(char *fileName, int id) {
this->getId(fileName, id, 0666|IPC_CREAT|IPC_EXCL);
return this->attachMemory();
}
int AbstractSharedMemory::destroy(void) {
// Me desattacho de la memoria
shmdt ( (void *)this->data );
// Si no quedan procesos attachados, libero la memoria
//if (! this->getCantAttachProcesses()) {
shmctl(this->id, IPC_RMID, NULL);
//}
return 0;
}
int AbstractSharedMemory::getCantAttachProcesses(void) const {
shmid_ds estado;
shmctl(this->id, IPC_STAT, &estado);
return estado.shm_nattch;
}
int AbstractSharedMemory::attachMemory() {
// Me attacho a la memoria dejando al SO que elija donde ubicar la memoria
//(atributo en NULL)y para lectura/escritura (atributo en 0)
void *shmaddr = shmat(this->id, NULL, 0);
if (shmaddr == (void *)-1) {
char error[255];
sprintf(error, "Fallo la operacion shmat: %s", strerror(errno));
char className[255];
strcpy(className, "AbstractSharedMemory");
throw IPCException(className, error);
}
data = shmaddr;
return 0;
}
int AbstractSharedMemory::getId(char *fileName, int id, int flags) {
key_t clave = ftok (fileName, id);
if ( clave == -1 ) {
char error[255];
sprintf(error, "Fallo la operacion ftok: %s", strerror(errno));
char className[255];
strcpy(className, "AbstractSharedMemory");
throw IPCException(className, error);
}
this->id = shmget( clave, this->getMemorySize() , flags);
if ( this->id == -1 ) {
char error[255];
sprintf(error, "Fallo la operacion shmget: %s", strerror(errno));
char className[255];
strcpy(className, "AbstractSharedMemory");
throw IPCException(className, error);
}
return 0;
}
| true |
1baefdcb1e250337c11fc4fc2e21127b30ea6ea0 | C++ | sytu/cpp_primer | /ch05/5_7_correction.cpp | UTF-8 | 535 | 3.71875 | 4 | [] | no_license | //a.
if (ival1 != ival2)
ival1 = ival2; // add semicolon at here
else ival1 = ival2 = 0;
//b.
if (ival < minval) { // Braces needed to include both satetments in scope.
minval = ival;
occurs = 1;
}
//c.
if (int ival = get_value())
cout << "ival = " << ival << endl;
else if (!ival) // Second if statement should be else-if.
cout << "ival = 0\n";
// ival cannot be accessed outside the range of the if statement
//d.
if (ival == 0) // using == equality operator instead of using = assignment operator
ival = get_value();
| true |
8bddb107c39193d357936b7f165a8543b7a994ae | C++ | wlau006/endre_test | /notes and extra/rletest.cpp | UTF-8 | 1,290 | 2.90625 | 3 | [] | no_license | #include "rle.h"
#include <iostream>
int main(){
//std::string hello = "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x42\x42\x42\x42\x42\x42\x42";
std::string hello = "how many shrimp do you have to eat, before you make your skin turn pink, eat too much and you'll get sick, shrimp are pretty rich";
rle thing;
std::cout << "V1" << std::endl;
std::cout << "ORIGINAL: " << hello << std::endl;
std::string output = thing.encode(hello);
std::cout << "ENCODED: " << output << std::endl;
std::string decode = thing.decode(output);
std::cout << "DECODED: " << decode << std::endl;
if(hello != decode){
std::cout << "RLE FAILED" << std::endl;
}else{
std::cout << "RLE SUCCESS" << std::endl;
}
std::cout << std::endl;
std::cout << "==========================================" << std::endl << std::endl;
std::cout << "V2" << std::endl;
std::cout << "ORIGINAL: " << hello << std::endl;
output = thing.encodev2(hello);
std::cout << "ENCODED: " << output << std::endl;
decode = thing.decodev2(output);
std::cout << "DECODED: " << decode << std::endl;
if(hello != decode){
std::cout << "RLE FAILED " << std::endl;
}else{
std::cout << "RLE SUCCESS" << std::endl;
}
return 0;
} | true |
0e47b8e23de041a57aa17ee126eff09d5fe98746 | C++ | programmerQI/CSCI2270 | /hw2/hw2n.cpp | UTF-8 | 4,706 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
#define ARRAYSIZE_IGNOREWORDS 50
#define STARTSIZE_UNIQUEWORDS 100
int arraysize_uniquewords = STARTSIZE_UNIQUEWORDS;
int dtimes = 0;
struct WordItem{
std::string word;
int count;
WordItem() : word(""), count(0) {}
};
WordItem* doubleArray(WordItem ori[])
{
dtimes ++;
int size_newarray = 2 * arraysize_uniquewords;
WordItem* newArray = new WordItem[size_newarray];
for(int i = 0; i < arraysize_uniquewords; i ++){
newArray[i] = ori[i];
}
arraysize_uniquewords = size_newarray;
delete [] ori;
ori = NULL;
return newArray;
}
int getStopWords(std::string filename, std::string ignorewords[], int size)
{
std::ifstream in(filename);
if(! in.is_open()){
return -1;
}
int cnt = 0;
std::string line;
while(std::getline(in, line)){
if(cnt >= size){
break;
}
ignorewords[cnt ++] = line;
}
in.close();
return cnt;
}
bool isStopWord(std::string word, std::string ignorewords[], int l)
{
for(int i = 0; i < l; i ++){
if(word == ignorewords[i]){
return true;
}
}
return false;
}
int isUniqueWord(std::string word, WordItem uniquewords[], int l)
{
for(int i = 0; i < l; i ++){
if(word == uniquewords[i].word){
//std::cout << "221" << std::endl;
return i;
}
}
return -1;
}
int readText(std::string filename, WordItem **uniquewords, int *numuqwords, std::string ignorewords[], int numigwords)
{
std::ifstream in(filename);
if(! in.is_open()){
return -1;
}
int total = 0;
std::string line = "";
while(getline(in, line)){
std::string word = "";
line.append(" ");
for(int i = 0; i < line.length(); i ++){
char c = line[i];
if(c == ' ' && ! word.empty()){
if(!isStopWord(word, ignorewords, numigwords)){
int index_uqword = isUniqueWord(word, *uniquewords, *numuqwords);
if(index_uqword != -1){
(*uniquewords)[index_uqword].count ++;
} else {
if((*numuqwords) >= arraysize_uniquewords){
*uniquewords = doubleArray(*uniquewords);
}
(*uniquewords)[(*numuqwords)].word = word;
(*uniquewords)[(*numuqwords)].count ++;
(*numuqwords) ++;
}
total ++;
}
word = "";
} else {
word = word + c;
}
}
}
in.close();
return total;
}
void qSort(WordItem uniqueWords[], int begin, int end)
{
if(begin >= end){
return;
}
WordItem pvt = uniqueWords[begin];
int i = begin;
int j = end;
while(i < j){
while(i < j && uniqueWords[j].count < pvt.count){
j --;
}
if(i < j){
uniqueWords[i] = uniqueWords[j];
}
while(i < j && uniqueWords[i].count >= pvt.count){
i ++;
}
if(i < j){
uniqueWords[j] = uniqueWords[i];
}
}
uniqueWords[i] = pvt;
qSort(uniqueWords, begin, i - 1);
qSort(uniqueWords, i + 1, end);
}
void arraySort(WordItem uniqueWords[], int length)
{
qSort(uniqueWords, 0, length - 1);
}
void printNext10(WordItem uniqueWords[], int N, int total){
for(int i = 0; i < 10 && (i + N) < total; i ++){
std::cout << std::fixed;
std::cout << std::setprecision(4);
float f = 1.0 * uniqueWords[i + N].count / total;
std::cout << f << " - " << uniqueWords[i + N].word << std::endl;
}
}
int main(int argc, char *argv[])
{
std::string n(argv[1]);
std::string igwordsfilename(argv[3]);
std::string txtfilename(argv[2]);
std::string ignorewords[ARRAYSIZE_IGNOREWORDS];
int numigwords = getStopWords(igwordsfilename, ignorewords, ARRAYSIZE_IGNOREWORDS);
//std::cout << numigwords << std::endl;
int total, numuqwords;
numuqwords = 0;
WordItem *uniquewords = new WordItem[arraysize_uniquewords];
total = readText(txtfilename, &uniquewords, &numuqwords, ignorewords, numigwords);
arraySort(uniquewords, numuqwords);
std::cout << "Array doubled: " << dtimes << std::endl;
std::cout << "#" << std::endl;
std::cout << "Unique non-common words: " << numuqwords << std::endl;
std::cout << "#" << std::endl;
std::cout << "Total non-common words: " << total << std::endl;
std::cout << "#" << std::endl;
std::cout << "Probability of next 10 words from rank " << std::stoi(n) << std::endl;
std::cout << "---------------------------------------" << std::endl;
printNext10(uniquewords, std::stoi(n), total);
delete [] uniquewords;
uniquewords = NULL;
return 0;
}
| true |
aa33f75d7f274ae911b77b3660a66ea1fd7beb9a | C++ | yaelhava/MasterMind | /SmartGuesser.hpp | UTF-8 | 552 | 2.625 | 3 | [] | no_license | #include <string>
#include "Guesser.hpp"
#include "calculate.hpp"
#include <list>
using namespace std;
namespace bullpgia{
//this class represents a smart guesser that crack the code in 100 turns
class SmartGuesser : public bullpgia::Guesser{
private:
list<string> list; //will save all the options
string currGuess; //save the current guess
public:
string guess() override;
void learn(string s) override;
void startNewGame(uint length) override;
};
} | true |
d7ae08a323e4acb9b9a284cb27dbbf98b7b55306 | C++ | ankelesh/qTagger | /Tagger/Widgets/AuthorTabWidget.h | UTF-8 | 2,214 | 2.5625 | 3 | [] | no_license | #pragma once
#include "CharacterTabWidget.h"
#include "Widgets/TagHolder.h"
/*
This file contains specialized widget for managing author tags
AuthorTabWidget - QWidget child, contains QListWidget and lot of buttons
provides signals:
author_add(Tag) - new author was added to the list
author_erase() - request for deleting author
break_deduction(QString)- request for moving author back to filename
got_author(Tag) - new author was chosen by user
*/
class AuthorTabWidget : public QWidget
// This class is specialized for author operations
{
Q_OBJECT
private:
taglist* allauthors;
QStringList tags;
Tag lastAuthor; // Holds last author choose
QHBoxLayout * mainLayout; // Holds all elements
QVBoxLayout * listLayout; // Holds list widget and search string
QVBoxLayout * buttonHolder; // Holds all buttons
TagHolder * tagholder; // Holds author names
QPushButton * addButton;
QPushButton * eraseButton;
QPushButton *breakDeduce;
QPushButton * unknownButton;
QPushButton * deleteButton;
QPushButton * apply;
QCompleter * completer; // Provides completing to search widget
QLineEdit * search;
int & global_tag_counter; // Link to the global counter, which provides unique values for tag id's
public:
AuthorTabWidget(QWidget * root, QList <Tag> & auths, int & glcl, int fntszb = 20, int fntszn = 20);
//This function moves most popular tags to the top
void sort_and_refresh();
//getters and setters
QString getLAuthor() { return lastAuthor.tag; };
void setLAuthor(Tag & t) { lastAuthor = t; };
void setLAuthor(QString & qs);
int getAuthsCount() const { return allauthors->count(); }
QListWidgetItem * getCurrItem() { return tagholder->currentItem(); };
QList<Tag> getAuthors();
void prepare();
void applyCurrent();
public slots:
void add_tag_press(int id = 0);
void erase_press();
void break_de_press();
void list_clicked(QListWidgetItem * qlwi);
void unknown_press();
void search_completed();
void apply_press();
void leaveThis(int id, bool forward);
signals:
void author_add(Tag t);
void author_erase();
void break_deduction(QString qs);
void got_author(Tag t);
void goOutThis(int id, int page);
void taggingThisImageDone();
};
| true |
67fc5ea645c6030f9f9036a894b29834ea4ce89d | C++ | michael-ennis89/DataStructure-Implementations | /LinkedList Integers/LinkedList.hpp | UTF-8 | 469 | 2.96875 | 3 | [] | no_license | /*
File: LinkedList.hpp
Description: Definition for LinkedList Class.
Date: 2/12/2018
Author: Michael Ennis
*/
#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP
struct Node
{
int number; // Data element
Node *next; // Next node in LinkedList
};
class LinkedList
{
private:
Node *head;
int nodeCount = 0;
public:
LinkedList(){};
void addNode(int x);
void removeNode(int x);
void printList();
};
#endif // LINKEDLIST_HPP
| true |
21a37aafa50da5cff3fa034216faa55317d4eb9a | C++ | jacobmanning/sandbox | /learn/src/fluent_cpp/expressive_types/inheritance.cc | UTF-8 | 299 | 3 | 3 | [] | no_license | #include <iostream>
#include <named_type.hh>
#include <traits.hh>
using Length = util::named_type<double, struct LengthParameter, traits::Addable, traits::Printable>;
int main()
{
auto x = Length{3.4};
auto y = Length{5.6};
auto total = x + y;
std::cout << "Total = " << total << '\n';
}
| true |
f015e9ffbdb7ad5e1067392be6c1da525bf9eb28 | C++ | minh3td97/Minesweeper- | /src/Cell.cpp | UTF-8 | 1,335 | 3.484375 | 3 | [] | no_license | #include "Cell.h"
#include "Point.h"
#include <iostream>
using namespace std;
Cell::Cell(const int _value, const bool _isWritten, const Point _point, const bool _flag){
value = _value;
isWritten = _isWritten;
coord = _point;
}
Cell::Cell(const int _value, const bool _isWritten){
Point point;
Cell(_value, _isWritten, point, false);
}
Cell::Cell(){
Point point;
Cell(0, false, point, false);
}
void Cell::setCell(const int _value, const bool _isWritten, const Point _point, const bool _flag){
value = _value;
isWritten = _isWritten;
coord = _point;
flag = _flag;
}
void Cell::setValue(const int _value){
value = _value;
}
void Cell::setFlag(const bool _flag){
flag = _flag;
}
int Cell::getValue(){
return value;
}
void Cell::setWrite(const bool _isWritten){
isWritten = _isWritten;
}
bool Cell::wrote(){
return isWritten;
}
void Cell::setCoord(const int x, const int y){
coord.setPoint(x, y);
}
Point Cell::getPosition(){
return coord;
}
bool Cell::isFlag(){
return flag;
}
void Cell::printPosition(){
cout << coord.getX() << " " << coord.getY() << endl;
}
| true |
d9aea2d8cf9fbf82db8ad8f7c1fab6c166ff19db | C++ | hjeldin/dojo | /include/dojo/PolyTextArea.h | UTF-8 | 2,458 | 2.6875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "dojo_common_header.h"
#include "Renderable.h"
namespace Dojo
{
class Font;
class Tessellation;
class PolyTextArea : public Renderable
{
public:
enum RenderingType
{
RT_OUTLINE,
RT_SURFACE,
RT_EXTRUDED
};
///creates a new PolyTextArea object at position, using "font", centered or not around the center, using rendering options RT
PolyTextArea( Object* parent, const Vector& position, Font* font, bool centered, RenderingType rt );
virtual ~PolyTextArea();
///sets the extrusion parameters, changes taking effect once per frame
/**to disable beveled extrusion, pass 0 to both bevelDepth and inflateRadius
\param depth the depth of the extrusion as a fraction of the font height
\param bevelDepth the depth of the bevel as a fraction of the font height
\param inflateRadius the radius of the bevel's inflation as a fraction of the font height
*/
void setExtrusionParameters( float depth, float bevelDepth=0, float inflateRadius=0 )
{
DEBUG_ASSERT( depth > 0, "extrusion depth must be a positive number" );
DEBUG_ASSERT( bevelDepth >= 0 && bevelDepth < depth*0.5, "the depth of the bevel must not exceed half of the total depth" );
mDepth = depth;
mBevelDepth = bevelDepth;
mInflateRadius = inflateRadius;
}
///sets additional interline height
void setInterline( float interline )
{
mInterline = interline;
}
///adds some text to this poly area
void addText( const String& str )
{
mContent += str;
mDirty = true;
}
///replaces the poly area content with this text
void setText( const String& str )
{
mContent = str;
mDirty = true;
}
void clear()
{
mContent = String::EMPTY;
mDirty = true;
}
///gets the current interline
float getInterline()
{
return mInterline;
}
virtual void onAction( float dt )
{
if( mDirty )
_prepare();
Renderable::onAction(dt);
}
protected:
String mContent;
bool mCentered;
Mesh* mMesh;
Font* pFont;
RenderingType mRendering;
float mDepth, mBevelDepth, mInflateRadius;
float mSpaceWidth, mInterline;
bool mDirty;
int mPrevLayerIdx;
void _centerLine( int rowStartIdx, float rowWidth );
void _prepare();
void _tesselateExtrusionStrip( Tessellation* t, int layerAbaseIdx, int layerBbaseIdx );
void _addExtrusionLayer( Tessellation* t, const Vector& origin, float inflate, const Vector* forcedNormal = NULL );
private:
};
}
| true |
c1ac75f379ad6f9e8e51728b3621275d92eeef33 | C++ | mcolula/CaribbeanOnlineJudge-Solutions | /frankzappa-p1094-Accepted-s800741.cpp | UTF-8 | 1,303 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <utility>
#include <cstdio>
#include <map>
using namespace std;
typedef struct {
int * id;
int * sz;
} UnionFind;
int create(UnionFind * u, int n) {
u->id = new int[n];
u->sz = new int[n];
for(int i = 0; i < n; i++) {
u->sz[i] = 1;
u->id[i] = i;
}
}
int find(UnionFind * u, int p) {
int n = p;
while(n != u->id[n])
n = u->id[n];
return n;
}
int connect(UnionFind * u, int p, int q) {
int rootQ = find(u, q);
int rootP = find(u, p);
if (rootP == rootQ) return u->sz[rootP];
if (u->sz[rootP] < u->sz[rootQ]) {
u->id[rootP] = rootQ;
u->sz[rootQ] += u->sz[rootP];
return u->sz[rootQ];
}
else {
u->id[rootQ] = rootP;
u->sz[rootP] += u->sz[rootQ];
return u->sz[rootP];
}
}
int main() {
int t, n;
int x, y;
char a[40];
char b[40];
UnionFind net;
map <string, int> people;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
create(&net, 2 * n);
while (n--) {
scanf("%s %s", a, b);
if (people.count(a) == 0)
people[a] = people.size() - 1;
if (people.count(b) == 0)
people[b] = people.size() - 1;
x = people[a];
y = people[b];
printf("%d\n", connect(&net, x, y));
}
people.clear();
}
return 0;
}
| true |
b9ccd95a8b3fe50463c1aa86e0be168214df3275 | C++ | GCourtney27/Retina-Engine | /Engine/Graphics/IndexBuffer.h | UTF-8 | 1,207 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef IndicesBuffer_h__
#define IndicesBuffer_h__
#include <d3d11.h>
#include <wrl/client.h>
#include <vector>
class IndexBuffer
{
private:
IndexBuffer(const IndexBuffer& rhs);
private:
Microsoft::WRL::ComPtr<ID3D11Buffer> buffer;
UINT indexCount = 0;
public:
IndexBuffer() {}
ID3D11Buffer* Get()const
{
return buffer.Get();
}
ID3D11Buffer* const* GetAddressOf()const
{
return buffer.GetAddressOf();
}
UINT IndexCount() const
{
return this->indexCount;
}
HRESULT Initialize(ID3D11Device *device, DWORD * data, UINT indexCount)
{
if (buffer.Get() != nullptr)
buffer.Reset();
this->indexCount = indexCount;
//Load Index Data
D3D11_BUFFER_DESC indexBufferDesc;
ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc));
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(DWORD) * indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA indexBufferData;
indexBufferData.pSysMem = data;
HRESULT hr = device->CreateBuffer(&indexBufferDesc, &indexBufferData, buffer.GetAddressOf());
return hr;
}
};
#endif // IndicesBuffer_h__ | true |