blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d9d357948bec78d2fc8f77b2d5f01676af22651e | 77a1e8b6e3181b097a196bda951ae5ed05115729 | /unittests/database_tests.cpp | 51f7502f513adb17c6139130a97434c997f0d15c | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | yinchengtsinghua/EOSIOChineseCPP | 04888f80cb7a946fb54c2494137868cb86685ff1 | dceabf6315ab8c9a064c76e943b2b44037165a85 | refs/heads/master | 2020-04-18T01:20:58.685186 | 2019-01-23T04:17:07 | 2019-01-23T04:17:07 | 167,115,462 | 21 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 4,494 | cpp | database_tests.cpp |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
/*
*@文件
*@eos/license中定义的版权
**/
#include <eosio/testing/tester.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <fc/crypto/digest.hpp>
#include <boost/test/unit_test.hpp>
#ifdef NON_VALIDATING_TEST
#define TESTER tester
#else
#define TESTER validating_tester
#endif
using namespace eosio::chain;
using namespace eosio::testing;
namespace bfs = boost::filesystem;
BOOST_AUTO_TEST_SUITE(database_tests)
//撤消基础结构的简单测试
BOOST_AUTO_TEST_CASE(undo_test) {
try {
TESTER test;
//对于这个单元测试,绕过对状态数据库访问的只读限制,这实际上需要改变数据库以正确地进行测试。
eosio::chain::database& db = const_cast<eosio::chain::database&>( test.control->db() );
auto ses = db.start_undo_session(true);
//创建帐户
db.create<account_object>([](account_object &a) {
a.name = "billy";
});
//确保我们可以按名称检索该帐户
auto ptr = db.find<account_object, by_name, std::string>("billy");
BOOST_TEST(ptr != nullptr);
//撤消帐户创建
ses.undo();
//确保我们再也找不到帐户
ptr = db.find<account_object, by_name, std::string>("billy");
BOOST_TEST(ptr == nullptr);
} FC_LOG_AND_RETHROW()
}
//在数据库上测试取块方法,用ID取块,用编号取块
BOOST_AUTO_TEST_CASE(get_blocks) {
try {
TESTER test;
vector<block_id_type> block_ids;
const uint32_t num_of_blocks_to_prod = 200;
//生成200个块并检查它们的ID是否与上面的匹配
test.produce_blocks(num_of_blocks_to_prod);
for (uint32_t i = 0; i < num_of_blocks_to_prod; ++i) {
block_ids.emplace_back(test.control->fetch_block_by_number(i + 1)->id());
BOOST_TEST(block_header::num_from_id(block_ids.back()) == i + 1);
BOOST_TEST(test.control->fetch_block_by_number(i + 1)->id() == block_ids.back());
}
//用于检查预期不可逆块的实用函数
auto calc_exp_last_irr_block_num = [&](uint32_t head_block_num) -> uint32_t {
const auto producers_size = test.control->head_block_state()->active_schedule.producers.size();
const auto max_reversible_rounds = EOS_PERCENT(producers_size, config::percent_100 - config::irreversible_threshold_percent);
if( max_reversible_rounds == 0) {
return head_block_num;
} else {
const auto current_round = head_block_num / config::producer_repetitions;
const auto irreversible_round = current_round - max_reversible_rounds;
return (irreversible_round + 1) * config::producer_repetitions - 1;
}
};
//检查最后一个不可逆块号是否设置正确
const auto expected_last_irreversible_block_number = calc_exp_last_irr_block_num(num_of_blocks_to_prod);
BOOST_TEST(test.control->head_block_state()->dpos_irreversible_blocknum == expected_last_irreversible_block_number);
//检查是否找不到块201(仅存在20个块)
BOOST_TEST(test.control->fetch_block_by_number(num_of_blocks_to_prod + 1 + 1) == nullptr);
const uint32_t next_num_of_blocks_to_prod = 100;
//生成100个块并检查它们的ID是否与上面的匹配
test.produce_blocks(next_num_of_blocks_to_prod);
const auto next_expected_last_irreversible_block_number = calc_exp_last_irr_block_num(
num_of_blocks_to_prod + next_num_of_blocks_to_prod);
//检查最后一个不可逆的块号是否正确更新
BOOST_TEST(test.control->head_block_state()->dpos_irreversible_blocknum == next_expected_last_irreversible_block_number);
//检查201区是否现在可以找到
BOOST_CHECK_NO_THROW(test.control->fetch_block_by_number(num_of_blocks_to_prod + 1));
//检查最新的头块匹配
BOOST_TEST(test.control->fetch_block_by_number(num_of_blocks_to_prod + next_num_of_blocks_to_prod + 1)->id() ==
test.control->head_block_id());
} FC_LOG_AND_RETHROW()
}
BOOST_AUTO_TEST_SUITE_END()
|
55f3dfa806659c591aa93283c6f17f21449ad938 | 09bba7e46fd23b6c065b4bd1af90b67bae9216a2 | /hw8/Animal.cpp | 21289bc1ae869cf413de0257b0587d702e827280 | [] | no_license | cat-kat/cpp-itmo | abf8991a6e774f72362e77bc004b38be321efb06 | ed1d975fc4fd594acf0d826b8c07a3dbf69b6fcc | refs/heads/master | 2021-10-24T09:50:29.734381 | 2019-03-25T00:33:35 | 2019-03-25T00:33:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | Animal.cpp | #include "ManBearPig.h"
Animal::Animal(string const& name, size_t id, int hp)
: Unit(id, hp),
mName(name) {}
string Animal::name() const {
return mName;
}
|
aad9c2b5d3ff134b16afd1e5e91b6fdbfb30088f | 6e665dcd74541d40647ebb64e30aa60bc71e610c | /800/VPBX_Support/stacks/sipstack/SipRetryAfter.cxx | 79bbfdc429716d567514a86036981832a2aff9af | [] | no_license | jacklee032016/pbx | b27871251a6d49285eaade2d0a9ec02032c3ec62 | 554149c134e50db8ea27de6a092934a51e156eb6 | refs/heads/master | 2020-03-24T21:52:18.653518 | 2018-08-04T20:01:15 | 2018-08-04T20:01:15 | 143,054,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,226 | cxx | SipRetryAfter.cxx | /*
* $Log: SipRetryAfter.cxx,v $
* Revision 1.1.1.1 2006/11/30 16:27:10 lizhijie
* AS800 VPBX_Support
*
* Revision 1.1.1.1 2006/06/03 11:55:33 lizhijie
* build a independent directory for VPBX support libraris
*
* $Id: SipRetryAfter.cxx,v 1.1.1.1 2006/11/30 16:27:10 lizhijie Exp $
*/
#include "global.h"
#include "SipRetryAfter.hxx"
#include "symbols.hxx"
#include "SipParserMode.hxx"
#include "cpLog.h"
using namespace Assist;
string
SipRetryAfterParserException::getName( void ) const
{
return "SipRetryAfterParserException";
}
///
SipRetryAfter::SipRetryAfter()
:
flagcomment(false),
flagduration(false)
{
}
///
SipRetryAfter::SipRetryAfter( const Data& srcData )
:
flagcomment(false),
flagduration(false)
{
try
{
decode(srcData);
}
catch (SipRetryAfterParserException&)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
}
SipRetryAfter&
SipRetryAfter::operator=(const SipRetryAfter& rhs)
{
if ( &rhs != this )
{
date = rhs.date;
datedata = rhs.datedata;
comment = rhs.comment;
flagcomment = rhs.flagcomment;
flagduration = rhs.flagduration;
}
return *this;
}
void SipRetryAfter::decode(const Data& retrydata)
{
Data data = retrydata;
try
{
scanRetryAfter(data);
}
catch (SipRetryAfterParserException& exception)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
exception.getDescription(),
__FILE__,
__LINE__, SCAN_RETRYAFTER_FAILED);
}
}
}
void
SipRetryAfter::scanRetryAfter(const Data &tmpdata)
{
Data rtdata = tmpdata;
Data newvalue;
int retn = rtdata.match("(", &newvalue, true);
if (retn == NOT_FOUND)
{
Data rtvalue;
int ret = rtdata.match(";", &rtvalue, true);
if (ret == FOUND)
{
parseDate(rtvalue);
parseDuration(rtdata);
}
else if (ret == NOT_FOUND)
{
parseDate(rtdata);
}
else if (ret == FIRST)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in scanRetryAfter :(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
}
else if (retn == FOUND)
{
parseDate(newvalue);
Data finald = rtdata;
Data finalv;
int rt = finald.match(")", &finalv, true);
if (rt == FOUND)
{
setComment(finalv);
Data valuei;
int reth = finald.match(";", &valuei, true);
if (reth == FOUND)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in scanRetryAfter :(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
else if (reth == NOT_FOUND)
{
}
else if (reth == FIRST)
{
parseDuration(finald);
}
}
else if (rt == NOT_FOUND)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in scanRetryAfter :(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
else if (rt == FIRST)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in scanRetryAfter :(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
}
else if (retn == FIRST)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in scanRetryAfter :(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
}
void
SipRetryAfter::parseDuration(const Data& datdata)
{
Data durdata = datdata;
Data durvalue;
int retn = durdata.match("=", &durvalue, true);
if (retn == FOUND)
{
if (durdata == SIP_DURATION)
{
setDuration(durdata.convertInt());
}
}
else if (retn == NOT_FOUND)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in ParseDuration :(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
else if (retn == FIRST)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in Parse Duration:(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
}
void
SipRetryAfter::parseDate(const Data& dadata)
{
Data dtdata = dadata;
Data dtvalue;
int retn = dtdata.match(",", &dtvalue, false);
if (retn == FOUND)
{
SipDate datetmp(dtdata);
date = datetmp;
}
else if (retn == NOT_FOUND)
{
setDuration(dtdata.convertInt());
}
else if (retn == FIRST)
{
if (SipParserMode::sipParserMode())
{
throw SipRetryAfterParserException(
"failed to decode the Retry After string in Parse Date :(",
__FILE__,
__LINE__, DECODE_RETRYAFTER_FAILED);
}
}
}
///
SipRetryAfter::SipRetryAfter( const SipRetryAfter& src )
:
date(src.date),
datedata(src.datedata),
comment(src.comment),
duration(src.duration),
flagcomment(src.flagcomment),
flagduration(src.flagduration)
{}
bool
SipRetryAfter::operator ==(const SipRetryAfter& src) const
{
cpDebug(LOG_DEBUG_STACK, "Retry After == Operator ");
if ( (date == src.date) &&
(comment == src.comment) &&
(duration == src.duration )
)
{
cpDebug(LOG_DEBUG_STACK, "Retry After == Operator returning True");
return true;
}
else
{
cpDebug(LOG_DEBUG_STACK, "Retry After == Operator returning False");
return false;
}
}
///
SipDate SipRetryAfter::getDate() const
{
return date;
}
///
void SipRetryAfter::setDate( const SipDate& newdate )
{
date = newdate;
}
///
Data SipRetryAfter::getComment() const
{
return comment;
}
///
void SipRetryAfter::setComment( const Data& newcomment )
{
comment = newcomment;
flagcomment = true;
}
///
int SipRetryAfter::getDuration() const
{
return duration.convertInt();
}
///
void
SipRetryAfter::setDuration( int newduration )
{
duration = Data(newduration);
flagduration = true ;
}
///
Data SipRetryAfter::encode() const
{
Data ret;
Data ldatedata = date.encode();
if (ldatedata.length())
{
ret += SIP_RETRYAFTER;
ret += SP;
ret += ldatedata;
if (flagcomment)
{
ret += comment;
}
if (flagduration)
{
ret += ";";
ret += "duration";
ret += "=";
ret += duration;
}
}
return ret;
}
// End of File
SipHeader*
SipRetryAfter::duplicate() const
{
return new SipRetryAfter(*this);
}
bool
SipRetryAfter::compareSipHeader(SipHeader* msg) const
{
SipRetryAfter* otherMsg = dynamic_cast<SipRetryAfter*>(msg);
if(otherMsg != 0)
{
return (*this == *otherMsg);
}
else
{
return false;
}
}
|
4ffba440aa6872811cbbcdfb5b974b58fdfac18d | f27cb638eec4bbaa42267c5904315f74dfc30209 | /SHP6HMLOX/LED.ino | 46ae322ed8e1ffa0f580e837cbaeb2dec9308d60 | [] | no_license | MasterPu/SHP6HMLOX | dfc5dde3e544860ee6d530272c4676af77745a3e | bcdcd87bc5b8c45467af43c3195a3181bc1f8edc | refs/heads/master | 2020-04-28T17:30:23.139803 | 2019-03-13T18:33:13 | 2019-03-13T18:33:13 | 175,449,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | ino | LED.ino | void switchLED(bool State) {
if (GlobalConfig.LEDDisabled) {
digitalWrite(LEDPin, On);
} else {
digitalWrite(LEDPin, State);
}
}
void blinkLED(int count) {
byte oldState = digitalRead(LEDPin);
delay(100);
for (int i = 0; i < count; i++) {
switchLED(!oldState);
delay(100);
switchLED(oldState);
delay(100);
}
delay(200);
}
|
b3f2b48ab6d0c95c664fb7bc9cb38c4ff3b6edf2 | 6a11d2e56eda699ff63e56ac87d69934cd48740c | /mstl_image_dir.hpp | 90f3a2732cd7491f576e87603acf37585d84298c | [] | no_license | halsten/my-toolkit | 727152c9aa480a3d989ac97cc29849555d9db54d | 4d37e920ed66f045f2866c98549617de4d9817d3 | refs/heads/master | 2023-03-26T01:33:45.513547 | 2017-07-16T14:40:46 | 2017-07-16T14:40:46 | 351,218,795 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | hpp | mstl_image_dir.hpp | #pragma once
#include "mstl_address.hpp"
template<size_t data_directory>
class IMAGE_DIR : public Address {
public:
__forceinline IMAGE_DIR() : Address{} {}
__forceinline ~IMAGE_DIR() {}
IMAGE_DIR(Address image_base) :
Address{image_base} {
init();
}
__forceinline void init() {
IMAGE_DATA_DIRECTORY *dir;
IMAGE_DOS_HEADER *dos;
IMAGE_NT_HEADERS *nt;
// init dos header from as (image base)
dos = as<IMAGE_DOS_HEADER*>();
// sanity check image really quick
if (dos->e_magic != IMAGE_DOS_SIGNATURE)
return;
// init nt header
nt = RVA<IMAGE_NT_HEADERS*>(as(), dos->e_lfanew);
// sanity check nt header rl quick
if (nt == nullptr || nt->Signature != IMAGE_NT_SIGNATURE)
return;
// get RVA of our desired directory
dir = &nt->OptionalHeader.DataDirectory[data_directory];
// set and finish
m_ptr = RVA(as(), dir->VirtualAddress);
}
// get the dir we're fkn with
constexpr size_t get_directory() const {
return data_directory;
};
}; |
afe48a307674180274b5ea66bf5039e3ceed3bad | b61d1d9f55b8c13b6bd5504ed97b17d311c5c215 | /C/Test5.cpp | 0e4ee5574f6229d0628afa80b92bad55cc80885a | [] | no_license | Dhanuka99/Practical | b78eabe08f9885a4e207b163ad6438fb4f97cb15 | 73c37d666d3161a392d73419f8062e33940fef22 | refs/heads/master | 2023-08-04T13:57:21.225038 | 2021-09-08T14:55:17 | 2021-09-08T14:55:17 | 402,864,048 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 161 | cpp | Test5.cpp | //
// Created by DHANUKA on 9/8/2021.
//increment and decrement
//
#include <stdio.h>
int main(){
int a = 5;
printf("%d ",a++);
printf("%d ",a);
}
|
609fc2ede7836616c64920c1fb02b0ca094d4d21 | 32fcc41cc1b59a46932158e5062c8c37f88cd989 | /core/pass.cpp | b3442fd26b5f46845e9786ff01322ee9c1ebd711 | [
"Apache-2.0"
] | permissive | google/jsonnet | 4cb224b7836e215df4bac809ad1ffed628a4d3d7 | e605e4673294d2bf43eb8351fb8f5d9ba26d5e68 | refs/heads/master | 2023-08-28T16:27:58.576444 | 2023-08-14T12:02:45 | 2023-08-14T12:02:45 | 22,527,161 | 6,616 | 546 | Apache-2.0 | 2023-08-14T12:02:46 | 2014-08-01T20:29:12 | Jsonnet | UTF-8 | C++ | false | false | 10,786 | cpp | pass.cpp | /*
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "pass.h"
namespace jsonnet::internal {
void CompilerPass::fodder(Fodder &fodder)
{
for (auto &f : fodder)
fodderElement(f);
}
void CompilerPass::specs(std::vector<ComprehensionSpec> &specs)
{
for (auto &spec : specs) {
fodder(spec.openFodder);
switch (spec.kind) {
case ComprehensionSpec::FOR:
fodder(spec.varFodder);
fodder(spec.inFodder);
expr(spec.expr);
break;
case ComprehensionSpec::IF: expr(spec.expr); break;
}
}
}
void CompilerPass::params(Fodder &fodder_l, ArgParams ¶ms, Fodder &fodder_r)
{
fodder(fodder_l);
for (auto ¶m : params) {
fodder(param.idFodder);
if (param.expr) {
fodder(param.eqFodder);
expr(param.expr);
}
fodder(param.commaFodder);
}
fodder(fodder_r);
}
void CompilerPass::fieldParams(ObjectField &field)
{
if (field.methodSugar) {
params(field.fodderL, field.params, field.fodderR);
}
}
void CompilerPass::fields(ObjectFields &fields)
{
for (auto &field : fields) {
switch (field.kind) {
case ObjectField::LOCAL: {
fodder(field.fodder1);
fodder(field.fodder2);
fieldParams(field);
fodder(field.opFodder);
expr(field.expr2);
} break;
case ObjectField::FIELD_ID:
case ObjectField::FIELD_STR:
case ObjectField::FIELD_EXPR: {
if (field.kind == ObjectField::FIELD_ID) {
fodder(field.fodder1);
} else if (field.kind == ObjectField::FIELD_STR) {
expr(field.expr1);
} else if (field.kind == ObjectField::FIELD_EXPR) {
fodder(field.fodder1);
expr(field.expr1);
fodder(field.fodder2);
}
fieldParams(field);
fodder(field.opFodder);
expr(field.expr2);
} break;
case ObjectField::ASSERT: {
fodder(field.fodder1);
expr(field.expr2);
if (field.expr3 != nullptr) {
fodder(field.opFodder);
expr(field.expr3);
}
} break;
}
fodder(field.commaFodder);
}
}
void CompilerPass::expr(AST *&ast_)
{
fodder(ast_->openFodder);
visitExpr(ast_);
}
void CompilerPass::visit(Apply *ast)
{
expr(ast->target);
params(ast->fodderL, ast->args, ast->fodderR);
if (ast->tailstrict) {
fodder(ast->tailstrictFodder);
}
}
void CompilerPass::visit(ApplyBrace *ast)
{
expr(ast->left);
expr(ast->right);
}
void CompilerPass::visit(Array *ast)
{
for (auto &element : ast->elements) {
expr(element.expr);
fodder(element.commaFodder);
}
fodder(ast->closeFodder);
}
void CompilerPass::visit(ArrayComprehension *ast)
{
expr(ast->body);
fodder(ast->commaFodder);
specs(ast->specs);
fodder(ast->closeFodder);
}
void CompilerPass::visit(Assert *ast)
{
expr(ast->cond);
if (ast->message != nullptr) {
fodder(ast->colonFodder);
expr(ast->message);
}
fodder(ast->semicolonFodder);
expr(ast->rest);
}
void CompilerPass::visit(Binary *ast)
{
expr(ast->left);
fodder(ast->opFodder);
expr(ast->right);
}
void CompilerPass::visit(Conditional *ast)
{
expr(ast->cond);
fodder(ast->thenFodder);
if (ast->branchFalse != nullptr) {
expr(ast->branchTrue);
fodder(ast->elseFodder);
expr(ast->branchFalse);
} else {
expr(ast->branchTrue);
}
}
void CompilerPass::visit(Error *ast)
{
expr(ast->expr);
}
void CompilerPass::visit(Function *ast)
{
params(ast->parenLeftFodder, ast->params, ast->parenRightFodder);
expr(ast->body);
}
void CompilerPass::visit(Import *ast)
{
visit(ast->file);
}
void CompilerPass::visit(Importstr *ast)
{
visit(ast->file);
}
void CompilerPass::visit(Importbin *ast)
{
visit(ast->file);
}
void CompilerPass::visit(InSuper *ast)
{
expr(ast->element);
}
void CompilerPass::visit(Index *ast)
{
expr(ast->target);
if (ast->id != nullptr) {
} else {
if (ast->isSlice) {
if (ast->index != nullptr)
expr(ast->index);
if (ast->end != nullptr)
expr(ast->end);
if (ast->step != nullptr)
expr(ast->step);
} else {
expr(ast->index);
}
}
}
void CompilerPass::visit(Local *ast)
{
assert(ast->binds.size() > 0);
for (auto &bind : ast->binds) {
fodder(bind.varFodder);
if (bind.functionSugar) {
params(bind.parenLeftFodder, bind.params, bind.parenRightFodder);
}
fodder(bind.opFodder);
expr(bind.body);
fodder(bind.closeFodder);
}
expr(ast->body);
}
void CompilerPass::visit(Object *ast)
{
fields(ast->fields);
fodder(ast->closeFodder);
}
void CompilerPass::visit(DesugaredObject *ast)
{
for (AST *assert : ast->asserts) {
expr(assert);
}
for (auto &field : ast->fields) {
expr(field.name);
expr(field.body);
}
}
void CompilerPass::visit(ObjectComprehension *ast)
{
fields(ast->fields);
specs(ast->specs);
fodder(ast->closeFodder);
}
void CompilerPass::visit(ObjectComprehensionSimple *ast)
{
expr(ast->field);
expr(ast->value);
expr(ast->array);
}
void CompilerPass::visit(Parens *ast)
{
expr(ast->expr);
fodder(ast->closeFodder);
}
void CompilerPass::visit(SuperIndex *ast)
{
if (ast->id != nullptr) {
} else {
expr(ast->index);
}
}
void CompilerPass::visit(Unary *ast)
{
expr(ast->expr);
}
#define VISIT(var,astType,astClass) \
case astType: { \
assert(dynamic_cast<astClass *>(var)); \
auto *ast = static_cast<astClass *>(var); \
visit(ast); \
} break
void CompilerPass::visitExpr(AST *&ast_)
{
switch(ast_->type) {
VISIT(ast_, AST_APPLY, Apply);
VISIT(ast_, AST_APPLY_BRACE, ApplyBrace);
VISIT(ast_, AST_ARRAY, Array);
VISIT(ast_, AST_ARRAY_COMPREHENSION, ArrayComprehension);
// VISIT(ast_, AST_ARRAY_COMPREHENSION, ArrayComprehensionSimple);
VISIT(ast_, AST_ASSERT, Assert);
VISIT(ast_, AST_BINARY, Binary);
VISIT(ast_, AST_BUILTIN_FUNCTION, BuiltinFunction);
VISIT(ast_, AST_CONDITIONAL, Conditional);
VISIT(ast_, AST_DESUGARED_OBJECT, DesugaredObject);
VISIT(ast_, AST_DOLLAR, Dollar);
VISIT(ast_, AST_ERROR, Error);
VISIT(ast_, AST_FUNCTION, Function);
VISIT(ast_, AST_IMPORT, Import);
VISIT(ast_, AST_IMPORTSTR, Importstr);
VISIT(ast_, AST_IMPORTBIN, Importbin);
VISIT(ast_, AST_INDEX, Index);
VISIT(ast_, AST_IN_SUPER, InSuper);
VISIT(ast_, AST_LITERAL_BOOLEAN, LiteralBoolean);
VISIT(ast_, AST_LITERAL_NULL, LiteralNull);
VISIT(ast_, AST_LITERAL_NUMBER, LiteralNumber);
VISIT(ast_, AST_LITERAL_STRING, LiteralString);
VISIT(ast_, AST_LOCAL, Local);
VISIT(ast_, AST_OBJECT, Object);
VISIT(ast_, AST_OBJECT_COMPREHENSION, ObjectComprehension);
VISIT(ast_, AST_OBJECT_COMPREHENSION_SIMPLE, ObjectComprehensionSimple);
VISIT(ast_, AST_PARENS, Parens);
VISIT(ast_, AST_SELF, Self);
VISIT(ast_, AST_SUPER_INDEX, SuperIndex);
VISIT(ast_, AST_UNARY, Unary);
VISIT(ast_, AST_VAR, Var);
default:
std::cerr << "INTERNAL ERROR: Unknown AST: " << ast_ << std::endl;
std::abort();
break;
}
}
void CompilerPass::file(AST *&body, Fodder &final_fodder)
{
expr(body);
fodder(final_fodder);
}
/** A pass that clones the AST it is given. */
class ClonePass : public CompilerPass {
public:
ClonePass(Allocator &alloc) : CompilerPass(alloc) {}
virtual void expr(AST *&ast);
};
#define CLONE(var,astType,astClass) \
case astType: { \
assert(dynamic_cast<astClass *>(var)); \
auto *ast = static_cast<astClass *>(var); \
var = alloc.clone(ast); \
} break
void ClonePass::expr(AST *&ast_)
{
switch(ast_->type) {
CLONE(ast_, AST_APPLY, Apply);
CLONE(ast_, AST_APPLY_BRACE, ApplyBrace);
CLONE(ast_, AST_ARRAY, Array);
CLONE(ast_, AST_ARRAY_COMPREHENSION, ArrayComprehension);
// CLONE(ast_, AST_ARRAY_COMPREHENSION, ArrayComprehensionSimple);
CLONE(ast_, AST_ASSERT, Assert);
CLONE(ast_, AST_BINARY, Binary);
CLONE(ast_, AST_BUILTIN_FUNCTION, BuiltinFunction);
CLONE(ast_, AST_CONDITIONAL, Conditional);
CLONE(ast_, AST_DESUGARED_OBJECT, DesugaredObject);
CLONE(ast_, AST_DOLLAR, Dollar);
CLONE(ast_, AST_ERROR, Error);
CLONE(ast_, AST_FUNCTION, Function);
CLONE(ast_, AST_IMPORT, Import);
CLONE(ast_, AST_IMPORTSTR, Importstr);
CLONE(ast_, AST_IMPORTBIN, Importbin);
CLONE(ast_, AST_INDEX, Index);
CLONE(ast_, AST_IN_SUPER, InSuper);
CLONE(ast_, AST_LITERAL_BOOLEAN, LiteralBoolean);
CLONE(ast_, AST_LITERAL_NULL, LiteralNull);
CLONE(ast_, AST_LITERAL_NUMBER, LiteralNumber);
CLONE(ast_, AST_LITERAL_STRING, LiteralString);
CLONE(ast_, AST_LOCAL, Local);
CLONE(ast_, AST_OBJECT, Object);
CLONE(ast_, AST_OBJECT_COMPREHENSION, ObjectComprehension);
CLONE(ast_, AST_OBJECT_COMPREHENSION_SIMPLE, ObjectComprehensionSimple);
CLONE(ast_, AST_PARENS, Parens);
CLONE(ast_, AST_SELF, Self);
CLONE(ast_, AST_SUPER_INDEX, SuperIndex);
CLONE(ast_, AST_UNARY, Unary);
CLONE(ast_, AST_VAR, Var);
default:
std::cerr << "INTERNAL ERROR: Unknown AST: " << ast_ << std::endl;
std::abort();
break;
}
CompilerPass::expr(ast_);
}
AST *clone_ast(Allocator &alloc, AST *ast)
{
AST *r = ast;
ClonePass(alloc).expr(r);
return r;
}
} // namespace jsonnet::internal
|
c7b0d39af53571e58e5f1b5064b14c36d6c08b47 | 03c71398ebae1405492d7e141c1fc6199d37d56f | /Labs/Lab6/Menu.cpp | 0c338a596df3f9a64924426cfc2c4e272a674b3d | [] | no_license | AStockinger/Cpp-Projects | f40bea19ddd84fb07cc10c1c1e761a82f6bd07b9 | f53d22a1067ddbdb8cacb2e5bbc91f4360916d1c | refs/heads/master | 2020-04-11T20:14:14.455812 | 2018-12-18T04:48:03 | 2018-12-18T04:48:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,131 | cpp | Menu.cpp | /******************************************************************************
** Program name: Lab 6
** Author: Amy Stockinger
** Date: 10/27/18
** Description: Menu function implementation
******************************************************************************/
#include "Menu.hpp"
#include "InputVal.hpp"
#include "DoublyLinkedList.hpp"
#include <iostream>
#include <climits>
using std::cout;
using std::endl;
void menu(){
bool playing = true;
int choice;
int num;
DoublyLinkedList list;
cout << "Welcome to my linked list!" << endl;
cout << "**This program includes both extra credit options**" << endl;
while(playing){
cout << "Choose from the following options:" << endl;
cout << "1. Add new node to the head" << endl;
cout << "2. Add new node to the tail" << endl;
cout << "3. Delete from head" << endl;
cout << "4. Delete from tail" << endl;
cout << "5. Traverse the list reversely" << endl;
cout << "6. Print value of head node" << endl;
cout << "7. Print value of tail node" << endl;
cout << "8. Read list from file" << endl;
cout << "9. Quit" << endl;
getInt(choice, 1, 9);
switch(choice){
case 1: getInt(num, 0, INT_MAX);
list.addHeadNode(num);
list.traverse();
break;
case 2: getInt(num, 0, INT_MAX);
list.addTailNode(num);
list.traverse();
break;
case 3: list.deleteFirstNode();
list.traverse();
break;
case 4: list.deleteLastNode();
list.traverse();
break;
case 5: list.traverseReversely();
break;
case 6: list.printNodeHead();
break;
case 7: list.printNodeTail();
break;
case 8: list.readFromFile();
list.traverse();
break;
case 9: cout << "Goodbye!" << endl;
playing = false;
return;
break;
}
}
} |
9ec01257fd22fbf115e27330c381909275ce167e | 42e52b620748c68ee175f1eef6c31a9e66f330bc | /swift/util/str_util.cc | 5d63e4628790de98a83ee6276c4f29a0d3d706f7 | [] | no_license | hzliu/swift | a4e0e2fb1316345f0c6d2fc175d00afae0cf696c | db88a63231d752169c25cd6e4fa9acf434b6d45d | refs/heads/master | 2016-09-05T23:32:04.307152 | 2012-06-07T09:17:47 | 2012-06-07T09:17:47 | 4,544,706 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cc | str_util.cc | #include <swift/util/str_util.h>
std::vector<std::string> split(const std::string &str, const char *delimeters)
{
std::vector<std::string> results;
std::string::size_type pos = 0;
while(pos != std::string::npos)
{
std::string::size_type next = str.find_first_of(delimeters, pos);
if(next == std::string::npos)
{
results.push_back(str.substr(pos));
return results;
}
results.push_back(str.substr(pos, next - pos));
pos = next + 1;
}
return results;
}
|
d68431abe815859b51a993d0a2e9fab456b4a39d | 0e8d57f10639b0bdcab2c89b307029697c909863 | /atcoder/abc203/D/main.cpp | 9728c863a079bbfb250080e5a3cfe32510c4e448 | [
"Apache-2.0"
] | permissive | xirc/cp-algorithm | 07a6faf5228e07037920f5011326c16091a9157d | e83ea891e9f8994fdd6f704819c0c69f5edd699a | refs/heads/main | 2021-12-25T16:19:57.617683 | 2021-12-22T12:06:49 | 2021-12-22T12:06:49 | 226,591,291 | 15 | 1 | Apache-2.0 | 2021-12-22T12:06:50 | 2019-12-07T23:53:18 | C++ | UTF-8 | C++ | false | false | 1,524 | cpp | main.cpp | #include <bits/stdc++.h>
inline int64_t binary_search(
std::function<bool(int64_t)> const& predicate,
int64_t ng,
int64_t ok
) {
assert(!predicate(ng));
assert(predicate(ok));
while (abs(ok - ng) > 1) {
auto m = (ok + ng) / 2;
if (predicate(m)) ok = m;
else ng = m;
}
return ok;
}
using namespace std;
using ll = int64_t;
using ff = long double;
int K, N;
vector<vector<int>> A;
bool can_be_median(int X) {
int const L = (K * K / 2) + 1;
vector<vector<int>> M(N+1, vector<int>(N+1, 0));
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
M[i+1][j+1] = (A[i][j] > X ? 1 : 0);
}
}
for (int i = 0; i <= N; ++i) {
for (int j = 0; j < N; ++j) {
M[i][j+1] += M[i][j];
}
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j <= N; ++j) {
M[i+1][j] += M[i][j];
}
}
for (int i = 0; i + K <= N; ++i) {
for (int j = 0; j + K <= N; ++j) {
int s = M[i+K][j+K] - M[i][j+K] - M[i+K][j] + M[i][j];
if (s < L) return true;
}
}
return false;
}
int solve() {
return binary_search(can_be_median, -1, 1e9);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> N >> K;
A.assign(N, vector<int>(N, 0));
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cin >> A[i][j];
}
}
cout << solve() << endl;
return 0;
} |
8901d898649dea7fa8762e35b462d332acca4f53 | 192d706e55f91fa65b7449a0c2af76cbbb29be4d | /D2/2018_10_29.cpp | d7570cfb67d1a82774af8f0b8c3003c56ab0a0f8 | [] | no_license | sungkae/SW-ExpertAcademy | 976d7ac4f73e821a0ce9ca78cc09e45c1627bec0 | 57f8e3df5dcbf544bbaf891852af0618ff68e561 | refs/heads/master | 2020-03-30T09:02:33.796587 | 2018-10-29T14:42:11 | 2018-10-29T14:42:11 | 151,057,540 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 504 | cpp | 2018_10_29.cpp | #include <iostream>
using namespace std;
int main()
{
int testCase,day;
int price[1000001] = { 0 };
cin >> testCase;
for (int i = 0; i < testCase; ++i)
{
cin >> day;
//매매가 입력
int max = 0,count = 0;
for (int j = 0; j < day; ++j)
{
cin >> price[j];
if (max < price[j])
{
max = price[j];
count++;
}
}
if (count == day && max == price[0])
{
cout << "0" << endl;
continue;
}
//구하자, 배열의 size는 day만큼이다.
}
return 0;
} |
20e2e061ceb0f4dbec14bb87571afa832c1356b1 | 2d6bb5d4f863a11d39f657ccd74e333d913eb798 | /includes/aha_debug_screen.h | 0aea4ebc5463fd1ff93bed6fb33747a50c0cec27 | [] | no_license | Hyarius/Aha | 9d8ab492e22969ac88ea5139454d83f02f2292cf | 9acea919f3a3ee143d68187e3611edefb9bd4169 | refs/heads/master | 2021-01-04T12:01:38.627667 | 2020-04-13T13:21:59 | 2020-04-13T13:21:59 | 240,538,146 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | aha_debug_screen.h | #ifndef AHA_DEBUG_SCREEN_H
#define AHA_DEBUG_SCREEN_H
#include "jgl.h"
#include "aha_editor_mode.h"
class c_debug_screen : public c_widget
{
private:
class c_game_engine* _engine;
public:
c_debug_screen(c_game_engine *p_engine, c_widget* p_parent = nullptr);
void draw_line(int& nb_line, string text);
void render();
string parse_direction(Vector3 direction);
void set_geometry_imp(Vector2 p_achor, Vector2 p_area) {}
};
#endif |
3936464bc27499dbee83c4872bc08a4aca71a131 | f28224ebcca66c4e8e0e31ae6135863e9d2e7f00 | /12.integer-to-roman.cpp | ec43994928079c59e772586eaa6dbc37faee5c5c | [] | no_license | fkljboy/my-leetcode | 8df5df625be2c3559ad4376d731ea0e6b25cb3c8 | f5d05b437b9938f82e85d19a08b16779bd790c4f | refs/heads/master | 2021-04-02T11:09:25.022762 | 2020-03-18T15:31:18 | 2020-03-18T15:31:18 | 248,268,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | cpp | 12.integer-to-roman.cpp | /*
* @lc app=leetcode id=12 lang=cpp
*
* [12] Integer to Roman
*/
// @lc code=start
class Solution {
public:
string intToRoman(int num) {
vector<int> values={1000,900,500,400,100,90,50,40,10,9,5,4,1};
vector<string> strs={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
string res;
for (int i=0;i<values.size();i++){
while (num>=values[i]){
res+=strs[i];
num-=values[i];
}
}
return res;
}
};
// @lc code=end
/*将数字和罗马数字一一对应,然后循环解决 符合贪心算法的策略 |
98a9ec343f8a3ba186ca53c68007432c68dd0a4d | 68e588d7651638b31d62b58bb17414a4f6b4e669 | /ch09/ex9_52.cpp | 04c22f7aaa80e86c709adc2d02fd6d77accfe238 | [] | no_license | HongfeiXu/CplusplusPrimer | 8d8844c9ca73c89067ec78a9cf3a4fee2b10a89b | 676a428b1164dd0e980e696d6553f02be96c633c | refs/heads/master | 2022-03-19T00:57:17.604996 | 2022-02-20T14:19:27 | 2022-02-20T14:19:27 | 57,424,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 841 | cpp | ex9_52.cpp | /*
* 练习 9.52:使用 stack 处理括号化表达式。
* 感觉题目的要求应该是类似于表达式求值。这里并没有实现,只是实现了去括号的操作,而且还只能处理一对括号。待改进。
*/
#include <stack>
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
string expression("Hello, (World)!");
bool bracketSeen = false;
stack<char> stk;
for(const auto c : expression)
{
if(c == '(')
{
bracketSeen = true;
continue;
}
else if(c == ')')
{
bracketSeen = false;
}
if(bracketSeen)
stk.push(c);
}
string repstr;
while(!stk.empty())
{
repstr += stk.top();
stk.pop();
}
expression.replace(expression.find("("), repstr.size() + 2, repstr);
cout << expression << endl;
return 0;
}
/*
Hello, dlroW!
请按任意键继续. . .
*/ |
d6eeeccf5876616c47128868f08714748e742aff | a8929c2a28e972f7fa64458fd961af994e77335e | /Clone.cpp | f333db55a67b7193bac3798dba01e04d839becb9 | [] | no_license | ligeweiwu/jianzhioffercpp | 8ad50939333a4b38d634bb45d8f23b99acf7f61d | 33dba9fa79288d03f6218f57ab2f3ff0241e2b6f | refs/heads/master | 2020-05-15T19:27:47.202296 | 2019-05-29T19:18:47 | 2019-05-29T19:18:47 | 182,456,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,773 | cpp | Clone.cpp | #include<stdio.h>
#include<math.h>
#include <iostream>
#include<bits/stdc++.h>
#include<vector>
#include<stack>
#include <unordered_map>
#include<map>
#include<unordered_set>
using namespace std;
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
class Solution {
public:
RandomListNode* Clone1(RandomListNode* pHead) //san bu cha ru fa, see blog
{
if(pHead==NULL)
{
return NULL;
}
RandomListNode* p1=pHead;
RandomListNode* p2=pHead;
while(p1!=NULL)
{
RandomListNode* clone=new RandomListNode(p1->label);
clone->next=p1->next;
p1->next=clone;
p1=p1->next->next;
}
while(p2!=NULL)
{
if(p2->random!=NULL)//important, boundary condition, deal with NULL situation
{
p2->next->random=p2->random->next;
}
p2=p2->next->next;
}
RandomListNode* p3=pHead;
RandomListNode* p4=pHead->next;
RandomListNode* p5=pHead->next;
while(p3!=NULL)
{
p3->next=p3->next->next;
if(p4->next!=NULL)
{
p4->next=p4->next->next;
}
p3=p3->next;
p4=p4->next;
}
return p5;
}
RandomListNode* Clone2(RandomListNode* pHead) //using map(ordered) method, it's easy to realize it(or can use unordered_map)
{
if(pHead==NULL)
{
return NULL;
}
map<RandomListNode*,RandomListNode*> clone;
RandomListNode *h=pHead;
RandomListNode *p=new RandomListNode(h->label);
clone[h]=p;
while(h->next!=NULL)
{
h=h->next;
p->next=new RandomListNode(h->label);
p=p->next;
clone[h]=p;
}
map<RandomListNode*,RandomListNode*>::iterator iter;
iter=clone.begin();
while(iter!=clone.end())
{
if(iter->first->random!=NULL)
{
iter->second->random=clone[iter->first->random];
}
iter++;
}
return clone[pHead];
}
RandomListNode* Clone3(RandomListNode* pHead)
{
if(pHead==NULL)
{
return NULL;
}
RandomListNode *clone=new RandomListNode(pHead->label);
map1[pHead]=clone;
clone->next=Clone3(pHead->next);
if(pHead->random!=NULL)
{
clone->random=map1[pHead->random];
}
return clone;
}
unordered_map<RandomListNode *,RandomListNode *>map1;
};
int main()
{
return 0;
}
|
6c58040d3069cb3d19d0e6b1a5317687aab0e6a0 | 6d37c919b4c4eb18671e2e8bb26c45cc5f584360 | /include/LinearLayer.hpp | 683882d0ca17e395e10ddc8f121a9610939afa43 | [] | no_license | BorisLestsov/CudaInference | f8f9fb62eedf5b3cf78d894c2eb537678e11d0eb | eb7ff688251bb741f47cdc4471312cb7a25338bf | refs/heads/master | 2022-07-14T05:57:59.463151 | 2020-05-06T02:02:49 | 2020-05-06T02:02:49 | 259,452,572 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | hpp | LinearLayer.hpp | #ifndef CUDA_PROJ_LINEARLAYER_CUH
#define CUDA_PROJ_LINEARLAYER_CUH
#include "Layer.hpp"
#include "Tensor.hpp"
#include <string>
#include <memory>
#include <cublas.h>
#include <cublas_v2.h>
class LinearLayer: public Layer {
public:
LinearLayer(cublasHandle_t& cublas_handle_p, const std::string& w_path, bool bias=true);
~LinearLayer();
void forward();
void set_input(std::shared_ptr<Tensor<float>> input);
std::shared_ptr<Tensor<float>> get_output();
int get_output_dim();
private:
int batch_size, input_dim, output_dim;
std::shared_ptr<Tensor<float>> _input, _w, _b, _res, _tmp;
cublasHandle_t& cublas_handle;
std::vector<float> data_b;
bool _bias;
};
#endif //CUDA_PROJ_LINEARLAYER_CUH
|
786cca94174329babea2acd229a606784d277db7 | 055f943f2cba917ff71f5db9f2b2b9e963ddb8f4 | /company/Manager_Dev/Xepoll_Client.cpp | 5e86dc0e557ca7ad4f4a612bcbfd7e8d3e9eeee6 | [] | no_license | zj23564/GitProject | 1c64daf39214d45b5516e48e104b015f5152bd38 | b6e272d47fc68e02db5f696595d8d8c9fdb2e2d2 | refs/heads/master | 2021-01-18T14:02:54.088766 | 2013-01-30T08:11:28 | 2013-01-30T08:11:28 | 7,910,189 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,957 | cpp | Xepoll_Client.cpp | #include "../include/Xepoll_Client.h"
#include<libxml/parser.h>
#include<libxml/tree.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char read_buff1[1024]={0};
char read_buff2[1024]={0};
char read_buff3[1024]={0};
char read_buff4[1024]={0};
char timebuff[1024]={0};
char write_buff[512] = {0};
map<int,DEVICE*> Xepoll_Client::Login_device;
//map<int,DEVICE*>Xepoll_Client:: ::iterator iter_login;
void ReadXml()
{
int sfd;
sfd=open("xml.xml",O_RDWR);
if(sfd<0){
printf("open sound 1\n");
//exit(EXIT_FAILURE);
return;
}
read(sfd,read_buff1,1024);
close(sfd);
sfd=open("request.xml",O_RDWR);
if(sfd<0){
printf("open sound 2\n");
//exit(EXIT_FAILURE);
return;
}
read(sfd,read_buff2,1024);
//close(sfd);
sfd=open("request2.xml",O_RDWR);
if(sfd<0){
printf("open sound 3\n");
//exit(EXIT_FAILURE);
return;
}
read(sfd,read_buff3,1024);
//close(sfd);
}
Xepoll_Client::Xepoll_Client(int Sockfd)
{
//ctor
m_Sockfd = Sockfd;
}
Xepoll_Client::~Xepoll_Client()
{
//dtor
}
int Xepoll_Client::Send(char *Buffer,int Len)
{
write(this->m_Sockfd,Buffer,Len);
return this->m_Sockfd;
}
int Xepoll_Client::Recv(char *Buffer,int Size)
{
read(this->m_Sockfd,Buffer,Size);
return this->m_Sockfd;
}
void Xepoll_Client::Gettime(void)
{
time_t tim;
struct tm * nowtime;
time(&tim);
nowtime = localtime(&tim);
int year = nowtime->tm_year+1900;
int mon = nowtime->tm_mon+1;
int day = nowtime->tm_mday;
int hour = nowtime->tm_hour;
int min = nowtime->tm_min;
int sec = nowtime->tm_sec;
char tmpbuf[512] = {0};
sprintf(tmpbuf,"%d%02d%02d%02d%02d%02d",year,mon,day,hour,min,sec);
sprintf(timebuff,"<iq type='set'>\n <query xmlns='posacar:signaling:heartbeat'>\n <time>%s</time>\n </query>\n</iq>",tmpbuf);
}
int register_count = 0;
int Xepoll_Client::Xml_Ans(char* buff,int fd)
{
xmlDocPtr doc;
xmlNodePtr root,node,res;
xmlChar *rt,*id,*passwd,*type,*ns;
// int fd = 0;;
// printf("in ans_xml buff i s\n %s\n ",buff);
// xmlNodePtr root,node;
//xmlChar *rt,*result,*addr,*port,*ns;
doc = xmlParseMemory(buff,strlen(buff));
if(doc == NULL){
printf("file is NULL\n");
return 0;
}
root = xmlDocGetRootElement(doc);
for(node = root->children;node;node = node->next){
//printf("node name is\n%s\n",node->name);
if(xmlStrcasecmp(node->name,BAD_CAST"query")==0){
// printf("xmlns is %s\n",node->ns->href);
char* p = strtok((char*)(node->ns->href),":");
p=strtok(NULL,":");
p=strtok(NULL,":");
printf("p is %s\n",p);
if(0==strcmp(p,"querylb")){
printf("device serch\n");
/*************解析出设备的ID 和密码 还有类型*****************/
memcpy(write_buff,read_buff1,strlen(read_buff1));
printf("write buff is \n%s\n ",write_buff);
fd = Send(write_buff,strlen(write_buff));
memset(write_buff,0,512);
break;
}
else if(0==strcmp(p,"register")){
printf("device register\n");
char* add_tmp = new char[sizeof(DEVICE)];
DEVICE* add = (DEVICE*)add_tmp;
for(res = node->children;res;res = res->next){
printf("res name is %s\n",res->name);
if(xmlStrcasecmp(res->name,BAD_CAST"id")==0){
id = xmlNodeGetContent(res);
memcpy(add->title,(char*)id,strlen((char*)id));
printf("id is\n %s\n",id);
}
else if(xmlStrcasecmp(res->name,BAD_CAST"passwd")==0){
passwd = xmlNodeGetContent(res);
printf("passwd is\n %s\n",passwd);
}
else if(xmlStrcasecmp(res->name,BAD_CAST"type")==0){
type = xmlNodeGetContent(res);
printf("type is\n %s\n",type);
add->Type = atoi((char*)type);
}
}
Login_device[fd] = add;
printf("Login_device.size is %d\n",Login_device.size());
xmlFree(id);
xmlFree(passwd);
xmlFree(type);
/**********************************************/
memcpy(write_buff,read_buff2,strlen(read_buff2));
printf("write buff is \n%s\n ",write_buff);
fd = Send(write_buff,strlen(write_buff));
memset(write_buff,0,512);
break;
}
else if(0==strcmp(p,"heartbeat")){
Gettime();
//printf("device heart beat\n");
register_count++;
printf("device heartbeat count is\n*******************\n***** %d******\n*******************\\n",register_count/2);
memcpy(write_buff,timebuff,512);
printf("write buff is \n%s\n ",write_buff);
fd = Send(write_buff,strlen(write_buff));
memset(timebuff,0,512);
memset(write_buff,0,512);
break;
}
else if(0==strcmp(p,"alarm")){
printf("device alarm\n");
break;
}
}
}
return fd;
} |
dd8cb0b53772326d2bb4f8fdcb97d9ab623054c2 | 375e5eca6bb3f80692212a9b975fc6b7786d6d22 | /ed.cpp | 2cab80b2b37d7d8b87182612e351ee8d0df43705 | [] | no_license | 3point141/dp | 156e0c02247fab27fc1e979dde017ed3efdea7ec | d8a538b4a1f72a5012d2670aa2a7fd0ff12ba9e1 | refs/heads/master | 2020-03-26T12:06:43.799159 | 2018-08-15T20:48:50 | 2018-08-15T20:48:50 | 144,876,042 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,481 | cpp | ed.cpp | /*Given two strings str1 and str2 and below operations that can performed on str1.
Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.
Insert
Remove
Replace
--> saturday
-->sunday
>>3
*/
/*
//recursion
#include<bits/stdc++.h>
using namespace std;
int minimum(int a,int b, int c)
{
if(a<b && a<c)
return a;
if(b<a && b<c)
return b;
if(c<a && c<b)
return c;
}
int mini(string a,string b,int l1, int l2)
{
if(l1==0)
return l2;
if(l2==0)
return l1;
if(a[l1-1]==b[l2-1])
return mini(a,b,l1-1,l2-1);
return 1 + minimum(mini(a,b,l1-1,l2),mini(a,b,l1-1,l2-1),mini(a,b,l1,l2-1));
}
int main()
{
string s1,s2;
getline(cin,s1);
getline(cin,s2);
int l1=s1.length();
int l2=s2.length();
cout<<mini(s1,s2,l1,l2)<<endl;
}
*/
//dynamic program
#include<bits/stdc++.h>
using namespace std;
int min(int a,int b,int c)
{
if(a<b && a<c)
return a;
if(b<a && b<c)
return b;
if(c<a && c<b)
return c;
}
int edit(string s1,string s2,int l1, int l2)
{
int res[l1+1][l2+1];
for(int i=0;i<=l1;i++)
{
for(int j=0;j<=l2;j++)
{
if(i==0)
res[i][j]=j;
else if(j==0)
res[i][j]=i;
else if(s1[i-1]==s2[j-1])
res[i][j]=res[i-1][j-1];
else
res[i][j]=1+min(res[i-1][j],res[i-1][j-1],res[i][j-1]);
}
}
return res[l1][l2];
}
int main()
{
string s1,s2;
getline(cin,s1);
getline(cin,s2);
int l1=s1.length();
int l2=s2.length();
cout<<edit(s1,s2,l1,l2)<<endl;
}
|
afce3dde448dc4520e760920730a95b8eb189025 | 9bc012a24217cd534db1a2b7e4f8ffaa1ca2b049 | /tests/arm_cs_test.cpp | 020f31666253138f0b00b234eb13e134a66b9a81 | [] | no_license | cvra/debra-old | 897eb245341c6f96ee8612a2578a2cc4217f9fb0 | f9e8a4492972f1a2d935038e5405360431e1369f | refs/heads/master | 2021-03-12T22:13:03.195619 | 2014-06-07T17:15:16 | 2014-06-07T17:15:16 | 13,085,575 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | cpp | arm_cs_test.cpp | #include "CppUTest/TestHarness.h"
extern "C" {
#include "../arm_cs.h"
}
static int pwm_called;
static int get_encoder_called;
static void pwm(void *p, int32_t v)
{
pwm_called++;
}
static int32_t get_encoder(void *p)
{
get_encoder_called++;
return 0;
}
TEST_GROUP(ArmControlTestGroup)
{
arm_control_loop_t loop;
void setup(void)
{
arm_cs_init_loop(&loop);
}
};
TEST(ArmControlTestGroup, LoopIsEnabled)
{
CHECK(loop.manager.enabled);
}
TEST(ArmControlTestGroup, LoopArchitectureIsCorrect)
{
POINTERS_EQUAL(pid_do_filter, loop.manager.correct_filter);
POINTERS_EQUAL(&loop.pid, loop.manager.correct_filter_params);
}
TEST(ArmControlTestGroup, ProcessOutCalled)
{
arm_cs_connect_motor(&loop, pwm, NULL);
arm_cs_manage(&loop);
CHECK_EQUAL(1, pwm_called);
}
TEST(ArmControlTestGroup, ProcessInCalled)
{
arm_cs_connect_encoder(&loop, get_encoder, NULL);
arm_cs_manage(&loop);
CHECK_EQUAL(1, get_encoder_called);
}
|
05115086ed198b7957ba2d5af2eb447bbe2af693 | af31bc46543cb027fa0371a5aaab41b94033d474 | /src/flappy_box/controller/paddle_logic.cpp | 410fb498a863a83fad9f7dbb8f6269dbc9923ae8 | [] | no_license | XanClic/hairy-wallhack | 76c51e1ae9496761d93dc9225a062d27660b981a | 4103d8a718e03435cba0d7b19000092bbd444b35 | refs/heads/master | 2021-01-24T16:09:37.828735 | 2016-03-16T04:16:45 | 2016-03-16T04:16:45 | 21,553,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,971 | cpp | paddle_logic.cpp | #include "math.hpp"
#include "flappy_box/controller/paddle_logic.hpp"
#include <GL/glut.h>
static const scalar_type player_accel_scale = 1000.f;
static const scalar_type accel_damping = .0f;
static const scalar_type vlcty_damping = .01f;
using namespace controller;
using namespace flappy_box::controller;
PaddleLogic::PaddleLogic(const std::shared_ptr<flappy_box::model::Paddle> &paddle_ptr):
_model(paddle_ptr.get())
{}
bool PaddleLogic::advance(Logic &l, const InputEventHandler::keyboard_event &evt)
{
scalar_type timestep_sec = l.game_model()->timestep().count();
if (evt.special_key == GLUT_KEY_RIGHT) {
right_down = evt.key_state == InputEventHandler::keyboard_event::KEY_DOWN;
} else if (evt.special_key == GLUT_KEY_LEFT) {
left_down = evt.key_state == InputEventHandler::keyboard_event::KEY_DOWN;
}
if (left_down == right_down) {
_model->playerControl().x() = 0.f;
} else if (left_down) {
_model->playerControl().x() = -1.f;
} else if (right_down) {
_model->playerControl().x() = 1.f;
}
_model->acceleration() = _model->acceleration() * powf(accel_damping, timestep_sec) + _model->playerControl() * player_accel_scale;
_model->velocity() = _model->velocity() * powf(vlcty_damping, timestep_sec) + _model->acceleration() * timestep_sec;
if (_model->velocity().length() > _model->maxVelocity()) {
_model->velocity() *= _model->maxVelocity() / _model->velocity().length();
}
_model->position() += _model->velocity() * timestep_sec;
for (int i = 0; i < 3; i++) {
if (fabs(_model->position()[i]) > _model->maxPosition()[i]) {
_model->position()[i] = copysign(_model->maxPosition()[i], _model->position()[i]);
_model->velocity()[i] *= -1.f;
}
}
for (scalar_type *scale: {&_model->scale(), &_model->relativeFanPower()}) {
if (*scale < 1.f) {
*scale *= exp(timestep_sec / 10.f);
if (*scale > 1.f) {
*scale = 1.f;
}
}
}
return false;
}
|
dd2ad2bb8555fe62bcb7b9dea2e512524c20efaa | 772d932a0e5f6849227a38cf4b154fdc21741c6b | /CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/graphics/visual2d/drawable/ListEntry2D.cpp | 4a317621f73fb3b5e2e43116df4584710102c3d8 | [] | no_license | AdrianNostromo/CodeSamples | 1a7b30fb6874f2059b7d03951dfe529f2464a3c0 | a0307a4b896ba722dd520f49d74c0f08c0e0042c | refs/heads/main | 2023-02-16T04:18:32.176006 | 2021-01-11T17:47:45 | 2021-01-11T17:47:45 | 328,739,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,629 | cpp | ListEntry2D.cpp | #include "ListEntry2D.h"
using namespace base;
ListEntry2D::ListEntry2D(
IAppMetrics* appMetrics, IAppAssets* appAssets, ArrayList<MenuItemConfig*>* viewItemConfigs, ArrayList<StateChangeDurations*>* viewEaseDurationsSList, List2D* list,
int entryUid)
: super(appMetrics, appAssets, viewItemConfigs, viewEaseDurationsSList),
list(list),
entryUid(entryUid)
{
//void
}
Map1D<std::string, std::shared_ptr<base::IWrappedValue>>* ListEntry2D::getUserDataMap() {
if (userDataMap == nullptr) {
userDataMap = new Map1D<std::string, std::shared_ptr<base::IWrappedValue>>();
}
return userDataMap;
}
bool ListEntry2D::getIsActive() {
return isActive;
}
void ListEntry2D::setIsActive(bool isActive, bool doAnimation) {
if (this->isActive == isActive) {
return;
}
this->isActive = isActive;
updateShowStateIfChanged(doAnimation, nullptr);
}
void ListEntry2D::show(bool doAnimation) {
std::string targetStateId = computeStateFlags("_in_");
setShowState(computeStateFlags("_out_toIn_"), targetStateId, doAnimation, nullptr, false);
}
void ListEntry2D::setLocalStateFlags(std::shared_ptr<std::string> localStateFlags) {
this->localStateFlags = localStateFlags;
updateShowStateIfChanged(true, nullptr);
}
std::string ListEntry2D::computeStateFlags(std::string baseState) {
std::string state = super::computeStateFlags(baseState);
if (localStateFlags != nullptr) {
state += *localStateFlags;
}
if (isActive) {
state += "active_";
} else {
state += "inactive_";
}
return state;
}
ListEntry2D::~ListEntry2D() {
if (userDataMap != nullptr) {
delete userDataMap;
userDataMap = nullptr;
}
}
|
b1062fbb71e86e7cc45f842bccfce0b94b79cde9 | 998c67cc02748f338a801a1d76147512210a9cdf | /src/nmea_parser.h | 620d164652fd0a30c257ca3760576787134f2650 | [] | no_license | Azrrael-exe/nmea-string | 0cfe999a95910ea60beea2a7cd11c2dfbda21b43 | b0d9bfa26d35ae72bc6d1b767832b184c3c34363 | refs/heads/master | 2020-03-22T00:45:16.842481 | 2018-07-16T15:50:14 | 2018-07-16T15:50:14 | 139,263,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,567 | h | nmea_parser.h | #ifndef nmea_parser_h
#define nmea_parser_h
#include <Arduino.h>
class NMEA {
public:
NMEA();
void parse(char c);
bool isReady();
uint8_t fields();
String getStrin();
String getField(uint8_t i);
void setField(uint8_t i, String val);
String getString();
String getRaw();
String getPayload(uint8_t i);
private:
void clear();
bool ready;
uint8_t count;
uint8_t divs;
bool end;
String temp_payload[20];
String payload[20];
String raw;
};
NMEA::NMEA(){
ready = false;
};
bool NMEA::isReady(){
return ready;
}
void NMEA::clear(){
for(int i=0; i<20; i++){
temp_payload[i] = "";
payload[i] = "";
}
}
void NMEA::parse(char c){
if(c == '$'){
divs = 0;
end = false;
raw = "";
clear();
}
else if(c == ','){
temp_payload[divs] += c;
raw += c;
divs ++;
}
else if(c == '*'){
end = true;
for(int i=0; i<divs; i++){
payload[i] = temp_payload[i];
}
ready = true;
}
else {
temp_payload[divs] += c;
raw += c;
}
}
String NMEA::getString(){
ready = false;
String output = "";
for(int i = 0; i<divs; i++){
output += payload[i];
}
uint8_t parity = 0;
for(int i = 0; i<output.length(); i++){
parity ^= output[i];
}
char cadena[5];
sprintf(cadena, "*%X\n\r", parity);
output += cadena;
return "$" + output;
}
String NMEA::getRaw(){
return raw;
}
String NMEA::getField(uint8_t i){
return payload[i];
}
void NMEA::setField(uint8_t i, String val){
payload[i] = val + ",";
}
uint8_t NMEA::fields(){
return divs;
}
#endif
|
12c4222546fec0e72dee37c985aa1177a9de3adf | 5a19f0763cccd59abe5617d842301e4e7fe25a13 | /source/housys/src/hou/sys/window_mode.cpp | 711e4f6d80aff79ec228e3b86f3fbe047eab6293 | [
"MIT"
] | permissive | DavideCorradiDev/houzi-game-engine | 6bfec0a8580ff4e33defaa30b1e5b490a4224fba | d704aa9c5b024300578aafe410b7299c4af4fcec | refs/heads/master | 2020-03-09T01:34:13.718230 | 2019-02-02T09:53:24 | 2019-02-02T09:53:24 | 128,518,126 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 643 | cpp | window_mode.cpp | // Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/sys/window_mode.hpp"
#include "hou/cor/core_functions.hpp"
#define WINDOW_MODE_CASE(ws, os) \
case window_mode::ws: \
return (os) << #ws
namespace hou
{
std::ostream& operator<<(std::ostream& os, window_mode wm)
{
switch(wm)
{
WINDOW_MODE_CASE(windowed, os);
WINDOW_MODE_CASE(fullscreen, os);
WINDOW_MODE_CASE(desktop_fullscreen, os);
}
return STREAM_VALUE(os, window_mode, wm);
}
} // namespace hou
|
c02c27952c78b7553ae82adc339cdcd9a39e31ae | 7e900cdc2d13b4555b6145023e5622052727c6de | /include/fps.hpp | 1bfed063f8b3d4278fab47c68ac9874b22052899 | [] | no_license | TartanLlama/choco-cheddar-charlie | 5b8f60423fe7b1f533b606edf2c171330dea2fee | 2993cb54cc3413cd0114d4a14dd665ec668fd4cd | refs/heads/master | 2021-05-08T18:14:08.727420 | 2018-02-04T09:31:03 | 2018-02-04T09:31:03 | 119,508,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | hpp | fps.hpp | #ifndef CHOCO_FPS_HPP
#define CHOCO_FPS_HPP
#include "timer.hpp"
namespace choco {
class fps_capper {
public:
fps_capper() {
fps_timer.start();
}
~fps_capper() {
fps_timer.stop();
}
void start_frame() {
cap_timer.start();
}
void end_frame() {
auto frame_ticks = cap_timer.get_ticks();
if(frame_ticks < s_ticks_per_frame) {
SDL_Delay(s_ticks_per_frame - frame_ticks);
}
n_frames++;
last_time_ = cap_timer.get_ticks();
cap_timer.pause();
}
double delta() {
return last_time_? 1.0/last_time_ : 0;
}
private:
static constexpr int s_frame_rate = 60;
static constexpr int s_ticks_per_frame = 1000 / s_frame_rate;
tl::u32 n_frames;
timer fps_timer;
timer cap_timer;
tl::u64 last_time_;
};
}
#endif
|
ae359f31718ce23f0be2c53e753388385cff4f60 | ee110713d2a41ba2958db6a50e2f6fcbedea6ff3 | /34-N皇后问题 II.cpp | 9e9872ce3fcdc8eecff233f3b57a186a42021de5 | [] | no_license | libaoquan95/LintCode | fe3e355bf0cecd828d045d45614dbafa8eb5ff2d | 403a5e1520706cb529e257a74f071658766a0aa7 | refs/heads/master | 2021-01-20T08:06:38.150185 | 2017-08-28T04:18:46 | 2017-08-28T04:18:46 | 90,096,556 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,071 | cpp | 34-N皇后问题 II.cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
/**
* http://www.lintcode.com/zh-cn/problem/n-queens-ii/-34-N»ÊºóÎÊÌâ II
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
if(n == 1) {
return 1;
}
else if(n < 4) {
return 0;
}
int result = 0;
int i=0, row=0, col=0, j=0, k=0;
int *pCheckerboard = new int[n];
for(i=0; i<n; i++) {
pCheckerboard[i] = -1;
}
while(row < n) {
while(col < n) {
if(canPlace(row, col, n, pCheckerboard)) {
pCheckerboard[row] = col;
col = 0;
break;
}
else {
col++;
}
}
if(pCheckerboard[row] == -1) {
if(row == 0) {
break;
}
else {
row--;
col = pCheckerboard[row] + 1;
pCheckerboard[row] = -1;
continue;
}
}
if(row == n-1) {
result++;
col = pCheckerboard[row] + 1;
pCheckerboard[row] = -1;
continue;
}
row++;
}
delete[] pCheckerboard;
return result;
}
int canPlace(int row, int col, int n, int *pCheckerboard) {
int i;
for(i=0; i<n && i!=row; i++) {
if(pCheckerboard[i] == col) {
return 0;
}
if(abs(row-i) == abs(col-pCheckerboard[i])) {
return 0;
}
}
return 1;
}
};
int main()
{
Solution s;
int result = s.totalNQueens(4);
cout<<result<<endl;
return 0;
} |
15549fc3d7533867150765279e9b63a11ee616f3 | 1d3ccb79ec8c3b6cab8aa6adaec3b6fe1c67d2f7 | /others/criticalPath.cpp | 6979ec167db9290cb8154fea490973f1b1f3ef69 | [] | no_license | pppyj/oj | 5a1eb25747155e5cb2112772eb67c49082a1e156 | 602d88d968500afd1a0cc5c06091cdf0901978cb | refs/heads/master | 2020-05-16T09:01:51.231814 | 2019-04-02T03:18:57 | 2019-04-02T03:18:57 | 182,933,627 | 1 | 0 | null | 2019-04-23T04:37:13 | 2019-04-23T04:37:13 | null | UTF-8 | C++ | false | false | 2,024 | cpp | criticalPath.cpp | #include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXV = 101;
struct Edge {
int node, weight;
};
vector<Edge> G[MAXV];
int nodeNum, edgeNum, inDegree[MAXV], ve[MAXV], vl[MAXV];
stack<int> topOrder;
bool topologicalSort() {
queue<int> q;
for(int i = 0; i < nodeNum; i++) {
if(inDegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int u = q.front();
printf("%d", u);
q.pop();
topOrder.push(u);
for(int i = 0; i < G[u].size(); i++) {
int v = G[u][i].node;
inDegree[v]--;
if(inDegree[v] == 0){
q.push(v);
}
if(ve[u] + G[u][i].weight > ve[v]) {
ve[v] = ve[u] + G[u][i].weight;
}
}
}
printf("\n");
return topOrder.size() == nodeNum;
}
int criticalPath() {
fill(ve, ve + MAXV, 0);
if(!topologicalSort()){
return -1;
}
fill(vl, vl + MAXV, ve[nodeNum-1]);
while(!topOrder.empty()) {
int u = topOrder.top();
topOrder.pop();
for(int i = 0; i < G[u].size(); i++) {
int v = G[u][i].node;
if(vl[v] - G[u][i].weight < vl[u]) {
vl[u] = vl[v] - G[u][i].weight;
}
}
}
for(int u = 0; u < nodeNum; u++) {
for(int i = 0; i < G[u].size(); i++) {
int v = G[u][i].node, w = G[u][i].weight;
int e = ve[u], l = vl[v] - w;
if(e == l) {
printf("%d->%d\n", u , v);
}
}
}
return ve[nodeNum-1];
}
int main() {
int u, v, w;
fill(inDegree, inDegree + MAXV, 0);
scanf("%d%d", &nodeNum, &edgeNum);
for(int i = 0; i < edgeNum; i++) {
scanf("%d%d%d", &u, &v, &w);
Edge edge = {
.node = v,
.weight = w
};
G[u].push_back(edge);
inDegree[v]++;
}
criticalPath();
return 0;
} |
b1f138659865f280b233e0bb0003c360348d0331 | 629d68576825cddacc281bbb91208ca38faa3120 | /src/monitors/drone_monitor.cpp | 841dc6729124870bbc5d6ff588e74eaf1fd83b38 | [] | no_license | ronakbhag/drone_navigation | 10b69f763763a92fa728ddbedab0e803792d08bf | 3fd225a68be0b4da56cacdbc42b9541ee20c8f22 | refs/heads/main | 2023-02-01T01:39:41.110938 | 2020-12-19T17:19:45 | 2020-12-19T17:19:45 | 322,719,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,082 | cpp | drone_monitor.cpp | /********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2018, Airlitix
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Airlitix nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Carlos Diaz Alvarenga & Andrew Dobson */
/* Node to control the drone with velocity commands (output from the navigation stack) at a given height*/
#include <tf2_ros/static_transform_broadcaster.h>
#include "drone.h"
#include "ros_util.h"
#include <mutex>
//Some Global Checking information
ros::Time last_odom_time(0);
double odom_dropout_threshold;
std::mutex odom_time_mx;
bool map_transform_set;
bool odom_live;
bool simulation;
bool using_mapping;
nav_msgs::Odometry odom_message;
//Depending on the firmware, we need to check for different modes
std::string cc_control_mode;
/**
* Callback for reading the odom time
*/
void odom_check(const nav_msgs::Odometry::ConstPtr& msg)
{
std::lock_guard<std::mutex> lock(odom_time_mx);
last_odom_time = msg->header.stamp;
odom_message = *msg;
// ROS_WARN("WE HAVE ODOM, ODOM IS HERE!!!!!!!!!");
}
/**
* Drone monitor node used to monitor the status of the drone.
* Also ued to arm and set the mode of the drone.
*/
int main(int argc, char**argv)
{
ros::init(argc, argv, "drone_monitor");
ros::NodeHandle nh;
ROS_WARN("[drone_monitor] STARTING...");
//Some members we'll use to track things
drone_interface::Drone drone;
odom_live = false;
map_transform_set = false;
odom_dropout_threshold = GetParam<double>( nh, ros::this_node::getName() + "/odom_dropout_threshold", 0.1 );
double update_gap = 99.0;
simulation = GetParam<bool>( nh, "/use_sim_time" );
using_mapping = GetParam<bool>( nh, "/use_mapping", false );
static tf2_ros::StaticTransformBroadcaster static_broadcaster;
//Alright, we need to read what firmware we're running for
std::string fw = GetParam<std::string>( nh, ros::this_node::getName() + "/firmware", "-" );
if( fw == "px4" )
{
cc_control_mode = "OFFBOARD";
}
else if( fw == "apm" )
{
cc_control_mode = "GUIDED";
}
else
{
ROS_FATAL_STREAM("Unknown Firmware type [" << fw << "] : Aborting...");
exit(4);
}
ROS_WARN_STREAM("Proceeding with firmware [" << fw << "]");
//If we are using a mapping solution, then we will assume our map transformation is set
if( using_mapping )
{
map_transform_set = true;
}
//We need to set up subscribers which check if things are healthy
ros::Subscriber odom_sub = nh.subscribe<nav_msgs::Odometry>("/mavros/local_position/odom", 20, odom_check);
// First: Wait for FCU connection
ros::Rate rate(2.0);
while( ros::ok() && !drone.getCurrentState().connected )
{
ros::spinOnce();
ROS_WARN("Waiting for FCU connection...");
drone.reportCurrentState();
rate.sleep();
}
ROS_INFO("Flight Controller Connected!");
while( ros::ok() )
{
//For the sake of consistency, we have to wait until we have a position
// estimation from the drone before attempting to arm (need to set map transform)
while( ros::ok() && !odom_live )
{
//do the check for odom liveness
ros::spinOnce();
{ //Only lock the mutex for when we are doing the check
std::lock_guard<std::mutex> lock(odom_time_mx);
update_gap = (ros::Time::now() - last_odom_time).toSec();
odom_live = update_gap < odom_dropout_threshold;
}
ROS_WARN("Waiting for odometry information...");
//Now, if we've gotten odometry information, but haven't set up our
// map transformation
if( odom_live && !map_transform_set )
{
//Get the orientation information
double x = odom_message.pose.pose.orientation.x;
double y = odom_message.pose.pose.orientation.y;
double z = odom_message.pose.pose.orientation.z;
double w = odom_message.pose.pose.orientation.w;
//Then I need to extract the transform from this...
tf::Quaternion q(x,y,z,w);
tf::Vector3 axis = q.getAxis();
double angle = q.getAngle();
//I can do some error checking to see if the axis is off... but then what?
//Assuming the axis isn't too far off, I should be able to build the transform.
tf::Quaternion map_q( tf::Vector3(0,0,1), angle );
// tf::Transform map_odom_static( map_q, tf::Vector3(0,0,0) );
geometry_msgs::TransformStamped static_transformStamped;
static_transformStamped.header.stamp = ros::Time::now();
static_transformStamped.header.frame_id = "map";
static_transformStamped.child_frame_id = "odom";
static_transformStamped.transform.translation.x = 0;
static_transformStamped.transform.translation.y = 0;
static_transformStamped.transform.translation.z = 0;
static_transformStamped.transform.rotation.x = map_q.x();
static_transformStamped.transform.rotation.y = map_q.y();
static_transformStamped.transform.rotation.z = map_q.z();
static_transformStamped.transform.rotation.w = map_q.w();
static_broadcaster.sendTransform(static_transformStamped);
map_transform_set = true;
}
rate.sleep();
}
//Arm drone if in simulation, otherwise just wait
while (ros::ok() && !drone.getCurrentState().armed)
{
ROS_WARN("Waiting for drone to arm...");
if( simulation )
{
ROS_INFO("Sending arm command");
drone.arm();
}
ros::spinOnce();
rate.sleep();
}
ROS_INFO("Drone Armed!");
// Set Mode to our companion computer control mode
while( ros::ok() && drone.getCurrentState().mode != cc_control_mode )
{
if( simulation )
{
drone.setMode(cc_control_mode);
}
ros::spinOnce();
ROS_WARN_STREAM("Waiting for control override: current control mode: [" << drone.getCurrentState().mode << "]");
rate.sleep();
}
ROS_INFO_STREAM("Drone mode set to " << cc_control_mode << "!");
//Then, sit and idle, checking if the status is okay
ros::Rate idlerate(30.0);
update_gap = 0.0;
while( ros::ok() && drone.getCurrentState().mode == cc_control_mode && drone.getCurrentState().armed && odom_live )
{
ros::spinOnce();
{ //Only lock the mutex for when we are doing the check
std::lock_guard<std::mutex> lock(odom_time_mx);
update_gap = (ros::Time::now() - last_odom_time).toSec();
odom_live = update_gap < odom_dropout_threshold;
}
idlerate.sleep();
}
//If odometry information has been lost, we are in srs trouble
if( !odom_live )
{
ROS_WARN_STREAM("Odometry information has been lost! :: Gap [" << update_gap << "]");
}
}
//TODO: If the status here goes awol, what should our behavior be?
return 0;
}
|
db81ab25efe96170eed8f01873689f1737c1d2e2 | 3364697d5507fc120c38b491c88b7d454d039b20 | /FileSharing/serverfilethread.h | a975b4265dc58ca6935a7e38ab717b770bf84c5e | [] | no_license | andrei-datcu/-homework-IP-File-Sharing-QT | acd98bd120bdfc31c04b57d2c87d1040201e2e59 | 9216c41d2a5f44595234ec1b14a595acef6a8a51 | refs/heads/master | 2021-03-12T22:57:10.292830 | 2014-05-16T21:43:05 | 2014-05-16T21:43:05 | 30,667,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | h | serverfilethread.h | #ifndef SERVERFILETHREAD_H
#define SERVERFILETHREAD_H
#include "ShareFileSystem.h"
#include <QObject>
#include <QThread>
#include <QTcpSocket>
class ServerFileThread : public QThread
{
Q_OBJECT
public:
ServerFileThread(QObject *parent, int socketDescriptor, ShareFileSystem &share);
~ServerFileThread();
void run();
public slots:
void bytesWritten(qint64 bytes);
private:
int socketDescriptor;
ShareFileSystem &share;
};
#endif // SERVERFILETHREAD_H
|
d7370c9fc36b10f6fd4e9306ad8b3ecc302e84fe | 1e2c4f28970f7fc97909b21242a2b0492ae374ea | /Przychodnia/mainwindow.cpp | f31d40c01822c5f68e52dd069e4fda96eda24edf | [] | no_license | maciekgrzela/aplikacja-przychodnia-inzynieria-oprogramowania-2019 | 48f8945ad3ac52df00bb7def6da2e7649a0e2fb9 | 92cb815fb8d67f3f6039ef3979fb7408608bbb1a | refs/heads/main | 2023-08-17T14:19:35.861888 | 2021-09-27T16:14:24 | 2021-09-27T16:14:24 | 402,008,917 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,362 | cpp | mainwindow.cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent, bool czyManager, Osoba *zalogowany)
: QMainWindow(parent)
, ui(new Ui::MainWindow) {
ui->setupUi(this);
przychodnia = Przychodnia::getInstancja();
this->zalogowanoJakoManager = czyManager;
this->zalogowany = zalogowany;
this->setWindowTitle("Aplikacja Przychodnia v1.0.0 @ Zalogowano: "+zalogowany->getImie()+" "+zalogowany->getNazwisko());
this->przygotujInterfejsGraficzny();
this->wyswietlListePacjentow(przychodnia->zwrocPacjentow(), ui->pacjenciWizytaTableView);
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyWizytaTableView);
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegi(), ui->zabiegiWizytaTableView);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::przydzielUprawnieniaDlaPracownika() {
if(!zalogowanoJakoManager){
ui->zabiegiBtn->setEnabled(false);
ui->pracownicyBtn->setEnabled(false);
ui->kompetencjeBtn->setEnabled(false);
}
}
void MainWindow::wyswietlListePacjentow(QList<Pacjent *> listaPacjentow, QTableView *viewPacjent) {
QStandardItemModel *pacjentModel = new QStandardItemModel(viewPacjent);
pacjentModel->setColumnCount(8);
pacjentModel->setHorizontalHeaderLabels({"Imię", "Nazwisko", "E-mail", "Telefon", "Ulica", "Numer", "Kod", "Miejscowość"});
viewPacjent->setModel(pacjentModel);
przychodnia->wypelnijModelPacjentow(listaPacjentow, pacjentModel);
}
void MainWindow::wyswietlListePracownikow(QList<Pracownik *> listaPracownikow, QTableView *viewPracownik) {
QStandardItemModel *pracownikModel = new QStandardItemModel(viewPracownik);
pracownikModel->setColumnCount(3);
pracownikModel->setHorizontalHeaderLabels({"Imię", "Nazwisko", "Kod logowania"});
viewPracownik->setModel(pracownikModel);
przychodnia->wypelnijModelPracownikow(listaPracownikow, pracownikModel);
}
void MainWindow::wyswietlListeZabiegow(QList<Zabieg *> listaZabiegow, QTableView *viewZabieg) {
QStandardItemModel *zabiegModel = new QStandardItemModel(viewZabieg);
zabiegModel->setColumnCount(4);
zabiegModel->setHorizontalHeaderLabels({"Nazwa", "Cena", "Czas trwania", "Opis"});
viewZabieg->setModel(zabiegModel);
przychodnia->wypelnijModelZabiegow(listaZabiegow, zabiegModel);
}
void MainWindow::przygotujTabele()
{
QList<QTableView*> tableViews = findChildren<QTableView*>();
foreach(QTableView* view, tableViews) {
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
view->setSelectionBehavior(QAbstractItemView::SelectRows);
view->setSelectionMode(QAbstractItemView::SingleSelection);
view->horizontalHeader()->setStretchLastSection(true);
view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
view->verticalHeader()->hide();
}
}
void MainWindow::przygotujInterfejsGraficzny() {
przydzielUprawnieniaDlaPracownika();
przygotujTabele();
ui->menuTab->tabBar()->hide();
ui->userNameLabel->setText(zalogowany->getImie()+" "+zalogowany->getNazwisko());
QList<QLineEdit*> lineEdits = ui->godzinyPracownikaGroupBox->findChildren<QLineEdit*>();
foreach(QLineEdit *line, lineEdits){
line->setInputMask("99:99");
}
}
void MainWindow::wypelnijPolaGodzinPracy(QString odGodzina, QString doGodzina) {
QList<QLineEdit*> lineEdits = ui->godzinyPracownikaGroupBox->findChildren<QLineEdit*>();
int i = 0;
foreach(QLineEdit *line, lineEdits){
if(i%2 == 0){
line->setText(odGodzina);
}else {
line->setText(doGodzina);
}
i++;
}
}
QString MainWindow::godzinaDoPolaTekstowego(QString godzina) {
qDebug() << "Godz: -------------------------------- " << godzina;
QString godz = godzina.mid(0, godzina.indexOf(":"));
qDebug() << "Godzina: "<< godz;
QString min = godzina.mid(godzina.indexOf(":")+1, godzina.length() - godzina.lastIndexOf(":"));
qDebug() << "Minuta" << min;
QString sek = godzina.mid(godzina.lastIndexOf(":")+1);
qDebug() << "Sekunda" << sek;
int godzInt = godz.toInt();
int minInt = min.toInt();
int sekInt = sek.toInt();
if(godzInt < 10){
godz = "0"+godz;
}
if(minInt < 10){
min = "0"+min;
}
if(sekInt < 10){
sek = "0"+sek;
}
return godz+""+min;
}
QString MainWindow::usunDodatkoweInfo(QString tekst) {
tekst.replace(" PLN", "").replace("h", "");
return tekst;
}
void MainWindow::uaktywnijPrzyciskiGodziny() {
QList<QToolButton*> btns = ui->godzinyGroupBox->findChildren<QToolButton*>();
foreach(QToolButton *btn, btns){
btn->setEnabled(true);
}
}
void MainWindow::uaktywnijPrzycisk(QToolButton *btn) {
if(btn->styleSheet().contains("background-color: rgb(0,51,102)")){
btn->setStyleSheet(btn->styleSheet().replace("rgb(0,51,102)", "rgb(192,19,0)"));
ui->godzinaWizytyLineEdit->setText(btn->text().mid(0, btn->text().indexOf("-") - 1));
daneGodziny.append(btn->text().mid(0, btn->text().indexOf(":")).toInt());
daneGodziny.append(btn->text().mid(btn->text().indexOf(":")+1, btn->text().indexOf("-")-4).toInt());
daneGodziny.append(0);
}else {
btn->setStyleSheet(btn->styleSheet().replace("rgb(192,19,0)", "rgb(0,51,102)"));
ui->godzinaWizytyLineEdit->setText("");
daneGodziny.clear();
}
if(daneTerminu.length() > 0 && daneZabiegu.length() > 0 && danePacjenta.length() > 0 && danePracownika.length() > 0 && ui->godzinaWizytyLineEdit->text().length() > 0){
ui->umowWizyteBtn->setEnabled(true);
}else {
ui->umowWizyteBtn->setEnabled(false);
}
}
void MainWindow::on_wizytyBtn_clicked()
{
ui->menuTab->setCurrentIndex(0);
}
void MainWindow::on_pacjenciBtn_clicked()
{
this->wyswietlListePacjentow(przychodnia->zwrocPacjentow(), ui->pacjenciTableView);
ui->menuTab->setCurrentIndex(1);
}
void MainWindow::on_kompetencjeBtn_clicked()
{
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyKompetencjeTableView);
ui->menuTab->setCurrentIndex(2);
}
void MainWindow::on_zabiegiBtn_clicked()
{
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegi(), ui->zabiegiTableView);
ui->menuTab->setCurrentIndex(3);
}
void MainWindow::on_pracownicyBtn_clicked()
{
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyTableView);
ui->menuTab->setCurrentIndex(4);
}
void MainWindow::on_ustawieniaBtn_clicked()
{
ui->menuTab->setCurrentIndex(5);
}
void MainWindow::on_wylogujBtn_clicked() {
QCoreApplication::quit();
}
void MainWindow::on_szukajPacjenciWizytaBtn_clicked() {
if(ui->szukajPacjenciWizytaLineEdit->text().length() > 0){
QList<Pacjent*> pacjenciKryteria = przychodnia->zwrocPacjentow(ui->szukajPacjenciWizytaLineEdit->text());
this->wyswietlListePacjentow(pacjenciKryteria, ui->pacjenciWizytaTableView);
}else {
this->wyswietlListePacjentow(przychodnia->zwrocPacjentow(), ui->pacjenciWizytaTableView);
}
}
void MainWindow::on_szukajZabiegiWizytaBtn_clicked() {
if(ui->szukajZabiegiWizytaLineEdit->text().length() > 0){
QList<Zabieg*> zabiegiKryteria = przychodnia->zwrocZabiegi(ui->szukajZabiegiWizytaLineEdit->text());
this->wyswietlListeZabiegow(zabiegiKryteria, ui->zabiegiWizytaTableView);
}else {
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegi(), ui->zabiegiWizytaTableView);
}
}
void MainWindow::on_szukajPracownicyWizytaBtn_clicked() {
if(ui->szukajPracownicyWizytaLineEdit->text().length() > 0){
QList<Pracownik*> pracownicyKryteria = przychodnia->zwrocPracownikow(ui->szukajPracownicyWizytaLineEdit->text());
this->wyswietlListePracownikow(pracownicyKryteria, ui->pracownicyWizytaTableView);
}else {
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyWizytaTableView);
}
}
void MainWindow::on_szukajPacjentaBtn_clicked() {
if(ui->szukajPacjentaLineEdit->text().length() > 0){
QList<Pacjent*> pacjenciKryteria = przychodnia->zwrocPacjentow(ui->szukajPacjentaLineEdit->text());
this->wyswietlListePacjentow(pacjenciKryteria, ui->pacjenciTableView);
}else {
this->wyswietlListePacjentow(przychodnia->zwrocPacjentow(), ui->pacjenciTableView);
}
}
void MainWindow::on_szukajPracownikaKompetencjeBtn_clicked() {
if(ui->szukajPracownikaKompetencjeLineEdit->text().length() > 0){
QList<Pracownik*> pracownicyKryteria = przychodnia->zwrocPracownikow(ui->szukajPracownikaKompetencjeLineEdit->text());
this->wyswietlListePracownikow(pracownicyKryteria, ui->pracownicyKompetencjeTableView);
}else {
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyKompetencjeTableView);
}
}
void MainWindow::on_szukajZabieguBtn_clicked() {
if(ui->szukajZabieguLineEdit->text().length() > 0){
QList<Zabieg*> zabiegiKryteria = przychodnia->zwrocZabiegi(ui->szukajZabieguLineEdit->text());
this->wyswietlListeZabiegow(zabiegiKryteria, ui->zabiegiTableView);
}else {
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegi(), ui->zabiegiTableView);
}
}
void MainWindow::on_szukajPracownikaBtn_clicked() {
if(ui->szukajPracownikaLineEdit->text().length() > 0){
QList<Pracownik*> pracownicyKryteria = przychodnia->zwrocPracownikow(ui->szukajPracownikaLineEdit->text());
this->wyswietlListePracownikow(pracownicyKryteria, ui->pracownicyTableView);
}else {
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyTableView);
}
}
void MainWindow::on_dodajPracownikaPracownicyBtn_clicked() {
przychodnia->dodajPracownika(ui->pracownikImieLineEdit->text(), ui->pracownikNazwiskoLineEdit->text(), ui->pracownikKodLogowaniaLineEdit->text());
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyTableView);
}
void MainWindow::on_pracownicyTableView_clicked(const QModelIndex &index) {
QList<QString> danePracownika;
for(auto i = 0; i < index.model()->columnCount(); i++){
danePracownika.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
QList<QLineEdit*> lineEdits = ui->danePracownikaGroupBox->findChildren<QLineEdit*>();
int i = 0;
foreach(QLineEdit* line, lineEdits) {
line->setText(danePracownika.at(i));
i++;
}
i = 0;
modyfikowanyPracownik = przychodnia->szukajPracownika(danePracownika.at(0), danePracownika.at(1), danePracownika.at(2));
QList<GodzinyPracy*> godzPracyModyfikowanego = modyfikowanyPracownik->getGodzinyPracy();
if(godzPracyModyfikowanego.length() > 0){
lineEdits = ui->godzinyPracownikaGroupBox->findChildren<QLineEdit*>();
foreach(GodzinyPracy *godz, godzPracyModyfikowanego){
lineEdits.at(i)->setText(godzinaDoPolaTekstowego(godz->getGodzinaOd()->toString()));
lineEdits.at(i+1)->setText(godzinaDoPolaTekstowego(godz->getGodzinaDo()->toString()));
i+=2;
}
}
}
void MainWindow::on_modyfikujPracownikaPracownicyBtn_clicked() {
if(modyfikowanyPracownik != nullptr){
przychodnia->modyfikujPracownika(modyfikowanyPracownik, ui->pracownikImieLineEdit->text(), ui->pracownikNazwiskoLineEdit->text(), ui->pracownikKodLogowaniaLineEdit->text());
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyTableView);
}
}
void MainWindow::on_pracownikWyczyscBtn_clicked() {
QList<QLineEdit*> lineEdits = ui->danePracownikaGroupBox->findChildren<QLineEdit*>();
foreach(QLineEdit* line, lineEdits) {
line->setText("");
}
modyfikowanyPracownik = nullptr;
ui->pracownicyTableView->clearSelection();
}
void MainWindow::on_usunPracownikaBtn_clicked() {
if(modyfikowanyPracownik != nullptr){
przychodnia->usunPracownika(modyfikowanyPracownik);
this->wyswietlListePracownikow(przychodnia->zwrocPracownikow(), ui->pracownicyTableView);
on_pracownikWyczyscBtn_clicked();
}
}
void MainWindow::on_ustawSchemat715_clicked() {
wypelnijPolaGodzinPracy("07:00", "15:00");
}
void MainWindow::on_ustawSchemat816_clicked()
{
wypelnijPolaGodzinPracy("08:00", "16:00");
}
void MainWindow::on_ustawSchemat917_clicked()
{
wypelnijPolaGodzinPracy("09:00", "17:00");
}
void MainWindow::on_ustawSchemat1018_clicked()
{
wypelnijPolaGodzinPracy("10:00", "18:00");
}
void MainWindow::on_ustawSchemat1119_clicked()
{
wypelnijPolaGodzinPracy("11:00", "19:00");
}
void MainWindow::on_godzinyPracyWyczyscBtn_clicked() {
wypelnijPolaGodzinPracy("", "");
on_pracownikWyczyscBtn_clicked();
}
void MainWindow::on_godzinyPracyZatwierdzBtn_clicked() {
QList<QString> dniTygodnia;
dniTygodnia << "Poniedziałek" << "Wtorek" << "Środa" << "Czwartek" << "Piątek";
if(modyfikowanyPracownik != nullptr){
QList<QLineEdit*> lineEdits = ui->godzinyPracownikaGroupBox->findChildren<QLineEdit*>();
int i = 0;
foreach(QString dzien, dniTygodnia){
przychodnia->zmienGodzinyPracyPracownika(modyfikowanyPracownik, dzien, lineEdits.at(i)->text(), lineEdits.at(i+1)->text());
i+=2;
}
}
}
void MainWindow::on_zabiegiTableView_clicked(const QModelIndex &index) {
QList<QString> daneZabiegu;
for(auto i = 0; i < index.model()->columnCount(); i++){
daneZabiegu.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
QList<QLineEdit*> lineEdits = ui->daneZabieguGroupBox->findChildren<QLineEdit*>();
int i = 0;
foreach(QLineEdit* line, lineEdits) {
line->setText(usunDodatkoweInfo(daneZabiegu.at(i)));
i++;
}
ui->opisZabiegiLineEdit->setText(daneZabiegu.last());
modyfikowanyZabieg = przychodnia->szukajZabiegu(daneZabiegu.at(0),usunDodatkoweInfo(daneZabiegu.at(1)).toDouble(),usunDodatkoweInfo(daneZabiegu.at(2)).toDouble(),daneZabiegu.at(3));
}
void MainWindow::on_zabiegiWyczyscBtn_clicked() {
QList<QLineEdit*> lineEdits = ui->daneZabieguGroupBox->findChildren<QLineEdit*>();
foreach(QLineEdit* line, lineEdits) {
line->setText("");
}
ui->opisZabiegiLineEdit->setText("");
modyfikowanyZabieg = nullptr;
ui->zabiegiTableView->clearSelection();
}
void MainWindow::on_zabiegiUsunBtn_clicked() {
if(modyfikowanyZabieg != nullptr){
przychodnia->usunZabieg(modyfikowanyZabieg);
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegi(), ui->zabiegiTableView);
on_zabiegiWyczyscBtn_clicked();
}
}
void MainWindow::on_zabiegiDodajBtn_clicked() {
przychodnia->dodajZabieg(ui->nazwaZabiegiLineEdit->text(), usunDodatkoweInfo(ui->cenaZabiegiLineEdit->text()).toDouble(), usunDodatkoweInfo(ui->czasZabiegiLineEdit->text()).toDouble(), ui->opisZabiegiLineEdit->toPlainText());
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegi(), ui->zabiegiTableView);
}
void MainWindow::on_zabiegiModyfikujBtn_clicked() {
if(modyfikowanyZabieg != nullptr){
przychodnia->modyfikujZabieg(modyfikowanyZabieg, ui->nazwaZabiegiLineEdit->text(), usunDodatkoweInfo(ui->cenaZabiegiLineEdit->text()).toDouble(), usunDodatkoweInfo(ui->czasZabiegiLineEdit->text()).toDouble(), ui->opisZabiegiLineEdit->toPlainText());
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegi(), ui->zabiegiTableView);
}
}
void MainWindow::on_pacjenciWyczyscBtn_clicked() {
QList<QLineEdit*> lineEdits = ui->danePacjentaGroupBox->findChildren<QLineEdit*>();
foreach(QLineEdit* line, lineEdits) {
line->setText("");
}
modyfikowanyPacjent = nullptr;
ui->pacjenciTableView->clearSelection();
}
void MainWindow::on_pacjenciTableView_clicked(const QModelIndex &index) {
QList<QString> danePacjenta;
for(auto i = 0; i < index.model()->columnCount(); i++){
danePacjenta.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
QList<QLineEdit*> lineEdits = ui->danePacjentaGroupBox->findChildren<QLineEdit*>();
int i = 0;
foreach(QLineEdit* line, lineEdits) {
line->setText(danePacjenta.at(i));
i++;
}
modyfikowanyPacjent = przychodnia->szukajPacjenta(danePacjenta.at(0),danePacjenta.at(1),danePacjenta.at(2),danePacjenta.at(3),danePacjenta.at(4),danePacjenta.at(5).toInt(),danePacjenta.at(6).toInt(),danePacjenta.at(7));
}
void MainWindow::on_pacjenciUsunBtn_clicked() {
if(modyfikowanyPacjent != nullptr){
przychodnia->usunPacjenta(modyfikowanyPacjent);
this->wyswietlListePacjentow(przychodnia->zwrocPacjentow(), ui->pacjenciTableView);
on_pacjenciWyczyscBtn_clicked();
}
}
void MainWindow::on_modyfikujDanePacjentaBtn_clicked() {
if(modyfikowanyPacjent != nullptr){
przychodnia->modyfikujPacjenta(modyfikowanyPacjent, ui->imiePacjenciLineEdit->text(), ui->nazwiskoPacjenciLineEdit->text(), ui->emailPacjenciLineEdit->text(), ui->telefonPacjenciLineEdit->text(), ui->ulicaPacjenciLineEdit->text(), ui->numerPacjenciLineEdit->text().toInt(), ui->kodPacjenciLineEdit->text().toInt(), ui->miejscowoscPacjenciLineEdit->text());
this->wyswietlListePacjentow(przychodnia->zwrocPacjentow(), ui->pacjenciTableView);
}
}
void MainWindow::on_pacjenciDodajBtn_clicked() {
przychodnia->dodajPacjenta(ui->imiePacjenciLineEdit->text(), ui->nazwiskoPacjenciLineEdit->text(), ui->emailPacjenciLineEdit->text(), ui->telefonPacjenciLineEdit->text(), ui->ulicaPacjenciLineEdit->text(), ui->numerPacjenciLineEdit->text().toInt(), ui->kodPacjenciLineEdit->text().toInt(), ui->miejscowoscPacjenciLineEdit->text());
this->wyswietlListePacjentow(przychodnia->zwrocPacjentow(), ui->pacjenciTableView);
}
void MainWindow::on_pracownicyKompetencjeTableView_clicked(const QModelIndex &index) {
QList<QString> danePracownika;
for(auto i = 0; i < index.model()->columnCount(); i++){
danePracownika.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
QList<QLineEdit*> lineEdits = ui->danePracKompetencjeGroupBox->findChildren<QLineEdit*>();
int i = 0;
foreach(QLineEdit* line, lineEdits) {
line->setText(danePracownika.at(i));
i++;
}
modyfikowanyPracownik = przychodnia->szukajPracownika(danePracownika.at(0), danePracownika.at(1), danePracownika.at(2));
this->wyswietlListeZabiegow(modyfikowanyPracownik->kompetencjePracownika(), ui->przeglKompetencjiTableView);
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegiNiedozwoloneDla(modyfikowanyPracownik), ui->rozszKompetencjiTableView);
}
void MainWindow::on_przeglKompetencjiTableView_doubleClicked(const QModelIndex &index) {
QList<QString> daneZabiegu;
for(auto i = 0; i < index.model()->columnCount(); i++){
daneZabiegu.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
Zabieg *nowaKompetencja = przychodnia->szukajZabiegu(daneZabiegu.at(0),usunDodatkoweInfo(daneZabiegu.at(1)).toDouble(),usunDodatkoweInfo(daneZabiegu.at(2)).toDouble(),daneZabiegu.at(3));
if(modyfikowanyPracownik != nullptr && nowaKompetencja != nullptr){
modyfikowanyPracownik->usunKompetencje(nowaKompetencja);
}
this->wyswietlListeZabiegow(modyfikowanyPracownik->kompetencjePracownika(), ui->przeglKompetencjiTableView);
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegiNiedozwoloneDla(modyfikowanyPracownik), ui->rozszKompetencjiTableView);
}
void MainWindow::on_rozszKompetencjiTableView_doubleClicked(const QModelIndex &index) {
QList<QString> daneZabiegu;
for(auto i = 0; i < index.model()->columnCount(); i++){
daneZabiegu.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
Zabieg *nowaKompetencja = przychodnia->szukajZabiegu(daneZabiegu.at(0),usunDodatkoweInfo(daneZabiegu.at(1)).toDouble(),usunDodatkoweInfo(daneZabiegu.at(2)).toDouble(),daneZabiegu.at(3));
if(modyfikowanyPracownik != nullptr && nowaKompetencja != nullptr){
modyfikowanyPracownik->dodajKompetencje(nowaKompetencja);
}
this->wyswietlListeZabiegow(modyfikowanyPracownik->kompetencjePracownika(), ui->przeglKompetencjiTableView);
this->wyswietlListeZabiegow(przychodnia->zwrocZabiegiNiedozwoloneDla(modyfikowanyPracownik), ui->rozszKompetencjiTableView);
}
void MainWindow::on_pacjenciWizytaTableView_clicked(const QModelIndex &index) {
danePacjenta.clear();
for(auto i = 0; i < index.model()->columnCount(); i++){
danePacjenta.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
ui->danePacjentaLineEdit->setText(danePacjenta.at(0)+" "+danePacjenta.at(1));
if(daneTerminu.length() > 0 && daneZabiegu.length() > 0 && danePacjenta.length() > 0 && danePracownika.length() > 0 && ui->godzinaWizytyLineEdit->text().length() > 0){
ui->umowWizyteBtn->setEnabled(true);
}else {
ui->umowWizyteBtn->setEnabled(false);
}
}
void MainWindow::on_zabiegiWizytaTableView_clicked(const QModelIndex &index) {
daneZabiegu.clear();
for(auto i = 0; i < index.model()->columnCount(); i++){
if(i != 0 && i != 3){
daneZabiegu.append(usunDodatkoweInfo(index.model()->data(index.model()->index(index.row(), i)).toString()));
}else {
daneZabiegu.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
}
ui->daneZabieguLineEdit->setText(daneZabiegu.at(0)+" "+daneZabiegu.at(1));
if(daneTerminu.length() > 0 && daneZabiegu.length() > 0 && danePacjenta.length() > 0 && danePracownika.length() > 0 && ui->godzinaWizytyLineEdit->text().length() > 0){
ui->umowWizyteBtn->setEnabled(true);
}else {
ui->umowWizyteBtn->setEnabled(false);
}
}
void MainWindow::on_pracownicyWizytaTableView_clicked(const QModelIndex &index) {
danePracownika.clear();
for(auto i = 0; i < index.model()->columnCount(); i++){
danePracownika.append(index.model()->data(index.model()->index(index.row(), i)).toString());
}
ui->danePracownikaLineEdit->setText(danePracownika.at(0)+" "+danePracownika.at(1));
if(ui->daneTerminuLineEdit->text().length() > 0){
uaktywnijPrzyciskiGodziny();
}
if(daneTerminu.length() > 0 && daneZabiegu.length() > 0 && danePacjenta.length() > 0 && danePracownika.length() > 0 && ui->godzinaWizytyLineEdit->text().length() > 0){
ui->umowWizyteBtn->setEnabled(true);
}else {
ui->umowWizyteBtn->setEnabled(false);
}
}
void MainWindow::on_calendarWidget_clicked(const QDate &date) {
ui->daneTerminuLineEdit->setText(QString::number(date.day()) + "." + QString::number(date.month()) + "." + QString::number(date.year()));
daneTerminu.clear();
daneTerminu.append(date.day());
daneTerminu.append(date.month());
daneTerminu.append(date.year());
if(ui->danePracownikaLineEdit->text().length() > 0){
uaktywnijPrzyciskiGodziny();
}
if(daneTerminu.length() > 0 && daneZabiegu.length() > 0 && danePacjenta.length() > 0 && danePracownika.length() > 0 && ui->godzinaWizytyLineEdit->text().length() > 0){
ui->umowWizyteBtn->setEnabled(true);
}else {
ui->umowWizyteBtn->setEnabled(false);
}
}
void MainWindow::on_umowWizyteBtn_clicked() {
daneTerminu.append(daneGodziny);
if(przychodnia->umowWizyte(danePacjenta, daneZabiegu, danePracownika, daneTerminu)){
QMessageBox::information(nullptr, "Sukces", "Pomyślnie wprowadzono wizytę");
}
on_wyczyscWizyteBtn_clicked();
}
void MainWindow::on_toolButton_clicked() {
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_2_clicked() {
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_3_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_4_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_5_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_6_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_7_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_8_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_9_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_10_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_11_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_12_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_13_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_14_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_15_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_16_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_17_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_18_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_19_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_20_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_21_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_22_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_toolButton_23_clicked()
{
QToolButton *btn = (QToolButton*)sender();
uaktywnijPrzycisk(btn);
}
void MainWindow::on_wyczyscWizyteBtn_clicked() {
daneZabiegu.clear();
daneGodziny.clear();
daneTerminu.clear();
danePacjenta.clear();
danePracownika.clear();
ui->pacjenciWizytaTableView->clearSelection();
ui->pracownicyWizytaTableView->clearSelection();
ui->zabiegiWizytaTableView->clearSelection();
ui->calendarWidget->clearFocus();
ui->daneTerminuLineEdit->setText("");
ui->daneZabieguLineEdit->setText("");
ui->danePacjentaLineEdit->setText("");
ui->danePracownikaLineEdit->setText("");
ui->godzinaWizytyLineEdit->setText("");
QList<QToolButton*> tbtns = ui->godzinyGroupBox->findChildren<QToolButton*>();
foreach(QToolButton *tb, tbtns){
tb->setStyleSheet(tb->styleSheet().replace("rgb(192,19,0)", "rgb(0,51,102)"));
tb->setEnabled(false);
}
}
|
5bc79c6c96bd59264d904167319426afa2807742 | f2798d917b6798fc8e15fbb42bbcad265d0af121 | /src/animators/add.h | c150003c20dd20b4219d8bd3dfd7df46a18556d9 | [] | no_license | SinaC/OldRaytrace | 86c92fb1a3ba2e83434b8d524b839bc15e17d114 | 6a891d074735b3e5d45a8d26dba7d58503ba7ac0 | refs/heads/master | 2021-01-15T20:58:44.074128 | 2014-08-21T20:46:05 | 2014-08-21T20:46:05 | 23,202,321 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | h | add.h | #ifndef __MOVER_ADD_H__
#define __MOVER_ADD_H__
#include <vector>
using namespace std;
#include "mover.h"
struct MoverAddV : public MoverVector {
//---- Datas
// TVector3* source1;
// TVector3* source2;
vector<TVector3*> source;
//---- Constructor
MoverAddV();
//---- Methods
virtual TVector3 vmove( const float time);
//---- Input
// parse one field
virtual bool parse( Context &ctx, RAYField *field );
// qualified expression
virtual bool qualifiedExpression( Value &res, const char *fieldName ) const;
//---- Output
virtual void print( const char *msg ) const;
//**** Private
private:
//--tag
static const enum EMoverAddTags {
// TAG_moverAdd_source1,
// TAG_moverAdd_source2
TAG_moverAdd_source
};
static const TTagList moverAddTags [];
};
#endif
|
1fa57bfe18939517ecf5a7a92e15f1ac1d3d7b6e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_old_log_673.cpp | 4fe953588162c47df63432aa8485758f773295c4 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63 | cpp | git_old_log_673.cpp | print_ref_status('-', "[deleted]", ref, NULL, NULL, porcelain); |
2292c135291fac868742605f328c111110aec109 | 2a9390355be52ed3faf56d345846e564961980ea | /Sorts/Quicksort.cpp | 5e7490f53e0121a8b255c770ea6a91bd66c94910 | [] | no_license | Anshulguptag/Data-Structures | 44890900bc49f2a752a10528c6279d4aafc17bc5 | 3ca979418f30278a2227ac3eabbe6cf21ec6c3aa | refs/heads/master | 2020-03-22T01:56:48.315518 | 2018-08-10T06:06:04 | 2018-08-10T06:06:04 | 139,340,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | Quicksort.cpp | #include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int partition(int A[], int start, int end)
{
int pivot = A[end];
int pIndex = start;
for (int i=start;i<end;i++)
{
if(A[i]<=pivot)
{
swap(&A[i], &A[pIndex]);
pIndex = pIndex+1;
}
}
swap(&A[pIndex],&A[end]);
return pIndex;
}
void quicksort(int A[],int start, int end)
{
if(start<end)
{
int pIndex = partition(A,start, end);
quicksort(A,start,pIndex-1);
quicksort(A,pIndex+1,end);
}
}
void print(int A[], int size)
{
for(int i=0;i<size;i++)
{
cout<<A[i]<<" ";
}
}
int main()
{
int arr[] = {12,13,11,5,8,7,2};
int size = *(&arr+1)-arr;
cout<<"Unsorted array: ";
print(arr,size);
quicksort(arr,0,size-1);
cout<<"\nSorted array: ";
print(arr,size);
}
|
7c8e9c95370f627f4061f908f8d180b972658fc0 | 1ac4a89c27e6eb0ab5b6c7ae06c52cd3e526d90b | /vikr-source/include/vikr/graphics/gl4/gl4_rendertarget.hpp | a4a241196c55c2e2c16f8866b3c28ab1d6feddf0 | [
"MIT"
] | permissive | lm165678/Vikr | e54d3cc6130238eb59d78f2813d3cda1a6440ef5 | 9ac78f9f47a2222dfd40700fcc48e88d898c086b | refs/heads/master | 2023-03-22T14:49:38.921733 | 2017-02-27T06:45:43 | 2017-02-27T06:45:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | hpp | gl4_rendertarget.hpp | //
// Copyright (c) Mario Garcia, Under the MIT License.
//
#ifndef __VIKR_GL4_RENDERTARGET_HPP
#define __VIKR_GL4_RENDERTARGET_HPP
namespace vikr {
} // vikr
#endif // __VIKR_GL4_RENDERTARGET_HPP |
ce6d5203b2ab48db828e7d0b2fe0c21ff06f0f33 | 6d6903123f7f454f9bbca23ce60cc1b514f4ea0d | /newmenu.h | 0d2916cf6c411696d1b66b51c2fb7223087b02c0 | [] | no_license | Warp-ass/rts | 65d4c4f0e76eeb08b6d94cd77566bc4b0548e12b | 51a0d33d7229f4ecf83a363476a337cff67c72b3 | refs/heads/master | 2023-04-04T05:09:48.641277 | 2015-03-24T18:12:12 | 2015-03-24T18:12:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | h | newmenu.h | /////////////////////////////////////////////////////////////////
//
//
// newmenu.h
//
//
//
/////////////////////////////////////////////////////////////////
#include "menue.h"
#define LANG_GERMAN 0
class NewGame {
private:
static void DrawBG(const short);
static void DrawButtons();
public:
static void draw();
static void Input();
}; |
41a853caae5da0afdb5634661786a60a27eece8d | 5a268f13d9907b09755a0ec02064add58abfe7e3 | /source/engine/core/hesp/objects/commands/CmdBipedChangePosture.h | 661a97ccc472716e3a9ca63ca2871c30f92c7dfd | [] | no_license | MajickTek/hesperus2 | 3ba0f621373ed1e11bd01ea47628f980c5305897 | d3d7ba8e0f8b3b2f049b00a56f2788fa8fbf62d7 | refs/heads/master | 2021-09-10T11:38:10.211295 | 2018-03-25T19:54:14 | 2018-03-25T19:54:14 | 109,333,957 | 1 | 0 | null | 2017-11-03T00:44:39 | 2017-11-03T00:44:39 | null | UTF-8 | C++ | false | false | 695 | h | CmdBipedChangePosture.h | /***
* hesperus: CmdBipedChangePosture.h
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#ifndef H_HESP_CMDBIPEDCHANGEPOSTURE
#define H_HESP_CMDBIPEDCHANGEPOSTURE
#include <hesp/objects/base/ObjectCommand.h>
namespace hesp {
class CmdBipedChangePosture : public ObjectCommand
{
//#################### PRIVATE VARIABLES ####################
private:
ObjectID m_objectID;
//#################### CONSTRUCTORS ####################
public:
CmdBipedChangePosture(const ObjectID& objectID);
//#################### PUBLIC METHODS ####################
public:
void execute(const ObjectManager_Ptr& objectManager, int milliseconds);
};
}
#endif
|
5afee9a57dc177b6938c63e851ef3c2138d843b2 | 6992931f3cef1b2529b87656614f2448b3b75bf8 | /include/misc.hpp | a737a228c52671e81f2c3aabbde12e1632f2084c | [] | no_license | Clon1998/reactive-weather-flower-pot | a59ee08bc321dc1d5a7b6548c17236d8b14fb113 | edd6a4708a5ad90d5e0afdd6a46de88eed4f49ab | refs/heads/master | 2022-12-13T07:32:20.869452 | 2020-09-11T15:25:07 | 2020-09-11T15:25:07 | 294,729,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | hpp | misc.hpp | #pragma once
#include <Arduino.h>
#include <FastLED.h>
void nblendU8TowardU8(uint8_t& cur, const uint8_t target, uint8_t amount);
CRGB fadeTowardColor(CRGB& cur, const CRGB& target, uint8_t amount);
CRGB colorFromTemperature(double temp); |
5066d3d649870692c36e2e7f255be92051b189db | 01167b048623538b7121c1dcacaf22fad82b5fb8 | /src/Switch.Core/src/Native/DirectoryApiGcc.cpp | ded4a7a73e42dc981d9bda4f6744c153fbfefef1 | [
"MIT"
] | permissive | victor-timoshin/Switch | 8cd250c55027f6c8ef3dd54822490411ffbe2453 | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | refs/heads/master | 2020-03-20T22:46:57.904445 | 2018-06-18T21:54:51 | 2018-06-18T21:54:51 | 137,815,096 | 5 | 3 | null | 2018-06-18T22:56:15 | 2018-06-18T22:56:15 | null | UTF-8 | C++ | false | false | 10,994 | cpp | DirectoryApiGcc.cpp | #if defined(__linux__) || defined(__APPLE__)
#include <dirent.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/stat.h>
#include "../../include/Switch/System/Collections/Generic/Dictionary.hpp"
#include "../../include/Switch/System/IO/FileAttributes.hpp"
#include "../../include/Switch/System/Environment.hpp"
#include "Api.hpp"
namespace {
class Enumerator : public System::Collections::Generic::IEnumerator<string> {
public:
enum class FileType {
File,
Directory
};
Enumerator(const string& path, const string& pattern, FileType fileType) : path(path), pattern(pattern), fileType(fileType) {Reset();}
~Enumerator() {
if (this->handle != null)
closedir(this->handle);
}
bool MoveNext() override {
dirent* item;
System::IO::FileAttributes attributes;
do {
if ((item = readdir(this->handle)) != null)
Native::DirectoryApi::GetFileAttributes(string::Format("{0}/{1}", this->path, item->d_name), attributes);
} while (item != null && ((this->fileType == FileType::Directory && (attributes & System::IO::FileAttributes::Directory) != System::IO::FileAttributes::Directory) || (this->fileType == FileType::File && (attributes & System::IO::FileAttributes::Directory) == System::IO::FileAttributes::Directory) || string(item->d_name) == "." || string(item->d_name) == ".." || string(item->d_name).EndsWith(".app") || !PatternCompare(item->d_name, this->pattern)));
if (item == null)
return false;
this->current = string::Format("{0}{1}{2}", this->path, this->path.EndsWith('/') ? "" : System::Char('/').ToString(), item->d_name);
return true;
}
void Reset() override {
if (this->handle != null)
closedir(this->handle);
this->handle = opendir(path.Data());
}
protected:
const string& GetCurrent() const override {
if (this->handle == null)
throw System::InvalidOperationException(caller_);
return this->current;
}
private:
bool PatternCompare(const string& fileName, const string& pattern) {
if (string::IsNullOrEmpty(pattern))
return string::IsNullOrEmpty(fileName);
if (string::IsNullOrEmpty(fileName))
return false;
if (pattern == "*" || pattern == "*.*")
return true;
if (pattern[0] == '*')
return PatternCompare(fileName, pattern.Substring(1)) || PatternCompare(fileName.Substring(1), pattern);
return ((pattern[0] == '?') || (fileName[0] == pattern[0])) && PatternCompare(fileName.Substring(1), pattern.Substring(1));
}
string path;
string pattern;
DIR* handle = null;
mutable string current;
FileType fileType;
};
}
char32 Native::DirectoryApi::AltDirectorySeparatorChar() {
return '/';
}
char32 Native::DirectoryApi::DirectorySeparatorChar() {
return '/';
}
char32 Native::DirectoryApi::PathSeparator() {
return ':';
}
System::Array<char32> Native::DirectoryApi::InvalidPathChars() {
return {34, 60, 62, 124, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0};
}
char32 Native::DirectoryApi::VolumeSeparator() {
return '/';
}
System::Collections::Generic::Enumerator<string> Native::DirectoryApi::EnumerateDirectories(const string& path, const string& pattern) {
return System::Collections::Generic::Enumerator<string>(new_<Enumerator>(path, pattern, Enumerator::FileType::Directory));
}
System::Collections::Generic::Enumerator<string> Native::DirectoryApi::EnumerateFiles(const string& path, const string& pattern) {
return System::Collections::Generic::Enumerator<string>(new_<Enumerator>(path, pattern, Enumerator::FileType::File));
}
int32 Native::DirectoryApi::GetFileAttributes(const string& path, System::IO::FileAttributes& attributes) {
struct IntToFileAttributeConverter {
System::IO::FileAttributes operator()(int32 attribute) {
System::IO::FileAttributes fileAttributes = (System::IO::FileAttributes)0;
if ((attribute & S_IRUSR) == S_IRUSR && (attribute & S_IWUSR) == 0)
fileAttributes |= System::IO::FileAttributes::ReadOnly;
if ((attribute & S_IFSOCK) == S_IFSOCK || (attribute & S_IFIFO) == S_IFIFO)
fileAttributes |= System::IO::FileAttributes::System;
if ((attribute & S_IFDIR) == S_IFDIR)
fileAttributes |= System::IO::FileAttributes::Directory;
if ((attribute & S_IFREG) == S_IFREG)
fileAttributes |= System::IO::FileAttributes::Archive;
if ((attribute & S_IFBLK) == S_IFBLK || (attribute & S_IFCHR) == S_IFCHR)
fileAttributes |= System::IO::FileAttributes::Device;
if ((attribute & S_IFREG) == S_IFREG)
fileAttributes |= System::IO::FileAttributes::Normal;
return fileAttributes;
}
};
struct stat status {0};
int32 retValue = stat(path.Data(), &status);
attributes = IntToFileAttributeConverter()(status.st_mode);
return retValue;
}
int32 Native::DirectoryApi::GetFileTime(const string& path, int64& creationTime, int64& lastAccessTime, int64& lastWriteTime) {
struct stat status {0};
if (stat(path.Data(), &status) != 0)
return -1;
creationTime = status.st_ctime;
lastAccessTime = status.st_atime;
lastWriteTime = status.st_mtime;
return 0;
}
string Native::DirectoryApi::GetFullPath(const string& relativePath) {
System::Array<string> directories = relativePath.Split(DirectorySeparatorChar(), System::StringSplitOptions::RemoveEmptyEntries);
string fullPath;
if (relativePath[0] != DirectorySeparatorChar())
fullPath = GetCurrentDirectory();
for (string& item : directories) {
if (item == ".." && fullPath.LastIndexOf(DirectorySeparatorChar()) != -1)
fullPath = fullPath.Remove(fullPath.LastIndexOf(DirectorySeparatorChar()));
else if (item != ".")
fullPath = string::Format("{0}{1}{2}", fullPath, DirectorySeparatorChar(), item);
}
if (relativePath[relativePath.Length - 1] == DirectorySeparatorChar())
fullPath = string::Format("{0}{1}", fullPath, DirectorySeparatorChar());
return fullPath;
}
string Native::DirectoryApi::GetCurrentDirectory() {
char path[MAXPATHLEN + 1];
return getcwd(path, MAXPATHLEN) ? path : "";
}
int32 Native::DirectoryApi::SetCurrentDirectory(const string& directoryName) {
return chdir(directoryName.c_str());
}
int64 Native::DirectoryApi::GetFileSize(const string& path) {
struct stat status;
if (stat(path.Data(), &status) != 0)
return 0;
return status.st_size;
}
int32 Native::DirectoryApi::CreateDirectory(const string& directoryName) {
return mkdir(directoryName.Data(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
}
int32 Native::DirectoryApi::RemoveDirectory(const string& directoryName) {
return rmdir(directoryName.Data());
}
int32 Native::DirectoryApi::RemoveFile(const string& path) {
return unlink(path.Data());
}
int32 Native::DirectoryApi::RenameFile(const string& oldPath, const string& newPath) {
System::IO::FileAttributes fileAttributes = (System::IO::FileAttributes)0;
if (GetFileAttributes(newPath, fileAttributes) == 0)
return -1;
return rename(oldPath.Data(), newPath.Data());
}
string Native::DirectoryApi::GetKnowFolderPath(System::Environment::SpecialFolder id) {
#if defined(__APPLE__)
static System::Collections::Generic::Dictionary<System::Environment::SpecialFolder, string> specialFolders = {{System::Environment::SpecialFolder::Desktop, System::Environment::ExpandEnvironmentVariables("%HOME%/Desktop")}, {System::Environment::SpecialFolder::Personal, System::Environment::ExpandEnvironmentVariables("%HOME%")}, {System::Environment::SpecialFolder::Favorites, System::Environment::ExpandEnvironmentVariables("%HOME%/Library/Favorites")}, {System::Environment::SpecialFolder::MyMusic, System::Environment::ExpandEnvironmentVariables("%HOME%/Music")}, {System::Environment::SpecialFolder::MyVideos, System::Environment::ExpandEnvironmentVariables("%HOME%/Videos")}, {System::Environment::SpecialFolder::DesktopDirectory, System::Environment::ExpandEnvironmentVariables("%HOME%/Desktop")}, {System::Environment::SpecialFolder::Fonts, System::Environment::ExpandEnvironmentVariables("%HOME%/Library/Fonts")}, {System::Environment::SpecialFolder::Templates, System::Environment::ExpandEnvironmentVariables("%HOME%/Templates")}, {System::Environment::SpecialFolder::ApplicationData, System::Environment::ExpandEnvironmentVariables("%HOME%/.config")}, {System::Environment::SpecialFolder::LocalApplicationData, System::Environment::ExpandEnvironmentVariables("%HOME%/.local/share")}, {System::Environment::SpecialFolder::InternetCache, System::Environment::ExpandEnvironmentVariables("%HOME%/Library/Caches")}, {System::Environment::SpecialFolder::CommonApplicationData, "/usr/share"}, {System::Environment::SpecialFolder::ProgramFiles, "/Applications"}, {System::Environment::SpecialFolder::MyPictures, System::Environment::ExpandEnvironmentVariables("%HOME%/Pictures")}, {System::Environment::SpecialFolder::UserProfile, System::Environment::ExpandEnvironmentVariables("%HOME%")}, {System::Environment::SpecialFolder::CommonTemplates, "/usr/share/templates"}};
#else
static System::Collections::Generic::Dictionary<System::Environment::SpecialFolder, string> specialFolders = {{System::Environment::SpecialFolder::Desktop, System::Environment::ExpandEnvironmentVariables("%HOME%/Desktop")}, {System::Environment::SpecialFolder::MyDocuments, System::Environment::ExpandEnvironmentVariables("%HOME%")}, {System::Environment::SpecialFolder::MyMusic, System::Environment::ExpandEnvironmentVariables("%HOME%/Music")}, {System::Environment::SpecialFolder::MyVideos, System::Environment::ExpandEnvironmentVariables("%HOME%/Videos")}, {System::Environment::SpecialFolder::DesktopDirectory, System::Environment::ExpandEnvironmentVariables("%HOME%/Desktop")}, {System::Environment::SpecialFolder::Fonts, System::Environment::ExpandEnvironmentVariables("%HOME%/.fonts")}, {System::Environment::SpecialFolder::Templates, System::Environment::ExpandEnvironmentVariables("%HOME%/Templates")}, {System::Environment::SpecialFolder::ApplicationData, System::Environment::ExpandEnvironmentVariables("%HOME%/.config")}, {System::Environment::SpecialFolder::LocalApplicationData, System::Environment::ExpandEnvironmentVariables("%HOME%/.local/share")}, {System::Environment::SpecialFolder::CommonApplicationData, "/usr/share"}, {System::Environment::SpecialFolder::MyPictures, System::Environment::ExpandEnvironmentVariables("%HOME%/Pictures")}, {System::Environment::SpecialFolder::UserProfile, System::Environment::ExpandEnvironmentVariables("%HOME%")}, {System::Environment::SpecialFolder::CommonTemplates, "/usr/share/templates"}};
#endif
if (!specialFolders.ContainsKey(id))
return "";
return specialFolders[id];
}
string Native::DirectoryApi::GetTempPath() {
if (getenv("TMPDIR") != null)
return getenv("TMPDIR");
return "/tmp/";
}
#endif
|
dd3e8f26ad7c78bba9ab8b6b28799122a15ba739 | c5117348d4e97cadc546d8573d84c8ab4eed4374 | /UnitsAndBuildings/UnitsAndBuildings/Buildings/Refueling.cpp | 6a6a2e881e0024f172877e8164d91a217d181eef | [] | no_license | litelawliet/JeuStrategie | 3dd5b9fc67a43dc6bdf2c09461af4f0b36229c37 | b3dcfe822c2b7039155b521a4f84c924106e2897 | refs/heads/master | 2021-08-30T22:44:34.464824 | 2017-12-19T17:05:13 | 2017-12-19T17:05:13 | 102,288,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | cpp | Refueling.cpp | #include "Refueling.h"
Refueling::Refueling()
{
std::cout << "REFUELING constructor\n";
}
Refueling::~Refueling()
{
std::cout << "REFUELING destructor\n";
}
|
f452473a96d22f45773f7a7f756e7072db90c6c9 | 9a5257de7e51a879042fb63e16d3fba652e0aff7 | /src/util/Data.h | b94d1d40ddd39b07280e5b42fa01c22b324d03dd | [
"Apache-2.0"
] | permissive | openthread/wpantund | 146c0eb45ab56e85b15b4bbd9830192ad1d4fa9a | e2fd726982d626817b1db56c4361c1c5cb7d6201 | refs/heads/master | 2023-01-12T02:17:39.422466 | 2023-01-05T17:07:18 | 2023-01-05T20:46:41 | 60,717,054 | 176 | 130 | Apache-2.0 | 2023-01-05T20:46:42 | 2016-06-08T17:32:11 | C++ | UTF-8 | C++ | false | false | 1,668 | h | Data.h | /*
*
* Copyright (c) 2016 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Description:
* Class definition for binary data container.
*
*/
#ifndef __wpantund__Data__
#define __wpantund__Data__
#include <vector>
#include <stdint.h>
#include <stdlib.h>
namespace nl {
class Data : public std::vector<uint8_t> {
public:
Data(const std::vector<uint8_t>& x) : std::vector<uint8_t>(x) {
}
Data(
const uint8_t* ptr, size_t len
) : std::vector<uint8_t>(ptr, ptr + len) {
}
template<typename _InputIterator>
Data(_InputIterator __first, _InputIterator __last)
: std::vector<uint8_t>(__first, __last) { }
Data(size_t len = 0) : std::vector<uint8_t>(len) {
}
Data& append(const Data& d) {
insert(end(),d.begin(),d.end());
return *this;
}
Data& append(const uint8_t* ptr, size_t len) {
insert(end(),ptr,ptr+len);
return *this;
}
void pop_front(size_t len) {
erase(begin(), begin()+len);
}
uint8_t* data() {
return empty() ? NULL : &*begin();
}
const uint8_t* data() const {
return empty() ? NULL : &*begin();
}
};
};
#endif /* defined(__wpantund__Data__) */
|
e7c852e51d84b109f046e018fc64b865c805fe73 | edbcb5936d22469a1bf9bc30d47f5c12e3a9a83e | /otherExamples/Deque.cpp | 29223e1c681601605f830d7faffa0fb68b36ac10 | [] | no_license | takehiro-code/data-structures-algorithm | 6f056f5e0eeaa5b496d38a4bd083b0b714727bda | 7988ffb1049a683d7dfbb73b70966f45ca7a197a | refs/heads/main | 2023-08-08T03:49:37.702129 | 2021-09-22T00:41:36 | 2021-09-22T00:41:36 | 372,345,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,880 | cpp | Deque.cpp | #include "Deque.h"
#include <iostream>
using std::cout;
using std::endl;
// To be completed for exercise 4
// Helper method for Deque(Deque) and op=
// ONLY CHANGE BODY OF THESE TWO METHODS
void Deque::copyDeque(const Deque & dq)
{
// initialize n, front, back
n = dq.n;
front = nullptr;
back = nullptr;
copyNode(dq.back, front);
}
// Recursive helper method for copyDeque
void Deque::copyNode(Ex4Node* original, Ex4Node* copy)
{
//base case
if (original == nullptr) {
return;
}
// recusive case
else
{
// identical to insert_front
copy = new Ex4Node(original->data, nullptr, front);
front = copy;
if (back == nullptr) {
back = front;
}
else {
front->next->previous = front;
}
copyNode(original->previous, copy);
}
}
// DO NOT CHANGE ANYTHING BELOW THIS LINE
// --------------------------------------
Deque::Deque()
{
front = back = nullptr;
n = 0;
}
Deque::Deque(const Deque & dq)
{
copyDeque(dq);
}
Deque & Deque::operator=(const Deque & dq)
{
if (this != &dq) {
removeAll();
copyDeque(dq);
}
return *this;
}
Deque::~Deque()
{
//cout << "... in destructor ..."; // debug print
removeAll();
}
void Deque::insert_front(int val)
{
Ex4Node* newNode = new Ex4Node(val, nullptr, front);
front = newNode;
// Deque was empty
if (back == nullptr) {
back = front;
}
else {
front->next->previous = front;
}
n++;
}
void Deque::insert_back(int val)
{
// Deque is empty
if (back == nullptr) {
back = new Ex4Node(val);
front = back;
}
else {
back->next = new Ex4Node(val);
back->next->previous = back;
back = back->next;
}
n++;
}
int Deque::remove_front()
{
// Deque is empty
if (front == nullptr) {
throw runtime_error("remove_front failed - empty");
}
int result = front->data;
Ex4Node* temp = front;
front = front->next;
if (front == nullptr) {
back = nullptr;
}
else {
front->previous = nullptr;
}
n--;
delete temp;
return result;
}
int Deque::remove_back()
{
// Deque is empty
if (back == nullptr) {
throw runtime_error("remove_back failed - empty");
}
int result = back->data;
Ex4Node* temp = back;
back = back->previous;
if (back == nullptr) {
front = nullptr;
}
else {
back->next = nullptr;
}
n--;
delete temp;
return result;
}
int Deque::size() const
{
return n;
}
bool Deque::empty() const
{
return front == nullptr && back == nullptr;
}
void Deque::removeAll()
{
Ex4Node* temp = front;
while (front != nullptr) {
front = temp->next;
delete temp;
temp = front;
}
n = 0;
front = back = nullptr;
}
void Deque::printForwards() const
{
Ex4Node* p = front;
while (p != nullptr) {
cout << p->data << " ";
p = p->next;
}
}
void Deque::printBackwards() const
{
Ex4Node* p = back;
while (p != nullptr) {
cout << p->data << " ";
//cout << p->data << ": p->previous = " << p->previous << endl; //debug print
p = p->previous;
}
} |
e46412342361ab9dc842e07ce4cd1c2474b0eb7c | 002df2aecf110b3718c22aa99db1c74c8e66c0fe | /Problems/0378. Kth Smallest Element in a Sorted Matrix.cpp | 9e76a3bab32968449bfee21e89e341411780f3ef | [
"MIT"
] | permissive | KrKush23/LeetCode | ddde2f95ac745ed3751486439b81873069706ed7 | 2a87420a65347a34fba333d46e1aa6224c629b7a | refs/heads/master | 2023-08-23T16:28:02.852347 | 2021-10-12T20:52:02 | 2021-10-12T20:52:02 | 234,703,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,015 | cpp | 0378. Kth Smallest Element in a Sorted Matrix.cpp | #define vi vector<int>
class Solution {
int n;
int countLessEqual(vector<vector<int>>& matrix, int num){
int cnt{0};
for(auto row: matrix){
int l=0, r=n;
while(l < r){
int mid = l + (r-l)/2;
if(row[mid] <= num)
l = mid+1;
else
r = mid;
}
cnt += l;
}
return cnt;
}
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
n = matrix.size();
// 2 BINARY SEARCH approach ============================
int l = matrix[0][0], r = matrix[n-1][n-1];
while(l<r){
int mid = l + (r-l)/2; // find mid
if(countLessEqual(matrix, mid) < k) //no. of elements less or equal to mid...
l = mid+1; // if < k..l = mid+1
else
r = mid; // if >= k..r=mid
}
return l;
// FAST..but not using the SORTED MATRIx fact===========
/*
priority_queue<int> pq; // MAX HEAP
for(auto i:matrix){
for(auto j:i){
if(pq.size()<k)
pq.push(j);
else if(j < pq.top()){
pq.pop();
pq.push(j);
}
}
}
return pq.top();
*/
// Kth samllest from multiple SORTED LISTS
/*
priority_queue<vi, vector<vi>, greater<vi>> pq; // MIN HEAP
for(int i=0; i<n and i<k; i++)
pq.push({matrix[i][0], i, 0});
int res{};
while(k--){
auto cur = pq.top();
pq.pop();
res = cur[0];
int i=cur[1], j=cur[2];
if(k==0)
break;
if(j+1<n)
pq.push({matrix[i][j+1], i, j+1});
}
return res;
*/
}
};
|
1a3215f3722cf7f6e5da68e4a1e6ff41752a0244 | 7f25ac596812ed201f289248de52d8d616d81b93 | /eggeek/codeforces/617D.cpp | 31ca7cfa764f01bbb26cc4fb4e40300fd11c4d46 | [] | no_license | AplusB/ACEveryDay | dc6ff890f9926d328b95ff536abf6510cef57eb7 | e958245213dcdba8c7134259a831bde8b3d511bb | refs/heads/master | 2021-01-23T22:15:34.946922 | 2018-04-07T01:45:20 | 2018-04-07T01:45:20 | 58,846,919 | 25 | 49 | null | 2016-07-14T10:38:25 | 2016-05-15T06:08:55 | C++ | UTF-8 | C++ | false | false | 1,090 | cpp | 617D.cpp | #include <bits/stdc++.h>
using namespace std;
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) int((a).size())
#define LOWB(x) (x & (-x))
#define UNIQUE(a) sort(ALL(a)), (a).erase(unique(ALL(a)), (a).end())
#define INF 1e9
#define INF_LL 4e18
#define rep(i,a,b) for(__typeof(b) i=a; i<(b); ++i)
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
/*-----------------------------------*/
int x[3], y[3];
int solve() {
if (x[0] == x[1] && x[1] == x[2]) return 1;
if (y[0] == y[1] && y[1] == y[2]) return 1;
for (int i=0; i<3; i++) {
for (int j=i+1; j<3; j++) {
int k = 3 - i - j;
if (x[i] == x[j]) {
if (y[k] <= min(y[i], y[j])) return 2;
if (y[k] >= max(y[i], y[j])) return 2;
}
if (y[i] == y[j]) {
if (x[k] <= min(x[i], x[j]) ||
x[k] >= max(x[i], x[j])) return 2;
}
}
}
return 3;
}
int main() {
for (int i=0; i<3; i++) {
scanf("%d%d", &x[i], &y[i]);
}
cout << solve() << endl;
return 0;
}
|
357a7e39e48b90a1e91357cf66322c4b49bf8d31 | 890a0d3b20266612ca6b728abe2a95c03a8a68de | /include/Controller/ZHM5CCTargetController.h | 8a90352cb4a05b5e0f62d262769a932c0cbc15b5 | [] | no_license | pavledev/HitmanAbsolutionSDK | 377c8a6cd1c115e2e446ddefbdbafc8cd03c05a2 | e3e4b09da4b9ae9b6cc6117be5ff24479fb6134e | refs/heads/main | 2022-07-28T11:57:34.434004 | 2021-09-29T11:48:32 | 2021-09-29T11:48:32 | 337,443,029 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,644 | h | ZHM5CCTargetController.h | #pragma once
#include "float4.h"
#include "SHM5CCTarget.h"
#include "ZHitman5.h"
#include "ZPF5Location.h"
class ZHM5CCTargetController
{
public:
struct STargetPositions
{
ECCTargetPos m_eFirstPos;
ECCTargetPos m_eSecondPos;
};
bool m_bAllowAttacks;
float4 m_vMainDir;
float4 m_vMainPos;
SHM5CCTarget m_TargetPos[4];
SHM5CCTarget m_RunInTargetInfo[3];
TEntityRef<ZHitman5> m_pHitman;
ZPF5Location m_StartLocation;
bool m_bLock;
ZHM5CCTargetController() = default;
ZHM5CCTargetController(const TEntityRef<ZHitman5>& pHitman);
bool ReservePosition(const TEntityRef<ZActor>& rActor, ECCNodeType eStartState);
void ForcePosition(const TEntityRef<ZActor>& rActor, ECCNodeType eStartState);
const SHM5CCTarget& GetTarget(unsigned int nIndex) const;
SHM5CCTarget* GetTarget();
void ResetTimers();
void ResetTimeToAttack(const TEntityRef<ZActor>& rActor, bool pacified);
void Update();
const SHM5CCTarget* GetTargetInfo(const TEntityRef<ZActor>& rActor) const;
void ReleaseTargets();
void ReleaseRunInTargets();
void ReleaseTarget(const TEntityRef<ZActor>& rActor);
void ReleaseCrowdActors();
void ReleaseAllExcept(const TEntityRef<ZActor>& rActor);
float4 GetMainPosition() const;
unsigned int GetNumTargets() const;
const ZPF5Location& GetStartLocation() const;
void Lock(bool bLock);
SHM5CCTarget* ChangeTarget();
bool ReserveRunIn(const TEntityRef<ZActor>& rActor);
float4 GetHitmanPos() const;
ZPF5Location GetHitmanMappedPos() const;
ZPF5Location GetMappedPos(const float4& vPos) const;
unsigned int GetNumActiveReservations() const;
unsigned int GetNumRunInReservations() const;
unsigned int GetMaxReservations() const;
void UpdateTimeToAttack();
SHM5CCTarget* GetFirstReadyTarget();
SHM5CCTarget* GetFirstWaitingTarget();
SHM5CCTarget* GetAvaliableTarget(const TEntityRef<ZActor>& rActor);
SHM5CCTarget* GetAvaliableTarget(unsigned int idx);
SHM5CCTarget* GetAvaliableTarget();
void AllowTargetsToAttack(bool allow);
void ForceWaitingTarget(unsigned int iNumTargets);
SHM5CCTarget* GetSelectedTarget();
void ResetTargetSelection();
void SelectTarget(const float4& selectDir, bool ignoreWaitingTargets);
void SelectTarget(const TEntityRef<ZActor>& rActor);
bool CanReservePosition(const float4& vHitmanPos, const float4& vActorPos) const;
bool CanReservePosition(const TEntityRef<ZActor>& rActor) const;
bool ReserveSecondaryPos(const TEntityRef<ZActor>& rActor, ECCNodeType eStartState);
bool OppositePos(ECCTargetPos eTargetPos, ECCTargetPos eTargetPos2) const;
STargetPositions GetTargetPositions(const TEntityRef<ZActor>& rActor) const;
~ZHM5CCTargetController() = default;
};
|
9888b1ade44cfa8d72b6df34cec52f03dd080add | 6138481191cf879454ac593b81f5eec9fc16cdc2 | /pcommon/pcomn_safeptr.h | 5da615c3ef8a07db187da55ac3a1e6b80bf91e90 | [
"Zlib"
] | permissive | ymarkovitch/libpcomn | 0eb122863618e79353489d76190a0cd655858912 | baf5f87e107f8e9f2a6136e1e20c7b20e9f800b2 | refs/heads/master | 2022-05-24T00:13:04.212161 | 2022-05-23T14:38:29 | 2022-05-23T15:13:38 | 23,715,041 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 13,102 | h | pcomn_safeptr.h | /*-*- mode: c++; tab-width: 3; indent-tabs-mode: nil; c-file-style: "ellemtel"; c-file-offsets:((innamespace . 0)(inclass . ++)) -*-*/
#ifndef __PCOMN_SAFEPTR_H
#define __PCOMN_SAFEPTR_H
/*******************************************************************************
FILE : pcomn_safeptr.h
COPYRIGHT : Yakov Markovitch, 1994-2020. All rights reserved.
See LICENSE for information on usage/redistribution.
DESCRIPTION : Safe pointer templates
CREATION DATE: 25 Nov 1994
*******************************************************************************/
/** @file
Safe pointers.
- ptr_shim
- safe_ref
- safe_ptr
- malloc_ptr
*******************************************************************************/
#include <pcomn_meta.h>
#include <pcommon.h>
#include <stdexcept>
#include <utility>
#include <memory>
namespace pcomn {
/***************************************************************************//**
Safepointer for malloc-allocated objects
*******************************************************************************/
template<typename T>
using malloc_ptr = std::unique_ptr<T, malloc_delete> ;
/***************************************************************************//**
Proxy object for any pointer-like or pointer type
Useful as a function parameter object where serves as a "shim" converting any
pointer-like objects to plain pointers
*******************************************************************************/
template<typename T>
struct ptr_shim {
constexpr ptr_shim(nullptr_t) : _ptr(nullptr) {}
template<typename P>
constexpr ptr_shim(const P &p,
typename std::enable_if<std::is_convertible<decltype(&*p), T *>::value, Instantiate>::type = {}) :
_ptr(&*p) {}
constexpr T *get() const { return _ptr ; }
constexpr operator T *() const { return get() ; }
constexpr T &operator*() const { return *get() ; }
constexpr T *operator->() const { return get() ; }
constexpr T &operator[](ptrdiff_t ndx) const { return _ptr[ndx] ; }
private:
T *_ptr ;
} ;
/***************************************************************************//**
Reference wrapper object, which may, depending on construction mode, delete the
object whose reference it holds.
Have two modes: owning and unowning.
*******************************************************************************/
template<typename T>
class safe_ref {
PCOMN_NONCOPYABLE(safe_ref) ;
PCOMN_NONASSIGNABLE(safe_ref) ;
public:
typedef T type ; /**< For compatibility with std::reference_wrapper */
typedef T element_type ;
/// Construct a safe reference that dows @e not own the passed object.
constexpr safe_ref(element_type &unowned_object) : _ref(unowned_object) {}
/// Construct a safe reference that @e owns the passed object.
/// @throw std::invalid_argument if @a owned_object is nullptr.
safe_ref(std::unique_ptr<element_type> &&owned_object) :
_owner(std::move(PCOMN_ENSURE_ARG(owned_object))),
_ref(*_owner)
{}
/// Allow runtime selection of object ownership.
/// Either unowned or owned must be nonnull.
safe_ref(element_type *unowned, std::unique_ptr<element_type> &&owned) :
_owner(std::move(owned)),
_ref(_owner ? *_owner : *PCOMN_ENSURE_ARG(unowned))
{}
constexpr T &get() const { return _ref ; }
constexpr operator T&() const { return get() ; }
constexpr T *operator->() const { return &get() ; }
constexpr bool owns() const { return !!_owner ; }
private:
const std::unique_ptr<type> _owner ;
type & _ref ;
} ;
/***************************************************************************//**
A smart reference with value semantics, like std::reference_ptr crossed with
std::unique_ptr, with shared default value.
Has an extra non-type template parameter of type T, which specifies a reference
to the *global default value*, pointer to which is used instead of nullptr.
Default-constructed objects of the instance of this template refer to this
default object.
For any two different unique_value<T> objects x and y, the following holds:
@code
&x.get() != &y.get() || &x.get() == unique_value<T>::unique_value_ptr()
@endcode
That is, every unique_value<T> refers either to the single global constant default
object of type T, or to a *unique* T object allocated with operator new; no two
different unique_value<T> objects can refer to the same *non-default* T object.
@code
struct Foo {
Foo() ;
int bar() const ;
void set_bar(int) ;
friend bool operator==(const Foo&,const Foo&) ;
} ;
// Default constructor: after this there will be
// &foo0.get()==&pcomn::default_constructed<Foo>::value
// No Foo constructors called, no dynamic allocations, foo0 is an unowning reference
// to &pcomn::default_constructed<Foo>::value.
pcomn::unique_value<Foo> foo0 ;
// &foo1.get()==&foo0.get(), both foo0 and foo1 refer to pcomn::default_constructed<Foo>::value
pcomn::unique_value<Foo> foo1 ;
// Note that
// foo2.get()==pcomn::default_constructed<Foo>::value, but
// &foo2.get()!=&pcomn::default_constructed<Foo>::value
pcomn::unique_value<Foo> foo2 (Foo()) ;
// The underlying object of foo2 is copied by value.
// Now foo1.get(), foo2.get(), and pcomn::default_constructed<Foo>::value are
// different objects.
foo1 = foo2 ;
@endcode
*******************************************************************************/
template<typename T, const T &default_value = pcomn::default_constructed<T>::value>
class unique_value {
public:
PCOMN_STATIC_CHECK(!std::is_reference<T>() && !std::is_void<T>()&& !std::is_array<T>()) ;
typedef const T type ; /**< For compatibility with std::reference_wrapper */
typedef type element_type ;
/// Create a reference to default_value.
/// After this constructor, `&this->get()==default_value_ptr()`
constexpr unique_value() noexcept = default ;
/// Create an owning reference to the copy of the argument.
/// This is "by value" constructor that calls T copy constructor, *except* for the
/// case when `value` is the reference to `default_value`.
///
unique_value(const T &value) :
_owner(is_default(&value) ? default_value_unsafe_ptr() : new T(value))
{}
/// Value-move constructor.
/// Calls T move constructor, *except* for the case when `value` is the reference
/// to `default_value`.
///
unique_value(T &&value) :
_owner(is_default(&value) ? default_value_unsafe_ptr() : new T(std::move(value)))
{}
unique_value(const unique_value &other) : unique_value(other.get()) {}
/// Move constructor.
/// No allocations, no T copy/move constructor calls.
/// After this constructor `other` always refers to default_value.
///
unique_value(unique_value &&other) noexcept : unique_value()
{
_owner.swap(other._owner) ;
}
/// Make a safe reference that owns the passed object.
///
/// @throw std::invalid_argument if `owned_object` is nullptr.
unique_value(std::unique_ptr<T> &&value) :
_owner(std::move(PCOMN_ENSURE_ARG(value)))
{}
/// Destructor deletes the object referred to *iff* the internal reference does not
/// refer to `default_value`.
~unique_value()
{
discharge_default_reference() ;
}
unique_value &operator=(unique_value &&other) noexcept
{
if (_owner == other._owner)
return *this ;
if (other.is_default())
_owner = std::unique_ptr<T>(default_value_unsafe_ptr()) ;
else
_owner.swap(other._owner) ;
return *this ;
}
unique_value &operator=(const unique_value &other)
{
if (_owner == other._owner)
return *this ;
std::unique_ptr<T> value_copy (other.is_default() ? default_value_unsafe_ptr() : new T(other.get())) ;
discharge_default_reference() ;
_owner = std::move(value_copy) ;
return *this ;
}
void swap(unique_value &other) noexcept
{
_owner.swap(other._owner) ;
}
constexpr const T &get() const noexcept { return *_owner ; }
constexpr operator const T&() const noexcept { return get() ; }
constexpr const T *operator->() const noexcept { return _owner.get() ; }
/// Get a nonconstant reference to the underlying value, doing copy-on-write if the
/// internal reference is to `default_value`.
///
T &mutable_value()
{
PCOMN_STATIC_CHECK(!std::is_const_v<T>) ;
if (is_default())
{
_owner.release() ;
_owner.reset(new T(*default_value_ptr())) ;
}
return *_owner ;
}
/// Get the pointer to the (global) default value.
/// This is a pointer to `default_value` template parameter.
/// @note Never nullptr.
///
static constexpr const T *default_value_ptr() noexcept { return &default_value ; }
private:
std::unique_ptr<T> _owner {default_value_unsafe_ptr()} ;
private:
static constexpr T *default_value_unsafe_ptr() noexcept { return const_cast<T*>(default_value_ptr()) ; }
static constexpr bool is_default(type *value) noexcept { return value == default_value_unsafe_ptr() ; }
constexpr bool is_default() const noexcept { return is_default(_owner.get()) ; }
void discharge_default_reference() noexcept
{
if (is_default())
_owner.release() ;
}
} ;
PCOMN_DEFINE_SWAP(unique_value<T>, template<typename T, const T &>) ;
/***************************************************************************//**
Safe pointer like std::unique_ptr but with *no* move semantics.
*******************************************************************************/
template<typename T>
class safe_ptr : private std::unique_ptr<T> {
typedef std::unique_ptr<T> ancestor ;
PCOMN_NONCOPYABLE(safe_ptr) ;
PCOMN_NONASSIGNABLE(safe_ptr) ;
public:
using typename ancestor::element_type ;
using typename ancestor::pointer ;
using ancestor::release ;
using ancestor::get ;
constexpr safe_ptr() = default ;
constexpr safe_ptr(nullptr_t) {}
explicit constexpr safe_ptr(pointer p) : ancestor(p) {}
typename std::add_lvalue_reference<element_type>::type operator*() const { return *get() ; }
typename std::add_lvalue_reference<element_type>::type operator[](size_t i) const { return get()[i] ; }
pointer operator->() const { return get() ; }
operator pointer() const { return get() ; }
constexpr explicit operator bool() const noexcept { return ancestor::operator bool() ; }
safe_ptr &reset(pointer p)
{
ancestor::reset(p) ;
return *this ;
}
safe_ptr &reset(nullptr_t = nullptr)
{
ancestor::reset() ;
return *this ;
}
safe_ptr &operator=(nullptr_t) { return reset() ; }
void swap(safe_ptr &other)
{
ancestor::swap(*static_cast<ancestor *>(&other)) ;
}
template<typename C>
friend std::basic_ostream<C> &operator<<(std::basic_ostream<C> &os, const safe_ptr &p)
{
return os << static_cast<const safe_ptr::ancestor &>(p) ;
}
} ;
PCOMN_DEFINE_SWAP(safe_ptr<T>, template<typename T>) ;
/***************************************************************************//**
Both std::unique_ptr and pcomn::safe_ptr are trivially swappable, but only with
the standard deleter object.
*******************************************************************************/
template<typename T>
struct is_trivially_swappable<std::unique_ptr<T>> : std::true_type {} ;
template<typename T>
struct is_trivially_swappable<safe_ptr<T>> : std::true_type {} ;
template<typename T>
struct is_trivially_swappable<unique_value<T>> : std::true_type {} ;
/******************************************************************************/
/** unique_ptr creation helper
Don't confuse with C++14 make_unique<T>(), which calls T's constructor forwarding
its arguments.
*******************************************************************************/
template<typename T>
inline std::unique_ptr<T> make_unique_ptr(T *p) { return std::unique_ptr<T>(p) ; }
/*******************************************************************************
Backward compatibility declaration
*******************************************************************************/
template<typename T, typename D = std::default_delete<T> >
using PTSafePtr = std::unique_ptr<T, D> ;
template<typename T, typename D = std::default_delete<T[]>>
using PTVSafePtr = std::unique_ptr<T[]> ;
template<typename T>
using PTMallocPtr = std::unique_ptr<T, malloc_delete> ;
} // end of namespace pcomn
#endif /* __PCOMN_SAFEPTR_H */
|
111e714f371b2050c3752307862fe5f1ec984837 | 0dd9cf13c4a9e5f28ae5f36e512e86de335c26b4 | /Hackerrank_InterviewStreet/tower-breakers-again-1.cpp | df1f08d9d3bcdfd1043f1387db36139b06b93892 | [] | no_license | yular/CC--InterviewProblem | 908dfd6d538ccd405863c27c65c78379e91b9fd3 | c271ea63eda29575a7ed4a0bce3c0ed6f2af1410 | refs/heads/master | 2021-07-18T11:03:07.525048 | 2021-07-05T16:17:43 | 2021-07-05T16:17:43 | 17,499,294 | 37 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 1,120 | cpp | tower-breakers-again-1.cpp | /*
*
* Tag: Game
* Time: O(sqrt(n))
* Space: O(sqrt(n))
*/
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <unordered_map>
using namespace std;
const int N = 110;
const int M = 100100;
int sg[M], n, v;
int grundy(int v);
int mergeSG(int x, int y){
if(x&1)
return grundy(y);
return 0;
}
int grundy(int v){
if(sg[v] != -1)
return sg[v];
set<int> st;
for(int i = 1; i*i <= v && i < v; ++ i){
if(v%i)
continue;
if(i > 1)
st.insert(mergeSG(i, v/i));
st.insert(mergeSG(v/i, i));
}
int res = 0;
while(st.count(res)) res++;
return sg[v] = res;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
fill(sg, sg + M, -1);
int T;
scanf("%d",&T);
while(T --){
scanf("%d",&n);
int ans = 0;
for(int i = 0; i < n; ++ i){
scanf("%d",&v);
ans^=grundy(v);
}
puts(ans?"1":"2");
}
return 0;
}
|
efe6f35aa5131f346cedd412ec9055455bad53d5 | 9aa0ec9065485acab4fba5263b86366402a1a9b1 | /excercise/carry_num.cpp | 8a28b6b258d4afa0e415bfb33b507dcb5089f761 | [] | no_license | defuyun/ACM | 1883ad46f057b79f7fab2a7b659ab8320a1a9ca7 | b2879d10b1a292b593250d5b85fb791b17a676c4 | refs/heads/master | 2021-01-18T21:18:40.290945 | 2016-05-06T01:17:00 | 2016-05-06T01:17:00 | 33,590,907 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | carry_num.cpp | #include<stdio.h>
#include<iostream>
// Q. calculate the number of times a carry in would occur for 2 number addition, the number would be < 9 digit
// max int 2,147,483,647. > 2,000,00,00 so using int to store is fine, input 0 0 means end of file
int main(){
int a,b,c = 0;
int ans = 0;
while(std::cin >> a >> b){
if(!a && !b) break;
while(a && b){
c = (a%10 + b%10) >= 10 ? 1 : 0;
a /= 10; b /= 10;
ans += c;
}
std::cout << ans << std::endl;
}
return 0;
}
|
805484e90d960edef742d34aa11a030e7f42cca2 | 602e0f4bae605f59d23688cab5ad10c21fc5a34f | /MyToolKit/Stock/SouhuStockPlates.cpp | a35e7debe172bf23a44e364c99fc89a60ece9215 | [] | no_license | yanbcxf/cpp | d7f26056d51f85254ae1dd2c4e8e459cfefb2fb6 | e059b02e7f1509918bbc346c555d42e8d06f4b8f | refs/heads/master | 2023-08-04T04:40:43.475657 | 2023-08-01T14:03:44 | 2023-08-01T14:03:44 | 172,408,660 | 8 | 5 | null | null | null | null | GB18030 | C++ | false | false | 16,690 | cpp | SouhuStockPlates.cpp | #include "StdAfx.h"
#include "SouhuStockPlates.h"
#include "UrlUtils.h"
CSouhuStockPlates::CSouhuStockPlates(void)
{
m_strEnglishName = "SouhuStockPlates";
}
CSouhuStockPlates::~CSouhuStockPlates(void)
{
m_vec_code.clear();
m_vec_name.clear();
m_vec_company_number.clear();
m_vec_total_volume.clear();
m_vec_total_turnover.clear();
m_vec_parent_code.clear();
m_vec_is_stock.clear();
}
int CSouhuStockPlates::CheckReport(vector<string>& arrayHeader, vector<vector<string>>& arrayData)
{
string header[] = {
"板块或股票代码",
"板块或股票名称",
"公司家数",
"总手",
"总成交金额",
"上级板块代码",
"是否股票"
};
if(arrayHeader.size()!=7)
return CSV_CHECK_FORMAT_ERROR;
for(int i=0; i<7; i++)
{
if(arrayHeader[i]!=header[i])
return CSV_CHECK_FORMAT_ERROR;
}
return CSV_CHECK_NO_ERROR;
}
void CSouhuStockPlates::ParseCsvFile(vector<string>& arrayHeader, vector<vector<string>>& arrayData)
{
stringstream ss;
/*string connectString = "dbname=stock port=3306 host=127.0.0.1 user=root ";
backend_factory const &backEnd = *soci::factory_mysql();*/
m_vec_code.clear();
m_vec_name.clear();
m_vec_company_number.clear();
m_vec_total_volume.clear();
m_vec_total_turnover.clear();
m_vec_parent_code.clear();
m_vec_is_stock.clear();
try
{
ss << "CSouhuStockPlates ParseCsvFile。。。。。。\r\n";
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
for (int row = 0; row < arrayData.size(); row++)
{
int colnum = arrayData[row].size();
m_vec_code[row]=atoi(arrayData[row][0].c_str());
m_vec_name[row]= 1<colnum ? (arrayData[row][1]):0;
m_vec_company_number[row]= 2<colnum ? atoi(arrayData[row][2].c_str()):0;
m_vec_total_volume[row]= 3<colnum ? String2Double(arrayData[row][3]):0;
m_vec_total_turnover[row]= 4<colnum ? String2Double(arrayData[row][4]):0;
m_vec_parent_code[row]= 5<colnum ? atoi(arrayData[row][5].c_str()):0;
m_vec_is_stock[row]= 6<colnum ? atoi(arrayData[row][6].c_str()):0;
}
ss.str("");
ss << "OK, CSouhuStockPlates ParseCsvFile 完毕.\r\n";
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
}
catch (std::exception const & e)
{
ss.str("");
ss << e.what() << '\r\n';
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
}
}
void CSouhuStockPlates::ParseXmlElement(void)
{
}
bool CSouhuStockPlates::ParseCsvFileName(string szFileName)
{
vector<string> firstMatch;
if(Pcre2Grep(m_strEnglishName.c_str(), szFileName,firstMatch )<=0)
return false;
return true;
}
void CSouhuStockPlates::ImportToDatabase(void)
{
if( m_vec_code.size()<=0)
return;
stringstream ss;
backend_factory const &backEnd = *soci::factory_mysql();
try
{
ss << "CSouhuStockPlates::ImportToDatabase 开始导入数据.....\r\n";
//sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
session sql(g_MysqlPool);
// 删除“过时”的板块分组
ss.str("");
ss << "delete from SouhuStockPlates where (Code, Parent_Code) not in( ";
for (int row = 0; row < m_vec_code.size(); row++)
{
ss << "(" << m_vec_code[row] << "," << m_vec_parent_code[row] << ")";
if(row < m_vec_code.size()-1)
ss << ",";
}
ss << ")";
string test1 = ss.str();
sql << test1;
for (int row = 0; row < m_vec_code.size(); row++)
{
ss.str("");
ss << "insert into SouhuStockPlates "
<< " select " << Int2String(m_vec_code[row]) << ", \'"
<< m_vec_name[row] << "\', "
<< Int2String(m_vec_company_number[row]) << ", "
<< Double2String(m_vec_total_volume[row]) << ", "
<< Double2String(m_vec_total_turnover[row]) << ", "
<< Int2String(m_vec_parent_code[row]) << ", "
<< Int2String(m_vec_is_stock[row]) << " "
<< " from dual where not exists (SELECT 1 from SouhuStockPlates "
<< " where Parent_Code=" << Int2String(m_vec_parent_code[row]) << " "
<< " and Code=" << Int2String(m_vec_code[row]) << " ) ";
string test = /*Gbk2Utf8*/(ss.str());
sql << test;
ss.str("");
ss << "update SouhuStockPlates "
<< " set Code=" << Int2String(m_vec_code[row]) << ", Name=\'"
<< m_vec_name[row] << "\', Company_Number="
<< Int2String(m_vec_company_number[row]) << ",Total_Volume="
<< Double2String(m_vec_total_volume[row]) << ", Total_Turnover="
<< Double2String(m_vec_total_turnover[row]) << ", Parent_Code="
<< Int2String(m_vec_parent_code[row]) << ", Is_Stock="
<< Int2String(m_vec_is_stock[row]) << " "
<< " where Parent_Code=" << Int2String(m_vec_parent_code[row]) << " "
<< " and Code=" << Int2String(m_vec_code[row]) << " ";
test = /*Gbk2Utf8*/(ss.str());
sql << test;
}
ss.str("");
ss << "共有数据 " << m_vec_code.size() ;
ss << " OK, CSouhuStockPlates::ImportToDatabase 数据导入完毕. \r\n";
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
}
catch (std::exception const & e)
{
ss.str("");
ss << e.what() << '\r\n';
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
}
}
CStockDataModel * CSouhuStockPlates::NewCopy()
{
CSouhuStockPlates * pTrading = new CSouhuStockPlates();
pTrading->m_nRowNum = m_nRowNum;
/*pTrading->m_vec_open = m_vec_open;
pTrading->m_vec_high = m_vec_high;
pTrading->m_vec_low = m_vec_low;
pTrading->m_vec_close = m_vec_close;
pTrading->m_vec_volume = m_vec_volume;*/
return pTrading;
}
string CSouhuStockPlates::GetDownloadUrl()
{
return "";
}
string CSouhuStockPlates::SqlScript()
{
stringstream ss;
ss << "create table if not exists SouhuStockPlates (Code int , Name varchar(256), Company_Number int, "
<< " Total_Volume DECIMAL(15,4), Total_Turnover DECIMAL(15,4), "
<< " Parent_Code int, Is_Stock int, PRIMARY KEY ( Code, Parent_Code))";
return ss.str();
}
string CSouhuStockPlates::SaveAsCsv()
{
stringstream ss;
//////////////////////////////////////////////////////////////////////////
// 对于本日已经成功下载的 ,忽略该任务
if(CheckDownloadFileInfo(GetCsvFileName())>0)
{
ss.str("");
ss << "搜狐板块,本日已经最新";
ss << "\r\n";
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
return "NoMoreData";
}
CStdioFile targetFile;
bool bWriteTitle = true;
string mainPlate[3] = {
//"http://hq.stock.sohu.com/pl/pl-1.html?uid=1512222240560727&7027194625967",
"http://hq.stock.sohu.com/pl/pl-1631.html?uid=1512222240560727&7027194625967",
"http://hq.stock.sohu.com/pl/pl-1632.html?uid=1512222240560727&7027194625967",
"http://hq.stock.sohu.com/pl/pl-1630.html?uid=1512222240560727&7027194625967"
};
// 先下载主板的信息
vector<string> vecCode;
for(int index =0; index<3; index++)
{
try
{
string strGBK=CUrlUtils::PostUrlOfSouhu(mainPlate[index].c_str(),NULL);
vector<string> vecMatch;
string pattern = "<script>document.domain=\\'sohu.com\\';PEAK_ODIA=parent\\.PEAK_ODIA;</script><script>PEAK_ODIA\\(";
if(Pcre2Grep(pattern, strGBK.c_str() ,vecMatch )>0)
{
string::size_type pos = strGBK.find(vecMatch[0]);
strGBK = strGBK.substr(pos + 10 + vecMatch[0].length());
strGBK = strGBK.substr(0, strGBK.length()-11);
strGBK = ReplaceChar(strGBK, '\'', "\"");
strGBK = "[" + strGBK + "]";
Json::Value jsonRoot;
Json::Reader reader(Json::Features::strictMode());
bool parsingSuccessful = reader.parse(strGBK, jsonRoot);
if (!parsingSuccessful) {
ss.str("");
ss << "搜狐板块【" << index << "】,解析 JSON 错误 :";
ss << reader.getFormattedErrorMessages().c_str();
ss << "\r\n";
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
}
else
{
//Json::Value json_result = jsonRoot[1];
if(jsonRoot.type()== Json::arrayValue)
{
int size = jsonRoot.size();
if(size>0)
{
if(bWriteTitle)
{
BOOL b = targetFile.Open(GetCsvFileName().c_str(),\
CFile::modeWrite|CFile::shareDenyWrite|CFile::modeCreate|CFile::typeText);
if(b==FALSE)
return "";
// 第一次循环时,才输出 CSV 文件的标题头
ss.str("");
ss << "板块或股票代码," << "板块或股票名称," << "公司家数," << "总手," << "总成交金额," ;
ss << "上级板块代码," << "是否股票" << "\n";
targetFile.WriteString(ss.str().c_str());
bWriteTitle = false;
ss.str("");
ss << "1631," << "行业分类," << "0," << "0," << "0," ;
ss << "0," << "0" << "\n";
targetFile.WriteString(ss.str().c_str());
ss.str("");
ss << "1632," << "地域板块," << "0," << "0," << "0," ;
ss << "0," << "0" << "\n";
targetFile.WriteString(ss.str().c_str());
ss.str("");
ss << "1630," << "概念板块," << "0," << "0," << "0," ;
ss << "0," << "0" << "\n";
targetFile.WriteString(ss.str().c_str());
}
for(int r = 0; r< size; r++)
{
Json::Value struction = jsonRoot[r];
ss.str("");
ss << struction[0] << "," << struction[1] << "," << struction[2] << "," << struction[6] << ",";
ss << struction[7] << ",";
if(index==0)
ss << "1631";
else if(index==1)
ss << "1632";
else if(index==2)
ss << "1630";
ss << ",0" << "\n";
string test = ss.str();
targetFile.WriteString(ss.str().c_str());
vecCode.push_back(struction[0].asString());
}
ss.str("");
ss << "搜狐板块【" << index << "】获取 JSON 成功.\r\n";
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
}
}
else
{
ss.str("");
ss << "搜狐板块【" << index << "】 获取数据失败.\r\n";
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
}
}
}
}
catch (std::exception const & e)
{
ss.str("");
ss << "搜狐板块,异常" << e.what() << ' \r\n';
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
}
}
if(bWriteTitle==true)
return "";
// 开始下载各个子板块所属的股票信息
for(int i=0; i < vecCode.size(); i++)
{
string strUrl = vecCode[i];
strUrl = string("http://hq.stock.sohu.com/pl/") + strUrl + string("-1.html?uid=1512222240560727&7027194625967");
string strGBK=CUrlUtils::PostUrlOfSouhu(strUrl.c_str(),NULL);
vector<string> vecMatch;
string pattern = "<script>document.domain=\\'sohu.com\\';PEAK_ODIA=parent\\.PEAK_ODIA;</script><script>PEAK_ODIA\\(";
if(Pcre2Grep(pattern, strGBK.c_str() ,vecMatch )>0)
{
string::size_type pos = strGBK.find(vecMatch[0]);
strGBK = strGBK.substr(pos + vecMatch[0].length());
strGBK = strGBK.substr(0, strGBK.length()-10);
strGBK = ReplaceChar(strGBK, '\'', "\"");
Json::Value jsonRoot;
Json::Reader reader(Json::Features::strictMode());
bool parsingSuccessful = reader.parse(strGBK, jsonRoot);
if (!parsingSuccessful) {
ss.str("");
ss << "搜狐板块【" << vecCode[i] << "】,解析 JSON 错误 :";
ss << reader.getFormattedErrorMessages().c_str();
ss << "\r\n";
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
}
else
{
//Json::Value json_result = jsonRoot[1];
if(jsonRoot.type()== Json::arrayValue)
{
int size = jsonRoot.size();
if(size>0)
{
for(int r = 2; r< size; r++)
{
Json::Value struction = jsonRoot[r];
string strCode = struction[0].asString();
strCode = strCode.substr(3);
ss.str("");
ss << strCode << "," << struction[1] << "," << 1 << "," << struction[6] << ",";
ss << struction[7] << ",";
ss << vecCode[i] << ", 1";
ss << "\n";
string test = ss.str();
targetFile.WriteString(ss.str().c_str());
}
ss.str("");
ss << "搜狐板块【" << vecCode[i] << "】获取 JSON 成功.\r\n";
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
}
}
else
{
ss.str("");
ss << "搜狐板块【" << vecCode[i] << "】 获取数据失败. \r\n";
sendToOutput(ss.str().c_str(),m_hWnd, m_nLogType);
}
}
}
}
if(bWriteTitle==false)
{
// bWriteTitle == false, 说明本次成功下载了数据
targetFile.Flush();
targetFile.Close();
return GetCsvFileName();
}
return "";
}
string CSouhuStockPlates::GetCsvFileName()
{
CString tmp;
tmp.Format("%s/StockInfo/%s.csv" , g_strCurrentDir.c_str(), m_strEnglishName.c_str());
return string(tmp.GetBuffer());
}
void CSouhuStockPlates::ExportFromDatabase(double startTime, double endTime)
{
stringstream ss;
backend_factory const &backEnd = *soci::factory_mysql();
try
{
ss << "CSouhuStockPlates 开始从 MYSQL 获取数据......";
ss << "【" << m_nCode << "】";
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
//////////////////////////////////////////////////////////////////////////
ss.str("");
ss << "select Code, Name, Company_Number, Total_Volume, Total_Turnover, Parent_Code, Is_Stock"
<< " from SouhuStockPlates order by Is_Stock, Parent_Code, Code " ; /*order by Is_Stock, Parent_Code, Code*/
string test = ss.str();
row r;
//session sql(backEnd, m_ConnectString);
session sql(g_MysqlPool);
statement st = (sql.prepare << ss.str(),into(r)) ;
st.execute();
int cnt = 0;
while (st.fetch())
{
m_vec_code[cnt] = r.get<int>("Code");
m_vec_name[cnt] = /*Utf8_GBK*/(r.get<string>("Name"));
m_vec_company_number[cnt] = r.get<int>("Company_Number");
m_vec_total_volume[cnt] = r.get<double>("Total_Volume");
m_vec_total_turnover[cnt] = r.get<double>("Total_Turnover");
m_vec_parent_code[cnt] = r.get<int>("Parent_Code");
m_vec_is_stock[cnt] = r.get<int>("Is_Stock");
cnt++;
}
if(cnt>0)
{
m_nRowNum = cnt;
}
ss.str("");
ss << "OK, 从 MYSQL 获取数据完毕.";
ss << " 共 " << cnt << "条 \r\n" ;
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
}
catch (std::exception const & e)
{
ss.str("");
ss << e.what() << ' \r\n';
sendToOutput(ss.str().c_str(), m_hWnd, m_nLogType);
}
}
void CSouhuStockPlates::NotifyDatabaseImportedToWindow()
{
stringstream ss;
/*ss << "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
ss << "<root>";
ss << "<msg_type code=\"" << m_nCode << "\" ";
ss << " model=\"" << ModelType() << "\" ";
ss << " >DatabaseImported</msg_type>";
ss << "<data " ;
if(m_vec_close.size()>0)
{
ss << " param1=\"" << m_vec_report_date[0] << "\" ";
ss << " param2=\"" << Double2String(m_vec_close[0]) << "\" ";
}
ss << " >";
ss << "</data></root>";*/
sendToOutput(ss.str().c_str(), m_hWnd);
}
CStockPlateTree * CSouhuStockPlates::GenerateTree()
{
CStockPlateTree * pTree = new CStockPlateTree;
CStockPlateTree * pNode = pTree;
for(int i=0; i<m_vec_code.size(); i++)
{
CStockPlateData treeNode;
treeNode.code = Int2String(m_vec_code[i], m_vec_is_stock[i]==1? "%06d":"%08d");
treeNode.name = m_vec_name[i];
treeNode.company_number = m_vec_company_number[i];
treeNode.total_turnover = m_vec_total_turnover[i];
treeNode.total_volume = m_vec_total_volume[i];
treeNode.is_stock = m_vec_is_stock[i];
CStockPlateData treeNodeParent;
treeNodeParent.code = Int2String(m_vec_parent_code[i], "%08d");
treeNodeParent.is_stock = 0;
if(pNode)
{
CStockPlateData spd = *pNode->get();
if(spd.code != treeNodeParent.code || spd.is_stock!=0)
pNode = NULL;
}
if(pNode==NULL)
pNode = pTree->SearchSpecialNode(treeNodeParent);
if(pNode)
{
pNode->insert(treeNode);
}
else
{
pTree->insert(treeNode);
}
}
return pTree;
}
vector<CStockPlateData> CSouhuStockPlates::FetchDataFromTree(CStockPlateTree * pPlates, int nPlateCode)
{
vector<CStockPlateData> vecStockPlateData;
if(pPlates)
{
// 以某个节点为根,进行子树的搜索
CStockPlateData treeNode;
treeNode.code = Int2String(nPlateCode, "%08d");
treeNode.is_stock = 0;
CStockPlateTree * pNode = pPlates->SearchSpecialNode(treeNode);
if(pNode==NULL)
pNode = pPlates;
if(pNode)
{
// 该节点为根节点
CStockPlateData spd = *pNode->get();
spd.code = Int2String(nPlateCode, "%08d");
spd.parent_code = "-1";
spd.is_stock = 0;
if(spd.name.empty())
spd.name = "根目录";
vecStockPlateData.push_back(spd);
CStockPlateTree::pre_order_iterator pre_order_it = pNode->pre_order_begin();
while(pre_order_it!=pNode->pre_order_end())
{
CStockPlateData spd = *pre_order_it;
if(pre_order_it.node()->parent()->is_root()==false)
{
spd.parent_code = pre_order_it.node()->parent()->get()->code;
}
else
{
spd.parent_code = Int2String(nPlateCode, "%08d");
}
vecStockPlateData.push_back(spd);
pre_order_it++;
}
}
}
return vecStockPlateData;
} |
19363867dc60a0b5f9feb708803b42c514c6d4aa | cd6271e74aa829d13d3438e1f57638acef741a54 | /include/Vec3.h | da50fc4c420db3cbbb4eb31f7657ffeb6ba52ee6 | [] | no_license | damiano-massarelli/dCloth | d96d0589add48f264fbca515bf04c22bce27df90 | c3fcf3ac4ff0e88ad06b64cde545fd3efedac265 | refs/heads/master | 2020-05-04T15:54:03.281599 | 2019-04-04T12:20:33 | 2019-04-04T12:20:33 | 179,260,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | h | Vec3.h | #ifndef VEC3_H
#define VEC3_H
#include <ostream>
struct Vec3 {
float x = 0;
float y = 0;
float z = 0;
Vec3 operator-(const Vec3& v) const;
Vec3 operator+(const Vec3& v) const;
float length() const;
float distanceTo(const Vec3& v) const;
void normalize();
Vec3 operator*(float s) const;
Vec3 operator/(float s) const;
};
std::ostream& operator<<(std::ostream& out, const Vec3& v);
#endif // VEC3_H
|
efc954349ed446369e8a57daee90b154735e8845 | a6e9463a5c48e0e7c4ac1da362845ba51af341fc | /include/coffee_machine/behavior_tree.h | e441187c884b62f29a7687e20f2cd9bd1f6c75ed | [] | no_license | easyrobotic/coffee_machine | 36ad8456e24b1c2a1b4f2e6b5502daa7681e65b3 | 018546abcbc6bfd2b8b9e77fe07978b125667a5a | refs/heads/master | 2023-02-15T10:11:31.073294 | 2021-01-09T16:38:21 | 2021-01-09T16:38:21 | 293,077,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 409 | h | behavior_tree.h |
#include "behaviortree_cpp_v3/behavior_tree.h"
#include "behaviortree_cpp_v3/bt_factory.h"
#include <iostream>
namespace CoffeMachineNS{
BT::NodeStatus IsMachineOpen();
BT::NodeStatus IsCleanCupReady();
class CoffeMachine
{
public:
CoffeMachine() : _opened(true)
{
}
BT::NodeStatus open();
BT::NodeStatus close();
private:
bool _opened;
};
}
|
9deb7462d5327cc7d48f525664fb3fd5bf81dbb6 | 1753460630f6ca3c3799ef9d8dc56bde6c621a34 | /msvc10/AddressListDialog.h | d1992b0edc62a6ae515ab95c78265bb62fd8e13e | [] | no_license | liugming531/CallingShow | 88e955b9fcc6209c0061b7b632bfa7429fd04c58 | a7e09a96e04d18bd23521e36b4adc5f4090ed32b | refs/heads/master | 2021-01-22T06:01:50.356499 | 2017-02-20T08:38:10 | 2017-02-20T08:38:10 | 81,728,532 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 617 | h | AddressListDialog.h | #pragma once
#include "afxcmn.h"
// CAddressListDialog 对话框
class CAddressListDialog : public CDialog
{
DECLARE_DYNAMIC(CAddressListDialog)
public:
CAddressListDialog(CWnd* pParent = NULL); // 标准构造函数
virtual ~CAddressListDialog();
// 对话框数据
enum { IDD = IDD_ADDRESSLIST_DIALOG };
void SetType(int type){ addr_type = type; }
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
private:
CListCtrl m_list_info;
//0-企业通讯录 1-个人通讯录 2-企业内部通讯录
int addr_type;
};
|
f198881269fa1ad852a9b7930a9da87ae2d42d0c | fca16f6b7838bd515de786cf6e8c01aee348c1f9 | /fps2015aels/uilibgp2015/OGL/Select/Option.h | 768fc2535ccb58202b5845ef31182031a48924de | [] | no_license | antoinechene/FPS-openGL | 0de726658ffa278289fd89c1410c490b3dad7f54 | c7b3cbca8c6dc4f190dc92a273fe1b8ed74b7900 | refs/heads/master | 2020-04-06T07:01:17.983451 | 2012-09-06T14:06:25 | 2012-09-06T14:06:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 719 | h | Option.h | #ifndef __OPTION_H__
#define __OPTION_H__
#include "../Drawable/Drawable.h"
#include "../Label/Label.h"
namespace ID
{
class Option : public Drawable
{
public:
Option(int value,
void* font, char* text,
Color* fg = (Color*)&COLOR_BLACK);
Option(const Option& button);
virtual ~Option(void);
virtual int RefreshSurface(int x, int y);
void SetLabel(Label* label);
Label* GetLabel(void) const;
void SetLabelPos(int16_t x, int16_t y);
void SetLabelPos(REL_POS_TYPE);
void GetLabelPos(int16_t* x, int16_t* y) const;
REL_POS_TYPE GetLabelRelPos(void) const;
int GetValue(void) const;
void SetValue(int);
private:
int __value;
Label* __label;
};
}
#endif
|
4d1f487c7dcb5b0b5947ba3c1aba983b7a19e153 | 24da289dc12ac1eb7d65f9573c31b3a3befa9d5f | /problemes/probleme321.cpp | 20e9e66bfc928dab79da351d958219d202aafa41 | [
"MIT"
] | permissive | ZongoForSpeed/ProjectEuler | a69cf3fda3d792d786ef1e11d9c3ed2fdf0eb047 | d2299f9f4ea0054160782d545e0abb7df35fa782 | refs/heads/master | 2023-09-04T07:59:59.037694 | 2023-08-31T22:40:48 | 2023-08-31T22:40:48 | 40,210,928 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,500 | cpp | probleme321.cpp | #include <numeric>
#include "problemes.h"
#include "utilitaires.h"
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;
ENREGISTRER_PROBLEME(321, "Swapping Counters") {
// A horizontal row comprising of 2n + 1 squares has n red counters placed at one end and n blue counters at the
// other end, being separated by a single empty square in the centre. For example, when n = 3.
//
// p321_swapping_counters_1.gif
// A counter can move from one square to the next (slide) or can jump over another counter (hop) as long as the
// square next to that counter is unoccupied.
//
// p321_swapping_counters_2.gif
// Let M(n) represent the minimum number of moves/actions to completely reverse the positions of the coloured
// counters; that is, move all the red counters to the right and all the blue counters to the left.
//
// It can be verified M(3) = 15, which also happens to be a triangle number.
//
// If we create a sequence based on the values of n for which M(n) is a triangle number then the first five terms
// would be:
// 1, 3, 10, 22, and 63, and their sum would be 99.
//
// Find the sum of the first forty terms of this sequence.
size_t limite = 40;
// M(n) = n.(n+2) = t.(t+1)/2
// 2*n*(n+2) = t.(t+1)
// 2X² + 4X - Y² - Y = 0
// Xn+1 = 3 Xn + 2 Yn + 3
// Yn+1 = 4 Xn + 3 Yn + 5
vecteur solutions;
{
std::pair<nombre, nombre> s(0, 0);
for (size_t i = 0; i < limite; ++i) {
nombre Xn = s.first;
nombre Yn = s.second;
nombre X1 = 3 * Xn + 2 * Yn + 3;
nombre Y1 = 4 * Xn + 3 * Yn + 5;
s = std::make_pair(X1, Y1);
solutions.push_back(s.first);
// std::cout << s << std::endl;
}
}
{
std::pair<nombre, nombre> s(1, 2);
solutions.push_back(s.first);
for (size_t i = 0; i < limite; ++i) {
nombre Xn = s.first;
nombre Yn = s.second;
nombre X1 = 3 * Xn + 2 * Yn + 3;
nombre Y1 = 4 * Xn + 3 * Yn + 5;
s = std::make_pair(X1, Y1);
solutions.push_back(s.first);
// std::cout << s << std::endl;
}
}
std::sort(solutions.begin(), solutions.end());
// std::cout << solutions << std::endl;
nombre resultat = std::reduce(solutions.begin(), std::next(solutions.begin(), limite));
return std::to_string(resultat);
}
|
60fcfb2ee1e9689c450d9d703d5838331143e86d | a0e84f8285757e4f39a330b9f70ae9d50dce2495 | /LibCarla/source/carla/road/element/LaneMarking.cpp | 76714ae0a7096678a602836b7a73ab490bdebcbe | [
"MIT",
"CC-BY-4.0",
"LGPL-2.1-only"
] | permissive | germanros1987/carla | 61e4014a6e8818fef3783ed7aba0df6da8485f6c | b7d98000b7f75a9404788ebf6bfa8d7f00eef50d | refs/heads/master | 2020-03-18T22:53:04.725832 | 2020-01-09T18:09:34 | 2020-01-09T18:09:34 | 135,371,141 | 2 | 0 | MIT | 2019-02-26T02:42:42 | 2018-05-30T01:25:21 | C++ | UTF-8 | C++ | false | false | 2,714 | cpp | LaneMarking.cpp | // Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "carla/road/element/LaneMarking.h"
#include "carla/Exception.h"
#include "carla/StringUtil.h"
#include "carla/road/element/RoadInfoMarkRecord.h"
namespace carla {
namespace road {
namespace element {
static LaneMarking::Type GetType(std::string str) {
StringUtil::ToLower(str);
if (str == "broken") {
return LaneMarking::Type::Broken;
} else if (str == "solid") {
return LaneMarking::Type::Solid;
} else if (str == "solid solid") {
return LaneMarking::Type::SolidSolid;
} else if (str == "solid broken") {
return LaneMarking::Type::SolidBroken;
} else if (str == "broken solid") {
return LaneMarking::Type::BrokenSolid;
} else if (str == "broken broken") {
return LaneMarking::Type::BrokenBroken;
} else if (str == "botts dots") {
return LaneMarking::Type::BottsDots;
} else if (str == "grass") {
return LaneMarking::Type::Grass;
} else if (str == "curb") {
return LaneMarking::Type::Curb;
} else if (str == "none") {
return LaneMarking::Type::None;
} else {
return LaneMarking::Type::Other;
}
}
static LaneMarking::Color GetColor(std::string str) {
StringUtil::ToLower(str);
if (str == "standard") {
return LaneMarking::Color::Standard;
} else if (str == "blue") {
return LaneMarking::Color::Blue;
} else if (str == "green") {
return LaneMarking::Color::Green;
} else if (str == "red") {
return LaneMarking::Color::Red;
} else if (str == "white") {
return LaneMarking::Color::White;
} else if (str == "yellow") {
return LaneMarking::Color::Yellow;
} else {
return LaneMarking::Color::Other;
}
}
static LaneMarking::LaneChange GetLaneChange(RoadInfoMarkRecord::LaneChange lane_change) {
switch (lane_change) {
case RoadInfoMarkRecord::LaneChange::Increase:
return LaneMarking::LaneChange::Right;
case RoadInfoMarkRecord::LaneChange::Decrease:
return LaneMarking::LaneChange::Left;
case RoadInfoMarkRecord::LaneChange::Both:
return LaneMarking::LaneChange::Both;
default:
return LaneMarking::LaneChange::None;
}
}
LaneMarking::LaneMarking(const RoadInfoMarkRecord &info)
: type(GetType(info.GetType())),
color(GetColor(info.GetColor())),
lane_change(GetLaneChange(info.GetLaneChange())),
width(info.GetWidth()) {}
} // namespace element
} // namespace road
} // namespace carla
|
440d7d33c07e2be4233dcc38f36d1ef51b76280c | 3db9a02ffad9561136d017e2e84e3135f4f5de10 | /Pixeland/Spritesheet.cpp | 6fb8424418678a8c8e5895fcdd26767462e1b556 | [] | no_license | Solocat/Pixeland | 53eca10083a37f1dee3c5e3be0cfe51591641d06 | 3378450268917fc8899b5827cd924b8f3174ab32 | refs/heads/master | 2020-08-27T21:27:25.407489 | 2019-11-22T11:53:22 | 2019-11-22T11:53:22 | 217,492,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,046 | cpp | Spritesheet.cpp | #include "Spritesheet.h"
using namespace std;
Spritesheet::Spritesheet()
{
tileWidth = 0;
tileHeight = 0;
}
Spritesheet::Spritesheet(string _file, int _tileWidth, int _tileHeight, bool alpha)
{
makeSheet(_file, _tileWidth, _tileHeight, alpha);
}
Spritesheet::~Spritesheet()
{
}
void Spritesheet::makeSheet(string _file, int _tileWidth, int _tileHeight, bool alpha)
{
tileWidth = _tileWidth;
tileHeight = _tileHeight;
cout << "Loading " << _file.c_str() << "... ";
if (alpha)
{
sf::Image img;
if (!img.loadFromFile(_file))
{
cout << "Loading failed" << endl;
return;
}
img.createMaskFromColor(sf::Color::Black);
fullTex.loadFromImage(img);
}
else if (!fullTex.loadFromFile(_file))
{
cout << "Loading failed" << endl;
return;
}
cout << "Ok" << endl;
}
sf::IntRect Spritesheet::getRect(unsigned i)
{
sf::IntRect recto;
recto.width = tileWidth;
recto.height = tileHeight;
unsigned pix = i * tileWidth;
recto.left = pix % fullTex.getSize().x;
recto.top = pix / fullTex.getSize().y;
return recto;
} |
7bde19ecfed246f08c40cfd9237fe52cccce9334 | 5df35d81902a17e80424913186d1fd69939ab099 | /MonkeyCatch/制作環境/MonkeyCatch/scene.h | 3e3f508818fbdaed33808083f07c44f56b7fe215 | [] | no_license | takeuchiwataru/TakeuchiWataru | 3ec5646cfe8931a5be36f1e59e7bdd2f1d717ad4 | e8944112f299e77151e3538f785b2cea5f96d356 | refs/heads/master | 2020-05-17T07:35:38.500004 | 2019-10-29T06:50:16 | 2019-10-29T06:50:16 | 183,582,190 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,097 | h | scene.h | //=============================================================================
//
// オブジェクト処理 [scene.h]
// Author : 竹内亘
//
//=============================================================================
#ifndef _SCENE_H_
#define _SCENE_H_
#include "main.h"
//*****************************************************************************
// マクロ定義
//*****************************************************************************
#define NUM_PRIORITY (8)
//*****************************************************************************
// クラスの定義
//*****************************************************************************
class CScene
{
public:
typedef enum
{// オブジェクトの種類
OBJTYPE_NONE = 0,
OBJTYPE_2D,
OBJTYPE_3D,
OBJTYPE_X,
OBJTYPE_BILLBOARD,
OBJTYPE_PLAYER,
OBJTYPE_ENEMY,
OBJTYPE_OBJECT,
OBJTYPE_GRASS,
OBJTYPE_ITEM,
OBJTYPE_FRAME,
OBJTYPE_PARTICLE,
OBJTYPE_MAX
}OBJTYPE;
CScene(int nPriority = 3, OBJTYPE objType = OBJTYPE_NONE);
virtual ~CScene();
virtual HRESULT Init(D3DXVECTOR3 pos) = 0;
virtual void Uninit(void) = 0;
virtual void Update(void) = 0;
virtual void Draw(void) = 0;
void SetObjType(OBJTYPE ObjType);
OBJTYPE GetObjType(void);
CScene *GetTop(int nPriority = 3);
CScene *GetNext(void);
bool GetDeath(void);
// 静的メンバ関数
static void ReleseAll(void);
static void UpdateAll(void);
static void DrawAll(void);
void UninitAll(int nPriority);
protected:
void Release(void);
CScene * m_pNext; // 次のオブジェクトへのポインタ
private:
static CScene * m_apTop[NUM_PRIORITY]; // 先頭のオブジェクトへのポインタ
static CScene * m_apCur[NUM_PRIORITY]; // 現在(最後尾)のオブジェクトへのポインタ
CScene * m_pPrev; // 前のオブジェクトへのポインタ
int m_nPriority; // 優先順位の番号
OBJTYPE m_objType; // オブジェクトの種類
bool m_bDeath; // 死亡フラグ
static int m_nNumAll;
static int m_nNumPriority[NUM_PRIORITY];
int m_nID; // 自分自身の番号
};
#endif |
27e8163f37f13d0c90a393966315f137a682f0cf | 4af76538543201ee3013151d3b70368c2e496366 | /primos gemelos.cpp | e70906594d1a8da0765e0b6a6cd7aaed528440ef | [] | no_license | Eder-Monsalve/Paradigmas-de-Programacion | 579c34f07e56249077cc5bb9bf723826b1eddc08 | 68d6f68eba7cb07c198c2940b059af48d9009ae8 | refs/heads/main | 2023-08-07T13:30:46.295139 | 2021-09-18T17:19:05 | 2021-09-18T17:19:05 | 346,846,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,700 | cpp | primos gemelos.cpp | /// Modulo para Primos Gemelos y Primos Felices
// Autor: Todos
// 24/07/2021
#include <math.h>
#include <iostream>
using namespace std;
void primosGemelos(void);
bool esPrimo(int numero);
int moduloDigitos(int n);
void primoFeliz(void);
int main()
{
cout<<"\n\n\t\t Primos Gemelos ";
primosGemelos();
primoFeliz();
return 0;
}
bool esPrimo(int numero){
int i;
if(numero==0 or numero==1){
return false;
}else{
for(i = 2;i < numero; i++){
if(numero % i==0){
return false;
}
} return true;
}
}
void primosGemelos(void){
int i;
int n;
cout<< "\n Ingrese Numero \n";
cin>> n;
while(n<2 or n>35000){
cout<< "\n Ingrese numero valido 2-35000";
cin>> n;
}
for(i = 2 ; i < n; i++){
if(esPrimo(i)==true and esPrimo(i+2)==true){
cout<<"\n "<< i <<" "<< i + 2<<" Son Gemelos";
}
}
}
int moduloDigitos(int n){
int d1,d2,d3,d4;
int cociente;
int suma;
d1=0;
d2=0;
d3=0;
d4=0;
d1= n % 10;
cociente = n /10;
d2= cociente % 10;
cociente = cociente /10;
d3= cociente % 10;
cociente = cociente /10;
d4= cociente % 10;
suma= d1*d1+d2*d2+d3*d3+d4*d4;
return suma;
}
void primoFeliz(void){
int numero;
int i;
int suma;
cout<<"\n Ingrese un numero \n";
cin>> numero;
while(numero <= 9 or numero >=10000){
cout<<"Ingrese numero valido 10-9999";
cin>>numero;
}
i=1;
if(esPrimo(numero)==true){
suma=numero;
do{
suma=moduloDigitos(suma);
cout<< " suma " << suma;
system ("pause");
i++;
}while(suma>10 and i<100);
if (suma==1){
cout<< numero << "\n Es un Primo Feliz";
}else
cout<< numero << "\n No es un Primo Feliz";
}
else
cout<< numero << "\n No es Primo";
}
|
85afcb72e6ad2337617a179cbc84811b1f193089 | 0f399c573b88ef5ea3fffd3c475059ec694583bb | /18_4Sum.cpp | d0e9f3b2a5c307a80846d40db1068f9a360d4111 | [] | no_license | EasonQiu/LeetCode | 31075bc2ca28d23509e290b4935949500e1fec24 | 5be348261bb5f45e471de3f44dd2f57ec671ffcf | refs/heads/master | 2021-01-12T22:21:30.725971 | 2017-09-22T02:42:53 | 2017-09-22T02:42:53 | 68,566,605 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,348 | cpp | 18_4Sum.cpp | // Given an array S of n integers, are there elements a, b, c, and d in S
// such that a + b + c + d = target? Find all unique quadruplets in the array
// which gives the sum of target.
// Note: The solution set must not contain duplicate quadruplets.
// For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
// A solution set is:
// [
// [-1, 0, 0, 1],
// [-2, -1, 1, 2],
// [-2, 0, 0, 2]
// ]
// 解法:先排序,然后固定第一个元素(不同),接着用2sum的方法对撞型指针搜索
// 写的时候不要忘了排序!!
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
if (nums.size() < 4) return vector<vector<int> >();
int size = nums.size();
vector<vector<int> > ans;
sort(nums.begin(), nums.end());
for (int i = 0; i < size - 3; ++i) {
// de-duplicate & prune
if (i != 0 && nums[i] == nums[i - 1]) continue;
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
if (nums[i] + nums[size - 3] + nums[size - 2] + nums[size - 1] < target) continue;
int target1 = target - nums[i];
// 3 Sum
for (int j = i + 1; j < size - 2; ++j) {
// de-duplicate & prune
if (j != i + 1 && nums[j] == nums[j - 1]) continue;
if (nums[j] + nums[j + 1] + nums[j + 2] > target1) break;
if (nums[j] + nums[size - 2] + nums[size - 1] < target1) continue;
int target2 = target1 - nums[j];
// 2 Sum
int low = j + 1, high = size - 1;
while (low < high) {
if (nums[low] + nums[high] == target2) {
ans.push_back(vector<int>{nums[i], nums[j], nums[low], nums[high]});
while (low < high && nums[low + 1] == nums[low]) ++low;
while (low < high && nums[high - 1] == nums[high]) --high;
++low; --high;
} else if (nums[low] + nums[high] < target2) {
++low;
} else {
--high;
}
}
}
}
return ans;
}
};
int main() {
vector<int> nums = {1, 0, -1, 0, -2, 2};
Solution sol;
vector<vector<int> > ans = sol.fourSum(nums, 0);
for (vector<int> vec : ans) {
for (int n : vec) cout << n << " ";
cout << endl;
}
return 0;
} |
0c5fba106d8a3d0581ac2d71f9d93aacfd982809 | e87e3f13fbc670e8cdb5a9dc0040237e145750a1 | /thread_local.hpp | af36a6ea6d895b7e2cd56d9a7b189a72843ac155 | [] | no_license | sleepiforest/ThreadLocal | fa1f8a0fb06a8afc9acee2cf755f13bf71300f0f | 37d82edc406171a3675cb3d58ec2f61fcd282190 | refs/heads/master | 2020-04-07T09:08:38.818126 | 2018-05-09T03:03:26 | 2018-05-09T03:03:26 | 124,199,197 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | hpp | thread_local.hpp | #pragma once
#include <pthread.h>
#include <stdint.h>
#include <assert.h>
template<typename T>
class ThreadLocal
{
public:
ThreadLocal() {
pthread_key_create(&data, DeleteData);
}
~ThreadLocal()
{
pthread_key_delete(data);
}
template<typename... Args>
T & GetData(const Args &... args)
{
T * data_ptr = (T*) pthread_getspecific(data);
if( data_ptr == NULL )
{
data_ptr = new T(args...);
pthread_setspecific(data, data_ptr);
}
assert(data_ptr != NULL);
return *data_ptr;
}
template<typename... Args>
static T & Instance(const Args &... args)
{
static ThreadLocal s_obj;
return s_obj.GetData(args...);
}
private:
static void DeleteData(void * ctx_ptr)
{
delete (T*)ctx_ptr;
}
private:
pthread_key_t data;
};
|
7b13b5b4b4c45cc57e0e7c64ae12afa0d7eaf0da | 6e6ff309bb84e07b59523b6bf97c95357b704d3c | /assignment_package/src/scene/terrain.cpp | f81f15a51bf77a52baaaafde6065c457553668af | [] | no_license | tatran5/Mini-Minecraft | 1fe7babe82a925946866011e8778cdcbe5488012 | 98a0b8a257122e59f7d530a9fdf03c9ba8c158c1 | refs/heads/master | 2022-11-16T03:47:15.498170 | 2020-07-07T05:09:31 | 2020-07-07T05:09:31 | 277,722,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90,109 | cpp | terrain.cpp | #include <scene/terrain.h>
#include <scene/cube.h>
#include <iostream>
#include <string>
#include <QThreadPool>
#include <scene/worker.h>
#include <glm/gtx/random.hpp>
Terrain::Terrain(OpenGLContext* context) : context(context), dimensions(64, 256, 64), numElementsAddedWithExpand(0)
{}
BlockType Terrain::getBlockAt(int x, int y, int z) const
{
float xCoord = x - x % 16;
float zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
uint64_t xzCoord = (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
auto search = chunkMap.find(xzCoord);
if (search != chunkMap.end())
{
return chunkMap.value(xzCoord)->blockAt(x - xCoord, y, z - zCoord);
}
return EMPTY;
}
bool Terrain::chunkExistsAt(int x, int y, int z) {
float xCoord = x - x % 16;
float zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
uint64_t xzCoord = (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
auto search = chunkMap.find(xzCoord);
return chunkMap.contains(xzCoord);
}
Chunk* Terrain::getChunkAt(int x, int z) {
int xCoord = x - x % 16;
int zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
uint64_t xzCoord = (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
if (chunkMap.contains(xzCoord))
{
return chunkMap.value(xzCoord);
}
return nullptr;
}
void Terrain::setBlockAt(int x, int y, int z, BlockType t)
{
bool usedChunk = false;
float xCoord = x - x % 16;
float zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
uint64_t xzCoord = (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
auto search = chunkMap.find(xzCoord);
if (search != chunkMap.end())
{
chunkMap.value(xzCoord)->blockAt(x - xCoord, y, z - zCoord) = t;
usedChunk = true;
toCreate.insert(chunkMap.value(xzCoord));
}
}
void Terrain :: fillChunk(Chunk &chunk) {
for (int x = 0; x < 16; x++) {
for(int z = 0; z < 16; z++ ) {
float heightTest = fmin(254, fbm((chunk.xzCoords.x + x) / 160.f, (chunk.xzCoords.y + z) / 160.f) * 32.f + 129.f);
chunk.fillBetween(x,z,0,128,STONE);
chunk.fillBetween(x,z,129,heightTest,DIRT);
chunk.blockAt(x,heightTest + 1, z) = GRASS;
}
}
}
void Terrain :: fillChunkBiome(Chunk& chunk) {
// chunkbounds : x = minX, y = maxX, z = minZ, w = maxZ
for (int currX = 0; currX < 16; currX++)
{
for (int currZ = 0; currZ < 16; currZ++)
{
float x = chunk.xzCoords.x + currX;
float z = chunk.xzCoords.y + currZ;
chunk.fillBetween(currX, currZ, 0,128,STONE);
//---------------------------------------
//BIOME & WORLEY
//---------------------------------------
int numBiome = 3;
float cellSize = 50.f; //each cell spans #cellSize blocks
//get the cell location that the current block is located within
int curBlockCellLocX = glm::floor(x / cellSize);
int curBlockCellLocZ = glm::floor(z / cellSize);
BlockType curBlockType = BEDROCK; //for debug
// Want the block to be of the type of the closest "heart"
// Want to check how close the "heart" is to the block and what type of block it is
float distToClosestHeart = 999999999.f;
float distToNextClosestHeart = 999999999.f;
int modClosestHeartResult = 0; //helps to determine what blocktype of the heart block is
int modNextClosestHeartResult = 0;
glm::vec2 locClosestHeart;
glm::vec2 locNextClosestHeart;
//iterate throught 9 cells (8 surrounding and itself)
for (int curCellX = curBlockCellLocX - 1;
curCellX <= curBlockCellLocX + 1; curCellX ++) {
for (int curCellZ = curBlockCellLocZ - 1;
curCellZ <= curBlockCellLocZ + 1; curCellZ ++) {
//the input to random2 is converted back to block size
glm::vec2 heartCurCellLoc =
glm::vec2(curCellX * cellSize, curCellZ * cellSize) +
cellSize * random2(glm::vec2(curCellX, curCellZ));
// Check if the location of this block is closer than
// the closest distance from this block to any hearts of cells
float distToCurHeart = glm::length(heartCurCellLoc - glm::vec2(x, z));
// If the location of this block is closer to this heart than previous hearts,
// set the current block to be the same as this heart's block type
if (distToCurHeart < distToClosestHeart){
modNextClosestHeartResult = modClosestHeartResult;
modClosestHeartResult = glm::mod( ((int)heartCurCellLoc.x +
(int)heartCurCellLoc.y), numBiome);
distToNextClosestHeart = distToClosestHeart;
distToClosestHeart = distToCurHeart;
locNextClosestHeart = locClosestHeart;
locClosestHeart = heartCurCellLoc;
}
}
}
//avoid negative modulo values
modClosestHeartResult = glm::abs(modClosestHeartResult);
modNextClosestHeartResult = glm::abs(modNextClosestHeartResult);
// Decide block texture ----------------------------------------------------------------------------
// (modHeartToUse, distToUse, locToUse) corresponds to the same heart that determines the type
// of biome that the current block belongs to
// It can be either the closest heart, or the next closest heart
int modHeartToUse = modClosestHeartResult; // marks the biome that the current block is of
int modHeartNotToUse = modNextClosestHeartResult;
float distToUse = distToClosestHeart;
float distNotToUse = distToNextClosestHeart;
glm::vec2 locToUse = locClosestHeart;
glm::vec2 locNotToUse = locNextClosestHeart;
// To create transition between biomes
// If distance to closest heart is further away than constant * cellSize, the chance of this
// block being the same biome as the closest heart's dependes on how far away it is. If
// it is not the same as the closest heart's,
if (distToClosestHeart > 0.43 * (distToClosestHeart + distToNextClosestHeart)) {
// Arbitrary functions to determine which block it should be
// Returns a value from 0 - 100
float randVal = rand() % 100;
if (randVal < 49) {
modHeartToUse = modNextClosestHeartResult;
modHeartNotToUse = modClosestHeartResult;
distToUse = distToNextClosestHeart;
distNotToUse = distToClosestHeart;
locToUse = locNextClosestHeart;
locNotToUse = locClosestHeart;
}
}
//--------------------------------------------------------------------------
// From the result of modulo, decides which biomes to belong to;
if (modHeartToUse == 2) {
curBlockType = SNOW;
} else if (modHeartToUse == 1) {
curBlockType = GRASS;
} else {
curBlockType == SAND;
}
// --------------------------------------------------------------
//TRYWORKING
float heightToUse;
float heightNotToUse;
// Find the height of the heart of the biome which this current block is the same type with
if (modHeartToUse == 2) {
heightToUse = fmin(254, fbm(locToUse.x / 160.f, locToUse.y / 160.f) * 40.f + 129.f);
} else if (modHeartToUse == 1) {
heightToUse = fmin(254, fbm(locToUse.x / 160.f, locToUse.y / 160.f) * 30.f + 129.f);
} else {
heightToUse = fmin(254, fbm(locToUse.x / 160.f, locToUse.y / 160.f) * 27.f + 129.f);
}
// Find the height of the next closest heart of which this current block is potentially
// not the same type with
if (modHeartNotToUse != modHeartToUse) {
if (modHeartNotToUse == 2) {
heightNotToUse = fmin(254, fbm(locNotToUse.x / 160.f,
locNotToUse.y / 160.f) * 40.f + 129.f);
} else if (modHeartNotToUse == 1) {
heightNotToUse = fmin(254, fbm(locNotToUse.x / 160.f,
locNotToUse.y / 160.f) * 30.f + 129.f);
} else {
heightNotToUse = fmin(254, fbm(locNotToUse.x / 160.f,
locNotToUse.y / 160.f) * 27.f + 129.f);
}
}
// Interpolate the height of the block when the two closest hearts are of different biomes type
float heightCurBlock;
if (modHeartNotToUse != modHeartToUse &&
distToClosestHeart > 0.43 * (distToClosestHeart + distToNextClosestHeart)) {
heightCurBlock = glm::mix(heightToUse, heightNotToUse, distToUse / (distToUse + distNotToUse));
} else {
if (modHeartToUse == 2) {
heightCurBlock = fmin(254, fbm(x / 160.f, z / 160.f) * 40.f + 129.f);
} else if (modHeartToUse == 1) {
heightCurBlock = fmin(254, fbm(x / 160.f, z / 160.f) * 30.f + 129.f);
} else {
heightCurBlock = fmin(254, fbm(x / 160.f, z / 160.f) * 27.f + 129.f);
}
}
if (curBlockType == GRASS) {
chunk.fillBetween(currX, currZ, 129, heightCurBlock, DIRT);
} else if (curBlockType == SAND) {
chunk.fillBetween(currX, currZ, 129, heightCurBlock, SAND);
} else {
chunk.fillBetween(currX, currZ, 129, heightCurBlock, BEDROCK);
}
chunk.blockAt(currX, heightCurBlock + 1, currZ) = curBlockType; //----biome
}
}
}
Chunk* Terrain :: makeChunkAtList(int x, int z, QHash <uint64_t, Chunk*>& newChunks) {
bool usedChunk = false;
float xCoord = x - x % 16;
float zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
uint64_t xzCoord = (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
auto search = chunkMap.find(xzCoord);
if (chunkMap.contains(xzCoord) || chunkList.contains(xzCoord))
{
return nullptr;
}
Chunk* newChunk = new Chunk(context);
//take mod of 16 to determine nearest multiple of 16, coordinate at which to create new chunk
newChunk->xzCoords = glm::vec2(xCoord, zCoord);
newChunk->xzCoord = xzCoord;
//newChunk->blockAt(x - xCoord, y, z - zCoord) = t;
fillChunkBiome(*newChunk);
newChunks.insert(xzCoord, newChunk);
// adding to chunk map
//recreate.insert(newChunk);
return newChunk;
}
void Terrain :: setBlockAtNewChunks(int x, int y, int z, BlockType t, QHash<uint64_t, Chunk *> &newChunks) {
// std::cout << "trying to set block at" << x << ", " << y << ", " << z << "\n";
bool usedChunk = false;
int xCoord = x - x % 16;
int zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
uint64_t xzCoord = (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
if(newChunks.contains(xzCoord)) {
newChunks.value(xzCoord)->blockAt(x - xCoord, y, z - zCoord) = t;
//toCreate.insert(newChunks.value(xzCoord));
}
}
Terrain::~Terrain() {
for(auto p = chunkMap.begin(); p != chunkMap.end(); p++) {
delete p.value();
}
}
void Terrain::fillBetweenNewChunks(int x, int z, int bottomLimit, int topLimit, BlockType t, QHash <uint64_t, Chunk*>& newChunks)
{
float xCoord = x - x % 16;
float zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
// uint64_t xzCoord = (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
// if(!chunkMap.contains(xzCoord)) {
// return;
// }
for (int i = bottomLimit; i <= topLimit; ++i)
{
setBlockAtNewChunks(x, i, z, t, newChunks);
}
}
void Terrain::fillBetweenList(int x, int z, int bottomLimit, int topLimit, BlockType t)
{
for (int i = bottomLimit; i <= topLimit; ++i)
{
// setBlockAtNewChunks(x, i, z, t);
}
}
uint64_t xzCoord(int x, int z) {
float xCoord = x - x % 16;
float zCoord = z - z % 16;
if(x < 0 && x % 16 != 0) {
xCoord = x - (x % 16 + 16);
}
if (z < 0 && z % 16 != 0) {
zCoord = z - (z % 16 + 16);
}
return (static_cast<uint64_t> (xCoord) << 32) | (static_cast<uint64_t> (zCoord) & 0x00000000FFFFFFFF);
}
// Fractal Brownian Motion for random height field generation
float rand(glm::vec2 n) {
return (glm::fract(sin(glm::dot(n + glm::vec2(91.2328, -19.8232), glm::vec2(12.9898, 4.1414))) * 43758.5453));
}
float cosineInterpolate(float a, float b, float x)
{
float ft = x * 3.1415927;
float f = (1 - cos(ft)) * .5;
return a*(1-f) + b*f;
}
float interpNoise2D(float x, float z)
{
float intX = floor(x);
float fractX = glm::fract(x);
float intZ = floor(z);
float fractZ = glm::fract(z);
float v1 = rand(glm::vec2(intX, intZ));
float v2 = rand(glm::vec2(intX + 1, intZ));
float v3 = rand(glm::vec2(intX, intZ + 1));
float v4 = rand(glm::vec2(intX + 1, intZ + 1));
float i1 = cosineInterpolate(v1, v2, fractX);
float i2 = cosineInterpolate(v3, v4, fractX);
return cosineInterpolate(i1, i2, fractZ);
}
float fbm(float x, float z)
{
float total = 0;
float persistence = 0.55f;
int octaves = 8;
for(int i = 1 ; i <= octaves; i++)
{
float freq = pow(2.f, i);
float amp = pow(persistence, i);
total += interpNoise2D(x * freq,
z * freq) * amp;
}
return total;
}
void Terrain::setWorldBounds(glm::vec4 newBounds)
{
m_currBounds = newBounds;
}
glm::vec2 Terrain::random2(glm::vec2 p) {
return glm::fract(43758.5453f * glm::sin(glm::vec2(glm::dot(p, glm::vec2(127.1, 311.7)),
glm::dot(p, glm::vec2(269.5, 183.3)))));
}
void Terrain::calcInitPos(float x, float z) {
float heightTest = fmin(254, fbm(x / 160.f, z / 160.f) * 32.f + 129.f);
m_playerInitPos = glm::vec3(28, heightTest + 3.f, 32);
}
void Terrain::createInitScene(float minX, float maxX, float minZ, float maxZ)
{
m_currBounds = glm::vec4(minX, maxX, minZ, maxZ);
// Create the basic terrain floor
for(int x = minX; x < maxX; ++x)
{
for(int z = minZ; z < maxZ; ++z)
{
for(int y = 0; y <= 255; ++y)
{
if (y <= 128)
{
setBlockAt(x, y, z, STONE);
}
else if (y > 128 & y <= 255)
{
//---------------------------------------
//BIOME & WORLEY
//---------------------------------------
int numBiome = 3;
float cellSize = 50.f; //each cell spans #cellSize blocks
//get the cell location that the current block is located within
int curBlockCellLocX = glm::floor(x / cellSize);
int curBlockCellLocZ = glm::floor(z / cellSize);
BlockType curBlockType = BEDROCK; //for debug
// Want the block to be of the type of the closest "heart"
// Want to check how close the "heart" is to the block and what type of block it is
float distToClosestHeart = 999999999.f;
float distToNextClosestHeart = 999999999.f;
int modClosestHeartResult = 0; //helps to determine what blocktype of the heart block is
int modNextClosestHeartResult = 0;
glm::vec2 locClosestHeart;
glm::vec2 locNextClosestHeart;
//iterate throught 9 cells (8 surrounding and itself)
for (int curCellX = curBlockCellLocX - 1;
curCellX <= curBlockCellLocX + 1; curCellX ++) {
for (int curCellZ = curBlockCellLocZ - 1;
curCellZ <= curBlockCellLocZ + 1; curCellZ ++) {
//the input to random2 is converted back to block size
glm::vec2 heartCurCellLoc =
glm::vec2(curCellX * cellSize, curCellZ * cellSize) +
cellSize * random2(glm::vec2(curCellX, curCellZ));
// Check if the location of this block is closer than
// the closest distance from this block to any hearts of cells
float distToCurHeart = glm::length(heartCurCellLoc - glm::vec2(x, z));
// If the location of this block is closer to this heart than previous hearts,
// set the current block to be the same as this heart's block type
if (distToCurHeart < distToClosestHeart){
modNextClosestHeartResult = modClosestHeartResult;
modClosestHeartResult = glm::mod( ((int)heartCurCellLoc.x +
(int)heartCurCellLoc.y), numBiome);
distToNextClosestHeart = distToClosestHeart;
distToClosestHeart = distToCurHeart;
locNextClosestHeart = locClosestHeart;
locClosestHeart = heartCurCellLoc;
}
}
}
//avoid negative modulo values
modClosestHeartResult = glm::abs(modClosestHeartResult);
modNextClosestHeartResult = glm::abs(modNextClosestHeartResult);
// Decide block texture ----------------------------------------------------------------------------
// (modHeartToUse, distToUse, locToUse) corresponds to the same heart that determines the type
// of biome that the current block belongs to
// It can be either the closest heart, or the next closest heart
int modHeartToUse = modClosestHeartResult; // marks the biome that the current block is of
int modHeartNotToUse = modNextClosestHeartResult;
float distToUse = distToClosestHeart;
float distNotToUse = distToNextClosestHeart;
glm::vec2 locToUse = locClosestHeart;
glm::vec2 locNotToUse = locNextClosestHeart;
// To create transition between biomes
// If distance to closest heart is further away than constant * cellSize, the chance of this
// block being the same biome as the closest heart's dependes on how far away it is. If
// it is not the same as the closest heart's,
if (distToClosestHeart > 0.43 * (distToClosestHeart + distToNextClosestHeart)) {
// Arbitrary functions to determine which block it should be
// Returns a value from 0 - 100
float randVal = rand() % 100;
if (randVal < 49) {
modHeartToUse = modNextClosestHeartResult;
modHeartNotToUse = modClosestHeartResult;
distToUse = distToNextClosestHeart;
distNotToUse = distToClosestHeart;
locToUse = locNextClosestHeart;
locNotToUse = locClosestHeart;
}
}
//--------------------------------------------------------------------------
// From the result of modulo, decides which biomes to belong to;
if (modHeartToUse == 2) {
curBlockType = SNOW;
} else if (modHeartToUse == 1) {
curBlockType = GRASS;
} else {
curBlockType == SAND;
}
// --------------------------------------------------------------
//TRYWORKING
float heightToUse;
float heightNotToUse;
// Find the height of the heart of the biome which this current block is the same type with
if (modHeartToUse == 2) {
heightToUse = fmin(254, fbm(locToUse.x / 160.f, locToUse.y / 160.f) * 40.f + 129.f);
} else if (modHeartToUse == 1) {
heightToUse = fmin(254, fbm(locToUse.x / 160.f, locToUse.y / 160.f) * 30.f + 129.f);
} else {
heightToUse = fmin(254, fbm(locToUse.x / 160.f, locToUse.y / 160.f) * 27.f + 129.f);
}
// Find the height of the next closest heart of which this current block is potentially
// not the same type with
if (modHeartNotToUse != modHeartToUse) {
if (modHeartNotToUse == 2) {
heightNotToUse = fmin(254, fbm(locNotToUse.x / 160.f,
locNotToUse.y / 160.f) * 40.f + 129.f);
} else if (modHeartNotToUse == 1) {
heightNotToUse = fmin(254, fbm(locNotToUse.x / 160.f,
locNotToUse.y / 160.f) * 30.f + 129.f);
} else {
heightNotToUse = fmin(254, fbm(locNotToUse.x / 160.f,
locNotToUse.y / 160.f) * 27.f + 129.f);
}
}
// Interpolate the height of the block when the two closest hearts are of different biomes type
float heightCurBlock;
if (modHeartNotToUse != modHeartToUse &&
distToClosestHeart > 0.43 * (distToClosestHeart + distToNextClosestHeart)) {
heightCurBlock = glm::mix(heightToUse, heightNotToUse, distToUse / (distToUse + distNotToUse));
} else {
if (modHeartToUse == 2) {
heightCurBlock = fmin(254, fbm(x / 160.f, z / 160.f) * 40.f + 129.f);
} else if (modHeartToUse == 1) {
heightCurBlock = fmin(254, fbm(x / 160.f, z / 160.f) * 30.f + 129.f);
} else {
heightCurBlock = fmin(254, fbm(x / 160.f, z / 160.f) * 27.f + 129.f);
}
}
if (curBlockType == GRASS) {
//fillBetween(x, z, 129, heightCurBlock, DIRT);
} else if (curBlockType == SAND) {
//fillBetween(x, z, 129, heightCurBlock, SAND);
} else {
//fillBetween(x, z, 129, heightCurBlock, BEDROCK);
}
setBlockAt(x, heightCurBlock + 1, z, curBlockType); //----biome
if (x == 28 && z == 32)
{
m_playerInitPos = glm::vec3(28, heightCurBlock + 5.f, 32);
}
break;
}
}
}
}
//makeRiver();
makeTrees();
}
void Terrain::createScene(float minX, float maxX, float minZ, float maxZ)
{
Worker* thread = new Worker(&mutex, glm::vec4(minX, maxX, minZ, maxZ), this);
QThreadPool::globalInstance()->start(thread);
}
void Terrain::setAdjacencies(Chunk* chunk)
{
float zBack = chunk->xzCoords.y - 16;
float xBack = chunk->xzCoords.x;
uint64_t xzCoordBack = (static_cast<uint64_t> (xBack) << 32) | (static_cast<uint64_t> (zBack) & 0x00000000FFFFFFFF);
// std::unordered_map<uint64_t, Chunk*>::iterator back = chunkMap.find(xzCoordBack);
if((chunkMap.contains(xzCoordBack)))
{
chunk->back = chunkMap.value(xzCoordBack);
chunkMap.value(xzCoordBack)->front = chunk;
}
float zFront = chunk->xzCoords.y + 16;
float xFront = chunk->xzCoords.x;
uint64_t xzCoordFront = (static_cast<uint64_t> (xFront) << 32) | (static_cast<uint64_t> (zFront) & 0x00000000FFFFFFFF);
//std::unordered_map<uint64_t, Chunk*>::iterator front = chunkMap.find(xzCoordFront);
if((chunkMap.contains(xzCoordFront)))
{
chunk->front = chunkMap.value(xzCoordFront);
chunkMap.value(xzCoordFront)->back = chunk;
}
float zLeft = chunk->xzCoords.y;
float xLeft = chunk->xzCoords.x - 16;
uint64_t xzCoordLeft = (static_cast<uint64_t> (xLeft) << 32) | (static_cast<uint64_t> (zLeft) & 0x00000000FFFFFFFF);
// std::unordered_map<uint64_t, Chunk*>::iterator left = chunkMap.find(xzCoordLeft);
if(chunkMap.contains(xzCoordLeft))
{
chunk->left = chunkMap.value(xzCoordLeft);
chunkMap.value(xzCoordLeft)->right = chunk;
}
float zRight = chunk->xzCoords.y;
float xRight = chunk->xzCoords.x + 16;
uint64_t xzCoordRight = (static_cast<uint64_t> (xRight) << 32) | (static_cast<uint64_t> (zRight) & 0x00000000FFFFFFFF);
// std::unordered_map<uint64_t, Chunk*>::iterator right = chunkMap.find(xzCoordRight);
if(chunkMap.contains(xzCoordRight))
{
chunk->right = chunkMap.value(xzCoordRight);
chunkMap.value(xzCoordRight)->left = chunk;
}
}
Chunk::Chunk(OpenGLContext* context) : Drawable(context), blockArray(65536),
front(nullptr), back(nullptr), left(nullptr), right(nullptr),
createdOpaque(false)
{}
Chunk:: ~Chunk() {}
BlockType& Chunk::blockAt(int x, int y, int z) {
return blockArray[x + 16 * y + 256 * 16 * z];
}
BlockType Chunk::blockAt(int x, int y, int z) const {
return blockArray[x + 16 * y + 256 * 16 * z];
}
void Chunk::fillBetween(int x, int z, int bottomLimit, int topLimit, BlockType t) {
if(x < 0 || x > 15 || z < 0 || z > 15) {
return;
}
for (int i = bottomLimit; i <= topLimit; ++i)
{
blockAt(x, i, z) = t;
}
}
void createSquareIndices(int& initial, std::vector<int>& idx) {
for(int i = 0; i + 2 < 4; i++) {
idx.push_back(initial);
idx.push_back(initial + i + 1);
idx.push_back(initial + i + 2);
}
initial += 4;
}
bool Terrain::isTransparent(BlockType t) {
return (t == WATER || t == LAVA);
}
//void Chunk::pushBlockIntoVBO(std::vector<glm::vec4>& inter, std::vector<int>& idx,
// glm::vec2& uvStartCoord, float& cosPow, float& animatable,
// int& currX, int& currY, int& currZ,
// float& norLengthBlock, int& initial,
// BlockType& blockType, bool depthMode)
//{
// glm::vec2 topUVStartCoord;
// glm::vec2 botUVStartCoord;
// if (!depthMode) {
// // For certain block types, the starting UV coordinates for top and bottom are different
// // Switch from uv coordinate to block coordinate
// topUVStartCoord = uvStartCoord / norLengthBlock ;
// botUVStartCoord = uvStartCoord / norLengthBlock;
// if (blockType == GRASS) {
// topUVStartCoord = glm::vec2(8, 2);
// botUVStartCoord = glm::vec2(2, 0);
// } else if (blockType == WOOD) {
// topUVStartCoord = glm::vec2(5, 1);
// botUVStartCoord = glm::vec2(5, 1);
// }
// // Switch from block coordinate to uv coordinate
// topUVStartCoord *= norLengthBlock;
// botUVStartCoord *= norLengthBlock;
// }
// //if it is not water and adjacent to water
// bool opaqueAdjTrans = true;
// bool opaque = true;
// if(Terrain::isTransparent(blockAt(currX,currY,currZ))) {
// opaque = false;
// }
// bool adjEmpty = false;
// if(currX == 15) {
// adjEmpty = false;
// if (right != nullptr) {
// adjEmpty = (right -> blockAt(0,currY,currZ) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(right -> blockAt(0,currY,currZ)) && opaque;
// } else {
// adjEmpty = true;
// }
// } else {
// adjEmpty = (blockArray.at((currX + 1) + 16 * currY + 16 * 256 * currZ) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(blockArray.at((currX + 1) + 16 * currY + 16 * 256 * currZ)) && opaque;
// }
// // face right of the block------------------------------------------------------------
// if (adjEmpty || opaqueAdjTrans) {
// inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y, cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ + 1), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ + 1), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// createSquareIndices(initial, idx);
// adjEmpty = false;
// }
// if(currX == 0) {
// adjEmpty = false;
// if (left != nullptr) {
// adjEmpty = (left->blockAt(15,currY,currZ) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(left->blockAt(15,currY,currZ)) && opaque;
// } else {
// adjEmpty = true;
// }
// } else {
// adjEmpty = (blockArray.at((currX - 1) + 16 * currY + 256 * 16 * currZ) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(blockArray.at((currX - 1) + 16 * currY + 256 * 16 * currZ)) && opaque;
// }
// // face left of the block------------------------------------------------------------
// if(adjEmpty || opaqueAdjTrans) {
// inter.push_back(glm::vec4(float(currX), float(currY), float(currZ), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(-1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x,
// uvStartCoord.y + norLengthBlock,
// cosPow,
// animatable));
// }
// inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(-1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x,
// uvStartCoord.y,
// cosPow,
// animatable));
// }
// inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ + 1), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(-1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock,
// uvStartCoord.y,
// cosPow,
// animatable));
// }
// inter.push_back(glm::vec4(float(currX), float(currY), float(currZ + 1), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(-1,0,0,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock,
// uvStartCoord.y + norLengthBlock,
// cosPow,
// animatable));
// }
// createSquareIndices(initial, idx);
// adjEmpty = false;
// }
// if(currY == 255) {
// adjEmpty = true;
// } else {
// adjEmpty = (blockArray.at(currX + 16 * (currY + 1) + 256 * 16 * currZ) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * (currY + 1) + 256 * 16 * currZ)) && opaque;
// }
// // face on top of the block------------------------------------------------------------
// if (adjEmpty || opaqueAdjTrans) {
// //don't need to check chunk adjacency since there are no chunks above
// inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,1,0,0));
// inter.push_back(glm::vec4(topUVStartCoord.x, topUVStartCoord.y,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,1,0,0));
// inter.push_back(glm::vec4(topUVStartCoord.x + norLengthBlock, topUVStartCoord.y,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ + 1), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,1,0,0));
// inter.push_back(glm::vec4(topUVStartCoord.x + norLengthBlock, topUVStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ + 1), 1.0f));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,1,0,0));
// inter.push_back(glm::vec4(topUVStartCoord.x, topUVStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// createSquareIndices(initial, idx);
// adjEmpty = false;
// }
// if(currY == 0) {
// adjEmpty = true;
// } else {
// adjEmpty = (blockArray.at(currX + 16 * (currY - 1) + 256 * 16 * currZ) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * (currY - 1) + 256 * 16 * currZ)) && opaque;
// }
// // face at bottom of the block------------------------------------------------------------
// if (adjEmpty || opaqueAdjTrans) {
// //don't need to check chunk adjacency since there are no chunks below
// inter.push_back(glm::vec4(float(currX), float(currY), float(currZ), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,-1,0,0));
// inter.push_back(glm::vec4(botUVStartCoord.x, botUVStartCoord.y,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,-1,0,0));
// inter.push_back(glm::vec4(botUVStartCoord.x + norLengthBlock, botUVStartCoord.y,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ + 1), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,-1,0,0));
// inter.push_back(glm::vec4(botUVStartCoord.x + norLengthBlock, botUVStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX), float(currY), float(currZ + 1), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,-1,0,0));
// inter.push_back(glm::vec4(botUVStartCoord.x, botUVStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// createSquareIndices(initial, idx);
// adjEmpty = false;
// }
// if(currZ == 0) {
// adjEmpty = false;
// if (back != nullptr) {
// adjEmpty = (back->blockAt(currX,currY,15) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(back->blockAt(currX,currY,15)) && opaque;
// } else {
// adjEmpty = true;
// }
// } else {
// adjEmpty = (blockArray.at(currX + 16 * currY + 256 * 16 * (currZ - 1)) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * currY + 256 * 16 * (currZ - 1))) && opaque;
// }
// // face behind block------------------------------------------------------------
// if(adjEmpty || opaqueAdjTrans) {
// inter.push_back(glm::vec4(float(currX), float(currY), float(currZ), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,1,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,1,0));
// inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,1,0));
// inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y, cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,1,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y,
// cosPow, animatable));
// }
// createSquareIndices(initial, idx);
// adjEmpty = false;
// }
// if(currZ == 15) {
// adjEmpty = false;
// if (front != nullptr) {
// adjEmpty = (front->blockAt(currX, currY, 0) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(front->blockAt(currX,currY,0)) && opaque;
// } else {
// adjEmpty = true;
// }
// } else {
// adjEmpty = (blockArray.at(currX + 16 * currY + 256 * 16 * (currZ + 1)) == EMPTY);
// opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * currY + 256 * 16 * (currZ + 1))) && opaque;
// }
// // face in front of block------------------------------------------------------------
// if(adjEmpty || opaqueAdjTrans) {
// inter.push_back(glm::vec4(float(currX), float(currY), float(currZ + 1), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,-1,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ + 1), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,-1,0));
// inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y + norLengthBlock,
// cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ + 1), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,-1,0));
// inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y, cosPow, animatable));
// }
// inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ + 1), 1));
// if (!depthMode) {
// inter.push_back(glm::vec4(0,0,-1,0));
// inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y,
// cosPow, animatable));
// }
// createSquareIndices(initial, idx);
// adjEmpty = false;
// }
//}
void Chunk::pushBlockIntoVBO(std::vector<glm::vec4>& inter, std::vector<int>& idx,
glm::vec2& uvStartCoord, float& cosPow, float& animatable,
int& currX, int& currY, int& currZ,
float& norLengthBlock, int& initial, BlockType& blockType)
{
// For certain block types, the starting UV coordinates for top and bottom are different
// Switch from uv coordinate to block coordinate
glm::vec2 topUVStartCoord = uvStartCoord / norLengthBlock ;
glm::vec2 botUVStartCoord = uvStartCoord / norLengthBlock;
if (blockType == GRASS) {
topUVStartCoord = glm::vec2(8, 2);
botUVStartCoord = glm::vec2(2, 0);
} else if (blockType == WOOD) {
topUVStartCoord = glm::vec2(5, 1);
botUVStartCoord = glm::vec2(5, 1);
}
// Switch from block coordinate to uv coordinate
topUVStartCoord *= norLengthBlock;
botUVStartCoord *= norLengthBlock;
//if it is not water and adjacent to water
bool opaqueAdjTrans = true;
bool opaque = true;
if(Terrain::isTransparent(blockAt(currX,currY,currZ))) {
opaque = false;
}
bool adjEmpty = false;
if(currX == 15) {
adjEmpty = false;
if (right != nullptr) {
adjEmpty = (right -> blockAt(0,currY,currZ) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(right -> blockAt(0,currY,currZ)) && opaque;
} else {
adjEmpty = true;
}
} else {
adjEmpty = (blockArray.at((currX + 1) + 16 * currY + 16 * 256 * currZ) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(blockArray.at((currX + 1) + 16 * currY + 16 * 256 * currZ)) && opaque;
}
// face right of the block------------------------------------------------------------
if (adjEmpty || opaqueAdjTrans) {
inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ), 1.0f));
inter.push_back(glm::vec4(1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y + norLengthBlock,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ), 1.0f));
inter.push_back(glm::vec4(1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y, cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ + 1), 1.0f));
inter.push_back(glm::vec4(1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ + 1), 1.0f));
inter.push_back(glm::vec4(1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y + norLengthBlock,
cosPow, animatable));
createSquareIndices(initial, idx);
adjEmpty = false;
}
if(currX == 0) {
adjEmpty = false;
if (left != nullptr) {
adjEmpty = (left->blockAt(15,currY,currZ) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(left->blockAt(15,currY,currZ)) && opaque;
} else {
adjEmpty = true;
}
} else {
adjEmpty = (blockArray.at((currX - 1) + 16 * currY + 256 * 16 * currZ) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(blockArray.at((currX - 1) + 16 * currY + 256 * 16 * currZ)) && opaque;
}
// face left of the block------------------------------------------------------------
if(adjEmpty || opaqueAdjTrans) {
inter.push_back(glm::vec4(float(currX), float(currY), float(currZ), 1.0f));
inter.push_back(glm::vec4(-1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x,
uvStartCoord.y + norLengthBlock,
cosPow,
animatable));
inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ), 1.0f));
inter.push_back(glm::vec4(-1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x,
uvStartCoord.y,
cosPow,
animatable));
inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ + 1), 1.0f));
inter.push_back(glm::vec4(-1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock,
uvStartCoord.y,
cosPow,
animatable));
inter.push_back(glm::vec4(float(currX), float(currY), float(currZ + 1), 1.0f));
inter.push_back(glm::vec4(-1,0,0,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock,
uvStartCoord.y + norLengthBlock,
cosPow,
animatable));
createSquareIndices(initial, idx);
adjEmpty = false;
}
if(currY == 255) {
adjEmpty = true;
} else {
adjEmpty = (blockArray.at(currX + 16 * (currY + 1) + 256 * 16 * currZ) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * (currY + 1) + 256 * 16 * currZ)) && opaque;
}
// face on top of the block------------------------------------------------------------
if (adjEmpty || opaqueAdjTrans) {
//don't need to check chunk adjacency since there are no chunks above
inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ), 1.0f));
inter.push_back(glm::vec4(0,1,0,0));
inter.push_back(glm::vec4(topUVStartCoord.x, topUVStartCoord.y,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ), 1.0f));
inter.push_back(glm::vec4(0,1,0,0));
inter.push_back(glm::vec4(topUVStartCoord.x + norLengthBlock, topUVStartCoord.y,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ + 1), 1.0f));
inter.push_back(glm::vec4(0,1,0,0));
inter.push_back(glm::vec4(topUVStartCoord.x + norLengthBlock, topUVStartCoord.y + norLengthBlock,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ + 1), 1.0f));
inter.push_back(glm::vec4(0,1,0,0));
inter.push_back(glm::vec4(topUVStartCoord.x, topUVStartCoord.y + norLengthBlock,
cosPow, animatable));
createSquareIndices(initial, idx);
adjEmpty = false;
}
if(currY == 0) {
adjEmpty = true;
} else {
adjEmpty = (blockArray.at(currX + 16 * (currY - 1) + 256 * 16 * currZ) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * (currY - 1) + 256 * 16 * currZ)) && opaque;
}
// face at bottom of the block------------------------------------------------------------
if (adjEmpty || opaqueAdjTrans) {
//don't need to check chunk adjacency since there are no chunks below
inter.push_back(glm::vec4(float(currX), float(currY), float(currZ), 1));
inter.push_back(glm::vec4(0,-1,0,0));
inter.push_back(glm::vec4(botUVStartCoord.x, botUVStartCoord.y,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ), 1));
inter.push_back(glm::vec4(0,-1,0,0));
inter.push_back(glm::vec4(botUVStartCoord.x + norLengthBlock, botUVStartCoord.y,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ + 1), 1));
inter.push_back(glm::vec4(0,-1,0,0));
inter.push_back(glm::vec4(botUVStartCoord.x + norLengthBlock, botUVStartCoord.y + norLengthBlock,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX), float(currY), float(currZ + 1), 1));
inter.push_back(glm::vec4(0,-1,0,0));
inter.push_back(glm::vec4(botUVStartCoord.x, botUVStartCoord.y + norLengthBlock,
cosPow, animatable));
createSquareIndices(initial, idx);
adjEmpty = false;
}
if(currZ == 0) {
adjEmpty = false;
if (back != nullptr) {
adjEmpty = (back->blockAt(currX,currY,15) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(back->blockAt(currX,currY,15)) && opaque;
} else {
adjEmpty = true;
}
} else {
adjEmpty = (blockArray.at(currX + 16 * currY + 256 * 16 * (currZ - 1)) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * currY + 256 * 16 * (currZ - 1))) && opaque;
}
// face behind block------------------------------------------------------------
if(adjEmpty || opaqueAdjTrans) {
inter.push_back(glm::vec4(float(currX), float(currY), float(currZ), 1));
inter.push_back(glm::vec4(0,0,-1,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y + norLengthBlock,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ), 1));
inter.push_back(glm::vec4(0,0,-1,0));
inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y + norLengthBlock,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ), 1));
inter.push_back(glm::vec4(0,0,-1,0));
inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y, cosPow, animatable));
inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ), 1));
inter.push_back(glm::vec4(0,0,-1,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y,
cosPow, animatable));
createSquareIndices(initial, idx);
adjEmpty = false;
}
if(currZ == 15) {
adjEmpty = false;
if (front != nullptr) {
adjEmpty = (front->blockAt(currX, currY, 0) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(front->blockAt(currX,currY,0)) && opaque;
} else {
adjEmpty = true;
}
} else {
adjEmpty = (blockArray.at(currX + 16 * currY + 256 * 16 * (currZ + 1)) == EMPTY);
opaqueAdjTrans = Terrain::isTransparent(blockArray.at(currX + 16 * currY + 256 * 16 * (currZ + 1))) && opaque;
}
// face in front of block------------------------------------------------------------
if(adjEmpty || opaqueAdjTrans) {
inter.push_back(glm::vec4(float(currX), float(currY), float(currZ + 1), 1));
inter.push_back(glm::vec4(0,0,1,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y + norLengthBlock,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY), float(currZ + 1), 1));
inter.push_back(glm::vec4(0,0,1,0));
inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y + norLengthBlock,
cosPow, animatable));
inter.push_back(glm::vec4(float(currX + 1), float(currY + 1), float(currZ + 1), 1));
inter.push_back(glm::vec4(0,0,1,0));
inter.push_back(glm::vec4(uvStartCoord.x, uvStartCoord.y, cosPow, animatable));
inter.push_back(glm::vec4(float(currX), float(currY + 1), float(currZ + 1), 1));
inter.push_back(glm::vec4(0,0,1,0));
inter.push_back(glm::vec4(uvStartCoord.x + norLengthBlock, uvStartCoord.y,
cosPow, animatable));
createSquareIndices(initial, idx);
adjEmpty = false;
}
}
void Chunk::bindOpaquePart() {
count = idxOpaque.size();
//generateInterleaved();
context->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufInter);
context->glBufferData(GL_ELEMENT_ARRAY_BUFFER, interOpaque.size() * sizeof(glm::vec4), interOpaque.data(), GL_STATIC_DRAW);
// generateIdx();
context->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufIdx);
context->glBufferData(GL_ELEMENT_ARRAY_BUFFER, idxOpaque.size() * sizeof(GLuint), idxOpaque.data(), GL_STATIC_DRAW);
}
void Chunk::bindNonOpaquePart() {
count = idxNonOpaque.size();
// generateInterleaved();
context->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufInter);
context->glBufferData(GL_ELEMENT_ARRAY_BUFFER, interNonOpaque.size() * sizeof(glm::vec4), interNonOpaque.data(), GL_STATIC_DRAW);
// generateIdx();
context->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufIdx);
context->glBufferData(GL_ELEMENT_ARRAY_BUFFER, idxNonOpaque.size() * sizeof(GLuint), idxNonOpaque.data(), GL_STATIC_DRAW);
}
void Chunk::clearData() {
idxOpaque.clear();
idxNonOpaque.clear();
interOpaque.clear();
interNonOpaque.clear();
}
void Chunk :: create() {
clearData();
// The below are for UV mapping
float sizeWholeImageTexture = 256.f; //the given image is of size 256 x 256 --T
float lengthBlock = 16.f;
float norLengthBlock = lengthBlock / sizeWholeImageTexture; //normalized length of block
glm::vec4 defColor = glm::vec4(0.2f, 1.0f, 0.6f, 1);
int initialOpaque = 0;
int initialNonOpaque = 0;
if (!createdOpaque) { //To ensure we only iterate through all blocks once
for (int currX = 0; currX < 16; currX++) {
for (int currY = 0; currY < 256; currY++) {
for (int currZ = 0; currZ < 16; currZ++) {
glm::vec2 uvStartCoord = glm::vec2(0.f, 0.f);
float opaque = true;
float animatable = 0.f; //1 means animatable (lava, water), 0 means not
float cosPow = 1.f;
int posInBlockArr = currX + 16 * currY + 16 * 256 * currZ;
BlockType curBlockType = blockArray[posInBlockArr];
if (curBlockType != EMPTY) {
switch(curBlockType)
{
case BAMBOO:
cosPow = 5000.f;
uvStartCoord = glm::vec2(9, 4);
break;
case BEDROCK:
cosPow = 8000.f;
uvStartCoord = glm::vec2(1, 1);
break;
case DIRT:
cosPow = 1.f;
uvStartCoord = glm::vec2(2, 0);
break;
case GRASS:
cosPow = 10.f;
uvStartCoord = glm::vec2(3, 0); // grass side
break;
case GUM:
cosPow = 1.5f;
uvStartCoord = glm::vec2(2, 8);
break;
case ICE:
opaque = false;
cosPow = 6000.f;
uvStartCoord = glm::vec2(3, 4);
break;
case LAVA:
cosPow = 200.f;
uvStartCoord = glm::vec2(14, 14);
animatable = 1.f;
break;
case LEAF:
cosPow = 10.f;
uvStartCoord = glm::vec2(5, 3);
break;
case SAND:
cosPow = 10.f;
uvStartCoord = glm::vec2(2, 1);
break;
case SNOW:
cosPow = 1.f;
uvStartCoord = glm::vec2(2, 4);
break;
case STONE:
cosPow = 7000.f;
uvStartCoord = glm::vec2(0, 0);
break;
case WATER:
opaque = false;
cosPow = 9000.f;
uvStartCoord = glm::vec2(13, 12);
animatable = 1.f;
break;
case WOOD:
cosPow = 1.f;
uvStartCoord = glm::vec2(4, 1); //wood side
}
uvStartCoord *= norLengthBlock; //change from block coordinate to uv coordinate
if (opaque) { //the block is opaque
pushBlockIntoVBO(interOpaque, idxOpaque, uvStartCoord, cosPow,
animatable, currX, currY, currZ,
norLengthBlock, initialOpaque, curBlockType);
} else { //the block is not opaque
pushBlockIntoVBO(interNonOpaque, idxNonOpaque, uvStartCoord, cosPow,
animatable, currX, currY, currZ,
norLengthBlock, initialNonOpaque, curBlockType);
}
}
}
}
}
}
generateInterleaved();
generateIdx();
}
Terrain::Turtle::Turtle(glm::vec4 pos, glm::vec4 orientation, float depth)
: pos(pos), orientation(orientation), depth(depth), material(WATER)
{
}
Terrain::Turtle::Turtle(glm::vec4 pos, glm::vec4 orientation, float depth, BlockType material)
: pos(pos), orientation(orientation), depth(depth), material(material)
{
}
//Terrain::Turtle::Turtle(Turtle t)
// : pos(t.pos), orientation(t.orientation), depth(t.depth)
//{
//}
Terrain::Turtle::Turtle()
: pos(0), orientation(0), depth(0)
{
}
void Terrain::expandString(QString &sentence) {
QString newString = "";
for(QChar c : sentence) {
if(charToExpandedString.contains(c)) {
newString += charToExpandedString.value(c);
} else {
newString += c;
}
// charToDrawingOperation
}
sentence = newString;
}
void Terrain::setExpandedStrings(LType r) {
charToExpandedString.clear();
switch(r) {
case DELTA:
charToExpandedString.insert('X',"F[+F-F+FX][-F+FX]");
break;
case LINEAR:
charToExpandedString.insert('X',"F[+F--FF][FFFX]");
break;
case TREE:
charToExpandedString.insert('X',"bF.[+,<lsFX].bF[.>.<lsFX].bF[-.-lsFX]X");
break;
case BAMBOOTREE:
charToExpandedString.insert('X',"bF.[+,<lFX].bF[.>.<lFX].bF[-.-lFX]X");
break;
case PINE:
charToExpandedString.insert('X',"F[>>>>>FX]");
break;
default:
charToExpandedString.insert('X',"F[+F-F+FX][-F+FX]");
break;
}
}
void Terrain::setDrawingRules(LType r) {
charToDrawingOperation.insert('F',&Terrain::moveTurtleForwardRand);
charToDrawingOperation.insert('-',&Terrain::rotateTurtleNeg);
charToDrawingOperation.insert('+',&Terrain::rotateTurtlePos);
charToDrawingOperation.insert('[',&Terrain::pushTurtle);
charToDrawingOperation.insert(']',&Terrain::popTurtle);
charToDrawingOperation.insert('<',&Terrain::rotateTurtleXNeg);
charToDrawingOperation.insert('>',&Terrain::rotateTurtleXPos);
charToDrawingOperation.insert('.',&Terrain::rotateTurtleZPos);
charToDrawingOperation.insert(',',&Terrain::rotateTurtleZNeg);
charToDrawingOperation.insert('l',&Terrain::makeTurtleLeaf);
charToDrawingOperation.insert('b',&Terrain::makeTurtleBamboo);
charToDrawingOperation.insert('g',&Terrain::makeTurtleGrass);
charToDrawingOperation.insert('w',&Terrain::makeTurtleWood);
charToDrawingOperation.insert('s',&Terrain::subTurtleDepth);
charToDrawingOperation.insert('a',&Terrain::addTurtleDepth);
}
void Terrain::moveTurtleUp(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case TREE:
{
currTurt.pos.y += 3;
break;
}
default:
{
break;
}
}
}
void Terrain::moveTurtleForwardRand(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case DELTA:
for(int i = 0; i < 5; i++) {
glm::vec4 prevPos = currTurt.pos;
float randfloat = fbm(prevPos.x, prevPos.z) * 2;
float randAng = -30 + fbm(prevPos.x, prevPos.z) * 70;
glm::mat4 randRot = glm::rotate(glm::mat4(), glm::radians(randAng),glm::vec3(0.f,1.f,0.f));
currTurt.pos += (float) (randfloat + 1.f / fmax(1.f, pow((float) turtleStack.size() * 0.5f, 1.3f))) * randRot * currTurt.orientation ;
drawLine(prevPos, currTurt.pos, 4.f / fmax(0.5f,turtleStack.size() * 2), WATER, newChunks);
}
break;
case LINEAR:
for(int i = 0; i < 4; i++) {
glm::vec4 prevPos = currTurt.pos;
float randfloat = 4 + fbm(prevPos.x, prevPos.z) * 8;
float randAng = -100 + fbm(prevPos.x, prevPos.z) * 200;
glm::mat4 randRot = glm::rotate(glm::mat4(), glm::radians(randAng),glm::vec3(0.f,1.f,0.f));
currTurt.pos += (float) (randfloat + 1.f / fmax(0.5f, pow((float) turtleStack.size() * 0.5f, 1.3f))) * randRot * currTurt.orientation ;
drawLine(prevPos, currTurt.pos, 2.f / fmax(0.5f,turtleStack.size() * 0.4), LAVA, newChunks);
}
break;
case TREE:
{
float randfloat = (4.f + fbm(currTurt.pos.x, currTurt.pos.z) * 2.f) / fmax(1, turtleStack.size() * 10);
for(int i = 0; i < randfloat; i ++) {
glm::vec4 prevPos = currTurt.pos;
currTurt.pos += currTurt.orientation;
int x = floor(currTurt.pos.x);
int y = floor(fmax(fmin(currTurt. pos.y, 255), 0));
int z = floor(currTurt.pos.z);
for (float j = -currTurt.depth; j < currTurt.depth; j++) {
for (float k = -currTurt.depth; k < currTurt.depth; k++) {
for(float l = -currTurt.depth; l < currTurt.depth; l++) {
setBlockAt(x + j, y + k, z + l, currTurt.material);
}
}
}
}
currTurt.depth = fmax(0.5, currTurt.depth - 3);
break;
}
case BAMBOOTREE:
{
float randfloat = (4.f + fbm(currTurt.pos.x, currTurt.pos.z) * 2.f) / fmax(1, turtleStack.size() * 10);
for(int i = 0; i < randfloat; i ++) {
glm::vec4 prevPos = currTurt.pos;
currTurt.pos += currTurt.orientation;
int x = floor(currTurt.pos.x);
int y = floor(fmax(fmin(currTurt. pos.y, 255), 0));
int z = floor(currTurt.pos.z);
for (float j = -currTurt.depth; j < currTurt.depth; j++) {
for (float k = -currTurt.depth; k < currTurt.depth; k++) {
for(float l = -currTurt.depth; l < currTurt.depth; l++) {
setBlockAt(x + j, y + k, z + l, currTurt.material);
}
}
}
}
break;
}
case PINE:
{
float randfloat = 4.f + (fbm(currTurt.pos.x, currTurt.pos.z) * 2.f) / fmax(1, turtleStack.size() * 10);
for(int i = 0; i < randfloat; i ++) {
glm::vec4 prevPos = currTurt.pos;
currTurt.pos += currTurt.orientation;
int x = floor(currTurt.pos.x);
int y = floor(fmax(fmin(currTurt. pos.y, 255), 0));
int z = floor(currTurt.pos.z);
for (float j = -currTurt.depth; j < currTurt.depth; j++) {
for (float k = -currTurt.depth; k < currTurt.depth; k++) {
for(float l = -currTurt.depth; l < currTurt.depth; l++) {
setBlockAt(x + j, y + k, z + l, currTurt.material);
}
}
}
}
break;
}
}
}
void Terrain::moveTurtleBackward(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
currTurt.pos -= currTurt.orientation;
}
void Terrain::rotateTurtleZPos(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case TREE:
{
float angle = (50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 50) / fmax(1, turtleStack.size());
currTurt.orientation = glm::normalize(glm::rotate(glm::mat4(),angle,glm::vec3(0.f,0.f,1.f)) * currTurt. orientation);
break;
}
case PINE:
{
float angle = (50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 50) / fmax(1, turtleStack.size());
currTurt.orientation = glm::normalize(glm::rotate(glm::mat4(),angle,glm::vec3(0.f,0.f,1.f)) * currTurt. orientation);
break;
}
default:
break;
}
}
void Terrain::rotateTurtleZNeg(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case TREE:
{
float angle = -(50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 50) / fmax(1, turtleStack.size());
currTurt.orientation = glm::normalize(glm::rotate(glm::mat4(),angle,glm::vec3(0.f,0.f,1.f)) * currTurt. orientation);
break;
}
case BAMBOOTREE:
{
float angle = -(-100 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 200) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),angle,glm::vec3(0.f,0.f,1.f)) * currTurt. orientation;
break;
}
case PINE:
{
float angle = -(-100 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 200) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),angle,glm::vec3(0.f,0.f,1.f)) * currTurt. orientation;
break;
}
default:
break;
}
}
void Terrain::rotateTurtleXPos(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case TREE:
{
float angle =(50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 50) / fmax(1, turtleStack.size());
currTurt.orientation = glm::normalize(glm::rotate(glm::mat4(),angle,glm::vec3(1.f,0.f,0.f)) * currTurt.orientation);
break;
}
case BAMBOOTREE:
{
float angle =(-100 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 200) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),angle,glm::vec3(1.f,0.f,0.f)) * currTurt.orientation;
break;
}
case PINE:
{
float angle =(-100 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 200) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),angle,glm::vec3(1.f,0.f,0.f)) * currTurt.orientation;
break;
}
default:
break;
}
}
void Terrain::rotateTurtleXNeg(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case TREE:
{
float angle = -50 - fbm(currTurt.orientation.x, currTurt. orientation.z) * 50 / fmax(1, turtleStack.size());
currTurt.orientation = glm::normalize(glm::rotate(glm::mat4(),angle,glm::vec3(1.f,0.f,0.f)) * currTurt.orientation);
break;
}
case BAMBOOTREE:
{
float angle = -50 - fbm(currTurt. orientation.x, currTurt. orientation.z) * 50 / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),angle,glm::vec3(1.f,0.f,0.f)) * currTurt.orientation;
break;
}
case PINE:
{
float angle = -50 - fbm(currTurt. orientation.x, currTurt. orientation.z) * 50 / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),angle,glm::vec3(1.f,0.f,0.f)) * currTurt.orientation;
break;
}
default:
break;
}
}
void Terrain::rotateTurtlePos(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case DELTA:
{
float angle = (50 + fbm(currTurt.orientation.x, currTurt.orientation.z) * 40) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),glm::radians(angle),glm::vec3(0.f,1.f,0.f)) * currTurt.orientation;
break;
}
case LINEAR:
{
float angle = (50 + fbm(currTurt.orientation.x, currTurt.orientation.z) * 3) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),glm::radians(angle),glm::vec3(0.f,1.f,0.f)) * currTurt.orientation;
break;
}
case TREE:
{
float angle = (50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 50) / fmax(1, turtleStack.size());
currTurt. orientation = glm::rotate(glm::mat4(),angle, glm::vec3(0.f,1.f,0.f)) * currTurt. orientation;
break;
}
case BAMBOOTREE:
{
float angle = (50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 50) / fmax(1, turtleStack.size());
currTurt. orientation = glm::rotate(glm::mat4(),angle, glm::vec3(0.f,1.f,0.f)) * currTurt. orientation;
break;
}
case PINE:
{
float angle = -(50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 3) / fmax(1, turtleStack.size());
currTurt. orientation = glm::rotate(glm::mat4(),angle, glm::vec3(0.f,1.f,0.f)) * currTurt. orientation;
break;
}
}
}
void Terrain::rotateTurtleNeg(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
switch (r) {
case DELTA:
{
float angle = (-50 - fbm(currTurt.orientation.x, currTurt.orientation.z) * 40) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),glm::radians(angle),glm::vec3(0.f,1.f,0.f)) * currTurt.orientation;
break;
}
case LINEAR:
{
float angle = (-50 - fbm(currTurt.orientation.x, currTurt.orientation.z) * 3) / fmax(1, turtleStack.size());
currTurt.orientation = glm::rotate(glm::mat4(),glm::radians(angle),glm::vec3(0.f,1.f,0.f)) * currTurt.orientation;
break;
}
case TREE:
{
float angle = -(50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 3) / fmax(1, turtleStack.size());
currTurt. orientation = glm::rotate(glm::mat4(),angle, glm::vec3(0.f,1.f,0.f)) * currTurt. orientation;
break;
}
case BAMBOOTREE:
{
float angle = -(50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 3) / fmax(1, turtleStack.size());
currTurt. orientation = glm::rotate(glm::mat4(),angle, glm::vec3(0.f,1.f,0.f)) * currTurt. orientation;
break;
}
case PINE:
{
float angle = -(50 + fbm(currTurt. orientation.x, currTurt. orientation.z) * 3) / fmax(1, turtleStack.size());
currTurt. orientation = glm::rotate(glm::mat4(),angle, glm::vec3(0.f,1.f,0.f)) * currTurt. orientation;
break;
}
}
}
void Terrain::pushTurtle(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
turtleStack.push(currTurt);
}
void Terrain::popTurtle(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
if(turtleStack.size() > 0) {
currTurt = turtleStack.pop();
}
}
void Terrain:: bresenhamAlongH(int x1, int x2, int z1, int z2, int y, float thickness, BlockType type, QHash <uint64_t, Chunk*>& newChunks) {
if (z2 < z1) {
//will be negative
int m_new = 2 * (z2 - z1);
int slope_error_new = m_new + (x2 - x1);
for (float x = x1, z = z1; x <= x2; x++)
{
// riverCreated.insert(getChunkAt(x, z));
for(float i = -thickness; i < thickness; i++) {
int bottom = 128;
int deep = 15;
//if(chunkExistsAt(x, bottom,z + i) && getBlockAt(x, bottom, z + i) != type) {
fillBetweenNewChunks(x, z + i, bottom, 255, EMPTY, newChunks);
fillBetweenNewChunks(x, z + i, bottom - deep, bottom, type, newChunks);
carve(x, z + i, bottom + 1, 7, 10, newChunks);
//}
}
// Add slope to increment angle formed
//gets smaller since m_new is negative
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new <= 0)
{
z--;
slope_error_new += 2 * (x2 - x1);
}
}
} else {
int m_new = 2 * (z2 - z1);
int slope_error_new = m_new - (x2 - x1);
for (int x = x1, z = z1; x <= x2; x++)
{
//if (created.contains(getChunkAt(x, z))) {
// riverCreated.insert(getChunkAt(x, z));
//}
for(float i = -thickness; i < thickness; i++) {
int bottom = 128;
int deep = 15;
// if(chunkExistsAt(x, bottom, z + i) && getBlockAt(x, bottom, z + i) != type) {
fillBetweenNewChunks(x, z + i, bottom, 255, EMPTY, newChunks);
fillBetweenNewChunks(x, z + i, bottom - deep, bottom, type, newChunks);
carve(x, z + i, bottom + 1, 7, 10, newChunks);
// }
}
// Add slope to increment angle formed
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new >= 0)
{
z++;
slope_error_new -= 2 * (x2 - x1);
}
}
}
}
void Terrain::bresenhamAlongV(int x1, int x2, int z1, int z2, int y, float thickness, BlockType type, QHash <uint64_t, Chunk*>& newChunks) {
if (x2 >= x1) {
int m_new = 2 * (x2 - x1);
int slope_error_new = m_new - (z2 - z1);
//offset for locked dimension to be drawn, lets us procedurally extend into locked dimension
int offset = 0;
for (int x = x1, z = z1; z <= z2; z++)
{
// if (created.contains(getChunkAt(x, z))) {
// riverCreated.insert(getChunkAt(x, z));
// }
for(float i = -thickness; i < thickness; i++) {
int bottom = 128;
int deep = 15;
// if(chunkExistsAt(x + i,bottom,z) && getBlockAt(x + i, bottom, z) != type) {
fillBetweenNewChunks(x + i, z, bottom, 255, EMPTY, newChunks);
fillBetweenNewChunks(x + i, z, bottom - deep, bottom, type, newChunks);
carve(x + i, z, bottom + 1, 7, 10, newChunks);
// }
}
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new >= 0)
{
x++;
slope_error_new -= 2 * (z2 - z1);
}
}
} else {
int m_new = 2 * (x2 - x1);
int slope_error_new = m_new + (z2 - z1);
int offset = 0;
for (int x = x1, z = z1; z <= z2; z++)
{
// if (created.contains(getChunkAt(x, z))) {
// riverCreated.insert(getChunkAt(x, z));
//}
for(float i = -thickness; i < thickness; i++) {
int bottom = 128;
int deep = 15;
//if(chunkExistsAt(x + i,bottom,z) && getBlockAt(x + i, bottom, z) != type) {
fillBetweenNewChunks(x + i, z, bottom, 255, EMPTY, newChunks);
fillBetweenNewChunks(x + i, z, bottom - deep, bottom, type, newChunks);
carve(x + i, z, bottom + 1, 7, 10, newChunks);
// }
}
// Add slope to increment angle formed
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new <= 0)
{
x--;
slope_error_new += 2 * (z2 - z1);
}
}
}
}
//uses bresenhams line algorithm
void Terrain::drawLine(glm::vec4 v1, glm::vec4 v2, float thickness, BlockType type, QHash <uint64_t, Chunk*>& newChunks) {
glm::vec4 start = v1;
glm::vec4 end = v2;
if(v1.x > v2.x) {
start = v2;
end = v1;
}
int x1 = start.x;
int z1 = start.z;
int x2 = end.x;
int z2 = end.z;
if(fabs(x1 - x2) > fabs(z1 - z2)) {
if(newChunks.contains(xzCoord(x1,z1)) || newChunks.contains(xzCoord(x2,z2))) {
bresenhamAlongH(x1, x2, z1, z2, 128, thickness, type, newChunks);
}
} else {
if(v1.z > v2.z) {
start = v2;
end = v1;
} else {
start = v1;
end = v2;
}
x1 = start.x;
z1 = start.z;
x2 = end.x;
z2 = end.z;
if(newChunks.contains(xzCoord(x1,z1)) || newChunks.contains(xzCoord(x2,z2))) {
bresenhamAlongV(x1, x2, z1, z2, 128, thickness, type, newChunks);
}
}
}
void Terrain::makeTurtleLeaf(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
currTurt.material = LEAF;
}
void Terrain:: makeTurtleWood(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
currTurt.material = WOOD;
}
void Terrain:: makeTurtleBamboo(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
currTurt.material = BAMBOO;
}
void Terrain:: makeTurtleGrass(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
currTurt.material = GRASS;
}
void Terrain :: addTurtleDepth(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
currTurt.depth += 1;
}
void Terrain :: subTurtleDepth(LType r, Turtle& currTurt, QStack<Turtle>& turtleStack, QHash <uint64_t, Chunk*>& newChunks) {
currTurt.depth = fmax(0.5, currTurt.depth - 0.5);
}
void Terrain::makeRiver(QHash <uint64_t, Chunk*>& newChunks) {
Turtle currTurt(glm::vec4(32,128,16,1), glm::vec4(1,0,0,1), 0, WATER);
QStack<Turtle> turtleStack;
setExpandedStrings(DELTA);
setDrawingRules(DELTA);
QString axiom = "FX";
for(int i = 0; i < 5; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(DELTA, currTurt, turtleStack, newChunks);
}
}
currTurt = Turtle(glm::vec4(32,128,48,1),glm::vec4(-1,0,0,1),0, LAVA);
setExpandedStrings(LINEAR);
setDrawingRules(LINEAR);
axiom = "FX";
for(int i = 0; i < 3; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(LINEAR, currTurt, turtleStack, newChunks);
}
}
}
void Terrain :: makeTreeAtChunk(Chunk* chunk) {
QHash <uint64_t, Chunk*> newChunks;
float zCoord = (int) (chunk->xzCoord & 0x00000000FFFFFFFF);
float xCoord = (int) ((chunk->xzCoord >> 32));
float treeType = fbm(xCoord + 3, zCoord - 8);
float chance = fbm(xCoord + 1, zCoord + 10) * 1.f;
int randX = floor(fbm(xCoord, zCoord) * 16);
int randZ = floor(fbm(xCoord + 7, zCoord - 3) * 16);
float x = randX + xCoord;
float z = randZ + zCoord;
float heightTest = findTop(x,z);
BlockType soil = getBlockAt(x, heightTest - 1, z);
if(chance > 0.89) {
if(soil == DIRT) {
Turtle currTurt = Turtle(glm::vec4(x,heightTest,z,1),glm::vec4(0,1,0,1),0.5, BAMBOO);
QStack<Turtle> turtleStack;
setExpandedStrings(BAMBOOTREE);
setDrawingRules(DELTA);
QString axiom = "FX";
int branches = floor(fbm(xCoord + 12, zCoord - 12) * 2);
for(int i = 0; i < 2 + branches; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(BAMBOOTREE, currTurt, turtleStack, newChunks);
}
}
} else if (soil == GRASS) {
Turtle currTurt = Turtle(glm::vec4(x,heightTest,z,1),glm::vec4(0,1,0,1),2, WOOD);
QStack<Turtle> turtleStack;
setExpandedStrings(PINE);
setDrawingRules(DELTA);
QString axiom = "FX";
int branches = floor(fbm(xCoord + 12, zCoord - 12) * 2);
for(int i = 0; i < 1 + branches; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(TREE, currTurt, turtleStack, newChunks);
}
}
} else {
Turtle currTurt = Turtle(glm::vec4(x,heightTest,z,1),glm::vec4(0,1,0,1),1.5, WOOD);
QStack<Turtle> turtleStack;
setExpandedStrings(TREE);
setDrawingRules(DELTA);
QString axiom = "FX";
int branches = floor(fbm(xCoord + 12, zCoord - 12) * 2);
for(int i = 0; i < 1 + branches; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(PINE, currTurt, turtleStack, newChunks);
}
}
}
}
}
void Terrain :: makeTrees() {
QHash <uint64_t, Chunk*> newChunks;
for(auto p = chunkMap.begin(); p != chunkMap.end(); p++) {
float zCoord = (int) (p.key() & 0x00000000FFFFFFFF);
float xCoord = (int) ((p.key() >> 32));
float treeType = fbm(xCoord + 3, zCoord - 8);
float chance = fbm(xCoord + 1, zCoord + 10) * 1.f;
int randX = floor(fbm(xCoord, zCoord) * 16);
int randZ = floor(fbm(xCoord + 7, zCoord - 3) * 16);
float x = randX + xCoord;
float z = randZ + zCoord;
float heightTest = findTop(x,z);
BlockType soil = getBlockAt(x, heightTest - 1, z);
p.value()->filled;
if(chance > 0.7) {
if(soil == DIRT) {
Turtle currTurt = Turtle(glm::vec4(x,heightTest,z,1),glm::vec4(0,1,0,1),4, BAMBOO);
QStack<Turtle> turtleStack;
setExpandedStrings(BAMBOOTREE);
setDrawingRules(DELTA);
QString axiom = "FX";
int branches = floor(fbm(xCoord + 12, zCoord - 12) * 2);
for(int i = 0; i < 2 + branches; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(BAMBOOTREE, currTurt, turtleStack, newChunks);
}
}
} else if (soil == GRASS) {
Turtle currTurt = Turtle(glm::vec4(x,heightTest,z,1),glm::vec4(0,1,0,1),40, WOOD);
QStack<Turtle> turtleStack;
setExpandedStrings(PINE);
setDrawingRules(DELTA);
QString axiom = "FX";
int branches = floor(fbm(xCoord + 12, zCoord - 12) * 2);
for(int i = 0; i < 1 + branches; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(TREE, currTurt, turtleStack, newChunks);
}
}
} else {
Turtle currTurt = Turtle(glm::vec4(x,heightTest,z,1),glm::vec4(0,1,0,1),4, WOOD);
QStack<Turtle> turtleStack;
setExpandedStrings(TREE);
setDrawingRules(DELTA);
QString axiom = "FX";
int branches = floor(fbm(xCoord + 12, zCoord - 12) * 2);
for(int i = 0; i < 2 + branches; i++) {
expandString(axiom);
}
for(QChar c : axiom) {
if(charToDrawingOperation.contains(c)) {
Rule r = charToDrawingOperation.value(c);
(this->*r)(TREE, currTurt, turtleStack, newChunks);
}
}
}
}
p.value()->filled = true;
}
}
int Terrain::findTop(int x, int z) {
for(int y = 0; y < 256; y++) {
if(getBlockAt(x,y,z) == EMPTY) {
return y;
}
}
return 256;
}
float Terrain::calcHeightTest(int x, int z) {
return fmin(254, fbm(x / 128.f, z / 128.f) * 32.f + 129.f);
}
void Terrain::carve(int x, int z, int min, int radius, float fallOff, QHash <uint64_t, Chunk*>& newChunks) {
int posXHeight = calcHeightTest(x + radius + 1, z);
int posZHeight = calcHeightTest(x, z + radius + 1);
int negXHeight = calcHeightTest(x - radius - 1, z);
int negZHeight = calcHeightTest(x, z - radius - 1);
for(int i = -radius; i < radius + 1; i++) {
for(int j = -radius; j < radius + 1; j++) {
float interpX = glm::mix(negXHeight, posXHeight, ((float) (i + radius) / (2 * radius)));
float interpZ = glm::mix(negZHeight, posZHeight, ((float) (j + radius) / (2 * radius)));
float interpHeight = (interpX + interpZ) * 0.5f;
int height = min;
height = glm::mix(min, (int) interpHeight, ((float) (abs(i) + abs(j)) / (2 * radius))) + pow((abs(i) + abs(j)) * fallOff, 0.5);
// if(getBlockAt(x + i, height, z + j) != EMPTY && chunkExistsAt(x + i, height, z + j)) {
fillBetweenNewChunks(x + i, z + j, height, 255, EMPTY, newChunks);
//}
if (getChunkAt(x + i, z + j) != nullptr) {
// riverCreated.insert(getChunkAt(x + i, z + j));
}
if (getChunkAt(x + i + 1, z + j + 1) != nullptr) {
// riverCreated.insert(getChunkAt(x + i + 1, z + j + 1));
}
if (getChunkAt(x + i - 1, z + j - 1) != nullptr) {
// riverCreated.insert(getChunkAt(x + i - 1, z + j - 1));
}
// created.remove(getChunkAt(x + i, z + j));
// created.remove(getChunkAt(x + i - 1, z + j - 1));
// created.remove(getChunkAt(x + i + 1, z + j + 1));
// }
}
}
}
|
79a6caa55dd759671fe71744d59a32e324e26ddc | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2700486_0/C++/kraskevich/main.cpp | 7c4b30c077675c42d2b97e00f65d7beb52973212 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,905 | cpp | main.cpp | #include <algorithm>
#include <iostream>
#include <string.h>
#include <sstream>
#include <fstream>
#include <cassert>
#include <cstdlib>
#include <complex>
#include <cctype>
#include <cstdio>
#include <vector>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define pii pair<int, int>
int n;
int x, y;
int h[200];
double ans;
void go(int pos, int currX, int currY, double prob)
{
if (pos == n)
{
if (h[x] >= y)
ans += prob;
return;
}
currY = h[currX] + 2;
currY = max(currY, h[currX - 1] + 1);
currY = max(currY, h[currX + 1] + 1);
bool freeL = true;
bool freeR = true;
if (h[currX - 1] >= currY - 1)
freeL = false;
if (h[currX + 1] >= currY - 1)
freeR = false;
if (currY == 0)
freeL = freeR = false;
if (freeL)
go(pos, currX - 1, currY - 1, prob * (freeR ? 0.5 : 1.0));
if (freeR)
go(pos, currX + 1, currY - 1, prob * (freeL ? 0.5 : 1.0));
if (!freeL && !freeR)
{
int temp = h[currX];
h[currX] = currY;
go(pos + 1, 100, 10000, prob);
h[currX] = temp;
}
}
void solve(int test)
{
cin >> n >> x >> y;
x += 100;
fill(h, h + 200, -2);
ans = 0;
if (x >= 0 && x < 200)
go(0, 100, 10000, 1.0);
cout << "Case #" << test << ": ";
cout << ans;
cout << endl;
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cout.setf(ios::fixed);
cout.precision(10);
int T;
cin >> T;
for (int test = 1; test <= T; test++)
solve(test);
fclose(stdin);
fclose(stdout);
return 0;
}
|
14382ae68e4dfa9ce636cec0c3b886365a489bc9 | d1dc30ab429eec50de00f6d41c81fa5a4c7301e0 | /threadserveur.h | 33f99e4f7faa0cab2065fb064df499b3f4478c41 | [] | no_license | lehouxouelleta/cll12-GestionnaireAgile-Serveur | 4a01d81cf15d5a29857ca402e42cf8d32304bd50 | bf376a0be056c8b7e493dc58429543076bf4fc19 | refs/heads/master | 2020-06-01T00:41:18.232169 | 2012-05-16T18:30:14 | 2012-05-16T18:30:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | h | threadserveur.h | #ifndef THREADSERVEUR_H
#define THREADSERVEUR_H
#include <QThread>
#include "serveur.h"
class ThreadServeur : public QThread
{
Q_OBJECT
public:
explicit ThreadServeur(int Descriptor = 0);
QTcpSocket *socket;
int m_socketDescriptor;
int codeServeur;
QString nomClient;
QString codeClient;
QByteArray baTaches;
bool termine;
QString valide;
void run();
signals:
void siRecoieConnection(QString);
void siTermineConnection(QString);
void siTacheTerminee(QString,QString);
void siFermeture();
void siPrendreTache(QString,QString);
void siAbandon(QString,QString);
public slots:
void slNouvelleTache(QStringList);
void slDeconnection();
void slRepondu(QString);
};
#endif // THREADSERVEUR_H
|
7f0e9b6174c53b9c3a682ff46c40755b14eab404 | 76b8c20de3c1eab0719e3ef84f04f8cd84105ba0 | /VirtualMemory.cpp | e80776f3a900aff547fae591b1b2a47aff74a04d | [] | no_license | ornokrean/OS_ex4 | e01d3a48ea7b65ae3a7eb6d76ef4f04d572c1d01 | 9b31766ca972f8fd84f894e3cc1ecf4a23ec5459 | refs/heads/master | 2020-05-30T12:01:11.171567 | 2019-05-29T16:30:01 | 2019-05-29T16:30:01 | 189,720,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,363 | cpp | VirtualMemory.cpp | #include "VirtualMemory.h"
#include "PhysicalMemory.h"
#include "string.h"
#include <math.h>
#include <stdio.h>
#include <iostream>
using namespace std;
void clearTable(uint64_t frameIndex)
{
for (uint64_t i = 0; i < PAGE_SIZE; ++i)
{
PMwrite(frameIndex * PAGE_SIZE + i, 0);
}
}
/*
* Fills an int array with the p addresses and the offset.
* */
void getAddressParts(uint64_t vAddress, uint64_t *addresses)
{
int bitAnd = (1 << OFFSET_WIDTH) - 1; //Creates 1^OFFSET_WIDTH
// For doing this with an array
for (int i = TABLES_DEPTH; i >= 0; --i)
{
addresses[i] = (vAddress & bitAnd);
//Shift right by offset width to get the next spot:
// cout << vAddress << endl;
vAddress = (vAddress >> OFFSET_WIDTH);
}
// cout << "ARRAY" << endl;
// for (int j = 0; j <= TABLES_DEPTH; ++j)
// {
//
// cout << addresses[j] << endl;
// }
}
/*
* Returns offset
* */
uint64_t getOFFSET(uint64_t vAddress)
{
int bitAnd = (1 << OFFSET_WIDTH) - 1; //Creates 1^OFFSET_WIDTH
return (vAddress & bitAnd);
}
/*Returns true if the frame is empty*/
bool isClear(uint64_t frameIndex)
{
int w = 0;
for (uint64_t i = 0; i < PAGE_SIZE; ++i)
{
PMread(frameIndex * PAGE_SIZE + i, &w);
if (w != 0)
{
return false;
}
}
return true;
}
uint64_t calcCyclicDistance(uint64_t from, uint64_t to)
{
if (to - from < NUM_PAGES - (to - from))
{
return to - from;
}
return NUM_PAGES - (to - from);
}
//
//void findCyclicDistance(uint64_t page_num, int depth, uint64_t frame_index, uint64_t fixed_page,
// uint64_t *currentMaxDistPage)
//{
// //If reached actual page
// if (depth == TABLES_DEPTH)
// {
// //Calculate the minimal distance between the current page and the page to insert:
// //Update the max distance frame if the new distance is larger:
// if (calcCyclicDistance(page_num, fixed_page) > calcCyclicDistance(*currentMaxDistPage, fixed_page))
// {
// *currentMaxDistPage = page_num;
// }
// return;
// }
// // Update the page number - each round, we shift it OFFSET_WIDTH bits to the left to make room for the next "part"
// page_num <<= OFFSET_WIDTH;
// int word = 0;
//
// for (uint64_t i = 0; i < PAGE_SIZE; ++i)
// {
// //Get the next frame
// PMread(frame_index * PAGE_SIZE + i, &word);
// if (word != 0)
// {
// findCyclicDistance(page_num + i, depth + 1, uint64_t(word), fixed_page, currentMaxDistPage);
// }
// }
//}
//
///*
// * Finds an empty frame (a frame with 0 in all its rows) which is not the protected frame
// * */
//void findEmptyFrame(uint64_t frame, uint64_t protectedFrame, uint64_t *clearFrame)
//{
// // Empty frame found - exit recursion
// if (*clearFrame != -1)
// {
// return;
// }
// //If the frame is empty and it is not the frame we don't want to use:
// if (isClear(frame) && frame != protectedFrame)
// {
// *clearFrame = frame;
// return;
// }
// int word = 0;
// for (uint64_t i = 0; i < PAGE_SIZE; ++i)
// {
// PMread(frame * PAGE_SIZE + i, &word);
// if (word != 0)
// {
// findEmptyFrame(uint64_t(word), protectedFrame, clearFrame);
// }
// }
//}
//
///*
// * Traverses the tree in DFS, and saves the max index of frames visited
// * */
//void findMax(uint64_t frameIndex, uint64_t *maxFrame)
//{
// int word = 0;
// for (uint64_t i = 0; i < PAGE_SIZE; ++i)
// {
// PMread(frameIndex * PAGE_SIZE + i, &word);
// if (word != 0)
// {
// if (word > *maxFrame)
// {
// *maxFrame = uint64_t(word);
// }
// findMax(uint64_t(word), maxFrame);
// }
// }
//
//}
void
combinedFind(uint64_t frameIndex, uint64_t *emptyFrame, uint64_t *maxFrame, uint64_t *cyclicFrame,
uint64_t protectedFrame, uint64_t constructedPageNum, int depth, uint64_t pageToInsert,
uint64_t parent, uint64_t *cycPageNum, uint64_t *stepParent)
{
//Found empty frame already, no need to continue search
if (*emptyFrame > 0)
{
return;
}
//
if (depth == TABLES_DEPTH)
{
//Calculate the minimal distance between the current page and the page to insert:
//Update the max distance frame if the new distance is larger:
if (*cyclicFrame == pageToInsert ||
calcCyclicDistance(constructedPageNum, pageToInsert) <
calcCyclicDistance(*cyclicFrame, pageToInsert))
{
*cyclicFrame = frameIndex;
*cycPageNum = constructedPageNum;
*stepParent = parent;
}
return;
}
//If the frame is empty and it is not the frame we don't want to use:
if (isClear(frameIndex) && frameIndex != protectedFrame && frameIndex != 0)
{
PMwrite(parent * PAGE_SIZE + getOFFSET(constructedPageNum), 0);
*emptyFrame = frameIndex;
return;
}
int word = 0;
constructedPageNum <<= OFFSET_WIDTH;
for (uint64_t i = 0; i < PAGE_SIZE; ++i)
{
PMread(frameIndex * PAGE_SIZE + i, &word);
if (word != 0)
{
if (word > *maxFrame)
{
*maxFrame = uint64_t(word);
}
combinedFind(uint64_t(word), emptyFrame, maxFrame, cyclicFrame, protectedFrame,
constructedPageNum + i,
depth + 1, pageToInsert, frameIndex, cycPageNum, stepParent);
}
}
}
/*
* Finds an available frame and returns its index
* Priority:
* Empty>Unused>Used(Needs evicting)
* */
uint64_t getFrame(uint64_t protectedFrame, uint64_t page_num)
{
//First Priority: Empty Frame
uint64_t emptyFrame = 0;
uint64_t maxFrame = 0;
uint64_t cyclicFrame = page_num;
uint64_t parent = 0;
uint64_t cyclicPageNum = 0;
combinedFind(0, &emptyFrame, &maxFrame, &cyclicFrame, protectedFrame, 0, 0, page_num,
0, &cyclicPageNum, &parent);
//First Priority: Empty Frame
if (emptyFrame > 0)
{
return emptyFrame;
}
//Second Priority: Unused Frame:
//Case: RAM not full yet
if (maxFrame + 1 < NUM_FRAMES)
{
return maxFrame + 1;
}
//Third Priority: Evict a page:
if (cyclicFrame > 0)
{
PMevict(cyclicFrame, cyclicPageNum);
PMwrite(parent * PAGE_SIZE + getOFFSET(cyclicPageNum), 0);
return cyclicFrame;
}
return 0;
}
//TODO: Important!!!!!! When moving an empty frame or evicting a page
/*
* Returns the frame index of the given page_num
* */
uint64_t translateVaddress(const uint64_t page_num, const uint64_t *addresses)
{
int depth = 0;
int pageWord = 0;
uint64_t currentFrame = 0;
uint64_t pageIndexInFrame = 0;
//Run on each p in addresses- not including the offset d which is in the last spot
while (depth < TABLES_DEPTH)
{
pageIndexInFrame = addresses[depth];
//cout << pageIndexInFrame << endl;
PMread(currentFrame * PAGE_SIZE + pageIndexInFrame, &pageWord);
//Case: Page Fault- handle importing frame
if (pageWord == 0)
{
/*Find an unused frame or evict a page from some frame*/
uint64_t frame = getFrame(currentFrame, page_num);
if (frame == 0)
{
return 0;
}
//Case: Actual Page table and not a page of page tables
if (depth + 1 == TABLES_DEPTH)
{
/*Restore from disk*/
PMrestore(frame, page_num);
}
else
{
/*Write 0's to all rows*/
clearTable(uint64_t(frame));
}
pageWord = int(frame);
//Update the "parent" with the relevant frame index
PMwrite(currentFrame * PAGE_SIZE + pageIndexInFrame, pageWord);
}
currentFrame = uint64_t(pageWord);
depth++;
}
//This is the resulting page we get from the loop: the index of the last page's frame
return uint64_t(pageWord);
}
void VMinitialize()
{
clearTable(0);
}
int VMread(uint64_t virtualAddress, word_t *value)
{
uint64_t paddresses[TABLES_DEPTH + 1];
getAddressParts(virtualAddress, paddresses);
uint64_t addr = translateVaddress((virtualAddress >> OFFSET_WIDTH), paddresses);
//Case: Virtual address cannot be mapped
if (addr < 1)
{
return 0;
}
PMread(addr * PAGE_SIZE + paddresses[TABLES_DEPTH], value);
return 1;
}
int VMwrite(uint64_t virtualAddress, word_t value)
{
uint64_t paddresses[TABLES_DEPTH + 1];
getAddressParts(virtualAddress, paddresses);
uint64_t addr = translateVaddress((virtualAddress >> OFFSET_WIDTH), paddresses);
//Case: Virtual address cannot be mapped
if (addr < 1)
{
return 0;
}
PMwrite(addr * PAGE_SIZE + paddresses[TABLES_DEPTH], value);
return 1;
}
/*----------------------------------------- General Work Flow -----------------------------------------*/
/*TODO Tasks:
1. Split the input address correctly to separate parts: p1...pn,d.
2. Write a DFS algorithm that searches for an empty frame
3. Handle Evicting pages
4. Recursive function for handling each p_i, where each such recursion takes heed not to
evict frames set there by previous p's
5. Frame Choice:
5.1: Empty Frame: All rows are 0. No need to evict, but remove the reference to it from its parent
5.2: Unused Frame: Since we fill frames in order in the beginning, all used frames are in the memory
one after the other. So, if max_frame_index+1<NUM_FRAMES then frame at index max_frame_index+1
#When traversing the tree, keep an index of the maximal frame visited and of the page visited
*/
/*
* helper for printTree
*/
void printSubTree1(uint64_t root, int depth, bool isEmptyMode)
{
if (depth == TABLES_DEPTH)
{
return;
}
word_t currValue = 0;
if ((isEmptyMode || root == 0) && depth != 0)
{
isEmptyMode = true;
}
//right son
PMread(root * PAGE_SIZE + 1, &currValue);
printSubTree1(static_cast<uint64_t>(currValue), depth + 1, isEmptyMode);
//father
for (int _ = 0; _ < depth; _++)
{
std::cout << '\t';
}
if (isEmptyMode)
{
std::cout << '_' << '\n';
}
else
{
if (depth == TABLES_DEPTH - 1)
{
word_t a, b;
PMread(root * PAGE_SIZE + 0, &a);
PMread(root * PAGE_SIZE + 1, &b);
std::cout << root << " -> (" << a << ',' << b << ")\n";
}
else
{
std::cout << root << '\n';
}
}
//left son
PMread(root
* PAGE_SIZE + 0, &currValue);
printSubTree1(static_cast <uint64_t>(currValue), depth + 1, isEmptyMode);
}
/**
* print's the virtual memory tree. feel free to use this function is Virtual Memory for debuging.
*/
void printTree1()
{
std::cout << "---------------------" << '\n';
std::cout << "Virtual Memory:" << '\n';
printSubTree1(0, 0, false);
std::cout << "---------------------" << '\n';
}
|
df0dd4fbaccf0ac5af16db2333d458476e353c0f | f9ef4458855e0e21c5bdd83fb706541cdced2e6f | /yquest_server/src/constants.h | f1e5d724e5dc3ba0895320d1828e8f40ce4015fa | [] | no_license | Chudovishee/yquest | 4e3778681d3017f2ea91af8444bf41153dc52a5d | 452c113c38a3ef9601ac35e0f735617e04c7bc4c | refs/heads/master | 2021-01-19T00:30:30.465816 | 2011-09-22T16:18:15 | 2011-09-22T16:18:15 | 2,416,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 934 | h | constants.h |
#ifndef CONSTANTS
#define CONSTANTS
#include <string>
//protocol
const int YQUEST_PROTOCOL = 1;
//commands
const int noneCommand = 0;
const int authCommand = 1;
const int protocolCommand = 2;
//errors
const int NOT_ERROR = 0;
const int PROTOCOL_ERROR = 1;
const int SERVER_CONFIG_ERROR = 5;
const int SERVER_DB_ERROR = 6;
const int unauthorized_mail = 2;
const int unauthorized_name = 3;
const int unauthorized_password = 4;
const int duplicate_mail = 7;
const int login_fail = 8;
const int google_login_fail = 9;
const int auth_fail = 10; //токен и ид не прошли проверку при выполнении комманды
const int auth_ok = 12;
const int command_fail = 11; //команда зафэйлилась или не была найдена
//user
const int google_auth = 1;
const int yquest_auth = 2;
const int auth_token_expiration = 60;//86400; //1день
#endif
|
976c0bd8c58dc3ffbe54dc88be1308e0b47cb341 | 71a6e955c82acf6a41d69dfd49dd053cd5000da9 | /src/mcckeyboardcmdrecord.h | 4898a5c06d39325f195ecdd108265a0f083e77bd | [] | no_license | iElaine/mcc_old | 9100073e11305b89202cfa98219bac2011f198dc | 7e2ca172bd57e27dc8c687e4105c34fc3f96942d | refs/heads/master | 2016-09-05T12:33:04.888487 | 2013-12-11T06:05:47 | 2013-12-11T06:05:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,281 | h | mcckeyboardcmdrecord.h | /**
* @file mcckeyboardcmdrecord.h
* @author TommyWang Email<xuchu1986@gmail.com>
* @brief
*/
#ifndef __MCCKEYBOARDCMDRECORD_H__
#define __MCCKEYBOARDCMDRECORD_H__
#include "mcckeyboard.h"
#include <cstdio>
#include <string.h>
#define EXT_NAME ".rec"
enum eKBCmdValue {
eKBValue_0 = 0,
eKBValue_1,
eKBValue_2,
eKBValue_3,
eKBValue_4,
eKBValue_5,
eKBValue_6,
eKBValue_7,
eKBValue_8,
eKBValue_9,
};
class MCCKeyboardCmdRecordSet {
public:
MCCKeyboardCmdRecordSet() {};
MCCKeyboardCmdRecordSet(const char *name, int baudrate, int databits, int stopbits, char parity);
int AddRecord(void *cmd, int len, eKBCmdValue value);
void Init(const char *name, int baudrate, int databits, int stopbits, char parity);
int DumpToFile(const char *filename = NULL);
protected:
struct Record{
};
char m_name[256];
int m_baudrate;
int m_databits;
int m_stopbits;
char m_parity;
std::vector<MCCKeyboardCmdRecord> m_records;
};
class MCCKeyboardCmdRecord {
public:
/**
* @brief constructor
*/
MCCKeyboardCmdRecord();
MCCKeyboardCmdRecord(void *p_cmd, int length, eKBCmdValue kvalue);
/**
* @brief destructor
*/
virtual ~MCCKeyboardCmdRecord();
void *cmd;
int len;
eKBCmdValue value;
};
#endif /* __MCCKEYBOARDCMDRECORD_H__ */
|
1931c2e57ddf82e51aacab7e75ccedf36b240146 | dd35b04e77ddf0e83e2eaf324b154cb5d56bfe86 | /CS441 (Multiple Lanugages)/CountPrimes.cpp | 642d9143a774c30ba180966e5761499c20622ef7 | [] | no_license | styro103/AcademicPrograms | 7afb3ab8d588c467a90cae38ef6c03fc53ddeb1b | 87cfc71903d750b7465d02d56c6accd6cf25450d | refs/heads/master | 2021-01-22T23:15:26.318873 | 2016-01-28T15:29:48 | 2016-01-28T15:29:48 | 20,346,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | cpp | CountPrimes.cpp | /*
Shaun Mbateng
CS 441 - J. Sorenson
MPI Counting Primes
April 21, 2014
*/
#include <iostream>
#include <cmath>
#include "mpi.h"
using namespace std;
int main (int argc, char * argv[]);
int prime_number (int n, int id, int np);
int main (int argc, char * argv[])
{
int id; //For Rank
int n; //Number to Count to
int np; //Number of Processes
int primes; //Big Number of Primes (For MPI Reduce)
int primes_count; //Number of Primes
MPI_Init(&argc,&argv); // start up MPI
MPI_Comm_size(MPI_COMM_WORLD, &np); // get number of processors
MPI_Comm_rank(MPI_COMM_WORLD, &id); // get my ID number
if(id==0) // Enter Number to Count To
{
cout <<""<<endl;
cout<<"***Prime Number Counter***"<<endl;
cout << "Please enter n: ";
cin >> n;
}
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD); // share n with broadcast
primes_count = prime_number(n, id, np); //Get Number of Primes
MPI_Reduce(&primes_count, &primes, 1, MPI_INT, MPI_SUM,0,MPI_COMM_WORLD); //Reduce Number of Primes to "primes" Variable
if (id == 0) //Display Value of n, and Number of Primes
{
cout <<""<<endl;
cout <<"Number of Processors = "<<np<<endl;
cout << "n = " << n <<endl;
cout << "No. of Primes = "<<primes<<endl;
cout <<""<<endl;
}
MPI_Finalize(); // done!
return 0;
}
int prime_number(int n, int id, int np) //Function That Returns Number of Primes by Striping
{
int count = 0; //Integer to Hold Count of Primes, Initialized to Zero
for (int i = 2 + id; i <= n; i = i + np) // Count Primes with Striping
{
//These Were Added to Make the Program Do Less Searching, and Run Faster
if (i % 2 == 0 && np % 2 == 0 && i > 2) //If i is Even, and so is np, and i>2
break; //Break Out of Loop, All Following i's Will be Even, and Thus Not Prime
if (i % 2 == 0 && i > 2) //If i is Even and Greater Than 2, Not Prime, Go to Next Loop Iteration
continue;
int prime = 1; //Integer to Test Whether Prime or Not, Initialized to 1
for (int j = 2; j <= sqrt(i); j++) //From 2 till Square Root of i
{
if ((i % j) == 0) //Check if Evenly Divides
{
prime = 0; //If So Break
break;
}
}
count += prime; //Increment Count if Necessary
}
return count; //Return Count
}
/*
--Sample Run--
***Prime Number Counter***
Please enter n: 1000000000
Number of Processors = 32
n = 1000000000
No. of Primes = 50847534
*/
|
32126a1ebea4b2ee53a475361933e5a7ba327e26 | a3a12224ce1742689598066bcfd039c9ce10e446 | /codeforces/268b.cpp | 71a61538541eb3b21ca3b3af3c06a33643d1cac2 | [] | no_license | sasankrajeev/Codeforces | 6c6e72f48fffb74f1bcc2ddf21eecd02c35e394e | ebb0a5e2f968cb3a74319a05d3381004d7e46cc2 | refs/heads/master | 2020-03-23T12:45:08.159911 | 2018-09-06T18:09:14 | 2018-09-06T18:09:14 | 141,579,485 | 0 | 0 | null | 2018-07-19T13:16:18 | 2018-07-19T12:55:19 | C++ | UTF-8 | C++ | false | false | 330 | cpp | 268b.cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n,i,s=0,l=0,k=1;
cin >> n;
if(n==1){
cout<<1;
}else if(n==2){
cout<<3;
}else{
for(i=1;i<=n-2;i++){
s=s+(n-i-1)*(k)+(n-i);
l++;
k++;
}
cout<<s+n+1;
}
return 0;
}
|
f7e79cd564c441341e7bdd498cd5b013d2c20c9b | ea30c450430c9bf032aa942c390da6da3d3aeec6 | /FoamTarget/LEDs.h | 2d5b39651c995eb4464d60a50e80361fba426704 | [
"Apache-2.0"
] | permissive | BenjaminPelletier/FoamTargets | 327b7e7214fd8d7e4cfda98998c7b19df65abd9d | 65b00792decefc3546139efb82d8115c1f7de6b5 | refs/heads/main | 2023-08-31T21:43:15.690733 | 2021-01-09T11:00:47 | 2021-01-09T11:04:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,684 | h | LEDs.h | #ifndef LEDs_h
#define LEDs_h
// TODO: https://github.com/FastLED/FastLED/issues/507 https://randomnerdtutorials.com/esp32-dual-core-arduino-ide/
struct TargetStyles {
typedef enum : uint8_t {
blank = 0,
blankHit,
red,
redHit,
blue,
blueHit,
green,
redSelected,
blueSelected,
rainbow
} Style;
};
typedef bool(*DrawTargetHandler)(const int* sides, uint16_t* animationFrame, unsigned long* tLastFrame, unsigned long tNow);
#define declDraw(handlerName) bool handlerName(const int* s, uint16_t* f, unsigned long* t0, unsigned long t)
declDraw(bDrawBlank); declDraw(sDrawBlank);
declDraw(bDrawBlankHit); declDraw(sDrawBlankHit);
declDraw(bDrawRed); declDraw(sDrawRed);
declDraw(bDrawRedHit); declDraw(sDrawRedHit);
declDraw(bDrawBlue); declDraw(sDrawBlue);
declDraw(bDrawBlueHit); declDraw(sDrawBlueHit);
declDraw(bDrawGreen); declDraw(sDrawGreen);
declDraw(bDrawRedSelected); declDraw(sDrawRedSelected);
declDraw(bDrawBlueSelected); declDraw(sDrawBlueSelected);
declDraw(bDrawRainbow); declDraw(sDrawRainbow);
const DrawTargetHandler bigHandlers[] = {
bDrawBlank,
bDrawBlankHit,
bDrawRed,
bDrawRedHit,
bDrawBlue,
bDrawBlueHit,
bDrawGreen,
bDrawRedSelected,
bDrawBlueSelected,
bDrawRainbow,
};
const DrawTargetHandler smallHandlers[] = {
sDrawBlank,
sDrawBlankHit,
sDrawRed,
sDrawRedHit,
sDrawBlue,
sDrawBlueHit,
sDrawGreen,
sDrawRedSelected,
sDrawBlueSelected,
sDrawRainbow
};
class TargetDisplay {
public:
TargetStyles::Style styleIdle;
TargetStyles::Style styleHit;
uint16_t animationFrame;
unsigned long tLastFrame;
void resetAnimation();
};
void TargetDisplay::resetAnimation() {
animationFrame = 0;
tLastFrame = 0;
}
const int NUM_LEDS = 74;
const uint8_t NUM_TARGETS = 5;
TargetDisplay targetDisplays[NUM_TARGETS];
const uint8_t NUM_SMALL_TARGET_SIDES = 4;
const int targetSides[][NUM_SMALL_TARGET_SIDES] = {
{ 2, 3, 0, 1 },
{ 17, 4, 0, 0 },
{ 25, 22, 23, 24 },
{ 49, 26, 0, 0 },
{ 44, 31, 0, 0 },
};
const uint8_t INDICATOR_TOP_INDEX = 9;
const uint8_t INDICATOR_TOP_LENGTH = 8;
const uint8_t INDICATOR_BOTTOM_INDEX = 36;
const uint8_t INDICATOR_BOTTOM_LENGTH = 8;
const uint8_t INDICATOR_SIDE_INDEX = 54;
const uint8_t INDICATOR_SIDE_LENGTH = 20;
const uint8_t BIG_SIDE_LENGTH = 5;
CRGB leds[NUM_LEDS];
class CRGB2 {
public:
enum {
VeryDarkRed = 0x200000,
VeryDarkBlue = 0x000020
} ExtendedColors;
};
const CRGB SPECTRUM[] = { CRGB::Red, CRGB::Orange, CRGB::Yellow, CRGB::Green, CRGB::Cyan, CRGB::Blue, CRGB::Indigo, CRGB::Violet, CRGB::Magenta };
const uint8_t SPECTRUM_LENGTH = sizeof(SPECTRUM) / sizeof(CRGB);
#endif
|
c373f95f4052b25a93dd6621cdafcb8c6fdee457 | b04636f31f716c21a6c0d77bc49b876bc496fff7 | /Olympiad/VOI/VO Online 2019/Jury files/Contestants/Blablabla/danang.cpp | 3d95d1b4501d16e69149de5bf758578d94225d99 | [] | no_license | khanhvu207/competitiveprogramming | 736b15d46a24b93829f47e5a7dbcf461f4c30e9e | ae104488ec605a3d197740a270058401bc9c83df | refs/heads/master | 2021-12-01T00:52:43.729734 | 2021-11-23T23:29:31 | 2021-11-23T23:29:31 | 158,355,181 | 19 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,564 | cpp | danang.cpp | #include <bits/stdc++.h>
using namespace std;
#define fi "danang.inp"
#define fo "danang.out"
#define oo 1e18
#define maxn 200005
#define tr(i,c) for (__typeof((c).begin()) i=(c).begin();i!=(c).end();i++)
#define For(i,a,b) for (int i=a;i<=b;i++)
typedef pair<int64_t,int64_t> II;
set <II> s;
vector <II> a[maxn];
int64_t kc[maxn],dd[maxn],tr[maxn];
int m,n,k;
int64_t d;
void dijkstra(int64_t s1) {
For(i,1,n) kc[i]=oo,dd[i]=0;
s.clear();
dd[s1]=1;
kc[s1]=0;
tr[s1]=0;
s.insert(II(kc[s1],s1));
while (!s.empty()) {
II x=*s.begin();
s.erase(x);
int u=x.second;
tr(it,a[u]) {
int64_t v=(*it).first;
int64_t l=(*it).second;
if (tr[u]+d<=l) {
if (kc[v]>kc[u]+l) {
if (dd[v]) s.erase(II(kc[v],v));
kc[v]=kc[u]+l;
dd[v]=1;
s.insert(II(kc[v],v));
tr[v]=l;
}
else if (kc[v]==kc[u]+l)
if (tr[v]>l) tr[v]=l;
}
}
}
}
int main()
{
freopen(fi,"r",stdin);
freopen(fo,"w",stdout);
scanf("%d%d%I64d",&n,&m,&d);
For(i,1,m) {
int64_t u,v,uv;
scanf("%I64d%I64d%I64d",&u,&v,&uv);
a[v].push_back(II(u,uv));
a[u].push_back(II(v,uv));
}
For(i,1,n) a[i].push_back(II(0,0));
For(i,1,n) tr[i]=oo;
dijkstra(1);
if (kc[n]==oo) kc[n]=-1;
cout<<kc[n];
For(i,1,n) cout<<tr[i]<<" ";
return 0;
}
|
eefe3c2cd2fa8529fac0d49db47f95f01f011dbd | 04d45ce6c8de7cff18aae9a7e3bde12501b7c3fa | /bakwaas.cpp | 0244b8dbfc58fed49192085a1fedc2067f115c70 | [] | no_license | anandheritage/codes | 7e7cb28476054f7bfe2cfc38b59d05c24ce6336a | a763d838fba222cfd7bdb128380347c89594c1f7 | refs/heads/master | 2020-06-02T20:03:34.892475 | 2014-06-22T06:20:23 | 2014-06-22T06:20:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,784 | cpp | bakwaas.cpp | #include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
struct data
{
int value;
int index;
};
bool key(const data & i,const data & j) {
return (i.value > j.value);
}
struct data diff[1001];
int L[1001][1001],B[1001][1001],C[1001][1001];
int a[1001],rel[1001];
int main(void)
{
int t,n,m,k,maxi=0,i,j;
for(scanf("%d",&t);t>0;t--)
{
scanf("%d%d%d",&n,&m,&k);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&B[i][j]);
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&C[i][j]);
L[i][j]=B[i][j]-C[i][j];
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(j!=a[i])
{
if(maxi<L[i][j])
maxi=L[i][j];
}
}
if(maxi>L[i][a[i]])
{
visit[i]=1;
diff[i].value=maxi-L[i][a[i]];
rel[i]=maxi;
diff[i].index=i;
}
else
rel[i]=L[i][a[i]];
}
sort(diff+1, diff+n+1,key);
for(i=1;i<=k;i++)
{
if(diff[i].value>0)
{
a[diff[i].index]=rel[diff[i].index];
printf("gg");
}
}
int sum=0;
for(i=1;i<=n;i++)
{
if(visit[i]==1)
{
sum=sum+rel[i];
}
else
sum=sum+B[i][a[i]];
printf("%d\n",a[i]);
}
printf("%d\n",sum);
}
}
|
0d26c448eade0221b9ed3ff02fb3b054e6667dc4 | 49346e3693803acf722b0edcb0aeac19cff60268 | /9_struct1/main.cpp | d3f8f90571083759a7ca601b2f8267b17eea04b5 | [] | no_license | Polina120A/AAP | 906469c0eb2002127116129bb776446265abdecb | 7162757bbc771bd09299a78d90432696cee48b35 | refs/heads/main | 2023-05-09T10:43:35.845427 | 2021-06-02T14:38:05 | 2021-06-02T14:38:05 | 342,288,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | main.cpp | //Робот-автомобиль описывается как структура с полями: скорость, длительность движения и номер. Напишите функцию для расчёта пройденного расстояния.
#include <iostream>
#include <fstream>
struct Robot{
float S, t;
};
int main()
{
Robot a,b;
std::ifstream fin;
fin.open("data.txt");
fin >> a.S >> b.t;
fin.close();
float d = a.S/b.t;
std::cout << d;
return 0;
}
|
018149cf4221c14410f5d478396081b9d56513ae | 46e423f7d8d9dc7b07c01297de43f1d3837d192f | /Source/chimera/Actor.cpp | 9930cd7667475b15c5efea959ee146d30ceca3af | [] | no_license | moresascha/Chimera | 34fd188c2e364ef9f484e532db194438eea4b9cd | e9cc2027e6866cdad471c3a8e6a30dd0614df1a9 | refs/heads/master | 2020-05-19T15:34:15.735279 | 2016-09-27T20:31:03 | 2016-09-27T20:31:03 | 11,747,790 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cpp | Actor.cpp | #include "Actor.h"
namespace chimera
{
Actor::Actor(ActorId id) : IActor(id)
{
std::stringstream ss;
ss << "Actor_";
ss << m_id;
SetName(ss.str());
}
/*VOID Actor::VReplaceComponent(std::unique_ptr<IActorComponent> pComponent)
{
auto it = m_components.find(pComponent->VGetComponentId());
if(it == this->m_components.end())
{
LOG_WARNING("Nothing to replace");
return;
}
it->second->VDestroy();
this->m_components.erase(it);
this->m_components[pComponent->VGetComponentId()] = pComponent;
} */
} |
9cc624f7022559a6b00764e47ec6600967b5ae80 | f463b1ef906e2032ec7a2b0efa7ec45cc1d44bb7 | /roboteam_ai/src/bt/composites/MemSelector.cpp | 4f70e5e40f5c36f9f68a26244c0aca3e382e30c9 | [
"MIT"
] | permissive | ThijsLuttikhuis/roboteam_ai | bfbb3087c90d24d18bb7452f5e917a7fd9a2a76f | 9114cae354629333dd9842e22ed05186e89fb1cd | refs/heads/master | 2020-04-13T08:28:12.878606 | 2018-12-20T11:26:54 | 2018-12-20T11:26:54 | 163,082,080 | 0 | 0 | null | 2018-12-25T12:45:56 | 2018-12-25T12:45:55 | null | UTF-8 | C++ | false | false | 693 | cpp | MemSelector.cpp | #include "MemSelector.hpp"
namespace bt {
void MemSelector::initialize() {
index = 0;
}
Node::Status MemSelector::update() {
if (HasNoChildren()) {
return Status::Success;
}
// Keep going until a child behavior says it's running.
while (index < children.size()) {
auto &child = children.at(index);
auto status = child->tick();
// If the child succeeds, or keeps running, do the same.
if (status != Status::Failure) {
return status;
}
index ++;
}
return Status::Failure;
}
using Ptr = std::shared_ptr<MemSelector>;
std::string MemSelector::node_name() {
return "MemSelector";
}
} //bt
|
57d1040e85f23b2703506fa71dee38e04861403c | bc52a14f02b9e4294121e092949233bc1d8b3f32 | /src/MacOS/MacHelper.hpp | d95bcee53b94ccb038c7a9cfe63d1bed73926dc0 | [] | no_license | krzystooof/IntersectionSimulator | 329c4674adb4fc256d22a4bb503ed12a4a7c89df | 97e88e171e3516e19794966c7af5cc843b1ae22a | refs/heads/master | 2020-06-13T06:09:45.018662 | 2019-07-01T16:36:44 | 2019-07-01T16:36:44 | 194,564,816 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | hpp | MacHelper.hpp | #ifndef MACOS_HELPER_HPP
#define MACOS_HELPER_HPP
#include "CoreFoundation/CoreFoundation.h"
class MacHelper
{
public:
MacHelper();
};
#endif // MACOS_HELPER_HPP
|
4ab55b0cbe8f23039b928ff2c54cdd22f38ca1df | db96b049c8e27f723fcb2f3a99291e631f1a1801 | /src/sample/app/deployable_cgi/sample.cpp | 9a61dc5edb5fa2a30933d39d92b74f159670cdc2 | [] | no_license | Watch-Later/ncbi-cxx-toolkit-public | 1c3a2502b21c7c5cee2c20c39e37861351bd2c05 | 39eede0aea59742ca4d346a6411b709a8566b269 | refs/heads/master | 2023-08-15T14:54:41.973806 | 2021-10-04T04:03:02 | 2021-10-04T04:03:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,128 | cpp | sample.cpp | /* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Denis Vakatov
*
* File Description:
* Plain example of a CGI/FastCGI application.
*
* USAGE: sample.cgi?message=Some+Message
*
* NOTE:
* 1) needs HTML template file "cgi.html" in curr. dir to run,
* 2) needs configuration file "cgi.ini",
* 3) on most systems, you must make sure the executable's extension
* is '.cgi'.
*
*/
#include <ncbi_pch.hpp>
#include <cgi/cgiapp.hpp>
#include <cgi/cgictx.hpp>
#include <html/html.hpp>
#include "deployable_cgi.hpp"
USING_NCBI_SCOPE;
#define NEED_SET_DEPLOYMENT_UID
/////////////////////////////////////////////////////////////////////////////
// CCgiSampleApplication::
//
void CCgiSampleApplication::Init()
{
// Standard CGI framework initialization
CCgiApplication::Init();
// Describe possible cmd-line and HTTP entries
// (optional)
x_SetupArgs();
}
void CCgiSampleApplication::x_SetupArgs()
{
// Disregard the case of CGI arguments
SetRequestFlags(CCgiRequest::fCaseInsensitiveArgs);
// Create CGI argument descriptions class
// (For CGI applications only keys can be used)
unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
// Specify USAGE context
arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
"CGI sample application");
arg_desc->AddOptionalKey("message",
"message",
"Message passed to CGI application",
CArgDescriptions::eString,
CArgDescriptions::fAllowMultiple);
// Setup arg.descriptions for this application
SetupArgDescriptions(arg_desc.release());
}
void CCgiSampleApplication::x_LookAtArgs()
{
// You can catch CArgException& here to process argument errors,
// or you can handle it in OnException()
const CArgs& args = GetArgs();
// "args" now contains both command line arguments and the arguments
// extracted from the HTTP request
if ( args["message"] ) {
// get the first "message" argument only...
const string& m = args["message"].AsString();
(void) m.c_str(); // just get rid of compiler warning about unused variable
// ...or get the whole list of "message" arguments
const auto& values = args["message"].GetStringList(); // const CArgValue::TStringArray&
for (const auto& v : values) {
// do something with each message 'v' (string)
(void) v.c_str(); // just get rid of compiler warning about unused variable
}
} else {
// no "message" argument is present
}
}
/////////////////////////////////////////////////////////////////////////////
// MAIN
//
int NcbiSys_main(int argc, ncbi::TXChar* argv[])
{
return CCgiSampleApplication().AppMain(argc, argv);
}
|
40668c34b09178423c23776b33f715a8cf2a4b8e | c6fd85f8c23bac14e1db7e18bf5afd4a3feede20 | /arduino/hardware/arduino/cores/arduino/Serial.cpp | e55bbabfe32b2bee64f54d55ad4f476f2749b5d7 | [] | no_license | linksprite/ucos-ii-for-pcDuino | 3a49490b87aa49a2eb3b0b701623fe6a2ace2ebe | a78cccadcab1989b84d6ecfcf8524e7cfe85760b | refs/heads/master | 2016-09-11T04:17:31.002353 | 2014-02-19T18:01:10 | 2014-02-19T18:01:10 | 16,992,461 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 7,522 | cpp | Serial.cpp | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "Arduino.h"
#include "wiring_private.h"
#include <termios.h>
#include "Serial.h"
HwSerial Serial;
void serialEvent() __attribute__((weak));
#define serialEvent_implemented
void serialEvent()
{
Serial.process_recv();
}
void serialEventRun(void)
{
#ifdef serialEvent_implemented
serialEvent();
#endif
}
static const char* serial_name = "/dev/ttyS1";
static inline char get_databit(byte config)
{
switch (config)
{
case SERIAL_5N1:
case SERIAL_5N2:
case SERIAL_5E1:
case SERIAL_5E2:
case SERIAL_5O1:
case SERIAL_5O2:
return CS5;
case SERIAL_6N1:
case SERIAL_6N2:
case SERIAL_6E1:
case SERIAL_6E2:
case SERIAL_6O1:
case SERIAL_6O2:
return CS6;
case SERIAL_7N1:
case SERIAL_7N2:
case SERIAL_7E1:
case SERIAL_7E2:
case SERIAL_7O1:
case SERIAL_7O2:
return CS7;
case SERIAL_8N1:
case SERIAL_8N2:
case SERIAL_8E1:
case SERIAL_8E2:
case SERIAL_8O1:
case SERIAL_8O2:
default:
return CS8;
}
}
static inline char get_stopbit(byte config)
{
switch (config)
{
case SERIAL_5N2:
case SERIAL_6N2:
case SERIAL_7N2:
case SERIAL_8N2:
case SERIAL_5E2:
case SERIAL_6E2:
case SERIAL_7E2:
case SERIAL_8E2:
case SERIAL_5O2:
case SERIAL_6O2:
case SERIAL_7O2:
case SERIAL_8O2:
return 2;
case SERIAL_5N1:
case SERIAL_6N1:
case SERIAL_7N1:
case SERIAL_8N1:
case SERIAL_5E1:
case SERIAL_6E1:
case SERIAL_7E1:
case SERIAL_8E1:
case SERIAL_5O1:
case SERIAL_6O1:
case SERIAL_7O1:
case SERIAL_8O1:
default:
return 1;
}
}
static inline char get_parity(byte config)
{
switch (config)
{
case SERIAL_5N1:
case SERIAL_5N2:
case SERIAL_6N1:
case SERIAL_6N2:
case SERIAL_7N1:
case SERIAL_7N2:
case SERIAL_8N1:
case SERIAL_8N2:
default:
return 'N';
case SERIAL_5O1:
case SERIAL_5O2:
case SERIAL_6O1:
case SERIAL_6O2:
case SERIAL_7O1:
case SERIAL_7O2:
case SERIAL_8O1:
case SERIAL_8O2:
return 'O';
case SERIAL_5E1:
case SERIAL_5E2:
case SERIAL_6E1:
case SERIAL_6E2:
case SERIAL_7E1:
case SERIAL_7E2:
case SERIAL_8E1:
case SERIAL_8E2:
return 'E';
}
}
static inline int get_valid_baud(unsigned long speed)
{
switch (speed)
{
case 300:
return B300;
case 600:
return B600;
case 1200:
return B1200;
case 2400:
return B2400;
case 4800:
return B4800;
case 9600:
return B9600;
case 14400:
return 0;
case 19200:
return B19200;
case 28800:
return 0;
case 38400:
return B38400;
case 57600:
return B57600;
case 115200:
return B115200;
default:
return 0;
}
}
//static void signal_handler_IO ()
//{
// serial.process_recv();
// serial.process_send();
//}
//under construct
HwSerial::HwSerial()
{
_rx_buffer.head = _rx_buffer.tail = 0;
_tx_buffer.head = _tx_buffer.tail = 0;
_fd = -1;
}
HwSerial::~HwSerial()
{
end();
}
void HwSerial::begin(unsigned long baud, byte config)
{
int ret;
struct termios Opt;
//struct sigaction saio;
hw_pinMode(GPIO0, IO_UART_FUNC); //uart_rx
hw_pinMode(GPIO1, IO_UART_FUNC); //uart_tx
_fd = open(serial_name, O_RDWR| O_NOCTTY | O_NONBLOCK );
if (_fd < 0 )
{
pabort("can't open tty");
}
tcgetattr(_fd, &Opt);
tcflush(_fd, TCIOFLUSH);
int rate = get_valid_baud(baud);
if(rate > 0)
{
cfsetispeed(&Opt, rate);
cfsetospeed(&Opt, rate);
}
Opt.c_cflag &= ~CSIZE;
Opt.c_cflag |= get_databit(config);
switch (get_parity(config))
{
case 'N':
default:
Opt.c_cflag &= ~PARENB;
Opt.c_iflag &= ~INPCK;
break;
case 'O':
Opt.c_cflag |= (PARODD | PARENB);
Opt.c_iflag |= INPCK;
break;
case 'E':
Opt.c_cflag |= PARENB;
Opt.c_cflag &= ~PARODD;
Opt.c_iflag |= INPCK;
break;
}
switch (get_stopbit(config))
{
case 1:
default:
Opt.c_cflag &= ~CSTOPB;
break;
case 2:
Opt.c_cflag |= CSTOPB;
break;
}
//Opt.c_cflag |= (CLOCAL | CREAD);
Opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
//Opt.c_lflag &= ~(ECHO);
//Opt.c_cc[VTIME] = 0;
//Opt.c_cc[VMIN] = 0;
//saio.sa_handler = signal_handler_IO;
//sigemptyset (&(saio.sa_mask));
//saio.sa_flags = 0;
//saio.sa_restorer = NULL;
//sigaction (SIGIO, &saio, NULL);
//if (-1 == fcntl (_fd, F_SETFL, O_ASYNC))
// pabort("SETFL SIGIO");
//if (-1 == fcntl (_fd, F_SETOWN, getpid ()))
// pabort("F_SETOWN SIGIO");
ret = tcsetattr(_fd, TCSANOW, &Opt);
if (ret != 0)
pabort("can't set tty baut");
tcflush(_fd,TCIOFLUSH);
}
void HwSerial::end()
{
if(_fd)
close(_fd);
_fd = -1;
}
int HwSerial::available(void)
{
if(_rx_buffer.head <= _rx_buffer.tail)
return (_rx_buffer.tail - _rx_buffer.head);
else
return (SERIAL_BUFFER_SIZE - _rx_buffer.head + _rx_buffer.tail);
}
int HwSerial::peek(void)
{
if (_rx_buffer.head == _rx_buffer.tail) {
return -1;
} else {
return _rx_buffer.buffer[_rx_buffer.head];
}
}
int HwSerial::read(void)
{
if (_rx_buffer.head == _rx_buffer.tail) {
return -1;
} else {
unsigned char c = _rx_buffer.buffer[_rx_buffer.head];
_rx_buffer.head = (unsigned int)(_rx_buffer.head + 1) % SERIAL_BUFFER_SIZE;
return c;
}
}
void HwSerial::flush()
{
_rx_buffer.head = _rx_buffer.tail = 0;
_tx_buffer.head = _tx_buffer.tail = 0;
//::flush(_fd);
tcflush(_fd, TCIOFLUSH);
}
int HwSerial::write(byte c)
{
return (::write(_fd, &c ,1));
}
int HwSerial::process_recv()
{
int len = SERIAL_BUFFER_SIZE - available();
int retval = 0;
if ( _fd < 0 )
return -1;
if(len > 0)
{
//fd_set fs_read;
//struct timeval tv_timeout={_timeout/1000,(_timeout%1000)*1000};
//FD_ZERO (&fs_read);
//FD_SET (_fd, &fs_read);
//retval = select (_fd+1, &fs_read, NULL, NULL, &tv_timeout);
//if (retval>0)
{
//if(FD_ISSET(_fd,&fs_read))
{
char buf[SERIAL_BUFFER_SIZE];
retval = ::read(_fd, buf, len);
if(retval > 0)
{
if(retval >= SERIAL_BUFFER_SIZE -_rx_buffer.tail)
{
memcpy(_rx_buffer.buffer + _rx_buffer.tail, buf, SERIAL_BUFFER_SIZE - _rx_buffer.tail);
memcpy(_rx_buffer.buffer, buf + SERIAL_BUFFER_SIZE - _rx_buffer.tail, retval - (SERIAL_BUFFER_SIZE - _rx_buffer.tail));
_rx_buffer.tail = retval - ( SERIAL_BUFFER_SIZE - _rx_buffer.tail);
}
else
{
memcpy(_rx_buffer.buffer + _rx_buffer.tail, buf, retval);
_rx_buffer.tail += retval;
}
}
}
}
}
return retval;
}
HwSerial::operator bool() {
return true;
}
|
5a1942b53ff327ea3c02d0405760f7909240b897 | d1c6b9e32cf783a058c7898084b9651cc8c6d4ae | /advancedCpp/Fractal/src/Fractal.cpp | 8e07cbc3d6cb71358074ae5253aff7ff1a2222f2 | [] | no_license | tomasarrufat/cppcourse | 81da5068c010d6b6054b0532e9bcb6c03a492be7 | 258e554cfc5f63c01435b59e96fcbd68e9adcea5 | refs/heads/master | 2021-06-04T21:48:53.059285 | 2019-09-08T12:42:36 | 2019-09-08T12:42:36 | 106,089,588 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | cpp | Fractal.cpp | // Name : Fractal.cpp
#include <iostream>
#include <cstdint>
#include "FractalCreator.h"
using namespace std;
using namespace fgen;
int main()
{
int const WIDTH = 1960;
int const HEIGHT = 1080;
int const SUB = 10;
FractalCreator fractalCreator(WIDTH, HEIGHT);
//BitMap m_bitmap(m_width, m_height);
//ZoomList m_zoomList(m_width, m_height);
fractalCreator.addZoom(Zoom(WIDTH/2, HEIGHT/2, 2.0/WIDTH));
fractalCreator.addZoom(Zoom(-475, HEIGHT/2, 0.05));
fractalCreator.addZoom(Zoom(-410, HEIGHT/2, 0.01));
fractalCreator.addZoom(Zoom(WIDTH/2+282, HEIGHT/2, 0.01));
fractalCreator.addZoom(Zoom(WIDTH/2-332, HEIGHT/2, 0.01));
fractalCreator.addZoom(Zoom(WIDTH/2-60, HEIGHT/2, 0.001));
fractalCreator.addZoom(Zoom(WIDTH/2-25, HEIGHT/2, 0.01));
fractalCreator.calculateIteration();
int subsample{1};
char answer{'n'};
while( answer != 'y' && answer != 'Y')
{
cout << "Enter subsample: ";
cin >> subsample;
cout << endl;
fractalCreator.drawFractal(subsample);
fractalCreator.writeBitmap("test.bmp");
cout << "Do you want to finish? [Y/n]: ";
cin >> answer;
cout << endl;
}
cout << "Finished." << endl;
return 0;
}
|
005307ccec09fff59819bcf334a2d0ad1798d3a4 | 26d3464790b1233ade5c8d9db7ba16d950d06298 | /Source/SheepOutCplusplus/AI/BTT/BTTask_SetSheepState.h | fe3eb4ca4d11d99f817c354cf4f6ee128ac5237f | [] | no_license | hktari/sheepout | 3a25b960fc4f6b42d9ca71741313cec457787e89 | e8290d836f008d8e797194abb2f7cae3f1af5a07 | refs/heads/master | 2020-04-08T03:13:34.525758 | 2018-11-24T19:27:09 | 2018-11-24T19:27:09 | 158,967,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 555 | h | BTTask_SetSheepState.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "BehaviorTree/Tasks/BTTask_BlackboardBase.h"
#include "AI/AISheepController.h"
#include "BTTask_SetSheepState.generated.h"
/**
*
*/
UCLASS()
class SHEEPOUTCPLUSPLUS_API UBTTask_SetSheepState : public UBTTask_BlackboardBase
{
GENERATED_BODY()
UPROPERTY(Category = Node, EditAnywhere)
TEnumAsByte<ESheepStates> State;
virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory);
};
|
67271c854792dbce99025fdeb52d160f11f2a314 | d80e0c6c37955948dad1d912e7150a9101505572 | /zad03/main.cpp | 213771ebd3abfb8b8180d3d648aeba60af663e89 | [] | no_license | CrazyWorldPL/CPP | 111bf62fc2c236f45dab3f1deb946898c7c4d69c | 6bf624c9ef9317c5fc45fd77c0b3a3f874faf69d | refs/heads/main | 2023-04-24T13:55:38.354865 | 2021-05-13T14:46:50 | 2021-05-13T14:46:50 | 367,064,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | cpp | main.cpp | #include <iostream>
#include <iomanip>
using namespace std;
double metry,milimetry;
int main() {
cout << "Podaj ilosc metrow: ";
cin >> metry;
milimetry = metry * 1000;
cout << "Ilosc milimetrow: ";
cout << fixed << showpoint;
cout << setprecision(10);
cout << milimetry << endl;
return 0;
}
|
9a386c819b3d8076f7d6739f9fffe0076a73e378 | 54b4bba892e7e91537d8cd3e461f37c00155dafa | /part2/hashmap.h | af532b28844366f80b9d1995349c7b6a7f002cb3 | [] | no_license | ZiyiPeng/CS4500 | 3b733ac808998d37688063feeab958feb73ce6f2 | 312bb9f4078fffab29b0afb1e4174a31dfb1693f | refs/heads/master | 2022-04-02T01:57:25.182548 | 2020-01-24T21:53:55 | 2020-01-24T21:53:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,969 | h | hashmap.h | //
// Created by Jiawen Liu on 1/24/20.
//
#ifndef PART2_HASHMAP_H
#define PART2_HASHMAP_H
#endif //PART2_HASHMAP_H
#pragma once;
#include <cstring>
#include "object.h"
#include "hashnode.h"
class Hashmap : public Object {
private:
Hashnode** table;
int size;
int capacity;
public:
/**
* Default constructor that constructs an empty HashMap with
* the default initial capacity 16
*/
Hashmap();
/**
* Destructor that delete Hashmap object
*/
~Hashmap();
public:
/**
* Returns the number of key-value (Hashnode) mappings in this map.
*/
int get_size();
/**
* Returns the capacity of key-value (Hashnode) mappings in this map.
*/
int get_cap();
/**
* return index for hashcode of key
* @param key the key that used to be hashed and get location of an object that needs to be stored
* @return index index of the inner array
*/
int index_for(Object* key);
/**
* resize of inner array when size hits its threshold(capacity)
*/
void resize();
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old value is replaced.
* @param key key with which the specified value is to be associated
* @param val value to be associated with the specified key
* @return the previous value associated with key, or null if there was no mapping for key.
*/
Object* put(Object* key, Object* val);
/**
* Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or null if this map contains no mapping for the key
*/
Object* get(Object* key);
/**
* Returns true if this map contains a mapping for the specified key.
* @param key The key whose presence in this map is to be tested
* @return true if this map contains a mapping for the specified key, otherwise false
*/
bool containsKey(Object* key);
/**
* Removes the mapping for the specified key from this map if present.
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with key, or null if there was no mapping for key.
*/
Object* remove(Object* key);
/**
* @return a list of the keys contained in this map
*/
Object** keys();
/**
* @return a list of values contained in this map
*/
Object** values();
};
Hashmap:: Hashmap() : Object(){
table = new Hashnode* [16];
size = 0;
capacity = 16;
for(int i = size; i < capacity; i++){
table[i] = nullptr;
}
}
Hashmap:: ~Hashmap() {
delete[] table;
}
int Hashmap:: get_size(){
return size;
}
int Hashmap:: get_cap(){
return capacity;
}
int Hashmap:: index_for(Object* key) {
if(key) {
return key->hashCode() & (capacity - 1);
}
}
void Hashmap:: resize() {
capacity *= 2;
Hashnode** newTable = new Hashnode* [capacity];
for(int i = 0; i < size; i++){
Hashnode* needAdd = new Hashnode(table[i]);
while(table[i] != NULL) {
int index = index_for(needAdd->_key);
while(newTable[index] != NULL) {
newTable[index] = newTable[index]->next;
}
newTable[index] = needAdd;
table[i] = table[i]->next;
}
}
delete [] table;
table = newTable;
}
Object* Hashmap:: put(Object* key, Object* val) {
if(size == capacity) {
resize();
}
int index = index_for(key);
Hashnode* node = new Hashnode(key, val);
Hashnode* cur = table[index];
if(cur == NULL) {
table[index] = node;
size++;
}
else {
while(cur->next != NULL) {
if(cur->_key->equals(key)){
cur->_value = val;
return cur->_value;
}
cur = cur->next;
}
if(cur->_key->equals(key)) {
cur->_value = val;
} else {
cur->next = node;
size++;
}
}
return NULL;
}
Object* Hashmap:: get(Object* key){
int index = index_for(key);
Hashnode* cur = table[index];
while(cur != NULL){
if(cur->_key->equals(key)){
return cur->_value;
}
cur = cur->next;
}
return NULL;
}
bool Hashmap:: containsKey(Object* key){
int index = index_for(key);
Hashnode* cur = table[index];
while(cur != NULL){
if(cur->_key->equals(key)){
return true;
}
cur = cur->next;
}
return false;
}
Object* Hashmap:: remove(Object* key) {
int index = index_for(key);
Hashnode* cur = table[index];
Hashnode* pre = NULL;
while(cur != NULL){
if(cur->_key->equals(key)){
if(pre != NULL){
pre->next = cur->next;
} else {
table[index] = cur->next;
}
size--;
return cur->_value;
}
else{
pre = cur;
cur = cur->next;
}
}
return NULL;
}
Object** Hashmap:: keys(){
Object** result = new Object*[size];
int key_size = 0;
for(int i = 0; i < capacity; i++){
Hashnode* cur = table[i];
while(cur != NULL){
result[key_size] = cur->_key;
cur = cur->next;
key_size++;
}
}
return result;
}
Object** Hashmap:: values() {
Object** result = new Object*[size];
int key_size = 0;
for(int i = 0; i < capacity; i++){
Hashnode* cur = table[i];
while(cur != NULL){
result[key_size] = cur->_value;
cur = cur->next;
key_size++;
}
}
return result;
} |
b4ee133c58232501c8b6f8021e38d0327a162bd4 | d9357508a1d203d63ce12c733037038d6bc210a1 | /Algorithm/Algorithm/2020/654_最大二叉树.cpp | 6ba18c9066f0c5b7ea13b54c4ac2a19ba540160d | [] | no_license | zhangzhex/leetcode | b6bad37bdecb68d97f58d49d935cf53ace21e0f9 | 9b47011413daa483eae4c4088d731e0dca9ed2aa | refs/heads/master | 2023-04-04T09:21:11.058656 | 2021-04-15T15:51:34 | 2021-04-15T15:51:34 | 268,554,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | cpp | 654_最大二叉树.cpp | //
// 654_最大二叉树.cpp
// Algorithm
//
// Created by zack on 2020/5/26.
// Copyright © 2020 zack. All rights reserved.
//
#include <stdio.h>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return findRoot(nums, 0, (int)nums.size());
}
TreeNode *findRoot(vector<int>& nums, int leftIndex, int rightIndex){
if (leftIndex >= rightIndex) {
return NULL;
}
int maxIndex = leftIndex;
for (int i = leftIndex + 1; i < rightIndex; i++) {
if (nums[maxIndex] < nums[i]) {
maxIndex = i;
}
}
TreeNode *root = new TreeNode(nums[maxIndex]);
root->left = findRoot(nums, leftIndex, maxIndex);
root->right = findRoot(nums, maxIndex+1, rightIndex);
return root;
}
};
|
9a23d5b983574795dbf5c7973b43da2cdf2137b5 | f7ec77f23c16b12e06835957aee51e86381005f1 | /airhockey/src/modifier/preprocessor.hpp | 2a6708bfb36161b5f579aaa8171298ddcc4a54db | [] | no_license | andwang1/aurora-representation-learning | ebc70cf9975098850ae954d230f7ae385fb43101 | 3f9a0af0a21a423119eac861865c1bd9587a4275 | refs/heads/master | 2023-07-16T07:04:04.597548 | 2021-09-02T17:19:11 | 2021-09-02T17:19:11 | 402,490,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | hpp | preprocessor.hpp | //
// Created by Luca Grillotti on 31/10/2019.
//
#ifndef SFERES2_PREPROCESSOR_HPP
#define SFERES2_PREPROCESSOR_HPP
#include <iostream>
class RescaleFeature {
public:
RescaleFeature() : no_prep(true) {}
typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Mat;
void init() {
no_prep = true;
}
void init(const Mat &data) {
no_prep = false;
m_mean_dataset = data.colwise().mean();
// m_std_dataset = (data.array().rowwise() - m_mean_dataset.transpose().array()).pow(2).colwise().mean().sqrt();
}
void apply(const Mat &data, Mat &res) const {
if (no_prep) {
res = data;
} else {
// res = a + (data.array() - _min) * (b - a) / (_max - _min);
res = data.array().rowwise() - m_mean_dataset.transpose().array();
// res = res.array().rowwise() / (m_std_dataset.transpose().array() + 0.001f);
}
}
void deapply(const Mat &data, Mat &res) const {
if (no_prep) {
res = data;
} else {
// res = data.array().rowwise() * m_std_dataset.transpose().array();
// res = res.array().rowwise() + m_mean_dataset.transpose().array();
// res = res.cwiseMax(0.).cwiseMin(1.);
res = data.array().rowwise() + m_mean_dataset.transpose().array();
}
}
private:
bool no_prep;
Eigen::VectorXf m_mean_dataset;
Eigen::VectorXf m_std_dataset;
};
#endif //SFERES2_PREPROCESSOR_HPP
|
5edbcc2acad6259453cfb5d9d82c59ecf44340d1 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /src/AlienImage/AlienImage_SunRFAlienData.cxx | 3430ac3e513b55de406d78d2f419d58dcdb6e164 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,983 | cxx | AlienImage_SunRFAlienData.cxx | #include <Aspect_GenericColorMap.hxx>
#include <Image_PseudoColorImage.hxx>
#include <AlienImage_MemoryOperations.hxx>
#include <AlienImage_SUNRFFormat.hxx>
#include <Image_Convertor.hxx>
#include <AlienImage_SunRFAlienData.ixx>
#include <Aspect_ColorMapEntry.hxx>
#include <Standard_Byte.hxx>
#include <Standard.hxx>
#ifdef TRACE
static int Verbose = 1 ;
#endif
#define RUN_FLAG 0x80
// Each line of the image is rounded out to a multiple of 16 bits
#define ROWBYTES() (((myHeader.ras_width*myHeader.ras_depth + 7 )/8 + 1 ) & ~1 )
AlienImage_SunRFAlienData::AlienImage_SunRFAlienData()
{ Clear() ; }
void AlienImage_SunRFAlienData::SetFormat(
const AlienImage_SUNRFFormat aFormat )
{ switch ( aFormat ) {
case AlienImage_SUNRF_Old :
myHeader.ras_type = RT_OLD ; break ;
case AlienImage_SUNRF_Standard :
myHeader.ras_type = RT_STANDARD ; break ;
case AlienImage_SUNRF_ByteEncoded :
myHeader.ras_type = RT_BYTE_ENCODED ; break ;
case AlienImage_SUNRF_RGB :
myHeader.ras_type = RT_FORMAT_RGB ; break ;
default :
cout << "SunRFAlienData : Unknown or Unsuported Format\n" ;
break ;
}
}
AlienImage_SUNRFFormat AlienImage_SunRFAlienData::Format() const
{ AlienImage_SUNRFFormat ret = AlienImage_SUNRF_Unknown ;
switch ( myHeader.ras_type ) {
case RT_OLD :
ret = AlienImage_SUNRF_Old ; break ;
case RT_STANDARD :
ret = AlienImage_SUNRF_Standard ; break ;
case RT_BYTE_ENCODED :
ret = AlienImage_SUNRF_ByteEncoded ; break ;
case RT_FORMAT_RGB :
ret = AlienImage_SUNRF_RGB ; break ;
}
return ret ;
}
void AlienImage_SunRFAlienData::FreeData()
{
if ( myData && myDataSize ) {
//Free all allocated memory
Standard::Free(myData) ;
myData = NULL ;
myDataSize = 0 ;
}
if ( myRedData && myHeader.ras_maplength ) {
//Free all allocated memory
Standard::Free( myRedData) ;
myRedData = NULL ;
}
if ( myGreenData && myHeader.ras_maplength ) {
//Free all allocated memory
Standard::Free(myGreenData) ;
myRedData = NULL ;
}
if ( myBlueData && myHeader.ras_maplength ) {
//Free all allocated memory
Standard::Free(myBlueData) ;
myRedData = NULL ;
}
}
void AlienImage_SunRFAlienData::Clear()
{ FreeData() ;
myHeader.ras_magic = RAS_MAGIC ;
myHeader.ras_width = 0 ;
myHeader.ras_height = 0 ;
myHeader.ras_length = 0 ;
myHeader.ras_type = RT_STANDARD ;
myHeader.ras_maptype = RMT_NONE ;
myHeader.ras_maplength = 0 ;
}
Standard_Boolean AlienImage_SunRFAlienData::Write( OSD_File& file ) const
{ Standard_Integer size;
AlienImage_SUNRFFileHeader TheHeader = myHeader ;
// Write out TheHeader information
if ( myData && myDataSize &&
myHeader.ras_type == RT_FORMAT_RGB &&
myHeader.ras_depth == 8 ) {
// Convert PseudoColorImage to TrueColor
Handle(Image_Image) aImage = ToImage() ;
if ( aImage->IsKind( STANDARD_TYPE(Image_PseudoColorImage) ) ) {
Image_Convertor Convertor;
Handle(Image_ColorImage) aCImage =
Convertor.Convert(Handle(Image_PseudoColorImage)::DownCast(aImage));
Handle(AlienImage_SunRFAlienData) newThis =
new AlienImage_SunRFAlienData() ;
newThis->FromImage( aCImage ) ;
newThis->SetFormat( AlienImage_SUNRF_RGB ) ;
return newThis->Write( file ) ;
}
}
size = ( Standard_Integer ) sizeof( TheHeader ) ;
const Standard_Address pHeader = ( Standard_Address ) &TheHeader ;
file.Write( pHeader, sizeof( TheHeader ) ) ;
if ( file.Failed() ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
// write out the color map buffer
if ( TheHeader.ras_maplength ) {
file.Write( myRedData, myHeader.ras_maplength/3 ) ;
file.Write( myGreenData, myHeader.ras_maplength/3 ) ;
file.Write( myBlueData, myHeader.ras_maplength/3 ) ;
if ( file.Failed() ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
}
Standard_Integer rwbytes ;
rwbytes = ROWBYTES() ;
if ( myData && myDataSize ) {
if ( myHeader.ras_type == RT_OLD ||
myHeader.ras_type == RT_STANDARD ||
myHeader.ras_type == RT_FORMAT_RGB ) {
if ( myHeader.ras_type == RT_FORMAT_RGB ) {
// Swap Sun Default BGR Format to RGB
Standard_Byte *p = ( Standard_Byte * )myData ;
Standard_Byte tmp, *pix ;
Standard_Integer j, i ;
if ( myHeader.ras_depth == 24 || myHeader.ras_depth == 32 ) {
for ( i = 0 ;i < myHeader.ras_height ; i++, p += rwbytes ) {
for ( j = 0, pix=p; j < myHeader.ras_width ; j++,pix+=3) {
if ( myHeader.ras_depth == 32 ) pix++ ;
tmp = *pix ;
*pix = *(pix+2) ;
*(pix+2) = tmp ;
}
}
}
else if ( myHeader.ras_depth == 8 ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
}
file.Write( myData, myDataSize ) ;
if ( file.Failed() ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
if ( myHeader.ras_type == RT_FORMAT_RGB &&
( myHeader.ras_depth == 24 || myHeader.ras_depth == 32 ) ) {
// Swap RGB Format to Sun Default
Standard_Byte *p = ( Standard_Byte * )myData ;
Standard_Byte tmp, *pix ;
Standard_Integer j, i ;
for ( i = 0 ;i < myHeader.ras_height ; i++, p += rwbytes ) {
for ( j = 0, pix=p; j < myHeader.ras_width ; j++,pix+=3) {
if ( myHeader.ras_depth == 32 ) pix++ ;
tmp = *pix ;
*pix = *(pix+2) ;
*(pix+2) = tmp ;
}
}
}
}
else if ( myHeader.ras_type == RT_BYTE_ENCODED ) {
Standard_Byte *p = ( Standard_Byte * )myData ;
Standard_Integer i ;
for ( i = 0 ; i < myHeader.ras_height ; i++, p += rwbytes ) {
if ( WritePixelRow( file, ( Standard_Address) p, rwbytes ) ==
Standard_False ) {
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
}
}
}
return( Standard_True ) ;
}
Standard_Boolean AlienImage_SunRFAlienData::Read( OSD_File& file )
{ Standard_Integer bblcount, size ;
Standard_Address pheader = ( Standard_Address ) &myHeader ;
// Read in myHeader information
file.Read( pheader, sizeof( myHeader ), bblcount ) ;
if ( file.Failed() || ( bblcount != sizeof( myHeader ) ) ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
// check to see if the dump file is in the proper format */
if (myHeader.ras_magic != RAS_MAGIC) {
// ERROR "XWD file format version mismatch."
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
#ifdef TRACE
if ( Verbose ) cout << myHeader << endl << flush ;
#endif
// read in the color map buffer
if ( myHeader.ras_maplength ) {
size = myHeader.ras_maplength / 3 ;
myRedData = Standard::Allocate( size ) ;
myGreenData = Standard::Allocate( size ) ;
myBlueData = Standard::Allocate( size ) ;
file.Read( myRedData, size, bblcount ) ;
file.Read( myGreenData, size, bblcount ) ;
file.Read( myBlueData, size, bblcount ) ;
if ( file.Failed() || ( bblcount != size ) ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
#ifdef TRACE
if ( Verbose ) {
Standard_Byte *r = ( Standard_Byte * )myRedData ;
Standard_Byte *g = ( Standard_Byte * )myGreenData ;
Standard_Byte *b = ( Standard_Byte * )myBlueData ;
for (i = 0 ; i < myHeader.ncolors; i++,p++) {
cout << "(" << r << "," << g << "," << b << ")\n" << flush ;
}
}
#endif
}
if ( myHeader.ras_width && myHeader.ras_height && myHeader.ras_depth ) {
Standard_Integer rwbytes ;
rwbytes = ROWBYTES() ;
myDataSize = rwbytes * myHeader.ras_height ;
myData = Standard::Allocate( myDataSize ) ;
if ( myHeader.ras_type == RT_OLD ||
myHeader.ras_type == RT_STANDARD ||
myHeader.ras_type == RT_FORMAT_RGB ) {
file.Read( myData, myDataSize, bblcount ) ;
if ( file.Failed() || ( bblcount != myDataSize ) ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
if ( myHeader.ras_type == RT_FORMAT_RGB &&
( myHeader.ras_depth == 24 || myHeader.ras_depth == 32 )) {
// Swap RGB to Sun Default BGR Format
Standard_Byte *p = ( Standard_Byte * )myData ;
Standard_Byte tmp, *pix ;
Standard_Integer i, j ;
for ( i = 0 ; i < myHeader.ras_height ; i++, p += rwbytes ) {
for ( j = 0, pix = p; j < myHeader.ras_width ; j++,pix+=3) {
if ( myHeader.ras_depth == 32 ) pix++ ;
tmp = *pix ;
*pix = *(pix+2) ;
*(pix+2) = tmp ;
}
}
}
}
else if ( myHeader.ras_type == RT_BYTE_ENCODED ) {
Standard_Byte *p = ( Standard_Byte * )myData ;
Standard_Integer i ;
for ( i = 0 ; i < myHeader.ras_height ; i++, p += rwbytes ) {
if ( ReadPixelRow( file, ( Standard_Address) p, rwbytes ) ==
Standard_False ) {
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
}
}
}
return( Standard_True ) ;
}
Handle_Image_Image AlienImage_SunRFAlienData::ToImage() const
{ if ( myHeader.ras_depth <= 8 &&
myHeader.ras_maplength ) {
return( ToPseudoColorImage() ) ;
}
else if ( myHeader.ras_depth == 24 || myHeader.ras_depth == 32 ) {
return( ToColorImage() ) ;
}
else {
Standard_TypeMismatch_Raise_if( Standard_True,
"Attempt to convert a SunRFAlienData to a unknown Image_Image type");
return( NULL ) ;
}
}
void AlienImage_SunRFAlienData::FromImage( const Handle_Image_Image& anImage )
{ if ( anImage->Type() == Image_TOI_PseudoColorImage ) {
Handle(Image_PseudoColorImage) aPImage =
Handle(Image_PseudoColorImage)::DownCast(anImage) ;
FromPseudoColorImage( aPImage ) ;
}
else if ( anImage->Type() == Image_TOI_ColorImage ) {
Handle(Image_ColorImage) aCImage =
Handle(Image_ColorImage)::DownCast(anImage) ;
FromColorImage( aCImage ) ;
}
else {
Standard_TypeMismatch_Raise_if( Standard_True,
"Attempt to convert a unknown Image_Image type to a SunRFAlienData");
}
}
//------------------------------------------------------------------------------
// Private Method
//------------------------------------------------------------------------------
Standard_Boolean AlienImage_SunRFAlienData::ReadPixelRow(
OSD_File& file,
const Standard_Address pdata,
const Standard_Integer rwbytes)
{ Standard_Byte *p = ( Standard_Byte * )pdata ;
Standard_Byte byte, val ;
Standard_Integer RLEcnt, PixelCount, i, bblcount ;
Standard_Address pb = ( Standard_Address ) &byte ;
PixelCount = 0 ;
while ( PixelCount < myHeader.ras_width ) {
file.Read( pb, 1, bblcount ) ;
if ( file.Failed() || ( bblcount != 1 ) ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
if ( byte != RUN_FLAG ) {
// Get a single pixel byte
RLEcnt = 1 , val = byte ;
}
else { // RLE Flag
file.Read( pb, 1, bblcount ) ;
if ( file.Failed() || ( bblcount != 1 ) ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
if ( byte == 0 ) {
RLEcnt = 1 , val = RUN_FLAG ;
}
else {
RLEcnt = byte ;
file.Read( pb, 1, bblcount ) ;
if ( file.Failed() || ( bblcount != 1 ) ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
val = byte ;
}
for ( i = 0 ; i < RLEcnt ; i++, PixelCount++, p++ ) *p = val ;
}
}
return( Standard_True ) ;
}
Standard_Boolean AlienImage_SunRFAlienData::WritePixelRow(
OSD_File& file,
const Standard_Address pdata,
const Standard_Integer rwbytes ) const
{ Standard_Integer n, n1, n2 = 0;
Standard_Byte *scanln = ( Standard_Byte * ) pdata ;
Standard_Byte b ;
while ( n2 < rwbytes ) {
n1 = n2 ;
n2 = n1 + 1 ;
while( ( n2 < rwbytes ) && ( scanln[n1] == scanln[n2] ) ) n2++ ;
n = n2 - n1 ;
if ( n == 1 ) {
b = scanln[n1]; file.Write( ( Standard_Address ) &b, 1 ) ;
if ( scanln[n1] == RUN_FLAG ) {
b = 0 ; file.Write( ( Standard_Address ) &b, 1 ) ;
}
if ( file.Failed() ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
}
else {
while ( n > 256 ) {
b = RUN_FLAG ; file.Write( ( Standard_Address ) &b, 1) ;
b = 255 ; file.Write( ( Standard_Address ) &b, 1) ;
b = scanln[n1];file.Write( ( Standard_Address ) &b, 1) ;
n -= 256 ;
if ( file.Failed() ) {
// ERROR
file.Seek( 0, OSD_FromBeginning ) ;
return( Standard_False ) ;
}
}
b = RUN_FLAG ; file.Write( ( Standard_Address ) &b, 1 ) ;
b = n-1 ; file.Write( ( Standard_Address ) &b, 1 ) ;
b = scanln[n1];file.Write( ( Standard_Address ) &b, 1 ) ;
}
}
return( Standard_True ) ;
}
void AlienImage_SunRFAlienData::FromPseudoColorImage(
const Handle(Image_PseudoColorImage)& TheImage)
{ Standard_Integer rowbytes,i ;
Standard_Integer x, y, pix;
Handle(Image_PseudoColorImage)anImage =
TheImage->Squeeze(Aspect_IndexPixel( 0 )) ;
Handle(Aspect_ColorMap) Cmap = anImage->ColorMap() ;
Aspect_ColorMapEntry aEntry ;
FreeData() ;
myHeader.ras_magic = RAS_MAGIC ;
myHeader.ras_width = anImage->Width() ;
myHeader.ras_height = anImage->Height() ;
myHeader.ras_depth = 8 ;
rowbytes = ROWBYTES() ;
myDataSize = myHeader.ras_height * rowbytes ;
myData = Standard::Allocate( myDataSize ) ;
myHeader.ras_length = myDataSize ;
myHeader.ras_maptype = RMT_EQUAL_RGB ;
myHeader.ras_maplength = Cmap->Size() ;
myRedData = Standard::Allocate( myHeader.ras_maplength ) ;
myGreenData = Standard::Allocate( myHeader.ras_maplength ) ;
myBlueData = Standard::Allocate( myHeader.ras_maplength ) ;
Standard_Byte *pr = ( Standard_Byte * ) myRedData ;
Standard_Byte *pg = ( Standard_Byte * ) myGreenData ;
Standard_Byte *pb = ( Standard_Byte * ) myBlueData ;
for ( i = 0 ; i < myHeader.ras_maplength ; i++, pr++, pg++, pb++ ) {
aEntry = Cmap->FindEntry( i ) ;
*pr = ( Standard_Byte ) ( aEntry.Color().Red() * 255. + 0.5 ) ;
*pg = ( Standard_Byte ) ( aEntry.Color().Green() * 255. + 0.5 ) ;
*pb = ( Standard_Byte ) ( aEntry.Color().Blue() * 255. + 0.5 ) ;
}
myHeader.ras_maplength *= 3 ;
if ( myData != NULL ) {
Standard_Byte *pr = ( Standard_Byte * ) myData ;
Standard_Byte *p ;
for ( y = 0 ; y < myHeader.ras_height ; y++, pr += rowbytes ) {
for ( x = 0, p = pr ; x < myHeader.ras_width ; x++ ) {
pix = anImage->Pixel( anImage->LowerX()+x ,
anImage->LowerY()+y ).Value() ;
*p = ( Standard_Byte ) pix ; p++ ;
}
}
}
}
void AlienImage_SunRFAlienData::FromColorImage(
const Handle_Image_ColorImage& anImage)
{ Standard_Integer rowbytes ;
Standard_Integer x, y;
Quantity_Color col ;
Standard_Real r,g,b ;
FreeData() ;
myHeader.ras_magic = RAS_MAGIC ;
myHeader.ras_width = anImage->Width() ;
myHeader.ras_height = anImage->Height() ;
myHeader.ras_depth = 24 ;
rowbytes = ROWBYTES() ;
myDataSize = myHeader.ras_height * rowbytes ;
myData = Standard::Allocate( myDataSize ) ;
myHeader.ras_length = myDataSize ;
myHeader.ras_maptype = RMT_NONE ;
myHeader.ras_maplength = 0 ;
if ( myData != NULL ) {
Standard_Byte *pr = ( Standard_Byte * ) myData ;
Standard_Byte *p ;
for ( y = 0 ; y < myHeader.ras_height ; y++, pr += rowbytes ) {
for ( x = 0, p = pr ; x < myHeader.ras_width ; x++ ) {
col = anImage->Pixel( anImage->LowerX()+x ,
anImage->LowerY()+y ).Value() ;
r = ( Standard_Integer ) ( col.Red() * 255. + 0.5 );
g = ( Standard_Integer ) ( col.Green() * 255. + 0.5 );
b = ( Standard_Integer ) ( col.Blue() * 255. + 0.5 );
*p = ( Standard_Byte ) b ; p++ ;
*p = ( Standard_Byte ) g ; p++ ;
*p = ( Standard_Byte ) r ; p++ ;
}
}
}
}
Handle_Image_ColorImage AlienImage_SunRFAlienData::ToColorImage() const
{ Aspect_ColorPixel CPixel ;
Quantity_Color acolor ;
Handle(Image_ColorImage) ret_image = NULL ;
Standard_Integer x,y, rowbytes ;
Standard_Real r,g,b ;
Standard_Byte *pr = ( Standard_Byte * ) myData ;
Standard_Byte *p ;
if ( myHeader.ras_depth == 24 || myHeader.ras_depth == 32 ) {
ret_image = new Image_ColorImage( 0,0,
(Standard_Integer)myHeader.ras_width,
(Standard_Integer)myHeader.ras_height ) ;
rowbytes = ROWBYTES() ;
for ( y = 0 ; y < myHeader.ras_height ; y++, pr += rowbytes ) {
for ( x = 0, p = pr ; x < myHeader.ras_width ; x++ ) {
if ( myHeader.ras_depth == 32 ) p++ ; // Skeep Alpha
b = ( Standard_Real ) *p / 255. ; p++ ;
g = ( Standard_Real ) *p / 255. ; p++ ;
r = ( Standard_Real ) *p / 255. ; p++ ;
acolor.SetValues( r,g,b, Quantity_TOC_RGB ) ;
CPixel.SetValue ( acolor ) ;
ret_image->SetPixel( ret_image->LowerX()+x ,
ret_image->LowerY()+y, CPixel ) ;
}
}
}
return( ret_image ) ;
}
Handle_Image_PseudoColorImage AlienImage_SunRFAlienData::ToPseudoColorImage()
const
{ Standard_Real r,g,b ;
Standard_Integer x, y ;
Handle(Image_PseudoColorImage) ret_image = NULL ;
if ( myHeader.ras_depth <= 8 &&
myHeader.ras_maplength ) {
Standard_Integer i,rowbytes ;
Aspect_ColorMapEntry Centry ;
Quantity_Color color ;
Aspect_IndexPixel IPixel ;
Standard_Byte *red = ( Standard_Byte * ) myRedData ;
Standard_Byte *green = ( Standard_Byte * ) myGreenData ;
Standard_Byte *blue = ( Standard_Byte * ) myBlueData ;
Standard_Byte *p ;
Standard_Byte *pr = ( Standard_Byte * ) myData ;
Handle(Aspect_GenericColorMap) colormap =
new Aspect_GenericColorMap();
for ( i = 0 ; i < myHeader.ras_maplength/3 ; i++, red++, green++, blue++ ) {
r = ( Standard_Real ) *red / 255. ;
g = ( Standard_Real ) *green / 255. ;
b = ( Standard_Real ) *blue / 255. ;
color.SetValues( r,g,b, Quantity_TOC_RGB );
Centry.SetValue( i, color ) ;
colormap->AddEntry( Centry ) ;
}
ret_image = new Image_PseudoColorImage( 0,0,
Standard_Integer(myHeader.ras_width),
Standard_Integer(myHeader.ras_height),
colormap ) ;
rowbytes = ROWBYTES() ;
for ( y = 0 ; y < myHeader.ras_height ; y++, pr += rowbytes ) {
for ( x = 0, p = pr ; x < myHeader.ras_width ; x++, p++ ) {
IPixel.SetValue( Standard_Integer( *p ) ) ;
ret_image->SetPixel( ret_image->LowerX()+x ,
ret_image->LowerY()+y, IPixel ) ;
}
}
}
return ret_image ;
}
|
691cd072fdd82ebbe9b100fcd1ec5d89b6a6b312 | 5be8b855fe4a8cf7236f29f8b55c940b672e0262 | /kenji/cpp/test/src/common/mnist/mnist_test.cpp | 76ddb794d3c9add7521b3270f00b6ed7e72c021e | [] | no_license | sh0nk/zero-deeplearning | 17cf44ba5566faea7c36d0cc83cb8c8d2c355001 | c6765b1d976a747fefd53f67fe69ccb4ce436e08 | refs/heads/master | 2021-01-01T17:06:40.511196 | 2017-11-25T12:12:24 | 2017-11-25T12:12:24 | 97,996,548 | 2 | 0 | null | 2017-11-25T04:51:07 | 2017-07-22T00:38:45 | C++ | UTF-8 | C++ | false | false | 3,534 | cpp | mnist_test.cpp | //
// Created by Kenji Nomura on 9/3/17.
//
#include "catch.hpp"
#include "common/mnist/Mnist.h"
const std::vector<std::uint8_t> IMAGE_0_THRESH_DATA =
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
TEST_CASE("mnist#mnist", "[mnist]") {
const std::string image_path = "data/train-images-idx3-ubyte";
const std::string label_path = "data/train-labels-idx1-ubyte";
Mnist mnist(image_path, label_path);
mnist.image.show(0);
mnist.label.show(0);
CHECK(mnist.label.getNumberOfData() == 60000);
CHECK(mnist.label.get(0) == 5);
CHECK(mnist.label.get(1) == 0);
CHECK(mnist.label.get(2) == 4);
CHECK(mnist.label.get(mnist.size() - 1) == 8);
CHECK(mnist.label.get(mnist.size()) == '\0');
CHECK(mnist.image.getNumberOfData() == 60000);
CHECK(mnist.image.size() == 784);
CHECK(mnist.image.rows() == 28);
CHECK(mnist.image.cols() == 28);
for (int i = 0; i < mnist.image.size(); i++) {
CHECK((mnist.image.get(0)[i] > 0 ? 1 : 0) == IMAGE_0_THRESH_DATA[i]);
}
CHECK(!mnist.image.get(mnist.size() - 1).empty());
CHECK(mnist.image.get(mnist.size()).empty());
}
|
c3ac023356f6d18c643fe252c3887c3e0f717f58 | b7132b54f4a175675b49e7bf1d2b1c4125a017e6 | /CodeChef/DIV3/Maximum_Production.c++ | f0192b1d52ddfbf2e3d3ea3e445473a649051e1a | [] | no_license | vishalsinghhh/Competitive-Programming-CPP | b1587fff601dcc540a2d9b6f25d5ff919dc9b617 | 82da2c1dd4582c6fe6b720507d07197e80242a6c | refs/heads/main | 2023-06-13T02:20:34.540045 | 2021-07-11T17:10:21 | 2021-07-11T17:10:21 | 382,071,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,849 | Maximum_Production.c++ | /*
*****QUESTION 💯*********
Chefland has 7 days in a week. Chef is very conscious about his work done during the week.
There are two ways he can spend his energy during the week. The first way is to do x units of work every day and the second way is to do y (>x) units of work for the first d (<7) days and to do z (<x) units of work thereafter since he will get tired of working more in the initial few days.
Find the maximum amount of work he can do during the week if he is free to choose either of the two strategies.
Input
The first line contains an integer T, the number of test cases. Then the test cases follow.
Each test case contains a single line of input, four integers d, x, y, z.
Output
For each testcase, output in a single line the answer to the problem.
Constraints
1≤T≤5⋅103
1≤d<7
1≤z<x<y≤18
Subtasks
Subtask #1 (100 points): Original constraints
Sample Input
3
1 2 3 1
6 2 3 1
1 2 8 1
Sample Output
14
19
14
Explanation
Test Case 1: Using the first strategy, Chef does 2⋅7=14 units of work and using the second strategy Chef does 3⋅1+1⋅6=9 units of work. So the maximum amount of work that Chef can do is max(14,9)=14 units by using the first strategy.
Test Case 2: Using the first strategy, Chef does 2⋅7=14 units of work and using the second strategy Chef does 3⋅6+1⋅1=19 units of work. So the maximum amount of work that Chef can do is max(14,19)=19 units by using the second strategy.*/
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int d, x, y, z;
cin >> d >> x >> y >> z;
int first_strategy, second_strategy;
first_strategy = x*7;
int dayLeft=(7-d);
second_strategy = y*d + dayLeft*z;
cout<<max(first_strategy, second_strategy)<<endl;
}
return 0;
} | |
fd4fad8c88a2d86964bcc15e83f00176b2b455d8 | 44d3e38803b1c154354dd17fa110325951e5d703 | /lib/algorithms/neimansolomon_hash_dyn_matching.h | 11b275555e629b418baac7098c3861f81cfed5c9 | [] | no_license | isaidhiptohop/dynamic_matching | 3ef4942f9e5f93ce1575525be9166088d1828376 | 85ddf0791b5d5d3abe42e7439a6f53a2c1198f68 | refs/heads/master | 2020-03-22T14:22:09.059942 | 2018-10-07T12:43:38 | 2018-10-07T12:43:38 | 140,174,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,090 | h | neimansolomon_hash_dyn_matching.h | /******************************************************************************
* neiman_solomon_dyn_matching.h
*
*
******************************************************************************
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef NEIMANSOLOMON_HASH_DYN_MATCHING_H
#define NEIMANSOLOMON_HASH_DYN_MATCHING_H
#include <bitset>
#include <cassert>
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include "dyn_matching.h"
struct RNG {
std::mt19937 mt;
int nextInt (int lb, int rb) {
std::uniform_int_distribution<unsigned int> A(lb, rb);
return A(mt);
}
};
class neimansolomon_hash_dyn_matching : public dyn_matching {
public:
neimansolomon_hash_dyn_matching (dyn_graph_access* G) : dyn_matching(G) {
}
virtual EdgeID new_edge(NodeID source, NodeID target) {
}
virtual void remove_edge(NodeID source, NodeID target) {
}
private:
// the data structure N(v), which is a vector of hash maps which save
// <id, index>-pairs and a vector of vectors where each inner vector i
// saves the neighbours of a node with id=i
std::vector<std::vector<NodeID> > neighbour_n;
std::vector<std::unordered_map<NodeID, size_t> > neighbour_n_maps;
// a vector that saves the degree of each node
std::vector<size_t> deg_n;
};
#endif // NEIMANSOLOMON_HASH_DYN_MATCHING_H
|
47faebcb9199e47b92ed5f3cee4ce52799f5c520 | 07bd6d166bfe69f62559d51476ac724c380f932b | /devel/include/webots_demo/speaker_is_sound_playing.h | 9f134864dcd33ea81f3fbf7cba96bafc358e18a4 | [] | no_license | Dangko/webots_differential_car | 0efa45e1d729a14839e6e318da64c7f8398edd17 | 188fe93c2fb8d2e681b617df78b93dcdf52e09a9 | refs/heads/master | 2023-06-02T16:40:58.472884 | 2021-06-14T09:19:58 | 2021-06-14T09:19:58 | 376,771,194 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,188 | h | speaker_is_sound_playing.h | // Generated by gencpp from file webots_demo/speaker_is_sound_playing.msg
// DO NOT EDIT!
#ifndef WEBOTS_DEMO_MESSAGE_SPEAKER_IS_SOUND_PLAYING_H
#define WEBOTS_DEMO_MESSAGE_SPEAKER_IS_SOUND_PLAYING_H
#include <ros/service_traits.h>
#include <webots_demo/speaker_is_sound_playingRequest.h>
#include <webots_demo/speaker_is_sound_playingResponse.h>
namespace webots_demo
{
struct speaker_is_sound_playing
{
typedef speaker_is_sound_playingRequest Request;
typedef speaker_is_sound_playingResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
}; // struct speaker_is_sound_playing
} // namespace webots_demo
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::webots_demo::speaker_is_sound_playing > {
static const char* value()
{
return "5e90e3a791904b68b561b7067a8d366b";
}
static const char* value(const ::webots_demo::speaker_is_sound_playing&) { return value(); }
};
template<>
struct DataType< ::webots_demo::speaker_is_sound_playing > {
static const char* value()
{
return "webots_demo/speaker_is_sound_playing";
}
static const char* value(const ::webots_demo::speaker_is_sound_playing&) { return value(); }
};
// service_traits::MD5Sum< ::webots_demo::speaker_is_sound_playingRequest> should match
// service_traits::MD5Sum< ::webots_demo::speaker_is_sound_playing >
template<>
struct MD5Sum< ::webots_demo::speaker_is_sound_playingRequest>
{
static const char* value()
{
return MD5Sum< ::webots_demo::speaker_is_sound_playing >::value();
}
static const char* value(const ::webots_demo::speaker_is_sound_playingRequest&)
{
return value();
}
};
// service_traits::DataType< ::webots_demo::speaker_is_sound_playingRequest> should match
// service_traits::DataType< ::webots_demo::speaker_is_sound_playing >
template<>
struct DataType< ::webots_demo::speaker_is_sound_playingRequest>
{
static const char* value()
{
return DataType< ::webots_demo::speaker_is_sound_playing >::value();
}
static const char* value(const ::webots_demo::speaker_is_sound_playingRequest&)
{
return value();
}
};
// service_traits::MD5Sum< ::webots_demo::speaker_is_sound_playingResponse> should match
// service_traits::MD5Sum< ::webots_demo::speaker_is_sound_playing >
template<>
struct MD5Sum< ::webots_demo::speaker_is_sound_playingResponse>
{
static const char* value()
{
return MD5Sum< ::webots_demo::speaker_is_sound_playing >::value();
}
static const char* value(const ::webots_demo::speaker_is_sound_playingResponse&)
{
return value();
}
};
// service_traits::DataType< ::webots_demo::speaker_is_sound_playingResponse> should match
// service_traits::DataType< ::webots_demo::speaker_is_sound_playing >
template<>
struct DataType< ::webots_demo::speaker_is_sound_playingResponse>
{
static const char* value()
{
return DataType< ::webots_demo::speaker_is_sound_playing >::value();
}
static const char* value(const ::webots_demo::speaker_is_sound_playingResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // WEBOTS_DEMO_MESSAGE_SPEAKER_IS_SOUND_PLAYING_H
|
3fcfe814723799d0c171db21e2c5226d19132211 | a772b49b7beb00cfe7d71a7bb67c3c26882eef5b | /USACO Gold/2015-2016/Jan. 2016/1.AngryCows/main.cpp | 7c5e65e2d6f1696aaffe2b1859cde8b63ea4b447 | [] | no_license | yao-alan/USACO | 8207e78f7a36be7f241011f54abea94965f7a3b2 | 3acefcf385cfd96345549046afebc792b4395ebb | refs/heads/master | 2023-06-10T14:16:18.652205 | 2021-07-02T18:49:08 | 2021-07-02T18:49:08 | 293,708,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,171 | cpp | main.cpp | #include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <utility>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#define V vector
#define pb push_back
#define mp make_pair
#define sz size
#define rsz resize
typedef long long ll;
#define FOR(i, a, b) for(int i = (a); i < (b); ++i)
using namespace std;
/* 1. For a given power R, optimal to land in the middle of a gap as close to
2R in size; for each haybale at position x, look for haybale with
greatest position <= x+2R
2. Once a position y has been found, simulate explosions by destroying
a lower bound >= y-R and upper bound <= y+R; continue until nothing more
can be destroyed and see if this covers max(haybale) - min(haybale)
3. Binary search on 2R
*/
int binsearch_helper(bool type, vector<int>& arr, double x) {
// lower_bound = greatest number <= x
// upper_bound = smallest number >= x
int lo = 0, hi = arr.size()-1;
int best = type ? lo : hi;
while (lo <= hi) {
int mid = lo + (hi-lo)/2;
if (type) { // lower bound
if (arr[mid] <= x) {
best = max(best, mid);
lo = mid+1;
} else {
hi = mid-1;
}
} else { // upper bound
if (arr[mid] >= x) {
best = min(best, mid);
hi = mid-1;
} else {
lo = mid+1;
}
}
}
return best;
}
int lower_bound(vector<int>& arr, double x) { return binsearch_helper(true, arr, x); }
int upper_bound(vector<int>& arr, double x) { return binsearch_helper(false, arr, x); }
int main() {
freopen("angry.in", "r", stdin);
freopen("angry.out", "w", stdout);
// all values are doubled so that we can binary search on multiples of 0.5
int N; cin >> N;
vector<int> haybales;
for (int i = 0; i < N; ++i) {
int h; cin >> h;
haybales.pb(2*h);
}
sort(haybales.begin(), haybales.end());
int min2R = 2e9;
int lo = 1, hi = 2*(haybales.back() - haybales.front());
double center = haybales.front() + (haybales.back()-haybales.front())/2.0;
while (lo <= hi) {
int mid2R = lo + (hi-lo)/2;
/* figure out where to drop cow
1. if we can explode everything on right but not left, move left
2. if we can explode everything on left but not right, move right
3. else if we cannot explode everything, break
*/
bool possible = false;
int left = 0, right = haybales.back();
while (left <= right) {
int mid = left + (right-left)/2;
// simulate exploding cows
double power = mid2R/2.0;
int lowestLeft = upper_bound(haybales, mid-power);
while (power > 0 && lowestLeft != 0) {
power -= 2.0;
int lower = upper_bound(haybales, haybales[lowestLeft] - power);
if (lower == lowestLeft) break;
lowestLeft = lower;
}
power = mid2R/2.0;
int highestRight = lower_bound(haybales, mid+power);
while (power > 0 && highestRight != N-1) {
power -= 2.0;
int higher = lower_bound(haybales, haybales[highestRight] + power);
if (higher == highestRight) break;
highestRight = higher;
}
if (lowestLeft > 0 && highestRight < N-1) { // R unusable
break;
} else if (lowestLeft > 0) { // move left
right = mid-1;
} else if (highestRight < N-1) { // move right
left = mid+1;
} else if (lowestLeft == 0 && highestRight == N-1) {
possible = true;
break;
}
}
if (possible) {
min2R = min(min2R, mid2R);
hi = mid2R-1;
} else {
lo = mid2R+1;
}
}
printf("%1.1f", double(min2R)/4.0);
}
|
2f583eea8e4b05c452fe24f008d8cf3ae374d5b7 | 879fc5574b6dd2c683b4c12e39ba51e44e6dc942 | /src/lib/math/nbtheory.cpp | 07abfca952408cfde8d5721824743288b50e7530 | [
"MIT"
] | permissive | carlzhangweiwen/gazelle_mpc | a48072cf296dd106ee0dd8d010e728d579f2f522 | 45818ccf6375100a8fe2680f44f37d713380aa5c | refs/heads/master | 2020-09-24T13:38:33.186719 | 2019-12-06T02:15:48 | 2019-12-06T02:15:48 | 225,770,500 | 0 | 0 | MIT | 2019-12-04T03:25:50 | 2019-12-04T03:25:49 | null | UTF-8 | C++ | false | false | 17,253 | cpp | nbtheory.cpp | /**
* @file nbtheory.cpp This code provides number theory utilities.
* @author TPOC: palisade@njit.edu
*
* @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "nbtheory.h"
#include "distributiongenerator.h"
#include "time.h"
#include <chrono>
#include <stdexcept>
#include "../utils/debug.h"
#define _USE_MATH_DEFINES
//#include <cmath>
//#include <time.h>
//#include <sstream>
namespace lbcrypto {
/*
Generates a random number between 0 and n.
Input: BigInteger n.
Output: Randomly generated BigInteger between 0 and n.
*/
static ui64 RNG(const ui64 modulus)
{
// static parameters for the 32-bit unsigned integers used for multiprecision random number generation
auto distribution = std::uniform_int_distribution<ui64>(0, modulus-1);
return distribution(get_prng());
}
/*
A witness function used for the Miller-Rabin Primality test.
Inputs: a is a randomly generated witness between 2 and p-1,
p is the number to be tested for primality,
s and d satisfy p-1 = ((2^s) * d), d is odd.
Output: true if p is composite,
false if p is likely prime
*/
static bool WitnessFunction(const ui64 a, const ui64 d, ui32 s, const ui64 p)
{
bool dbg_flag = false;
DEBUG("calling modexp a " << a << " d " << d << " p " << p);
ui64 mod = mod_exp(a, d, p);
DEBUG("mod " << mod);
bool prevMod = false;
for (ui32 i = 1; i < s + 1; i++) {
DEBUG("wf " << i);
if (mod != 1 && mod != p - 1)
prevMod = true;
else
prevMod = false;
mod = (mod*mod) % p;
if (mod == 1 && prevMod) return true;
}
return (mod != 1);
}
/*
A helper function to RootOfUnity function. This finds a generator for a given prime q.
Input: BigInteger q which is a prime.
Output: A generator of prime q
*/
static ui64 FindGenerator(const ui64 q)
{
bool dbg_flag = false;
std::set<ui64> primeFactors;
DEBUG("calling PrimeFactorize");
ui64 qm1 = q - 1;
ui64 qm2 = q - 2;
PrimeFactorize(qm1, primeFactors);
DEBUG("done");
bool generatorFound = false;
ui64 gen;
while (!generatorFound) {
ui32 count = 0;
gen = (RNG(qm2) + 1) % q;
DEBUG("Trying gen " << gen);
for (auto it = primeFactors.begin(); it != primeFactors.end(); ++it) {
auto test = mod_exp(gen, qm1 / (*it), q);
DEBUG("mod_exp(" << gen << ", " << (qm1 / (*it)) << ", " << q << ") = " << test);
if (test == 1)
break;
else
count++;
}
if (count == primeFactors.size()) generatorFound = true;
}
return gen;
}
/*
A helper function for arbitrary cyclotomics. This finds a generator for any composite q (cyclic group).
Input: BigInteger q (cyclic group).
Output: A generator of prime q
*/
ui64 FindGeneratorCyclic(const ui64 q)
{
bool dbg_flag = false;
std::set<ui64> primeFactors;
DEBUG("calling PrimeFactorize");
ui64 phi_q = ui64(GetTotient(q));
ui64 phi_q_m1 = ui64(GetTotient(q));
PrimeFactorize(phi_q, primeFactors);
DEBUG("done");
bool generatorFound = false;
ui64 gen;
while (!generatorFound) {
ui32 count = 0;
DEBUG("count " << count);
gen = RNG(phi_q_m1) + 1; // gen is random in [1, phi(q)]
if (GreatestCommonDivisor(gen, q) != 1) {
// Generator must lie in the group!
continue;
}
// Order of a generator cannot divide any co-factor
for (auto it = primeFactors.begin(); it != primeFactors.end(); ++it) {
DEBUG("in set");
DEBUG("divide " << phi_q << " by " << *it);
if (mod_exp(gen, phi_q / (*it), q) == 1){
break;
} else {
count++;
}
}
if (count == primeFactors.size()) generatorFound = true;
}
return gen;
}
/*
A helper function for arbitrary cyclotomics. Checks if g is a generator of q (supports any cyclic group, not just prime-modulus groups)
Input: Candidate generator g and modulus q
Output: returns true if g is a generator for q
*/
bool IsGenerator(const ui64 g, const ui64 q)
{
bool dbg_flag = false;
std::set<ui64> primeFactors;
DEBUG("calling PrimeFactorize");
ui64 qm1 = ui64(GetTotient(q));
PrimeFactorize(qm1, primeFactors);
DEBUG("done");
ui32 count = 0;
for (auto it = primeFactors.begin(); it != primeFactors.end(); ++it) {
DEBUG("in set");
DEBUG("divide " << qm1 << " by " << *it);
if (mod_exp(g, qm1 / (*it), q) == 1) break;
else count++;
}
if (count == primeFactors.size())
return true;
else
return false;
}
/*
finds roots of unity for given input. Assumes the the input is a power of two. Mostly likely does not give correct results otherwise.
input: m as number which is cyclotomic(in format of int),
modulo which is used to find generator (in format of BigInteger)
output: root of unity (in format of BigInteger)
*/
ui64 RootOfUnity(ui32 m, const ui64 modulo)
{
bool dbg_flag = false;
DEBUG("in Root of unity m :" << m << " modulo " << modulo);
ui64 M(m);
if (((modulo - 1) % M) != 0) {
std::string errMsg = "Please provide a primeModulus(q) and a cyclotomic number(m) satisfying the condition: (q-1)/m is an integer. The values of primeModulus = " + std::to_string(modulo) + " and m = " + std::to_string(m) + " do not satisfy this condition";
throw std::runtime_error(errMsg);
}
ui64 result;
DEBUG("calling FindGenerator");
ui64 gen = FindGenerator(modulo);
DEBUG("gen = " << gen);
DEBUG("calling gen.ModExp( " << ((modulo - 1)/M) << ", modulus " << modulo << ")");
result = mod_exp(gen, (modulo - 1)/M, modulo);
DEBUG("result = " << result);
if (result == 1) {
DEBUG("LOOP?");
return RootOfUnity(m, modulo);
}
return result;
}
uv64 RootsOfUnity(ui32 m, const uv64 moduli) {
uv64 rootsOfUnity(moduli.size());
for (ui32 i = 0; i < moduli.size(); i++) {
rootsOfUnity[i] = RootOfUnity(m, moduli[i]);
}
return rootsOfUnity;
}
ui64 GreatestCommonDivisor(const ui64 a, const ui64 b)
{
bool dbg_flag = false;
ui64 m_a, m_b, m_t;
m_a = a;
m_b = b;
DEBUG("GCD a " << a << " b " << b);
while (m_b != 0) {
m_t = m_b;
DEBUG("GCD m_a.Mod(b) " << m_a << "( " << m_b << ")");
m_b = m_a % m_b;
m_a = m_t;
DEBUG("GCD m_a " << m_b << " m_b " << m_b);
}
DEBUG("GCD ret " << m_a);
return m_a;
}
/*
The Miller-Rabin Primality Test
Input: p the number to be tested for primality.
Output: true if p is prime,
false if p is not prime
*/
bool MillerRabinPrimalityTest(const ui64 p, const ui32 niter)
{
bool dbg_flag = false;
if (p < 2 || ((p != 2) && ((p%2) == 0)))
return false;
if (p == 2 || p == 3 || p == 5)
return true;
ui64 d = p - 1;
ui32 s = 0;
DEBUG("start while d " << d);
while ((d%2) == 0) {
d = d/2;
s++;
}
DEBUG("end while s " << s);
bool composite = true;
for (ui32 i = 0; i < niter; i++) {
DEBUG(".1");
ui64 a = (RNG(p - 3)+2)%p;
DEBUG(".2");
composite = (WitnessFunction(a, d, s, p));
if (composite)
break;
}
DEBUG("done composite " << composite);
return (!composite);
}
/*
The Pollard Rho factorization of a number n.
Input: n the number to be factorized.
Output: a factor of n.
*/
const ui64 PollardRhoFactorization(const ui64 n)
{
bool dbg_flag = false;
ui64 divisor(1);
ui64 c(RNG(n));
ui64 x(RNG(n));
ui64 xx(x);
//check divisibility by 2
if (n%2 == 0)
return ui64(2);
do {
x = (x*x + c) % n;
xx = (xx*xx + c) % n;
xx = (xx*xx + c) % n;
divisor = GreatestCommonDivisor(((x - xx) > 0) ? x - xx : xx - x, n);
DEBUG("PRF divisor " << divisor);
} while (divisor == 1);
return divisor;
}
/*
Recursively factorizes and find the distinct primefactors of a number
Input: n is the number to be prime factorized,
primeFactors is a set of prime factors of n.
*/
void PrimeFactorize(ui64 n, std::set<ui64>& primeFactors)
{
bool dbg_flag = false;
DEBUG("PrimeFactorize " << n);
// primeFactors.clear();
DEBUG("In PrimeFactorize n " << n);
DEBUG("set size " << primeFactors.size());
if (n == 0 || n == 1) return;
DEBUG("calling MillerRabinPrimalityTest(" << n << ")");
if (MillerRabinPrimalityTest(n)) {
DEBUG("Miller true");
primeFactors.insert(n);
return;
}
DEBUG("calling PrFact n " << n);
ui64 divisor(PollardRhoFactorization(n));
DEBUG("calling PF " << divisor);
PrimeFactorize(divisor, primeFactors);
DEBUG("calling div " << divisor);
//ui64 reducedN = n.DividedBy(divisor);
n /= divisor;
DEBUG("calling PF reduced n " << n);
PrimeFactorize(n, primeFactors);
}
ui64 FirstPrime(ui32 nBits, ui32 m) {
ui64 r = mod_exp(ui64(2), ui64(nBits), ui64(m));
ui64 qNew = (ui64(1) << nBits) + (ui64(m) - r) + ui64(1);
size_t i = 1;
while (!MillerRabinPrimalityTest(qNew)) {
qNew += ui64(i*m);
i++;
}
return qNew;
}
ui64 NextPrime(const ui64 &q, ui32 m) {
ui64 qNew = q + m - (q % m) + 1;
while (!MillerRabinPrimalityTest(qNew)) {
qNew += m;
}
return qNew;
}
ui32 GreatestCommonDivisor(const ui32& a, const ui32& b)
{
bool dbg_flag = false;
ui32 m_a, m_b, m_t;
m_a = a;
m_b = b;
DEBUG("GCD a " << a << " b " << b);
while (m_b != 0) {
m_t = m_b;
DEBUG("GCD m_a.Mod(b) " << m_a << "( " << m_b << ")");
m_b = m_a % (m_b);
m_a = m_t;
DEBUG("GCD m_a " << m_b << " m_b " << m_b);
}
DEBUG("GCD ret " << m_a);
return m_a;
}
ui64 NextPowerOfTwo(const ui64 &n) {
ui32 result = ceil(log2(n));
return result;
}
ui64 GetTotient(const ui64 n) {
std::set<ui64> factors;
ui64 enn(n);
PrimeFactorize(enn, factors);
ui64 primeProd(1);
ui64 numerator(1);
for (auto &r : factors) {
numerator = numerator * (r - 1);
primeProd = primeProd * r;
}
primeProd = (enn / primeProd) * numerator;
return primeProd;
}
/*Naive Loop to find coprimes to n*/
uv64 GetTotientList(const ui64 &n) {
uv64 result;
ui64 one(1);
for (ui64 i = ui64(1); i < n; i = i + ui64(1)) {
if (GreatestCommonDivisor(i, n) == one)
result.push_back(i);
}
return result; //std::move(result);
}
sv32 GetCyclotomicPolynomialRecursive(ui32 m) {
sv32 poly;
if (m == 1) {
poly = { -1,1 };
return poly;
}
if (m == 2) {
poly = { 1,1 };
return poly;
}
auto IsPrime = [](ui32 mm) {
bool flag = true;
for (ui32 i = 2; i < mm; i++) {
if (mm%i == 0) {
flag = false;
return flag;
}
}
return flag;
};
if (IsPrime(m)) {
poly = sv32(m, 1);
return poly;
}
auto GetDivisibleNumbers = [](ui32 mm) {
std::vector<ui32> div;
for (ui32 i = 1; i < mm; i++) {
if (mm%i == 0) {
div.push_back(i);
}
}
return div;
};
auto PolyMult = [](const sv32 &a, const sv32 &b) {
ui32 degreeA = a.size() - 1;
ui32 degreeB = b.size() - 1;
ui32 degreeResultant = degreeA + degreeB;
sv32 result(degreeResultant + 1, 0);
for (ui32 i = 0; i < a.size(); i++) {
for (ui32 j = 0; j < b.size(); j++) {
const auto &valResult = result.at(i + j);
const auto &valMult = a.at(i)*b.at(j);
result.at(i + j) = valMult + valResult;
}
}
return result;
};
auto PolyQuotient = [](const sv32 ÷nd, const sv32 &divisor) {
ui32 divisorLength = divisor.size();
ui32 dividendLength = dividend.size();
ui32 runs = dividendLength - divisorLength + 1; //no. of iterations
sv32 result(runs + 1);
auto mat = [](const int x, const int y, const int z) {
int result = z - (x*y);
return result;
};
sv32 runningDividend(dividend);
ui32 divisorPtr;
for (ui32 i = 0; i < runs; i++) {
int divConst = (runningDividend.at(dividendLength - 1));//get the highest degree coeff
divisorPtr = divisorLength - 1;
for (ui32 j = 0; j < dividendLength - i - 1; j++) {
if (divisorPtr > j) {
runningDividend.at(dividendLength - 1 - j) = mat(divisor.at(divisorPtr - 1 - j), divConst, runningDividend.at(dividendLength - 2 - j));
}
else
runningDividend.at(dividendLength - 1 - j) = runningDividend.at(dividendLength - 2 - j);
}
result.at(i + 1) = runningDividend.at(dividendLength - 1);
}
result.at(0) = 1;//under the assumption that both dividend and divisor are monic
result.pop_back();
return result;
};
auto divisibleNumbers = GetDivisibleNumbers(m);
sv32 product(1, 1);
for (ui32 i = 0; i < divisibleNumbers.size(); i++) {
auto P = GetCyclotomicPolynomialRecursive(divisibleNumbers[i]);
product = PolyMult(product, P);
}
//make big poly = x^m - 1
sv32 bigPoly(m + 1, 0);
bigPoly.at(0) = -1;
bigPoly.at(m) = 1;
poly = PolyQuotient(bigPoly, product);
return poly;
}
uv64 GetCyclotomicPolynomial(ui32 m, const ui64 modulus) {
auto intCP = GetCyclotomicPolynomialRecursive(m);
uv64 result(intCP.size(), modulus);
for (ui32 i = 0; i < intCP.size(); i++) {
auto val = intCP[i];
if (intCP.at(i) > -1)
result[i] = ui64(val);
else {
val *= -1;
result[i] = ui64(modulus - ui64(val));
}
}
return result;
}
}
|
ddb606c240248d45e236377f45e9095844f1866b | 332eec9d47742c7a251d6d50746e732a3016d08f | /tileMapGen.h | 986ec480603747519a783ee524e5722e393590e6 | [] | no_license | lolcube/magen | 74c1fb908ece277b4f576a76b3db6f9effe6ec47 | d4991bef22ed91f4d40d2d42396df0cfd9d4b022 | refs/heads/master | 2020-08-12T23:22:47.718750 | 2019-10-13T17:54:20 | 2019-10-13T17:54:20 | 214,863,150 | 1 | 1 | null | 2019-10-13T18:29:17 | 2019-10-13T17:28:39 | C | UTF-8 | C++ | false | false | 102 | h | tileMapGen.h | #pragma once
#include <SDL2/SDL.h>
#include <vector>
class MapGen{
public:
private:
};
|
7ef65021955050b5d461603c03d1e13d4491faeb | d12aa4b8087c23c976ff362ff10efcb921f426f8 | /tests/test-crypto/main.cpp | d5d19ecbc01c78fef8e9f6c976bed1a62d49dc3a | [] | no_license | bensoer/haanrad | 4abcf0d7fec80711d7050f3619578afda147c318 | 78591cbf390df207c5fc78c01149003c1dade354 | refs/heads/master | 2021-03-27T16:51:33.094715 | 2016-12-01T06:55:23 | 2016-12-01T06:55:23 | 72,496,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,725 | cpp | main.cpp | //
// Created by bensoer on 15/11/16.
//
#include <cstring>
#include <iostream>
#include "../../src/shared/HCrypto.h"
#include "../../src/shared/PacketIdentifier.h"
#include "../../src/shared/utils/Structures.h"
#include "../../src/shared/utils/Logger.h"
#include "../../src/shared/Authenticator.h"
#include <netinet/tcp.h>
using namespace std;
int main(int argc, char * argv[]){
Logger::setDebug(true);
Logger::debug("Creating Fake PAcket");
PacketMeta * meta = new PacketMeta();
meta->ipType = NetworkType::IPv4;
meta->transportType = TransportType::TCP;
meta->applicationType = ApplicationType::TLS;
string message = "{HAAN1jdklsajdklsa";
struct iphdr * ip = (struct iphdr *)meta->packet;
ip->ihl = 5;
struct tcphdr * tcp = (struct tcphdr *)(meta->packet + 20); // 20 byte default header ( 4 * 5)
tcp->doff = 5;
char * applicationLayer = (meta->packet + 20 + sizeof(tcphdr));
struct TLS_HEADER * tls = (struct TLS_HEADER *)(meta->packet + 20 + sizeof(tcphdr));
tls->contentType=23;
tls->type = 771;
tls->length = htons(1);
char * payload = meta->packet + 20 + sizeof(tcphdr) + sizeof(TLS_HEADER);
memcpy(payload, message.c_str(), message.size());
Authenticator::setPassword("password");
Authenticator::addAuthSignature(meta);
Logger::debug("Creating Crypto Handler");
HCrypto * crypto = new HCrypto();
crypto->initialize("password");
Logger::debug("Now Encrypting");
crypto->encryptPacket(meta, applicationLayer);
Logger::debug("Now Decrypting");
crypto->decryptPacket(meta, applicationLayer);
Logger::debug("Printing Results");
cout << ">" << string(payload) << "<" << endl;
return 0;
} |
039a9e8df85d08963248994fab3db33b12e90557 | ced0e0cc944fa994f468d37b288f6c4d98fbaa37 | /Vector/Vector.h | 01069eb7a101fbd698b79859bd8392d3d2d330f4 | [] | no_license | Vlad-git805/OOP-dz-10 | 6ee25ed3ec19e84fdd26c325bad94e0c1b7984b4 | 7fc4ebb72995ed5b3a0b2be1189e42e14c1dd6bd | refs/heads/master | 2022-10-22T16:09:39.563395 | 2020-06-10T14:12:33 | 2020-06-10T14:12:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | h | Vector.h | #pragma once
#include <iostream>
#include "Point.h"
using namespace std;
class Vector
{
private:
Point* points;
int countPoints;
public:
Vector();
Vector(const Vector& other);
Vector(Vector&& other);
Vector& operator=(const Vector&other);
Vector& operator=(Vector&& other);
void Add_Point(const Point &p);
void Print()const;
~Vector();
}; |
9ffd529dbf2f64eef85f3d060f7896b2fba27100 | 732c7328e90690833bb82c5f2a253b36ad551701 | /structural/facade/main.cpp | d17ffd8a9dc7e76318f76a2674313b5013de8f42 | [] | no_license | VasylA/cpp_design_patterns | 89c5e0d5f943d1d95057437a03aea36fa086b8b9 | d122595dd8b8ee4d8410b90598834d11cf49688e | refs/heads/master | 2021-01-14T03:08:42.601473 | 2020-02-27T08:10:38 | 2020-02-27T08:10:38 | 242,581,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | main.cpp | #include "skiresortfacade.h"
#include <iostream>
#include <memory>
int main()
{
std::unique_ptr<SkiResortFacade> skiResortFacade = std::make_unique<SkiResortFacade>();
auto restPrice = skiResortFacade->organizeRestWithOwnSkies(4);
std::cout << "Price for rest with own skies is " << restPrice << std::endl;
restPrice = skiResortFacade->organizeAllInclusiveRest(175, 65, 40, 5, 5);
std::cout << "Price for all inclusive rest is " << restPrice << std::endl;
return 0;
}
|
202934a3b796b1ecf5f18425504b2b7e04173ae6 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /Implementation/560.cpp | 85829dafd40519069ad0e1f11029bc40ad56fb52 | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | 560.cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
long int n,k,m;
cin>>n>>k;
vector<int> v(n);
for(int i=0;i<n;i++){
cin>>v[i];
}
int c=0;
for(int i=0;i<n;i++)
if(v[i]>=v[k-1] && v[i]>0)
c++;
cout<<c<<endl;
}
|
0c00dda2a25dd16ee38d976e4a8d02c4bdf93367 | 7f86d6422cb359aa46842d5e6c22385d4a0ff4ad | /source/button.cpp | 92e1d1547e96ac1ed8862edab3078a6287f4bfbf | [] | no_license | tomgalvin594/Struct | e6d0b65a710ba5ded170fbff030e1407d1c55183 | 1b0dfd212f9a549884e1a59ba3c8e1aefb90f3aa | refs/heads/master | 2021-01-10T02:42:02.877494 | 2015-05-24T01:15:38 | 2015-05-24T01:15:38 | 36,150,161 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,018 | cpp | button.cpp | #include "button.hpp"
#include <iostream>
Button::Button( sf::Vector2f position,
sf::Vector2f scale,
sf::Sprite sprite,
sf::Font font,
unsigned int char_size,
std::string label)
{
m_position = position;
m_sprite = sprite;
m_font = font;
m_sprite = sprite;
m_sprite.setPosition(position);
m_sprite.setScale(scale);
m_text.setFont(m_font);
m_text.setString(label);
m_text.setCharacterSize(char_size);
float sprite_w = m_sprite.getGlobalBounds().width;
float sprite_h = m_sprite.getGlobalBounds().height;
float label_w = m_text.getGlobalBounds().width;
float label_h = m_text.getGlobalBounds().height;
float y_offset = (m_font.getLineSpacing(char_size) - m_text.getCharacterSize()) * 1.5f;
m_text.setOrigin(label_w / 2, label_h / 2);
m_text.setPosition(position.x + sprite_w/2, position.y + sprite_h/2 - y_offset);
}
Button::~Button()
{
}
void Button::handle_events(sf::Event &event, std::shared_ptr<sf::RenderWindow> window)
{
if(event.type == sf::Event::MouseMoved)
{
int x = window->mapPixelToCoords({event.mouseMove.x,0}).x;
int y = window->mapPixelToCoords({0,event.mouseMove.y}).y;
if(is_mouse_over_button(x, y))
m_state = button_state::button_select;
else
m_state = button_state::button_general;
}
if(event.type == sf::Event::MouseButtonPressed)
{
if(m_state == button_state::button_select)
m_state = button_down;
}
}
void Button::update(float delta)
{
if(m_state == button_state::button_general)
m_sprite.setColor(sf::Color(200, 200, 200, 255));
else if(m_state == button_state::button_select)
m_sprite.setColor(sf::Color(255, 255, 255, 255));
else if(m_state == button_state::button_down)
m_sprite.setColor(sf::Color(255, 255, 255, 255));
}
void Button::render(std::shared_ptr<sf::RenderWindow> window)
{
window->draw(m_sprite);
window->draw(m_text);
}
void Button::set_scale(sf::Vector2f scale)
{
m_sprite.setScale(scale);
}
void Button::set_character_size(unsigned int size)
{
m_text.setCharacterSize(size);
}
void Button::reset_state()
{
m_state = button_state::button_general;
}
unsigned int Button::get_state() const
{
return m_state;
}
bool Button::is_mouse_over_button(int mouse_x, int mouse_y)
{
float top_left_x = m_position.x;
float top_left_y = m_position.y;
float top_right_x = m_position.x + m_sprite.getGlobalBounds().width;
float bottom_left_y = m_position.y + m_sprite.getGlobalBounds().height;
if( mouse_x >= top_left_x &&
mouse_x <= top_right_x &&
mouse_y >= top_left_y &&
mouse_y <= bottom_left_y)
return true;
return false;
}
|
e226117c4457e669ae1ffadd7938f97e5a3b7850 | 11f16ce13863efdfe9bbcd00286c53eacf6253b9 | /YTPolymorphism.cpp | 265c0c8c0b2e4d8439c563f4e722b246a4304b9f | [] | no_license | SCrawCode/C-OOP-Practice | a8b4a543d5f06a7aae8780c3850f86a6ce6814d6 | e171d28bf279a904d941d3c303e185bf8608ee65 | refs/heads/main | 2023-04-14T11:15:01.183323 | 2021-04-22T14:48:37 | 2021-04-22T14:48:37 | 360,553,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,700 | cpp | YTPolymorphism.cpp | //Practice with Classes (User-Defined Data type)
//Make a class for YoutTube channels with channel stats as attributes
//Utilize Constructors to simplify code for multiple instances of class
//A constructor is a method used to create an object of a specific class
//Utilize Encapsulation to prevent user from altering class data (Make Private)
//Hide class attributes from being directly manipulated and use public methods to allow program defined alterations
//Utilize inheritance to create derived classes that use the traits of a base class
#include <iostream>
#include <list>
using namespace std;
class YouTubeChannel {
private: //Makes attributes unaccessible outside of class
string Name;
int subscriberCount;
list<string> publishedVideos;
protected: //Allows access from derived classes
string Owner;
int contentQuality;
public: //Allows user to interact with name and owner
YouTubeChannel(string name, string owner) { //Constructor of Class
Name = name;
Owner = owner;
subscriberCount = 0; //A fresh channel starts with no subs
contentQuality = 0;
}
//Class method that prints class attributes without repetition
void getInfo() {
cout << "Channel: " << Name << endl;
cout << "YouTuber: " << Owner << endl;
cout << "Subscribers: " << subscriberCount << endl;
cout << "Published Videos: ";
for (string videoTitle: publishedVideos) {
cout << videoTitle << ", ";
}
cout << endl;
}
//Method that increments sub count by 1 per subscription
void subscribe() {
subscriberCount++;
}
void unsubscribe() {
if (subscriberCount > 0) {
subscriberCount--;
}
}
//Method that publishes videos
void publishVid(string Title) {
publishedVideos.push_back(Title);
}
};
class cookingYouTubeChannel:public YouTubeChannel {
public:
cookingYouTubeChannel(string name, string owner):YouTubeChannel(name, owner) {}
void Practice() {
cout << "Join " << Owner << " Practice Cooking, Learning New Recipes, and Experimenting with Spices!!!\n";
contentQuality++;
}
};
class musicYouTubeChannel:public YouTubeChannel {
public:
musicYouTubeChannel(string name, string owner):YouTubeChannel(name, owner) {}
void Practice() {
cout << "Join " << Owner << " in Singing, Learning New Songs, and How to Dance!!!\n";
contentQuality++;
}
};
int main() {
cookingYouTubeChannel cookingYtChannel("Amy's Kitchen", "Amy Wong");
musicYouTubeChannel musicYTChannel("JohnSings", "John Sean");
cookingYtChannel.Practice();
cookingYtChannel.Practice();
musicYTChannel.Practice();
musicYTChannel.Practice();
musicYTChannel.Practice();
return 0;
}
|
1ccacf4e4c8627937be3434dad23109ed629dee7 | cc355f1234133148dbb1e11be4df53351fe82da6 | /src/bridge.h | 5a0c1872a5a6d17041fbc54d05fedbedf225e7b3 | [] | no_license | drkzrg/hdspmidi | 0a2b0c60bce573c70b538b2c49441d9915d8c616 | 9a705d6053e0e2c8ee950887361ca901c105fd55 | refs/heads/master | 2023-03-17T09:55:56.436178 | 2012-12-23T23:42:30 | 2012-12-23T23:42:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | h | bridge.h | #ifndef BRIDGE_H
#define BRIDGE_H
#include "HDSPMixerCard.h"
#include "Channel.h"
#include "midicontroller.h"
#include "relay.h"
class Bridge
{
public:
Bridge();
~Bridge();
int vegas;
void restore(void);
void send_control(int dst, struct channel ch, int left_value, int right_value);
void control_normal(int dst, struct channel ch);
void control_solos();
void control_onair();
void dump_event(const snd_seq_event_t *ev);
HDSPMixerCard *hdsp_card;
Channels channels;
MidiController midicontroller;
Relay relay;
int phones;
int main;
int monitors;
};
#endif // BRIDGE_H
|
b249f8312cc1da4a4b56c42b22cba477beabad26 | 1055f8df38e7734b29dea44646d18ec2e731b46b | /coj/COJ-3286.cpp | 9bd0ce41e6f719100428dcd3082fa41a55e80920 | [] | no_license | Kireck211/competitive | 60115e92ae15be6834a028c5256cabf548d64bef | c21dfdb788f604716f25c1b26c9e3552d4a99110 | refs/heads/master | 2021-03-19T06:02:54.407717 | 2018-09-26T15:57:36 | 2018-09-26T15:57:36 | 105,324,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | cpp | COJ-3286.cpp | #include <iostream>
using namespace std;
int disjoints = 0;
int find(int parent[], int i)
{
return (parent[i] == i? i : parent[i] = find(parent, parent[i]));
}
void _union(int parent[], int i, int j)
{
int x = find(parent, i);
int y = find(parent, j);
if(x != y)
disjoints--;
parent[y] = x;
}
int main()
{
int t, n, m, a, b;
int parent[10000];
cin>>t;
while(t--)
{
cin>>n>>m;
disjoints = n;
for(int i = 0; i <= n; i++)
parent[i] = i;
for(int i = 0; i < m; i++)
{
cin>>a>>b;
_union(parent, a, b);
}
cout<<((disjoints*(disjoints-1))>>1)<<endl;
}
return 0;
} |
f966ee1a1e4feca6acc2396e23dd63515c5aa4a9 | 51ef1af1e47928bb4eedde22e3f614efd89414c6 | /Intellum/DXSystem.h | a7e32abc9bc017ab9bd68ed3e3e3e6b407a63bc8 | [] | no_license | Flave229/Intellum | b0e22d15fe9e83a94e4f29226489554929bdff08 | f43fd96069aae1da9b7a0993dd15aa6105991237 | refs/heads/master | 2021-07-07T07:09:51.509705 | 2017-10-02T15:38:20 | 2017-10-02T15:38:20 | 65,088,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | h | DXSystem.h | #ifndef _SYSTEM_H_
#define _SYSTEM_H_
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "Engine/Graphics/Graphics.h"
#include "Engine/GameTimer.h"
#include "Engine/SystemMetrics/FramesPerSecond.h"
#include "Engine/SystemMetrics/Cpu.h"
#include "engine/Input/Input.h"
class DXSystem
{
private:
LPCWSTR _applicationName;
HINSTANCE _hInstance;
HWND _hwnd;
FramesPerSecond* _framesPerSecond;
Cpu* _cpu;
GameTimer* _timer;
Input* _input;
Graphics* _graphics;
static bool _shutdownQueued;
private:
void Initialise();
void InitialiseWindows(Box& screenSize);
bool Frame(float delta) const;
void ShutdownWindows();
public:
DXSystem();
DXSystem(const DXSystem&);
~DXSystem();
void Shutdown();
void Run();
static void ShutdownApplication();
static LRESULT CALLBACK MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam);
};
static LRESULT CALLBACK WndProc(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam);
static DXSystem* ApplicationHandle = nullptr;
#endif |
84d1e0f7555dd529bdc865cc6f6579b7f7514490 | 1b49fac0f0ea40589ecd29d04a6f1ca4d6c3a7eb | /lib/actions/ferm/invert/qop_mg/syssolver_linop_qop_mg_w.cc | c7c89967e74370b9ef250df2f308dfb8c9466548 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | orginos/chroma | cc22c9854e2a0db2d4f17488904671015196c36f | 57ba8783393dd7668c6a45e7f4c9919280c29cd3 | refs/heads/master | 2021-01-16T21:38:32.182916 | 2015-10-18T16:03:54 | 2015-10-18T16:03:54 | 24,952,861 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,456 | cc | syssolver_linop_qop_mg_w.cc | // $Id: syssolver_linop_qdp_mg.cc, v1.0 2013-06-20 22:12 sdcohen $
/*! \file
* \brief Make contact with the QDP clover multigrid solver, transfer
* the gauge field, generate the coarse grids, solve systems
*/
#include "state.h"
#include "meas/inline/io/named_objmap.h"
#include "actions/ferm/invert/syssolver_linop_factory.h"
#include "actions/ferm/invert/syssolver_linop_aggregate.h"
#if BASE_PRECISION == 32
#define QDP_Precision 'F'
#define QLA_Precision 'F'
#define toReal toFloat
#elif BASE_PRECISION == 64
#define QDP_Precision 'D'
#define QLA_Precision 'D'
#define toReal toDouble
#endif
#include "actions/ferm/invert/qop_mg/syssolver_linop_qop_mg_w.h"
extern "C" {
// This should be placed on the include path.
#include "wilsonmg-interface.h"
}
#include "meas/glue/mesplq.h"
namespace Chroma
{
static multi1d<LatticeColorMatrix> u;
// These functions will allow QDP to look into the Chroma gauge field and set
// the QDP gauge field at each site equal to the one in Chroma. There doesn't
// seem to be a good way to treat the extra vector index of the gauge field,
// so we make a vector of functions to carry that index.
#define index(c) c[0]+nrow[0]/2*(c[1]+nrow[1]*(c[2]+nrow[2]*(c[3]+nrow[3]*((c[0]+c[1]+c[2]+c[3])%2)))) // Hrm, this didn't seem to work; using linearSiteIndex for now...
#define pepo(d) \
void peekpoke##d(QLA(ColorMatrix) *dest, int coords[]) {\
START_CODE();\
multi1d<int> x(4); for (int i=0; i<4; i++) x[i] = coords[i];\
ColorMatrix U; U.elem() = u[d].elem(Layout::linearSiteIndex(x));\
END_CODE();\
\
QLA(Complex) z;\
QLA(Real) real, imag;\
for (int c1=0; c1<3; c1++)\
for (int c2=0; c2<3; c2++) {\
real = U.elem().elem().elem(c1,c2).real();\
imag = U.elem().elem().elem(c1,c2).imag();\
if (0&&c1==0&&c2==0) {fflush(stdout);printf("Chroma: gauge[%d] I am node %d, parsing %d %d %d %d; I see %g + I %g\n",d,Layout::nodeNumber(),x[0],x[1],x[2],x[3],real,imag); fflush(stdout);}\
QLA(C_eq_R_plus_i_R)(&z, &real, &imag);\
QLA_elem_M(*dest,c1,c2) = z;\
}\
}
pepo(0)
pepo(1)
pepo(2)
pepo(3)
#undef pepo
#undef index
template<typename T> // T is the Lattice Fermion type
LinOpSysSolverQOPMG<T>::
LinOpSysSolverQOPMG(Handle< LinearOperator<T> > A_,
Handle< FermState<T,Q,Q> > state_,
const SysSolverQOPMGParams& invParam_) :
A(A_), state(state_), invParam(invParam_)
{
if (invParam.Levels>0 && PC(g_param).levels>0) MGP(finalize)();
// Copy the parameters read from XML into the QDP global structure
for (int d=0; d<4; d++) PC(g_param).bc[d] = 1;
PC(g_param).aniso_xi = toReal(invParam.AnisoXi);
PC(g_param).aniso_nu = toReal(invParam.AnisoNu);
PC(g_param).kappa = toReal(invParam.Kappa);
PC(g_param).kappac = toReal(invParam.KappaCrit);
PC(g_param).mass = toReal(invParam.Mass);
PC(g_param).massc = toReal(invParam.MassCrit);
PC(g_param).clov_s = toReal(invParam.Clover);
PC(g_param).clov_t = toReal(invParam.CloverT);
PC(g_param).res = toReal(invParam.Residual);
PC(g_param).ngcr = invParam.NumGCRVecs;
PC(g_param).maxiter = invParam.MaxIter;
PC(g_param).verb = invParam.Verbose;
PC(g_param).levels = invParam.Levels;
for (int n=0; n<invParam.Levels; n++) {
for (int d=0; d<4; d++)
PC(g_param).block[n][d] = invParam.Blocking[n][d];
PC(g_param).nNullVecs[n] = invParam.NumNullVecs[n];
PC(g_param).nullMaxIter[n] = invParam.NullMaxIter[n];
PC(g_param).nullRes[n] = toReal(invParam.NullResidual[n]);
PC(g_param).nullConv[n] = toReal(invParam.NullConvergence[n]);
PC(g_param).nExtraVecs[n] = invParam.NumExtraVecs[n];
PC(g_param).urelax[n] = toReal(invParam.Underrelax[n]);
PC(g_param).npre[n] = invParam.NumPreHits[n];
PC(g_param).npost[n] = invParam.NumPostHits[n];
PC(g_param).cngcr[n] = invParam.CoarseNumGCRVecs[n];
PC(g_param).cmaxiter[n] = invParam.CoarseMaxIter[n];
PC(g_param).cres[n] = toReal(invParam.CoarseResidual[n]);
}
// The vector of functions will be used by QDP to assign the gauge links
// at each site of the QDP lattice
if (invParam.Levels>0) {
/* We're going to pull the gauge field out of Chroma's aether */
#if 0
u = TheNamedObjMap::Instance().getData< multi1d<LatticeColorMatrix> >(invParam.GaugeID);
#else
u = state_->getLinks();
#endif
// Compute the plaquette for comparison with MG code
{
Double w_plaq, s_plaq, t_plaq, link;
MesPlq(u, w_plaq, s_plaq, t_plaq, link);
QDPIO::cout << "Plaquette from State: " << endl;
QDPIO::cout << " w_plaq = " << w_plaq << endl;
QDPIO::cout << " s_plaq = " << s_plaq << endl;
QDPIO::cout << " t_plaq = " << t_plaq << endl;
QDPIO::cout << " link trace = " << link << endl;
}
int machsize[4], latsize[4];
for (int d=0;d<4;d++) machsize[d] = Layout::logicalSize()[d];
for (int d=0;d<4;d++) latsize[d] = Layout::lattSize()[d];
void (*peekpoke[4])(QLA(ColorMatrix) *dest, int coords[]) =
{peekpoke0,peekpoke1,peekpoke2,peekpoke3};
MGP(initialize)(machsize, latsize, peekpoke);
//MGP(teststuff)();
}
}
template<typename T> // T is the Lattice Fermion type
LinOpSysSolverQOPMG<T>::
~LinOpSysSolverQOPMG()
{
if (invParam.Levels<0) MGP(finalize)();
}
void *fermionsrc, *fermionsol;
template<typename T>
void peekpokesrc(QLA(DiracFermion) *dest, int coords[])
{
multi1d<int> x(4); for (int i=0; i<4; i++) x[i] = coords[i];
Fermion src; src.elem() = ((T*)fermionsrc)->elem(Layout::linearSiteIndex(x));
/*START_CODE();
double bsq = norm2(*(T*)fermionsrc).elem().elem().elem().elem();
printf("Chroma: in norm2 = %g\n",bsq);
END_CODE();*/
//printf("Chroma: x = %i %i %i %i:\n",x[0],x[1],x[2],x[3]);
QLA(Complex) z;
QLA(Real) real, imag;
for (int s=0; s<4; s++)
for (int c=0; c<3; c++) {
real = src.elem().elem(s).elem(c).real();
imag = src.elem().elem(s).elem(c).imag();
//printf("Chroma: s=%i,c=%i == %g + I %g\n",s,c,real,imag);
QLA(C_eq_R_plus_i_R)(&z, &real, &imag);
QLA(elem_D)(*dest,c,s) = z;
}
}
template<typename T>
void peekpokesol(QLA(DiracFermion) *src, int coords[])
{
multi1d<int> x(4); for (int i=0; i<4; i++) x[i] = coords[i];
ColorVector ctmp;
Fermion ftmp;
/*START_CODE();
double bsq = norm2(*(T*)fermionsrc).elem().elem().elem().elem();
printf("Chroma: in norm2 = %g\n",bsq);
END_CODE();*/
//printf("Chroma: x = %i %i %i %i:\n",x[0],x[1],x[2],x[3]);
QLA(Complex) z;
QLA(Real) real, imag;
for (int s=0; s<4; s++) {
for (int c=0; c<3; c++) {
z = QLA_elem_D(*src,c,s);
QLA(R_eq_re_C)(&real, &z);
QLA(R_eq_im_C)(&imag, &z);
Complex ztmp = cmplx(Real(real), Real(imag));
pokeColor(ctmp, ztmp, c);
}
pokeSpin(ftmp, ctmp, s);
}
pokeSite(*((T*)fermionsol), ftmp, x);
}
//! Solve the linear system
/*!
* \param psi solution ( Modify )
* \param chi source ( Read )
* \return syssolver results
*/
template<typename T> // T is the Lattice Fermion type
SystemSolverResults_t
LinOpSysSolverQOPMG<T>::operator() (T& psi, const T& chi) const
{
START_CODE();
SystemSolverResults_t res;
StopWatch swatch;
swatch.reset();
swatch.start();
// Set global pointers to our source and solution fermion fields
fermionsrc = (void*)χ
fermionsol = (void*)ψ
double bsq = norm2(chi,all).elem().elem().elem().elem();
QDPIO::cout << "Chroma: chi all norm2 = " << bsq << endl;
res.n_count = MGP(solve)(peekpokesrc<T>, peekpokesol<T>);
bsq = norm2(psi,all).elem().elem().elem().elem();
QDPIO::cout << "Chroma: psi all norm2 = " << bsq << endl;
swatch.stop();
double time = swatch.getTimeInSeconds();
{
T r;
r[A->subset()] = chi;
T tmp;
(*A)(tmp, psi, PLUS);
r[A->subset()] -= tmp;
res.resid = sqrt(norm2(r, A->subset()));
}
QDPIO::cout << "QOPMG_SOLVER: " << res.n_count << " iterations."
<< " Rsd = " << res.resid
<< " Relative Rsd = " << res.resid/sqrt(norm2(chi,A->subset()))
<< endl;
QDPIO::cout << "QOPMG_SOLVER_TIME: " << time << " secs" << endl;
END_CODE();
return res;
}
//! QDP multigrid system solver namespace
namespace LinOpSysSolverQOPMGEnv
{
//! Anonymous namespace
namespace
{
//! Name to be used
const std::string name("QOP_CLOVER_MULTIGRID_INVERTER");
//! Local registration flag
bool registered = false;
}
//! Callback function for standard precision
LinOpSystemSolver<LatticeFermion>*
createFerm( XMLReader& xml_in,
const std::string& path,
Handle< FermState< LatticeFermion,
multi1d<LatticeColorMatrix>,
multi1d<LatticeColorMatrix> > > state,
Handle< LinearOperator<LatticeFermion> > A)
{
return new LinOpSysSolverQOPMG<LatticeFermion>
(A, state, SysSolverQOPMGParams(xml_in, path));
}
/*//! Callback function for single precision
LinOpSystemSolver<LatticeFermionF>*
createFermF( XMLReader& xml_in,
const std::string& path,
Handle< FermState< LatticeFermionF,
multi1d<LatticeColorMatrixF>,
multi1d<LatticeColorMatrixF> > > state,
Handle< LinearOperator<LatticeFermionF> > A)
{
return new LinOpSysSolverQOPMG<LatticeFermionF>
(A, SysSolverQOPMGParams(xml_in, path));
}*/
//! Register all the factories
bool registerAll()
{
bool success = true;
if (! registered)
{
success &= Chroma::TheLinOpFermSystemSolverFactory::Instance().registerObject(name, createFerm);
//success &= Chroma::TheLinOpFFermSystemSolverFactory::Instance().registerObject(name, createFermF);
registered = true;
}
return success;
}
}
}
|
56ea42d69ce54872fc972dfebd26957ec502454e | 3f5179150584730cc0ee2ddc8f232b5e372d84aa | /Source/ProjectR/Private/Jet/MotorDriveComponent.cpp | 0ccbc43ba653050ae57b15809fd0242afafd3b07 | [] | no_license | poettlr/ProjectR | 4e8963c006bc0e5a2f7ffe72b89e5f65355d5dde | 1b92b4c034c36f0cbb0ef8c2e02972dd86a3e1e1 | refs/heads/master | 2023-06-16T02:37:39.782708 | 2021-06-29T00:07:41 | 2021-06-29T00:07:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,999 | cpp | MotorDriveComponent.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Jet/MotorDriveComponent.h"
#include "Jet/Jet.h"
// Sets default values for this component's properties
UMotorDriveComponent::UMotorDriveComponent()
{
PrimaryComponentTick.bCanEverTick = false;
jet = Cast<AJet, AActor>(GetOwner());
accelerationValue = 5000.0f;
brakeAbsoluteValue = 5000.0f;
topSpeed = 1000.0f;
}
// Called when the game starts
void UMotorDriveComponent::BeginPlay()
{
Super::BeginPlay();
jetPhysicsComponent = Cast<UPrimitiveComponent, UActorComponent>(jet->GetComponentByClass(UPrimitiveComponent::StaticClass()));
}
float UMotorDriveComponent::currentSpeed()
{
return jet->forwardVelocity().Size();//speed is calculated as the forward velocity, parallel to floor if any.
}
float UMotorDriveComponent::settedTopSpeed()
{
return topSpeed;
}
void UMotorDriveComponent::accelerate(float anAccelerationMultiplier)
{
if (anAccelerationMultiplier > 0 && currentSpeed() < topSpeed && !FMath::IsNearlyEqual(currentSpeed(), topSpeed, 1.0f))
{
FVector forceToApply = jet->ForwardProjectionOnFloor() * acceleration();
jetPhysicsComponent->AddForce(forceToApply * anAccelerationMultiplier, NAME_None, true);
}
}
float UMotorDriveComponent::acceleration()
{
return accelerationValue;
}
float UMotorDriveComponent::brakeValue()
{
return brakeAbsoluteValue;
}
void UMotorDriveComponent::brake(float aBrakeMultiplier)
{
if (aBrakeMultiplier > 0)
{
FVector forceToApply = jet->ForwardProjectionOnFloor() * (-brakeValue());//notice the '-' next to brakeValue. Brake value's sign is positive.
jetPhysicsComponent->AddForce(forceToApply * aBrakeMultiplier, NAME_None, true);
}
}
bool UMotorDriveComponent::goesForward()
{
FVector forwardDirection = jet->ForwardProjectionOnFloor();
return jet->forwardVelocity().GetSignVector().Equals(
forwardDirection.GetSignVector(), 0.1f);
}
bool UMotorDriveComponent::goesBackwards()
{
return !goesForward() && currentSpeed() > 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.