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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
905a072fc8f9ecbee0ada3d63061787b81d0c933 | C++ | Yura52/teaching | /2019_hse_cpp_seminars/01_input_output_variables_if_loops_switch/08_if_else_switch.cpp | UTF-8 | 599 | 3.40625 | 3 | [] | no_license | #include <cstdint>
#include <iostream>
using i32 = int32_t;
int main() {
i32 a = 0;
std::cout << "enter a:\n";
std::cin >> a;
if (a > 1) {
std::cout << "a is greater than 1\n";
} else {
std::cout << "a is less or equal than 1\n";
}
switch (a) {
case 0: {
std::cout << "a equals 0\n";
break;
}
case 1: {
std::cout << "a equals 1\n";
break;
}
default: {
std::cout << "a is not equal to 0 nor 1\n";
break;
}
}
return 0;
}
| true |
f881d8e2ef6c3b3f3cdfbc1240ffd12f85cc3308 | C++ | charles-pku-2013/CodeRes_Cpp | /Templates/Example_Code/examples/basics/stack5assign.hpp | UTF-8 | 1,037 | 3.15625 | 3 | [] | no_license | /* The following code example is taken from the book
* "C++ Templates - The Complete Guide"
* by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002
*
* (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
template <typename T>
template <typename T2> //!! 多模板定义,模板类赋值,模板类的成员函数是另一个模板
Stack<T>& Stack<T>::operator= (Stack<T2> const& op2)
{
if ((void*)this == (void*)&op2) { // assignment to itself?
return *this;
}
Stack<T2> tmp(op2); // create a copy of the assigned stack
elems.clear(); // remove existing elements
while (!tmp.empty()) { // copy all elements
elems.push_front(tmp.top());
tmp.pop();
}
return *this;
}
| true |
d1a150208171eb5e505e13fd5b9666d3c6514b72 | C++ | hatigo/coleta-de-dados-HX711-e-armazenamento-em-SDcard | /coleta_de_dados_HX711_e_armazenamento_em_SDcard.ino | UTF-8 | 3,070 | 2.828125 | 3 | [] | no_license |
#include "FS.h"
#include "SD.h"
#include <SPI.h>
// --- Mapeamento de Hardware ---
#define ADDO 7 //Data Out
#define ADSK 6 //SCK
#define SD_CS 5
// --- Protótipo das Funções Auxiliares ---
unsigned long ReadCount();
// --- Variáveis Globais ---
unsigned long convert;
String dataMessage;
// --- Configurações Iniciais ---
void setup()
{
pinMode(ADDO, INPUT_PULLUP); //entrada para receber os dados
pinMode(ADSK, OUTPUT); //saída para SCK
Serial.begin(115200);
// Initialize SD card
SD.begin(SD_CS);
if(!SD.begin(SD_CS)) {
Serial.println("Card Mount Failed");
return;
}
uint8_t cardType = SD.cardType();
if(cardType == CARD_NONE) {
Serial.println("No SD card attached");
return;
}
Serial.println("Initializing SD card...");
if (!SD.begin(SD_CS)) {
Serial.println("ERROR - SD card initialization failed!");
return; // init failed
}
File file = SD.open("/data.txt");
if(!file) {
Serial.println("File doens't exist");
Serial.println("Creating file...");
writeFile(SD, "/data.txt", "Dados do Teste Estático \r\n");
}
else {
Serial.println("File already exists");
}
file.close();
} //end setup
// --- Loop Infinito ---
void loop()
{
convert = ReadCount();
logSDCard();
delay(100); //dúvida sobre o tempo de delay
} //end loop
// --- Funções ---
unsigned long ReadCount()
{
unsigned long Count = 0;
unsigned char i;
digitalWrite(ADSK, LOW);
while(digitalRead(ADDO));
for(i=0;i<24;i++)
{
digitalWrite(ADSK, HIGH);
Count = Count << 1;
digitalWrite(ADSK, LOW);
if(digitalRead(ADDO)) Count++;
} //end for
digitalWrite(ADSK, HIGH);
Count = Count^0x800000;
digitalWrite(ADSK, LOW);
return(Count);
} //end ReadCount
// Write the sensor readings on the SD card
void logSDCard() {
dataMessage = " -> " + String(convert) + "\n";
Serial.print("Save data: ");
Serial.println(dataMessage);
appendFile(SD, "/data.txt", dataMessage.c_str());
}
// Write to the SD card (DON'T MODIFY THIS FUNCTION)
void writeFile(fs::FS &fs, const char * path, const char * message) {
Serial.printf("Writing file: %s\n", path);
File file = fs.open(path, FILE_WRITE);
if(!file) {
Serial.println("Failed to open file for writing");
return;
}
if(file.print(message)) {
Serial.println("File written");
} else {
Serial.println("Write failed");
}
file.close();
}
// Append data to the SD card (DON'T MODIFY THIS FUNCTION)
void appendFile(fs::FS &fs, const char * path, const char * message) {
Serial.printf("Appending to file: %s\n", path);
File file = fs.open(path, FILE_APPEND);
if(!file) {
Serial.println("Failed to open file for appending");
return;
}
if(file.print(message)) {
Serial.println("Message appended");
} else {
Serial.println("Append failed");
}
file.close();
}
| true |
39314f74d4a8ae98a34402b7eeed99dfec59c7b9 | C++ | SebiH/ART | /tools/ImageProcessing/src/processors/UndistortProcessor.cpp | UTF-8 | 1,824 | 2.578125 | 3 | [] | no_license | #include "UndistortProcessor.h"
using namespace ImageProcessing;
using json = nlohmann::json;
UndistortProcessor::UndistortProcessor(const json & config)
{
cv::FileStorage fs_intrinsic_l(config["intrinsic_left"], cv::FileStorage::READ);
cv::FileStorage fs_distcoeffs_l(config["distcoeffs_left"], cv::FileStorage::READ);
fs_intrinsic_l["standard_left_intrinsic"] >> intrinsic_left_;
fs_distcoeffs_l["standard_left_distcoeffs"] >> distcoeffs_left_;
cv::FileStorage fs_intrinsic_r(config["intrinsic_right"], cv::FileStorage::READ);
cv::FileStorage fs_distcoeffs_r(config["distcoeffs_right"], cv::FileStorage::READ);
fs_intrinsic_r["standard_right_intrinsic"] >> intrinsic_right_;
fs_distcoeffs_r["standard_right_distcoeffs"] >> distcoeffs_right_;
}
UndistortProcessor::~UndistortProcessor()
{
}
std::shared_ptr<const FrameData> UndistortProcessor::Process(const std::shared_ptr<const FrameData>& frame)
{
cv::Size mat_size(frame->size.width, frame->size.height);
Init(mat_size);
cv::Mat img_left(mat_size, frame->size.CvType(), frame->buffer_left.get());
cv::remap(img_left, img_left, map1_l_, map2_l_, cv::INTER_LINEAR);
cv::Mat img_right(mat_size, frame->size.CvType(), frame->buffer_right.get());
cv::remap(img_right, img_right, map1_r_, map2_r_, cv::INTER_LINEAR);
return frame;
}
json UndistortProcessor::GetProperties()
{
return json();
}
void UndistortProcessor::SetProperties(const json & config)
{
}
void UndistortProcessor::Init(const cv::Size &framesize)
{
if (framesize != initialized_size)
{
cv::initUndistortRectifyMap(intrinsic_left_, distcoeffs_left_, cv::Mat(), cv::Mat(), framesize, CV_32FC1, map1_l_, map2_l_);
cv::initUndistortRectifyMap(intrinsic_right_, distcoeffs_right_, cv::Mat(), cv::Mat(), framesize, CV_32FC1, map1_r_, map2_r_);
initialized_size = framesize;
}
}
| true |
a2eeb59efe13424b4b04102e9eda8aafa5f67053 | C++ | Ashish-kumar7/geeks-for-geeks-solutions | /Greedy Algorithm/New Text Document.txt | UTF-8 | 1,294 | 2.625 | 3 | [] | no_license | #include <iostream>
#include<bits/stdc++.h>
using namespace std;
int making(int pages[],int n,int capacity)
{
unordered_set<int>s;
unordered_map<int,int>map1;
int pagefault=0;
for(int i=0;i<n;i++)
{
if(s.size()<capacity)
{
if(s.find(pages[i])==s.end())
{
s.insert(pages[i]);
pagefault++;
}
map1[pages[i]]=i;
}
else
{
if(s.find(pages[i])==s.end())
{
int x=INT_MAX;
int val;
for(auto it=s.begin();it!=s.end();it++)
{
if(map1[*it]<x)
{
x=map1[*it];
val=*it;
}
}
s.erase(val);
s.insert(pages[i]);
pagefault++;
}
map1[pages[i]]=i;
}
}
return pagefault;
}
int main() {
//code
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int A[n];
for(int i=0;i<n;i++)
{
cin>>A[i];
}
int jj;
cin>>jj;
cout<< making(A,n,jj);
cout<<endl;
}
return 0;
} | true |
1b9f5e7cf58fee9744ab08736821b470427443df | C++ | miviwi/Hamil | /Hamil/src/gx/commandbuffer.cpp | UTF-8 | 13,683 | 2.609375 | 3 | [] | no_license | #include <gx/commandbuffer.h>
#include <gx/renderpass.h>
#include <gx/program.h>
#include <gx/vertex.h>
#include <cassert>
namespace gx {
CommandBuffer::CommandBuffer(size_t initial_alloc) :
m_pool(nullptr),
m_memory(nullptr),
m_program(nullptr),
m_renderpass(nullptr),
m_last_draw(NonIndexedDraw)
{
m_commands.reserve(initial_alloc);
}
CommandBuffer CommandBuffer::begin(size_t initial_alloc)
{
return CommandBuffer(initial_alloc);
}
CommandBuffer& CommandBuffer::renderpass(ResourceId pass)
{
return appendCommand(OpBeginRenderPass, pass);
}
CommandBuffer& CommandBuffer::subpass(uint id)
{
if(id & ~OpDataMask) throw SubpassIdTooLargeError();
return appendCommand(OpBeginSubpass, id);
}
CommandBuffer& CommandBuffer::program(ResourceId prog)
{
checkResourceId(prog);
return appendCommand(OpUseProgram, prog);
}
CommandBuffer& CommandBuffer::draw(Primitive p, ResourceId vertex_array, size_t num_verts)
{
return appendCommand(make_draw(p, vertex_array, num_verts));
}
CommandBuffer& CommandBuffer::drawIndexed(Primitive p, ResourceId indexed_vertex_array, size_t num_inds)
{
return appendCommand(make_draw_indexed(p, indexed_vertex_array, num_inds));
}
CommandBuffer & CommandBuffer::drawBaseVertex(Primitive p,
ResourceId indexed_vertex_array, size_t num, u32 base, u32 offset)
{
return appendCommand(make_draw_base_vertex(p, indexed_vertex_array, num))
.appendExtraData(base)
.appendExtraData(offset);
}
CommandBuffer& CommandBuffer::bufferUpload(ResourceId buf, MemoryPool::Handle h, size_t sz)
{
checkResourceId(buf);
return appendCommand(make_buffer_upload(buf, h, sz));
}
CommandBuffer& CommandBuffer::uniformInt(uint location, int value)
{
if(location == ~0u) return *this; // The variable was optimized out
union {
int i;
u32 data;
} extra;
extra.i = value;
return appendCommand(OpPushUniform, make_push_uniform(OpDataUniformInt, location))
.appendExtraData(extra.data);
}
CommandBuffer& CommandBuffer::uniformFloat(uint location, float value)
{
if(location == ~0u) return *this; // The variable was optimized out
union {
float f;
u32 data;
} extra;
extra.f = value;
return appendCommand(OpPushUniform, make_push_uniform(OpDataUniformFloat, location))
.appendExtraData(extra.data);
}
CommandBuffer& CommandBuffer::uniformSampler(uint location, uint sampler)
{
if(location == ~0u) return *this; // The variable was optimized out
return appendCommand(OpPushUniform, make_push_uniform(OpDataUniformSampler, location))
.appendExtraData((u32)sampler);
}
CommandBuffer& CommandBuffer::uniformVector4(uint location, MemoryPool::Handle h)
{
if(location == ~0u) return *this; // The variable was optimized out
return appendCommand(OpPushUniform, make_push_uniform(OpDataUniformVector4, location))
.appendExtraData(h);
}
CommandBuffer& CommandBuffer::uniformMatrix4x4(uint location, MemoryPool::Handle h)
{
if(location == ~0u) return *this; // The variable was optimized out
return appendCommand(OpPushUniform, make_push_uniform(OpDataUniformMatrix4x4, location))
.appendExtraData(h);
}
CommandBuffer& CommandBuffer::fenceSync(ResourceId fence)
{
if(fence & ~OpDataFenceOpDataMask) throw ResourceIdTooLargeError();
u32 data = (OpDataFenceSync<<OpDataFenceOpShift) | fence;
return appendCommand(OpFence, data);
}
CommandBuffer& CommandBuffer::fenceWait(ResourceId fence)
{
if(fence & ~OpDataFenceOpDataMask) throw ResourceIdTooLargeError();
u32 data = (OpDataFenceWait<<OpDataFenceOpShift) | fence;
return appendCommand(OpFence, data);
}
CommandBuffer& CommandBuffer::generateMipmaps(ResourceId texture)
{
checkResourceId(texture);
return appendCommand(OpGenerateMipmaps, texture);
}
CommandBuffer& CommandBuffer::end()
{
return appendCommand(OpEnd);
}
CommandBuffer& CommandBuffer::bindResourcePool(ResourcePool *pool)
{
m_pool = pool;
return *this;
}
CommandBuffer& CommandBuffer::bindMemoryPool(MemoryPool *pool)
{
m_memory = pool;
return *this;
}
CommandBuffer& CommandBuffer::activeRenderPass(ResourceId renderpass)
{
assertResourcePool();
m_renderpass = &m_pool->get<RenderPass>(renderpass);
return *this;
}
CommandBuffer& CommandBuffer::execute()
{
if(m_commands.empty()) return *this;
assert(m_commands.back() >> OpShift == OpEnd
&& "Attempted to execute() a CommandBuffer without a previous call to end() on it!\n"
"(Or commands were added after the end() call)");
assertResourcePool();
u32 *pc = m_commands.data();
while(auto next_pc = dispatch(pc)) {
pc = next_pc;
}
return *this;
}
CommandBuffer& CommandBuffer::reset()
{
m_commands.clear();
m_program = nullptr;
return *this;
}
CommandBuffer& CommandBuffer::appendCommand(Command opcode, u32 data)
{
assert((data & ~OpDataMask) == 0 && "OpData has overflown into the opcode!");
assert(opcode < NumCommands && "The opcode is invalid!");
u32 command = (opcode << OpShift) | data;
m_commands.push_back(command);
return *this;
}
CommandBuffer& CommandBuffer::appendExtraData(u32 data)
{
m_commands.push_back(data);
return *this;
}
CommandBuffer& CommandBuffer::appendCommand(CommandWithExtra c)
{
return appendExtraData(c.command)
.appendExtraData(c.extra);
}
CommandBuffer::u32 *CommandBuffer::dispatch(u32 *op)
{
auto fetch_extra = [&]() -> CommandWithExtra
{
CommandWithExtra op_extra;
op_extra.command = *op;
op++;
op_extra.extra = *op;
return op_extra;
};
u32 command = *op;
u32 opcode = op_opcode(command);
u32 data = op_data(command);
switch(opcode) {
case Nop: break;
case OpBeginRenderPass:
m_renderpass = &m_pool->get<RenderPass>(data)
.begin(*m_pool);
break;
case OpBeginSubpass:
assertRenderPass();
m_renderpass->beginSubpass(*m_pool, data);
break;
case OpUseProgram:
m_program = &m_pool->get<Program>(data)
.use();
break;
case OpDraw:
case OpDrawIndexed:
assertProgram();
drawCommand(fetch_extra());
break;
case OpDrawBaseVertex: {
assertProgram();
auto extra = fetch_extra();
op++;
u32 base = *op;
op++;
u32 offset = *op;
drawCommand(extra, base, offset);
break;
}
case OpBufferUpload:
assertMemoryPool();
uploadCommand(fetch_extra());
break;
case OpPushUniform:
assertProgram();
pushUniformCommand(fetch_extra());
break;
case OpFence:
fenceCommand(data);
break;
case OpGenerateMipmaps:
m_pool->getTexture(data).get()
.generateMipmaps();
break;
case OpEnd:
endIndexedArray();
// TODO: maybe flush fences here instead of in gx::Fence::sync()?
//glFlush();
return nullptr;
default: assert(0); // unreachable
}
return op + 1;
}
void CommandBuffer::drawCommand(CommandWithExtra op, u32 base, u32 offset)
{
auto primitive = draw_primitive(op);
auto array = draw_array(op);
auto num = draw_num(op);
if(m_last_draw != array) endIndexedArray();
switch(op_opcode(op.command)) {
case OpDraw:
Pipeline::current()
.draw(offset, num);
//m_program->draw(primitive, m_pool->get<VertexArray>(array), offset, num);
return;
case OpDrawIndexed:
Pipeline::current()
.draw(offset, num);
//m_program->draw(primitive, m_pool->get<IndexedVertexArray>(array), offset, num);
m_last_draw = array;
break;
case OpDrawBaseVertex:
Pipeline::current()
.drawBaseVertex(base, offset, num);
//m_program->drawBaseVertex(primitive, m_pool->get<IndexedVertexArray>(array), base, offset, num);
m_last_draw = array;
break;
default: assert(0); // unreachable
}
}
void CommandBuffer::uploadCommand(CommandWithExtra op)
{
auto buffer = xfer_buffer(op);
auto handle = xfer_handle(op);
auto size = xfer_size(op);
auto ptr = m_memory->ptr(handle);
m_pool->getBuffer(buffer).get().upload(ptr, 0, sizeof(byte), size);
}
void CommandBuffer::pushUniformCommand(CommandWithExtra op)
{
auto type = (op.command >> OpDataUniformTypeShift) & OpDataUniformTypeMask;
auto location = op.command & OpDataUniformLocationMask;
union {
u32 data;
int i;
float f;
MemoryPool::Handle h;
} extra;
extra.data = op.extra;
switch(type) {
case OpDataUniformInt: m_program->uniformInt(location, extra.i); break;
case OpDataUniformFloat: m_program->uniformFloat(location, extra.f); break;
case OpDataUniformSampler: m_program->uniformSampler(location, extra.data); break;
case OpDataUniformVector4: m_program->uniformVector4(location, memoryPoolRef<vec4>(extra.h)); break;
case OpDataUniformMatrix4x4: m_program->uniformMatrix4x4(location, memoryPoolRef<mat4>(extra.h)); break;
default: throw UniformTypeInvalidError();
}
}
void CommandBuffer::fenceCommand(u32 data)
{
u32 op = (data>>OpDataFenceOpShift) & OpDataFenceOpMask;
u32 fence_id = data & OpDataFenceOpDataMask;
auto& fence = m_pool->get<gx::Fence>(fence_id);
switch(op) {
case OpDataFenceSync: fence.sync(); break;
case OpDataFenceWait: fence.wait(); break;
default: throw FenceOpInvalidError();
}
}
void CommandBuffer::endIndexedArray()
{
if(m_last_draw == NonIndexedDraw) return;
m_pool->get<IndexedVertexArray>(m_last_draw).end();
m_last_draw = NonIndexedDraw;
}
void CommandBuffer::checkResourceId(ResourceId id)
{
if(id & ~OpDataMask) throw ResourceIdTooLargeError();
}
void CommandBuffer::checkNumVerts(size_t num)
{
if(num & ~OpExtraNumVertsMask) throw NumVertsTooLargeError();
}
void CommandBuffer::checkHandle(MemoryPool::Handle h)
{
if((h >> MemoryPool::AllocAlignShift) & ~OpExtraHandleMask) throw HandleOutOfRangeError();
if(h & MemoryPool::AllocAlignMask) throw HandleUnalignedError();
}
void CommandBuffer::checkXferSize(size_t sz)
{
if(sz & ~OpExtraXferSizeMask) throw XferSizeTooLargeError();
}
void CommandBuffer::checkUniformLocation(uint location)
{
if(location & ~OpDataUniformLocationMask) throw UniformLocationTooLargeError();
}
void CommandBuffer::assertResourcePool()
{
assert(m_pool && "This method requires a bound ResourcePool!");
}
void CommandBuffer::assertProgram()
{
assert(m_program && "Command requires a bound Program!");
}
void CommandBuffer::assertMemoryPool()
{
assert(m_memory && "Command requires a bound MemoryPool!");
}
void CommandBuffer::assertRenderPass()
{
assert(m_renderpass && "Command requires an active RenderPass!");
}
CommandBuffer::Command CommandBuffer::op_opcode(u32 op)
{
auto opcode = op >> OpShift;
return (Command)(opcode & OpMask);
}
CommandBuffer::u32 CommandBuffer::op_data(u32 op)
{
return op & OpDataMask;
}
static constexpr Primitive p_primitive_lut[] ={
Primitive::Points,
Primitive::Lines, Primitive::LineLoop, Primitive::LineStrip,
Primitive::Triangles, Primitive::TriangleFan, Primitive::TriangleStrip,
(Primitive)~0u, // Sentinel
};
Primitive CommandBuffer::draw_primitive(CommandWithExtra op)
{
auto primitive = (op.extra >> OpExtraPrimitiveShift) & OpExtraPrimitiveMask;
return p_primitive_lut[primitive];
}
CommandBuffer::ResourceId CommandBuffer::draw_array(CommandWithExtra op)
{
return op_data(op.command);
}
size_t CommandBuffer::draw_num(CommandWithExtra op)
{
return (size_t)(op.extra & OpExtraNumVertsMask);
}
CommandBuffer::ResourceId CommandBuffer::xfer_buffer(CommandWithExtra op)
{
return op_data(op.command);
}
MemoryPool::Handle CommandBuffer::xfer_handle(CommandWithExtra op)
{
return (op_data(op.extra) & OpExtraHandleMask) << MemoryPool::AllocAlignShift;
}
size_t CommandBuffer::xfer_size(CommandWithExtra op)
{
return (size_t)((op_data(op.extra) >> OpExtraXferSizeShift) & OpExtraXferSizeMask);
}
CommandBuffer::CommandWithExtra CommandBuffer::make_draw(Primitive p,
ResourceId array, size_t num_verts)
{
checkResourceId(array);
// See p_primitive_lut above
u32 primitive = 0;
switch(p) {
case Primitive::Points: primitive = 0; break;
case Primitive::Lines: primitive = 1; break;
case Primitive::LineLoop: primitive = 2; break;
case Primitive::LineStrip: primitive = 3; break;
case Primitive::Triangles: primitive = 4; break;
case Primitive::TriangleFan: primitive = 5; break;
case Primitive::TriangleStrip: primitive = 6; break;
default: primitive = 7; break; // Assign to sentinel
}
checkNumVerts(num_verts);
auto num = (u32)(num_verts & OpExtraNumVertsMask);
checkResourceId(array);
CommandWithExtra c;
c.command = (OpDraw << OpShift) | array;
c.extra = (primitive << OpExtraPrimitiveShift) | num;
return c;
}
CommandBuffer::CommandWithExtra CommandBuffer::make_draw_indexed(Primitive p,
ResourceId array, size_t num_inds)
{
auto c = make_draw(p, array, num_inds);
c.command &= ~(OpMask << OpShift);
c.command |= OpDrawIndexed << OpShift;
return c;
}
CommandBuffer::CommandWithExtra CommandBuffer::make_draw_base_vertex(Primitive p,
ResourceId array, size_t num_inds)
{
auto c = make_draw(p, array, num_inds);
c.command &= ~(OpMask << OpShift);
c.command |= OpDrawBaseVertex << OpShift;
return c;
}
CommandBuffer::CommandWithExtra CommandBuffer::make_buffer_upload(ResourceId buf,
MemoryPool::Handle h, size_t sz)
{
checkHandle(h);
checkXferSize(sz);
auto handle = (u32)(h >> MemoryPool::AllocAlignShift);
auto size = (u32)(sz & OpExtraXferSizeMask);
CommandWithExtra c;
c.command = (OpBufferUpload << OpShift) | buf;
c.extra = (size << OpExtraXferSizeShift) | handle;
return c;
}
CommandBuffer::u32 CommandBuffer::make_push_uniform(u32 type, uint location)
{
checkUniformLocation(location);
return (type << OpDataUniformTypeShift) | location;
}
}
| true |
c7c57fe65670b4a62dfbf768eb79f9ce53384010 | C++ | DaeYoungKim/Recogbot | /src/utils/DB.cpp | UTF-8 | 2,552 | 2.59375 | 3 | [] | no_license | #include "utils/DB.h"
#include <cstdio>
#include <direct.h>
#include <assert.h>
namespace Recogbot {
DB::DB(char *folderName) {
_cnt=0;
_folderName=folderName;
}
void DB::createFolder(const char* name){
sprintf(_text,"../db/%s",name);
mkdir("../db");
mkdir(_text);
}
void DB::locateFolder(const char* name){
_folderName=name;
}
void DB::saveImg(IplImage* img, const char* tag){
assert(strcmp(_folderName.c_str(),"none")!=0);
assert(img!=0);
createFolder(_folderName.c_str());
sprintf(_text,"../db/%s/%05d_%s.jpg",_folderName.c_str(),_cnt, tag);
cvSaveImage(_text,img);
}
void DB::saveImgWithCnt(IplImage* img, const char* tag, unsigned cnt){
assert(img!=0);
createFolder(_folderName.c_str());
sprintf(_text,"../db/%s/%05d_%s.jpg",_folderName.c_str(),_cnt, tag);
cvSaveImage(_text,img);
_cnt = cnt;
}
IplImage* DB::readImg(const char* tag){
sprintf(_text,"../db/%s/%05d_%s.jpg",_folderName.c_str(),_cnt, tag);
return cvLoadImage(_text);
}
IplImage* DB::readGrayImg(const char* tag){
sprintf(_text,"../db/%s/%05d_%s.jpg",_folderName.c_str(),_cnt, tag);
return cvLoadImage(_text,0);
}
IplImage* DB::readImgwithCnt(const char* tag, unsigned cnt){
sprintf(_text, "../db/%s/%05d_%s.jpg", _folderName.c_str(), cnt, tag);
return cvLoadImage(_text);
}
void DB::saveArray(void *arrPtr, const char* tag, size_t nBytes, size_t nElements) {
sprintf(_text, "../db/%s/%05d_%s.arr", _folderName.c_str(), _cnt, tag );
FILE* pf = fopen(_text,"wb");
fwrite(arrPtr, nBytes, nElements, pf);
fclose(pf);
}
void DB::saveArray(void *arrPtr, const char* tag, size_t nBytes, size_t nElements, unsigned cnt) {
sprintf(_text, "../db/%s/%05d_%s.arr", _folderName.c_str(), cnt, tag);
FILE* pf = fopen(_text, "wb");
fwrite(arrPtr, nBytes, nElements, pf);
fclose(pf);
}
void DB::readArray(void *arrPtr, const char* tag, size_t nBytes, size_t nElements) {
sprintf(_text, "../db/%s/%05d_%s.arr", _folderName.c_str(), _cnt, tag);
FILE* pf = fopen(_text, "rb");
fread(arrPtr, nBytes, nElements, pf);
fclose(pf);
}
void DB::readArray(void *arrPtr, const char* tag, size_t nBytes, size_t nElements, unsigned cnt) {
sprintf(_text, "../db/%s/%05d_%s.arr", _folderName.c_str(), cnt, tag);
FILE* pf = fopen(_text, "rb");
fread(arrPtr, nBytes, nElements, pf);
fclose(pf);
}
void DB::setCnt(unsigned val) { _cnt = val; }
void DB::initCnt() { _cnt = 0; }
unsigned DB::getCnt() { return _cnt; }
void DB::increaseCnt() { ++_cnt; }
void DB::decreaseCnt() { --_cnt; }
} | true |
bdf462ce8d16ba6e2f411bd608f90f8737ba6ac9 | C++ | marcinmajkowski/SPOJ | /TRN.cpp | UTF-8 | 728 | 3.0625 | 3 | [] | no_license | #ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m = 0, n = 0;
int *matrix;
scanf("%d %d", &m, &n);
matrix = (int*) calloc(m*n, sizeof(int));
for (int i=0; i<m*n; ++i)
{
scanf("%d", &matrix[i]);
}
for (int i=0; i<n; ++i)
{
for (int k=0; k<m; ++k)
{
printf("%d ", matrix[i+k*n]);
}
printf("\n");
}
free(matrix);
return 0;
}
//int main()
//{
// int m = 0, n = 0;
// int matrix[4000];
//
// scanf("%d %d", &m, &n);
//
// for (int i=0; i<m*n; ++i)
// {
// scanf("%d", &matrix[i]);
// }
//
// for (int i=0; i<n; ++i)
// {
// for (int k=0; k<m; ++k)
// {
// printf("%d ", matrix[i+k*n]);
// }
// printf("\n");
// }
// return 0;
//} | true |
6ed11e36b8cd80f639ef73b140f658243ec9e08b | C++ | henrybzhang/usaco | /frac1.cpp | UTF-8 | 1,666 | 3.34375 | 3 | [] | no_license | /*
ID: LGD84711
LANG: C++
TASK: frac1
*/
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
ifstream fin ("frac1.in");
ofstream fout ("frac1.out");
int N, counter;
int gcd(int num, int den)
{
int common_factor = den % num;
if(num == 1) return num;
if(common_factor == 0) return den;
if(common_factor == 1) return num;
for(int x=2; x<common_factor; x++){
if(common_factor % x == 0 && num % x == 0){
return den;
}
}
if(num % common_factor == 0) return den;
else return num;
}
struct fractions
{
double value;
int num, den;
};
fractions frac_array[100000];
bool sort_fractions(const fractions &f1, const fractions &f2)
{
return f1.value < f2.value;
}
int main()
{
fin >> N;
frac_array[0].value = 0;
frac_array[0].num = 0;
frac_array[0].den = 1;
counter = 1;
for(int x=1; x<=N; x++){
for(int y=1; y<x; y++){
//cout << y << " " << x << " " << gcd(y, x) << endl;
if(gcd(y, x) == y){
frac_array[counter].value = (double) y / x;
frac_array[counter].den = x;
frac_array[counter].num = y;
cout << frac_array[counter].value << " " << frac_array[counter].num << "/" << frac_array[counter].den << endl;
counter++;
}
}
}
sort(frac_array, frac_array+counter, sort_fractions);
frac_array[counter].value = 1;
frac_array[counter].num = 1;
frac_array[counter].den = 1;
counter++;
for(int x=0; x<counter; x++){
fout << frac_array[x].num << "/" << frac_array[x].den << endl;
}
} | true |
52311849463d58bfb21fb63e9715138c3c3ec79c | C++ | yoanCesar78/qt | /controller.cpp | UTF-8 | 826 | 2.53125 | 3 | [] | no_license | #include "controller.hpp"
Controller::Controller(Client *c, MainWindow *w){ // connect différents listener
client = c;
main_window = w;
//connex entre vue et client
QObject::connect(main_window->getDisconnectBtn(), SIGNAL(clicked()), client,
SLOT(Disconnect()));
QObject::connect(main_window->getSendBtn(), SIGNAL(clicked()), this,
SLOT(SendMessage()));
QObject::connect(client, SIGNAL(newMessage(QString)), main_window,
SLOT(UpdateChat(QString)));
}
Controller::~Controller(){ //
}
void Controller::SendMessage(){ // à partir du controller, récupérer le msg envoyé par l'user
client->SendMessage(main_window->getUserInput()->text()); //prendre le user
main_window->getUserInput()->setText(""); // j'efface l'entrée pour que l'user puisse avoir une zone de saisie nettoyée
}
| true |
5489b19eac496cec2085ca2bb9dadce70f6bb692 | C++ | devedu-AI/Competitive-Coding-for-Interviews | /Strings/LongestCommonPrefix.cpp | UTF-8 | 742 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
string longestCommonPrefix(string ar[], int n)
{
if (n == 0)
return "-1";
if (n == 1)
return ar[0];
sort(ar, ar + n);
int en = min(ar[0].size(), ar[n - 1].size());
string first = ar[0];
string last = ar[n - 1];
int i = 0;
while (i < en && first[i] == last[i])
i++;
string pre = first.substr(0, i);
if(pre == "")
pre = "-1";
return pre;
}
int main()
{
//code
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
string arr[n];
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
string s = longestCommonPrefix(arr, n);
cout << s << endl;
}
return 0;
} | true |
dc46d9bf9980db097b7f81a38a3717452598ef84 | C++ | hrntsm/study-language | /CPP/HelloCpp2/chapter_1-2/ConsoleIO1.cpp | UTF-8 | 156 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(){
cout << 10 << ":" << 1.15 << endl;
cout << "Kitty" << "on" << "your" << "lap";
return 0;
} | true |
f4a8fa23c249223df93b0cab6fbc1a49649c681e | C++ | HuxyUK/NetLibrary | /Headers/NetLib/LobbyMember.h | UTF-8 | 502 | 2.609375 | 3 | [] | no_license | #ifndef NETLIB_LOBBYMEMBER_H
#define NETLIB_LOBBYMEMBER_H
#include <string>
namespace netlib
{
struct LobbyMember
{
friend class ClientConnection;
float ping = 0;
bool ready = false;
std::string name = "";
unsigned int uid = 0;
unsigned int lobbySlot = 0;
private:
static bool Sort(const LobbyMember& a,const LobbyMember& b)
{
return a.lobbySlot < b.lobbySlot;
}
};
}
#endif //NETLIB_LOBBYMEMBER_H
| true |
8c020297e35d22563ea6711d23760cc934cbfccd | C++ | REDasmOrg/REDasm-Loaders | /dex/demangler.cpp | UTF-8 | 1,678 | 3 | 3 | [
"MIT"
] | permissive | #include "demangler.h"
#include <string>
#include <regex>
std::string Demangler::getPackageName(const std::string& s)
{
std::regex rgx("L(.+)\\/.+;");
std::smatch m;
if(!std::regex_match(s, m, rgx)) return s;
std::string sm = m[1];
std::replace(sm.begin(), sm.end(), '/', '.');
return sm;
}
std::string Demangler::getObjectName(const std::string& s)
{
std::regex rgx("L(.+\\/)+(.+);");
std::smatch m;
return std::regex_match(s, m, rgx) ? m[2] : s;
}
std::string Demangler::getFullName(const std::string& s)
{
std::regex rgx("L(.+);");
std::smatch m;
if(!std::regex_match(s, m, rgx)) return s;
std::string sm = m[1];
std::replace(sm.begin(), sm.end(), '/', '.');
return sm;
}
std::string Demangler::getSignature(const std::string& s, bool wrap)
{
std::regex rgx("(L.+?;)");
std::sregex_iterator it(s.begin(), s.end(), rgx);
std::string res;
for( ; it != std::sregex_iterator(); it++)
{
if(!res.empty()) res += ", ";
res += Demangler::getObjectName((*it)[1]);
}
if(wrap) res = "(" + res + ")";
return res;
}
std::string Demangler::getReturn(const std::string& s)
{
std::regex rgx("\\(.*\\)(.+)");
std::smatch m;
return std::regex_match(s, m, rgx) ? Demangler::getType(m[1]) : s;
}
std::string Demangler::getType(const std::string& s)
{
if(s == "V") return "void";
if(s == "Z") return "boolean";
if(s == "B") return "byte";
if(s == "S") return "short";
if(s == "C") return "char";
if(s == "I") return "int";
if(s == "J") return "long";
if(s == "F") return "float";
if(s == "D") return "double";
return s;
}
| true |
0c9ee7cebc106cd229fab2880b6e3beeba8d63c2 | C++ | anshuman725/Ds-Algo-Practice | /spiral-order-matrix-traversal.cpp | UTF-8 | 3,564 | 3.796875 | 4 | [] | no_license | /*
Problem: We have to print the given 2D matrix in the spiral order.
Spiral Order means that firstly, first row is printed, then last column is printed,
then last row is printed and then first column is printed,
then we will come inwards in the similar way.
*/
/*
https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/0/?track=ppc-matrix&batchId=221#
vector method
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c)
{
// code here
int rs=0;
int rend=matrix.size()-1;
int cs=0;
int cend=matrix[0].size()-1;
int d=0;
vector<int>ans;
while(rs<=rend && cs<=cend)
{
if(d==0)
{
for(int i=cs;i<=cend;i++)
{
ans.push_back(matrix[rs][i]);
}
rs++;
}
else if(d==1)
{
for(int i=rs;i<=rend;i++)
{
ans.push_back(matrix[i][cend]);
}
cend--;
}
else if(d==2)
{
for(int i=cend;i>=cs;i--)
{
ans.push_back(matrix[rend][i]);
}
rend--;
}
else if(d==3)
{
for(int i=rend;i>=rs;i--)
{
ans.push_back(matrix[i][cs]);
}
cs++;
}
d=(d+1)%4;
}
return ans;
}
};
// { Driver Code Starts.
int main() {
int t;
cin>>t;
while(t--)
{
int r,c;
cin>>r>>c;
vector<vector<int> > matrix(r);
for(int i=0; i<r; i++)
{
matrix[i].assign(c, 0);
for( int j=0; j<c; j++)
{
cin>>matrix[i][j];
}
}
Solution ob;
vector<int> result = ob.spirallyTraverse(matrix, r, c);
for (int i = 0; i < result.size(); ++i)
cout<<result[i]<<" ";
cout<<endl;
}
return 0;
} // } Driver Code Ends
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int a[n][m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
int row_start = 0, row_end = n - 1, col_start = 0, col_end = m - 1;
while (row_start <= row_end && col_start <= col_end)
{
//first row is printed
for (int col = col_start; col <= col_end; col++)
{
cout << a[row_start][col] << " ";
}
row_start++;
//last column is printed
for (int row = row_start; row <= row_end; row++)
{
cout << a[row][col_end]<<" ";
}
col_end--;
//last row is printed
for (int col = col_end; col >= col_start; col--)
{
cout << a[row_end][col] << " ";
}
row_end--;
//then first column is printed
for (int row = row_end; row >= row_start; row--)
{
cout << a[row][col_start] << " ";
}
col_start++;
}
return 0;
}
| true |
d8f6089b32496b566576dc2acd489b717aa14d18 | C++ | amit1078-en/Data_Structure_And_Algorithms | /GRAPHS/BIPIRATE_GRAPH.cpp | UTF-8 | 3,005 | 3.734375 | 4 | [] | no_license | /*
BIPIRATE GRAPH
Given an adjacency list of a graph adj of V no. of vertices having 0 based index. Check whether the graph is bipartite or not.
Example 1:
Input:
Output: 1
Explanation: The given graph can be colored
in two colors so, it is a bipartite graph.
Example 2:
Input:
Output: 0
Explanation: The given graph cannot be colored
in two colors such that color of adjacent
vertices differs.
Your Task:
You don't need to read or print anything. Your task is to complete the function isBipartite() which takes V denoting no. of vertices and adj denoting adjacency list of graph and returns a boolean value true if graph is bipartite otherwise returns false.
Expected Time Complexity: O(V)
Expected Space Complexity: O(V)
Constraints:
1 = V, E = 105
Company Tags
Topic Tags
Related Courses
Related Interview Experiences
*/
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
bool isBipartite(int V, vector<int>adj[])
{
bool visited[V];
int color[V];
memset(color,0,sizeof(color));
memset(visited,false,sizeof(visited));
for(int i = 0;i<V;i++)
{
if(!visited[i])
{
visited[i] = true;
color[i] = 1;
queue<int> Q;
Q.push(i);
while(!Q.empty())
{
int front = Q.front();
visited[front] = true;
Q.pop();
for(int k:adj[front])
{
if(!visited[k])
{
Q.push(k);
if(color[k]==0)
{
if(color[front]==1)
{
color[k] = 2;
}
else
{
color[k] = 1;
}
}
else
{
if(color[front]==color[k])
{
return false;
}
}
}
else
{
if(color[front]==color[k])
{
return false;
}
}
visited[k] = true;
}
}
}
}
return true;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int V, E;
cin >> V >> E;
vector<int>adj[V];
for(int i = 0; i < E; i++){
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
Solution obj;
bool ans = obj.isBipartite(V, adj);
if(ans)cout << "1\n";
else cout << "0\n";
}
return 0;
} /
| true |
2860214a698c8faa6bfdcfb79af25479055d9920 | C++ | StephenGaryKing/Math-For-Games | /2D vector Program/project2D/Vector2.cpp | UTF-8 | 1,097 | 3.265625 | 3 | [
"MIT"
] | permissive | #include "Vector2.h"
Vector2::Vector2()
{
}
Vector2::Vector2(float X, float Y)
{
x = X;
y = Y;
}
Vector2 Vector2::Translate(const Vector2& a_first, const Vector2& a_second)
{
return Add(a_first, a_second);
}
Vector2 Vector2::Add(const Vector2& a_first, const Vector2& a_second)
{
Vector2 newVector;
newVector.x = a_first.x + a_second.x;
newVector.y = a_first.y + a_second.y;
return newVector;
}
Vector2 Vector2::Subtract(const Vector2& a_first, const Vector2& a_second)
{
Vector2 newVector;
newVector.x = a_first.x - a_second.x;
newVector.y = a_first.y - a_second.y;
return newVector;
}
Vector2 Vector2::Scale(const Vector2& a_point, float a_scalar)
{
return Multiply(a_point, a_scalar);
}
Vector2 Vector2::Multiply(const Vector2& a_point, float a_scalar)
{
Vector2 newVector;
newVector.x = a_point.x * a_scalar;
newVector.y = a_point.y * a_scalar;
return newVector;
}
Vector2 Vector2::Divide(const Vector2& a_point, float a_scalar)
{
Vector2 newVector;
newVector.x = a_point.x / a_scalar;
newVector.y = a_point.y / a_scalar;
return newVector;
}
Vector2::~Vector2()
{
}
| true |
2b3e11b2bba46bacec17ff996f6be05199a10e02 | C++ | lwmcdona/CMPUT379 | /Unix-Multithreaded-System-Simulator-master/Unix-Multithreaded-System-Simulator-master/shared.cpp | UTF-8 | 1,568 | 3.125 | 3 | [] | no_license | // the shared.cpp file, this file handles contains shared methods
// used throughout the program, also defines the mutex struct
// which holds all mutexes
#include "includes.hpp"
#include "shared.hpp"
// get the current time in milliseconds
long int get_current_time(){
struct timeval t;
gettimeofday(&t, NULL);
long int milli = t.tv_sec * 1000 + t.tv_usec / 1000;
return milli;
}
// converts the state of a task to a string
string state_to_string(enum State s){
if (s == WAIT){
return "WAIT";
}
if (s == RUN){
return "RUN";
}
if (s == IDLE){
return "IDLE";
}
return "";
}
// Initializes all mutexes
void Mutexes::initialize_mutexes(){
this->initalize_mutex(&this->printing_mutex);
this->initalize_mutex(&this->resources_mutex);
}
// ***the next 3 methods were influenced by resources on eclass***
// Initialize a mutex and perform error checking
void Mutexes::initalize_mutex(pthread_mutex_t* mutex){
int rval = pthread_mutex_init(mutex, NULL);
if (rval){
perror("mutex initiliazation failed");
exit(1);
}
}
// lock a mutex and perform error checking
void Mutexes::lock_mutex(pthread_mutex_t* mutex){
int rval = pthread_mutex_lock(mutex);
if (rval){
perror("mutex locking failed");
exit(1);
}
}
// unlock a mutex and perform error checking
void Mutexes::unlock_mutex(pthread_mutex_t* mutex){
int rval = pthread_mutex_unlock(mutex);
if (rval){
perror("mutex unlocking failed");
exit(1);
}
} | true |
0702b0d621134c063ce9b40f740763d78a37c9ea | C++ | eignatik/Lab3 | /Rearrange.h | UTF-8 | 315 | 2.578125 | 3 | [] | no_license | #include <list>
#include <iostream>
using namespace std;
#ifndef LAB3_REARRANGE_H
#define LAB3_REARRANGE_H
class Rearrange {
list<int> intList;
public:
Rearrange();
~Rearrange();
void fillList(int numberOfElements);
void printList();
void changeOrder();
};
#endif //LAB3_REARRANGE_H
| true |
0164a7b3d95938cf700e4b4c0155ca4b4a4c10f3 | C++ | JasonCreighton/snowy | /UCI.cpp | UTF-8 | 8,900 | 2.75 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2017 Jason Creighton
// Available under the MIT license, see included LICENSE file for details
#include "Common.hpp"
#include "UCI.hpp"
#include "Board.hpp"
#include "Search.hpp"
#include "IO.hpp"
#include "Constants.hpp"
#include "Util.hpp"
// In case someone wants to use a different build environment
#ifndef GIT_VERSION
#define GIT_VERSION "(version unknown)"
#endif
namespace {
void ChooseMoveTime(int timeLeft_ms, int increment_ms, int movesUntilNextTimeControl, int& out_softMoveTime_ms, int& out_hardMoveTime_ms) {
const int TIME_MANAGEMENT_MARGIN_MS = 100;
// No move time specified, so no time limit
if(timeLeft_ms == -1) {
out_softMoveTime_ms = -1;
out_hardMoveTime_ms = -1;
return;
}
int totalTimeAvailableUntilNextTimeControl_ms = timeLeft_ms + (increment_ms * movesUntilNextTimeControl);
int idealMoveTime_ms = totalTimeAvailableUntilNextTimeControl_ms / movesUntilNextTimeControl;
int avoidFlagTime_ms = std::max(timeLeft_ms - TIME_MANAGEMENT_MARGIN_MS, 0);
int upperLimit_ms = std::min(idealMoveTime_ms * 2, avoidFlagTime_ms);
int lowerLimit_ms = upperLimit_ms / 4;
out_softMoveTime_ms = lowerLimit_ms;
out_hardMoveTime_ms = upperLimit_ms;
IO::PutInfo("Thinking for " + std::to_string(lowerLimit_ms) + " - " + std::to_string(upperLimit_ms) + " ms");
}
}
UCI::UCI() : m_Search(m_Board) {
SetHashTableSize(DEFAULT_HASH_TABLE_SIZE_MB);
}
void UCI::Run() {
std::string line;
IO::PutLine("Snowy " GIT_VERSION " by Jason Creighton (built on " __DATE__ " " __TIME__ ")");
while(IO::GetLine(line)) {
if(!DoCommand(line)) {
return;
}
}
}
bool UCI::DoCommand(const std::string& commandLine) {
std::stringstream lineStream(commandLine);
std::string command;
lineStream >> command;
if(command == "uci") {
IO::PutLine("id name Snowy " GIT_VERSION);
IO::PutLine("id author Jason Creighton");
IO::PutLine("option name Hash type spin default " + std::to_string(DEFAULT_HASH_TABLE_SIZE_MB) +
" min " + std::to_string(MIN_HASH_TABLE_SIZE_MB) +
" max " + std::to_string(MAX_HASH_TABLE_SIZE_MB));
IO::PutLine("uciok");
} else if(command == "setoption") {
std::string constantName;
lineStream >> constantName;
if(constantName == "name") {
std::string name;
std::string constantValue;
std::string value;
lineStream >> name;
lineStream >> constantValue;
lineStream >> value;
if(constantValue != "value") {
IO::PutInfo(R"(Error parsing setoption: Expected "value")");
}
SetOption(name, value);
} else {
IO::PutInfo(R"(Error parsing setoption: Expected "name")");
}
} else if(command == "position") {
m_Search.WaitForSearch();
std::string fenString;
std::string token;
std::list<std::string> tokens;
while(lineStream >> token) {
tokens.push_back(token);
}
if(tokens.front() == "startpos") {
fenString = Board::FEN_START_POSITION;
tokens.pop_front();
} else if (tokens.front() == "fen") {
tokens.pop_front();
// FEN string should consist of up to 6 tokens (last two seemingly optional)
for(int i = 0; i < 6; ++i) {
if(!tokens.empty() && tokens.front() != "moves") {
fenString += tokens.front() + " ";
tokens.pop_front();
}
}
}
// Set up board
m_Board.ParseFen(fenString);
if(!tokens.empty() && tokens.front() == "moves") {
tokens.pop_front();
while(!tokens.empty()) {
Board::Move m = Board::ParseMove(tokens.front());
tokens.pop_front();
if(!m_Board.Make(m)) {
IO::PutInfo("WARNING: Unable to make move " + m.ToString());
}
}
}
IO::PutInfo("Position hash: " + IntegerToHexString(m_Board.Hash()));
} else if (command == "isready") {
IO::PutLine("readyok");
} else if (command == "go") {
std::string optionName;
Search::Parameters params;
params.Depth = -1;
params.BruteForce = false;
params.SoftMoveTime_ms = -1;
params.HardMoveTime_ms = -1;
params.ShowHistograms = false;
int wtime_ms = -1;
int winc_ms = 0;
int btime_ms = -1;
int binc_ms = 0;
int movesUntilNextTimeControl = 40;
while(lineStream >> optionName) {
if(optionName == "depth") { lineStream >> params.Depth; }
else if(optionName == "bruteforce") { lineStream >> params.BruteForce; }
else if(optionName == "movetime") { lineStream >> params.HardMoveTime_ms; }
else if(optionName == "wtime") { lineStream >> wtime_ms; }
else if(optionName == "winc") { lineStream >> winc_ms; }
else if(optionName == "btime") { lineStream >> btime_ms; }
else if(optionName == "binc") { lineStream >> binc_ms; }
else if(optionName == "movestogo") { lineStream >> movesUntilNextTimeControl; }
else if(optionName == "showhistograms") { lineStream >> params.ShowHistograms; }
}
if(params.HardMoveTime_ms == -1) {
// No move time, try to calculate one
if(m_Board.WhiteToMove()) {
ChooseMoveTime(wtime_ms, winc_ms, movesUntilNextTimeControl, params.SoftMoveTime_ms, params.HardMoveTime_ms);
} else {
ChooseMoveTime(btime_ms, binc_ms, movesUntilNextTimeControl, params.SoftMoveTime_ms, params.HardMoveTime_ms);
}
// NB: At this point moveTime_ms might still be -1, depending on the options given
}
if(params.Depth == -1) {
// No depth was specified, unlimited search depth
params.Depth = MAX_PLY;
// However, if no move time was given, perhaps a reasonable default
// so we don't search forever
if(params.HardMoveTime_ms == -1) {
params.HardMoveTime_ms = 5000;
}
}
m_Search.StartSearch(params);
} else if (command == "stop") {
m_Search.StopSearch();
} else if(command == "perft") {
m_Search.WaitForSearch();
int depth;
lineStream >> depth;
std::vector<Board::Move> moveList;
m_Board.FindPseudoLegalMoves(moveList);
for(auto &m : moveList) {
if(m_Board.Make(m)) {
long perftCount = m_Search.Perft(depth - 1);
if(perftCount != 0) {
IO::PutLine(m.ToString() + ": " + std::to_string(perftCount));
}
m_Board.Unmake();
}
}
} else if(command == "eval") {
m_Search.WaitForSearch();
int score = m_Search.Quiesce();
int staticEval = m_Board.StaticEvaluation();
IO::PutInfo("Static evaluation: " + std::to_string(staticEval));
IO::PutInfo("Quiesce score: " + std::to_string(score));
} else if(command == "d") {
m_Search.WaitForSearch();
m_Board.Print();
} else if(command == "num_features") {
IO::PutLine(std::to_string(Board::NUM_FEATURES));
} else if(command == "features") {
m_Search.WaitForSearch();
std::string featureString;
for(int f : m_Board.EvaluationFeatures()) {
featureString += std::to_string(f) + " ";
}
IO::PutLine(featureString);
} else if (command == "quit") {
return false;
}
return true;
}
void UCI::WaitForSearch() {
// Man, I hate dumb little wrappers like this. There must be a better way.
m_Search.WaitForSearch();
}
void UCI::SetOption(const std::string& name, const std::string& value) {
if(name == "Hash") {
int megabytes;
std::stringstream valueStream(value);
valueStream >> megabytes;
if(megabytes > MAX_HASH_TABLE_SIZE_MB) {
megabytes = MAX_HASH_TABLE_SIZE_MB;
}
if(megabytes < MIN_HASH_TABLE_SIZE_MB) {
megabytes = MIN_HASH_TABLE_SIZE_MB;
}
SetHashTableSize(megabytes);
} else {
IO::PutInfo("Unknown option \"" + name + "\"");
}
}
void UCI::SetHashTableSize(int megabytes) {
assert(megabytes >= 1);
int megabytesLog2 = -1;
while(megabytes != 0) {
megabytes >>= 1;
++megabytesLog2;
}
int bytesLog2 = megabytesLog2 + 20;
m_Search.SetHashTableSize(bytesLog2);
} | true |
0dfcbd09acfdc32d717965f15defc4283fab1539 | C++ | IgorBozhok/Repo_C | /Sasin/C-HW/13/hw13.cpp | UTF-8 | 12,160 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <ctime>
using namespace std;
class exepionMyArray
{
public:
enum exepionMyArrayType
{
UNKNOW_MY_ARR_EXEP = 0,
INC_SIZE__MY_ARR_EXEP,
INC_MEM__MY_ARR_EXEP,
DIVISION_BY_ZERO
};
private:
exepionMyArrayType exepType;
public:
exepionMyArray();
exepionMyArray(exepionMyArrayType exepType);
~exepionMyArray();
exepionMyArrayType getExepType() const;
void exepMass(void) const;
};
exepionMyArray::exepionMyArray()
{
exepType = UNKNOW_MY_ARR_EXEP;
}
exepionMyArray::exepionMyArray(exepionMyArrayType exepType)
{
this->exepType = exepType;
}
exepionMyArray::~exepionMyArray()
{
cout << "Exeption finish" << endl;
}
exepionMyArray::exepionMyArrayType exepionMyArray::getExepType() const
{
return exepType;
}
void exepionMyArray::exepMass(void) const
{
switch (exepType)
{
case UNKNOW_MY_ARR_EXEP:
{
cout << "Unknow error" << endl;
break;
}
case INC_SIZE__MY_ARR_EXEP:
{
cout << "Size error" << endl;
break;
}
case INC_MEM__MY_ARR_EXEP:
{
cout << "Memorry error" << endl;
break;
}
case DIVISION_BY_ZERO:
{
cout << "Division by zero error" << endl;
break;
}
default:
{
cout << "Inc code error" << endl;
break;
}
}
}
namespace matrix_fun
{
template<typename userType>
class Matrix
{
private:
userType ** arr;
unsigned int sizeI;
unsigned int sizeJ;
public:
Matrix();
Matrix(userType ** arr, unsigned int sizeI, unsigned int sizeJ);
Matrix(const Matrix & from);
Matrix& operator=(const Matrix &from);
Matrix operator+(const Matrix &from);
Matrix operator-(const Matrix &from);
Matrix operator*(const Matrix &from);
Matrix operator/(const Matrix &from);
void print();
~Matrix();
};
template<typename userType>
Matrix<userType>::Matrix()
{
arr = nullptr;
sizeI = 0;
sizeJ = 0;
}
template<typename userType>
Matrix<userType>::Matrix(userType ** arr, unsigned int sizeI, unsigned int sizeJ)
{
if (sizeI <= 0 || sizeJ <=0 || arr == nullptr)
{
this->arr = nullptr;
this->sizeI = 0;
this->sizeJ = 0;
}
else
{
this->sizeI = sizeI;
this->sizeJ = sizeJ;
this->arr = new userType*[this->sizeI];
for (int i = 0; i < sizeI; i++)
{
this->arr[i] = new userType[sizeJ];
}
for (int i = 0; i < this->sizeI; i++)
{
for (int j = 0; j < this->sizeJ; j++)
{
this->arr[i][j] = arr[i][j];
}
}
}
}
template<typename userType>
Matrix<userType>::Matrix(const Matrix & from)
{
if (from.sizeI <= 0 || from.sizeJ <= 0 || from.arr == nullptr)
{
this->arr = nullptr;
this->sizeI = 0;
this->sizeJ = 0;
}
else
{
this->sizeI = from.sizeI;
this->sizeJ = from.sizeJ;
this->arr = new userType*[this->sizeI];
for (int i = 0; i < sizeI; i++)
{
this->arr[i] = new userType[sizeJ];
}
for (int i = 0; i < this->sizeI; i++)
{
for (int j = 0; j < this->sizeJ; j++)
{
this->arr[i][j] = from.arr[i][j];
}
}
}
}
template<typename userType>
Matrix<userType>& Matrix<userType>::operator=(const Matrix & from)
{
if (this->arr != nullptr)
{
for (int i = 0; i < this->sizeI; i++)
{
delete[]arr[i];
}
delete[]arr;
}
if (from.sizeI <= 0 || from.sizeJ <= 0 || from.arr == nullptr)
{
this->arr = nullptr;
this->sizeI = 0;
this->sizeJ = 0;
}
else
{
this->sizeI = from.sizeI;
this->sizeJ = from.sizeJ;
this->arr = new userType*[this->sizeI];
for (int i = 0; i < sizeI; i++)
{
this->arr[i] = new userType[sizeJ];
}
for (int i = 0; i < this->sizeI; i++)
{
for (int j = 0; j < this->sizeJ; j++)
{
this->arr[i][j] = from.arr[i][j];
}
}
}
return *this;
}
template<typename userType>
Matrix<userType> Matrix<userType>::operator+(const Matrix &right)
{
if (this->arr == nullptr || right.arr == nullptr)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_MEM__MY_ARR_EXEP);
throw;
}
if (this->sizeI != right.sizeI || this->sizeJ != right.sizeJ || this->sizeI <= 0 || this->sizeJ <= 0 || right.sizeI <= 0 || right.sizeJ<=0 )
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_SIZE__MY_ARR_EXEP);
}
userType ** tmpArr = nullptr;
tmpArr = new userType*[this->sizeI];
for (int i = 0; i < sizeI; i++)
{
tmpArr[i] = new userType[this->sizeJ];
}
for (int i = 0; i < sizeI; i++)
{
for (int j = 0; j < sizeJ; j++)
{
tmpArr[i][j] = this->arr[i][j] + right.arr[i][j];
}
}
Matrix res(tmpArr, sizeI, sizeJ);
for (int i = 0; i < sizeJ; i++)
{
delete[]tmpArr[i];
}
delete[]tmpArr;
return res;
}
template<typename userType>
Matrix<userType> Matrix<userType>::operator-(const Matrix &right)
{
if (this->arr == nullptr || right.arr == nullptr)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_MEM__MY_ARR_EXEP);
throw;
}
if (this->sizeI != right.sizeI || this->sizeJ != right.sizeJ || this->sizeI <= 0 || this->sizeJ <= 0 || right.sizeI <= 0 || right.sizeJ <= 0)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_SIZE__MY_ARR_EXEP);
}
userType ** tmpArr = nullptr;
tmpArr = new userType*[this->sizeI];
for (int i = 0; i < sizeI; i++)
{
tmpArr[i] = new userType[this->sizeJ];
}
for (int i = 0; i < sizeI; i++)
{
for (int j = 0; j < sizeJ; j++)
{
tmpArr[i][j] = this->arr[i][j] - right.arr[i][j];
}
}
Matrix res(tmpArr, sizeI, sizeJ);
for (int i = 0; i < sizeJ; i++)
{
delete[]tmpArr[i];
}
delete[]tmpArr;
return res;
}
template<typename userType>
Matrix<userType> Matrix<userType>::operator*(const Matrix &right)
{
if (this->arr == nullptr || right.arr == nullptr)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_MEM__MY_ARR_EXEP);
throw;
}
if (this->sizeI != right.sizeI || this->sizeJ != right.sizeJ || this->sizeI <= 0 || this->sizeJ <= 0 || right.sizeI <= 0 || right.sizeJ <= 0)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_SIZE__MY_ARR_EXEP);
}
userType ** tmpArr = nullptr;
tmpArr = new userType*[this->sizeI];
for (int i = 0; i < sizeI; i++)
{
tmpArr[i] = new userType[this->sizeJ];
}
for (int i = 0; i < sizeI; i++)
{
for (int j = 0; j < sizeJ; j++)
{
tmpArr[i][j] = this->arr[i][j] * right.arr[i][j];
}
}
Matrix res(tmpArr, sizeI, sizeJ);
for (int i = 0; i < sizeJ; i++)
{
delete[]tmpArr[i];
}
delete[]tmpArr;
return res;
}
template<typename userType>
Matrix<userType> Matrix<userType>::operator/(const Matrix &right)
{
if (this->arr == nullptr || right.arr == nullptr)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_MEM__MY_ARR_EXEP);
throw;
}
if (this->sizeI != right.sizeI || this->sizeJ != right.sizeJ || this->sizeI <= 0 || this->sizeJ <= 0 || right.sizeI <= 0 || right.sizeJ <= 0)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::INC_SIZE__MY_ARR_EXEP);
}
for (int i = 0; i < right.sizeI; i++)
{
for (int j = 0; j < right.sizeJ; j++)
{
if (right.arr[i][j] == 0)
{
throw exepionMyArray(exepionMyArray::exepionMyArrayType::DIVISION_BY_ZERO);
}
}
}
userType ** tmpArr = nullptr;
tmpArr = new userType*[this->sizeI];
for (int i = 0; i < sizeI; i++)
{
tmpArr[i] = new userType[this->sizeJ];
}
for (int i = 0; i < sizeI; i++)
{
for (int j = 0; j < sizeJ; j++)
{
tmpArr[i][j] = this->arr[i][j] / right.arr[i][j];
}
}
Matrix res(tmpArr, sizeI, sizeJ);
for (int i = 0; i < sizeJ; i++)
{
delete[]tmpArr[i];
}
delete[]tmpArr;
return res;
}
template<typename userType>
void Matrix<userType>::print()
{
for (int i = 0; i < this->sizeI; i++)
{
for (int j = 0; j < this->sizeJ; j++)
{
cout << this->arr[i][j] << " ";
}
cout << endl;
}
}
template<typename userType>
Matrix<userType>::~Matrix()
{
for (int i = 0; i < this->sizeI; i++)
{
delete[]arr[i];
}
delete[]arr;
}
}
using matrix_fun::Matrix;
const int SizeIA = 5;
const int SizeJA = 5;
const int SizeIB = 5;
const int SizeJB = 5;
const int SizeDoubI = 5;
const int SizeDoubJ = 5;
void main(void)
{
srand(time(NULL));
int ** MassA;
MassA = new int*[SizeIA];
for (int i = 0; i < SizeIA; i++)
{
MassA[i] = new int[SizeJA];
}
for (int i = 0; i < SizeIA; i++)
{
for (int j = 0; j < SizeJA; j++)
{
MassA[i][j] = rand() % 100 - 50;
}
}
int ** MassB;
MassB = new int*[SizeIB];
for (int i = 0; i < SizeIB; i++)
{
MassB[i] = new int[SizeJB];
}
for (int i = 0; i < SizeIB; i++)
{
for (int j = 0; j < SizeJB; j++)
{
MassB[i][j] = rand() % 100 - 50;
}
}
double ** MassDouble;
MassDouble = new double*[SizeDoubI];
for (int i = 0; i < SizeDoubI; i++)
{
MassDouble[i] = new double[SizeDoubJ];
}
for (int i = 0; i < SizeDoubI; i++)
{
for (int j = 0; j < SizeDoubJ; j++)
{
MassDouble[i][j] = 0.1 *(rand() % 11); //(double)rand() / (double)RAND_MAX * (20 - -12) + -12;
}
}
Matrix<int> objA(MassA, SizeIA, SizeJA);
cout << "objA: " << endl;
objA.print();
cout << endl;
Matrix<int> objB(MassB, SizeIB, SizeJB);
cout << "objB: " << endl;
objB.print();
cout << endl;
Matrix<int> objA1(objA);
cout << "objA1(objA): " << endl;
objA.print();
cout << endl;
Matrix<int> objB1;
objB1 = objB;
cout << "objB1 = objB: " << endl;
objB1.print();
cout << endl;
cout << "objPlus = objA1 + objB2: " << endl;
Matrix<int> objPlus;
try
{
objPlus = objA1 + objB1;
}
catch (const exepionMyArray& exep)
{
exep.exepMass();
}
catch (...)
{
cout << "Catch(...)" << endl;
}
objPlus.print();
cout << endl;
cout << "objExep = objNullptr + objA1: " << endl;
Matrix<int> objNullptr(nullptr, SizeIA, SizeJA);
Matrix<int> objExep;
try
{
objExep = objNullptr + objA1;
}
catch (const exepionMyArray& exep)
{
exep.exepMass();
}
catch (...)
{
cout << "Catch(...)" << endl;
}
cout << endl;
cout << "objMinus = objA1 - objB1: " << endl;
Matrix<int> objMinus;
try
{
objMinus = objA1 - objB1;
}
catch (const exepionMyArray& exep)
{
exep.exepMass();
}
catch (...)
{
cout << "Catch(...)" << endl;
}
objMinus.print();
cout << endl;
cout << "objExep = objSize + objA1: " << endl;
Matrix<int> objSize(MassA, SizeIA, 4);
Matrix<int> objA1Exep;
try
{
objA1Exep = objSize + objB1;
}
catch (const exepionMyArray& exep)
{
exep.exepMass();
}
catch (...)
{
cout << "Catch(...)" << endl;
}
cout << endl;
cout << "objMinus = objA1 - objB1: " << endl;
Matrix<int> objMult;
try
{
objMult = objA1 * objB1;
}
catch (const exepionMyArray& exep)
{
exep.exepMass();
}
catch (...)
{
cout << "Catch(...)" << endl;
}
objMinus.print();
cout << endl;
cout << "obj6: " << endl;
Matrix<double> obj6(MassDouble, SizeDoubI, SizeDoubJ);
obj6.print();
cout << endl;
cout << "obj7 = obj6 + obj6: " << endl;
Matrix<double> obj7;
try
{
obj7 = obj6 + obj6;
}
catch (const exepionMyArray& exep)
{
exep.exepMass();
}
catch (...)
{
cout << "Catch(...)" << endl;
}
obj7.print();
cout << endl;
cout << "objDivision = obj6 / obj7: " << endl;
Matrix<double> objDivision;
try
{
objDivision = obj6 / obj7;
}
catch (const exepionMyArray& exep)
{
exep.exepMass();
}
catch (...)
{
cout << "Catch(...)" << endl;
}
objDivision.print();
cout << endl;
for (int i = 0; i < SizeIA; i++)
{
delete[]MassA[i];
}
delete[]MassA;
for (int i = 0; i < SizeIB; i++)
{
delete[]MassB[i];
}
delete[]MassB;
for (int i = 0; i < SizeDoubI; i++)
{
delete[]MassDouble[i];
}
delete[]MassDouble;
system("pause");
return;
} | true |
10c7f0f654a94db85ca00668c369122d9469409c | C++ | R1tschY/liblightports | /lightports/core/memory.h | UTF-8 | 2,029 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef WINSTRING_REF_H
#define WINSTRING_REF_H
#include <memory>
#include <type_traits>
#include <windows.h>
#include <cpp-utils/memory/unique_array.h>
namespace Windows {
//
// Local memory
namespace Detail {
struct LocalDeleter {
void operator()(void* ptr) {
::LocalFree(ptr);
}
};
} // namespace Detail
template<typename T>
using LocalPtr = std::unique_ptr<T, Detail::LocalDeleter>;
template<typename T>
using LocalArray = cpp::unique_array<T, Detail::LocalDeleter>;
//
// GeneralHandle
template<typename Deleter>
using ManagedHandle = std::unique_ptr<typename Deleter::pointer, Deleter>;
#define WINDOWS_DEFINE_HANDLE_DELETER(func) \
template<typename PointerT> \
struct func##Functor { \
typedef PointerT pointer; \
void operator()(PointerT handle) { \
func(handle); \
} \
}
#define WINDOWS_HANDLE_DELETER(func) func##Functor
#define WINDOWS_DEFINE_GENERIC_HANDLE_TYPE(name, deleter) \
WINDOWS_DEFINE_HANDLE_DELETER(deleter); \
template<typename T> \
using name = ::Windows::GeneralHandle<T, WINDOWS_HANDLE_DELETER(deleter)>;
#define WINDOWS_DEFINE_HANDLE_TYPE(name, type, deleter) \
WINDOWS_DEFINE_HANDLE_DELETER(deleter); \
using name = ::Windows::GeneralHandle<type, WINDOWS_HANDLE_DELETER(deleter)>;
template<
typename PointerT,
template<typename> class DeleterFuncT
>
using GeneralHandle = std::unique_ptr<PointerT, DeleterFuncT<PointerT> >;
//
// Handle
struct HandleDeleter {
typedef HANDLE pointer;
void operator()(HANDLE ptr)
{ ::CloseHandle(ptr); }
};
using Handle = ManagedHandle<HandleDeleter>;
struct HandleExDeleter {
typedef HANDLE pointer;
void operator()(HANDLE ptr)
{ if (ptr != INVALID_HANDLE_VALUE) ::CloseHandle(ptr); }
};
using HandleEx = ManagedHandle<HandleExDeleter>;
struct FindHandleDeleter {
typedef HANDLE pointer;
void operator()(HANDLE ptr)
{ if (ptr != INVALID_HANDLE_VALUE) ::FindClose(ptr); }
};
using FindHandle = ManagedHandle<FindHandleDeleter>;
} // namespace Windows
#endif // WINSTRING_REF_H
| true |
b71605cee536d44d1dbdadd5e3b27226fd6eebcc | C++ | longuan/hctunnel | /src/acceptor.h | UTF-8 | 654 | 2.625 | 3 | [] | no_license | #ifndef __ACCEPTOT_H__
#define __ACCEPTOR_H__
#include "eventhandler.h"
#include <fcntl.h>
class Acceptor : public IOWatcher
{
private:
int _listenport;
int _idlefd;
public:
Acceptor() : IOWatcher(ACCEPTOR), _listenport(0), _idlefd(::open("/dev/null", O_RDONLY | O_CLOEXEC))
{
_fd = ::socket(PF_INET, SOCK_STREAM, 0);
if (_fd < 0)
FATAL_ERROR("Acceptor socket error");
};
int start(int port);
void stop();
virtual ~Acceptor() =default;
virtual void handleEvent(EVENT_TYPE revents) override;
virtual void handleClose() override;
int acceptClient();
};
#endif // __ACCEPTOR_H__ | true |
e0911c355355e3567a445d20804679c270108934 | C++ | umaatgithub/QlicProject | /src/product.cpp | UTF-8 | 957 | 3.0625 | 3 | [] | no_license | #include "product.h"
Product::Product(int a, QString b, QString c, int d, int e)
{
ID = a;
Name = b;
Description = c;
Category_ID = d;
Price = e;
}
bool Product::setID(const int &a)
{
ID = a;
return true;
}
int Product::getID() const
{
return ID;
}
bool Product::setName(const QString &b)
{
Name = b ;
return true;
}
QString Product::getName() const
{
return Name ;
}
bool Product::setDescription(const QString &c)
{
Description = c ;
return true;
}
QString Product::getDescription() const
{
return Description ;
}
bool Product::setCategory_ID(const int &d)
{
Category_ID = d ;
return true;
}
int Product::getCategory_ID()const
{
return Category_ID;
}
bool Product::setPrice(const int &e)
{
Price = e ;
return true;
}
int Product::getPrice()const
{
return Price;
}
| true |
e88ed2a60cfe65e311732ac4c6210472bc426833 | C++ | arnabsarker/LaundroMeter | /LaundryArduino.cc | UTF-8 | 4,936 | 3.140625 | 3 | [] | no_license | #include < SoftwareSerial.h >
SoftwareSerial BTSerial(2, 3);
//CONSTANTS
const int DRIER_TIME = 45*60; //seconds it takes to dry clothes, approx. 45 minutes
//Threshold values used to determine events for the dryer.
const int X_DOOR_THRESHOLD = 30;
const int Y_DOOR_THRESHOLD = 30;
const int Z_DOOR_THRESHOLD = 70;
const double OFF_THRESHOLD = 5;
const int ON_TEMP_THRESHOLD = 3;
//constant used to convert temperature to degrees F
const double TEMP_MULTIPLIER = 500/1024.0;
//Setup values for Arduino pins
const int xPin = 2;
const int yPin = 3;
const int zPin = 4;
const int tPin = 0;
//INITIALIZED VALUES FOR PROGRAM
//Calibration array: initialized at the beginning so both setup() and loop() can access the values
int CalVal[] = {0, 0, 0, 0}; //Stores calibrated values for x, y, and z accelerations and temperature, in that order
//Since jerk is calculated with calibrated accelerations, it does not need to have its own calibration.
boolean dryerstarted = false; //boolean representing whether the dryer has started. Initial condition assumes the dryer is off.
boolean dooropen = false; //boolean representing whether the dryer door is open.Initiial condition assumes door is closed.
void setup() {
//Begin communication with bluetooth and serial monitor.
BTSerial.begin(9600);
Serial.begin(9600);
//Calibrates Machine before beginning
Serial.println("Hold Steady for Calibration...");
int i = 0;
int xcRead = 0;
int ycRead = 0;
int zcRead = 0;
int temp = 0;
//Adds together values for each variable for 5 seconds
while(i < 50){
xcRead = xcRead + analogRead(xPin);
ycRead = ycRead + analogRead(yPin);
zcRead = zcRead + analogRead(zPin);
temp += analogRead(tPin) * TEMP_MULTIPLIER;
i = i + 1;
delay(100);
}
//Stores average value for each variable into the CalVal array so they can be accessed in the loop
CalVal[0] = xcRead / 50; //Calibrated accelerations
CalVal[1] = ycRead / 50;
CalVal[2] = zcRead / 50;
CalVal[3] = temp / 50;
Serial.println("Temperature Calibration: " + (String) CalVal[3]);
Serial.println("x calibration: " + (String) CalVal[0] + "y calibration: " + (String)CalVal[1] + "z calibration: " + (String)CalVal[2]);
Serial.println("Calibration done!");
}
//Initializes arrays to store acceleration values for two consecutive calculations
int xRead[] ={0, 0};
int yRead[] ={0, 0};
int zRead[] ={0, 0};
//Starts a count of how long the dryer has been on
int halfsecondspassed = 0;
void loop() {
//Stores previous value of acceleration in Read[0] and the current value in Read[1], so jerk can be calculated later
xRead[0] = xRead[1]; xRead[1] = analogRead(xPin) - CalVal[0];
yRead[0] = yRead[1]; yRead[1] = analogRead(yPin) - CalVal[1];
zRead[0] = zRead[1]; zRead[1] = analogRead(zPin) - CalVal[2];
//Uses these consecutive values to calculate jerk.
int xjRead = (xRead[1] - xRead[0]);
int yjRead = (yRead[1] - yRead[0]);
int zjRead = (zRead[1] - zRead[0]);
//stores difference in temperature from calculated value
int dTemp = analogRead(tPin) * TEMP_MULTIPLIER - CalVal[3];
//Print to serial monitor for debugging
Serial.println("x: " + (String) xRead[1] + " y: " + (String) yRead[1] + "z: " + (String) zRead[1]);
Serial.println("xjerk: " + (String) xjRead + " yjerk: " + (String) yjRead + " zjerk: " + (String) zjRead);
Serial.println("Temp: " + (String) dTemp);
//The following code determines when to send a message to the other Arduino:
//Door Opened: Occurs when the accelerations reach a certain value and the door is not already open.
if(((abs(xjRead) > X_DOOR_THRESHOLD || abs(yjRead) > Y_DOOR_THRESHOLD) && (abs(zjRead) > Z_DOOR_THRESHOLD) && !dooropen)){
Serial.println("D");
BTSerial.println("D");
dooropen = true;
}
//Machine off: Occurs when all the accelerations are below a certain threshold (representing the machine's natural vibration)
//and the dryer has already been started. Could also occur if the drier has been running for long enough.
else if (((abs(xRead[1]) < OFF_THRESHOLD) && (abs(yRead[1]) < OFF_THRESHOLD) && (abs(zRead[1]) < OFF_THRESHOLD) && dryerstarted)
|| (halfsecondspassed > DRIER_TIME * 2)){
Serial.println("O");
BTSerial.println("O");
dryerstarted = false;
}
//Machine on: Should occur if the laudry machine is hot enough and it isn't already on
else if (abs(dTemp) > ON_TEMP_THRESHOLD && !dryerstarted){
Serial.println("N");
BTSerial.println("N");
dryerstarted = true;
} else{
Serial.println("");
BTSerial.println("");
}
delay(500); // delay so we can read the values more clearly
//Code to keep track of time
if(dryerstarted){
halfsecondspassed +=1; //keeps track of the time, since each loop is approximately half a second
} else {
halfsecondspassed = 0; //if the dryer hasn't started, the time should be 0
}
}
| true |
e06699bbf0323e8df38e294f8816c14c775b4bc3 | C++ | djmgeneseo/Data-Structures | /Degree_Sequences_Linked_List/Degree_Sequences_Linked_List_v1.0.cpp | UTF-8 | 4,967 | 3.953125 | 4 | [] | no_license | // David Murphy
// 09/19/17
// Discrete Math Practice
// v1.0
/*
* A degree sequence is a sequence of integers that represents the degrees of each vertex
* in an undirected graph.
* To be a degree sequence, the following two cases must be true:
* 1) Handshaking Theorem: The sum of the degrees of all the vertices is exactly
* TWICE the total number of edges.
* 2) Every non-increasing degree sequence of non-negative integers that has an
* EVEN NUMBER OF ODD TERMS is the degree sequence of an undirected graph.
*
* The position of the vertices along the linked list is contingent on their assigned degree.
* The vertices will arrange from that of highest degree to lowest.
*/
#include <iostream>
using namespace std;
struct vertex {
char label;
int d1;
vertex * next;
}; // struct vertex
vertex * createList() {
vertex*phead = new vertex;
(*phead).d1=0;
(*phead).next=0;
return phead;
} // vertex * createList()
/* Prints the amount of vertices, and the vertex label along with
* its degree in a list on a single line. The order is determined by the
* order of the link list, from head -> tail.
*
* Calls functions:
*
*/
void printList(vertex * head) {
cout << endl << "List contains " << (*head).d1 << " vertices: ";
if((*head).next!=0) {
vertex * temp = (*head).next;
cout << (*temp).label << "(" << (*temp).d1 << ") ";
while ((*temp).next!=0) {
temp = (*temp).next;
cout << (*temp).label << "(" << (*temp).d1 << ") ";
}
}
cout << endl << endl;
} // void printList(vertex * phead)
void advance(vertex *& ptr) {
ptr = (*ptr).next;
} // void advance(vertex *& ptr)
/* In order to insert new node, this function requires the passage of the node
* into the function that will be BEFORE the desired node to be inserted.
*/
void insert(vertex * pred, vertex * newVertex, vertex * head) {
(*newVertex).next = (*pred).next;
(*pred).next = newVertex;
(*head).d1++;
} // void insert(vertex * pred, vertex * newVertex, vertex * phead)
/* The position of the vertices along the linked list is contingent on their assigned degree.
* The vertices will arrange from that of highest degree to lowest.
*
* Calls functions:
* - advance()
* - insert()
*/
void insertInOrder(vertex * newvertex, vertex * head) {
vertex*pred = head;
// int i = the degree value of the newly inserted vertex.
int i = (*newvertex).d1;
vertex*succ = (*pred).next;
//search
while(succ!= 0 && i <= (*succ).d1) {
advance(pred);
advance(succ);
}
insert(pred, newvertex, head);
} // void insertInOrder(vertex * newvertex, vertex * head)
/* Checks if degree sequence: the sum of degrees is even
*
* Calls functions:
* - advance()
*/
bool isDegreeSequence(vertex * head) {
vertex*temp = new vertex;
temp=(*head).next;
int i = (*temp).d1;
// loop through list, accumulating the total degree value of each vertex in graph
while ((*temp).next !=0) {
advance(temp);
i = i + (*temp).d1;
}
// RETURN FALSE: if SUM of degrees of graph is ODD
if(i%2 !=0) {return false;}
// RETURN TRUE: else SUM of degrees is EVEN
else {return true;}
} // bool isListDegreeEven(vertex * head)
void main(){
cout << "v1.0" << endl;
cout << "David Murphy - Discrete Math Practice - 09/19/17" << endl;
cout << "Is your degree sequence a valid sequence for an undirected graph?" << endl << endl;
char label='.';
int deg;
bool degBool;
// Initialize list: (*phead).d1 is the total # of vertices
vertex*phead = createList();
// PROMPT USER INPUT
while(label != '/') {
// create new vertex
vertex*newvertex = new vertex;
// prompt for vertex label and degree #
cout << "Label a vertex using one character: ";
cin >> label;
// A '/' input terminates the selection interface prompt
if(label=='/'){break;}
cout << "Insert the vertex's degree (deg>0): ";
cin >> deg;
// Prompt if input is 0
while(deg==0){
cout << endl;
cout << "ERROR: degree must be > 0: ";
cin >> deg;
} // nested while
// assign values to vertex; insert vertex into list
(*newvertex).d1=deg;
(*newvertex).label=label;
insertInOrder(newvertex, phead);
// Print
printList(phead);
// // Prompt termination option
cout << "[Type '/' when finished]" << endl;
} // while
cout << endl;
// Check whether first list is a graphic sequence
degBool = isDegreeSequence(phead);
// YES
if((*phead).d1>0 && degBool) {
cout << "******************************************************************" << endl;
cout << "* YES! This is a valid degree sequence for an UNDIRECTED graph. *" << endl;
cout << "******************************************************************" << endl;
} else { // NO
cout << "*********************************************************************" << endl;
cout << "* NO! This is NOT a valid degree sequence for an UNDIRECTED graph. *" << endl;
cout << "*********************************************************************" << endl;
}
cout << endl;
} // main() | true |
dc8a5207f1a1fc350b367313953678ab334efcb3 | C++ | matbuster/cppframework | /Threading/Mutex.h | UTF-8 | 798 | 2.828125 | 3 | [] | no_license | /**
* \file Mutex.h
* \date 04/11/2015
* \author MAT
*/
#ifndef MUTEX_H
#define MUTEX_H
#ifdef _WINDOWS
#include <windows.h>
#endif
#ifdef LINUX
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include "../Timing/Chrono.h"
#endif
namespace Threading
{
class Mutex
{
private:
#ifdef _WINDOWS
/** win handle on the mutex */
HANDLE m_hMutex;
#endif
#ifdef LINUX
pthread_mutex_t m_hMutex;
#endif
/** internal lock release counter*/
int m_iCounterLock_Unlock;
public:
Mutex();
~Mutex();
/** get mutex */
bool WaitOne();
/** wait with a timeout value expressed in milliseconds */
bool WaitOne(int iTimeout);
/** release mutex */
bool Release();
};
};
#endif /* MUTEX_H*/ | true |
eed7fc10111d0e7c766815d8ad97b40a839ae0a8 | C++ | arunksoman/MFRC522_ESP32 | /src/main.cpp | UTF-8 | 3,046 | 2.59375 | 3 | [] | no_license |
// Include Libraries
#include "Arduino.h"
#include "RFID.h"
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>
// Pin Definitions
#define RFID_PIN_RST 22
#define RFID_PIN_SDA 21
const char * ssid = "anuja1";
const char * password = "ar3k57u4";
const char * host = "192.168.43.82";
String device_id = "00000001";
String rfidNo, postData;
WiFiServer server(80);
// Global variables and defines
// object initialization
RFID rfid(RFID_PIN_SDA,RFID_PIN_RST);
// Setup the essentials for your circuit to work. It runs first every time your circuit is powered with electricity.
void setup()
{
// Setup Serial which is useful for debugging
// Use the Serial Monitor to view printed messages
Serial.begin(9600);
Serial.println("start");
//initialize RFID module
rfid.init();
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
// digitalWrite(Led_OnBoard, LOW);
delay(250);
Serial.print(".");
// digitalWrite(Led_OnBoard, HIGH);
delay(250);
}
Serial.println(WiFi.localIP());
}
// Main logic of your circuit. It defines the interaction between the components you selected. After setup, it runs over and over again, in an eternal loop.
void loop()
{
// RFID Card Reader - RC522 - Test Code
//Read RFID tag if present
Serial.println("test");
String rfidtag = rfid.readTag();
//print the tag to serial monitor if one was discovered
if(rfidtag != "None"){
rfid.printTag(rfidtag);
rfidNo = rfidtag;
Serial.print("Tag: ");
Serial.println(rfidNo);
postData = "rfidNo=" + rfidNo + "&device_id=" + device_id;
Serial.println(postData);
HTTPClient http;
http.begin("http://192.168.43.212:8084/samplepro/webresources/generic"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
Serial.print("RFID No= ");
Serial.print(rfidNo);
const size_t capacity = JSON_OBJECT_SIZE(3 ) + JSON_ARRAY_SIZE(3) + 60;
DynamicJsonDocument doc(capacity);
// Parse JSON object
DeserializationError error = deserializeJson(doc, payload);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
Serial.println(F("Response:"));
Serial.println(doc["name"].as<char*>());
delay(1000);
http.end(); //Close connection
}
delay(1000);
}
| true |
0675bf713ba203233b385029c5d8b1ff9d4ce0dd | C++ | ilario-pierbattista/hasp-tracker | /matlab/preprocess/floor_rebase.cxx | UTF-8 | 1,279 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#include "mexutils.h"
/*
* Main function
*
* nlhs: Numero atteso di output
* plhs: Array di puntatori all'output
* nrhs: Numero di parametri in input
* prhs: Array di puntatori all'input
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
Image *origin, *destination;
double floorValue;
/* Controllo dell'input */
if (nrhs < 1 || nrhs > 2) {
mexErrMsgTxt("È richiesto un solo parametro in input:\n"
"\t1)Immagine\n"
"\t2)Floor Value\n");
}
if (nlhs != 1) {
mexErrMsgTxt("È richiesto un solo parametro in output:\n"
"\t1)Immagine processata");
}
plhs[0] = mxCreateNumericArray(2, mxGetDimensions(prhs[0]),
mxDOUBLE_CLASS, mxREAL);
origin = new Image(mxGetPr(prhs[0]), mxGetDimensions(prhs[0]));
destination = new Image();
destination->setImage(mxGetPr(plhs[0]));
destination->setSize(mxGetDimensions(plhs[0]));
if(nrhs == 2) {
floorValue = *(mxGetPr(prhs[1]));
Image::floorRebase(origin, destination, floorValue);
} else if(nrhs == 1) {
Image::floorRebase(origin, destination);
}
}
| true |
ca1b5773683914a2ad4d0627a68f3c5623ba1859 | C++ | fmi-lab/oop-2019-kn-group6-sem | /Exercise 5/row.cpp | UTF-8 | 2,352 | 3.6875 | 4 | [] | no_license | #include"row.h"
#include<iostream>
#include<cassert>
#include<cstring>
using namespace std;
row::row(const char* word, const char* meaning)
{
if(strlen(word) <= 100 && strlen(meaning) <= 500)
{
this->word = new char[strlen(word) + 1];
assert(this->word);
strcpy(this->word, word);
this->meaning = new char[strlen(meaning) + 1];
assert(this->meaning);
strcpy(this->meaning, meaning);
}
else
{
cout<<"Word is too long or meaning is too long!\n";
word = NULL;
meaning = NULL;
}
}
row::row(const row& other)
{
this->word = new char[strlen(other.word) + 1];
assert(this->word);
strcpy(this->word, other.word);
this->meaning = new char[strlen(other.meaning) + 1];
assert(this->meaning);
strcpy(this->meaning, other.meaning);
}
row::~row()
{
if(this->word)
{
delete[] word;
}
if(this->meaning)
{
delete[] meaning;
}
}
row& row::operator=(const row& other)
{
if(this != &other)
{
if(this->word)
{
delete[] word;
}
if(this->meaning)
{
delete[] meaning;
}
this->word = new char[strlen(other.word) + 1];
assert(this->word);
strcpy(this->word, other.word);
this->meaning = new char[strlen(other.meaning) + 1];
assert(this->meaning);
strcpy(this->meaning, other.meaning);
}
}
const char* row::get_word()const
{
return word;
}
const char* row::get_meaning()const
{
return meaning;
}
void row::set_word(const char* word)
{
if(strlen(word) <= 100){
if(strcmp(this->word, word) != 0)
{
if(this->word)
{
delete[] word;
}
this->word = new char[strlen(word) + 1];
assert(this->word);
strcpy(this->word, word);
}
} else{
cout<<"Word is too long!\n";
}
}
void row::set_meaning(const char* meaning)
{
if(strlen(meaning) <= 500){
if(strcmp(this->meaning, meaning) != 0)
{
if(this->meaning)
{
delete[] meaning;
}
this->meaning = new char[strlen(meaning) + 1];
assert(this->meaning);
strcpy(this->meaning, meaning);
}
} else{
cout<<"Meaning is too long!\n";
}
}
| true |
d365d374c580266173ed92e5196f28ad65969794 | C++ | TejBirring8/PacketProcessingCpp | /packet_processing/packet_definitions/_packet.h | UTF-8 | 2,252 | 2.71875 | 3 | [] | no_license | //
// Created by tbirring on 10/10/2019.
//
#ifndef CODETEST_PACKET_PROCESSING_PACKET_DEFINITIONS_PACKET_H
#define CODETEST_PACKET_PROCESSING_PACKET_DEFINITIONS_PACKET_H
#include "_types.h"
#include "../types.h"
namespace packet_processing::packet_definitions
{
// packet type - the byte specifying which packet (struct definition) is being read.
template < uint8_t PacketType, Endianness SourceEndianness, size_t PayloadSize >
class Packet;
}
/* this class represents a packet, implying basic formatting required for the system */
template < uint8_t packet_type, packet_processing::Endianness source_endianness, size_t size_of_payload_bytes >
class packet_processing::packet_definitions::Packet
{
public:
static const constexpr Endianness target_endianness = source_endianness;
static const constexpr size_t size_payload{size_of_payload_bytes};
private:
uint8_t rcvd_packet_type_{0};
uint32_t rcvd_timestamp_ms_{0};
PayloadByteStream<size_payload> stream_rcvd_payload_;
uint8_t rcvd_err_check_{0};
uint8_t bytewise_sum_of_packet{0}; // for error checking
public:
explicit Packet(std::istream& byteInputStream);
// used for packet-type comparison
static constexpr uint8_t get_type() { return packet_type; }
// getters for "header" bytes and error check byte
[[nodiscard]] uint8_t rcvd_packet_type() const { return rcvd_packet_type_; }
[[nodiscard]] uint32_t rcvd_timestamp_ms() const { return rcvd_timestamp_ms_; }
[[nodiscard]] uint8_t rcvd_err_check() const { return rcvd_err_check_; }
[[nodiscard]] unsigned long timestamp_sec() { return static_cast<unsigned long>(rcvd_timestamp_ms_ / 1000); }
// returns ref to istream encapsulating the payload buffer -
// the istream ref is used by subclasses to access/parse payload data
// using the PacketDataReader class.
std::istream& get_stream_of_payload_bytes() { return stream_rcvd_payload_; }
// check if this packet has errors : bytewise sum of all packet's bytes (excluding error check) % 256
// (because uint8_t)
bool is_erroneous() { return bytewise_sum_of_packet != rcvd_err_check_; }
};
#include "_packet.cpp.inc"
#endif // CODETEST_PACKET_PROCESSING_PACKET_DEFINITIONS_PACKET_H | true |
1c8eb87c9335a905dab9e4b152350c7a965d4281 | C++ | mszkowalik/FilterBank | /Effect.cpp | UTF-8 | 1,053 | 2.828125 | 3 | [] | no_license | #include "Effect.h"
#include "Delay.h"
#include "FShift.h"
Effect::Effect(FilterSettings _settings, Effect* _child)
{
settings = _settings;
child = _child;
}
Effect::Effect(Effect * _effect)
{
}
Effect::~Effect()
{
if (child)
delete child;
}
ParameterList Effect::getParamsList()
{
return ParamsList;
}
Effect * Effect::lastChild(Effect * parent)
{
Effect* ret = parent;
while (ret)
{
if (ret->child)
ret = ret->child;
else return ret;
}
return nullptr; // never gona reach this point if parent exists
}
void Effect::setParameter(string Name, sampleInter_t value)
{
ParamsList.setParameter(Name, value);
}
void Effect::setParamsList(ParameterList _list)
{
ParamsList = _list ;
}
Effect * Effect::EffectFactory(ParameterList params, Effects type, FilterSettings settings)
{
Effect* ret = nullptr;
switch (type)
{
case Effects::Effect_Delay:
ret = new Delay(settings, nullptr, params);
break;
case Effects::Effect_FShift:
ret = new FShift(settings, nullptr, params);
break;
default:
break;
}
return ret;
} | true |
91e13cbc618c99d9d4268ed0eb1dd7e793dbcd79 | C++ | trantrangntt/TINC | /thi/A/sg.cpp | UTF-8 | 576 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
int so(int n)
{
int a,m=1,so=1,i=1,s[10];
while(n>0)
{
s[i]=n%10;
n/=10;
i++;
}
for(int j=1;j<i-1;j++)
{
if(s[j]>=s[j+1]) return 0;
}
return 1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int a,b,dem=0;
scanf("%d %d",&a,&b);
for(int i=a;i<=b;i++)
{
if(so(i)) dem++;
}
printf("%d",dem);
printf("\n");
}
}
| true |
c2859f4ef870bbbe995f921feec927c3a783c335 | C++ | Annadd/cpp-example | /src/dtlib/DynamicArray.h | UTF-8 | 1,787 | 3.359375 | 3 | [] | no_license | #ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H
#include "Array.h"
namespace DTLib
{
template <typename T>
class DynamicArray : public Array<T>
{
protected:
int mLength;
T* copy(T* array, int len, int newLen)
{
T* ret = new T[newLen];
if(ret){
int size = (len < newLen) ? len : newLen;
for(int i = 0; i < size; i++){
ret[i] = array[i];
}
}
return ret;
}
void update(T* array, int length)
{
if(array){
T* temp = this->mArray;
this->mArray = array;
this->mLength = length;
delete [] temp;
} else {
THROW_EXCEPTION(NoEnoughMemeoryException, "No memory to update DynamicArray object...");
}
}
void init(T* array, int length)
{
if(array){
this->mArray = array;
this->mLength = length;
} else {
THROW_EXCEPTION(NoEnoughMemeoryException, "No memory to init DynamicArray object...");
}
}
public:
DynamicArray(int length = 0)
{
init(new T[length], length);
}
DynamicArray(const DynamicArray<T>& obj)
{
init(copy(obj.mArray, obj.mLength, obj.mLength), obj.mLength);
}
DynamicArray<T>& operator=(const DynamicArray<T>& obj)
{
if(this != &obj){
update(copy(obj.mArray, obj.mLength, obj.mLength), obj.mLength);
}
return *this;
}
int length() const
{
return mLength;
}
void resize(int length)
{
if(length != mLength){
update(copy(this->mArray, mLength, length), length);
}
}
~DynamicArray()
{
delete [] this->mArray;
}
};
}
#endif//DYNAMICARRAY_H
| true |
205d856b6ef28d2a164bd90b04791d9b744dc89b | C++ | jalayonm/Programacion-clases | /2020-09-09.git/funcion3.cpp | UTF-8 | 357 | 3.328125 | 3 | [] | no_license |
#include<iostream>
#include<cstdlib>
double average(double x, double y);
int main( int argc, char *argv[])
{
double x = std::atof(argv[1]);
double y = std::atof(argv[2]);
double z=0;
z = average( x,y);
std::cout << z << std::endl;
return 0;
}
double average(double x, double y)
{
double result = 0;
result = 0.5*(x+y);
return result;
} | true |
2da8e2d7e96fa276d689f729f79245ced89ba1df | C++ | wentwrong/hashing-result | /src/argparser.cpp | UTF-8 | 775 | 2.578125 | 3 | [] | no_license | #include "argparser.hpp"
ArgParser::ArgParser(int argc, char *argv[])
{
if(argc < 3) {
std::cerr << "Incorrect number of parameters." << std::endl
<< "Usage: ./hashing-result-mt input output 1024" << std::endl;
exit(1);
}
this->input_fn = argv[1];
this->output_fn = argv[2];
if(argc >= 3) {
try {
this->block_size = std::stoul(argv[3]);
} catch (...) {
this->block_size = DEFAULT_BLOCK_SIZE;
}
} else
this->block_size = DEFAULT_BLOCK_SIZE;
}
std::string ArgParser::get_input_fn()
{
return this->input_fn;
}
std::string ArgParser::get_output_fn()
{
return this->output_fn;
}
unsigned long ArgParser::get_block_size()
{
return this->block_size;
}
| true |
15c83669e195129df7deddfa07a33fc737346f8f | C++ | aravynn/QBWebPortal | /QBWebPortal/QBXMLSync.h | UTF-8 | 4,209 | 2.5625 | 3 | [] | no_license | #pragma once
/**
*
* QBXMLSync controls the actual processing functions required for the transfer of data from Quickbooks to the database.
* Additionally, this class will also manage any required inserts and updates to the file, as per the given data.
* This class is unlikely to store a great deal of held information.
*
*/
// std functions
#include <vector>
#include <string>
#include <sstream> // for date generator.
#include <iomanip> // setw
#include <memory> // weak, shared pointers.
#include <map> // will be used for back and forth data transfer.
// app classes.
#include "SQLControl.h"
#include "XMLParser.h"
#include "XMLNode.h"
#include "QBRequest.h"
enum class SQLTable {
inventory,
customer,
purchaseorder,
salesorder,
invoice,
estimate
};
// used for data transfer to and from the new thread.
struct TransferStatus {
int inventory{ -1 };
int customers{ -1 };
int salesorders{ -1 };
int estimates{ -1 };
int invoices{ -1 };
int minmax{ -1 };
};
class QBXMLSync
{
private:
SQLControl m_sql; // connects to SQL and handles any collection and return.
QBRequest m_req; // connects to QB and handles any collection and return.
std::shared_ptr<bool> m_isActive; // bool for determining the status of the run. will be defaulted to TRUE externally.
std::shared_ptr<TransferStatus> m_status;
void updateInventoryMinMax(std::string ListID, int min); // per line, update the min/max, to minimum, 0.
bool getIteratorData(XMLNode& nodeRet, std::list<int> path, std::string& iteratorID, int& statusCode, int& remainingCount);
int iterate(std::string& returnData, std::string& iteratorID, std::string table, int maximum = 100, std::string date = "NA", bool useOwner = false, bool modDateFilter = false, bool orderLinks = false);
bool queryAll(std::string& returnData, std::string table);
int addAddress(XMLNode& addressNode, std::string customerListID);
bool isActive();
public:
QBXMLSync(std::string QBID, std::string appName, std::string password, std::shared_ptr<TransferStatus> status = nullptr, std::shared_ptr<bool> active = nullptr); // generate the SQL and request items.
std::shared_ptr<TransferStatus> getStatus() { return m_status; }
bool getInventory();
bool getInventory_old(); // Remove once testing confirmed. ---------------------------------------------------------------------------------------------!!
bool getSalesOrders();
bool getSalesOrders_old(); // Remove once testing confirmed. ---------------------------------------------------------------------------------------------!!
bool getEstimates();
bool getEstimates_old(); // Remove once testing confirmed. ---------------------------------------------------------------------------------------------!!
bool getInvoices();
bool getInvoices_old(); // Remove once testing confirmed. ---------------------------------------------------------------------------------------------!!
bool getCustomers();
bool getCustomers_old(); // for removal. . -----------------------!!
bool getPriceLevels();
bool getSalesTerms();
bool getTaxCodes();
bool getSalesReps();
// bool getShippingTypes(); // not sure if required.
bool updateMinMax(); // update the minmax for all items.
bool updateMinMaxBatch(int batch = 100); // update the minmax for all items, in pre-grouped sets. This may not be at all valid.
bool updateMinMaxInventory(const std::string& listID, std::string& editSequence, int reorderPoint = -1, bool max = false);
bool updateMinMaxInventory(const std::vector<std::string>& listID, std::vector<std::string>& editSequence, std::vector<int> newValue, bool max = false); // max is assumed for ALL items.
bool updateInventoryPartnumbers(int limit = 100, std::string type = "ItemInventoryMod"); // limited update function for all parts. Just a one-off.
bool updatePartsBatch(const std::vector<std::string>& listID, std::vector<std::string>& editSequence, std::vector<std::string> newValue, std::string requestType); // limited update function continuance.
bool timeReset(SQLTable table, int Y = 1970, int M = 1, int D = 1, int H = 12, int m = 0, int S = 0);
bool timeReset(SQLTable table, std::string datetime = "1970-01-01 12:00:00");
bool fullsync();
};
| true |
99cec13e9bc3cc1bc42218b9f5cc0166f9db2703 | C++ | riera90/poo | /pr1/ej3-4-5/juego.cc | UTF-8 | 1,155 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | #include "dados.h"
#include <iostream>
int main(int argc, char const *argv[])
{
Dados d;
int v[4];
std::cout<<"dice 1: >'"<<d.getDado1()<<"'\n";
std::cout<<"dice 2: >'"<<d.getDado2()<<"'\n\n";
d.getUltimos1(v);
for (int i = 0; i < 5; ++i)
{
std::cout<<"v["<<i<<"]="<<v[i]<<"\n";
}
std::cout<<"\n";
d.getUltimos2(v);;
for (int i = 0; i < 5; ++i)
{
std::cout<<"v["<<i<<"]="<<v[i]<<"\n";
}
std::cout<<"\ntrow\n\n";
for (int i = 0; i < 6; ++i)
{
d.trow();
std::cout<<"dice 1: >'"<<d.getDado1()<<"'\n";
std::cout<<"dice 2: >'"<<d.getDado2()<<"'\n\n";
d.getUltimos1(v);
for (int i = 0; i < 5; ++i)
{
std::cout<<"v["<<i<<"]="<<v[i]<<"\n";
}
std::cout<<"\n";
d.getUltimos2(v);
for (int i = 0; i < 5; ++i)
{
std::cout<<"v["<<i<<"]="<<v[i]<<"\n";
}
}
/*
std::cout<<"trows dice 1: >'"<<d.getLanzamientos1()<<"'\n";
std::cout<<"trows dice 2: >'"<<d.getLanzamientos2()<<"'\n\n";
std::cout<<"sum dice 1: >'"<<d.get_sum_d1()<<"'\n";
std::cout<<"sum dice 2: >'"<<d.get_sum_d2()<<"'\n\n";
std::cout<<"mean dice 1: >'"<<d.getMedia1()<<"'\n";
std::cout<<"mean dice 2: >'"<<d.getMedia2()<<"'\n\n";
*/
} | true |
c748527eddfd6a99d24d3db246fce3ce6eea1d18 | C++ | duckhee/opencv_study | /chapter2/ex2-55/ex2_55.cpp | UTF-8 | 1,642 | 3 | 3 | [] | no_license | #include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
template <class T>
T* vec_to_arr(vector<T> v1) //1D array
{
T* v2 = new T[v1.size()];
for(int i = 0; i < v1.size(); i++)
{
v2[i] = v1[i];
}
return v2;
}
template<class T>
void delete_arr(T* arr)
{
delete[] arr;
}
int main()
{
Mat dstImage(512, 512, CV_8UC3, Scalar(255, 255, 255));
vector<Point> contour;
contour.push_back(Point(100, 100));
contour.push_back(Point(200, 100));
contour.push_back(Point(200, 200));
contour.push_back(Point(100, 200));
int npts[] = {contour.size()};
int i;
Point *P1 = &contour[0];
for(i = 0; i < contour.size(); i++)
{
cout<<"P1["<<i<<"] = "<<P1[i]<<endl;
}
//polylines(dstImage, (const Point**)&P1, npts, 1, true, Scalar(0, 0, 255));
Point *P2 = (Point *)Mat(contour).data;
for(i = 0; i < contour.size(); i++)
{
cout<<"P2["<<i<<"] = "<<P2[i]<<endl;
}
//polylines(dstImage, (const Point**)&P2, npts, 1, true, Scalar(0, 0, 255));
Point P3[4];
copy(contour.begin(), contour.end(), P3);
for(i = 0; i < contour.size(); i++)
{
cout<<"P3["<<i<<"] = "<<P3[i]<<endl;
}
//Point *ptrP3 = P3;
//polylines(dstImage, (const Point**)&P3, npts, 1, true, Scalar(0, 0, 255));
Point *P4 = vec_to_arr<Point>(contour);
for(i = 0; i < contour.size(); i++)
{
cout<<"P4["<<i<<"] = "<<P4[i]<<endl;
}
polylines(dstImage, (const Point**)&P4, npts, 1, true, Scalar(0, 0, 255));
delete_arr<Point>(P4);
imshow("dstImage", dstImage);
waitKey();
return 0;
} | true |
b01e4fba2551fbb8bcbda31d524d49129d0be283 | C++ | kslyre/optimizations | /functors.h | UTF-8 | 1,150 | 2.53125 | 3 | [] | no_license | #ifndef FUNCTORS_H
#define FUNCTORS_H
#include "derivable.h"
#include <QVector2D>
#include <QVector3D>
#include <structs.h>
class SimpleFunctor {
QVector<QVector2D> point1;
QVector<QVector2D> point2;
QVector2D center;
public:
SimpleFunctor();
SimpleFunctor(QVector<QVector2D> point1, QVector<QVector2D> point2, QVector2D center, ProblemVector probVector);
void operator()(ProblemVector pv, int index);
int elems() { return 2; }
int lengthVector() { return point1.length(); }
int lengthParams() { return probVector.count(); }
ProblemVector grad(int index, int indexElement);
ProblemVector probVector;
Derivable f1(int index, int indexParam, ProblemVector pv, int val);
double f(ProblemVector pv);
double innerF(int index, int elem);
};
class Functor
{
QVector<QVector3D> points1;
QVector<QVector3D> points2;
QVector3D center2;
public:
Functor();
Functor(QVector<QVector3D> points1, QVector<QVector3D> point2, ProblemVector pv);
int elems();
int lengthVector();
int lengthParams();
double func();
double innerFunc();
};
#endif // FUNCTORS_H
| true |
fde8ac59589bcf36fbafda95bfeae0d572ec0092 | C++ | JohnHonkanen/NBody | /nbody/Body.cpp | WINDOWS-1252 | 4,072 | 2.921875 | 3 | [] | no_license | /*
Name: John Honkanen
Student ID: B00291253
I declare that the following code was produced by John Honkanen (B00291253), Adam Stanton (B00266256) and Kyle Pearce (B00287219) as a group assignment for the IPM module and that this is our own work.
I am aware of the penalties incurred by submitting in full or in part work that is not our own and that was developed by third parties that are not appropriately acknowledged.
This file was created by John Honkanen (B00291253).
*/
#include "Body.h"
Body::Body()
{
}
/*
@param p Position
@param v Velocity
@param a Acceleration
@param m Mass
@param r Radius
@param c Color
*/
Body::Body(dvec2 p, dvec2 v, dvec2 a, double m, double r, vec3 c)
{
this->position = p;
this->velocity = v;
this->acceleration = v;
this->force = dvec2(0);
this->mass = m;
this->radius = r;
this->color = c;
gravitate = true;
staticBody = false;
canEat = true;
}
Body::~Body()
{
}
/*
Calculate the forces affecting our particle, and add it to our velcoity (Verlett method);
Newton's Gravitational acceleration (Gravity, James Brown(1986), pg 12)
@param b Body
@param dt deltaTime
*/
void Body::calculateForce(Body b)
{
if (gravitate) {
dvec2 DeltaPos = normalize(b.getP0() - this->position);
double distSqrd = dot(DeltaPos, DeltaPos);
//Calculate Acceleration. Can ignore mass of own body.
double A = (GRAV_CONST*b.getMass()) / (distSqrd + EPS*EPS);
this->force += A * DeltaPos;
}
}
/*
Verlett velocity solver for motion
@param dt timestep/delta time
*/
void Body::verlettStep(double dt)
{
//Calculate position + 1
this->position += dt * velocity+ 0.5f * dt * dt * acceleration;
//Calculate v+
dvec2 vhalf = velocity + (0.5*dt*acceleration);
//Compute ai+1
this->acceleration = force *dt;
//Compute v+1
this->velocity = vhalf + (0.5*dt*acceleration);
}
/*
Update our position and move forward (Verlett method);
@param dt deltaTime
*/
void Body::update(double dt)
{
if(!staticBody)
this->verlettStep(dt);
}
/*
Resets temporary acceleration/force
*/
void Body::resetForce()
{
this->force = dvec2(0);
}
/*
Renders using our renderer
*/
void Body::render(Renderer * r)
{
r->renderCircle(dvec3(this->position.x, this->position.y, 0), this->radius, 30, this->color);
}
/*
Circle-circle Collision
@param Body to check
*/
bool Body::checkCollision(Body b)
{
if (!canEat)
return false;
dvec2 op = b.getP0(); //Other Body's Position
double dx = op.x - this->position.x;
double dy = op.y - this->position.y;
dvec2 deltaDist = b.getPosition() - this->position;
double distSqrd = dot(deltaDist, deltaDist);
double radiusSqrd = (this->radius + b.getRadius()) * (this->radius + b.getRadius());
if (distSqrd < radiusSqrd)
return true;
return false;
}
/*
Calculates the inelastic Collision while maintaining momentum
The Law of Momentum Conservation (https://www.sciencetopia.net/physics/linear-momentum-principles)
@param Colliding Body
*/
void Body::inelasticCollision(Body b)
{
//Momentum for this Body
dvec2 thisMomentum = velocity * mass;
//Momentum for other Body
dvec2 otherMomentum = b.getCurrentVelocity() * b.getMass();
//Total Mass
double OneOvertotalMass = 1/(this->mass + b.getMass());
//Final Velocity
this->velocity = (thisMomentum + otherMomentum) * OneOvertotalMass;
}
/*
Add mass and radius from the a body
@param b Body
*/
void Body::add(Body b)
{
this->mass += b.getMass();
this->radius = sqrt((b.getRadius() * b.getRadius()) + (this->radius * this->radius));
if (this->color.g < 0.6) {
this->color.g += 0.05;
}
else if (this->color.b < 1) {
this->color.b += 0.05;
}
else if (this->color.r < 1) {
this->color.r += 0.05;
}
}
/*
*/
dvec2 Body::getP0()
{
return this->position;
}
dvec2 Body::getPosition()
{
return this->position;
}
/*
Get Mass
*/
double Body::getMass()
{
return this->mass;
}
/*
Get Radius
*/
double Body::getRadius()
{
return this->radius;
}
/*
Get Colour
*/
vec3 Body::getColor()
{
return this->color;
}
/*
Get Current Acceleration
*/
dvec2 Body::getCurrentAccleration()
{
return this->acceleration;
}
dvec2 Body::getCurrentVelocity()
{
return this->velocity;
}
| true |
28100ce34b93c299855bf278ab0378986f668708 | C++ | CISVVC/CIS202-GraphicsView | /mainwindow.cpp | UTF-8 | 3,074 | 2.578125 | 3 | [] | no_license | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include<cmath>
#include "axis.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->graphicsView->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
m_scene = new QGraphicsScene(QRectF(-360,-360,360,360));
ui->graphicsView->setScene(m_scene);
m_xres = 2;
m_yres = 100;
m_speed = 600;
drawCircle();
makeWaves();
for(auto w : m_waves) {
m_scene->addItem(w);
w->setPos(w->pos()-QPointF(600,100));
}
drawAxes();
drawLegend();
m_timer = new QTimer();
connect(m_timer,&QTimer::timeout,this,&MainWindow::nextStep);
m_timer->start(50);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::drawAxes() {
//m_scene->addLine(-600,-100,m_xres * 360,-100);
//m_scene->addLine(-600,m_yres-100,-600,-m_yres-100);
Axis *axis = new Axis(m_xres,m_yres*2,8,8);
m_scene->addItem(axis);
axis->setPos(-600,-100);
}
void MainWindow::drawCircle() {
m_circle = new CircleAnim();
m_scene->addItem(m_circle);
m_circle->setPos(QPointF(-600,-3.5*m_yres));
}
void MainWindow::makeWaves() {
m_waves.append(
new Wave("sine(d)",[] (double d){return sin(d);},QColor(0x8a,0x2b,0xe2)) // blueviolet
);
m_waves.append(
new Wave("2*sine(d)",[] (double d){return 2*sin(d);},QColor(0,0,0x8b)) // DarkBlue
);
m_waves.append(
new Wave("sine(2*d)",[] (double d){return sin(2*d);})
);
m_waves.append(
new Wave("sine(110*d)",[] (double d){return sin(110*d);},QColor(0,0xce,0xd1)) // DarkTurquoise
);
m_waves.append(
new Wave("sine(880*d)",[] (double d){return sin(880*d);},QColor(0,0x0,0x8b)) // DarkBlue
);
m_waves.append(
new Wave("cosine(d)",[](double d){return cos(d);},QColor(255,128,0))
);
m_waves.append(
new Wave("cosine(3*d)",[](double d){return cos(3*d);},QColor(255,128,0))
);
}
void MainWindow::drawLegend() {
int i=0;
int cx = 15;
int offset = -500;
for(auto w : m_waves) {
LegendItem *t = new LegendItem(w);
connect(t,&LegendItem::clicked,this,&MainWindow::setWaveVisible);
t->setPos(-600,offset+cx*i-11);
m_scene->addItem(t);
if(i != 0) {
t->on(false);
setWaveVisible(t);
}
i++;
}
}
void MainWindow::setWaveVisible(LegendItem *legend) {
if(legend->isOn()) {
legend->wave()->setVisible(true);
}
else {
legend->wave()->setVisible(false);
}
}
void MainWindow::nextStep() {
int inc = 5;
for(auto w : m_waves) {
w->nextStep(inc);
}
m_circle->nextStep(inc);
m_scene->update();
}
void MainWindow::setSpeed(int speed) {
m_speed = speed;
m_timer->setInterval(speed);
}
void MainWindow::resizeEvent(QResizeEvent *event) {
QMainWindow::resizeEvent(event);
//ui->graphicsView->fitInView(ui->graphicsView->sceneRect(), Qt::KeepAspectRatio);
}
| true |
8810f8a1f9389925976a4b8771c42de4a5391932 | C++ | 0xA1MN/Problem_Solving | /URI Online Judge/1047 - Game Time with Minutes.cpp | UTF-8 | 689 | 2.921875 | 3 | [] | no_license | // https://www.urionlinejudge.com.br/judge/en/problems/view/1047
// handle 24 hour case
#include <bits/stdc++.h>
using namespace std;
int main() {
int start_h, end_h, start_m, end_m, duration_h, duration_m;
cin>>start_h>>start_m>>end_h>>end_m;
duration_h = end_h - start_h;
if (duration_h < 0) {
duration_h = 24 + (end_h - start_h);
}
duration_m = end_m - start_m;
if (duration_m < 0) {
duration_m = 60 + (end_m - start_m);
duration_h--;
}
if (start_h == end_h && start_m == end_m) {
cout<<"O JOGO DUROU 24 HORA(S) E 0 MINUTO(S)"<<endl;
} else {
cout<<"O JOGO DUROU "<<duration_h<<" HORA(S) E "<<duration_m<<" MINUTO(S)"<<endl;
}
return 0;
} | true |
cb7e5a6f5726027905d8b4d18bf4d3f16dc6933f | C++ | Kirthik13/LeetCode-1 | /generateTrees.cpp | UTF-8 | 1,127 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <vector>
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
std::vector<TreeNode*> generateTrees(int beg, int end)
{
std::vector<TreeNode*> res;
if (beg > end)
{
res.push_back(NULL);
}
for (int i = beg; i <= end; ++i)
{
std::vector<TreeNode*> left = generateTrees(beg, i-1);
std::vector<TreeNode*> right = generateTrees(i+1, end);
for (int l = 0; l < left.size(); ++l)
{
for (int r = 0; r < right.size(); ++r)
{
TreeNode* p = new TreeNode(i);
p->left = left[l];
p->right = right[r];
res.push_back(p);
}
}
}
return res;
}
public:
std::vector<TreeNode*> generateTrees(int n)
{
return generateTrees(1, n);
}
};
int main(int argc, char** argv)
{
Solution sln;
return 0;
}
| true |
ac19ad3958510a301fa3fbde29dea733d249eb2f | C++ | eliadra/Laba4 | /Лабораторная№3 (4)/Лабораторная№3/Tokar.cpp | WINDOWS-1251 | 489 | 2.71875 | 3 | [] | no_license | #include "StdAfx.h"
#include <iostream>
#include "Tokar.h"
using namespace std;
Tokar::Tokar(void)
{
cout << " " << endl;
}
void Tokar::setstaz(int x)
{
this->staz = x;
}
void Tokar::getstaz()
{
cout << " : " << this->staz << endl;
}
Tokar::~Tokar()
{
cout << " " << endl;
}
void Tokar::history()
{
cout << " ";
}
| true |
ced2b63f8e2e4cc31ce081c90b2c1d4c40426abc | C++ | luchunabf/Cplusplus | /test_7_25_2/test_7_25_2/virtual.cpp | GB18030 | 1,186 | 3.109375 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class Base1
{
public:
virtual void func1()
{
cout << "Base1:: func1()" << endl;
}
virtual void func2()
{
cout << "Base1:: func2()" << endl;
}
private:
int _b1;
char _b2;
double _b3;
};
class Base2
{
public:
virtual void func1()
{
cout << "Base2:: func1()" << endl;
}
virtual void func2()
{
cout << "Base2:: func2()" << endl;
}
private:
int _b4;
double _b5;
char _b6;
};
class Drived :public Base1, public Base2
{
public:
virtual void func1()
{
cout << "Drived::func1()" << endl;
}
virtual void func3()
{
cout << "Drived:: func3()" << endl;
}
private:
int _d1;
};
int main()
{
Drived d1;
cout << sizeof(d1) << endl;//20 ָ̳࣬롾̳м࣬мָ롿ิƻ
return 0;/////////////̳м࣬Ƽָ룬Լ麯д˾ǣδдһ̳ӡ
////////////////////// ԼС̳м࣬ͼӼָ룬ճԱӺͼ
} | true |
64b80ccc193da24bbbeb807d43af7f4c284c2d8e | C++ | A-STAR0/hackerrank-solutions-1 | /DataStructures/LinkedLists/print-the-elements-of-a-linked-list.cpp | UTF-8 | 348 | 3.4375 | 3 | [
"MIT"
] | permissive | /*
Print elements of a linked list on console
head pointer input could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
void Print(Node *head)
{
Node* tracker = head;
while(tracker) {
cout << tracker->data << endl;
tracker = tracker->next;
}
}
| true |
8026c66b176927852500b21ab6369a78d0d325b0 | C++ | bog2k3/boglfw | /src/OSD/ScaleDisplay.cpp | UTF-8 | 2,581 | 2.546875 | 3 | [
"MIT"
] | permissive |
#include <boglfw/OSD/ScaleDisplay.h>
#include <boglfw/renderOpenGL/Viewport.h>
#include <boglfw/renderOpenGL/Camera.h>
#include <boglfw/renderOpenGL/Shape2D.h>
#include <boglfw/renderOpenGL/GLText.h>
#include <boglfw/renderOpenGL/RenderContext.h>
#include <glm/vec3.hpp>
#include <math.h>
#include <stdio.h>
static const glm::vec3 LINE_COLOR(0.8f, 0.8f, 0.8f);
static const glm::vec3 TEXT_COLOR(1.f, 1.f, 1.f);
ScaleDisplay::ScaleDisplay(FlexCoordPair pos, int maxPixelsPerUnit)
: pos_(pos)
, segmentsXOffset(50)
, segmentHeight(10)
, labelYOffset(-12)
, m_MaxSize(maxPixelsPerUnit)
{
}
void ScaleDisplay::draw(RenderContext const& ctx) {
float pixelsPerUnit = ctx.viewport().camera().getOrthoZoom();
int exponent = 0;
if (pixelsPerUnit > m_MaxSize) {
// small scale
while (pixelsPerUnit > m_MaxSize) {
exponent--;
pixelsPerUnit /= 10;
}
} else if (pixelsPerUnit < m_MaxSize) {
// large scale
while (pixelsPerUnit*10 <= m_MaxSize) {
exponent++;
pixelsPerUnit *= 10;
}
}
float segIncrement = 1.0f;
int segments = (int) floor(m_MaxSize / pixelsPerUnit);
if (segments == 1) {
segments = 5;
segIncrement = 0.2f;
/*} else if (segments == 2) {
segments = 8;
segIncrement = 0.25f;*/
} else if (segments <= 3) {
segments *= 2;
segIncrement = 0.5f;
}
int nVertex = 1 + segments * 3;
float cx = (float)pos_.x.get(FlexCoord::X_LEFT, ctx.viewport()) + segmentsXOffset;
float cy = (float)pos_.y.get(FlexCoord::Y_TOP, ctx.viewport()) - 1;
glm::vec2 vList[31]; // 31 is max vertex for max_seg=10
for (int i=0; i<segments; i++) {
int localSegHeight = (int)(i*segIncrement) == (i*segIncrement) ? segmentHeight : segmentHeight / 2;
vList[i*3+0] = glm::vec2(cx, cy-localSegHeight);
vList[i*3+1] = glm::vec2(cx, cy);
cx += (float)pixelsPerUnit * segIncrement;
vList[i*3+2] = glm::vec2(cx, cy);
}
vList[nVertex-1] = glm::vec2(cx, cy-segmentHeight);
Shape2D::get()->drawLineStrip(vList, nVertex, LINE_COLOR);
char scaleLabel[100];
snprintf(scaleLabel, 100, "(10^%d)", exponent);
GLText::get()->print(scaleLabel, pos_.get(ctx.viewport()), 14, TEXT_COLOR);
for (int i=0; i<segments+1; i++) {
snprintf(scaleLabel, 100, "%g", i*segIncrement);
int localSegHeight = (int)(i*segIncrement) == (i*segIncrement) ? 0 : segmentHeight / 2;
GLText::get()->print(scaleLabel,
pos_.get(ctx.viewport()) + glm::vec2{ -localSegHeight + segmentsXOffset+i*(int)(pixelsPerUnit*segIncrement),
-10 + localSegHeight },
12, TEXT_COLOR);
}
}
| true |
9fee367c636358b64f4d1feeaab25483d4f6a6c4 | C++ | devrangel/LearnOpenGL | /src/camera.h | UTF-8 | 2,514 | 2.96875 | 3 | [] | no_license | #pragma once
#include "GLFW/glfw3.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
const float YAW = -90.0f;
const float PITCH = 0.0f;
const float SPEED = 2.5f;
const float SENSITIVY = 0.000005f;
const float ZOOM = 45.0f;
class Camera
{
public:
glm::vec3 position;
glm::vec3 front;
glm::vec3 up;
Camera(glm::vec3 cameraPos, glm::vec3 cameraFront, glm::vec3 cameraUp, float yaw = YAW, float pitch = PITCH)
: position(cameraPos), front(cameraFront), up(cameraUp),
m_DeltaTime(0.0f), m_LastFrame(0.0f),
m_MovementSpeed(SPEED), m_MouseSensity(SENSITIVY), m_Zoom(ZOOM),
m_Yaw(yaw), m_Pitch(pitch)
{
this->updateCameraVectors();
}
glm::mat4 getViewMatrix() const
{
return glm::lookAt(this->position, this->position + this->front, this->up);
}
void processKeyboard(GLFWwindow* window)
{
// Calculate de delta time in order to make a smooth moviment
float currentFrame = (float)glfwGetTime();
this->m_DeltaTime = currentFrame - this->m_LastFrame;
this->m_LastFrame = currentFrame;
const float cameraSpeed = this->m_MovementSpeed * m_DeltaTime;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
position += cameraSpeed * front;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
position -= cameraSpeed * front;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
position -= glm::normalize(glm::cross(front, up)) * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
position += glm::normalize(glm::cross(front, up)) * cameraSpeed;
}
void processMouseMovement(float xoffset, float yoffset, bool constrainPitch = true)
{
xoffset *= this->m_MouseSensity;
yoffset *= this->m_MouseSensity;
this->m_Yaw += xoffset;
this->m_Pitch += yoffset;
if (constrainPitch)
{
if (this->m_Pitch > 89.0f)
this->m_Pitch = 89.0f;
if (this->m_Pitch < -89.0f)
this->m_Pitch = -89.0f;
}
this->updateCameraVectors();
}
private:
float m_DeltaTime;
float m_LastFrame;
float m_MouseSensity;
float m_MovementSpeed;
float m_Zoom;
float m_Yaw;
float m_Pitch;
void updateCameraVectors()
{
glm::vec3 frontVec;
frontVec.x = cos(glm::radians(this->m_Yaw)) * cos(glm::radians(this->m_Pitch));
frontVec.y = sin(glm::radians(this->m_Pitch));
frontVec.z = sin(glm::radians(this->m_Yaw)) * cos(glm::radians(this->m_Pitch));
this->front = glm::normalize(frontVec);
glm::vec3 right = glm::normalize(glm::cross(this->front, this->up));
this->up = glm::normalize(glm::cross(right, this->front));
}
}; | true |
398aba5927d9b8e563f464e04d203a491b0f65e8 | C++ | migue27au/ESP32HTTP | /ESP32HTTP/examples/ESP32HTTP_example/ESP32HTTP_example.ino | UTF-8 | 1,966 | 2.859375 | 3 | [] | no_license | /*
* EXAMPLE OF ESP32HTTP library
* Author: migue27au --> https://github.com/migue27au
* Last Update: 18/02/2021
*/
#include "ESP32HTTP.h"
char* server = "www.arduino.cc";
String path = "/asciilogo.txt";
char* ssid = "SSID";
char* password = "SSID PASSWORD";
HTTP http(server, HTTP_PORT);
//HTTP http(server, HTTP_PORT, true); //If you want to see the logger output. (Serial Speed is 115200 bauds)
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
int counter = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
/*
0: WL_IDLE_STATUS when Wi-Fi is changing state
1: WL_NO_SSID_AVAIL if the configured SSID cannot be reached
3: WL_CONNECTED after connection is established
4: WL_CONNECT_FAILED if the password is incorrect
6: WL_DISCONNECTED if the module is not configured in station mode
*/
Serial.print(WiFi.status());
counter++;
if(counter>=60){ //after 30 seconds timeout - reset board
ESP.restart();
}
}
Serial.println();
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
HTTPRequest request(HTTP_GET, path);
//HTTPRequest request(HTTP_POST, path, "your payload for post request here");
request.setHeader("User-Agent", "ESP32");
HTTPResponse response = http.sendRequest(request);
int responseCode = response.getResponseCode();
Serial.print("Responde Code: ");
Serial.println(responseCode);
Serial.println("Payload:");
Serial.println(response.getPayload());
if(responseCode == HTTP_RESPONSE_OK){
Serial.println("Successfull response");
} else{
Serial.println("Wrong response");
}
}
void loop() {
// put your main code here, to run repeatedly:
}
| true |
1a01235b170e42ebfdfe34d0497d8a6ffd325aae | C++ | kunmukh/CS-475 | /CS-475/InClass-Assignment/CS215/Practical_Exam_1/practical1/problem1.cpp | UTF-8 | 1,129 | 3.421875 | 3 | [] | no_license | //Kunal Mukherjee
//Practical Exam
//Problem 1
//14th Feb, 2016
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int Ackermann(int m, int n);
int main (int argc, char *argv[])
{
if (argc != 3)
{
cout << "Usage: " << argv[0] << "Inputfile Outfile" << endl;
}
ifstream infile (argv[1]);
if (!infile)
{
cout << "Error opening input file:" << argv[1] << endl;
exit(1);
}
ofstream outfile (argv[2]);
if (!outfile)
{
cout << "Error opening output file:" << argv[2] << endl;
exit(1);
}
int m;
int n;
int ackermann;
while (infile >> m)
{
infile >> n;
ackermann = Ackermann(m,n);
outfile << "Ackermann(" << m << "," << n <<") is "
<< ackermann << endl;
}
infile.close();
outfile.close();
return 0;
}
int Ackermann(int m, int n)
{
if (m == 0)
{
return n + 1;
}
if ( m > 0 && n == 0)
{
return Ackermann(m-1, 1);
}
if ( m > 0 && n > 0)
{
return Ackermann(m-1, Ackermann(m, n-1));
}
else
return 0;
}
| true |
6197b7d597d08ac593c13cf493f3b7a3e739971e | C++ | kloetzl/libdna | /test/Tdnax_revcomp.cxx | UTF-8 | 2,317 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "Tcommon.h"
#include <assert.h>
#include <catch2/catch.hpp>
#include <dna.h>
#include <string.h>
#include <string>
TEST_CASE("Basic revcomp checks")
{
auto forward = repeat("ACGT", 10);
auto buffer = new char[forward.size() + 1];
memset(buffer, 0, forward.size() + 1);
auto end_ptr = dna4_revcomp(dna::begin(forward), dna::end(forward), buffer);
REQUIRE(static_cast<size_t>(end_ptr - buffer) == forward.size());
REQUIRE(forward == buffer);
end_ptr = dnax_revcomp(
dnax_revcomp_table, dna::begin(forward), dna::end(forward), buffer);
REQUIRE(static_cast<size_t>(end_ptr - buffer) == forward.size());
REQUIRE(forward == buffer);
delete[] buffer;
}
TEST_CASE("Mono characters")
{
auto forward = std::string(100, 'A');
auto reverse = std::string(100, 0);
dnax_revcomp(
dnax_revcomp_table, dna::begin(forward), dna::end(forward),
dna::begin(reverse));
REQUIRE(std::string(100, 'T') == reverse);
forward = std::string(100, 'T');
reverse = std::string(100, 0);
dnax_revcomp(
dnax_revcomp_table, dna::begin(forward), dna::end(forward),
dna::begin(reverse));
REQUIRE(std::string(100, 'A') == reverse);
forward = std::string(100, 'C');
reverse = std::string(100, 0);
dnax_revcomp(
dnax_revcomp_table, dna::begin(forward), dna::end(forward),
dna::begin(reverse));
REQUIRE(std::string(100, 'G') == reverse);
forward = std::string(100, 'G');
reverse = std::string(100, 0);
dnax_revcomp(
dnax_revcomp_table, dna::begin(forward), dna::end(forward),
dna::begin(reverse));
REQUIRE(std::string(100, 'C') == reverse);
}
namespace dnax
{
auto
revcomp(const std::string &forward)
{
auto reverse = std::string(forward.size(), 0);
auto end = dnax_revcomp(
dnax_revcomp_table, dna::begin(forward), dna::end(forward),
dna::begin(reverse));
reverse.erase(end - dna::begin(reverse));
return reverse;
}
} // namespace dnax
using namespace std::string_literals;
TEST_CASE("Edge cases")
{
REQUIRE(dnax::revcomp("") == ""s);
REQUIRE(dnax::revcomp("T") == "A"s);
REQUIRE(dnax::revcomp("G") == "C"s);
REQUIRE(dnax::revcomp("C") == "G"s);
REQUIRE(dnax::revcomp("A") == "T"s);
REQUIRE(dnax::revcomp("t") == "a"s);
REQUIRE(dnax::revcomp("g") == "c"s);
REQUIRE(dnax::revcomp("c") == "g"s);
REQUIRE(dnax::revcomp("a") == "t"s);
REQUIRE(dnax::revcomp("_") == ""s);
}
| true |
a0253a4db4b5a86482d31f42311dad96436b803c | C++ | haxpor/cpp_st | /AliasNamespace2.cpp | UTF-8 | 553 | 3.90625 | 4 | [
"MIT"
] | permissive | /**
* Just a simple prove of concept of using `using` to alias struct inside namespace scope.
*/
#include <iostream>
namespace A
{
struct Util
{
static void foo()
{
std::cout << "foo()\n";
}
};
// style 2
// note: use this style to maintain the fully qualified namespace up to this point
using MyUtil = Util;
};
// style 1
// note: use this style to shorten the fully qualified namespace to just "MyUtil"
using MyUtil = A::Util;
int main()
{
// usage of style 1
MyUtil::foo();
// usage of style 2
A::MyUtil::foo();
return 0;
}
| true |
6b6fb80bd90a7cfa4ecff4a0d791af22db755960 | C++ | AABHINAAV/InterviewPrep | /Hashing/Find_Itinerary.cpp | UTF-8 | 1,287 | 3.796875 | 4 | [
"MIT"
] | permissive | //given many routes in the following format:
//from place1 to place 2
//Find the itinerary i.e the complete route using the given data
#include<iostream>
#include<unordered_map>
using namespace std;
//prints the itinerary
/*
we just need to find the starting location.Now the starting location
can never be the destination i.e starting location can't be present in the
value set of keys
So we maek another hash map where the keys will be the values of current map
Then we search for the starting location
*/
void findItinerary(unordered_map<string, string> route){
unordered_map<string, string> reverseMap;
unordered_map<string, string>:: iterator it;
//make the reverse hash map
for(it = route.begin(); it!=route.end(); it++){
reverseMap[it->second] = it->first;
}
//now search for the starting location
for(it = route.begin(); it!=route.end(); it++){
if(reverseMap.find(it->first) == reverseMap.end())
break;
}
//now print the path
int i = 0;
while(i < route.size()){
cout<<it->first<<"-> "<<it->second<<" , ";
it = route.find(it->second);
++i;
}
}
main(){
unordered_map<string, string> route;
route["Chennai"] = "Bangalore";
route["Bombay"] = "Delhi";
route["Goa"] = "Chennai";
route["Delhi"] = "Goa";
findItinerary(route);
}
| true |
af9f26c0d949e6c9ce44c08f08f183ec5870d285 | C++ | wuli2496/OJ | /UVa/1316 Supermarket/Supermarket(贪心+并查集).cpp | UTF-8 | 2,395 | 3.078125 | 3 | [
"Apache-2.0"
] | permissive | /**
* @class AlgoPolicy
* @author wl
* @date 08/12/2019
* @file main.cpp
* @brief
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <memory>
#include <cstring>
using namespace std;
const int MAXN = 10001;
template<typename Result>
class AlgoPolicy
{
public:
virtual ~AlgoPolicy() {}
virtual Result execute() = 0;
};
struct Product
{
int profit;
int deadline;
};
bool cmp(const Product& a, const Product& b)
{
return a.profit > b.profit;
}
class GreedyAlgo : public AlgoPolicy<int>
{
public:
GreedyAlgo(vector<Product>& products)
{
this->products = products;
memset(next, -1, sizeof(next));
}
virtual int execute() override
{
sort(products.begin(), products.end(), cmp);
int totalProfit = 0;
for (size_t i = 0; i < products.size(); ++i)
{
int t = find(products[i].deadline);
if (t)
{
totalProfit += products[i].profit;
next[t] = t - 1;
}
}
return totalProfit;
}
private:
int find(int x)
{
if (next[x] == -1)
{
return x;
}
next[x] = find(next[x]);
return next[x];
}
private:
vector<Product> products;
int next[MAXN];
};
AlgoPolicy<int>* makeAlgo(const string& name, vector<Product>& product)
{
if (name == "greedy")
{
return new GreedyAlgo(product);
}
return nullptr;
}
class Solution
{
public:
Solution(AlgoPolicy<int>* algo)
{
pimpl.reset(algo);
}
int run()
{
return pimpl->execute();
}
private:
shared_ptr<AlgoPolicy<int>> pimpl;
};
int main(int argc, char **argv)
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
#ifndef ONLINE_JUDGE
ifstream fin("F:\\OJ\\uva_in.txt");
streambuf* cinback = cin.rdbuf(fin.rdbuf());
#endif
size_t n;
while (cin >> n)
{
vector<Product> products(n);
for (size_t i = 0; i < n; ++i)
{
cin >> products[i].profit >> products[i].deadline;
}
AlgoPolicy<int>* algo = makeAlgo("greedy", products);
Solution solution(algo);
int ans = solution.run();
cout << ans << endl;
}
#ifndef ONLINE_JUDGE
cin.rdbuf(cinback);
#endif
return 0;
}
| true |
a6d897768ee0fe67eeb0d8e3132f5bd0d9646052 | C++ | sgumhold/cgv | /libs/delaunay/delaunay_mesh_with_hierarchy.h | UTF-8 | 2,364 | 2.8125 | 3 | [] | permissive | #pragma once
#include "mesh_geometry_reference.h"
#include "delaunay_mesh.h"
#include "lib_begin.h"
/// simple triangle mesh data structure using the corner data structure to store neighbor relations
template <class ta_delaunay_mesh = delaunay_mesh<> >
class CGV_API delaunay_mesh_with_hierarchy : public ta_delaunay_mesh
{
public:
/// type of triangle mesh
typedef ta_delaunay_mesh delaunay_mesh_type;
///
typedef typename delaunay_mesh_type::corner corner;
///
typedef typename delaunay_mesh_type::point_type point_type;
///
typedef typename delaunay_mesh_type::coord_type coord_type;
///
typedef typename delaunay_mesh_type::point_location_info point_location_info;
///
typedef typename delaunay_mesh_type::vertex_insertion_info vertex_insertion_info;
///
typedef delaunay_mesh<triangle_mesh<mesh_geometry_reference<coord_type,point_type> > > hierarchy_level_type;
protected:
/// hierarchy of delaunay triangulations used to speed up nearest neighbor search
std::vector<hierarchy_level_type*> H;
///
unsigned int hierarchy_factor;
///
unsigned int next_hierarchy;
public:
/**@name construction*/
//@{
/// construct empty delaunay mesh
delaunay_mesh_with_hierarchy();
/// implement copy constructor to set reference geometries in hierarchy correctly
delaunay_mesh_with_hierarchy(const delaunay_mesh_with_hierarchy& dm);
///
void set_hierarchy_factor(unsigned int hf);
/// configure the hierarchy settings for the given number of points or if not specified for the current number of points
void configure_hierarchy(unsigned int n = -1);
/// reimplement clear to remove all hierarchy levels
void clear();
//@}
/**@name geometric predicates*/
//@{
/// overload point localization to use hierarchy, the ci_start argument is ignored as its existence on the coarsest hierarchy level cannot be guaranteed
point_location_info localize_point(const point_type& p, unsigned int ci_start = 0) const;
/// reimplement nearest neighbor search using the hierarchy
unsigned int find_nearest_neighbor(const point_type& p, unsigned int ci_start = 0) const;
//@}
/// reimplement to construct the hierarchy levels
vertex_insertion_info insert_vertex(unsigned int vi, unsigned int ci_start = 0, std::vector<unsigned int>* touched_corners = 0);
};
#include <cgv/config/lib_end.h> | true |
531ee2eda7b68f09f3fc0cd6f947022f90933aa6 | C++ | iamnwi/papercraft-generator | /src/main.cpp | UTF-8 | 76,262 | 2.53125 | 3 | [] | no_license | // This example is heavily based on the tutorial at https://open.gl
#include <iostream>
#include <math.h>
#include <vector>
#include <list>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <cassert>
#include <iomanip>
// OpenGL Helpers to reduce the clutter
#include "Helpers.h"
// GLFW is necessary to handle the OpenGL context
#include <GLFW/glfw3.h>
// Linear Algebra Library
#include <Eigen/Core>
// Timer
#include <chrono>
typedef std::pair<int, int> Edge;
// Contains the vertex positions
Eigen::MatrixXd V(2,3);
// Contains the per-vertex color
Eigen::MatrixXd C(3,3);
// The view matrix
// Eigen::MatrixXd ViewMat(4,4);
Eigen::MatrixXd ProjectMat(4,4);
// Color, order in Key1 to Key9
Eigen::Vector3i RED(255, 0, 0);
Eigen::Vector3i GREEN(0, 255, 0);
Eigen::Vector3i BLUE(0, 0, 255); // Selected color
Eigen::Vector3i YELLOW(255, 255, 0);
Eigen::Vector3i BLACK(0, 0, 0);
Eigen::Vector3i WHITE(255, 255, 255);
Eigen::Vector3i GREY(128,128,128);
Eigen::Vector3i ORANGE(255, 165, 0);
Eigen::Vector3i PURPLE(160, 32, 240);
Eigen::Vector3i DIMGREY(105,105,105);
Eigen::Vector3i LIGHTGREY(200,200,200);
std::vector<Eigen::Vector3i> colors = {RED, GREEN, YELLOW, WHITE, LIGHTGREY, ORANGE, PURPLE};
// Flags
double pre_aspect_ratio = -1;
bool pre_aspect_is_x = false;
bool drag = false;
double hit_dist;
Eigen::Vector4d pre_cursor_point;
class Camera {
public:
Eigen::Matrix4d flatViewMat;
Eigen::Matrix4d ViewMat;
Eigen::Matrix4d ortho_mat;
Eigen::Matrix4d perspect_mat;
Eigen::Vector3d position;
Eigen::Vector3d global_up;
Eigen::Vector3d up;
Eigen::Vector3d right;
Eigen::Vector3d forward;
Eigen::Vector3d target;
// bounding box
double n, f, t, b, r, l;
int project_mode;
double theta;
int phi, zeta;
double radius;
Camera(GLFWwindow* window, Eigen::Vector3d position=Eigen::Vector3d(0.0, 0.0, 3.0), int project_mode = ORTHO) {
// set GLOBAL UP to y-axis as default, set look at target as origin(0,0,0)
this->global_up = Eigen::Vector3d(0.0, 1.0, 0.0);
this->n = 2.0; this->f = 100.0;
// FOV angle is initially 60 degrees
this->theta = (PI/180) * 60;
// trackball
this->target = Eigen::Vector3d(0.0, 0.0, 0.0);
this->phi = 0;
this->zeta = 0;
this->radius = 3.0;
this->flatViewMat <<
1.0, 0.0, 0.0, -position(0),
0.0, 1.0, 0.0, -position(1),
0.0, 0.0, 1.0, -position(2),
0.0, 0.0, 0.0, 1.0;
this->update_camera_pos();
this->look_at(window);
this->project_mode = project_mode;
}
void update_camera_pos() {
double rphi = (PI/180.0)*this->phi, rzeta = (PI/180.0)*this->zeta;
double y = this->radius * sin(rphi);
double x = this->radius * sin(rzeta) * cos(rphi);
double z = this->radius * cos(rzeta) * cos(rphi);
this->position = Eigen::Vector3d(x, y, z);
}
void rotate(int dPhi, int dZeta) {
this->phi = (this->phi+dPhi+360) % 360;
this->zeta = (this->zeta+dZeta+360) % 360;
this->update_camera_pos();
}
void zoom(double factor) {
this->theta *= factor;
}
void zoom2D(double factor) {
this->flatViewMat.col(0)(0) *= factor;
this->flatViewMat.col(1)(1) *= factor;
this->flatViewMat.col(3)(0) *= factor;
this->flatViewMat.col(3)(1) *= factor;
}
void pan2D(Eigen::Vector4d delta) {
this->flatViewMat.col(3) += delta;
}
void reset() {
this->theta = (PI/180) * 60;
this->phi = 0;
this->zeta = 0;
this->update_camera_pos();
}
void look_at(GLFWwindow* window, Eigen::Vector3d target = Eigen::Vector3d(0.0, 0.0, 0.0)) {
this->forward = (this->position - this->target).normalized();
// special case when forward is parallel to global up
double dotVal = this->global_up.dot(this->forward);
if (this->phi == 90 || this->phi == 270) {
this->right = (this->up.cross(this->forward).normalized());
}
else if (this->phi > 90 && this->phi < 270) {
this->right = (-this->global_up.cross(this->forward).normalized());
}
else {
this->right = (this->global_up.cross(this->forward).normalized());
}
this->up = this->forward.cross(this->right);
auto w = this->forward, u = this->right, v = this->up;
Eigen::Matrix4d LOOK;
LOOK <<
u(0), u(1), u(2), 0.0,
v(0), v(1), v(2), 0.0,
w(0), w(1), w(2), 0.0,
0.0, 0.0, 0.0, 1.0;
Eigen::Matrix4d AT;
AT <<
1.0, 0.0, 0.0, -this->position(0),
0.0, 1.0, 0.0, -this->position(1),
0.0, 0.0, 1.0, -this->position(2),
0.0, 0.0, 0.0, 1.0;
this->ViewMat = LOOK * AT;
this->update_project_mat(window);
}
Eigen::Vector3d to_world_point(Eigen::Vector3d screen_point) {
Eigen::Vector3d global_x, global_y, global_z;
global_x << 1.0, 0.0, 0.0;
global_y << 0.0, 1.0, 0.0;
global_z << 0.0, 0.0, 1.0;
double xworld = screen_point.dot(global_x);
double yworld = screen_point.dot(global_y);
double zworld = screen_point.dot(global_z);
return Eigen::Vector3d(xworld, yworld, zworld);
}
void switch_project_mode() {
this->project_mode *= -1;
}
void update_project_mat(GLFWwindow* window) {
int width, height;
glfwGetWindowSize(window, &width, &height);
width /= 2;
// height /= 2;
double aspect = (double)width/(double)height;
this->t = tan(theta/2) * std::abs(n);
this->b = -this->t;
this->r = aspect * this->t;
this->l = -this->r;
this->ortho_mat <<
2.0/(r-l), 0.0, 0.0, -(r+l)/(r-l),
0.0, 2.0/(t-b), 0.0, -(t+b)/(t-b),
0.0, 0.0, -2.0/(f-n), -(f+n)/(f-n),
0.0, 0.0, 0.0, 1.0;
this->perspect_mat <<
2*n/(r-l), 0., (r+l)/(r-l), 0.,
0., (2*n)/(t-b), (t+b)/(t-b), 0.,
0., 0., -(f+n)/(f-n), (-2*f*n)/(f-n),
0., 0., -1., 0;
}
Eigen::Matrix4d get_project_mat() {
if (this->project_mode == ORTHO) return this->ortho_mat;
return this->perspect_mat;
}
};
class Mesh {
public:
Eigen::Vector3d color;
Eigen::Vector4d centroid;
double r, s, tx, ty;
Eigen::Vector4d normal;
std::map<int, Eigen::Vector3d> vid2v;
std::map<int, Eigen::Vector3d> vid2fv;
std::vector<int> vids;
std::vector< std::pair< int, std::pair<int,int> > > nebMeshes;
int id;
Eigen::Matrix4d R;
Eigen::Matrix4d accR;
Eigen::Matrix4d animeM;
Mesh* parent;
std::vector<Mesh*> childs;
Edge rotEdge;
Eigen::Vector3d rotAixs;
Eigen::Vector3d edgeA;
Eigen::Vector3d edgeB;
double rotAngle;
double rotRad;
double rotSign;
double rotDot;
VertexArrayObject VAO;
VertexBufferObject VBO_P;
Mesh() {}
Mesh(int id, Eigen::MatrixXd V, int v1, int v2, int v3, Eigen::Vector3i color=LIGHTGREY) {
this->id = id;
this->color = color.cast<double>()/255.;
this->vids.push_back(v1); this->vids.push_back(v2); this->vids.push_back(v3);
this->vid2v[v1] = V.col(v1); this->vid2v[v2] = V.col(v2); this->vid2v[v3] = V.col(v3);
// init flat position
Eigen::Vector3d zero = Eigen::VectorXd::Zero(3);
this->vid2fv[v1] = zero; this->vid2fv[v2] = zero; this->vid2fv[v3] = zero;
this->accR = Eigen::MatrixXd::Identity(4,4);
this->R = Eigen::MatrixXd::Identity(4,4);
this->animeM = Eigen::MatrixXd::Identity(4,4);
this->parent = nullptr;
this->rotAngle = 0.;
this->rotRad = 0.;
this->rotDot = 0.;
this->rotSign = 1;
this->VAO.init();
this->VAO.bind();
this->VBO_P.init();
this->updateVBOP();
}
void updateVBOP() {
int v1 = vids[0], v2 = vids[1], v3 = vids[2];
Eigen::Matrix3d fV;
fV << vid2fv[v1], vid2fv[v2], vid2fv[v3];
this->VBO_P.update(m_to_float(fV));
}
Eigen::Matrix3d getFlatV() {
int v1 = vids[0], v2 = vids[1], v3 = vids[2];
Eigen::Matrix3d fV;
fV << vid2fv[v1], vid2fv[v2], vid2fv[v3];
return fV;
}
Eigen::Matrix3d getV() {
int v1 = vids[0], v2 = vids[1], v3 = vids[2];
Eigen::Matrix3d V;
V << vid2v[v1], vid2v[v2], vid2v[v3];
return V;
}
Mesh(Eigen::MatrixXd V, Eigen::MatrixXd bounding_box, Eigen::Vector3i color=LIGHTGREY) {
this->r = 0; this->s = 1; this->tx = 0; this->ty = 0;
this->color = color.cast<double>();
auto a = to_3(V.col(0)), b = to_3(V.col(1)), c = to_3(V.col(2));
auto tmp = ((b-a).cross(c-a)).normalized();
this->normal = Eigen::Vector4d(tmp(0), tmp(1), tmp(2), 0.0);
// Computer the barycenter(centroid) of the Mesh, alphea:beta:gamma = 1:1:1
Eigen::Vector4d A = V.col(0), B = V.col(1), C = V.col(2);
this->centroid = (1.0/3)*A + (1.0/3)*B + (1.0/3)*C;
}
bool getIntersection(Eigen::Vector4d ray_origin, Eigen::Vector4d ray_direction, Eigen::Vector4d &intersection, Eigen::MatrixXd V) {
// solve equation: e + td = a + u(b-a) + v(c-a)
// (a-b)u + (a-c)v + dt = a-e
Eigen::Vector4d a = V.col(0), b = V.col(1), c = V.col(2);
Eigen::Vector4d d = ray_direction, e = ray_origin;
double ai = (a-b)(0), di = (a-c)(0), gi = (d)(0);
double bi = (a-b)(1), ei = (a-c)(1), hi = (d)(1);
double ci = (a-b)(2), fi = (a-c)(2), ii = (d)(2);
double ji = (a-e)(0), ki = (a-e)(1), li = (a-e)(2);
double M = ai*(ei*ii-hi*fi)+bi*(gi*fi-di*ii)+ci*(di*hi-ei*gi);
double xt = -(fi*(ai*ki-ji*bi)+ei*(ji*ci-ai*li)+di*(bi*li-ki*ci))/M;
if (xt <= 0) return false;
double xu = (ji*(ei*ii-hi*fi)+ki*(gi*fi-di*ii)+li*(di*hi-ei*gi))/M;
if (xu < 0 || xu > 1) return false;
double xv = (ii*(ai*ki-ji*bi)+hi*(ji*ci-ai*li)+gi*(bi*li-ki*ci))/M;
// intersection inside the Mesh
intersection = ray_origin + xt*ray_direction;
intersection(3) = 1.0;
if (xv < 0 || xv+xu > 1) return false;
return true;
}
Eigen::Vector3d getH(Edge edge) {
int v1 = edge.first, v2 = edge.second;
int v3;
for (int vid: vids) {
if (vid != v1 && vid != v2) {
v3 = vid; break;
}
}
// Eigen::Vector3d aixs = (vid2v[v2]-vid2v[v1]).normalized();
// Eigen::Vector3d vec = vid2v[v3]-vid2v[v1];
Eigen::Vector3d aixs = (vid2v[v1]-vid2v[v2]).normalized();
Eigen::Vector3d vec = vid2v[v3]-vid2v[v2];
Eigen::Vector3d h = get_vertical_vec(vec, aixs);
return h;
}
};
class Node {
public:
double weight;
std::pair<int, int> edge;
int parentMeshId, meshId;
Node(double weight, std::pair<int, int> edge, int parentMeshId, int meshId) {
this->weight = weight;
this->edge = edge;
this->parentMeshId = parentMeshId;
this->meshId = meshId;
}
};
class CompareWeight {
public:
bool operator()(Node a, Node b) {
return a.weight < b.weight;
}
};
class Grid {
public:
double sizex, sizey;
std::map<int, std::map<int, std::vector<int> > > rows;
Grid(double sizex = 0.03, double sizey = 0.03) {
this->sizex = sizex; this->sizey = sizey;
}
void addItem(Mesh* mesh) {
Eigen::MatrixXd boundingBox = get_bounding_box_2d(mesh->getFlatV());
double minx = boundingBox.col(0)(0), maxx = boundingBox.col(1)(0);
double miny = boundingBox.col(0)(1), maxy = boundingBox.col(1)(1);
double x = minx;
while (x < maxx+sizex) {
double y = miny;
while (y < maxy+sizey) {
int r, c;
getCellIdx(x, y, r, c);
if (std::find(rows[r][c].begin(), rows[r][c].end(), mesh->id) == rows[r][c].end())
rows[r][c].push_back(mesh->id);
y += sizey;
}
x += sizex;
}
}
void getCellIdx(double x, double y, int &r, int &c) {
r = int(x/sizex);
c = int(y/sizey);
}
std::set<int> getNearMeshes(Eigen::Vector3d A, Eigen::Vector3d B, Eigen::Vector3d C) {
// compute bounding box
Eigen::Matrix3d V;
V << A, B, C;
Eigen::MatrixXd boundingBox = get_bounding_box_2d(V);
double minx = boundingBox.col(0)(0), maxx = boundingBox.col(1)(0);
double miny = boundingBox.col(0)(1), maxy = boundingBox.col(1)(1);
double x = minx;
std::set<int> nearMeshes;
while (x < maxx+sizex) {
double y = miny;
while (y < maxy+sizey) {
int r, c;
getCellIdx(x, y, r, c);
for (int meshId: rows[r][c]) {
nearMeshes.insert(meshId);
}
y += sizey;
}
x += sizex;
}
return nearMeshes;
}
};
class FlattenObject {
public:
std::map<int, Mesh*> meshes;
std::map<std::pair<int, int>, std::vector<int>> edge2meshes;
std::map<std::pair<int, int>, double> edge2weight;
Grid* grid;
std::map<int, int> idx2meshId;
Eigen::MatrixXd V;
Eigen::MatrixXd fV;
Eigen::VectorXi IDX;
VertexArrayObject VAO;
VertexBufferObject VBO_P;
IndexBufferObject IBO_IDX;
Eigen::MatrixXd ModelMat;
Eigen::MatrixXd T_to_ori;
Eigen::Vector4d barycenter;
void addEdge(int v1, int v2, int meshId) {
auto edge = v1 < v2? std::make_pair(v1, v2) : std::make_pair(v2, v1);
edge2meshes[edge].push_back(meshId);
if (edge2weight.find(edge) == edge2weight.end())
edge2weight[edge] = (V.col(v1)-V.col(v2)).norm();
}
void addNebMeshes(int v1, int v2, int meshId) {
auto edge = v1 < v2? std::make_pair(v1, v2) : std::make_pair(v2, v1);
for (int nebMeshId: edge2meshes[edge]) {
if (nebMeshId != meshId) {
meshes[meshId]->nebMeshes.push_back(std::make_pair(nebMeshId, edge));
}
}
}
bool flattenFirst(int meshId, std::set<int> &flatten) {
Mesh* mesh = meshes[meshId];
int v1 = mesh->vids[0], v2 = mesh->vids[1], v3 = mesh->vids[2];
double v1v2Len = (mesh->vid2v[v1] - mesh->vid2v[v2]).norm();
// mesh->vid2fv[v1] = Eigen::Vector3d(0., 0., 0.);
// mesh->vid2fv[v2] = Eigen::Vector3d(0., v1v2Len, 0.);
mesh->vid2fv[v1] = Eigen::Vector3d(0., 0., -1.);
mesh->vid2fv[v2] = Eigen::Vector3d(0., v1v2Len, -1.);
Eigen::Vector3d flatPos;
if (!flattenVertex(meshId, v3, v1, v2, mesh->vid2fv[v1], mesh->vid2fv[v2], flatPos, flatten)) {
return false;
}
mesh->vid2fv[v3] = flatPos;
// compute rotate angle
double rotAngle = 0.;
Eigen::Vector3d fv1Pos = mesh->vid2fv[v1];
Eigen::Vector3d fv2Pos = mesh->vid2fv[v2];
Eigen::Vector3d edgefA = fv1Pos, edgefB = fv2Pos;
Eigen::Vector3d edgeA = mesh->vid2v[v1], edgeB = mesh->vid2v[v2];
if (v2 < v1) {
edgeA = mesh->vid2v[v2]; edgeB = mesh->vid2v[v1];
edgefA = fv2Pos; edgefB = fv1Pos;
}
Eigen::Vector3d fRotAixs = (edgefA-edgefB).normalized();
mesh->R = get_rotate_mat(rotAngle, edgefA, edgefB);
mesh->edgeA = edgefA;
mesh->edgeB = edgefB;
mesh->rotEdge = std::make_pair(v1, v2);
mesh->rotAngle = rotAngle;
mesh->rotAixs = fRotAixs;
mesh->rotRad = 0.;
return true;
}
FlattenObject(Eigen::MatrixXd V, Eigen::VectorXi IDX, std::vector<bool> &meshFlattened) {
V.conservativeResize(3, V.cols());
this->V = V;
this->fV.resize(4, 0);
// create V and F matrix
std::cout << "create meshes" << std::endl;
// std::vector<Mesh*> meshes;
for (int i = 0; i < IDX.rows(); i += 3) {
int meshId = i/3;
// std::cout << "check id " << i/3 << std::endl;
if (meshFlattened[i/3]) continue;
// std::cout << "ok id " << i/3 << std::endl;
int v1 = IDX(i), v2 = IDX(i+1), v3 = IDX(i+2);
meshes[meshId] = new Mesh(meshId, V, v1, v2, v3, WHITE);
// add edge
addEdge(v1, v2, meshId);
addEdge(v2, v3, meshId);
addEdge(v1, v3, meshId);
}
// std::cout << "created meshes and edge to meshes" << std::endl;
// std::cout << "face #: " << meshes.size() << std::endl;
// std::cout << "edge #: " << edge2meshes.size() << std::endl;
// add edge field to mesh objects
for (auto it: meshes) {
int meshId = it.first;
Mesh* mesh = it.second;
int v1 = mesh->vids[0], v2 = mesh->vids[1], v3 = mesh->vids[2];
addNebMeshes(v1, v2, meshId);
addNebMeshes(v2, v3, meshId);
addNebMeshes(v1, v3, meshId);
// assert(mesh->nebMeshes.size() == 3);
}
// std::cout << "created meshes to nebs" << std::endl;
// new a Regular Grid to boost the overlap checking process.
grid = new Grid();
// maximal spaning tree(MST)
std::priority_queue<Node, std::vector<Node>, CompareWeight> pq;
std::set<int> flattened;
std::vector<double> dist(IDX.rows()/3, 0.);
// flat first mesh
int firstMeshId = meshes.begin()->first;
flattenFirst(firstMeshId, flattened);
flattened.insert(firstMeshId);
grid->addItem(meshes[firstMeshId]);
dist[firstMeshId] = DIST_MAX;
pq.push(Node(DIST_MAX, std::make_pair(0,0), 0, firstMeshId));
// std::cout << "flattened first mesh" << std::endl;
// std::cout << "mesh flat V" << std::endl;
// std::cout << meshes[firstMeshId].getFlatV() << std::endl;
// max spanning tree, prime algorithm
while (!pq.empty()) {
auto node = pq.top();
pq.pop();
Mesh* curMesh = meshes[node.meshId];
for(auto meshNedge: curMesh->nebMeshes) {
int nebMeshId = meshNedge.first;
auto edge = meshNedge.second;
if (flattened.find(nebMeshId) == flattened.end() && edge2weight[edge] > dist[nebMeshId]) {
dist[nebMeshId] = edge2weight[edge];
pq.push(Node(edge2weight[edge], edge, curMesh->id, nebMeshId));
}
}
// pop out all meshes that is flatted or cannot be flatted in this island
while (!pq.empty() && (flattened.find(pq.top().meshId) != flattened.end() || !flattenMesh(pq.top().parentMeshId, pq.top().meshId, pq.top().edge, flattened))) {
pq.pop();
}
if (!pq.empty()) {
node = pq.top();
flattened.insert(node.meshId);
grid->addItem(meshes[node.meshId]);
// build MST node connections
Mesh* curMesh = meshes[node.meshId];
Mesh* preMesh = meshes[node.parentMeshId];
curMesh->parent = preMesh;
preMesh->childs.push_back(curMesh);
}
}
for (int meshId: flattened) {
meshFlattened[meshId] = true;
Eigen::Matrix3d flatV = meshes[meshId]->getFlatV();
this->fV.conservativeResize(4, fV.cols()+3);
int last = this->fV.cols();
this->fV.col(last-3) = to_4_point(flatV.col(0));
this->fV.col(last-2) = to_4_point(flatV.col(1));
this->fV.col(last-1) = to_4_point(flatV.col(2));
this->idx2meshId[last-3] = meshId;
}
// update flat position to VBO, compute bounding box
this->VAO.init();
this->VAO.bind();
this->VBO_P.init();
this->VBO_P.update(m_to_float(this->fV));
// init model fields
this->ModelMat = Eigen::MatrixXd::Identity(4,4);
this->T_to_ori = Eigen::MatrixXd::Identity(4,4);
this->barycenter = Eigen::Vector4d(0.0, 0.0, 0.0, 1.0);
// check tree
// Mesh* root = meshes.begin()->second;
// std::queue<Mesh*> q;
// q.push(root);
// while (!q.empty()) {
// Mesh* cur = q.front();
// q.pop();
// for (Mesh* child: cur->childs) {
// q.push(child);
// }
// }
}
bool flattenMesh(int preMeshId, int meshId, std::pair<int, int> edge, std::set<int> &flattened) {
// find the remaining non-flattened vertex
// std::cout << "enter flattenMesh" << std::endl;
Mesh* preMesh = meshes[preMeshId];
Mesh* mesh = meshes[meshId];
int fv1 = edge.first, fv2 = edge.second;
int v3;
for (int vid: mesh->vids) {
if (vid != fv1 && vid != fv2) {
v3 = vid;
break;
}
}
// flatten the remaining vertex v3 according to the flat position of v1 and v2
Eigen::Vector3d fv3Pos;
if (!flattenVertex(meshId, v3, fv1, fv2, preMesh->vid2fv[fv1], preMesh->vid2fv[fv2], fv3Pos, flattened))
return false;
// get flat v1 and flat v2 from pre Mesh
mesh->vid2fv[fv1] = preMesh->vid2fv[fv1];
mesh->vid2fv[fv2] = preMesh->vid2fv[fv2];
mesh->vid2fv[v3] = fv3Pos;
// compute rotate angle
Eigen::Vector3d curh = mesh->getH(edge).normalized();
Eigen::Vector3d preh = preMesh->getH(edge).normalized();
double rotAngle = 180. - acos(curh.dot(preh)) * 180.0/PI;
double rotRad = PI-acos(curh.dot(preh));
double rotDot = -curh.dot(preh);
double rotSign = 1;
// std::cout << "curh.dot(preh)" << std::endl;
// std::cout << curh.dot(preh) << std::endl;
// std::cout << "rotAngle" << std::endl;
// std::cout << rotAngle << std::endl;
Eigen::Vector3d fv1Pos = mesh->vid2fv[fv1];
Eigen::Vector3d fv2Pos = mesh->vid2fv[fv2];
Eigen::Vector3d edgefA = fv1Pos, edgefB = fv2Pos;
Eigen::Vector3d edgeA = mesh->vid2v[fv1], edgeB = mesh->vid2v[fv2];;
if (fv2 < fv1) {
edgeA = mesh->vid2v[fv2]; edgeB = mesh->vid2v[fv1];
}
Eigen::Vector3d fRotAixs = (edgefA-edgefB).normalized();
Eigen::Vector3d rotAixs = (edgeA-edgeB).normalized();
if ((curh.cross(preh)).dot(rotAixs) < 0. ) {
rotAngle = -rotAngle;
rotRad = -rotRad;
rotSign = -1;
}
mesh->R = get_rotate_mat(rotAngle, edgefA, edgefB);
mesh->edgeA = edgefA;
mesh->edgeB = edgefB;
mesh->rotEdge = std::make_pair(fv1, fv2);
mesh->rotAngle = rotAngle;
mesh->rotRad = rotRad;
mesh->rotAixs = fRotAixs;
mesh->rotSign = rotSign;
mesh->rotDot = rotDot;
// std::cout << rotAngle << std::endl;
return true;
}
// compute the flat position of v3 according to the flat position of v1 and v2
// check overlap
bool flattenVertex(int meshId, int v3, int v1, int v2, Eigen::Vector3d fv1Pos, Eigen::Vector3d fv2Pos, Eigen::Vector3d &fv3Pos, std::set<int> &flattened) {
Mesh* mesh = meshes[meshId];
Eigen::Vector3d flat1, flat2;
// use get H to compute fH
Eigen::Vector3d aixs = (mesh->vid2v[v1]-mesh->vid2v[v2]).normalized();
Eigen::Vector3d vec = mesh->vid2v[v3]-mesh->vid2v[v2];
double len = vec.dot(aixs);
Eigen::Vector3d parallel = len*aixs;
Eigen::Vector3d hvec = vec-parallel;
Eigen::Vector3d faixs = (fv1Pos - fv2Pos).normalized();
Eigen::Vector3d fH = fv2Pos + len * faixs;
Eigen::Vector3d flatDir = Eigen::Vector3d(-faixs.y(), faixs.x(), 0.).normalized();
flat1 = fH + hvec.norm() * flatDir;
flat2 = fH + hvec.norm() * (-flatDir);
// check overlap
bool canFlat = false;
if (!overlap(flat1, fv1Pos, fv2Pos, flattened)) {
fv3Pos = flat1;
canFlat = true;
}
else {
if (!overlap(flat2, fv1Pos, fv2Pos, flattened)) {
fv3Pos = flat2;
canFlat = true;
}
}
return canFlat;
}
bool overlap(Eigen::Vector3d flatPos, Eigen::Vector3d fv1Pos, Eigen::Vector3d fv2Pos, std::set<int> &flattened) {
// check if any vertices of a flat Triangle inside the other flat Triangle
// get all near meshes and combine them to one vector
std::set<int> nearMeshes = grid->getNearMeshes(flatPos, fv1Pos, fv2Pos);
for (int meshId: nearMeshes) {
Eigen::Matrix3d meshfV = meshes[meshId]->getFlatV();
if (isInside(flatPos, meshfV)) return true;
Eigen::Vector3d center = (flatPos+fv1Pos+fv2Pos)/3.;
if (isInside(center, meshfV)) return true;
Eigen::Matrix3d curMeshfV;
curMeshfV << flatPos, fv1Pos, fv2Pos;
if (isInside(meshfV.col(0), curMeshfV)) return true;
if (isInside(meshfV.col(1), curMeshfV)) return true;
if (isInside(meshfV.col(2), curMeshfV)) return true;
center = (meshfV.col(0)+meshfV.col(1)+meshfV.col(2))/3.;
if (isInside(center, curMeshfV)) return true;
}
// check line intersection
for (int meshId: nearMeshes) {
if (lineCross(flatPos, fv1Pos, meshId)) return true;
if (lineCross(flatPos, fv2Pos, meshId)) return true;
}
return false;
}
bool lineCross(Eigen::Vector3d a, Eigen::Vector3d b, int meshId) {
Mesh* mesh = meshes[meshId];
int ov1, ov2, ov3;
ov1 = mesh->vids[0]; ov2 = mesh->vids[1]; ov3 = mesh->vids[2];
if (lineCross(a, b, mesh->vid2fv[ov1], mesh->vid2fv[ov2])) return true;
if (lineCross(a, b, mesh->vid2fv[ov2], mesh->vid2fv[ov3])) return true;
if (lineCross(a, b, mesh->vid2fv[ov1], mesh->vid2fv[ov3])) return true;
return false;
}
bool lineCross(Eigen::Vector3d a, Eigen::Vector3d b, Eigen::Vector3d c, Eigen::Vector3d d) {
// overlap?
if (((a-c).norm() < ESP || (a-d).norm() < ESP) && ((b-c).norm() < ESP || (b-d).norm() < ESP)) {
return false;
}
// parallel?
Eigen::Vector3d AB = b-a;
Eigen::Vector3d CD = d-c;
if (AB.cross(CD).norm() - 0. < ESP) {
return false;
}
// get intersection
Eigen::Matrix2d M;
Eigen::Vector2d R;
M << a.x()-b.x(), d.x()-c.x(), a.y()-b.y(), d.y()-c.y();
R << d.x()-b.x(), d.y()-b.y();
Eigen::Vector2d x = M.colPivHouseholderQr().solve(R);
// within range? 0 <= x <= 1
return x(0) > ESP && x(0) < 1.0-ESP && x(1) > ESP && x(1) < 1.0-ESP;
}
bool isInside(Eigen::Vector3d flatPos, Eigen::Matrix3d meshfV) {
Eigen::Vector3d a, b, c;
a = meshfV.col(0); b = meshfV.col(1); c = meshfV.col(2);
Eigen::Matrix3d M;
Eigen::Vector3d R;
M << a(0),b(0),c(0), a(1),b(1),c(1), 1,1,1;
R << flatPos(0), flatPos(1), 1;
Eigen::Vector3d x = M.colPivHouseholderQr().solve(R);
return x(0)-0. > ESP && x(1)-0. > ESP && x(2)-0. > ESP;
}
void translate(Eigen::Vector4d delta) {
Eigen::MatrixXd T = Eigen::MatrixXd::Identity(4, 4);
T.col(3)(0) = delta(0); T.col(3)(1) = delta(1); T.col(3)(2) = delta(2);
this->update_Model_Mat(T, true);
}
void scale(double factor) {
// double factor = 1+delta;
Eigen::MatrixXd S = Eigen::MatrixXd::Identity(4, 4);
S.col(0)(0) = factor; S.col(1)(1) = factor; S.col(2)(2) = 1.;
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(4,4);
S = (2*I-this->T_to_ori)*S*(this->T_to_ori);
this->update_Model_Mat(S, false);
}
void rotate(double degree, Eigen::Matrix4d rotateMat) {
double r = degree*PI/180.0;
Eigen::MatrixXd R = Eigen::MatrixXd::Identity(4, 4);
R.col(0)(0) = std::cos(r); R.col(0)(1) = std::sin(r);
R.col(1)(0) = -std::sin(r); R.col(1)(1) = std::cos(r);
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(4,4);
R = (2*I-this->T_to_ori)*rotateMat*(this->T_to_ori);
this->update_Model_Mat(R, false);
}
void update_Model_Mat(Eigen::MatrixXd M, bool left) {
if (left) {
// left cross mul
this->ModelMat = M*this->ModelMat;
}
else {
// right cross mul
this->ModelMat = this->ModelMat*M;
}
}
std::string export_svg(Camera *camera) {
std::stringstream ss;
for (int i = 0; i < this->fV.cols(); i += 3) {
Eigen::MatrixXd mesh_fV(4, 3);
mesh_fV.col(0) = fV.col(i);
mesh_fV.col(1) = fV.col(i+1);
mesh_fV.col(2) = fV.col(i+2);
mesh_fV = camera->get_project_mat()*camera->flatViewMat*ModelMat*mesh_fV;
std::string svg_str = get_tri_g_template();
std::string ax = std::to_string(mesh_fV.col(0).x()), ay = std::to_string(mesh_fV.col(0).y());
std::string bx = std::to_string(mesh_fV.col(1).x()), by = std::to_string(mesh_fV.col(1).y());
std::string cx = std::to_string(mesh_fV.col(2).x()), cy = std::to_string(mesh_fV.col(2).y());
svg_str = replace_all(svg_str, "$AX", ax); svg_str = replace_all(svg_str, "$AY", ay);
svg_str = replace_all(svg_str, "$BX", bx); svg_str = replace_all(svg_str, "$BY", by);
svg_str = replace_all(svg_str, "$CX", cx); svg_str = replace_all(svg_str, "$CY", cy);
ss << svg_str << std::endl;
}
std::string svg_str = ss.str();
return svg_str;
}
void adjustSize(Eigen::MatrixXd boundingBox) {
double maxx = boundingBox.col(1)(0), maxy = boundingBox.col(1)(1);
double minx = boundingBox.col(0)(0), miny = boundingBox.col(0)(1);
Eigen::MatrixXd curBox = get_bounding_box_2d(this->fV);
this->barycenter = (curBox.col(0) + curBox.col(1))/2.0;
this->barycenter(2) = 0; this->barycenter(3) = 1;
// Computer the translate Matrix from barycenter to the origin
Eigen::Vector4d delta = Eigen::Vector4d(0.0, 0.0, 0.0, 1.0) - this->barycenter;
T_to_ori.col(3)(0) = delta(0); T_to_ori.col(3)(1) = delta(1); T_to_ori.col(3)(2) = delta(2);
// adjust inital position according to bounding box
double scale_factor = fmin(1.0/(maxx-minx), 1.0/(maxy-miny));
this->translate(delta);
this->scale(scale_factor);
}
};
class _3dObject {
public:
Eigen::MatrixXd box;
Eigen::MatrixXd ModelMat;
Eigen::MatrixXd ModelMat_T;
Eigen::MatrixXd Adjust_Mat;
Eigen::MatrixXd T_to_ori;
Eigen::Vector4d barycenter;
Eigen::VectorXi IDX;
Eigen::MatrixXd V;
Eigen::MatrixXd C;
Eigen::MatrixXd Normals;
int render_mode;
double r, s, tx, ty;
// FlattenObject* flattenObj;
std::vector<FlattenObject> flattenObjs;
std::set<int> selectedMeshes;
std::vector<std::vector<Mesh*>> edges;
std::vector<Mesh*> meshes;
VertexArrayObject VAO;
VertexBufferObject VBO_P;
VertexBufferObject VBO_C;
VertexBufferObject VBO_N;
IndexBufferObject IBO_IDX;
_3dObject(){}
_3dObject(std::string off_path, int color_idx) {
//load from off file
Eigen::MatrixXd V, C;
Eigen::VectorXi IDX;
loadMeshfromOFF(off_path, V, C, IDX);
C = Eigen::MatrixXd(3, V.cols());
// int color_idx = rand() % colors.size();
Eigen::Vector3i color = colors[color_idx];
for (int i = 0; i < V.cols(); i++) {
C.col(i) = color.cast<double>();
}
//compute the bouncing box
box = get_bounding_box(V);
//create class Mesh for each mech
this->initial(V, C, IDX, box);
}
void initial(Eigen::MatrixXd V, Eigen::MatrixXd C, Eigen::VectorXi IDX, Eigen::MatrixXd bounding_box) {
// make sure it is a point
for (int i = 0; i < V.cols(); i++) {
V.col(i)(3) = 1.0;
}
this->IDX = IDX;
this->V = V;
this->C = C;
// Create a VAO
this->VAO.init();
this->VAO.bind();
// Initialize the VBO with the vertices data
this->VBO_P.init();
this->VBO_P.update(m_to_float(V));
this->VBO_C.init();
this->VBO_C.update(m_to_float(C/255.0));
this->VBO_N.init();
this->IBO_IDX.init();
this->IBO_IDX.update(IDX);
this->ModelMat = Eigen::MatrixXd::Identity(4,4);
this->ModelMat_T = Eigen::MatrixXd::Identity(4,4);
this->T_to_ori = Eigen::MatrixXd::Identity(4,4);
this->r = 0; this->s = 1; this->tx = 0; this->ty = 0;
this->render_mode = 0;
this->barycenter = (bounding_box.col(0) + bounding_box.col(1))/2.0;
// Computer the translate Matrix from barycenter to the origin
Eigen::Vector4d delta = Eigen::Vector4d(0.0, 0.0, 0.0, 1.0) - this->barycenter;
T_to_ori.col(3)(0) = delta(0); T_to_ori.col(3)(1) = delta(1); T_to_ori.col(3)(2) = delta(2);
// Adjust size
this->initial_adjust(bounding_box);
// initial edges
for (int i = 0; i < V.cols(); i++) {
this->edges.push_back(std::vector<Mesh*>());
}
std::cout << "start generating Meshs" << std::endl;
for (int i = 0; i < IDX.rows(); i+=3) {
int a = IDX(i), b = IDX(i+1), c = IDX(i+2);
Eigen::MatrixXd Vblock(4, 3);
Vblock << V.col(a), V.col(b), V.col(c);
auto mesh = new Mesh(Vblock, bounding_box);
this->meshes.push_back(mesh);
this->edges[a].push_back(mesh);
this->edges[b].push_back(mesh);
this->edges[c].push_back(mesh);
}
// Compute normlas for each vertex
if (this->edges.size() != V.cols()) {
std::cout << "Assert failed" << std::endl;
exit(1);
}
this->Normals.resize(V.rows(), V.cols());
for (int i = 0; i < V.cols(); i++) {
Eigen::Vector4d normal(0., 0., 0., 0.);
for (Mesh* mesh: this->edges[i]) {
normal += mesh->normal;
}
this->Normals.col(i) = normal.normalized();
}
this->VBO_N.update(m_to_float(this->Normals));
std::cout << "meshes # = " << this->meshes.size() << std::endl;
std::cout << "finish" << std::endl;
// create flatten object
// this->flattenObj = nullptr;
// this->flattenObjs.resize(10);
this->flatten();
}
void initial_adjust(Eigen::MatrixXd bounding_box) {
double maxx = bounding_box.col(1)(0), maxy = bounding_box.col(1)(1), maxz = bounding_box.col(1)(2);
double minx = bounding_box.col(0)(0), miny = bounding_box.col(0)(1), minz = bounding_box.col(0)(2);
double scale_factor = fmin(1.0/(maxx-minx), fmin(1.0/(maxy-miny), 1.0/(maxz-minz)));
this->scale(scale_factor);
}
bool hit(Eigen::Vector4d ray_origin, Eigen::Vector4d ray_direction, double &dist) {
bool intersected = false;
int cnt = 0;
int selectedMeshId;
for (auto mesh : this->meshes) {
Eigen::Vector4d intersection;
Eigen::MatrixXd mesh_V(4,3);
int i = this->IDX(cnt*3), j = this->IDX(cnt*3+1), k = this->IDX(cnt*3+2);
mesh_V << this->V.col(i), this->V.col(j), this->V.col(k);
mesh_V = this->ModelMat*mesh_V;
// the ray is parallel to the Mesh, no solution
Eigen::Vector4d world_normal = ((this->ModelMat.inverse()).transpose()*mesh->normal).normalized();
if (ray_direction.dot(world_normal) == 0) {
cnt++;
continue;
}
if (mesh->getIntersection(ray_origin, ray_direction, intersection, mesh_V)) {
intersected = true;
double curDist = (intersection-ray_origin).norm();
if (curDist < dist) {
selectedMeshId = cnt;
dist = curDist;
}
}
cnt++;
}
if (intersected) {
if (this->selectedMeshes.find(selectedMeshId) != selectedMeshes.end())
this->selectedMeshes.erase(selectedMeshId);
else
this->selectedMeshes.insert(selectedMeshId);
}
return intersected;
}
void translate(Eigen::Vector4d delta) {
// delta = this->Adjust_Mat.inverse()*delta;
this->tx += delta(0); this->ty += delta(1);
Eigen::MatrixXd T = Eigen::MatrixXd::Identity(4, 4);
T.col(3)(0) = delta(0); T.col(3)(1) = delta(1); T.col(3)(2) = delta(2);
Eigen::MatrixXd T_T = Eigen::MatrixXd::Identity(4, 4);
T_T.col(3)(0) = -delta(0); T_T.col(3)(1) = -delta(1); T_T.col(3)(2) = -delta(2);
this->update_Model_Mat(T, T_T, true);
}
void scale(double factor) {
// double factor = 1+delta;
this->s *= factor;
Eigen::MatrixXd S = Eigen::MatrixXd::Identity(4, 4);
S.col(0)(0) = factor; S.col(1)(1) = factor; S.col(2)(2) = factor;
Eigen::MatrixXd S_T = Eigen::MatrixXd::Identity(4, 4);
S_T.col(0)(0) = 1.0/factor; S_T.col(1)(1) = 1.0/factor; S_T.col(2)(2) = 1.0/factor;
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(4,4);
S = (2*I-this->T_to_ori)*S*(this->T_to_ori);
S_T = (2*I-this->T_to_ori)*S_T*(this->T_to_ori);
this->update_Model_Mat(S, S_T, false);
}
void rotate(double degree, Eigen::Matrix4d rotateMat) {
double r = degree*PI/180.0;
this->r += r;
Eigen::MatrixXd R = Eigen::MatrixXd::Identity(4, 4);
R.col(0)(0) = std::cos(r); R.col(0)(1) = std::sin(r);
R.col(1)(0) = -std::sin(r); R.col(1)(1) = std::cos(r);
Eigen::MatrixXd R_T = Eigen::MatrixXd::Identity(4, 4);
R_T.col(0)(0) = std::cos(r); R_T.col(0)(1) = -std::sin(r);
R_T.col(1)(0) = std::sin(r); R_T.col(1)(1) = std::cos(r);
Eigen::MatrixXd I = Eigen::MatrixXd::Identity(4,4);
R = (2*I-this->T_to_ori)*rotateMat*(this->T_to_ori);
R_T = (2*I-this->T_to_ori)*rotateMat.inverse()*(this->T_to_ori);
this->update_Model_Mat(R, R_T, false);
}
void update_Model_Mat(Eigen::MatrixXd M, Eigen::MatrixXd M_T, bool left) {
if (left) {
// left cross mul
this->ModelMat = M*this->ModelMat;
this->ModelMat_T = this->ModelMat_T*M_T;
}
else {
// right cross mul
this->ModelMat = this->ModelMat*M;
this->ModelMat_T = M_T*this->ModelMat_T;
}
}
void flatten() {
// delete all flatten object first
this->flattenObjs.clear();
// create a new flatten object using selected meshes
// use all meshes if no mesh is selected
Eigen::VectorXi selectedIDX;
if (this->selectedMeshes.size() == 0) {
selectedIDX = this->IDX;
}
else {
selectedIDX.resize((selectedMeshes.size()*3));
int i = 0;
for (auto meshId: this->selectedMeshes) {
selectedIDX(i++) = this->IDX(meshId*3);
selectedIDX(i++) = this->IDX(meshId*3+1);
selectedIDX(i++) = this->IDX(meshId*3+2);
}
}
std::cout << "starts flattening" << std::endl;
std::vector<bool> meshFlattened(selectedIDX.rows()/3, false);
int flattedCnt = 0;
while (flattedCnt < selectedIDX.rows()/3) {
this->flattenObjs.push_back(FlattenObject(this->V, selectedIDX, meshFlattened));
// check tree
std::cout << "check tree in 3d object flatten" << std::endl;
for (FlattenObject& flatObj: this->flattenObjs) {
Mesh* root = flatObj.meshes.begin()->second;
std::queue<Mesh*> q;
q.push(root);
std::cout << "tree" << std::endl;
while (!q.empty()) {
Mesh* cur = q.front();
q.pop();
std::cout << cur->id << std::endl;
for (Mesh* child: cur->childs) {
q.push(child);
}
}
}
flattedCnt = 0;
for (int i = 0; i < meshFlattened.size(); i++) {
flattedCnt += meshFlattened[i];
}
}
// scale all islands with a same ratio to fit the window
std::vector<Eigen::Matrix2d> islandsBoxs;
Eigen::MatrixXd boundingBox(2, 2);
double deltaY = 0.;
for (FlattenObject &flatObj: this->flattenObjs) {
Eigen::MatrixXd box = get_bounding_box_2d(flatObj.fV);
islandsBoxs.push_back(box);
if (box.col(1)(1)-box.col(0)(1) > deltaY) {
deltaY = box.col(1)(1)-box.col(0)(1);
boundingBox = box;
}
}
std::cout << "island # = " << this->flattenObjs.size() << std::endl;
for (FlattenObject &flatObj: this->flattenObjs) {
std::cout << "mesh # = " << flatObj.fV.cols()/3 << std::endl;
}
// arrange the layout of islands on paper
double maxW = 0.;
for (auto box: islandsBoxs) {
maxW = fmax(maxW, box.col(1).x()-box.col(0).x());
}
double paperL = 0., paperT = 0., paperR = maxW, paperB = 0.;
double curX = paperL, curY = paperT;
double margin = 0.1;
for (int i = 0; i < this->flattenObjs.size(); i++) {
FlattenObject &flatObj = this->flattenObjs[i];
Eigen::Matrix2d box = islandsBoxs[i];
double w = box.col(1).x()-box.col(0).x(), h = box.col(1).y()-box.col(0).y();
if (curX+w+margin > paperR) {
curX = paperL;
curY = paperB;
}
islandMoveTo(curX, curY, box, flatObj);
curX += w+margin;
paperB = fmin(paperB, curY-(h+margin));
}
// scale the whole paper to fit the window
double scaleFactor = fmin(1.0/(paperT-paperB), 1.0/(paperR-paperL));
Eigen::MatrixXd S = Eigen::MatrixXd::Identity(4, 4);
S.col(0)(0) = scaleFactor; S.col(1)(1) = scaleFactor; S.col(2)(2) = scaleFactor;
for (FlattenObject &flatObj: this->flattenObjs) {
flatObj.ModelMat = S*flatObj.ModelMat;
}
// move paper center to the center of the screen
Eigen::Vector4d paperCenter(scaleFactor*(paperL+paperR)/2.0, scaleFactor*(paperT+paperB)/2.0, 0., 1.);
Eigen::Vector4d delta = Eigen::Vector4d(0., 0., 0., 1.)-paperCenter;
for (FlattenObject &flatObj: this->flattenObjs) {
flatObj.translate(delta);
}
}
void islandMoveTo(double l, double t, Eigen::Matrix2d boundBox, FlattenObject &flatObj) {
Eigen::Vector2d leftTop = Eigen::Vector2d(l, t);
double bminx = boundBox.col(0).x(), bmaxy = boundBox.col(1).y();
Eigen::Vector4d bleftTop = Eigen::Vector4d(bminx, bmaxy, 0., 1.);
bleftTop = flatObj.ModelMat*bleftTop;
Eigen::Vector2d delta = leftTop - Eigen::Vector2d(bleftTop.x(), bleftTop.y());
flatObj.translate(Eigen::Vector4d(delta(0), delta(1), 0., 0.));
}
};
class _3dObjectBuffer {
public:
std::vector<_3dObject*> _3d_objs;
_3dObject* selected_obj;
FlattenObject* selected_flat_obj;
int color_idx;
_3dObjectBuffer() {
selected_obj = nullptr;
selected_flat_obj = nullptr;
color_idx = 0;
}
void add_object(std::string off_path) {
this->color_idx = (this->color_idx)%colors.size();
this->color_idx++;
_3d_objs.push_back(new _3dObject(off_path, this->color_idx));
}
bool hit(int subWindow, Eigen::Vector4d ray_origin, Eigen::Vector4d ray_direction, double &ret_dist, int mode=CILCK_ACTION) {
double min_dist = DIST_MAX;
_3dObject* selected = nullptr;
FlattenObject* selected_flat = nullptr;
if (subWindow == LEFTSUBWINDOW) {
// find the hitted 3D object if any
for (auto obj: _3d_objs) {
double dist = DIST_MAX;
if (obj->hit(ray_origin, ray_direction, dist)) {
if (selected == nullptr || min_dist > dist) {
min_dist = dist;
selected = obj;
}
}
}
}
ret_dist = min_dist;
if (mode == CILCK_ACTION) {
this->selected_obj = selected;
this->selected_flat_obj = selected_flat;
}
return selected != nullptr || selected_flat != nullptr;
}
bool translate(Eigen::Vector4d delta) {
if (this->selected_obj != nullptr) {
this->selected_obj->translate(delta);
return true;
}
else if (this->selected_flat_obj != nullptr) {
this->selected_flat_obj->translate(delta);
return true;
}
return false;
}
bool rotate(double degree, Eigen::Vector3d rotateAixs) {
if (this->selected_obj != nullptr) {
auto M = this->get_rotate_mat(degree, rotateAixs);
this->selected_obj->rotate(degree, M);
return true;
}
else if (this->selected_flat_obj != nullptr) {
auto M = this->get_rotate_mat(degree, rotateAixs);
this->selected_flat_obj->rotate(degree, M);
return true;
}
return false;
}
bool scale(double factor) {
if (this->selected_obj != nullptr) {
this->selected_obj->scale(factor);
return true;
}
else if (this->selected_flat_obj != nullptr) {
this->selected_flat_obj->scale(factor);
return true;
}
return false;
}
bool switch_render_mode(int mode) {
if (this->selected_obj == nullptr) return false;
this->selected_obj->render_mode = mode;
return true;
}
bool delete_obj() {
if (this->selected_obj != nullptr) {
this->_3d_objs.erase(std::remove(this->_3d_objs.begin(), this->_3d_objs.end(), this->selected_obj), this->_3d_objs.end());
delete this->selected_obj;
this->selected_obj = nullptr;
return true;
}
return false;
}
Eigen::Matrix4d get_rotate_mat(double angle, Eigen::Vector3d rotateAixs) {
double r = (PI/180) * (angle/2);
double x = rotateAixs.x() * sin(r);
double y = rotateAixs.y() * sin(r);
double z = rotateAixs.z() * sin(r);
double w = cos(r);
Eigen::Matrix4d rotate_mat;
rotate_mat <<
1-2*y*y-2*z*z, 2*x*y-2*z*w, 2*x*z+2*y*w, 0,
2*x*y+2*z*w, 1-2*x*x-2*z*z, 2*y*x-2*x*w, 0,
2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x*x-2*y*y, 0,
0,0,0,1;
return rotate_mat;
}
std::string export_flat_svg(Camera *camera) {
std::stringstream ss;
for (auto it = _3d_objs.rbegin(); it != _3d_objs.rend(); it++) {
for (FlattenObject &flatObj: (*it)->flattenObjs) {
ss << flatObj.export_svg(camera) << std::endl;
}
}
std::string svg_str = ss.str();
return svg_str;
}
};
class Player {
public:
bool playing;
double frames;
int frame;
std::queue<Mesh*> waitlist;
void init(_3dObject* obj3d) {
// FlattenObject& flatObj = obj3d->flattenObjs[0];
for (FlattenObject &flatObj: obj3d->flattenObjs) {
waitlist.push(flatObj.meshes.begin()->second);
}
frames = 10.;
frame = 0;
playing = true;
}
void nextFrame() {
updateAnimateMats();
}
void updateAnimateMats() {
// std::cout << "update animate matrix" << std::endl;
frame += 1;
const double dt = (double)frame/frames;
if (dt > 1.) {
frame = 0;
Mesh* root = waitlist.front();
waitlist.pop();
for (Mesh* child: root->childs) {
child->accR = root->animeM;
waitlist.push(child);
}
}
// BFS update
if (!waitlist.empty()) {
Mesh* root = waitlist.front();
std::queue<Mesh*> q;
q.push(root);
Eigen::Matrix4d R = get_rotate_mat(dt*root->rotRad, root->edgeA, root->edgeB);
root->animeM = root->accR * R;
while (!q.empty()) {
Mesh* cur = q.front();
q.pop();
for (Mesh* child: cur->childs) {
child->animeM = root->animeM;
q.push(child);
}
}
}
else {
playing = false;
std::cout << "end keyframe playing" << std::endl;
}
}
};
class CameraBuffer {
public:
std::vector<Camera*> cameras;
int focusWindow;
CameraBuffer(GLFWwindow* window, int size) {
for (int i = 0; i < size; i++)
cameras.push_back(new Camera(window));
focusWindow = 0;
}
Camera* getCamera() {
return cameras[focusWindow];
}
void updateWindowScale(GLFWwindow* window) {
for (auto camera: cameras) {
camera->update_project_mat(window);
camera->look_at(window);
}
}
};
_3dObjectBuffer* _3d_objs_buffer;
std::vector<_3dObject*>* _3d_objs;
// Camera *camera;
CameraBuffer* camera_buf;
Player player = Player();
void export_svg(GLFWwindow* window) {
std::string svg_str = get_svg_root_template();
// adjust aspect ratio
int width, height;
glfwGetWindowSize(window, &width, &height);
double aspect = (double)width/(double)height;
svg_str = replace_all(svg_str, "$d", std::to_string(-1.0/aspect));
std::cout << "w: " << width << "h: " << height << std::endl;
std::cout << "aspect " << aspect << std::endl;
// flatten objects
std::string flat_svg_str = _3d_objs_buffer->export_flat_svg(camera_buf->getCamera());
svg_str = replace_all(svg_str, "$TG", flat_svg_str);
// Save svg to file
std::ofstream svg_file;
svg_file.open (EXPORT_PATH);
svg_file << svg_str;
svg_file.close();
}
Eigen::Vector4d get_click_position(GLFWwindow* window, int &subWindow) {
// Get the position of the mouse in the window
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
// Get the size of the window
int width, height;
glfwGetWindowSize(window, &width, &height);
// Convert screen position to world coordinates
Eigen::Vector4d p_screen;
// click on right screen
if (xpos > width/2) {
subWindow = RIGHTSUBWINDOW;
p_screen = Eigen::Vector4d((xpos-width/2)*2,height-1-ypos,0.0,1.0);
}
// click on left screen
else {
subWindow = LEFTSUBWINDOW;
p_screen = Eigen::Vector4d(xpos*2,height-1-ypos,0.0,1.0);
}
Camera* camera = camera_buf->getCamera();
Eigen::Vector4d p_canonical((p_screen[0]/width)*2-1,(p_screen[1]/height)*2-1,-camera->n,1.0);
Eigen::Vector4d p_camera = camera->get_project_mat().inverse() * p_canonical;
if (fabs(p_camera(3)-1.0) > 0.001) {
p_camera = p_camera/p_camera(3);
}
Eigen::Vector4d p_world;
if (subWindow == RIGHTSUBWINDOW)
p_world = camera->flatViewMat.inverse() * p_camera;
else if (subWindow == LEFTSUBWINDOW)
p_world = camera->ViewMat.inverse() * p_camera;
return p_world;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
// Convert screen position to world coordinates
int subWindow;
Eigen::Vector4d click_point = get_click_position(window, subWindow);
camera_buf->focusWindow = subWindow;
Camera* camera = camera_buf->getCamera();
// Update the position of the first vertex if the left button is pressed
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
Eigen::Vector4d ray_origin = click_point;
// orth projection
Eigen::Vector4d ray_direction;
if (subWindow == RIGHTSUBWINDOW) {
ray_direction = Eigen::Vector4d(0., 0., -1., 0.);
}
else {
if (camera->project_mode == ORTHO) {
ray_direction = -to_4_vec(camera->forward);
}
else if (camera->project_mode == PERSPECT) {
ray_direction = (click_point-to_4_vec(camera->position)).normalized();
ray_direction(3) = 0.0;
}
}
double dist = 0;
if (_3d_objs_buffer->hit(subWindow, ray_origin, ray_direction, dist)) {
drag = true;
hit_dist = dist;
pre_cursor_point = click_point;
}
}
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
drag = false;
}
}
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
// Convert screen position to world coordinates
int subWindow;
Eigen::Vector4d click_point = get_click_position(window, subWindow);
if (drag) {
Eigen::Vector4d delta = click_point-pre_cursor_point;
_3d_objs_buffer->translate(delta);
pre_cursor_point = click_point;
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
Camera* camera = camera_buf->getCamera();
switch (key)
{
// export svg
case GLFW_KEY_0:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "export SVG");
export_svg(window);
}
break;
// import an object
case GLFW_KEY_1:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "import an object");
_3d_objs_buffer->add_object(CUSTOM_OFF_PATH);
}
break;
// Add a Cube from OFF
case GLFW_KEY_2:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "add a cube");
_3d_objs_buffer->add_object(CUBE_OFF_PATH);
}
break;
// Add a Cone
case GLFW_KEY_3:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "add a cone");
_3d_objs_buffer->add_object(CONE_OFF_PATH);
}
break;
// Add a Ball
case GLFW_KEY_4:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "add a cone");
_3d_objs_buffer->add_object(BALL_OFF_PATH);
}
break;
// Add a Fox
case GLFW_KEY_5:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "add a fox");
_3d_objs_buffer->add_object(FOX_OFF_PATH);
}
break;
// Add a Bunny
case GLFW_KEY_6:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "add a bunny");
_3d_objs_buffer->add_object(BUNNY_OFF_PATH);
}
break;
// Deleta an object
case GLFW_KEY_DELETE:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->delete_obj()) {
glfwSetWindowTitle (window, "deleted one object");
}
}
break;
// Clockwise rotate 10 degree
case GLFW_KEY_H:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->rotate(10, camera->forward)) {
glfwSetWindowTitle (window, "clockwise rotate 10");
}
}
break;
// Counter-clockwise rotate 10 degree
case GLFW_KEY_J:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->rotate(-10, camera->forward)) {
glfwSetWindowTitle (window, "counter-clockwise rotate 10");
}
}
break;
// Scale up 25%
case GLFW_KEY_K:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->scale(1.25)) {
glfwSetWindowTitle (window, "scale up 25%");
}
}
break;
// Scale down 25%
case GLFW_KEY_L:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->scale(1.0/1.25)) {
glfwSetWindowTitle (window, "scale down 25%");
}
}
break;
// move object up (camera up direction)
case GLFW_KEY_W:
if (action == GLFW_PRESS) {
// if (_3d_objs_buffer->translate(Eigen::Vector4d(0., 0.2, 0., 0.))) {
if (_3d_objs_buffer->translate(to_4_vec(camera->up)/10.0)) {
glfwSetWindowTitle (window, "move up");
}
}
break;
// move object down (camera -up direction)
case GLFW_KEY_S:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->translate(-to_4_vec(camera->up)/10.0)) {
glfwSetWindowTitle (window, "move down");
}
}
break;
// move object left (camera -right direction)
case GLFW_KEY_A:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->translate(-to_4_vec(camera->right)/10.0)) {
glfwSetWindowTitle (window, "move left");
}
}
break;
// move object right (camera right direction)
case GLFW_KEY_D:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->translate(to_4_vec(camera->right)/10.0)) {
glfwSetWindowTitle (window, "move right");
}
}
break;
// move object toward camera (camera -forward direction)
case GLFW_KEY_E:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->translate(-to_4_vec(camera->forward)/10.0)) {
glfwSetWindowTitle (window, "move toward camera");
}
}
break;
// move object away from camera (camera forward direction)
case GLFW_KEY_Q:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->translate(to_4_vec(camera->forward)/10.0)) {
glfwSetWindowTitle (window, "move away from camera");
}
}
break;
// Move the camera
case GLFW_KEY_LEFT:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "rotate camera to left 10 degree");
camera->rotate(0, -10);
camera->look_at(window);
}
break;
case GLFW_KEY_RIGHT:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "rotate camera to right 10 degree");
camera->rotate(0, 10);
camera->look_at(window);
}
break;
case GLFW_KEY_UP:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "rotate camera to up 10 degree");
camera->rotate(10, 0);
camera->look_at(window);
}
break;
case GLFW_KEY_DOWN:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "rotate camera to down 10 degree");
camera->rotate(-10, 0);
camera->look_at(window);
}
break;
// zoom in / zoom out
case GLFW_KEY_EQUAL:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "right-subwindow zoom in 10%");
camera->zoom(0.9);
camera->look_at(window);
}
break;
case GLFW_KEY_MINUS:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "left-subwindow zoom out 10%");
camera->zoom(1.0/0.9);
camera->look_at(window);
}
break;
// reset camera
case GLFW_KEY_R:
if (action == GLFW_PRESS) {
glfwSetWindowTitle (window, "reset camera");
camera->reset();
camera->look_at(window);
}
break;
// switch project mode
case GLFW_KEY_M:
if (action == GLFW_PRESS) {
camera->switch_project_mode();
if (camera->project_mode == ORTHO)
glfwSetWindowTitle (window, "switch to ortho projection");
else
glfwSetWindowTitle (window, "switch to perspective projection");
}
break;
// flatten the selected 3d object
case GLFW_KEY_F:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->selected_obj != nullptr && !player.playing) {
glfwSetWindowTitle (window, "flatten the selected 3d object");
_3d_objs_buffer->selected_obj->flatten();
_3d_objs_buffer->selected_flat_obj = nullptr;
}
}
break;
// play animation
case GLFW_KEY_SPACE:
if (action == GLFW_PRESS) {
if (_3d_objs_buffer->selected_obj != nullptr) {
glfwSetWindowTitle (window, "play animation");
player.init(_3d_objs_buffer->selected_obj);
}
}
break;
default:
break;
}
}
int main(void)
{
std::cout << std::setprecision(10);
GLFWwindow* window;
// Initialize the library
if (!glfwInit())
return -1;
// Activate supersampling
glfwWindowHint(GLFW_SAMPLES, 8);
// Ensure that we get at least a 3.2 context
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
// On apple we have to load a core profile with forward compatibility
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(640, 480, "3D Editor", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);
#ifndef __APPLE__
glewExperimental = true;
GLenum err = glewInit();
if(GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
}
glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM
fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
#endif
int major, minor, rev;
major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
// Initialize the OpenGL Program
// A program controls the OpenGL pipeline and it must contains
// at least a vertex shader and a fragment shader to be valid
Program program;
const GLchar* vertex_shader =
"#version 410 core\n"
"in vec4 position;"
"uniform vec3 color;"
"uniform mat4 ViewMat;"
"uniform mat4 ModelMat;"
"uniform mat4 ProjectMat;"
"uniform mat4 AnimateT;"
"out vec3 f_color;"
"void main()"
"{"
" gl_Position = ProjectMat*ViewMat*ModelMat*AnimateT*position;"
" f_color = color;"
"}";
const GLchar* fragment_shader =
"#version 410 core\n"
"in vec3 f_color;"
"out vec4 outColor;"
"uniform vec3 lineColor;"
"uniform int isLine;"
"void main()"
"{"
" if (isLine == 1)"
" outColor = vec4(lineColor, 1.0);"
" else"
" outColor = vec4(f_color, 1.0);"
"}";
// Compile the two shaders and upload the binary to the GPU
// Note that we have to explicitly specify that the output "slot" called outColor
// is the one that we want in the fragment buffer (and thus on screen)
program.init(vertex_shader,fragment_shader,"outColor");
program.bind();
// Register the keyboard callback
glfwSetKeyCallback(window, key_callback);
// Register the mouse callback
glfwSetMouseButtonCallback(window, mouse_button_callback);
// Register the mouse cursor position callback
glfwSetCursorPosCallback(window, cursor_position_callback);
// Update viewport
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// Inital control objects
_3d_objs_buffer = new _3dObjectBuffer();
// camera = new Camera(window);
camera_buf = new CameraBuffer(window, 2);
// bind light
// auto light = _3d_objs_buffer->ray_tracer->lights[0];
// glUniform4fv(program.uniform("light.position"), 1, light->position.data());
// glUniform3fv(program.uniform("light.intensities"), 1, light->intensity.data());
// bind special colors
Eigen::Vector3d special_color = (SELCET_COLOR.cast<double>())/255.0;
// glUniform3fv(program.uniform("selectedColor"), 1, special_color.data());
special_color = (BLACK.cast<double>())/255.0;
// special_color = (WHITE.cast<double>())/255.0;
glUniform3fv(program.uniform("lineColor"), 1, v_to_float(special_color).data());
Eigen::MatrixXd I44 = Eigen::MatrixXd::Identity(4,4);
// Loop until the user closes the window
while (!glfwWindowShouldClose(window))
{
// Bind your program
program.bind();
// Clear the framebuffer
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Enable depth test
glEnable(GL_DEPTH_TEST);
glEnable(GL_PROGRAM_POINT_SIZE);
// Update window scaling
camera_buf->updateWindowScale(window);
// define render color
Eigen::Vector3d white = (WHITE.cast<double>())/255.0;
Eigen::Vector3d red = (RED.cast<double>())/255.0;
int WindowWidth, WindowHeight;
glfwGetWindowSize(window, &WindowWidth, &WindowHeight);
// right screen
glViewport(WindowWidth, 0, WindowWidth, WindowHeight*2);
// Send the View Mat to Vertex Shader
Camera* rightCam = camera_buf->cameras[1];
Eigen::Vector4d rightCamPos = to_4_point(rightCam->position);
glUniform4fv(program.uniform("viewPosition"), 1, v_to_float(rightCamPos).data());
glUniformMatrix4fv(program.uniform("ViewMat"), 1, GL_FALSE, m_to_float(rightCam->ViewMat).data());
glUniformMatrix4fv(program.uniform("ProjectMat"), 1, GL_FALSE, m_to_float(rightCam->get_project_mat()).data());
if (player.playing) {
player.nextFrame();
}
for (auto obj: _3d_objs_buffer->_3d_objs) {
// prepare
for (FlattenObject &flatObj: obj->flattenObjs) {
glUniformMatrix4fv(program.uniform("ModelMat"), 1, GL_FALSE, m_to_float(flatObj.ModelMat).data());
flatObj.VAO.bind();
program.bindVertexAttribArray("position", flatObj.VBO_P);
glUniform3fv(program.uniform("color"), 1, v_to_float(white).data());
for (int i = 0; i < flatObj.fV.cols(); i += 3) {
// get animation model matrix
int meshId = flatObj.idx2meshId[i];
Mesh* mesh = flatObj.meshes[meshId];
Eigen::Matrix4d AnimateT = mesh->animeM;
// std::cout << "AnimateT" << std::endl;
// std::cout << AnimateT << std::endl;
glUniformMatrix4fv(program.uniform("AnimateT"), 1, GL_FALSE, m_to_float(AnimateT).data());
glUniform1i(program.uniform("isLine"), 1);
glDrawArrays(GL_LINE_LOOP, i, 3);
glUniform1i(program.uniform("isLine"), 0);
glDrawArrays(GL_TRIANGLES, i, 3);
}
}
}
// left screen
glViewport(0, 0, WindowWidth, WindowHeight*2);
// Send the View Mat to Vertex Shader
Camera* leftCam = camera_buf->cameras[0];
Eigen::Vector4d leftCamPos = to_4_point(leftCam->position);
glUniform4fv(program.uniform("viewPosition"), 1, v_to_float(leftCamPos).data());
glUniformMatrix4fv(program.uniform("ViewMat"), 1, GL_FALSE, m_to_float(leftCam->ViewMat).data());
glUniformMatrix4fv(program.uniform("ProjectMat"), 1, GL_FALSE, m_to_float(leftCam->get_project_mat()).data());
glUniformMatrix4fv(program.uniform("ViewMat"), 1, GL_FALSE, m_to_float(leftCam->ViewMat).data());
glUniformMatrix4fv(program.uniform("AnimateT"), 1, GL_FALSE, m_to_float(I44).data());
for (auto obj: _3d_objs_buffer->_3d_objs) {
obj->VAO.bind();
program.bindVertexAttribArray("position",obj->VBO_P);
glUniformMatrix4fv(program.uniform("ModelMat"), 1, GL_FALSE, m_to_float(obj->ModelMat).data());
for (int i = 0; i < obj->meshes.size(); i++) {
if (obj->selectedMeshes.find(i) != obj->selectedMeshes.end()) {
glUniform3fv(program.uniform("color"), 1, v_to_float(red).data());
}
else {
glUniform3fv(program.uniform("color"), 1, v_to_float(white).data());
}
glUniform1i(program.uniform("isLine"), 1);
glDrawElements(GL_LINE_LOOP, 3, GL_UNSIGNED_INT, (void*)(sizeof(int)* (i*3)));
glUniform1i(program.uniform("isLine"), 0);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, (void*)(sizeof(int)* (i*3)));
}
}
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
// Deallocate opengl memory
program.free();
// Deallocate glfw internals
glfwTerminate();
return 0;
} | true |
eaefa575d6f039e422c861e12c148ebe07dbf881 | C++ | jasonjamet/CUDAisation | /CUDAisationCANSI/main.cpp | UTF-8 | 4,001 | 2.703125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include "node.hpp"
#include "CodeGen.hpp"
#include "CodeString.hpp"
#include "set"
#include "algorithm"
extern FILE *yyin;
extern int yyparse();
extern TranslationUnit* root;
bool checkExtentionFile(char* fileName) {
if(fileName != NULL) {
std::string fileNameStr = fileName;
std::string fileExtention = fileNameStr.substr(fileNameStr.find(".")+1);
return (fileExtention == "c" || fileExtention == "cpp");
} else {
return true;
}
}
void generateXmlOutput(std::string outputFileName, bool show) {
if(outputFileName != "") {
if(outputFileName.find(".") != std::string::npos) {
FILE *outFile_p;
outFile_p=fopen(outputFileName.c_str(),"w");
if(outFile_p == NULL) {
printf("couldn't open temp for writting\n");
exit(0);
} else {
fputs(root->toStdString().c_str(),outFile_p);
fclose(outFile_p);
}
}
}
if(show) {
std::cout << root->toStdString() << std::endl;
}
}
void generateCcodeOutput(std::string outputFileName, bool show) {
CodeBlock *context = new CodeBlock();
root->toPrettyCode(context);
if(outputFileName != "") {
FILE *outFile_p;
outFile_p=fopen(outputFileName.c_str(),"w");
if(outFile_p == NULL) {
printf("couldn't open temp for writting\n");
exit(0);
} else {
fputs(context->toPrettyCode().c_str(),outFile_p);
fclose(outFile_p);
}
}
if(show) {
std::cout << context->toPrettyCode();
}
}
void help() {
std::cout << "Transforms \"C\" functions to \"CUDA\" functions." << std::endl
<< "Usage: cudaparse [OPTION] [FILE]" << std::endl
<< std::endl
<< "Example: cudaparse main.c" << std::endl
<< "-x \t\t Print an XML representation of the tree (build from ANSI-C)." << std::endl
<< "-c \t\t Print the C code with cuda kernel(s)." << std::endl
<< "-o OUTPUT_FILE \t Save the result on a file, depend to the prints options (if none, store the c result)." << std::endl
<< "-h \t Print help informations." << std::endl;
}
int main(int argc, char **argv) {
int opt = 0;
bool showXml = false;
bool showC = false;
std::string outputFileName = "";
while ((opt = getopt(argc, argv, "xco:h")) != -1) {
switch(opt) {
case 'x':
showXml = true;
break;
case 'c':
showC = true;
break;
case 'o':
if(optarg == NULL || optarg == argv[argc-1]) {
std::cout << "Option -o requires an argument. -h for more informations" << std::endl;
return 1;
} else {
std::string outputFileNameStr = optarg;
if(outputFileNameStr.find("-") != std::string::npos) {
std::cout << "Option -o requires an argument. -h for more informations" << std::endl;
return 1;
}
outputFileName = optarg;
}
break;
case 'h':
case '?':
if (optopt == 'o') {
fprintf (stderr, "Option -%c requires an argument. -h for more informations\n", optopt);
}
else if (isprint (optopt)) {
fprintf (stderr, "Unknown option `-%c'. -h for more informations\n", optopt);
}
help();
return 1;
default:
help();
return 1;
}
}
if(argc < 2) {
std::cout << "Please specify an input file" << std::endl;
return 1;
} else {
if(checkExtentionFile(argv[argc-1])) {
yyin=fopen(argv[argc-1],"r+");
if(yyin == NULL) {
std::cout << "Couldn't open file" << std::endl;
return 1;
} else {
if(yyparse() == 0) {
integrityTest();
if(showC && showXml && outputFileName != "") {
generateXmlOutput("", true);
generateCcodeOutput(outputFileName.c_str(), true);
} else if(!showC && !showXml && outputFileName == "") {
generateCcodeOutput("", true);
} else {
generateXmlOutput(outputFileName.c_str(), showXml);
generateCcodeOutput(outputFileName.c_str(), showC);
}
} else {
std::cout << "Error during the parse of the file." << std::endl;
}
fclose(yyin);
}
} else {
std::cout << "Please specify a C or C++ input file" << std::endl;
}
}
return 0;
}
| true |
98480daa16cf98130ce32af8c80a70017656df80 | C++ | mnetoiu/SensorsMaps | /SensorsMaps/dht-light-co-blue.ino | UTF-8 | 1,451 | 2.6875 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <SimpleDHT.h>
SoftwareSerial MyBlue(2, 3); // RX | TX
int pinDHT11 = 7;
SimpleDHT11 dht11;
int sensorPin = 2; //define analog pin 2 for light sensor
int sensorCO = 0; // define analog pin 0 for CO sensor
int light = 0;
int valueCO;
void setup() {
Serial.begin(9600);
MyBlue.begin(9600); //Baud Rate for AT-command Mode.
}
void loop() {
// read light sensor and DHT
light = (1023 - analogRead(sensorPin)) / 10.2;
valueCO = analogRead(sensorCO);
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
return;
}
Serial.print("Temperature: ");
Serial.print((int)temperature); Serial.println(" °C");
MyBlue.print((int)temperature); MyBlue.print(" °C");
MyBlue.print("|");
Serial.print("Humidity: ");
Serial.print((int)humidity); Serial.println(" %");
MyBlue.print((int)humidity); MyBlue.print(" %");
MyBlue.print("|");
Serial.print("Luminosity: ");
Serial.println(light, DEC); // light intensity
MyBlue.print(light, DEC); MyBlue.print(" %"); // light intensity
MyBlue.print("|");
Serial.print("CO value: ");
Serial.println(valueCO, DEC); // light intensity
MyBlue.print(valueCO, DEC); // light intensity
// DHT11 sampling rate is 1HZ.
delay(10000);
}
| true |
d6aa89dbfe2ff91e7a6395f67f2b8f88f84259eb | C++ | Pycorax/StateMachine | /Source/FiniteStateMachine.h | UTF-8 | 2,289 | 3.453125 | 3 | [] | no_license | /******************************************************************************/
/*!
\file NPC.h
\author Tng Kah Wei
\brief
NPC Finite State Machine interface class to turn any object into a Finite
State Machine.
*/
/******************************************************************************/
#ifndef FINITE_STATE_MACHINE_H
#define FINITE_STATE_MACHINE_H
// STL Includes
#include <string>
// Using Directives
using std::string;
namespace StateMachine
{
// Forward Declarations
class ConcurrentStateMachine;
/******************************************************************************/
/*!
Class FiniteStateMachine:
\brief Finite State Machine interface class meant to provide Finite
State Machine functionality to inherited classes.
To use this class, simply inherit from it and define FSMStates for
it. Said FSMStates should be declared as friend classes of the
NPC.
To set the starting state, use setCurrentState() to specify the
state to use. setCurrentState() will automatically call the Init()
of the state.
m_currentState and m_previousState are hidden so as to abstract
the data away from the user.
*/
/******************************************************************************/
class FiniteStateMachine
{
/*
* State Classes Friend Declarations
* States should be able to access this class's properties
*/
friend class State;
private:
// Stores the current state of this character
State* m_currentState;
// Stores a state that is set to deletion
State* m_previousState;
// Stores a parent ConcurrentStateMachine*
ConcurrentStateMachine* m_parent;
public:
FiniteStateMachine();
virtual ~FiniteStateMachine() = 0;
virtual void Update(double dt);
virtual void Exit(void);
// Getters
virtual string GetStateName(void);
virtual string GetThisStateName(void);
virtual string GetChildStateName(void);
protected:
// Use this function to set the current state. Automatically calls the state's Init() and destroys the previous state.
void setCurrentState(State* startState);
// Functions exposed for FiniteStateMachineInstance() for use with ConcurrentStateMachine
void setParent(ConcurrentStateMachine* csm);
public:
ConcurrentStateMachine* GetParent(void) const;
};
}
#endif | true |
8153bab6fe2e45cb937543d2e04565103a4542b2 | C++ | ing181/arduino.3 | /C++/2020-11-18/första_programmet.cpp | UTF-8 | 228 | 2.5625 | 3 | [] | no_license | // Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
// En kommentar, bara för programmeraren
// skärmen utmatningsoperatorn "Det som matas ut" ;
cout << "Hej pa dig";
}
| true |
086d83eb8ceb34277f0b2e4f5eeb8eb48ed014c1 | C++ | kodekill/Keyboard-Prank | /Keyboard_Mouse.ino | UTF-8 | 1,517 | 3.09375 | 3 | [] | no_license | #include <Mouse.h>
#include <Keyboard.h>
#define MIN 5000 //5 seconds
#define MAX 15000 //15 seconds
#define KEYL 33 //Lowest Ascii Dec
#define KEYH 126 //High Ascii Dec
#define DEL 8 //Delete key
int mouseState = 0;
int LED = 17;
int choice = 0;
void setup() {
Mouse.begin();
Keyboard.begin();
pinMode(LED, OUTPUT);
randomSeed(analogRead(0));
choice = random((100%4));
Serial.begin(9600);
}
void loop(){
Pick_Prank(choice);
//LED_Blink();
Serial.println(choice);
}
void Pick_Prank(int choice){
switch (choice){
case 1:
random_click();
break;
case 2:
sparatic();
break;
case 3:
delete_Everything();
break;
case 4:
random_Key();
break;
}
}
// sends random clicks
void random_click(){
unsigned int interval = random(MIN, MAX);
delay(interval);
Mouse.click();
}
//Sparatic Mouse movements
void sparatic(){
int x = random(51) - 20;
int y = random(51) - 20;
Mouse.move(x,y);
delay(50);
}
// sends random keypresses
void random_Key(){
unsigned int interval = random(MIN, MAX);
delay(interval);
for (int i = 0; i <= (interval%5); i++){
unsigned int key_value = random(KEYL, KEYH);
Keyboard.write(key_value);
delay(10);
Keyboard.release(key_value);
}
}
//hold down delete key
void delete_Everything(){
Keyboard.write(DEL);
delay(200);
}
//LED blinks just for testing purposes
void LED_Blink(){
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
delay(200);
}
| true |
d1dd9541e246c805cca17c8f84d411b868f58b80 | C++ | abmodi/TC | /Div2/SRM650A/SRM650A/Source.cpp | UTF-8 | 445 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<set>
using namespace std;
class TaroJiroDividing
{
public:
int getNumber(int A, int B)
{
int count = 0;
set<int> a;
while (A%2 == 0 && A != 0)
{
a.insert(A);
A = A / 2;
}
a.insert(A);
while (B % 2 == 0 && B != 0)
{
if (a.find(B) != a.end())
++count;
B = B / 2;
}
if (a.find(B) != a.end())
++count;
return count;
}
};
| true |
9622011e07107793fb278ed9652a58ebab9ebdcb | C++ | qjagh95/MyData | /MyMap/MyMap.h | UHC | 8,028 | 3.28125 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#define TrueAssert(p) assert(!(p))
template<typename T1, typename T2>
class MyMap
{
private:
class Node
{
public:
Node() :Left(NULL), Right(NULL), Top(NULL)
{
memset(&Key, 0, sizeof(T1));
memset(&Data, 0, sizeof(T2));
}
Node(const T1& _Key, const T2& _Data) :Key(_Key), Data(_Data), Left(NULL), Right(NULL), Top(NULL) {}
~Node()
{
if (Left != NULL)
{
delete Left;
Left = NULL;
}
if (Right != NULL)
{
delete Right;
Right = NULL;
}
}
T1 GetKey() const { return Key; }
T2 GetData() const { return Data; }
//ȸ
void FirstOrder()
{
//Ʈ Ű
cout << Key << endl;
//Ʈ Left FirstOrder
if (Left != NULL)
Left->FirstOrder();
//Ʈ Right FirstOrder
if (Right != NULL)
Right->FirstOrder();
// ݺ Ͽ Left Left // Right Right ϸ ȸѴ.
}
//ȸ
void MidOrder()
{
if (Left != NULL)
Left->MidOrder();
cout << Key << endl;
if (Right != NULL)
Right->MidOrder();
}
//ȸ
void LastOrder()
{
if (Left != NULL)
Left->LastOrder();
if (Right != NULL)
Right->LastOrder();
cout << Key << endl;
}
void ReversMid()
{
if (Right != NULL)
Right->ReversMid();
cout << Key << endl;
if (Left != NULL)
Left->ReversMid();
}
//Find()
Node* Find(const T1& _Key)
{
if (Key == _Key)
return this;
if (Key > _Key)
{
if (Left != NULL)
return Left->Find(_Key);
return NULL;
}
else if (Key < _Key)
{
if (Right != NULL)
return Right->Find(_Key);
return NULL;
}
}
T1 Key;
T2 Data;
Node *Left;
Node *Right;
Node *Top;
};
public:
class Iter
{
public:
Iter() : CurNode(NULL) {}
Iter(Node* const _Node) : CurNode(_Node) {}
~Iter() {}
friend class MyMap;
T1& GetKey() const { return CurNode->Key; }
T2& GetData() const { return CurNode->Data; }
void SetKey(const T1& Value) { CurNode->Key = Value; }
Node* GetNode() const { return CurNode; }
bool operator!=(const Iter& _Value) const { return CurNode != _Value.CurNode; }
bool operator >(const Iter& _Value) const { return CurNode > _Value.CurNode; }
bool operator <(const Iter& _Value) const { return CurNode < _Value.CurNode; }
Iter& operator++(int)
{
if (CurNode->Right != NULL) ///üũ ؾѴ. ( ū üũؾߵDZ)
{
CurNode = CurNode->Right; ///
while (CurNode->Left != NULL) /// Left üũؼ Left ٽ ű
CurNode = CurNode->Left;
}
else
{
// Top NULL ƴϰ(Ʈ尡 ƴϰ)
// Top Right ٸ
while (CurNode->Top != NULL && CurNode->Top->Right == CurNode)
CurNode = CurNode->Top;
//while ĭ Ű
CurNode = CurNode->Top;
}//else
return (Iter&)CurNode->Key;
}//operator++()
private:
Node* CurNode;
};
public:
MyMap() : Size(0), RootNode(NULL) {}
~MyMap()
{
if (RootNode == NULL)
return;
delete RootNode;
RootNode = NULL;
}
//ͻ
void Insert(const T1& Key, const T2& Data)
{
Size++;
Node* NewNode = new Node(Key, Data);
if (Size == 1) //ó߰ϴ³ (Ʈ)
RootNode = NewNode;
else //ó߰ϴ° ƴ϶
{
if (RootNode == NULL)
return;
Node* TempNode = RootNode;
for (size_t i = 0; i < Size; i++) ///Ʈ ü ŭ
{
if (TempNode->Key > NewNode->Key)
{
if (TempNode->Left == NULL) /// ãҴ űѴ
{
TempNode->Left = NewNode;
NewNode->Top = TempNode;
}
TrueAssert(TempNode->Key == NewNode->Key); ///Ű ٸ .
TempNode = TempNode->Left; /// Ѱܶ~
}
else if (TempNode->Key < NewNode->Key)
{
if (TempNode->Right == NULL) /// ãҴ ű Ѵ
{
TempNode->Right = NewNode;
NewNode->Top = TempNode;
}
TrueAssert(TempNode->Key == NewNode->Key);
TempNode = TempNode->Right;
}
}//for(size)
}//else
}//insert()
Iter Begin()
{
Node* TempNode = RootNode;
while (TempNode->Left != NULL)
TempNode = TempNode->Left;
return TempNode;
}
Iter End()
{
return NULL;
}
Iter Find(const T1& KeyValue)
{
Node* TempNode = RootNode;
while (TempNode != NULL) ///° ũ Left Right ˾Ƽ ãư.
{
if (TempNode->Key == KeyValue)
return TempNode;
else if (TempNode->Key < KeyValue)
TempNode = TempNode->Right;
else if (TempNode->Key > KeyValue)
TempNode = TempNode->Left;
}
return NULL;
// Find
//return RootNode->Find(KeyValue);
}
void Delete(Iter _Iter)
{
Node* EraseNode = _Iter.CurNode;
if (EraseNode == NULL)
return;
if (EraseNode->Left == NULL && EraseNode->Right == NULL && EraseNode->Top != NULL) ///ڽ ƹ͵
{
if (EraseNode->Top->Left == EraseNode)
EraseNode->Top->Left = NULL;
else if (EraseNode->Top->Left == EraseNode)
EraseNode->Top->Right = NULL;
else
EraseNode = NULL;
}
else if (EraseNode->Left == NULL || EraseNode->Right == NULL) ///ϳ ڽij带
{
if (EraseNode->Left != NULL) ///Left Ҷ
{
EraseNode->Left->Top = EraseNode->Top;
if (EraseNode->Top->Left != NULL)
{
if (EraseNode->Top != RootNode)
EraseNode->Top->Left = EraseNode->Left;
if (EraseNode->Top == RootNode && EraseNode->GetKey() < RootNode->GetKey())
RootNode->Left = EraseNode->Left;
}
else
EraseNode->Top->Right = EraseNode->Left;
EraseNode->Left = NULL;
}
else if (EraseNode->Right != NULL) ///Right Ҷ
{
EraseNode->Right->Top = EraseNode->Top;
if (EraseNode->Top->Left != NULL)
{
if (EraseNode->Top != RootNode)
EraseNode->Top->Left = EraseNode->Left;
if (EraseNode->Top == RootNode && EraseNode->GetKey() > RootNode->GetKey())
RootNode->Right = EraseNode->Right;
}
else
EraseNode->Top->Right = EraseNode->Left;
EraseNode->Right = NULL;
}//else if
} //else(Node->Left || Right != NULL)
else ///ΰ ڽij带 (ٲ)
{
Node* TempNode = EraseNode->Left;
Node* TempRoot = EraseNode;
while (TempNode->Left != NULL) /// Ʈ ū ã´
{
EraseNode = TempNode;
TempNode = TempNode->Right;
}
if (EraseNode->Left == TempNode)
EraseNode->Left = TempNode->Left;
else if (EraseNode->Right == TempNode)
EraseNode->Right = TempNode->Left;
EraseNode->Key = TempNode->Key;
EraseNode = TempNode;
}//else
delete EraseNode;
EraseNode = NULL;
}
//ȸ(־ )
void FirstOrder()
{
//Node Ŭȿ Լ ̿ ȸ
RootNode->FirstOrder();
}
//ȸ( )
void MidOrder()
{
//Node Ŭȿ Լ ̿ ȸ
RootNode->MidOrder();
}
// ȸ
void ReversMid()
{
RootNode->ReversMid();
}
//ȸ( ϸ Ʈ)
void LastOrder()
{
//Node Ŭȿ Լ ̿ ȸ
RootNode->LastOrder();
}
private:
Node* RootNode;
size_t Size;
//Լ ʰ ȸ Ѵٸ ؾ
//û ڵ嵵 ؼ ׳ ͷϴ° ϰ
stack<Node*> RootStack;
};
| true |
aded32f40cdb04b74a5b173c362924f69997512c | C++ | keithalewis/enumerator | /sequence/counted_enumerator_.h | UTF-8 | 2,277 | 3.25 | 3 | [] | no_license | // counted_enumerator_.h - enumerators with a size_t count
#pragma once
#include "enumerator_.h"
namespace fms {
template<class I,
class C = typename std::iterator_traits<I>::iterator_category,
class T = typename std::iterator_traits<I>::value_type,
class D = typename std::iterator_traits<I>::difference_type,
class P = typename std::iterator_traits<I>::pointer,
class R = typename std::iterator_traits<I>::reference>
class counted_enumerator_ : public fms::enumerator_<I,C,T,D,P,R> {
size_t n;
protected:
using fms::enumerator_<I,C,T,D,P,R>::enumerator_::i;
public:
counted_enumerator_(const I& i, size_t n)
: enumerator_<I,C,T,D,P,R>(i), n(n)
{ }
size_t size() const
{
return n;
}
I end() const
{
I e(i);
std::advance(e, n);
return e;
}
operator bool() const
{
return n != 0;
}
counted_enumerator_& operator++()
{
if (n) {
++i;
--n;
}
return *this;
}
counted_enumerator_ operator++(int)
{
counted_enumerator_ i_(*this);
operator++();
return i_;
}
};
template<class I,
class C = typename std::iterator_traits<I>::iterator_category,
class T = typename std::iterator_traits<I>::value_type,
class D = typename std::iterator_traits<I>::difference_type,
class P = typename std::iterator_traits<I>::pointer,
class R = typename std::iterator_traits<I>::reference>
inline counted_enumerator_<I,C,T,D,P,R> counted_enumerator(const I& i, size_t n)
{
return counted_enumerator_<I,C,T,D,P,R>(i, n);
}
// construct from array
template<class T, size_t N>
inline counted_enumerator_<T*> counted_enumerator(T(&a)[N])
{
return counted_enumerator_<T*>(a, N);
}
} // namespace fms
#ifdef _DEBUG
#include <cassert>
inline void test_counted_enumerator()
{
{
int i[] = {0,1,2};
auto e = fms::counted_enumerator(i);
auto e2(e);
e = e2;
assert (e.size() == 3);
assert (e);
assert (*e == 0);
assert (*++e == 1);
assert (e.size() == 2);
assert (*e++ == 1);
assert (e.size() == 1);
assert (*e == 2);
assert (e);
assert (e++);
assert (!e);
assert (!++e);
assert (e.size() == 0);
}
{
int i[] = {0,1,2};
auto e = fms::counted_enumerator(i);
int s{0};
for (const auto& ei: e)
s += ei;
assert (s == 3);
}
}
#endif | true |
cb82f971ea76dcc580104d40916c25087b30f95d | C++ | Mehwa/Algorithm_Study | /Algorithm_Study_KPark/BJ5022_ConnectLine/BJ5022_ConnectLine.cpp | UTF-8 | 3,256 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int N, M, a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y;
bool map[101][101];
bool visited[101][101];
int dist[101][101];
int dx[4] = { 1, -1, 0, 0 };
int dy[4] = { 0, 0, -1, 1 };
void input() {
cin >> N >> M;
cin >> a1x >> a1y;
cin >> a2x >> a2y;
cin >> b1x >> b1y;
cin >> b2x >> b2y;
memset(map, true, sizeof(map));
map[a1x][a1y] = false;
map[a2x][a2y] = false;
map[b1x][b1y] = false;
map[b2x][b2y] = false;
}
void printInput() {
/*cout << N << " " << M << endl;
cout << a1x << " " << a1y << endl;
cout << a2x << " " << a2y << endl;
cout << b1x << " " << b1y << endl;
cout << b2x << " " << b2y << endl;*/
for (int j = 0; j <= M; j++) {
for (int i = 0; i <= N; i++) {
cout << map[i][j];
}
cout << endl;
}
for (int j = 0; j <= M; j++) {
for (int i = 0; i <= N; i++) {
cout << dist[i][j];
}
cout << endl;
}
}
void init() {
memset(visited, false, sizeof(visited));
memset(dist, 0, sizeof(dist));
}
void initAll() {
memset(map, true, sizeof(map));
memset(visited, false, sizeof(visited));
memset(dist, 0, sizeof(dist));
map[a1x][a1y] = false;
map[a2x][a2y] = false;
map[b1x][b1y] = false;
map[b2x][b2y] = false;
}
int connectLineBFS(int startx, int starty, int endx, int endy) {
queue<pair<int, int> > q;
q.push(make_pair(startx, starty));
visited[startx][starty] = true;
while (!q.empty()) {
pair<int, int> cur = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = cur.first + dx[i];
int ny = cur.second + dy[i];
if (nx == endx && ny == endy) { //destination
dist[nx][ny] = dist[cur.first][cur.second] + 1;
return dist[nx][ny];
}
if (map[nx][ny] && !visited[nx][ny] && 0 <= nx && nx <= N && 0 <= ny && ny <= M) {
q.push(make_pair(nx, ny));
visited[nx][ny] = true;
dist[nx][ny] = dist[cur.first][cur.second] + 1;
}
}
}
return -1; //impossible
}
//backtrack min dist line
void updateMap(int startx, int starty, int endx, int endy, int distance) {
int curx = endx;
int cury = endy;
while (distance > 1) {
for (int i = 0; i < 4; i++) {
int nx = curx + dx[i];
int ny = cury + dy[i];
if (map[nx][ny] && dist[nx][ny] == distance - 1 && 0 <= nx && nx <= N && 0 <= ny && ny <= M) {
map[nx][ny] = false; //mark the way
distance--;
curx = nx;
cury = ny;
break;
}
}
}
}
int main()
{
int dist1 = 0, dist2 = 0, dist3 = 0, dist4 = 0, sum1 = 0, sum2 = 0;
input();
//connect A, B
dist1 = connectLineBFS(a1x, a1y, a2x, a2y);
updateMap(a1x, a1y, a2x, a2y, dist1);
init();
dist2 = connectLineBFS(b1x, b1y, b2x, b2y);
if(0 < dist1 && 0 < dist2) //sum1 possible
sum1 = dist1 + dist2;
initAll();
//connect B, A
dist3 = connectLineBFS(b1x, b1y, b2x, b2y);
updateMap(b1x, b1y, b2x, b2y, dist3);
init();
dist4 = connectLineBFS(a1x, a1y, a2x, a2y);
if(0 < dist3 && 0 < dist4) //sum2 possible
sum2 = dist3 + dist4;
if (sum1==0 && sum2==0) { //if both sum1 and sum2 impossible
cout << "IMPOSSIBLE" << endl;
}
else {
if (sum2 == 0) //if sum2 impossible
cout << sum1 << endl;
else if (sum1 == 0) //if sum1 impossible
cout << sum2 << endl;
else //if both sum1 and sum2 possible
cout << min(sum1, sum2) << endl;
}
}
| true |
08e746ce4fa880884e0daa626f8fd5b7466359f2 | C++ | ryanyl/zombie-dash | /StudentWorld.cpp | UTF-8 | 14,197 | 2.921875 | 3 | [] | no_license | #include "StudentWorld.h"
#include "GameConstants.h"
#include "Level.h"
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip> // defines the manipulator setw
using namespace std;
GameWorld* createStudentWorld(string assetPath)
{
return new StudentWorld(assetPath);
}
// Students: Add code to this file, StudentWorld.h, Actor.h and Actor.cpp
StudentWorld::StudentWorld(string assetPath)
: GameWorld(assetPath)
{}
StudentWorld::~StudentWorld()
{
cleanUp();
}
bool StudentWorld::moveActor(Direction dir, int amt, Actor *a)
{
switch (dir)
{
case 90:
if (canMove(a->getX(), a->getY() + amt, a)) {
a->moveTo(a->getX(), a->getY() + amt);
return true;
}
break;
case 270:
if (canMove(a->getX(), a->getY() - amt, a)) {
a->moveTo(a->getX(), a->getY() - amt);
return true;
}
break;
case 180:
if (canMove(a->getX() - amt, a->getY(), a)) {
a->moveTo(a->getX() - amt, a->getY());
return true;
}
break;
case 0:
if (canMove(a->getX() + amt, a->getY(), a)) {
a->moveTo(a->getX() + amt, a->getY());
return true;
}
break;
}
return false;
}
bool StudentWorld::canMove(double x1, double y1, Actor* a)
{
double x11 = x1 + SPRITE_WIDTH - 1, y11 = y1 + SPRITE_HEIGHT - 1;
double x2 = player->getX(), y2 = player->getY();
double x22 = x2 + SPRITE_WIDTH - 1, y22 = y2 + SPRITE_HEIGHT - 1;
//check if object will intersects with player after movement
if (a != player)
{
if ((x1 <= x22 && x11 >= x2 && y1 < y2 && y11 >= y2) || (x1 <= x22 && x11 >= x2 && y1 > y2 && y1 <= y22)
|| (y1 <= y22 && y11 >= y2 && x1 < x2 && x11 >= x2) || (y1 <= y22 && y11 >= y2 && x1 > x2 && x1 <= x22))
return false;
}
//check if object will intersect with any other solid object after movement
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
if ((*it)->isSolid() && (*it)->isAlive() && *it != a)
{
double x2 = (*it)->getX(), y2 = (*it)->getY();
double x22 = x2 + SPRITE_WIDTH - 1, y22 = y2 + SPRITE_HEIGHT - 1;
if ((x1 <= x22 && x11 >= x2 && y1 < y2 && y11 >= y2) || (x1 <= x22 && x11 >= x2 && y1 > y2 && y1 <= y22)
|| (y1 <= y22 && y11 >= y2 && x1 < x2 && x11 >= x2) || (y1 <= y22 && y11 >= y2 && x1 > x2 && x1 <= x22))
return false;
}
it++;
}
return true;
}
void StudentWorld::ZombieBorn(double x, double y)
{
if (randInt(1, 10) <= 3)
li.push_back(new SmartZombie(x, y, this));
else
li.push_back(new DumbZombie(x, y, this));
}
bool StudentWorld::addFlame(double x, double y, int dir)
{
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
if ((*it)->isFireproof())
{
if (overlap(x, y, (*it)->getX(), (*it)->getY()))
return false;
}
it++;
}
li.push_back(new Flame(x, y, dir, this));
return true;
}
bool StudentWorld::tryAddVomit(double x, double y)
{
bool doIt = (1 == randInt(1, 3)); //one in three chance zombie will do it
list<Actor*>::iterator it = li.begin();
if (overlap(x, y, player->getX(), player->getY()) && doIt)
{
li.push_back(new Vomit(x, y, this));
playSound(SOUND_ZOMBIE_VOMIT);
return true;
}
while (it != li.end())
{
if ((*it)->isAlive() && (*it)->canBeInfected() && overlap(x, y, (*it)->getX(), (*it)->getY()))
{
if (doIt)
{
li.push_back(new Vomit(x, y, this));
playSound(SOUND_ZOMBIE_VOMIT);
return true;
}
}
it++;
}
return false;
}
void StudentWorld::addMine(double x, double y)
{
li.push_back(new Mine(x, y, this));
}
void StudentWorld::addPit(double x, double y)
{
li.push_back(new Pit(x, y, this));
}
void StudentWorld::addVaccine(double x, double y)
{
int dir = 90 * randInt(0, 3);
if (dir == 0)
x += SPRITE_WIDTH;
if (dir == 180)
x -= SPRITE_WIDTH;
if (dir == 90)
y += SPRITE_HEIGHT;
if (dir == 270)
y -= SPRITE_HEIGHT;
list<Actor*>::iterator it = li.begin();
while (it != li.end()) {
if (overlap(x, y, (*it)->getX(), (*it)->getY()))
return;
it++;
}
li.push_back(new VaccinePack(x, y, this));
}
//========PROCESSING=OVERLAPS=============//
bool StudentWorld::overlap(double x1, double y1, double x2, double y2)
{
double diffx = SPRITE_WIDTH / 2;
double diffy = SPRITE_HEIGHT / 2;
x1 += diffx;
x2 += diffx;
y1 += diffy;
y2 += diffy;
return (x1 - x2) * (x1 - x2) + (y1 - y2)*(y1 - y2) <= 100.;
}
void StudentWorld::processFlame(double x, double y)
{
if (overlap(x, y, player->getX(), player->getY())) {
player->setDead();
return; //immmediately return if player dies
}
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
if ((*it)->canBeBurned() && (*it)->isAlive() && overlap(x, y, (*it)->getX(), (*it)->getY()))
(*it)->setDead();
it++;
}
}
void StudentWorld::processVomit(double x, double y)
{
if (overlap(x, y, player->getX(), player->getY())) {
player->setInfect(true);
}
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
if ((*it)->canBeInfected() && (*it)->isAlive() && overlap(x, y, (*it)->getX(), (*it)->getY()))
(*it)->setInfect(true);
it++;
}
}
void StudentWorld::processPit(double x, double y)
{
if (overlap(x, y, player->getX(), player->getY())) {
player->setDead();
return;
}
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
if ((*it)->canBeBurned() && (*it)->isSolid() && (*it)->isAlive() && overlap(x, y, (*it)->getX(), (*it)->getY()))
{
(*it)->setDead();
}
it++;
}
}
bool StudentWorld::processMine(double x, double y)
{
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
if ((*it)->isSolid() && (*it)->canBeBurned() && (*it)->isAlive() && overlap(x, y, (*it)->getX(), (*it)->getY()))
return true;
else if (overlap(x, y, player->getX(), player->getY()))
return true;
it++;
}
return false;
}
void StudentWorld::processExit(double x, double y)
{
list<Actor*>::iterator it = li.begin();
if (overlap(x, y, player->getX(), player->getY()))
player->exitSuccess();
while (it != li.end())
{
if ((*it)->canBeInfected() && (*it)->isAlive() && overlap(x, y, (*it)->getX(), (*it)->getY()))
{
(*it)->exitSuccess();
}
it++;
}
}
//=======FOR=AI=MOVE==========//
double StudentWorld::distance(double x, double y, double x1, double y1)
{
return sqrt((x - x1)*(x - x1) + (y - y1)*(y - y1));
}
double StudentWorld::distanceOfClosestCitizen(double x, double y)
{
list<Actor*>::iterator it = li.begin();
double result = 81;
double dist;
//check distance of all citizens
while (it != li.end())
{
if ((*it)->canBeInfected() && (*it)->isAlive()) {
dist = distance(x, y, (*it)->getX(), (*it)->getY());
if (dist < result)
result = dist;
}
it++;
}
return result;
}
double StudentWorld::distanceOfClosestZombie(double x, double y)
{
list<Actor*>::iterator it = li.begin();
double result = 1000;
double dist;
while (it != li.end())
{
if ((*it)->isSolid() && (*it)->canBeBurned() && !(*it)->canBeInfected() && (*it)->isAlive()) {
dist = distance(x, y, (*it)->getX(), (*it)->getY());
if (dist < result)
result = dist;
}
it++;
}
return result;
}
double StudentWorld::distanceOfPlayer(double x, double y)
{
return distance(x, y, player->getX(), player->getY());
}
Direction StudentWorld::chooseDirectionPlayer(double x, double y, int amt, bool isCit, Actor *a)
{
Direction choice1 = distanceOfPlayer(x, y + amt) < distanceOfPlayer(x, y) ? 90 : 270;
Direction choice2 = distanceOfPlayer(x + amt, y) < distanceOfPlayer(x, y) ? 0 : 180;
if (player->getX() == x) {
return choice1;
}
else if (player->getY() == y) {
return choice2;
}
//if actor being chosen for is a zombie
if (!isCit)
{
if (randInt(0, 1) == 1) {
return choice1;
}
return choice2;
}
//if actor being chosen for is a citizen
else {
if (randInt(0, 1) == 0) {
if (canMoveDir(x, y, choice1, amt, a))
return choice1;
else
return choice2;
}
else {
if (canMoveDir(x, y, choice2, amt, a))
return choice2;
else
return choice1;
}
}
}
Direction StudentWorld::chooseDirectionCitizen(double x, double y, int amt)
{
Direction choice1 = distanceOfClosestCitizen(x, y + amt) < distanceOfClosestCitizen(x, y) ? 90 : 270;
Direction choice2 = distanceOfClosestCitizen(x + amt, y) < distanceOfClosestCitizen(x, y) ? 0 : 180;
if (distanceOfClosestCitizen(x, y) - distanceOfClosestCitizen(x, y + amt) == amt || distanceOfClosestCitizen(x, y) - distanceOfClosestCitizen(x, y + amt) == -amt) {
return choice1;
}
else if (distanceOfClosestCitizen(x, y) - distanceOfClosestCitizen(x + amt, y) == amt || distanceOfClosestCitizen(x, y) - distanceOfClosestCitizen(x + amt, y) == -amt) {
return choice2;
}
else if (randInt(0, 1) == 1) {
return choice1;
}
else {
return choice2;
}
}
Direction StudentWorld::chooseDirectionAwayZombie(double x, double y, Actor *a)
{
Direction choice1 = distanceOfClosestZombie(x, y + 2) < distanceOfClosestZombie(x, y) ? 270 : 90;
Direction choice2 = distanceOfClosestZombie(x + 2, y) < distanceOfClosestZombie(x, y) ? 180 : 0;
bool rand = (randInt(1, 0) == 0);
if (distanceOfClosestZombie(x, y) - distanceOfClosestZombie(x, y + 2) == 2 || distanceOfClosestZombie(x, y) - distanceOfClosestZombie(x, y + 2) == -2) {
if (canMoveDir(x, y, choice1, 2, a))
return choice1;
if (rand)
{
if (canMoveDir(x, y, 180, 2, a))
return 180;
else if (canMoveDir(x, y, 0, 2, a))
return 0;
return 666;
}
if (canMoveDir(x, y, 0, 2, a))
return 0;
else if (canMoveDir(x, y, 180, 2, a))
return 180;
return 666;
}
else if (distanceOfClosestZombie(x, y) - distanceOfClosestZombie(x + 2, y) == 2 || distanceOfClosestZombie(x, y) - distanceOfClosestZombie(x + 2, y) == -2) {
if (canMoveDir(x, y, choice2, 2, a))
return choice2;
if (rand)
{
if (canMoveDir(x, y, 90, 2, a))
return 90;
else if (canMoveDir(x, y, 270, 2, a))
return 270;
return 666;
}
if (canMoveDir(x, y, 270, 2, a))
return 270;
else if (canMoveDir(x, y, 90, 2, a))
return 90;
return 666;
}
double endDist1, endDist2;
if (choice1 == 270)
endDist1 = distanceOfClosestZombie(x, y - 2);
if (choice1 == 90)
endDist1 = distanceOfClosestZombie(x, y + 2);
if (choice2 == 0)
endDist2 = distanceOfClosestZombie(x + 2, y);
if (choice2 == 180)
endDist2 = distanceOfClosestZombie(x - 2, y);
if (endDist1 > endDist2)
{
if (canMoveDir(x, y, choice1, 2, a))
return choice1;
if (canMoveDir(x, y, choice2, 2, a))
return choice2;
return 666;
}
if (canMoveDir(x, y, choice2, 2, a))
return choice2;
if (canMoveDir(x, y, choice1, 2, a))
return choice1;
return 666;
}
bool StudentWorld::canMoveDir(double x, double y, Direction dir, int amt, Actor *a)
{
switch (dir)
{
case 0:
return canMove(x + amt, y, a);
break;
case 180:
return canMove(x - amt, y, a);
break;
case 90:
return canMove(x, y + amt, a);
break;
case 270:
return canMove(x, y - amt, a);
break;
default:
return false;
}
}
//===========MAIN=THREE=FUNCTIONS===========//
int StudentWorld::init()
{
m_playerFinished = false;
m_numCit = 0;
if (getLevel() > 99)
return GWSTATUS_PLAYER_WON;
Level lev(assetPath());
ostringstream lvl;
lvl.fill('0');
lvl << "level" << setw(2) << getLevel() << ".txt";
cout << lvl.str();
Level::LoadResult result = lev.loadLevel(lvl.str());
if (result == Level::load_fail_file_not_found)
return GWSTATUS_PLAYER_WON;
else if (result == Level::load_fail_bad_format)
return GWSTATUS_LEVEL_ERROR;
else if (result == Level::load_success)
{
for (int i = 0; i < LEVEL_WIDTH; i++) {
for (int j = 0; j < LEVEL_HEIGHT; j++) {
Level::MazeEntry ge = lev.getContentsOf(i, j);
switch (ge)
{
case Level::wall:
li.push_back(new Wall(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
case Level::player:
player = new Penelope(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this);
break;
case Level::gas_can_goodie:
li.push_back(new Fuel(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
case Level::landmine_goodie:
li.push_back(new MineBox(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
case Level::citizen:
li.push_back(new Citizen(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
m_numCit++;
break;
case Level::exit:
li.push_back(new Exit(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
case Level::vaccine_goodie:
li.push_back(new VaccinePack(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
case Level::dumb_zombie:
li.push_back(new DumbZombie(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
case Level::pit:
li.push_back(new Pit(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
case Level::smart_zombie:
li.push_back(new SmartZombie(SPRITE_WIDTH*i, SPRITE_HEIGHT*j, this));
break;
default:
break;
}
}
}
}
return GWSTATUS_CONTINUE_GAME;
}
int StudentWorld::move()
{
ostringstream oss;
oss << "Score: ";
oss.fill('0');
if (getScore() < 0)
{
oss << "-" << setw(5) << -getScore();
}
else {
oss << setw(6) << getScore();
}
oss.fill(' ');
oss << setw(9) << "Level: " << getLevel();
oss << setw(9) << "Lives: " << getLives();
oss << setw(12) << "Vaccines: " << player->NumVac();
oss << setw(10) << "Flames: " << player->NumFireCharges();
oss << setw(9) << "Mines: " << player->NumMines();
oss << setw(12) << "Infected: " << player->infectionStat();
setGameStatText(oss.str());
if (player->isAlive())
{
player->doSomething();
if (!player->isAlive()) {
decLives();
return GWSTATUS_PLAYER_DIED;
}
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
if ((*it)->isAlive())
{
(*it)->doSomething();
if (!player->isAlive()) {
decLives();
return GWSTATUS_PLAYER_DIED;
}
if (m_playerFinished) {
return GWSTATUS_FINISHED_LEVEL;
}
}
it++;
}
it = li.begin();
while (it != li.end())
{
if (!(*it)->isAlive())
{
//Actor* a = *it;
delete *it;
it = li.erase(it);
//delete a;
}
else
it++;
}
return GWSTATUS_CONTINUE_GAME;
}
else
{
decLives();
return GWSTATUS_PLAYER_DIED;
}
}
void StudentWorld::cleanUp()
{
delete player;
player = nullptr;
list<Actor*>::iterator it = li.begin();
while (it != li.end())
{
Actor* a = *it;
it = li.erase(it);
delete a;
}
} | true |
c629d8e91a6653483fe5cb42f63141699c66756e | C++ | hwiebers19/CS172HW4 | /HW4-CS172/HW4-CS172/Rectangle2D.cpp | UTF-8 | 2,564 | 3.734375 | 4 | [] | no_license | //
// Rectangle2D.cpp
// HW4-CS172
//
// Created by Heidi Wiebers on 10/19/16.
// Copyright © 2016 Heidi Wiebers. All rights reserved.
//
#include "Rectangle2D.hpp"
//argument constructor which uses pointers in it
Rectangle2D::Rectangle2D(int x, int y, int width, int height)
{
this->x=x;
this->y=y;
this->width=width;
this->height=height;
}
//initalizes x, y, width, and height
Rectangle2D::Rectangle2D()
{
x=0;
y=0;
width=1;
height=1;
}
//gets the x value
int Rectangle2D::getx()const
{
return x;
}
//gets the y value
int Rectangle2D::gety()const
{
return y;
}
//sets the x value using a pointer
void Rectangle2D::setx(int x)
{
this->x=x;
}
//sets the y value using a pointer
void Rectangle2D::sety(int y)
{
this->y=y;
}
//gets the width
double Rectangle2D::getwidth()const
{
return width;
}
//gets the height
double Rectangle2D::getheight()const
{
return height;
}
//sets the width with a pointer
void Rectangle2D::setwidth(double width)
{
this->width=width;
}
//sets the height with a pointer
void Rectangle2D::setheight(double height)
{
this->height= height;
}
//gets the area of the rectangle
int Rectangle2D::getArea()const
{
return width*height;
}
//gets the perimeter of the rectangle
int Rectangle2D::getPerimeter()const
{
return width*2 + height*2;
}
//checks if the rectangle contains the point listed
bool Rectangle2D::contains(double x, double y)const
{
return x >= this->x && x <= this->x + this->width && y >= this->y && y <= this->y + this->height;
return false;
}
//checks if the rectangle constains the other rectangle listed
bool Rectangle2D::contains(const Rectangle2D &r)const
{
return contains(r.getx(), r.gety()) &&
contains(r.getx()+ r.getwidth(), r.gety()) &&
contains(r.getx(), r.gety() + r.getheight()) &&
contains(r.getx()+ r.getwidth(), r.gety()+r.getheight());
}
//checks if the rectangle overlaps with the other rectangle listed
bool Rectangle2D::overlaps(const Rectangle2D &r)const
{
return r.contains(r.getx(), r.gety()) ||
r.contains(r.getx()+r.getwidth(), r.gety()) ||
r.contains(r.getx(), r.gety() + r.getheight()) ||
r.contains(r.getx()+r.getwidth(), r.gety()+r.getheight())||
r.contains(this->getx(), this->gety()) ||
r.contains(this->getx()+this->getwidth(), this->gety()) ||
r.contains(this->getx(), this->gety() + this->getheight()) ||
r.contains(this->getx()+this->getwidth(), this->gety()+r.getheight());
}
| true |
d0860604c98ae0217d51c0253c9842a275b78e17 | C++ | samm007aqp/set_problems | /set_problem_4_5/geometry.cpp | UTF-8 | 3,923 | 2.953125 | 3 | [] | no_license | #include "geometry.h"
int Punto::getX()const{
return x;
}
int Punto::getY()const{
return y;
}
void Punto::setX(int new_x){
x= new_x;
}
void Punto::setY(int new_y){
y= new_y;
}
//----------------------------------------------
Arreglo_Puntos::Arreglo_Puntos(){
tamano = 0;
puntos = new Punto[tamano];
}
Arreglo_Puntos::Arreglo_Puntos(const Punto pts[],const int c_tamano){
tamano = c_tamano;
puntos = new Punto[tamano];
for(int i=0; i<tamano;i++) *(puntos+i)= pts[i];
}
Arreglo_Puntos::Arreglo_Puntos ( const Arreglo_Puntos &pts){
tamano = pts.tamano;
puntos = new Punto[tamano];
for(int i=0; i<tamano ; i++) *(puntos + i) = *(pts.puntos +i);
}
Arreglo_Puntos::~Arreglo_Puntos(){
delete [] puntos;
}
void Arreglo_Puntos::Reajustar_tamano(int new_tamano){
Punto *pts = new Punto[new_tamano];
int minimo = (new_tamano > tamano ? tamano : new_tamano);
for (int i=0; i< tamano;i++) *(pts+i) = *(puntos+i);
delete [] puntos;
tamano = new_tamano;
puntos = pts;
}
void Arreglo_Puntos::agregar_p(const Punto &p){
Reajustar_tamano(tamano+1);
*(puntos+tamano-1) = p;
}
void Arreglo_Puntos::limpiar(){
Reajustar_tamano(0);
}
void Arreglo_Puntos::insertar (int posicion, Punto p){
Reajustar_tamano(tamano +1);
for(int i=tamano-2; i>= posicion ;i--)
*(puntos+i+1) = *(puntos+i);
}
void Arreglo_Puntos::remover(int posicion){
for(int i=posicion; i< tamano-1 ;i++){
*(puntos+i) = *(puntos+i+1);}
Reajustar_tamano(tamano-1);
}
int Arreglo_Puntos::get_tamano(){
return tamano;
}
const int Arreglo_Puntos::get_tamano()const{
return tamano;
}
Punto *Arreglo_Puntos::get_punto(int posicion){
return puntos+posicion;
}
const Punto *Arreglo_Puntos::get_punto(int posicion)const {
return puntos+posicion;
}
//***********---------------------------------------------------------------------
int Poligono::num_poligonos = 0;
Poligono::Poligono( const Arreglo_Puntos &x):Apuntos(x)
{num_poligonos++;}
Poligono::Poligono( const Punto a[], const int p_tamano):Apuntos( a , p_tamano){
num_poligonos++;
}
/***********************************************************/
Punto constructorPoints[4];
Punto *updateConstructorPoints(const Punto &p1,const Punto &p2,const Punto &p3,const Punto &p4 = Punto(0,0))
{ constructorPoints [0] = p1 ;
constructorPoints [1] = p2 ;
constructorPoints [2] = p3 ;
constructorPoints [3] = p4 ;
return constructorPoints;
}
Rectangulo::Rectangulo(const Punto &ll, const Punto &ur)
: Poligono(updateConstructorPoints(ll,Punto(ll.getX(),ur.getY()), ur,Punto(ur.getX(),ll.getY())),4){}
Rectangulo::Rectangulo(const int llx, const int lly, const int urx, const int ury) : Poligono(updateConstructorPoints(Punto(llx,lly),Punto(llx,ury),
Punto(urx,ury), Punto(urx,lly)),4){}
double Rectangulo::area() const{
int length = Apuntos . get_punto (1) -> getY () - Apuntos . get_punto (0) -> getY () ;
int width = Apuntos . get_punto (2) -> getX () - Apuntos . get_punto (1) -> getX () ;
return abs((double)length*width);
}
Triangulo::Triangulo(const Punto &a, const Punto &b, const Punto &c)
: Poligono(updateConstructorPoints(a,b,c),3){}
double Triangulo::area()const{
int dx0 = Apuntos . get_punto (0) -> getX () - Apuntos . get_punto (1) -> getX ();
int dx1 = Apuntos . get_punto (1) -> getX () - Apuntos . get_punto (2) -> getX ();
int dx2 = Apuntos . get_punto (2) -> getX () - Apuntos . get_punto (0) -> getX ();
int dy0 = Apuntos . get_punto (0) -> getY () - Apuntos . get_punto (1) -> getY ();
int dy1 = Apuntos . get_punto (1) -> getY () - Apuntos . get_punto (2) -> getY ();
int dy2 = Apuntos . get_punto (2) -> getY () - Apuntos . get_punto (0) -> getY ();
double a = sqrt(dx0*dx0 + dy0*dy0);
double b = sqrt(dx1*dx1 + dy1*dy1);
double c = sqrt(dx2*dx2 + dy2*dy2);
double s=(a +b+c) /2;
return sqrt( s * (s-a)*(s-b)*(s-c) );
}
| true |
ca01d85043ebb614f20c64b6e423a9e8b111d519 | C++ | sandychn/LeetCode-Solutions | /Medium/0207-course-schedule.cpp | UTF-8 | 1,027 | 3.125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> inDegree(numCourses);
vector<vector<int>> edges(numCourses);
for (const vector<int>& edge : prerequisites) {
int a = edge[0], b = edge[1];
edges[b].push_back(a);
++inDegree[a];
}
return toposort(numCourses, inDegree, edges);
}
bool toposort(int n, vector<int>& inDegree, const vector<vector<int>>& edges) {
queue<int> q;
int cnt = 0;
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int now = q.front();
q.pop();
++cnt;
for (size_t i = 0; i < edges[now].size(); i++) {
int to = edges[now][i];
if (--inDegree[to] == 0) {
q.push(to);
}
}
}
return cnt == n;
}
};
| true |
cbaebc3e3dc4293f05ad97cbf796713c8f573cd1 | C++ | dyxcode/DataStructuresAndAlgorithms | /sort(排序)/MergeSort.cpp | GB18030 | 1,582 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <climits>
using namespace std;
//void Merge(int * const first, int * const mid, int * const last) {
// vector<int> left(first, mid);
// vector<int> right(mid, last);
// left.push_back(INT_MAX); //ڱINT_MAXDZȽеĽϴ
// right.push_back(INT_MAX); //ֵINT_MAXС
//
// int i = 0, j = 0;
// for (int k = 0; k < last - first; ++k) {
// if (left[i] <= right[j]) {
// *(first + k) = left[i++];
// } else {
// *(first + k) = right[j++];
// }
// }
//}
void Merge(int * const first, int * const mid, int * const last) {
vector<int> left(first, mid);
vector<int> right(mid, last);
int i = 0, j = 0, k = 0;
while (i != left.size() && j != right.size()) {
if (left[i] <= right[j]) {
*(first + k) = left[i++];
} else {
*(first + k) = right[j++];
}
++k;
}
while (i != left.size()) {
*(first + k) = left[i++];
++k;
}
while (j != right.size()) {
*(first + k) = right[j++];
++k;
}
}
void MergeSort(int * const begin, int * const end) {
if (begin + 1 >= end)
return ;
int m = (end - begin) / 2;
MergeSort(begin, begin + m);
MergeSort(begin + m, end);
Merge(begin, begin + m, end);
}
int main(void) {
int a[9];
int n = 0;
while (cin >> a[n++]);
MergeSort(a, a + 9);
for (int i = 0; i < 9; ++i) {
cout << a[i] << ends;
}
return 0;
}
| true |
39858ad88c31195944c3545670730f3ad880bde9 | C++ | victor-istomin/CodeRacing | /cpp-cgdk/Vec2.h | UTF-8 | 2,569 | 3.640625 | 4 | [] | no_license | #pragma once
#include "Utils.h"
#include <cmath>
template <class T>
class Vec2 {
public:
T m_x, m_y;
Vec2() : m_x(0), m_y(0) {}
Vec2(T x, T y) : m_x(x), m_y(y) {}
Vec2(const Vec2& v) : m_x(v.m_x), m_y(v.m_y) {}
template <typename Point>
static Vec2 fromPoint(const Point& p) { return Vec2(p.x, p.y); }
Vec2& operator=(const Vec2& v) { m_x = v.m_x; m_y = v.m_y; return *this; }
Vec2 operator+(Vec2& v) const { return Vec2(m_x + v.m_x, m_y + v.m_y); }
Vec2 operator-(Vec2& v) const { return Vec2(m_x - v.m_x, m_y - v.m_y); }
Vec2& operator+=(Vec2& v) { m_x += v.m_x; m_y += v.m_y; return *this; }
Vec2& operator-=(Vec2& v) { m_x -= v.m_x; m_y -= v.m_y; return *this; }
Vec2 operator+(double s) const { return Vec2(m_x + s, m_y + s); }
Vec2 operator-(double s) const { return Vec2(m_x - s, m_y - s); }
Vec2 operator*(double s) const { return Vec2(m_x * s, m_y * s); }
Vec2 operator/(double s) const { return Vec2(m_x / s, m_y / s); }
Vec2& operator+=(double s) { m_x += s; m_y += s; return *this; }
Vec2& operator-=(double s) { m_x -= s; m_y -= s; return *this; }
Vec2& operator*=(double s) { m_x *= s; m_y *= s; return *this; }
Vec2& operator/=(double s) { m_x /= s; m_y /= s; return *this; }
Vec2& set(T x, T y) { m_x = x; m_y = y; return *this; }
Vec2& rotate(double deg)
{
double theta = deg / 180.0 * PI;
double c = cos(theta);
double s = sin(theta);
double tx = m_x * c - m_y * s;
double ty = m_x * s + m_y * c;
m_x = static_cast<T>(tx);
m_y = static_cast<T>(ty);
return *this;
}
Vec2& normalize()
{
if (length() == 0)
return *this;
*this /= length();
return *this;
}
double dist(const Vec2& v) const { Vec2 d(v.m_x - m_x, v.m_y - m_y); return d.length(); }
double length() const { return std::hypot(m_x, m_y); }
Vec2& truncate(double length)
{
double a = angle();
m_x = length * cos(a);
m_y = length * sin(a);
return *this;
}
double angle() const
{
return std::atan2(m_y, m_x);
}
Vec2 ortho() const { return Vec2(m_y, -m_x); }
static double dot(const Vec2& v1, const Vec2& v2) { return v1.m_x * v2.m_x + v1.m_y * v2.m_y; }
static double cross(const Vec2& v1, const Vec2& v2) { return (v1.m_x * v2.m_y) - (v1.m_y * v2.m_x); }
static double angleBetween(const Vec2& a, const Vec2& b)
{
double cosine = dot(a, b) / a.length() / b.length();
return std::acos(cosine); // todo - sign?
}
};
typedef Vec2<float> Vec2f;
typedef Vec2<double> Vec2d;
| true |
f8363c2a540ebac191e95da88de378dc926ba452 | C++ | rongrong005/ap | /code/aggregation/ca_code/getsample.cc | UTF-8 | 805 | 2.625 | 3 | [
"MIT"
] | permissive | #include "Global.h"
#define MAX_LINE_SIZE 5000
int main(int argc, char*argv[])
{
int S = atoi(argv[1]);
int N,K;
cin >> N >> K ;
cerr << N << " " << K <<endl;
string line;
getline(cin, line); // clears the endl at the first line
string *LinesSampled = new string [S];
srand48(1973);
for (int i = 0; i < N; i ++){
getline(cin, line);
if (i < S){
LinesSampled[i] = line;
//cout << "line "<<i<<": "<<LinesSampled[i]<<endl;
}else{
int r = (int) floor(drand48() * (i+1));
if (r < S){
LinesSampled[r] = line;
//cout << line<<endl;
//cout << "line "<<r<<": "<<LinesSampled[r]<<endl;
}
}
}
//cout << "\nsample!\n"<<endl;
cout << S << " " << K <<endl;
for (int i = 0; i < S; i ++){
cout << LinesSampled[i]<<endl;
}
}
| true |
2a21501103c2caa9bae03a3c6df21fba32d13698 | C++ | playbyte/Arduino | /LED_Ej2_circle.ino | UTF-8 | 6,817 | 2.671875 | 3 | [] | no_license |
/* ################## TiraLED_WS2812B ####################
* Filename: LED_Ej2_circle.ino
* Descripción: Circulo de Leds
* Autor: Jose Mª Morales
* Revisión: 02-03-2017
* Probado: ARDUINO UNO r3 - IDE 1.8.2 (Windows7)
* Web: www.playbyte.es/electronica/
* Licencia: Creative Commons Share-Alike 3.0
* http://creativecommons.org/licenses/by-sa/3.0/deed.es_ES
* ##############################################################
*/
#include "FastLED.h"
#define DATA_PIN 6 // usamos este pin del ARDUINO
#define NUM_LEDS 12 // Tira de LEDs de 1m con 60leds/m
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB // Depende del fabricante
#define BRIGHTNESS 128
CRGB leds[NUM_LEDS]; // array con el estado de los LED
#define COLOR_LIGHT Magenta
void setup() {
// delay(2000);
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
// FastLED.setBrightness( BRIGHTNESS );
}
void loop() {
// CylonBounce(0xff, 0, 0, 4, 10, 50);
//delay(2000);
// TwinkleRandom(20, 100, false);
// rainbowCycle(20);
// Fire(55,120,15);
byte colors[3][3] = { {0xff, 0,0},
{0xff, 0xff, 0xff},
{0 , 0 , 0xff} };
BouncingColoredBalls(3, colors);
}
//===============================================
void showStrip() {
#ifdef ADAFRUIT_NEOPIXEL_H
// NeoPixel
strip.show();
#endif
#ifndef ADAFRUIT_NEOPIXEL_H
// FastLED
FastLED.show();
#endif
}
void setPixel(int Pixel, byte red, byte green, byte blue) {
#ifdef ADAFRUIT_NEOPIXEL_H
// NeoPixel
strip.setPixelColor(Pixel, strip.Color(red, green, blue));
#endif
#ifndef ADAFRUIT_NEOPIXEL_H
// FastLED
leds[Pixel].r = red;
leds[Pixel].g = green;
leds[Pixel].b = blue;
#endif
}
void setAll(byte red, byte green, byte blue) {
for(int i = 0; i < NUM_LEDS; i++ ) {
setPixel(i, red, green, blue);
}
showStrip();
}
//===============================================
void CylonBounce(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay){
for(int i = 0; i < NUM_LEDS-EyeSize-2; i++) {
setAll(0,0,0);
setPixel(i, red/10, green/10, blue/10);
for(int j = 1; j <= EyeSize; j++) {
setPixel(i+j, red, green, blue);
}
setPixel(i+EyeSize+1, red/10, green/10, blue/10);
showStrip();
delay(SpeedDelay);
}
delay(ReturnDelay);
for(int i = NUM_LEDS-EyeSize-2; i > 0; i--) {
setAll(0,0,0);
setPixel(i, red/10, green/10, blue/10);
for(int j = 1; j <= EyeSize; j++) {
setPixel(i+j, red, green, blue);
}
setPixel(i+EyeSize+1, red/10, green/10, blue/10);
showStrip();
delay(SpeedDelay);
}
delay(ReturnDelay);
}
//===============================================
void TwinkleRandom(int Count, int SpeedDelay, boolean OnlyOne) {
setAll(0,0,0);
for (int i=0; i<Count; i++) {
setPixel(random(NUM_LEDS),random(0,255),random(0,255),random(0,255));
showStrip();
delay(SpeedDelay);
if(OnlyOne) {
setAll(0,0,0);
}
}
delay(SpeedDelay);
}
//===============================================
void rainbowCycle(int SpeedDelay) {
byte *c;
uint16_t i, j;
for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
for(i=0; i< NUM_LEDS; i++) {
c=Wheel(((i * 256 / NUM_LEDS) + j) & 255);
setPixel(i, *c, *(c+1), *(c+2));
}
showStrip();
delay(SpeedDelay);
}
}
byte * Wheel(byte WheelPos) {
static byte c[3];
if(WheelPos < 85) {
c[0]=WheelPos * 3;
c[1]=255 - WheelPos * 3;
c[2]=0;
} else if(WheelPos < 170) {
WheelPos -= 85;
c[0]=255 - WheelPos * 3;
c[1]=0;
c[2]=WheelPos * 3;
} else {
WheelPos -= 170;
c[0]=0;
c[1]=WheelPos * 3;
c[2]=255 - WheelPos * 3;
}
return c;
}
//===============================================
void Fire(int Cooling, int Sparking, int SpeedDelay) {
static byte heat[NUM_LEDS];
int cooldown;
// Step 1. Cool down every cell a little
for( int i = 0; i < NUM_LEDS; i++) {
cooldown = random(0, ((Cooling * 10) / NUM_LEDS) + 2);
if(cooldown>heat[i]) {
heat[i]=0;
} else {
heat[i]=heat[i]-cooldown;
}
}
// Step 2. Heat from each cell drifts 'up' and diffuses a little
for( int k= NUM_LEDS - 1; k >= 2; k--) {
heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3;
}
// Step 3. Randomly ignite new 'sparks' near the bottom
if( random(255) < Sparking ) {
int y = random(7);
heat[y] = heat[y] + random(160,255);
//heat[y] = random(160,255);
}
// Step 4. Convert heat to LED colors
for( int j = 0; j < NUM_LEDS; j++) {
setPixelHeatColor(j, heat[j] );
}
showStrip();
delay(SpeedDelay);
}
void setPixelHeatColor (int Pixel, byte temperature) {
// Scale 'heat' down from 0-255 to 0-191
byte t192 = round((temperature/255.0)*191);
// calculate ramp up from
byte heatramp = t192 & 0x3F; // 0..63
heatramp <<= 2; // scale up to 0..252
// figure out which third of the spectrum we're in:
if( t192 > 0x80) { // hottest
setPixel(Pixel, 255, 255, heatramp);
} else if( t192 > 0x40 ) { // middle
setPixel(Pixel, 255, heatramp, 0);
} else { // coolest
setPixel(Pixel, heatramp, 0, 0);
}
}
//===============================================
void BouncingColoredBalls(int BallCount, byte colors[][3]) {
float Gravity = -9.81;
int StartHeight = 1;
float Height[BallCount];
float ImpactVelocityStart = sqrt( -2 * Gravity * StartHeight );
float ImpactVelocity[BallCount];
float TimeSinceLastBounce[BallCount];
int Position[BallCount];
long ClockTimeSinceLastBounce[BallCount];
float Dampening[BallCount];
for (int i = 0 ; i < BallCount ; i++) {
ClockTimeSinceLastBounce[i] = millis();
Height[i] = StartHeight;
Position[i] = 0;
ImpactVelocity[i] = ImpactVelocityStart;
TimeSinceLastBounce[i] = 0;
Dampening[i] = 0.90 - float(i)/pow(BallCount,2);
}
while (true) {
for (int i = 0 ; i < BallCount ; i++) {
TimeSinceLastBounce[i] = millis() - ClockTimeSinceLastBounce[i];
Height[i] = 0.5 * Gravity * pow( TimeSinceLastBounce[i]/1000 , 2.0 ) + ImpactVelocity[i] * TimeSinceLastBounce[i]/1000;
if ( Height[i] < 0 ) {
Height[i] = 0;
ImpactVelocity[i] = Dampening[i] * ImpactVelocity[i];
ClockTimeSinceLastBounce[i] = millis();
if ( ImpactVelocity[i] < 0.01 ) {
ImpactVelocity[i] = ImpactVelocityStart;
}
}
Position[i] = round( Height[i] * (NUM_LEDS - 1) / StartHeight);
}
for (int i = 0 ; i < BallCount ; i++) {
setPixel(Position[i],colors[i][0],colors[i][1],colors[i][2]);
}
showStrip();
setAll(0,0,0);
}
}
| true |
53b2402ee72c606397c082a9a1ff29ff0d2817b9 | C++ | jcschefer/icpc-practice | /2018-17-18/c.cpp | UTF-8 | 624 | 2.859375 | 3 | [] | no_license | #include <unordered_set>
#include<iostream>
using namespace std;
long calc(unordered_set<int> avoids, int targetsum, int sofar) {
if (sofar == targetsum) return 1;
int s = 0L;
for (int k = 1; k < targetsum; k++) {
if (avoids.find(k) == avoids.end()) {
//cout <<"adding"<<endl;
s += calc(avoids, targetsum - k, sofar+1);
}
}
return sofar +s;
}
int main() {
int p;
cin >> p;
for (int k = 0; k < p; k++) {
int trial;
int n,m,ks;
cin >> trial>>n>>m>>ks;
unordered_set<int> avoids;
while (m <= n) {
avoids.insert(m);
m += ks;
}
cout << trial << " " << calc(avoids, n,0) << endl;
}
}
| true |
495694d2bc70b98e3be29c120fa8805f4292fc32 | C++ | vishwesh-mishra/SnakeAndLadder | /Services/Game.h | UTF-8 | 383 | 2.859375 | 3 | [] | no_license | #pragma once
#include<map>
#include<string>
using namespace std;
class Game {
public:
map<string, int> playerPosition;
map<int, int> snakeLadder;
Game();
void readInput();
void printOutput(string player, int diceRoll, int startPosition, int endPosition);
void addSnakeLadder(int headStart, int tailEnd);
void addPlayer(string name);
int rollDice();
string runGame();
};
| true |
58fb0b9f126252508ca61492ac135d2898081f41 | C++ | manavsiddharthgupta/practice1 | /add.cpp | UTF-8 | 118 | 2.78125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a=8;
int b=90;
cout<<"sum of a and b is- "<<endl<<a+b;
} | true |
f1664a10854996a7d1af5adf297fb9732eb55472 | C++ | rezanour/randomoldstuff | /Main/GDK/Runtime/Public/Common/FileSystem.h | UTF-8 | 797 | 2.671875 | 3 | [] | no_license | #pragma once
#include "Platform.h"
#include <string>
#include <memory>
namespace GDK
{
namespace FileSystem
{
// root - Path to ZIP file or directory for volume.
// logicalRoot - The logical root of the volume. For example you could pass in "Media\Textures" and
// then this volume would only be used to load content that starts with "Media\Textures".
// priority - A priority order for content to consider this volume. Higher priority volumes are checked first.
void MountVolume(_In_ const std::wstring &root, _In_ const std::wstring &logicalRoot, _In_ int32_t priority);
// Opens a stream to the given file in the volumes mounted
std::shared_ptr<std::istream> OpenStream(_In_ const std::wstring &filename);
}
} | true |
572934efdea7ac1f8936e713b5a5a3e70e33b3b9 | C++ | jaisong87/Stencil-Calc | /distributedMemoryParallelism/distributedMemStencil.cpp | UTF-8 | 12,881 | 3.015625 | 3 | [] | no_license | /******************************************
*
* distributedMemStencil.cpp - Calculates Stencil
* on distributed memory architecture using MPI
*
*****************************************/
#include<iostream>
#include<sstream>
#include<iomanip>
#include<mpi.h>
using namespace std;
bool enableDebug = false; /* detailed debug flag - dump prints to myStream */
bool dbugFlag2 = false; /* basic debug flag - dump prints to myStream */
bool dumpSelfStream = false; /* Set this to see dbug prints from every worker */
int rank;
stringstream myStream; /* Stream of one worker, */
//#define myStream cout
/* Just an Init-Routine - Performs malloc
*/
bool initArray(float ***& threeDimSpace, int xD, int yD, int zD)
{
if(enableDebug)
myStream<<"Creating "<<xD<<"X"<<yD<<"X"<<zD<<" space for stencil computations"<<endl;
threeDimSpace = new float**[xD];
for(int i=0;i<xD;i++)
{
threeDimSpace[i] = new float*[yD];
for(int j=0;j<yD;j++)
threeDimSpace[i][j] = new float[zD];
}
return true; /* Success! */
}
/* To Deallocate the array */
bool cleanArray(float ***& threeDimSpace, int xD, int yD, int zD)
{
if(enableDebug)
myStream<<"Freeing "<<xD<<"X"<<yD<<"X"<<zD<<" space for stencil computations"<<endl;
for(int i=0;i<xD;i++)
{
for(int j=0;j<yD;j++)
{
delete[] threeDimSpace[i][j];
}
delete[] threeDimSpace[i];
}
delete[] threeDimSpace;
return true;
}
/* print the serial buffer for debug purposes */
void printSerialBuffer(float *buf, int len)
{
stringstream ss1;
ss1<<"SerialStream : ";
for(int i=0;i<len;i++)
ss1<<buf[i]<<' ';
myStream<<ss1.str()<<endl;
return;
}
/* print the 3-D space */
void printResult(float *** threeDimSpace, int xD, int yD, int zD)
{
stringstream ss1;
ss1<<"3D Grid ";
for(int x=0;x<xD;x++,ss1<<endl)
for(int y=0;y<yD;y++,ss1<<endl)
for(int z=0;z<zD;z++)
{
ss1<<setw(10)<<fixed<<threeDimSpace[x][y][z]<<' ';
}
myStream<<ss1.str();
return;
}
/* Copy original Space to a buffer
* There is no check for mallocs, frees, wild-ptrs etc
* Use all the functions carefully
*/
void copySpace(float ***& src, float***& dst, int xD, int yD, int zD)
{
if(enableDebug)
myStream<<"Copying from "<<xD<<"X"<<yD<<"X"<<zD<<" original space for stencil computations"<<endl;
for(int x=0;x<xD;x++)
for(int y=0;y<yD;y++)
for(int z=0;z<zD;z++)
dst[x][y][z] = src[x][y][z];
return;
}
/*Perform serial-stenicl Compuatations */
void computeStencil(float ***& threeDimSpace, float c0, float c1, float c2, float c3, int tf, int xD, int yD, int zD)
{
float *** tmpSpace;
initArray(tmpSpace, xD, yD, zD);
for(int t=1;t<=tf;t++)
{
copySpace(threeDimSpace, tmpSpace, xD, yD, zD);
for(int x =0;x<xD;x++)
for(int y=0;y<yD;y++)
for(int z=0;z<zD;z++)
{
float tmp = c0*tmpSpace[x][y][z];
if(z<(zD-1)) tmp+=(c1+c2+c3)*tmpSpace[x][y][z+1];
if(z>0) tmp+=(c1+c2+c3)*tmpSpace[x][y][z-1];
if(y<(yD-1)) tmp+=(c1+c2+c3)*tmpSpace[x][y+1][z];
if(y>0) tmp+=(c1+c2+c3)*tmpSpace[x][y-1][z];
if(x<(xD-1)) tmp+=(c1+c2+c3)*tmpSpace[x+1][y][z];
if(x>0) tmp+=(c1+c2+c3)*tmpSpace[x-1][y][z];
threeDimSpace[x][y][z] = tmp;
}
}
return;
}
/* serialize the buffer */
void serialize(float*& tmp,float*** origSpace, int dx, int dy, int dz)
{
int ctr= 0;
for(int i=0;i<dx;i++)
for(int j=0;j<dy;j++)
for(int k=0;k<dz;k++)
{
tmp[ctr] = origSpace[i][j][k];
ctr++;
}
return;
}
/* deserialize back the buffer */
bool deserializeBuffer(float***& mySpace, float* buf, int dx, int dy, int dz)
{
int ctr = 0;
for(int i=0;i<dx;i++)
for(int j=0;j<dy;j++)
for(int k=0;k<dz;k++)
{
mySpace[i][j][k] = buf[ctr];
ctr++;
}
return true;
}
int main(int argc, char* argv[])
{
int n=4, q, dx;
float c0 =1,c1=1,c2=1,c3=1, tf=1.0;
float *** threeDimSpace;
float*** finalResult;
float *** workChunk, ***tmpChunk;
float *buf;
int workerCount = 4; /* This means we need workRatio workers */
int myRank, totWorkers;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &totWorkers);
MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
/* The code takes only one instance of Input - For multiple input , we can have a flag and a while loop here for the whole code*/
if(myRank == 0)
{
if(enableDebug)
{
stringstream ss1;
if(dbugFlag2) ss1<<"I'm processor "<<myRank<<" co-ordinating all the work"<<endl;
myStream<<ss1.str();
}
if(cin>>q>>tf) /* Take Arbitrary number of inputs through stdin */
{
myStream<<" =================== MASTER ========================= "<<endl;
n = q;//(1<<q);
cin>>c0>>c1>>c2>>c3;
initArray(threeDimSpace, n, n, n ); /* Initialize the array */
for(int i=0;i<n;i++) /* Get the Input-(original space) */
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
cin>>threeDimSpace[i][j][k];
dx = n/workerCount;
if(dbugFlag2) myStream<<dx<<" sized chunks for "<<workerCount<<" workers"<<endl;
for(int w=1;w<=workerCount;w++)
{
if(dbugFlag2) myStream<<"Sending N to process "<<w<<endl;
MPI_Send(&n, 1, MPI_INT, w, 1, MPI_COMM_WORLD);
}
float params[5];
params[0] = c0;
params[1] = c1;
params[2] = c2;
params[3] = c3;
params[4] = tf;
/* send N to all processors */
for(int w=1;w<=workerCount;w++)
{
if(dbugFlag2) myStream<<"Sending N to process "<<w<<endl;
MPI_Send(¶ms, 5, MPI_FLOAT, w, 5, MPI_COMM_WORLD);
}
buf = new float[dx*n*n];
/* Send the workChunk to all the processors */
for(int w=1;w<=workerCount;w++)
{
serialize(buf, &threeDimSpace[(w-1)*dx], dx, n, n);
printSerialBuffer( buf , dx*n*n);
if(dbugFlag2) myStream<<"Sending workChunk of size "<<dx*n*n<<" to process "<<w<<endl;
MPI_Send((void*)buf, dx*n*n , MPI_FLOAT, w, 2, MPI_COMM_WORLD);
}
}
}
else if(myRank>=1 && myRank <= workerCount ) {
myStream<<" ======================== SLAVE# "<<myRank<<"======================"<<endl;
MPI_Status recvStatus;
MPI_Recv(&n,1, MPI_INT, 0, 1 , MPI_COMM_WORLD, &recvStatus);
float params[5];
MPI_Recv(¶ms, 5, MPI_FLOAT, 0, 5, MPI_COMM_WORLD, &recvStatus);
c0 = params[0];
c1 = params[1];
c2 = params[2];
c3 = params[3];
tf = params[4];
dx = n/workerCount;
initArray(workChunk, dx, n, n);
if(dbugFlag2) myStream<<"In process :"<<myRank<</*" tmpRank = "<<tmpRank<<*/" dx = "<<dx<<" n = "<<n<<endl;
if(dbugFlag2) myStream<<"Process "<<myRank<<" : expecting serialized buffer of size "<<dx*n*n<<" recieved from process0 "<<endl;
buf = new float[dx*n*n];
MPI_Recv((void*)buf, dx*n*n , MPI_FLOAT, 0, 2 , MPI_COMM_WORLD, &recvStatus);
if(dbugFlag2) myStream<<"process "<<myRank<<" : serialized buffer of size "<<dx*n*n<<" recieved from process0 "<<endl;
deserializeBuffer(workChunk, buf, dx, n, n);
printResult(workChunk, dx, n, n);
}
else {
if(enableDebug)
{
stringstream ss1;
if(dbugFlag2) ss1<<"I'm processor "<<myRank<<" idle without any of the work"<<endl;
myStream<<ss1.str();
}
}
stringstream ss2;
if(dbugFlag2) ss2<<"processor "<<myRank<<" finished the job"<<endl;
myStream<<ss2.str();
myStream<<"==============================================================="<<endl;
MPI_Barrier(MPI_COMM_WORLD);
/* We are done with the input . Now Lets start MPI - Phase2 All Calculations */
if(myRank>=1 && myRank<=workerCount)
{
MPI_Request send_req[2], recv_req[2];
MPI_Status stat;
float* histopLayer = new float[3*n*n];
float* mytopLayer = new float[3*n*n];
float* hisbotLayer = new float[3*n*n];
float* mybotLayer = new float[3*n*n];
/* Initialize tmpChunk */
initArray(tmpChunk, dx, n, n);
float C[4] = {c0,c1,c2,c3};
float xaxis, yaxis, zaxis;
xaxis = yaxis =zaxis = 0;
for(int t=0;t< tf;t++)
{
/* copy Space */
for(int tx=0;tx<dx;tx++)
for(int ty=0;ty<n;ty++)
for(int tz=0;tz<n;tz++)
tmpChunk[tx][ty][tz] = workChunk[tx][ty][tz];
/* Perform Computations */
for(int x=0;x<dx;x++)
for(int y=0;y<n;y++)
for(int z=0;z<n;z++)
{
double tmp = 0;
for(int dis=1;dis<=3;dis++)
{
xaxis = yaxis = zaxis = 0;
if(z<(n-dis)) { tmp+=(C[dis])*tmpChunk[x][y][z+dis];
zaxis += tmpChunk[x][y][z+dis];
}
if(z>=dis) { tmp+=(C[dis])*tmpChunk[x][y][z-dis];
zaxis += tmpChunk[x][y][z-dis];
}
if(y<(n-dis)) { tmp+=(C[dis])*tmpChunk[x][y+dis][z];
yaxis += tmpChunk[x][y+dis][z];
}
if(y>=dis) { tmp+=(C[dis])*tmpChunk[x][y-dis][z];
yaxis += tmpChunk[x][y-dis][z];
}
if(x<(n-dis)) { tmp+=(C[dis])*tmpChunk[x+dis][y][z];
xaxis += tmpChunk[x+dis][y][z];
}
if(x>=dis) { tmp+=(C[dis])*tmpChunk[x-dis][y][z];
xaxis += tmpChunk[x-dis][y][z];
}
}
tmp+= c0*tmpChunk[x][y][z];
workChunk[x][y][z] = tmp;
}
/* Construct own topLayer and BottomLayer */
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int l=0;l<3;l++)
{
mytopLayer[l*n*n+i*n+j] = tmpChunk[dx-l-1][i][j];
mybotLayer[l*n*n+i*n+j] = tmpChunk[l][i][j];
}
/* Send and recieve top/bottom layers among themselves */
if(myRank < workerCount) {
MPI_Isend(mytopLayer, n*n, MPI_FLOAT, myRank+1 , 10 + 2 * t, MPI_COMM_WORLD , & send_req[ 0 ] );
MPI_Irecv(hisbotLayer, n*n, MPI_FLOAT, myRank +1, 11 + 2 * t, MPI_COMM_WORLD , & recv_req[ 0 ] );
}
if(myRank > 1)
{
MPI_Isend(mybotLayer, n*n, MPI_FLOAT, myRank -1, 11 + 2 * t, MPI_COMM_WORLD , & send_req[ 1 ] );
MPI_Irecv(histopLayer, n*n, MPI_FLOAT, myRank -1, 10 + 2 * t, MPI_COMM_WORLD , & recv_req[ 1 ] );
}
if(myRank < workerCount) MPI_Wait(&recv_req[0], &stat);
if(myRank > 1) MPI_Wait(&recv_req[1], &stat);
if(myRank < workerCount) MPI_Wait(&send_req[0], &stat);
if(myRank > 1) MPI_Wait(&send_req[1], &stat);
/* Do upate on topLayes/bottom layer by using info gained from neighbour */
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
if(myRank > 1)
{
workChunk[0][i][j]+= (c1)*(histopLayer[i*n+j]);
workChunk[0][i][j]+= (c2)*(histopLayer[n*n+i*n+j]);
workChunk[0][i][j]+= (c3)*(histopLayer[2*n*n+i*n+j]);
workChunk[1][i][j]+= (c2)*(histopLayer[i*n+j]);
workChunk[1][i][j]+= (c3)*(histopLayer[n*n+i*n+j]);
workChunk[2][i][j]+= (c3)*(histopLayer[i*n+j]);
}
if(myRank < workerCount)
{
workChunk[dx-1][i][j]+= (c1)*(hisbotLayer[i*n+j]);
workChunk[dx-1][i][j]+= (c2)*(hisbotLayer[n*n+i*n+j]);
workChunk[dx-1][i][j]+= (c3)*(hisbotLayer[2*n*n+i*n+j]);
workChunk[dx-2][i][j]+= (c2)*(hisbotLayer[i*n+j]);
workChunk[dx-2][i][j]+= (c3)*(hisbotLayer[n*n+i*n+j]);
workChunk[dx-3][i][j]+= (c3)*(hisbotLayer[i*n+j]);
}
}
}
/* Deleye buffers */
delete[] mytopLayer;
delete[] histopLayer;
delete[] hisbotLayer;
delete[] mybotLayer;
}
MPI_Barrier(MPI_COMM_WORLD);
/* Phase 3 - Assemble it back and print*/
if(myRank == 0)
{
initArray(finalResult, n, n, n);
MPI_Status recvStatus;
float* buf = new float[dx*n*n];
for(int i=1;i<=workerCount;i++)
{
MPI_Recv((void*)buf, dx*n*n, MPI_FLOAT, i, 3, MPI_COMM_WORLD, &recvStatus);
/* deserialize the buffer */
int ctr = 0;
for(int x=0;x<dx;x++)
for(int y=0;y<n;y++)
for(int z=0;z<n;z++)
{
finalResult[(i-1)*dx+x][y][z] = buf[ctr];
ctr++;
}
myStream<<" Process#"<<myRank<<"Recieved data from process "<<i<<endl;
}
printResult(finalResult, n, n, n);
}
else if(myRank>=1 && myRank<=workerCount)
{
float* buf = new float[dx*n*n];
serialize(buf, workChunk, dx, n, n);
MPI_Send((void*)buf, dx*n*n, MPI_FLOAT, 0, 3, MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
if(dumpSelfStream)
{
cout<<myStream.str();
}
if(myRank == 0)
{
for(int i=0;i<n;i++,cout<<endl)
for(int j=0;j<n;j++,cout<<endl)
for(int k=0;k<n;k++)
cout<<setw(10)<<fixed<<finalResult[i][j][k]<<' ';
}
return 0;
}
| true |
d0c3ecdeba009aabe7fc43d8ac2719cf79e50618 | C++ | blizmax/XYZEngine-Public | /XYZEngine/src/XYZ/Renderer/Texture.cpp | UTF-8 | 2,362 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #include "stdafx.h"
#include "Texture.h"
#include "Renderer.h"
#include "XYZ/API/OpenGL/OpenGLTexture.h"
namespace XYZ {
Ref<Texture2D> Texture2D::Create(uint32_t width, uint32_t height, uint32_t channels, const TextureSpecs& specs)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
case RendererAPI::API::OpenGL: return Ref<OpenGLTexture2D>::Create(width, height, channels, specs);
}
XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
return nullptr;
}
Ref<Texture2D> Texture2D::Create(const TextureSpecs& specs, const std::string& path)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
case RendererAPI::API::OpenGL: return Ref<OpenGLTexture2D>::Create(specs, path);
}
XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
return nullptr;
}
void Texture2D::BindStatic(uint32_t rendererID, uint32_t slot)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
case RendererAPI::API::OpenGL: OpenGLTexture2D::Bind(rendererID, slot); return;
}
XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
}
uint32_t Texture::CalculateMipMapCount(uint32_t width, uint32_t height)
{
uint32_t levels = 1;
while ((width | height) >> levels)
levels++;
return levels;
}
Ref<Texture2D> Texture2DArray::Create(const TextureSpecs& specs, const std::initializer_list<std::string>& paths)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
case RendererAPI::API::OpenGL: return Ref<OpenGLTexture2DArray>::Create(specs, paths);
}
XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
return nullptr;
}
Ref<Texture2DArray> Texture2DArray::Create(uint32_t count, uint32_t width, uint32_t height, uint32_t channels, const TextureSpecs& specs)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
case RendererAPI::API::OpenGL: return Ref<OpenGLTexture2DArray>::Create(count, width, height, channels, specs);
}
XYZ_ASSERT(false, "Renderer::GetAPI() = RendererAPI::None");
return nullptr;
}
} | true |
dc9fbe00d9ce8687e0a21d82db0962befe152817 | C++ | yku/Competition | /AOJ/0075/BMI.cc | UTF-8 | 424 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
bool solve(int id, double w, double h)
{
double bmi = (w / (h * h));
if(bmi >= 25.0) return true;
else return false;
}
int main()
{
int id;
char comma;
double w, h;
while(cin >> id >> comma >> w >> comma >> h) {
if(solve(id, w, h)) cout << id << endl;
}
return 0;
}
| true |
612a63754513af19b48e4beb9004d5c00cc3eab3 | C++ | dennn66/ArduRoomba | /Firmware/MotorTest/MotorTest.ino | UTF-8 | 2,431 | 2.6875 | 3 | [] | no_license |
#define PIEZOBUZZER
#define LEFT 0
#define RIGHT 1
#ifdef PIEZOBUZZER
#define BUZZER 44 //
#define BUZZER_GND 42 //
void alert(int _times, int _runTime, int _stopTime)
{
for(int _ct=0; _ct < _times; _ct++)
{
delay(_stopTime);
analogWrite(BUZZER, 20); // Almost any value can be used except 0 and 255
delay(_runTime);
analogWrite(BUZZER, 0); // 0 turns it off
}
}
#endif
//1 - left, 2 - right
#define __M1DIR 29
#define __M1PWM 9
#define __M1FB A3
#define __M2DIR 27
#define __M2PWM 10
#define __M2FB A2
#define __nD1 25
#define __nD2 23
#define __nSF 31
/* Include the Pololu library */
#include "DualMC33926MotorShield.h"
/* Create the motor driver object */
// M1DIR, M1PWM, M1FB, M2DIR, M2PWM, M2FB, nD2, nSF
DualMC33926MotorShield drive(__M1DIR, __M1PWM, __M1FB, __M2DIR, __M2PWM, __M2FB, __nD1,__nD2, __nSF);
/* Wrap the motor driver initialization */
void initMotorController() {
drive.init();
}
/* Wrap the drive motor set speed function */
void setMotorSpeed(int i, int spd) {
if (i == LEFT) drive.setM1Speed(spd);
else drive.setM2Speed(spd);
}
// A convenience function for setting both motor speeds
void setMotorSpeeds(int leftSpeed, int rightSpeed) {
setMotorSpeed(LEFT, leftSpeed);
setMotorSpeed(RIGHT, rightSpeed);
}
void setMotorEnableFlag(boolean isEnabled){
// drive.setMotorEnableFlag(isEnabled);
}
boolean isMotorFault(){
return false; //drive.getFault();
}
void setup() {
Serial.begin(57600);
Serial.println("Starting up...");
initMotorController();
}
void loop() {
/*
int reverse = 1;
int speed = 400;
if (reverse){
digitalWrite(__M1DIR,HIGH);
analogWrite(__M1PWM, 255 - speed * 51 / 80); // default to using analogWrite, mapping 400 to 255
}else{
digitalWrite(__M1DIR,LOW);
analogWrite(__M1PWM,speed * 51 / 80); // default to using analogWrite, mapping 400 to 255
}
if (reverse){
digitalWrite(__M2DIR,HIGH);
analogWrite(__M2PWM, 255 - speed * 51 / 80); // default to using analogWrite, mapping 400 to 255
}else{
digitalWrite(__M2DIR,LOW);
analogWrite(__M2PWM,speed * 51 / 80); // default to using analogWrite, mapping 400 to 255
}
*/
for(int i = -400; i<=400; i+=10){
Serial.println(i);
setMotorSpeeds(i, i);
delay(1000);
}
}
| true |
3493a4bc3fade2f18388881b8a787cedc7d19544 | C++ | Egocentrix/CppPractice | /ObjectManager.cpp | UTF-8 | 1,960 | 3.8125 | 4 | [] | no_license | // To practice lifetime management and smart pointers
// See also https://rachelnertia.github.io/programming/2016/11/16/weak-ptr-fun-times/
#include <iostream>
#include <memory>
#include <unordered_map>
// Class to track objects and their existence. Objects will stay in memory as
// long as they are in use, and will be reloaded when they are required again.
// For now only handles objects that can be constructed with one string
// parameter, such as a filename to load the object from.
template <typename T>
class ObjectManager
{
private:
std::unordered_map<std::string, std::weak_ptr<T>> data;
public:
ObjectManager()
{
std::cout << "Constructing Objectmanager for type " << typeid(T).name() << std::endl;
}
~ObjectManager()
{
std::cout << "Desstructing Objectmanager " << typeid(T).name() << std::endl;
}
std::shared_ptr<T> addItem(const std::string key)
{
auto obj = std::make_shared<T>(key);
data[key] = obj;
return obj;
}
bool isKnown(const std::string key) const
{
return data.count(key) != 0;
}
bool isLoaded(const std::string key) const
{
return isKnown(key) && (data.at(key).expired() == false);
}
std::shared_ptr<T> getPointer(const std::string key)
{
if (isLoaded(key))
{
return data.at(key).lock(); // Create shared_ptr from weak_ptr
}
else
{
return addItem(key);
}
}
};
// Simple object for testing
class SimpleObj
{
private:
const std::string name;
public:
SimpleObj(const std::string &name) : name(name)
{
std::cout << "Contructing " << name << std::endl;
}
~SimpleObj()
{
std::cout << "Destructing " << name << std::endl;
}
};
// Main funtion
int main(int, char **)
{
SimpleObj obj1("obj1");
ObjectManager<SimpleObj> objMgr;
auto obj2 = objMgr.getPointer("Obj2");
}
| true |
e649ecb62839f892f5c9979ea49235e5065a7ea5 | C++ | zzm99/Algorithm-and-data-structure | /Datastructure/Sorting/Mergesort for Linked Lists.cpp | UTF-8 | 1,936 | 4.09375 | 4 | [] | no_license | // Merge sort is often preferred for sorting a linked list.
// The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly,
// and others (such as heapsort) completely impossible.
// https://www.geeksforgeeks.org/merge-sort-for-linked-list/
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
};
Node* SortedMerge(Node* a, Node* b);
void FrontBackSplit(Node* source, Node** frontRef, Node** backRef);
void MergeSort(Node** headRef){
Node* head = *headRef;
Node* a;
Node* b;
if((head == NULL) || (head->next == NULL))
return;
FrontBackSplit(head,&a,&b);
MergeSort(&a);
MergeSort(&b);
*headRef = SortedMerge(a, b);
}
Node* SortedMerge(Node* a, Node* b){
Node* result = NULL;
if(a == NULL) return b;
else if(b == NULL) return a;
if(a->data <= b->data){
result = a;
result->next = SortedMerge(a->next, b);
}
else{
result = b;
result->next = SortedMerge(a, b->next);
}
return result;
}
void FrontBackSplit(Node* source, Node** frontRef, Node** backRef){
Node* fast;
Node* slow;
slow = source;
fast = source->next;
while(fast != NULL){
fast = fast->next;
if(fast != NULL){
slow = slow->next;
fast = fast->next;
}
}
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
void push(Node** head_ref, int new_data){
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main(){
Node* a = NULL;
/* Let us create a unsorted linked lists to test the functions
Created lists shall be a: 2->3->20->5->10->15 */
push(&a, 15);
push(&a, 10);
push(&a, 5);
push(&a, 20);
push(&a, 3);
push(&a, 2);
MergeSort(&a);
cout << "Sorted Linked List is: " << endl;
printList(a);
return 0;
} | true |
7852481617da870f7178fb17fcfca0d7fe7634d9 | C++ | syedTabish/Codes | /basic/counting_sort.cpp | UTF-8 | 685 | 3.046875 | 3 | [] | no_license | #include<iostream>
#define MAX 100
using namespace std;
int main(){
int n;
int *a,*b;
int c[MAX] = {0};
//read data
cin >> n;
a = new int[n];
b = new int[n];
for(int i = 0; i < n;i++){
cin >> a[i];
}
//algorithm
//ensure c is zero
for(int i = 0;i < n; i++){
c[a[i]]++;
}
for(int i = 1;i < MAX;i++){
c[i] += c[i-1];
}
for(int i = n-1;i >= 0;i--){
b[c[a[i]]-1] = a[i];
c[a[i]]--;
}
//output data
for(int i = 0; i < n;i++){
cout << b[i] << " ";
}
cout << endl;
return 0;
}
/*
Running time is theta(k + n)
k is the MAX int value of array
*/
| true |
edb6346ef9f913a09d2d1bc01f4288098809146a | C++ | codenuri/TEMPLATE | /instantiation1.cpp | UTF-8 | 415 | 2.953125 | 3 | [] | no_license | /*
* HOME : ecourse.co.kr
* EMAIL : smkang @ codenuri.co.kr
* COURSENAME : C++ Template Programming
* MODULE : instantiation1.cpp
* Copyright (C) 2017 CODENURI Inc. All rights reserved.
*/
template<typename T> T square(T a)
{
T ret = a * a;
return ret;
}
int main()
{
// explicit instantiation
square<int>(3);
square<double>(3.4);
// implicit instantiation
square(3);
square(3.4);
} | true |
e7f42ab08c8cad515e20c33a66023f21738da700 | C++ | Shymae/androidpp | /Android/text/style/MetricAffectingSpan.h | UTF-8 | 2,534 | 2.765625 | 3 | [] | no_license | //
// MetricAffectingSpan.h
// Androidpp
//
// Created by Saul Howard on 1/22/14.
// Copyright (c) 2014 MoneyDesktop. All rights reserved.
//
#ifndef __Androidpp__MetricAffectingSpan__
#define __Androidpp__MetricAffectingSpan__
#include "AndroidMacros.h"
#include "Android/text/style/UpdateLayout.h"
#include "Android/text/style/CharacterStyle.h"
#include <memory>
using namespace std;
ANDROID_BEGIN
/**
* The classes that affect character-level text formatting in a way that
* changes the width or height of characters extend this class.
*/
class MetricAffectingSpan : public CharacterStyle, public UpdateLayout {
friend class CharacterStyle;
public:
virtual void updateMeasureState(shared_ptr<TextPaint> p) = 0;
/**
* Returns "this" for most MetricAffectingSpans, but for
* MetricAffectingSpans that were generated by {@link #wrap},
* returns the underlying MetricAffectingSpan.
*/
virtual CharacterStyle *getUnderlying() {
return this;
}
virtual string getType() {
return "MetricAffectingSpan";
};
private:
/**
* A Passthrough MetricAffectingSpan is one that
* passes {@link #updateDrawState} and {@link #updateMeasureState}
* calls through to the specified MetricAffectingSpan
* while still being a distinct object,
* and is therefore able to be attached to the same Spannable
* to which the specified MetricAffectingSpan is already attached.
*/
class Passthrough;
};
class MetricAffectingSpan::Passthrough : public MetricAffectingSpan {
private:
shared_ptr<MetricAffectingSpan> mStyle;
public:
/**
* Creates a new Passthrough of the specfied MetricAffectingSpan.
*/
Passthrough(shared_ptr<MetricAffectingSpan> cs) {
mStyle = cs;
}
/**
* Passes updateDrawState through to the underlying MetricAffectingSpan.
*/
void updateDrawState(shared_ptr<TextPaint> tp) {
mStyle->updateDrawState(tp);
}
/**
* Passes updateMeasureState through to the underlying MetricAffectingSpan.
*/
void updateMeasureState(shared_ptr<TextPaint> tp) {
mStyle->updateMeasureState(tp);
}
/**
* Returns the MetricAffectingSpan underlying this one, or the one
* underlying it if it too is a Passthrough.
*/
CharacterStyle *getUnderlying() {
return mStyle->getUnderlying();
}
};
ANDROID_END
#endif /* defined(__Androidpp__MetricAffectingSpan__) */
| true |
14e59d02fc812bfb6cea951442d44c12b5680f97 | C++ | teqno/f-framework | /f-library/src/activations.cpp | UTF-8 | 670 | 3 | 3 | [] | no_license | #include <math.h>
#include <iostream>
#include "activations.h"
Eigen::VectorXd sigmoid(const Eigen::VectorXd &z)
{
return z.array() / (1.0 + z.array().abs());
}
Eigen::VectorXd relu(const Eigen::VectorXd &z)
{
return z.cwiseMax(0);
}
Eigen::VectorXd sigmoid_prime(const Eigen::VectorXd &z)
{
return 1.0 / (z.array().abs() + 1.0).pow(2);
}
Eigen::VectorXd tanh_prime(const Eigen::VectorXd &z)
{
return 1.0 / z.array().cosh().pow(2);
}
Eigen::VectorXd relu_prime(const Eigen::VectorXd &z)
{
Eigen::VectorXd updatedZ(z.size());
for (int i = 0; i < z.size(); i++)
{
updatedZ(i) = z(i) > 0 ? 1.0 : 0.0;
}
return updatedZ;
} | true |
b3aa0d6f6d9983c10df24127728ba7c3963b5bf2 | C++ | jucelinoss/Estruturas_de_dados | /Estruturas_dados/Semana_5_Aula_14_Arvore_binaria/ArvoreBinaria.cpp | UTF-8 | 3,511 | 3.453125 | 3 | [] | no_license | #include <cstddef>
#include <iostream>
#include "ArvoreBinaria.h"
#include "Aluno.h"
ArvoreBinaria::ArvoreBinaria() {
raiz = NULL;
}
ArvoreBinaria::~ArvoreBinaria() {
deletarArvore(raiz);
}
void ArvoreBinaria::deletarArvore(No* noAtual) {
if (noAtual != NULL) {
deletarArvore(noAtual->filhoEsquerda);
deletarArvore(noAtual->filhoDireita);
delete noAtual;
}
}
No* ArvoreBinaria::getRaiz() {
return raiz;
}
bool ArvoreBinaria::estaVazio() {
return raiz == NULL;
}
bool ArvoreBinaria::estaCheio() {
try
{
No* temp = new No;
delete temp;
return false;
}
catch (bad_alloc exception )
{
return true;
}
}
void ArvoreBinaria::inserir(Aluno aluno) {
if (estaCheio()) {
cout << "A arvore esta cheia\n nao foi possivel inserir este elemento";
} else{
No* noNovo = new No;
noNovo->aluno = aluno;
noNovo->filhoEsquerda = NULL;
noNovo->filhoDireita = NULL;
if (estaVazio())
{
raiz = noNovo;
}
else {
No* temp = raiz;
while (temp != NULL) {
if (aluno.getRa() < temp->aluno.getRa()) {
if (temp->filhoEsquerda == NULL) {
temp->filhoEsquerda = noNovo;
break;
}
else {
temp = temp->filhoEsquerda;
}
}
else {
if (temp->filhoDireita == NULL) {
temp->filhoDireita = noNovo;
break;
}
else {
temp = temp->filhoDireita;
}
}
}
}
}
}
void ArvoreBinaria::remover(Aluno aluno) {
buscaRemocao(aluno, raiz);
}
void ArvoreBinaria::buscaRemocao(Aluno aluno, No*& noAtual) {
if (aluno.getRa() < noAtual->aluno.getRa()) {
buscaRemocao(aluno, noAtual->filhoEsquerda);
}
else if (aluno.getRa() > noAtual->aluno.getRa()) {
buscaRemocao(aluno, noAtual->filhoDireita);
}
else {
deletarNo(noAtual);
}
}
void ArvoreBinaria::deletarNo(No*& noAtual) {
No* temp = noAtual;
if (noAtual->filhoEsquerda == NULL) {
noAtual = noAtual->filhoDireita;
delete temp;
}
else if (noAtual->filhoDireita == NULL) {
noAtual = noAtual->filhoEsquerda;
delete temp;
}
else {
Aluno alunoSucessor;
getSucessor(alunoSucessor, noAtual);
noAtual->aluno = alunoSucessor;
buscaRemocao(alunoSucessor, noAtual->filhoDireita);
}
}
void ArvoreBinaria::getSucessor(Aluno& alunoSucessor, No* temp) {
temp = temp->filhoDireita;
while (temp->filhoEsquerda != NULL) {
temp = temp->filhoEsquerda;
}
alunoSucessor = temp->aluno;
}
void ArvoreBinaria::buscar(Aluno& aluno, bool& encontrado) {
encontrado = false;
No* noAtual = raiz;
while (noAtual != NULL) {
if (aluno.getRa() < noAtual->aluno.getRa()) {
noAtual = noAtual->filhoEsquerda;
}
else if (aluno.getRa() > noAtual->aluno.getRa()) {
noAtual = noAtual->filhoDireita;
}
else {
encontrado = true;
aluno = noAtual->aluno;
break;
}
}
}
void ArvoreBinaria::imprimirPreOrdem(No* noAtual) {
if (noAtual != NULL) {
cout << noAtual->aluno.getRa() << ": ";
cout << noAtual->aluno.getNome() << endl;
imprimirPreOrdem(noAtual->filhoEsquerda);
imprimirPreOrdem(noAtual->filhoDireita);
}
}
void ArvoreBinaria::imprimirEmOrdem(No* noAtual) {
if (noAtual != NULL) {
imprimirEmOrdem(noAtual->filhoEsquerda);
cout << noAtual->aluno.getRa() << ": ";
cout << noAtual->aluno.getNome() << endl;
imprimirEmOrdem(noAtual->filhoDireita);
}
}
void ArvoreBinaria::imprimirPosOrdem(No* noAtual) {
if (noAtual != NULL) {
imprimirPosOrdem(noAtual->filhoEsquerda);
imprimirPosOrdem(noAtual->filhoDireita);
cout << noAtual->aluno.getRa() << ": ";
cout << noAtual->aluno.getNome() << endl;
}
}
| true |
23f64128256e96a691db70d45acba2d8e18df1be | C++ | LuckyDmitry/devtools-course-practice | /modules/length_converter/src/length_converter.cpp | UTF-8 | 1,398 | 3.140625 | 3 | [
"CC-BY-4.0"
] | permissive | // Copyright 2020 Brazhnikov Eugene
#include "include/length_converter.h"
double LengthConverter::m_kmeter(const double& curr, bool side) {
if (curr >= 0 && side == false) // meter to kilometer
return curr / 1000;
if (curr >= 0 && side == true) // kilometer to meter
return curr * 1000;
return -1;
}
double LengthConverter::m_smeter(const double& curr, bool side) {
if (curr >= 0 && side == false)
return curr * 100;
if (curr >= 0 && side == true)
return curr / 100;
return -1;
}
double LengthConverter::m_mile(const double& curr, bool side) {
if (curr >= 0 && side == false)
return curr * 0.000621371;
if (curr >= 0 && side == true)
return curr / 0.000621371;
return -1;
}
double LengthConverter::m_yard(const double& curr, bool side) {
if (curr >= 0 && side == false)
return curr * 1.09361;
if (curr >= 0 && side == true)
return curr / 1.09361;
return -1;
}
double LengthConverter::m_ft(const double& curr, bool side) {
if (curr >= 0 && side == false)
return curr * 3.28084;
if (curr >= 0 && side == true)
return curr / 3.28084;
return -1;
}
double LengthConverter::m_inch(const double& curr, bool side) {
if (curr >= 0 && side == false)
return curr * 39.3701;
if (curr >= 0 && side == true)
return curr / 39.3701;
return -1;
}
| true |
a322a2e46f7fa9d280019ec4348de86125211838 | C++ | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/13/01/15.cpp | UTF-8 | 1,762 | 3.21875 | 3 | [] | no_license | #include <cstdio>
using namespace std;
void doCase()
{
char board[4][4];
for (int i=0; i<4; i++)
{
for (int j=0; j<4; j++)
{
scanf(" %c", &board[i][j]);
}
}
// rows
for (int i=0; i<4; i++)
{
int nO = 0;
int nX = 0;
for (int j=0; j<4; j++)
{
if (board[i][j] == 'X')
nX++;
if (board[i][j] == 'O')
nO++;
if (board[i][j] == 'T')
{
nX++;
nO++;
}
}
if (nO == 4)
{
printf("O won\n");
return;
}
if (nX == 4)
{
printf("X won\n");
return;
}
}
// columns
for (int i=0; i<4; i++)
{
int nO = 0;
int nX = 0;
for (int j=0; j<4; j++)
{
if (board[j][i] == 'X')
nX++;
if (board[j][i] == 'O')
nO++;
if (board[j][i] == 'T')
{
nX++;
nO++;
}
}
if (nO == 4)
{
printf("O won\n");
return;
}
if (nX == 4)
{
printf("X won\n");
return;
}
}
int nO = 0, nX = 0;
// diagonals
for (int i=0; i<4; i++)
{
if (board[i][i] == 'O')
nO++;
if (board[i][i] == 'X')
nX++;
if (board[i][i] == 'T')
{
nO++;
nX++;
}
}
if (nO == 4)
{
printf("O won\n");
return;
}
if (nX == 4)
{
printf("X won\n");
return;
}
nO = nX = 0;
for (int i=0; i<4; i++)
{
if (board[i][3-i] == 'O')
nO++;
if (board[i][3-i] == 'X')
nX++;
if (board[i][3-i] == 'T')
{
nO++;
nX++;
}
}
if (nO == 4)
{
printf("O won\n");
return;
}
if (nX == 4)
{
printf("X won\n");
return;
}
// check draw
for (int i=0; i<4; i++)
{
for (int j=0; j<4; j++)
{
if (board[i][j] == '.')
{
printf("Game has not completed\n");
return;
}
}
}
printf("Draw\n");
}
int main()
{
int T;
scanf("%d", &T);
for (int i=1; i<=T; i++)
{
printf("Case #%d: ", i);
doCase();
}
return 0;
}
| true |
925433f75adfde022ce649d8463293849004ed1f | C++ | packetinspector/random | /temp-light.ino | UTF-8 | 3,432 | 2.71875 | 3 | [] | no_license | // Quick use of DHT and FastLED
// In production
//Includes
#include <dht.h>
#include "FastLED.h"
FASTLED_USING_NAMESPACE
//Make a DHT object
dht DHT;
//Setup Stuff
#define DHT22_PIN 5
#define NUM_LEDS 1
#define DATA_PIN 6
#define LED_TYPE WS2812
#define COLOR_ORDER RGB
CRGB leds[NUM_LEDS];
struct
{
uint32_t total;
uint32_t ok;
uint32_t crc_error;
uint32_t time_out;
uint32_t connect;
uint32_t ack_l;
uint32_t ack_h;
uint32_t unknown;
} stat = { 0,0,0,0,0,0,0,0};
float ideal_temp = 72;
float high_temp = ideal_temp + 1.5;
float low_temp = ideal_temp - 1.5;
void setup()
{
Serial.begin(115200);
Serial.println("dht22_test.ino");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT_LIB_VERSION);
Serial.println();
Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)\tTime (us)");
// initialize digital pin LED_BUILTIN as an output.
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS);
long unsigned int colors[] = {CRGB::Red, CRGB::Green, CRGB::Blue};
for (int i=0; i <= 2; i++) {
leds[0] = colors[i];
//Fancy fade color for boot
for (int j=0; j <= 255; j += 5) {
FastLED.setBrightness(j);
FastLED.show();
delay(10);
}
}
//Turn it off
FastLED.clear();
}
void loop()
{
// READ DATA
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("DHT22 \t");
int chk = DHT.read22(DHT22_PIN);
stat.total++;
switch (chk)
{
case DHTLIB_OK:
stat.ok++;
Serial.print("OK,\t");
break;
case DHTLIB_ERROR_CHECKSUM:
stat.crc_error++;
Serial.print("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
stat.time_out++;
Serial.print("Time out error,\t");
break;
default:
stat.unknown++;
Serial.print("Unknown error,\t");
break;
}
Serial.println();
float temp = DHT.temperature*1.8 + 32;
if (stat.total % 20 == 0)
{
Serial.println("\nTOT\tOK\tCRC\tTO\tUNK");
Serial.print(stat.total);
Serial.print("\t");
Serial.print(stat.ok);
Serial.print("\t");
Serial.print(stat.crc_error);
Serial.print("\t");
Serial.print(stat.time_out);
Serial.print("\t");
Serial.print(stat.connect);
Serial.print("\t");
Serial.print(stat.ack_l);
Serial.print("\t");
Serial.print(stat.ack_h);
Serial.print("\t");
Serial.print(stat.unknown);
Serial.println("\n");
}
// Do Led Stuff
digitalWrite(LED_BUILTIN, LOW);
//Calculate Brightness
// 50 - 255
float diff = abs(ideal_temp - temp);
float bright = 0 + (diff * 50);
if (bright >= 250) {
bright = 255;
} else if (bright < 50) {
bright = 50;
}
if (temp > high_temp) {
leds[0] = CRGB::Red;
} else if (temp < low_temp) {
leds[0] = CRGB::Blue;
} else {
leds[0] = CRGB::Green;
}
FastLED.setBrightness(bright);
FastLED.show();
// Print Status
Serial.print(" Humidity: ");
Serial.print(DHT.humidity, 1);
Serial.print("\% Temp: ");
Serial.print(temp, 1);
Serial.print("F Diff: ");
Serial.print(diff, 1);
Serial.print(" Brightness: ");
Serial.print(bright);
Serial.println();
delay(4000);
}
//
// END OF FILE
//
| true |
74f0d64b56952fe14c76bda10a9b244438a1df15 | C++ | johng/Rasteriser | /Source/Camera.h | UTF-8 | 518 | 2.71875 | 3 | [] | no_license | #ifndef COMPUTER_GRAPHICS_CAMERA_H
#define COMPUTER_GRAPHICS_CAMERA_H
#include <iostream>
#include <glm/glm.hpp>
using namespace std;
using glm::vec3;
using glm::mat3;
using glm::mat4;
using glm::vec4;
class Camera
{
private:
vec3 pos;
vec3 dir;
public:
Camera (vec3 pos,vec3 dir);
void setPos(vec3 pos);
void setDir(vec3 pos);
void moveDir(vec3 pos);
void movePos(vec3 pos);
vec3 position();
vec3 direction();
friend ostream& operator<<(ostream& os, const Camera& cam);
};
#endif
| true |
54fc5b13c64154d7a9592d9e1fe3b2a88317129e | C++ | JS00000/acmCode | /hdu/1004.cpp | UTF-8 | 614 | 2.65625 | 3 | [] | no_license | #include "iostream"
#include "string"
using namespace std;
int main(int argc, char const *argv[])
{
int n;
cin >> n;
while(n!=0)
{
int j=0;
int k=0;
string str;
string in[1000];
int num[1000]={0};
while(k<n)
{
cin >> str;
bool p = false;
for (int i = 0; i < j; ++i)
{
if (str==in[i])
{
p = true;
num[i]++;
}
}
if (!p)
{
in[j] = str;
num[j]++;
j++;
}
k++;
}
int max = 0;
int maxx = 0;
for (int i = 0; i < n; ++i)
{
if (num[i]>max)
{
max = num[i];
maxx = i;
}
}
cout << in[maxx] << endl;
cin >> n;
}
}
| true |
3d1dadd9d0af03fa79a16d27eff17bd8387bdd48 | C++ | cooperyuan/attila | /src/trace/D3DStadistics/StatsUtils.h | UTF-8 | 26,959 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef STATS_UTILS_H
#define STATS_UTILS_H
#include <vector>
#include <set>
#include <algorithm>
#include <numeric>
#include <functional>
#ifndef WIN32
#include <function.h>
#endif
namespace workloadStats
{
/****************************************************************************************************
* workloadStats NameSpace *
****************************************************************************************************
* *
* This namespace contains the classes and structures used to get Workload statistics *
* for the traced OpenGL application. *
* *
* The statistical mode of GLInterceptor is enabled specifying any name different to null *
* in the batchStats, frameStats and traceStats fields of GLIConfig.ini file. *
* *
* After execution, in each of these files, the related and resumed statistics per batch, per *
* per frame and for the entire trace are available. *
* *
****************************************************************************************************
*/
/****************************************************************************************************
* StatsUtils.h classes *
****************************************************************************************************
* *
* StatsUtils.h defines a collection of classes and collectors that can be used to construct *
* several different types of accounting statistics taking or summarizing information for each *
* batch, for each frame and the entire trace. *
* *
* At the end of this file, a definition of the UserStat interface is given to derive all the *
* user statistics. *
****************************************************************************************************
/**
* Aggregator class generalizes the idea of an aggregation operation over a vector of generic data.
*
* This interface is implemented using templates to allow working with different basic types of data,
* either for the vector data type and the result type.
*/
template<class T1, class T2>
class Aggregator
{
public:
virtual T2 getAggregatedValue(const std::vector<T1>& values) const = 0;
/* Virtual destructor to call the derived class destructors. */
virtual ~Aggregator() {};
};
/**
* The TraceDataCollector class is the main base class of data collectors to construct statistics.
*
* It generalizes the idea of an object that carries out accounting using
* a frame Aggregator to resume batch statistic values into the frame statistic
* value (when the endFrame() method is invoked) and a trace Aggregator to resume
* this frame statistic values to a final trace statistic value (when the endTrace())
* method is invoked.
*
* The statistic batch data type (BT), the frame resumed data type (FT) and the
* trace data type (TT) can be different, and they are parametrizable because of the
* template based implementation of this class. The corresponding aggregators are forced
* to use the same data types. An example of this can be a TraceDataCollector subclass that uses
* an integer type to hold batch values, a float type for frame and trace values that
* allows to use an average aggregator to hold frame and trace info.
*
* class ConcreteTraceDataCollector: public TraceDataCollector<unsigned int,float,float> // <BT, FT, TT>
* {
* ....
*
* /**
* * The inlined constructor
* *
* ConcreteTraceDataCollector(const std::string& name)
* : TraceDataCollector<unsigned int,float,float>(name)
* {
* setAggregators(new ConcreteAggregator1<unsigned int, float>, // Frame aggregator
* new ConcreteAggregator2<float, float>); // Trace aggregator
* }
* ....
* };
*
*
* The batch values are stored in a vector holding vectors of batch values for each frame.
* The frame resumed values are stored in a separated vector and, in the same way, the final trace
* statistic value is stored separately in another attribute.
*
* The methods endBatch(), endFrame(), endTrace() are fully implemented and they
* perform and store the current batch or frame value computation. They also perform the
* corresponding switching to the next batch or frame.
*
* The endBatch() and setBatchValue() are declared virtual to allow GLIStat subclasses
* to redefine the behaviour and structures used for batch process and switching.
*
* The endFrame() is also declared virtual to allow statistics that only do a special
* management at the frame level, for example the Average Pixel Depth Complexity which uses
* the frame depth complexity map of the frame to extract this parameter.
*
*/
template<class BT, class FT, class TT>
class TraceDataCollector
{
protected:
const Aggregator<BT,FT>* frameAggregator;
const Aggregator<FT,TT>* traceAggregator;
std::vector<std::vector<BT> > batchValues; ///< To store individually batch values over the entire trace. At the end of the frame, the Frame
/// aggregator will resume the last filled batch vector in a new frame value.
mutable std::vector<FT> frameValues; ///< To store the frame statistic value over the entire trace. At the end of the trace, the Trace
/// aggregator will resume the frame vector in a final trace value.
mutable TT traceValue; ///< The final trace value.
BT neutralValue; ///< Needed to make template-based data collectors.
/**
* Must be called in each subclass. To be under the "protected:" section prevents from direct instantiation
* of this class.
*/
TraceDataCollector(bool deprecatedAggregation = true);
/**
* Must be called in each subclass constructor to initialize the aggregators
*/
void setAggregators( const Aggregator<BT,FT>* _frameAggregator, const Aggregator<FT,TT>* _traceAggregator );
bool deprecatedAggregation; ///< Tells if frame/trace values will be computed when getting values or at frame change/trace end events.
mutable bool frameAggregationComputed; ///< Tells if deprecated frame aggregation has been alreadly computed.
mutable bool traceAggregationComputed; ///< Tells if deprecated trace aggregation has been alreadly computed.
public:
/**
* Destructor. It deletes Aggregator classes allocated dynamically.
*/
virtual ~TraceDataCollector();
/**
* This method sets the batch value and marks the end of the batch.
*
*/
void endBatch(BT value);
/**
* This method marks the end of a frame.
*
* @note It calls the frame aggregator to resume the frame value based on the batch values stored for
* the frame up to now.
*
*/
void endFrame();
/**
* This method marks the end of the trace.
*
* @note It calls the trace aggregator to compute the final trace value over the entire frame vector
* and stores it in the trace value.
*
*/
void endTrace();
/**
* Methods used by GLIStatsManager to query statistics results
*
*/
BT getBatchValue(unsigned int frameIndex, unsigned int batchIndex) const;
FT getFrameValue(unsigned int frameIndex) const;
std::vector< BT > getFrameBatchesValues(unsigned int frameIndex) const;
TT getTraceValue() const;
unsigned int getFrameCount() const;
};
/****************************************************************************************
* Implemented Aggregator subclasses *
****************************************************************************************
*/
/**
* Count Aggregator
*
* Returns the number of elements of the aggregated data
*/
template<class T>
class CountAggregator: public Aggregator<T,unsigned int>
{
public:
virtual unsigned int getAggregatedValue(const std::vector<T>& values) const;
};
/**
* Different Count Aggregator
*
* Returns the number of different elements of the aggregated data.
*/
template<class T>
class DifferentCountAggregator: public Aggregator<T, unsigned int>
{
public:
virtual unsigned int getAggregatedValue(const std::vector<T>& values) const;
};
/**
* Sum Aggregator
*
* Returns the addition of all the elements of the aggregated data.
*/
template<class T>
class SumAggregator: public Aggregator<T, T>
{
public:
virtual T getAggregatedValue(const std::vector<T>& values) const;
};
/**
* Max Aggregator
*
* Returns the maximum value of the aggregated data.
*/
template<class T>
class MaxAggregator: public Aggregator<T,T>
{
public:
virtual T getAggregatedValue(const std::vector<T>& values) const;
};
/**
* Min Aggregator
*
* Returns the minimum value of the aggregated data.
*/
template<class T>
class MinAggregator: public Aggregator<T,T>
{
public:
virtual T getAggregatedValue(const std::vector<T>& values) const;
};
/**
* Average Aggregator
*
* Returns the average float value of the aggregated data values.
*/
template<class T>
class AverageAggregator: public Aggregator<T,float>
{
public:
virtual float getAggregatedValue(const std::vector<T>& values) const;
};
/**
* Weighted Average Aggregator
*
* Returns the weighted average float value of the aggregated data values.
*/
template<class T>
class WeightedAverageAggregator: public Aggregator<T,float>
{
public:
virtual float getAggregatedValue(const std::vector<std::pair<T,unsigned int> >& values) const;
};
/**
* Predicated Average Aggregator
*
* Returns the average float value of all the elements of the aggregated data different from
* the concrete value.
*/
template<class T>
class PredicatedAverageAggregator: public Aggregator<T,float>
{
private:
T targetValue;
public:
PredicatedAverageAggregator(T targetValue): targetValue(targetValue) {};
virtual float getAggregatedValue(const std::vector<T>& values) const;
};
/**
* List Different Count Aggregator
*
* Returns the count of all the different elements in the aggregated data sets.
*/
template<class T>
class ListDifferentCountAggregator: public Aggregator<std::set<T>, unsigned int>
{
public:
virtual unsigned int getAggregatedValue(const std::vector<std::set<T> >& values) const;
};
/**
* List Different Aggregator
*
* Returns a new set with unique elements of the vector sets.
*/
template<class T>
class ListDifferentAggregator: public Aggregator<std::set<T>, std::set<T> >
{
public:
virtual std::set<T> getAggregatedValue(const std::vector<std::set<T> >& values) const;
};
/**
* Frequency Aggregator
*
* Returns the percent of time that a concrete value appears in the data set.
*/
template<class T>
class FrequencyAggregator: public Aggregator<T,float>
{
private:
T concreteValue;
public:
FrequencyAggregator(T concreteValue): concreteValue(concreteValue) {};
virtual float getAggregatedValue(const std::vector<T>& values) const;
};
/********************************************************************************************
* TraceDataCollector concrete subclasses used by the user statistics *
********************************************************************************************
*/
template<class T>
class SumPerFrameSumTotal: public TraceDataCollector<T,T,T>
{
public:
SumPerFrameSumTotal()
: TraceDataCollector<T,T,T>()
{
setAggregators(new SumAggregator<T>, new SumAggregator<T>);
}
};
template<class T>
class SumPerFrameAverageTotal: public TraceDataCollector<T,T,float>
{
public:
SumPerFrameAverageTotal()
: TraceDataCollector<T,T,float>()
{
setAggregators(new SumAggregator<T>, new AverageAggregator<T>);
}
};
template<class T>
class AveragePerFrameAverageTotal: public TraceDataCollector<T,float,float>
{
public:
AveragePerFrameAverageTotal()
: TraceDataCollector<T,float,float>()
{
setAggregators(new AverageAggregator<T>, new AverageAggregator<float>);
}
};
template<class T>
class PredicatedAveragePerFrameAverageTotal: public TraceDataCollector<T,float,float>
{
public:
PredicatedAveragePerFrameAverageTotal(T targetValue)
: TraceDataCollector<T,float,float>()
{
setAggregators(new PredicatedAverageAggregator<T>(targetValue), new AverageAggregator<float>);
}
};
template<class T>
class MaxPerFrameMaxTotal: public TraceDataCollector<T,T,T>
{
public:
MaxPerFrameMaxTotal()
: TraceDataCollector<T,T,T>()
{
setAggregators(new MaxAggregator<T>, new MaxAggregator<T>);
}
};
template<class T>
class DifferentCountPerFrameAverageTotal: public TraceDataCollector<T,unsigned int,float>
{
public:
DifferentCountPerFrameAverageTotal()
: TraceDataCollector<T,unsigned int, float>()
{
setAggregators(new DifferentCountAggregator<T>, new AverageAggregator<unsigned int>);
}
};
template<class T>
class DifferentCountPerFrameSumTotal: public TraceDataCollector<T,unsigned int,unsigned int>
{
public:
DifferentCountPerFrameSumTotal()
: TraceDataCollector<T,unsigned int, unsigned int>()
{
setAggregators(new DifferentCountAggregator<T>, new SumAggregator<unsigned int>);
}
};
template<class T>
class ListDifferentCountPerFrameAverageTotal: public TraceDataCollector<std::set<T>,unsigned int,float>
{
public:
ListDifferentCountPerFrameAverageTotal()
: TraceDataCollector<std::set<T>,unsigned int, float>()
{
setAggregators(new ListDifferentCountAggregator<T>, new AverageAggregator<unsigned int>);
}
};
template<class T>
class ListDifferentPerFrameListDifferentTotal: public TraceDataCollector<std::set<T>, std::set<T>, std::set<T> >
{
public:
ListDifferentPerFrameListDifferentTotal()
: TraceDataCollector<std::set<T>, std::set<T>, std::set<T> >()
{
setAggregators(new ListDifferentAggregator<T>, new ListDifferentAggregator<T>);
}
};
template<class T>
class FrequencyPerFrameAverageTotal: public TraceDataCollector<T,float,float>
{
public:
FrequencyPerFrameAverageTotal(T concreteValue)
: TraceDataCollector<T,float,float>()
{
setAggregators(new FrequencyAggregator<T>(concreteValue), new AverageAggregator<float>);
}
};
/****************************************************************************************
* TraceDataCollector implementation: Because of the template based implementation, *
* this part is required to be in the header file. *
****************************************************************************************
*/
template<class BT, class FT, class TT>
TraceDataCollector<BT,FT,TT>::TraceDataCollector(bool deprecatedAggregation)
: batchValues(0), frameValues(0), frameAggregator(0), traceAggregator(0),
deprecatedAggregation(deprecatedAggregation), frameAggregationComputed(false),
traceAggregationComputed(false)
{
batchValues.push_back(std::vector<BT>(0));
};
template<class BT, class FT, class TT>
TraceDataCollector<BT,FT,TT>::~TraceDataCollector()
{
if (frameAggregator) delete frameAggregator;
if (traceAggregator) delete traceAggregator;
};
template<class BT, class FT, class TT>
void TraceDataCollector<BT,FT,TT>::setAggregators( const Aggregator<BT,FT>* _frameAggregator,
const Aggregator<FT,TT>* _traceAggregator )
{
frameAggregator = _frameAggregator;
traceAggregator = _traceAggregator;
};
template<class BT, class FT, class TT>
void TraceDataCollector<BT,FT,TT>::endBatch(BT value)
{
std::vector<BT>& batchValuesVector = batchValues.back();
batchValuesVector.push_back(value);
};
template<class BT, class FT, class TT>
void TraceDataCollector<BT,FT,TT>::endFrame()
{
if (!deprecatedAggregation)
{
const std::vector<BT>& currentValuesVector = batchValues.back();
if (!frameAggregator)
panic("workloadStats::TraceDataCollector","endFrame","Frame Aggregator not initialized");
// Call frameAggregator to compute frame value.
FT frameResumeValue = frameAggregator->getAggregatedValue(currentValuesVector);
frameValues.push_back(frameResumeValue);
};
// Reserve a new batch vector for the following frame.
batchValues.push_back(std::vector<BT>(0));
};
template<class BT, class FT, class TT>
void TraceDataCollector<BT,FT,TT>::endTrace()
{
if (!deprecatedAggregation)
{
if (!traceAggregator)
panic("workloadStats::TraceDataCollector","endTrace","Trace Aggregator not initialized");
traceValue = traceAggregator->getAggregatedValue(frameValues);
}
};
template<class BT, class FT, class TT>
BT TraceDataCollector<BT,FT,TT>::getBatchValue(unsigned int frameIndex, unsigned int batchIndex) const
{
if (frameIndex >= batchValues.size()-1)
panic("workloadStats::TraceDataCollector","getBatchValue","frame index out of bounds");
if (batchIndex >= batchValues[frameIndex].size())
panic("workloadStats::TraceDataCollector","getBatchValue","batch index out of bounds");
return batchValues[frameIndex][batchIndex];
};
template<class BT, class FT, class TT>
FT TraceDataCollector<BT,FT,TT>::getFrameValue(unsigned int frameIndex) const
{
if (deprecatedAggregation && !frameAggregationComputed)
{
typename std::vector<std::vector<BT> >::const_iterator iter = batchValues.begin();
while ( iter != batchValues.end() )
{
if ( (iter + 1) != batchValues.end() ) // Skip last vector of batches (added automatically at endFrame)
{
if (!frameAggregator)
panic("workloadStats::TraceDataCollector","getFrameValue","Frame Aggregator not initialized");
// Call frameAggregator to compute frame value.
FT frameResumeValue = frameAggregator->getAggregatedValue((*iter));
frameValues.push_back(frameResumeValue);
}
iter++;
}
frameAggregationComputed = true;
}
if (frameIndex >= frameValues.size())
panic("workloadStats::TraceDataCollector","getFrameValue","frame index out of bounds");
return frameValues[frameIndex];
};
template<class BT, class FT, class TT>
TT TraceDataCollector<BT,FT,TT>::getTraceValue() const
{
if (deprecatedAggregation && !traceAggregationComputed)
{
if (!traceAggregator)
panic("workloadStats::TraceDataCollector","getTraceValue","Trace Aggregator not initialized");
traceValue = traceAggregator->getAggregatedValue(frameValues);
traceAggregationComputed = true;
}
return traceValue;
};
template<class BT, class FT, class TT>
std::vector< BT > TraceDataCollector<BT,FT,TT>::getFrameBatchesValues(unsigned int frameIndex) const
{
if (frameIndex >= batchValues.size())
panic("workloadStats::TraceDataCollector","getFrameBatchesValues","frame index out of bounds");
return batchValues.at(frameIndex);
}
template<class BT, class FT, class TT>
unsigned int TraceDataCollector<BT,FT,TT>::getFrameCount() const
{
if (deprecatedAggregation && !frameAggregationComputed)
{
typename std::vector<std::vector<BT> >::const_iterator iter = batchValues.begin();
while ( iter != batchValues.end() )
{
if ( (iter + 1) != batchValues.end() ) // Skip last vector of batches (added automatically at endFrame)
{
if (!frameAggregator)
panic("workloadStats::TraceDataCollector","getFrameValue","Frame Aggregator not initialized");
// Call frameAggregator to compute frame value.
FT frameResumeValue = frameAggregator->getAggregatedValue((*iter));
frameValues.push_back(frameResumeValue);
}
iter++;
}
frameAggregationComputed = true;
}
return frameValues.size();
};
/**********************************************************************************************
* Aggregator subclasses methods implementation: Wherever is possible, the C++ STL algorithm *
functions are used. *
**********************************************************************************************
*/
template<class T>
unsigned int CountAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
return values.size();
};
template<class T>
unsigned int DifferentCountAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
typename std::vector<T>::const_iterator iter = values.begin();
std::set<T> differentList;
while ( iter != values.end() )
{
differentList.insert((*iter));
iter++;
}
return differentList.size();
};
template<class T>
T SumAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
return std::accumulate(values.begin(), values.end(), T(0));
};
template<class T>
T MaxAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
typename std::vector<T>::const_iterator maxValue = std::max_element(values.begin(),values.end());
return (*maxValue);
};
template<class T>
T MinAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
typename std::vector<T>::const_iterator minValue = std::min_element(values.begin(),values.end());
return (*minValue);
};
template<class T>
float AverageAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
T accum = std::accumulate(values.begin(), values.end(), T(0));
if (values.size() != 0)
{
return ((float) accum / (float) values.size());
}
else
return (float)accum;
};
template<class T>
float WeightedAverageAggregator<T>::getAggregatedValue(const std::vector<std::pair<T,unsigned int> >& values) const
{
std::vector<T> values2;
std::vector<unsigned int> weights;
typename std::vector<std::pair<T, unsigned int> >::const_iterator iter = values.begin();
while ( iter != values.end() )
{
values2.push_back(iter->first);
weights.push_back(iter->second);
iter++;
};
T accum = inner_product( values2.begin(), values2.end(), weights.begin(), T(0) );
unsigned int weightsAccum = std::accumulate(weights.begin(), weights.end(), T(0));
if (values2.size() != 0)
{
return ((float) accum / (float) weightsAccum);
}
else
return (float)accum;
};
template<class T>
struct pred_adder: public std::binary_function<T, T, T>
{
T value;
pred_adder(T value): value(value) {};
T operator()(T x, T y) { if (y != value) return (x + y); else return x; }
};
template<class T>
float PredicatedAverageAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
workloadStats::pred_adder<T> plus(targetValue);
T accum = std::accumulate(values.begin(), values.end(), T(0), plus);
unsigned int num_items = count_if( values.begin(), values.end(), bind2nd(not_equal_to<T>(), targetValue));
if (num_items != 0)
return (float) accum / (float) num_items;
else
return (float)accum;
};
template<class T>
unsigned int ListDifferentCountAggregator<T>::getAggregatedValue(const std::vector<std::set<T> >& values) const
{
typename std::vector<std::set<T> >::const_iterator iter = values.begin();
std::set<T> differentList;
while ( iter != values.end() )
{
typename std::set<T>::const_iterator iter2 = iter->begin();
while ( iter2 != iter->end() )
{
differentList.insert((*iter2));
iter2++;
}
iter++;
}
return differentList.size();
};
template<class T>
std::set<T> ListDifferentAggregator<T>::getAggregatedValue(const std::vector<std::set<T> >& values) const
{
typename std::vector<std::set<T> >::const_iterator iter = values.begin();
std::set<T> differentList;
while ( iter != values.end() )
{
typename std::set<T>::const_iterator iter2 = iter->begin();
while ( iter2 != iter->end() )
{
differentList.insert((*iter2));
iter2++;
}
iter++;
}
return differentList;
};
template<class T>
float FrequencyAggregator<T>::getAggregatedValue(const std::vector<T>& values) const
{
unsigned int times = std::count(values.begin(), values.end(), concreteValue);
return (float)times / values.size();
};
/*************************************************************
* Utility functions *
*************************************************************/
void computeRangeValueReuseMatrix(const std::vector<std::set<unsigned int> >& diffTextsPerFrame, float* reuseMat);
void computeValueSimilarityMatrix(const std::vector<std::set<unsigned int> >& diffTextsPerFrame, float* reuseMat);
void computeValueReuseForAColumn(const std::vector<std::set<unsigned int> >& diffTextsPerFrame, unsigned int initFrame,
unsigned int finFrame, unsigned int matDim, float* reuseMat,
std::set<unsigned int>& reusedVals, std::set<unsigned int>& diffVals);
void writeSquareMatrixToPPM(const char *fname, const float* matrix, unsigned int matrixDimension);
void computeAverageReusePerWindowSize(std::vector<float>& reuseStripChart, const float* matrix, unsigned int matrixDimension);
} // namespace workloadStats
#endif // STATS_UTILS_H
| true |
24e281f601c30dfb47bf3806790a53ba8a247104 | C++ | Newspaperman57/Particlesystem | /sources/DVector2.cpp | UTF-8 | 229 | 2.515625 | 3 | [] | no_license | #include "DVector2.h"
DVector2::DVector2() {
}
DVector2::DVector2(double X, double Y) {
this->X = X;
this->Y = Y;
}
DVector2::~DVector2() {
}
Vector2 DVector2::ToVector2() {
return Vector2((int)(X+0.5), (int)(Y+0.5));
}
| true |
f167802ff284d2c86babe99e49f6743ada93580a | C++ | ErnestSzczepaniak/rfs | /test/test_flash_bitmap.cpp | UTF-8 | 2,015 | 3.375 | 3 | [] | no_license | #include "test.h"
#include "flash_bitmap.h"
#include "string.h"
TEST_CASE("size assertion")
{
Flash_bitmap<8> bitmap_8;
Flash_bitmap<16> bitmap_16;
Flash_bitmap<24> bitmap_24;
Flash_bitmap<32> bitmap_32;
Flash_bitmap<64> bitmap_64;
REQUIRE(sizeof(bitmap_8) == 1);
REQUIRE(sizeof(bitmap_16) == 2);
REQUIRE(sizeof(bitmap_24) == 3);
REQUIRE(sizeof(bitmap_32) == 4);
REQUIRE(sizeof(bitmap_64) == 8);
}
TEST_CASE("bitmap fill")
{
Flash_bitmap<32> bitmap;
unsigned char compare[sizeof(bitmap)];
memset(compare, 0xff, sizeof(compare));
bitmap.fill(true);
REQUIRE(memcmp(&bitmap, compare, sizeof(compare)) == 0);
memset(compare, 0, sizeof(compare));
bitmap.fill(false);
REQUIRE(memcmp(&bitmap, compare, sizeof(compare)) == 0);
}
TEST_CASE("bitmap is full")
{
Flash_bitmap<32> bitmap;
bitmap.fill(true);
REQUIRE(bitmap.is_full(true) == true);
REQUIRE(bitmap.is_full(false) == false);
bitmap.fill(false);
REQUIRE(bitmap.is_full(false) == true);
REQUIRE(bitmap.is_full(true) == false);
}
TEST_CASE("bitmap set from false")
{
Flash_bitmap<32> bitmap;
bitmap.fill(false);
for (int i = 0; i < 32; i++)
{
bitmap.set(i, true);
REQUIRE(bitmap.get(i) == true);
}
REQUIRE(bitmap.is_full(true) == true);
}
TEST_CASE("bitmap clear from true")
{
Flash_bitmap<32> bitmap;
bitmap.fill(true);
for (int i = 0; i < 32; i++)
{
bitmap.set(i, false);
REQUIRE(bitmap.get(i) == false);
}
REQUIRE(bitmap.is_full(false) == true);
}
TEST_CASE("bitmap count")
{
Flash_bitmap<32> bitmap;
bitmap.fill(false);
REQUIRE(bitmap.count(false) == 32);
REQUIRE(bitmap.count(true) == 0);
for (int i = 0; i < 32; i++)
{
bitmap.set(i, true);
REQUIRE(bitmap.count(true) == i + 1);
REQUIRE(bitmap.count(false) == 32 - i - 1);
}
REQUIRE(bitmap.count(false) == 0);
REQUIRE(bitmap.count(true) == 32);
} | true |
1a4f136f18ef2647adaf461fdcc2ed325de7be5c | C++ | AliShahrose/Circuit_Simulator | /Battery.cc | UTF-8 | 295 | 2.640625 | 3 | [] | no_license | #include "Component.h"
#include "Battery.h"
Battery::Battery(std::string nm, double v, Connection& p, Connection& n) : Component(nm, p, n), voltage{v} {}
void Battery::simulate(double& t)
{
positive.value = voltage;
negative.value = 0.0;
}
double Battery::current()
{
return 0;
} | true |
0c37a68261ed26c6c255a05235cfd9da4baea240 | C++ | vityok/code-snippets | /fuzzbizz/cxx/fuzzbizz.cpp | UTF-8 | 2,190 | 3.078125 | 3 | [] | no_license | // -*- c-default-style: "linux"; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
#include <iostream>
#include <sstream>
const int ITER = 100;
const int MAX_NUM = 10000;
void fuzzbizz_inc(std::ostream& os, const int lim)
{
os << "inc" << std::endl;
os << "1" << std::endl;
if (lim < 2) { return; }
os << "2" << std::endl;
if (lim < 3) { return; }
os << "fuzz" << std::endl;
if (lim < 4) { return; }
os << "4" << std::endl;
if (lim < 5) { return; }
os << "bizz" << std::endl;
if (lim < 6) { return; }
os << "fuzz" << std::endl;
int next3 = 9;
int next5 = 10;
for (int num = 7; num <= lim; ++num)
{
bool div3 = (num == next3);
bool div5 = (num == next5);
if (div3 && div5) {
os << "fuzzbizz" << std::endl;
next3 = num+3;
next5 = num+5;
} else if (div3) {
os << "fuzz" << std::endl;
next3 = num+3;
} else if (div5) {
os << "bizz" << std::endl;
next5 = num+5;
} else {
os << num << std::endl;
}
}
}
void fuzzbizz(std::ostream& os, const int lim)
{
os << "div" << std::endl;
for (int num = 1; num <= lim; ++ num)
{
bool div3 = ((num % 3) == 0);
bool div5 = ((num % 5) == 0);
if (div3 && div5) {
os << "fuzzbizz" << std::endl;
} else if (div3) {
os << "fuzz" << std::endl;
} else if (div5) {
os << "bizz" << std::endl;
} else {
os << num << std::endl;
}
}
}
int main(int argc, char** argv)
{
if (argc > 1)
{
std::cout << "running inc version" << std::endl;
for (int i = 0; i < ITER; ++i)
{
std::ostringstream os;
fuzzbizz_inc(os, MAX_NUM);
}
}
else
{
std::cout << "running div version" << std::endl;
for (int i = 0; i < ITER; ++i)
{
std::ostringstream os;
fuzzbizz(os, MAX_NUM);
}
}
// std::cout << os.str() << std::endl;
return 0;
}
// g++ -Wall -Wextra -pedantic -o fuzzbizz fuzzbizz.cpp
| true |
2d33a5065c3dcd488f791bc3625f27b76dba474b | C++ | weiyy/ss | /json/ListNode.h | GB18030 | 3,095 | 3.734375 | 4 | [] | no_license | #pragma once
// ݽṹ
typedef struct tagNode
{
tagNode()
{
prev=0;
next=0;
value=0;
}
tagNode* prev;
tagNode* next;
void* value;
}Node, *PNode;
class ListNode
{
public:
ListNode()
{
head=0;
tail=0;
}
~ListNode(){}
// ȡͷڵ
PNode GetHead()
{
return head;
}
// ȡβڵ
PNode GetTail()
{
return tail;
}
// ȡڵһڵ
PNode next(PNode lpNode)
{
return lpNode->next;
}
// ȡڵһڵ
PNode prev(PNode lpNode)
{
return lpNode->prev;
}
// ͷһڵ
void PushFront(PNode lpNode)
{
lpNode->prev=0;
lpNode->next=head;
if(head)
{
head->prev=lpNode;
}
else
{
tail=lpNode;
}
head=lpNode;
}
// βһڵ
void PushBack(PNode lpNode)
{
lpNode->next=0;
lpNode->prev=tail;
if(tail)
{
tail->next=lpNode;
}
else
{
head=lpNode;
}
tail=lpNode;
}
// ָڵһڵ
void insert(PNode lpAfter,PNode lpNode)
{
if(lpAfter)
{
if(lpAfter->next)
{
lpAfter->next->prev =lpNode;
}
else
{
tail=lpNode;
}
lpNode->prev=lpAfter;
lpNode->next=lpAfter->next;
lpAfter->next =lpNode;
}
else
{
PushFront(lpNode);
}
}
// ͷһڵ
PNode PopFront()
{
if(head)
{
PNode lpNode=head;
if(head->next)
{
head->next->prev=0;
}
else
{
tail=0;
}
head=head->next;
lpNode->prev=lpNode->next=0;
return lpNode;
}
else
{
return 0;
}
}
// βһڵ
PNode PopBack()
{
if(tail)
{
PNode lpNode=tail;
if(tail->prev)
{
tail->prev->next=0;
}
else
{
head=0;
}
tail=tail->prev;
lpNode->prev=lpNode->next=0;
return lpNode;
}
else
{
return 0;
}
}
// ɾڵ
PNode remove(PNode lpNode)
{
if(lpNode->prev)
{
lpNode->prev->next=lpNode->next;
}
else
{
head=lpNode->next;
}
if(lpNode->next)
{
lpNode->next->prev=lpNode->prev;
}
else
{
tail=lpNode->prev;
}
return lpNode;
}
// ǷΪ
bool empty()
{
if(head || tail)
{
return false;
}
else
{
return true;
}
}
// ȡеĽڵ
long size()
{
long lnSize =0;
PNode lpNode=head;
while(lpNode)
{
++lnSize;
lpNode=next(lpNode);
}
return lnSize;
}
// ϲ
ListNode* combine(ListNode* other)
{
if(!other->empty())
{
if(!empty())
{
tail->next =other->head;
other->head->prev =tail;
tail =other->tail;
}
else
{
head =other->head;
tail =other->tail;
}
other->head =other->tail =0;
}
return this;
}
private:
PNode head;
PNode tail;
};
| true |