hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff2b230465ab648c9a9854158832d8bd9fac4b5c
| 6,908
|
cpp
|
C++
|
libraries/plugins/blockchain_history/account_history_api.cpp
|
scorum/scorum
|
1da00651f2fa14bcf8292da34e1cbee06250ae78
|
[
"MIT"
] | 53
|
2017-10-28T22:10:35.000Z
|
2022-02-18T02:20:48.000Z
|
libraries/plugins/blockchain_history/account_history_api.cpp
|
Scorum/Scorum
|
fb4aa0b0960119b97828865d7a5b4d0409af7876
|
[
"MIT"
] | 38
|
2017-11-25T09:06:51.000Z
|
2018-10-31T09:17:22.000Z
|
libraries/plugins/blockchain_history/account_history_api.cpp
|
Scorum/Scorum
|
fb4aa0b0960119b97828865d7a5b4d0409af7876
|
[
"MIT"
] | 27
|
2018-01-08T19:43:35.000Z
|
2022-01-14T10:50:42.000Z
|
#include <scorum/blockchain_history/account_history_api.hpp>
#include <scorum/blockchain_history/blockchain_history_plugin.hpp>
#include <scorum/blockchain_history/schema/history_object.hpp>
#include <scorum/app/api_context.hpp>
#include <scorum/app/application.hpp>
#include <scorum/blockchain_history/schema/operation_objects.hpp>
#include <scorum/common_api/config_api.hpp>
#include <scorum/protocol/operations.hpp>
#include <map>
namespace scorum {
namespace blockchain_history {
namespace detail {
class account_history_api_impl
{
public:
scorum::app::application& _app;
public:
account_history_api_impl(scorum::app::application& app)
: _app(app)
{
}
template <typename history_object_type, typename fill_result_functor>
void get_history(const std::string& account, uint64_t from, uint32_t limit, fill_result_functor& funct) const
{
const auto db = _app.chain_database();
FC_ASSERT(limit > 0, "Limit must be greater than zero");
FC_ASSERT(limit <= get_api_config(API_ACCOUNT_HISTORY).max_blockchain_history_depth,
"Limit of ${l} is greater than maxmimum allowed ${2}",
("l", limit)("2", get_api_config(API_ACCOUNT_HISTORY).max_blockchain_history_depth));
FC_ASSERT(from >= limit, "From must be greater than limit");
const auto& idx = db->get_index<account_history_index<history_object_type>, by_account>();
auto itr = idx.lower_bound(boost::make_tuple(account, from));
if (itr != idx.end())
{
auto end = idx.upper_bound(boost::make_tuple(account, int64_t(0)));
int64_t pos = int64_t(itr->sequence) - limit;
if (pos > 0)
{
end = idx.lower_bound(boost::make_tuple(account, pos));
}
while (itr != end)
{
funct(*itr);
++itr;
}
}
}
template <typename history_object_type>
std::map<uint32_t, applied_operation> get_history(const std::string& account, uint64_t from, uint32_t limit) const
{
std::map<uint32_t, applied_operation> result;
const auto db = _app.chain_database();
auto fill_funct = [&](const history_object_type& hobj) { result[hobj.sequence] = db->get(hobj.op); };
this->template get_history<history_object_type>(account, from, limit, fill_funct);
return result;
}
};
} // namespace detail
account_history_api::account_history_api(const scorum::app::api_context& ctx)
: _impl(new detail::account_history_api_impl(ctx.app))
{
}
account_history_api::~account_history_api()
{
}
void account_history_api::on_api_startup()
{
}
std::map<uint32_t, applied_operation>
account_history_api::get_account_scr_to_scr_transfers(const std::string& account, uint64_t from, uint32_t limit) const
{
const auto db = _impl->_app.chain_database();
return db->with_read_lock(
[&]() { return _impl->get_history<account_transfers_to_scr_history_object>(account, from, limit); });
}
std::map<uint32_t, applied_operation>
account_history_api::get_account_scr_to_sp_transfers(const std::string& account, uint64_t from, uint32_t limit) const
{
const auto db = _impl->_app.chain_database();
return db->with_read_lock(
[&]() { return _impl->get_history<account_transfers_to_sp_history_object>(account, from, limit); });
}
std::map<uint32_t, applied_operation>
account_history_api::get_account_history(const std::string& account, uint64_t from, uint32_t limit) const
{
const auto db = _impl->_app.chain_database();
return db->with_read_lock([&]() { return _impl->get_history<account_history_object>(account, from, limit); });
}
std::map<uint32_t, applied_withdraw_operation>
account_history_api::get_account_sp_to_scr_transfers(const std::string& account, uint64_t from, uint32_t limit) const
{
const auto db = _impl->_app.chain_database();
return db->with_read_lock([&]() {
std::map<uint32_t, applied_withdraw_operation> result;
auto fill_funct = [&](const account_withdrawals_to_scr_history_object& obj) {
auto it = result.emplace(obj.sequence, applied_withdraw_operation(db->get(obj.op))).first;
auto& applied_op = it->second;
share_type to_withdraw = 0;
applied_op.op.weak_visit(
[&](const withdraw_scorumpower_operation& op) { to_withdraw = op.scorumpower.amount; });
if (to_withdraw == 0u)
{
// If this is a zero-withdraw (such withdraw closes current active withdraw)
applied_op.status = applied_withdraw_operation::empty;
}
else if (!obj.progress.empty())
{
auto last_op = fc::raw::unpack<operation>(db->get(obj.progress.back()).serialized_op);
last_op.weak_visit(
[&](const acc_finished_vesting_withdraw_operation&) {
// if last 'progress' operation is 'acc_finished_' then withdraw was finished
applied_op.status = applied_withdraw_operation::finished;
},
[&](const withdraw_scorumpower_operation&) {
// if last 'progress' operation is 'withdraw_scorumpower_' then withdraw was either interrupted
// or finished depending on pre-last 'progress' operation
applied_op.status = applied_withdraw_operation::interrupted;
});
if (obj.progress.size() > 1)
{
auto before_last_op_obj = db->get(*(obj.progress.rbegin() + 1));
auto before_last_op = fc::raw::unpack<operation>(before_last_op_obj.serialized_op);
before_last_op.weak_visit([&](const acc_finished_vesting_withdraw_operation&) {
// if pre-last 'progress' operation is 'acc_finished_' then withdraw was finished
applied_op.status = applied_withdraw_operation::finished;
});
}
for (auto& id : obj.progress)
{
auto op = fc::raw::unpack<operation>(db->get(id).serialized_op);
op.weak_visit(
[&](const acc_to_acc_vesting_withdraw_operation& op) {
applied_op.withdrawn += op.withdrawn.amount;
},
[&](const acc_to_devpool_vesting_withdraw_operation& op) {
applied_op.withdrawn += op.withdrawn.amount;
});
}
}
};
_impl->get_history<account_withdrawals_to_scr_history_object>(account, from, limit, fill_funct);
return result;
});
}
} // namespace blockchain_history
} // namespace scorum
| 39.474286
| 119
| 0.633324
|
scorum
|
ff2beaf5448ece984586455a7d66ca52923bf014
| 876
|
cpp
|
C++
|
src/RocketEngine/component/TransformComponent.cpp
|
walthill/Rocket3D
|
45ba128699b354f21db04f4b114c81504c8e0771
|
[
"Apache-2.0"
] | null | null | null |
src/RocketEngine/component/TransformComponent.cpp
|
walthill/Rocket3D
|
45ba128699b354f21db04f4b114c81504c8e0771
|
[
"Apache-2.0"
] | 3
|
2019-12-07T01:28:17.000Z
|
2020-02-05T16:57:33.000Z
|
src/RocketEngine/component/TransformComponent.cpp
|
walthill/Rocket3D
|
45ba128699b354f21db04f4b114c81504c8e0771
|
[
"Apache-2.0"
] | null | null | null |
#include "TransformComponent.h"
TransformComponent::TransformComponent(const ComponentId & id) :
Component(id)
{
}
TransformComponent::~TransformComponent()
{
}
void TransformComponent::setPosition(rkm::Vector3 pos)
{
mTransformData.position = pos;
mDataChanged = true;
}
void TransformComponent::setData(const TransformData & data)
{
mTransformData.position = data.position;
mTransformData.rotation.angle = data.rotation.angle;
mTransformData.rotation.rotationAxis = data.rotation.rotationAxis;
mTransformData.scale = data.scale;
mDataChanged = true;
}
void TransformComponent::setScale(rkm::Vector3 scale)
{
mTransformData.scale = scale;
mDataChanged = true;
}
void TransformComponent::setRotation(rkm::Vector3 rotationAxis, float angle)
{
mTransformData.rotation.angle = angle;
mTransformData.rotation.rotationAxis = rotationAxis;
mDataChanged = true;
}
| 22.461538
| 76
| 0.78653
|
walthill
|
ff321bb1d9038f5ec7a212fb06087a5dcd36877a
| 106
|
hpp
|
C++
|
testCMake/src/testComp.hpp
|
demotomohiro/testCMakePackage
|
171fb4c97b752eaaecec5660cb63289eb01919e9
|
[
"MIT"
] | null | null | null |
testCMake/src/testComp.hpp
|
demotomohiro/testCMakePackage
|
171fb4c97b752eaaecec5660cb63289eb01919e9
|
[
"MIT"
] | null | null | null |
testCMake/src/testComp.hpp
|
demotomohiro/testCMakePackage
|
171fb4c97b752eaaecec5660cb63289eb01919e9
|
[
"MIT"
] | null | null | null |
#pragma once
#include "testcomp_export.h"
class TESTCOMP_EXPORT testComp {
public:
void print();
};
| 11.777778
| 32
| 0.716981
|
demotomohiro
|
ff3e881f63e2cc149bfccdc1e99e2eb6df9736b8
| 719
|
cpp
|
C++
|
state/state/Source1.cpp
|
katookei/cs202-18apcs3-group5
|
2ea17d891c67b740cc6f612e4f7738ec2c5c5f14
|
[
"MIT"
] | null | null | null |
state/state/Source1.cpp
|
katookei/cs202-18apcs3-group5
|
2ea17d891c67b740cc6f612e4f7738ec2c5c5f14
|
[
"MIT"
] | null | null | null |
state/state/Source1.cpp
|
katookei/cs202-18apcs3-group5
|
2ea17d891c67b740cc6f612e4f7738ec2c5c5f14
|
[
"MIT"
] | null | null | null |
#include "Header.h"
#include <string>
baseState* Morning::getnext()
{
return new Evening;
}
string Morning::getName()
{
return "morning";
}
string Evening::getName()
{
return "evening";
}
string Night::getName()
{
return "night";
}
baseState* Evening::getnext()
{
return new Night;
}
baseState* Night::getnext()
{
return new Morning;
}
void Sun::statechange()
{
if (pState)
{
baseState* State = pState->getnext();
delete State;
pState = State;
}
}
Sun::Sun()
{
pState = new Morning;
}
Sun::~Sun()
{
delete[] pState;
}
Sun::Sun(baseState* pContext)
{
pState = pContext;
}
void Sun::getNameState(baseState* a)
{
cout << a->getName();
}
| 12.186441
| 40
| 0.595271
|
katookei
|
ff42273a8490925f5ceee78c80f17ab26cc1d323
| 4,470
|
cc
|
C++
|
examples/coin.cc
|
joshbosley/lib_netsockets
|
931fb54993c5873cf2e621ee230b57c2345b667b
|
[
"Apache-2.0"
] | 1
|
2021-02-16T10:05:24.000Z
|
2021-02-16T10:05:24.000Z
|
examples/coin.cc
|
joshbosley/lib_netsockets
|
931fb54993c5873cf2e621ee230b57c2345b667b
|
[
"Apache-2.0"
] | null | null | null |
examples/coin.cc
|
joshbosley/lib_netsockets
|
931fb54993c5873cf2e621ee230b57c2345b667b
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include "coin.hh"
/////////////////////////////////////////////////////////////////////////////////////////////////////
//currency_t::currency_t
/////////////////////////////////////////////////////////////////////////////////////////////////////
currency_t::currency_t()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//currency_t::get_currencies_list
/////////////////////////////////////////////////////////////////////////////////////////////////////
int currency_t::get_currencies_list(const char* fname)
{
char *buf = 0;
size_t length;
FILE *f;
f = fopen(fname, "rb");
if (!f)
{
std::cout << "cannot open " << fname << std::endl;
return -1;
}
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
buf = (char*)malloc(length);
if (buf)
{
fread(buf, 1, length, f);
}
fclose(f);
char *endptr;
JsonValue value;
JsonAllocator allocator;
int status = jsonParse(buf, &endptr, &value, allocator);
if (status != JSON_OK)
{
std::cout << "invalid JSON format for " << fname << std::endl;
return -1;
}
JsonNode *root_obj = value.toNode();
//format is "coins" JSON object with an array of objects
assert(std::string(root_obj->key).compare("coins") == 0);
assert(root_obj->value.getTag() == JSON_ARRAY);
JsonNode *arr = root_obj->value.toNode();
size_t nbr_curr = 0;
for (JsonNode *node = arr; node != nullptr; node = node->next)
{
assert(node->value.getTag() == JSON_OBJECT);
parse_coin(node->value);
nbr_curr++;
}
assert(nbr_curr == m_coin_list.size());
std::cout << "parsed " << nbr_curr << " currencies..." << std::endl;
free(buf);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//currency_t::parse_coin
//object with {"id":2024,"name":"007Coin","code":"007"}
/////////////////////////////////////////////////////////////////////////////////////////////////////
int currency_t::parse_coin(JsonValue value)
{
assert(value.getTag() == JSON_OBJECT);
coin_list_t coin;
for (JsonNode *node = value.toNode(); node != nullptr; node = node->next)
{
if (std::string(node->key).compare("id") == 0)
{
assert(node->value.getTag() == JSON_NUMBER);
coin.id = (int)node->value.toNumber();
}
else if (std::string(node->key).compare("name") == 0)
{
assert(node->value.getTag() == JSON_STRING);
coin.name = node->value.toString();
}
else if (std::string(node->key).compare("code") == 0)
{
assert(node->value.getTag() == JSON_STRING);
coin.code = node->value.toString();
}
}
m_coin_list.push_back(coin);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//currency_t::get_coin_id
/////////////////////////////////////////////////////////////////////////////////////////////////////
std::string currency_t::get_coin_id(std::string code)
{
std::string str;
size_t size = m_coin_list.size();
for (size_t idx = 0; idx < size; idx++)
{
if (std::string(code).compare(m_coin_list.at(idx).code) == 0)
{
return std::to_string(m_coin_list.at(idx).id);
}
}
return str;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//currency_t::get_history
/////////////////////////////////////////////////////////////////////////////////////////////////////
int currency_t::get_history(char* buf)
{
char *endptr;
JsonValue value;
JsonAllocator allocator;
int status = jsonParse(buf, &endptr, &value, allocator);
if (status != JSON_OK)
{
std::cout << "invalid JSON format" << std::endl;
return -1;
}
JsonNode *root = value.toNode();
std::string code = root->value.toNode()->next->next->value.toString();
coin_history_t history(code);
JsonNode *arr = root->next->next->next->value.toNode();
size_t nbr_hist = 0;
for (JsonNode *node = arr; node != nullptr; node = node->next)
{
assert(node->value.getTag() == JSON_OBJECT);
std::string date = node->value.toNode()->value.toString();
std::string price = node->value.toNode()->next->value.toString();
history.m_history.push_back(date_price_t(date, price));
nbr_hist++;
}
m_coin_history.push_back(history);
return 0;
}
| 28.471338
| 101
| 0.485235
|
joshbosley
|
ff436588cbe0f27fde9e6c99d66505ed48581ecb
| 3,530
|
cpp
|
C++
|
ogsr_engine/Layers/xrRenderPC_R1/Blender_Vertex_aref.cpp
|
stepa2/OGSR-Engine
|
32a23aa30506684be1267d9c4fc272350cd167c5
|
[
"Apache-2.0"
] | 247
|
2018-11-02T18:50:55.000Z
|
2022-03-15T09:11:43.000Z
|
ogsr_engine/Layers/xrRenderPC_R1/Blender_Vertex_aref.cpp
|
stepa2/OGSR-Engine
|
32a23aa30506684be1267d9c4fc272350cd167c5
|
[
"Apache-2.0"
] | 193
|
2018-11-02T20:12:44.000Z
|
2022-03-07T13:35:17.000Z
|
ogsr_engine/Layers/xrRenderPC_R1/Blender_Vertex_aref.cpp
|
stepa2/OGSR-Engine
|
32a23aa30506684be1267d9c4fc272350cd167c5
|
[
"Apache-2.0"
] | 106
|
2018-10-26T11:33:01.000Z
|
2022-03-19T12:34:20.000Z
|
// Blender_Vertex_aref.cpp: implementation of the CBlender_Vertex_aref class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#pragma hdrstop
#include "Blender_Vertex_aref.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CBlender_Vertex_aref::CBlender_Vertex_aref()
{
description.CLS = B_VERT_AREF;
description.version = 1;
oAREF.value = 32;
oAREF.min = 0;
oAREF.max = 255;
oBlend.value = FALSE;
}
CBlender_Vertex_aref::~CBlender_Vertex_aref()
{
}
void CBlender_Vertex_aref::Save( IWriter& fs )
{
IBlender::Save (fs);
xrPWRITE_PROP (fs,"Alpha ref", xrPID_INTEGER, oAREF);
xrPWRITE_PROP (fs,"Alpha-blend", xrPID_BOOL, oBlend);
}
void CBlender_Vertex_aref::Load( IReader& fs, u16 version )
{
IBlender::Load (fs,version);
switch (version)
{
case 0:
xrPREAD_PROP (fs,xrPID_INTEGER, oAREF);
oBlend.value = FALSE;
break;
case 1:
default:
xrPREAD_PROP (fs,xrPID_INTEGER, oAREF);
xrPREAD_PROP (fs,xrPID_BOOL, oBlend);
break;
}
}
void CBlender_Vertex_aref::Compile(CBlender_Compile& C)
{
IBlender::Compile (C);
if (C.bEditor)
{
C.PassBegin ();
{
C.PassSET_ZB (TRUE,TRUE);
if (oBlend.value) C.PassSET_Blend (TRUE, D3DBLEND_SRCALPHA,D3DBLEND_INVSRCALPHA, TRUE,oAREF.value);
else C.PassSET_Blend (TRUE, D3DBLEND_ONE, D3DBLEND_ZERO, TRUE,oAREF.value);
C.PassSET_LightFog (TRUE,TRUE);
// Stage1 - Base texture
C.StageBegin ();
C.StageSET_Color (D3DTA_TEXTURE, D3DTOP_MODULATE, D3DTA_DIFFUSE);
C.StageSET_Alpha (D3DTA_TEXTURE, D3DTOP_MODULATE, D3DTA_DIFFUSE);
C.Stage_Texture (oT_Name);
C.Stage_Matrix (oT_xform, 0);
C.Stage_Constant ("$null");
C.StageEnd ();
}
C.PassEnd ();
} else {
switch (C.iElement)
{
case SE_R1_NORMAL_HQ:
// Level view
{
LPCSTR sname = "vert";
if (C.bDetail_Diffuse) sname = "vert_dt";
if (oBlend.value) C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA, TRUE,oAREF.value);
else C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_ONE, D3DBLEND_ZERO, TRUE,oAREF.value);
C.r_Sampler ("s_base", C.L_textures[0]);
C.r_Sampler ("s_detail",C.detail_texture);
C.r_End ();
}
break;
case SE_R1_NORMAL_LQ:
// Level view
{
LPCSTR sname = "vert";
if (oBlend.value) C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA, TRUE,oAREF.value);
else C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_ONE, D3DBLEND_ZERO, TRUE,oAREF.value);
C.r_Sampler ("s_base", C.L_textures[0]);
C.r_End ();
}
break;
case SE_R1_LPOINT:
C.r_Pass ("vert_point","add_point",FALSE,TRUE,FALSE,TRUE,D3DBLEND_ONE,D3DBLEND_ONE,TRUE,oAREF.value);
C.r_Sampler ("s_base", C.L_textures[0]);
C.r_Sampler_clf ("s_lmap", TEX_POINT_ATT );
C.r_Sampler_clf ("s_att", TEX_POINT_ATT );
C.r_End ();
break;
case SE_R1_LSPOT:
C.r_Pass ("vert_spot","add_spot",FALSE,TRUE,FALSE,TRUE,D3DBLEND_ONE,D3DBLEND_ONE,TRUE,oAREF.value);
C.r_Sampler ("s_base", C.L_textures[0]);
C.r_Sampler_clf ("s_lmap", "internal\\internal_light_att", true);
C.r_Sampler_clf ("s_att", TEX_SPOT_ATT );
C.r_End ();
break;
case SE_R1_LMODELS:
// Lighting only
C.r_Pass ("vert_l","vert_l",FALSE);
C.r_Sampler ("s_base",C.L_textures[0]);
C.r_End ();
break;
}
}
}
| 28.24
| 123
| 0.639377
|
stepa2
|
ff43980396f6f059c1657875a6da097910af0caf
| 4,880
|
hpp
|
C++
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/directory.hpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 1,414
|
2015-06-28T09:57:51.000Z
|
2021-10-14T03:51:10.000Z
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/directory.hpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 2,369
|
2015-06-25T01:45:44.000Z
|
2021-10-16T08:44:18.000Z
|
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/directory.hpp
|
redscientistlabs/Bizhawk50X-Vanguard
|
96e0f5f87671a1230784c8faf935fe70baadfe48
|
[
"MIT"
] | 430
|
2015-06-29T04:28:58.000Z
|
2021-10-05T18:24:17.000Z
|
#ifndef NALL_DIRECTORY_HPP
#define NALL_DIRECTORY_HPP
#include <nall/intrinsics.hpp>
#include <nall/sort.hpp>
#include <nall/string.hpp>
#include <nall/vector.hpp>
#if defined(PLATFORM_WINDOWS)
#include <nall/windows/utf8.hpp>
#else
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#endif
namespace nall {
struct directory {
static bool exists(const string &pathname);
static lstring folders(const string &pathname, const string &pattern = "*");
static lstring files(const string &pathname, const string &pattern = "*");
static lstring contents(const string &pathname, const string &pattern = "*");
};
#if defined(PLATFORM_WINDOWS)
inline bool directory::exists(const string &pathname) {
DWORD result = GetFileAttributes(utf16_t(pathname));
if(result == INVALID_FILE_ATTRIBUTES) return false;
return (result & FILE_ATTRIBUTE_DIRECTORY);
}
inline lstring directory::folders(const string &pathname, const string &pattern) {
lstring list;
string path = pathname;
path.transform("/", "\\");
if(!strend(path, "\\")) path.append("\\");
path.append("*");
HANDLE handle;
WIN32_FIND_DATA data;
handle = FindFirstFile(utf16_t(path), &data);
if(handle != INVALID_HANDLE_VALUE) {
if(wcscmp(data.cFileName, L".") && wcscmp(data.cFileName, L"..")) {
if(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
string name = (const char*)utf8_t(data.cFileName);
if(wildcard(name, pattern)) list.append(name);
}
}
while(FindNextFile(handle, &data) != false) {
if(wcscmp(data.cFileName, L".") && wcscmp(data.cFileName, L"..")) {
if(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
string name = (const char*)utf8_t(data.cFileName);
if(wildcard(name, pattern)) list.append(name);
}
}
}
FindClose(handle);
}
if(list.size() > 0) list.sort();
for(auto &name : list) name.append("/"); //must append after sorting
return list;
}
inline lstring directory::files(const string &pathname, const string &pattern) {
lstring list;
string path = pathname;
path.transform("/", "\\");
if(!strend(path, "\\")) path.append("\\");
path.append("*");
HANDLE handle;
WIN32_FIND_DATA data;
handle = FindFirstFile(utf16_t(path), &data);
if(handle != INVALID_HANDLE_VALUE) {
if((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
string name = (const char*)utf8_t(data.cFileName);
if(wildcard(name, pattern)) list.append(name);
}
while(FindNextFile(handle, &data) != false) {
if((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
string name = (const char*)utf8_t(data.cFileName);
if(wildcard(name, pattern)) list.append(name);
}
}
FindClose(handle);
}
if(list.size() > 0) list.sort();
return list;
}
inline lstring directory::contents(const string &pathname, const string &pattern) {
lstring folders = directory::folders(pathname); //pattern search of contents() should only filter files
lstring files = directory::files(pathname, pattern);
for(auto &file : files) folders.append(file);
return folders;
}
#else
inline bool directory::exists(const string &pathname) {
DIR *dp = opendir(pathname);
if(!dp) return false;
closedir(dp);
return true;
}
inline lstring directory::folders(const string &pathname, const string &pattern) {
lstring list;
DIR *dp;
struct dirent *ep;
dp = opendir(pathname);
if(dp) {
while(ep = readdir(dp)) {
if(!strcmp(ep->d_name, ".")) continue;
if(!strcmp(ep->d_name, "..")) continue;
if(ep->d_type & DT_DIR) {
if(wildcard(ep->d_name, pattern)) list.append(ep->d_name);
}
}
closedir(dp);
}
if(list.size() > 0) list.sort();
for(auto &name : list) name.append("/"); //must append after sorting
return list;
}
inline lstring directory::files(const string &pathname, const string &pattern) {
lstring list;
DIR *dp;
struct dirent *ep;
dp = opendir(pathname);
if(dp) {
while(ep = readdir(dp)) {
if(!strcmp(ep->d_name, ".")) continue;
if(!strcmp(ep->d_name, "..")) continue;
if((ep->d_type & DT_DIR) == 0) {
if(wildcard(ep->d_name, pattern)) list.append(ep->d_name);
}
}
closedir(dp);
}
if(list.size() > 0) list.sort();
return list;
}
inline lstring directory::contents(const string &pathname, const string &pattern) {
lstring folders = directory::folders(pathname); //pattern search of contents() should only filter files
lstring files = directory::files(pathname, pattern);
for(auto &file : files) folders.append(file);
return folders;
}
#endif
}
#endif
| 31.688312
| 108
| 0.628893
|
redscientistlabs
|
ff45138950bb3bf10ac006e14d17faee17de66a0
| 533
|
cpp
|
C++
|
Sources/Overload/OvCore/src/OvCore/Scripting/LuaBinder.cpp
|
kmqwerty/Overload
|
f3b8c751a05815400ed35dd2be20a3900f3454fd
|
[
"MIT"
] | 755
|
2019-07-10T01:26:39.000Z
|
2022-03-31T12:43:19.000Z
|
Sources/Overload/OvCore/src/OvCore/Scripting/LuaBinder.cpp
|
kmqwerty/Overload
|
f3b8c751a05815400ed35dd2be20a3900f3454fd
|
[
"MIT"
] | 111
|
2020-02-28T23:30:10.000Z
|
2022-01-18T13:57:30.000Z
|
Sources/Overload/OvCore/src/OvCore/Scripting/LuaBinder.cpp
|
kmqwerty/Overload
|
f3b8c751a05815400ed35dd2be20a3900f3454fd
|
[
"MIT"
] | 97
|
2019-11-06T15:19:56.000Z
|
2022-03-25T08:40:04.000Z
|
/**
* @project: Overload
* @author: Overload Tech.
* @licence: MIT
*/
#include "OvCore/Scripting/LuaBinder.h"
#include "OvCore/Scripting/LuaMathsBinder.h"
#include "OvCore/Scripting/LuaActorBinder.h"
#include "OvCore/Scripting/LuaComponentBinder.h"
#include "OvCore/Scripting/LuaGlobalsBinder.h"
void OvCore::Scripting::LuaBinder::CallBinders(sol::state& p_luaState)
{
auto& L = p_luaState;
LuaMathsBinder::BindMaths(L);
LuaActorBinder::BindActor(L);
LuaComponentBinder::BindComponent(L);
LuaGlobalsBinder::BindGlobals(L);
}
| 24.227273
| 70
| 0.767355
|
kmqwerty
|
ff49c19e404fbc5d75388a4ef788048adb4623a6
| 4,688
|
cpp
|
C++
|
main.cpp
|
kambala-decapitator/MpqSimpleIO
|
922ab66d923d6abf654dd8c3e178dc263a1cb215
|
[
"MIT"
] | 1
|
2018-11-21T10:16:02.000Z
|
2018-11-21T10:16:02.000Z
|
main.cpp
|
kambala-decapitator/MpqSimpleIO
|
922ab66d923d6abf654dd8c3e178dc263a1cb215
|
[
"MIT"
] | null | null | null |
main.cpp
|
kambala-decapitator/MpqSimpleIO
|
922ab66d923d6abf654dd8c3e178dc263a1cb215
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <cstring>
#include <StormLib/StormLib.h>
using std::cerr;
using std::endl;
using std::string;
int main(int argc, const char *argv[])
{
if (argc < 3)
{
cerr << "min 2 params" << endl;
return 1;
}
auto mode = argv[1];
auto isListMode = !strcmp(mode, "-l") || !strcmp(mode, "--list");
DWORD mpqFlag;
if (isListMode || !strcmp(mode, "-r") || !strcmp(mode, "--read"))
mpqFlag = STREAM_FLAG_READ_ONLY;
else if (!strcmp(mode, "-w") || !strcmp(mode, "--write"))
mpqFlag = STREAM_FLAG_WRITE_SHARE;
else
{
cerr << "unknown mode: " << mode << endl;
return 2;
}
if (!isListMode && argc < 5)
{
cerr << "not enough params for non-list mode" << endl;
return 3;
}
HANDLE mpqHandle = nullptr;
if (!SFileOpenArchive(argv[2], 0, BASE_PROVIDER_FILE | STREAM_PROVIDER_FLAT | mpqFlag, &mpqHandle))
{
cerr << "failed to open MPQ, error: " << GetLastError() << endl;
return 4;
}
auto closeMpq = [&mpqHandle]{ SFileCloseArchive(mpqHandle); };
if (mpqFlag == STREAM_FLAG_READ_ONLY)
{
// for list mode path mask is required
const auto extraListFileArgIndex = isListMode ? 4 : 5;
if (extraListFileArgIndex < argc)
SFileAddListFile(mpqHandle, argv[extraListFileArgIndex]);
auto mpqInternalPathMask = (!isListMode || argc > 3) ? argv[3] : "*";
SFILE_FIND_DATA findData;
if (auto findHandle = SFileFindFirstFile(mpqHandle, mpqInternalPathMask, &findData, nullptr))
{
string extractPath;
if (!isListMode)
{
extractPath = string{argv[4]};
if (extractPath.back() != '/')
#ifdef PLATFORM_WINDOWS
if (extractPath.back() != '\\')
#endif
extractPath += '/';
}
bool nextFileFound;
do
{
auto fileInternalPath = findData.cFileName;
if (isListMode)
std::cout << findData.dwFileSize << " " << fileInternalPath << endl;
else
{
auto fileExtractPath = extractPath + findData.szPlainName;
if (!SFileExtractFile(mpqHandle, fileInternalPath, fileExtractPath.c_str(), SFILE_OPEN_FROM_MPQ))
cerr << "failed to extract file '" << fileInternalPath << "', error: " << GetLastError() << endl;
}
nextFileFound = SFileFindNextFile(findHandle, &findData);
} while (nextFileFound);
SFileFindClose(findHandle);
}
else
{
auto err = GetLastError();
cerr << "no files found with mask '" << mpqInternalPathMask << "'";
if (err != ERROR_NO_MORE_FILES)
cerr << ", error: " << err;
cerr << endl;
}
}
else
{
string thirdParam{argv[3]}, prefixParam{"--prefix="}, internalPathPrefix;
int filesStartIndex;
bool isSinglePrefix;
if ((isSinglePrefix = thirdParam.find(prefixParam) == 0))
{
internalPathPrefix = thirdParam.substr(prefixParam.length());
filesStartIndex = 4;
}
else
{
filesStartIndex = 3;
if ((argc - filesStartIndex) % 2)
{
cerr << "each input file must be balanced with an output one" << endl;
closeMpq();
return 5;
}
}
for (int i = filesStartIndex; i < argc; ++i)
{
string filePath{argv[i]}, internalPath;
if (isSinglePrefix)
{
string fileName;
auto lastSlashIndex = filePath.rfind('/');
#ifdef PLATFORM_WINDOWS
if (lastSlashIndex == string::npos)
lastSlashIndex = filePath.rfind('\\');
#endif
internalPath = internalPathPrefix + filePath.substr(lastSlashIndex != string::npos ? lastSlashIndex + 1 : 0);
}
else
internalPath = argv[++i];
auto s = "'" + filePath + "' => '" + internalPath + "'";
if (SFileAddFileEx(mpqHandle, filePath.c_str(), internalPath.c_str(), MPQ_FILE_COMPRESS | MPQ_FILE_REPLACEEXISTING, MPQ_COMPRESSION_PKWARE, MPQ_COMPRESSION_NEXT_SAME))
std::cout << s << endl;
else
cerr << s << " error: " << GetLastError() << endl;
}
SFileCompactArchive(mpqHandle, nullptr, false);
}
closeMpq();
return 0;
}
| 33.014085
| 179
| 0.527944
|
kambala-decapitator
|
ff500333886de0d1b87de76fd1659a0a1ab75b8b
| 1,218
|
cpp
|
C++
|
OptionPricer01/OptionPricer01/Option01.cpp
|
b01703020/Financial_Computing
|
d98d4f6e784997129ece15cdaf33c506e0f35c9e
|
[
"MIT"
] | null | null | null |
OptionPricer01/OptionPricer01/Option01.cpp
|
b01703020/Financial_Computing
|
d98d4f6e784997129ece15cdaf33c506e0f35c9e
|
[
"MIT"
] | null | null | null |
OptionPricer01/OptionPricer01/Option01.cpp
|
b01703020/Financial_Computing
|
d98d4f6e784997129ece15cdaf33c506e0f35c9e
|
[
"MIT"
] | null | null | null |
//
// Option01.cpp
// OptionPricer01
//
// Created by wu yen sun on 2022/2/11.
//
#include "Option01.h"
#include "BinomialTreeModel.h"
#include <iostream>
#include <cmath>
using namespace std;
namespace fre
{
double PriceByCRR(double S0, double U, double D, double R, int N, double K)
{
double q = RiskNeutProb(U, D, R);
// If you are using MAC XCode
double Price[N+1];
// If you use Microsoft Visual Studio 2019
// double Price[9];
for (int i = 0; i < sizeof(Price)/sizeof(Price[0]); i++)
{
Price[i] = 0.0;
}
for (int i =0; i<=N; i++)
{
Price[i] = CallPayoff(CalculateAssetPrice(S0, U, D, N, i), K);
}
for (int n = N - 1; n >= 0; n--)
{
for (int i = 0; i <= n; i++)
{
Price[i] = (q * Price[i + 1] + (1 - q) * Price[i]) / R;
}
}
return Price[0];
}
double CallPayoff(double z, double K)
{
if (z > K) return z - K;
return 0.0;
}
double fact(int k)
{
if ( k==0 || k==1 ) return 1;
return fact(k-1)*k;
}
}
| 21
| 79
| 0.449097
|
b01703020
|
ff52b8ed5b5cc14d74b0833aa29d1ba74fd14811
| 157
|
cpp
|
C++
|
Level 1/Calculs et decouverte des variables/Kermesse/main.cpp
|
Wurlosh/France-ioi
|
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
|
[
"MIT"
] | 31
|
2018-10-30T09:54:23.000Z
|
2022-03-02T21:45:51.000Z
|
Level 1/Calculs et decouverte des variables/Kermesse/main.cpp
|
Wurlosh/France-ioi
|
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
|
[
"MIT"
] | 2
|
2016-12-24T23:39:20.000Z
|
2017-07-02T22:51:28.000Z
|
Level 1/Calculs et decouverte des variables/Kermesse/main.cpp
|
Wurlosh/France-ioi
|
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
|
[
"MIT"
] | 30
|
2018-10-25T12:28:36.000Z
|
2022-01-31T14:31:02.000Z
|
#include <iostream>
using namespace std;
int main()
{
int sum=0;
for(int i=1;i<=50;++i)
{
sum+=i;
cout<<sum<<endl;
}
return 0;
}
| 11.214286
| 25
| 0.509554
|
Wurlosh
|
ff54160d545f8d65ef7661dacd855f07d56bd12e
| 402
|
cpp
|
C++
|
AtCoder/colopl2018-qual/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
AtCoder/colopl2018-qual/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | 1
|
2021-10-19T08:47:23.000Z
|
2022-03-07T05:23:56.000Z
|
AtCoder/colopl2018-qual/b/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n, x; cin >> n >> x;
string s; cin >> s;
long long int ans = 0;
for (int i = 0; i < n; i++) {
int a; cin >> a;
if (s[i] == '1') {
if (a > x) ans += x;
else ans += a;
}
else ans += a;
}
cout << ans << endl;
}
| 20.1
| 33
| 0.435323
|
H-Tatsuhiro
|
ff55a97d4f141d2ae3e2b184cc06e3e7b29a2026
| 1,052
|
cpp
|
C++
|
DSA Crack Sheet/solutions/Subarray with 0 sum.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 5
|
2021-08-10T18:47:49.000Z
|
2021-08-21T15:42:58.000Z
|
DSA Crack Sheet/solutions/Subarray with 0 sum.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 2
|
2022-02-25T13:36:46.000Z
|
2022-02-25T14:06:44.000Z
|
DSA Crack Sheet/solutions/Subarray with 0 sum.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 1
|
2021-08-11T06:36:42.000Z
|
2021-08-11T06:36:42.000Z
|
/*
Subarray with 0 sum
====================
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanation:
2, -3, 1 is the subarray
with sum 0.
Example 2:
Input:
5
4 2 0 1 6
Output:
Yes
Explanation:
0 is one of the element
in the array so there exist a
subarray with sum 0.
Your Task:
You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= N <= 104
-105 <= a[i] <= 105
*/
bool subArrayExists(int arr[], int n)
{
unordered_set<int> prefix_sums;
int sum = 0;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
if (!sum)
return true;
if (prefix_sums.find(sum) != prefix_sums.end())
return true;
prefix_sums.insert(sum);
}
return false;
}
| 19.849057
| 237
| 0.668251
|
Akshad7829
|
ff57a99bb4bbd37f02a0fa6dac69a3ce2ee8ef6f
| 60
|
cpp
|
C++
|
Windows/VS2017/vtkIOVeraOut/vtkIOVeraOut.cpp
|
WinBuilds/VTK
|
508ab2644432973724259184f2cb83aced602484
|
[
"BSD-3-Clause"
] | null | null | null |
Windows/VS2017/vtkIOVeraOut/vtkIOVeraOut.cpp
|
WinBuilds/VTK
|
508ab2644432973724259184f2cb83aced602484
|
[
"BSD-3-Clause"
] | null | null | null |
Windows/VS2017/vtkIOVeraOut/vtkIOVeraOut.cpp
|
WinBuilds/VTK
|
508ab2644432973724259184f2cb83aced602484
|
[
"BSD-3-Clause"
] | null | null | null |
#include "vtkIOVeraOut.h"
vtkIOVeraOut::vtkIOVeraOut()
{
}
| 10
| 28
| 0.733333
|
WinBuilds
|
ff58813ebd02fdad515b5e0e27403d28a48bd47e
| 1,168
|
cpp
|
C++
|
solved/dominant striung(10745).cpp
|
goutomroy/uva.onlinejudge
|
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
|
[
"MIT"
] | null | null | null |
solved/dominant striung(10745).cpp
|
goutomroy/uva.onlinejudge
|
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
|
[
"MIT"
] | null | null | null |
solved/dominant striung(10745).cpp
|
goutomroy/uva.onlinejudge
|
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
|
[
"MIT"
] | null | null | null |
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct goutom
{
char a[11];
int len;
}roy[15005];
bool flag[15005];
long c=0;
int comp1(const void *A,const void *B)
{
goutom *x=(goutom*)A;
goutom *y=(goutom*)B;
return(x->len-y->len);
}
int comp2(const void *A,const void *B)
{
char *x=(char*)A;
char *y=(char*)B;
return(strcmp(x,y));
}
void show( )
{
int j,i,p,x,y;
char t1[11],t2[11];
for(i=0;i<c;i++)
{
strcpy(t1,roy[i].a);
for(j=i+1;j<c;j++)
{
strcpy(t2,roy[j].a);
for(x=p=0;x<roy[i].len;x++)
{
for(y=0;y<roy[j].len;y++)
if(t1[x]==t2[y])
{
t2[y]=0;
break;
}
if(y==roy[j].len)
{
p=1;
break;
}
}
if(p==0)
{
flag[i]=1;
break;
}
if(p==0 && (roy[i].len==roy[j].len))
flag[j]=1;
}
}
}
void main()
{
char str[11],result[15002][11];
long i,u;
while(scanf(" %s",str)==1)
{
strcpy(roy[c].a,str);
roy[c++].len=strlen(str);
}
qsort(roy,c,sizeof(goutom),comp1);
show( );
for(i=u=0;i<c;i++)
if(flag[i]==0)
strcpy(result[u++],roy[i].a);
qsort(result,u,sizeof(result[0]),comp2);
for(i=0;i<u;i++)
puts(result[i]);
}
| 14.243902
| 42
| 0.507705
|
goutomroy
|
ff5cd031a0f3ce32a8e1b4b29210d7403975e3fe
| 118
|
cpp
|
C++
|
libraries/chain/rate_limiting.cpp
|
betterchainio/betterchain
|
29f82c25ae6812beaf09f8d7069932474bea9f8b
|
[
"MIT"
] | 3
|
2018-01-18T07:12:34.000Z
|
2018-01-22T10:00:29.000Z
|
libraries/chain/rate_limiting.cpp
|
betterchainio/betterchain
|
29f82c25ae6812beaf09f8d7069932474bea9f8b
|
[
"MIT"
] | null | null | null |
libraries/chain/rate_limiting.cpp
|
betterchainio/betterchain
|
29f82c25ae6812beaf09f8d7069932474bea9f8b
|
[
"MIT"
] | 2
|
2018-01-30T01:03:10.000Z
|
2019-02-28T09:04:06.000Z
|
#include <betterchain/chain/rate_limiting.hpp>
namespace betterchain { namespace chain {
} } /// betterchain::chain
| 19.666667
| 46
| 0.754237
|
betterchainio
|
ff61fc705f65b24f5a78b3d5a011a0bc1723588b
| 1,174
|
cc
|
C++
|
src/kmer/KmerIntPair.cc
|
mgtools/kmerLSHSA
|
dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1
|
[
"Intel",
"MIT"
] | null | null | null |
src/kmer/KmerIntPair.cc
|
mgtools/kmerLSHSA
|
dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1
|
[
"Intel",
"MIT"
] | null | null | null |
src/kmer/KmerIntPair.cc
|
mgtools/kmerLSHSA
|
dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1
|
[
"Intel",
"MIT"
] | null | null | null |
#include <cstdlib>
#include "Kmer.h"
#include "KmerIntPair.h"
KmerIntPair::KmerIntPair(const Kmer &km, uint32_t val) {
SetKey(km);
SetVal(val);
}
void KmerIntPair::SetVal(const uint32_t val) {
//char val8 = (val > 0xFF) ? 0xFF : (char)val;
//memcpy(&this->v + KmerIntPair::IntOffset, &val8, sizeof(uint8_t));
//this->v[KmerIntPair::IntOffset] = val8;
//this->v[KmerIntPair::IntOffset] = val;
KmerIntPair::cnt = val;
//memcpy(this+KmerIntPair::IntOffset, &val, sizeof(uint32_t));
}
uint32_t KmerIntPair::GetVal() const {
//uint8_t tmp = *reinterpret_cast<const uint8_t*>(this+KmerIntPair::IntOffset);
//2/12/2015, uint8_t to uint32_t
//uint32_t tmp = *reinterpret_cast<const uint32_t*>(this+KmerIntPair::IntOffset);
//return tmp;
//return (uint8_t)this->v[KmerIntPair::IntOffset];
return KmerIntPair::cnt;
}
const Kmer& KmerIntPair::GetKey() const {
return *reinterpret_cast<const Kmer*>(this + KmerIntPair::KmerOffset);
}
void KmerIntPair::SetKey(const Kmer& km) {
memcpy(this, &km, sizeof(Kmer));
}
void SetKmerKey::operator()(KmerIntPair *value, const Kmer& km) {
memcpy(value + KmerIntPair::KmerOffset, &km, sizeof(Kmer));
}
| 26.681818
| 83
| 0.697615
|
mgtools
|
ff621cc1b7e09aa5b246d87787c1ce738e2a1a8a
| 1,733
|
cpp
|
C++
|
done/revegetate(1).cpp
|
birdhumming/usaco
|
f011e7bd4b71de22736a61004e501af2b273b246
|
[
"OLDAP-2.2.1"
] | null | null | null |
done/revegetate(1).cpp
|
birdhumming/usaco
|
f011e7bd4b71de22736a61004e501af2b273b246
|
[
"OLDAP-2.2.1"
] | null | null | null |
done/revegetate(1).cpp
|
birdhumming/usaco
|
f011e7bd4b71de22736a61004e501af2b273b246
|
[
"OLDAP-2.2.1"
] | null | null | null |
#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define ii pair<int, int>
#define ll long long
#define vi vector<int>
#define vc vector<char>
#define pb push_back
#define rz resize
#define mp make_pair
#define f first
#define s second
#define FOR(n) for (int i = 0; i < n; i++)
#define FOR1(n) for (int i = 1; i <= n; i++)
#define RFOR(n) for (int i = n - 1; i >= 0; i--)
#define DFOR(n, m) FOR(n) for (int j = 0; j < m; j++)
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int ddx[8] = {1, 0, -1, -1, -1, 0, 1, 1};
int ddy[8] = {1, 1, 1, 0, -1, -1, -1, 0};
bool in_bounds(int x, int y, int n, int m) {
if (x >= 0 && x < n && y >= 0 && y < m) return true;
return false;
}
const int N = 2 * 1e5 + 10;
int n, m;
int p[N];
int find (int x) {
if (p[x] == -1) return x;
return p[x] = find(p[x]);
}
void merge(int a, int b) {
a = find(a); b = find(b);
if (a == b) return;
if (a >= n) swap(a, b);
p[b] = a;
}
int main() {
freopen("revegetate.in", "r", stdin);
freopen("revegetate.out", "w", stdout);
scanf("%d%d", &n, &m);
memset(p, -1, sizeof p);
FOR(m) {
int a, b; char c;
cin >> c >> a >> b;
a--, b--;
if (a > b) swap(a, b);
if (c == 'S') {
merge(a, b);
merge(a + n, b + n);
}
else {
merge(a, b + n);
merge(b, a + n);
}
}
int cnt = 0;
FOR(n) {
if (find(i) == find(i + n)) {
printf("0");
return 0;
}
}
FOR(n)
merge(i, i + n);
printf("1");
FOR(n) {
if (i == find(i)) printf("0");
}
cout<<endl;
return 0;
}
| 19.91954
| 56
| 0.448932
|
birdhumming
|
ff62b279e9daf74ffb0fafc797a4e900bc7bba43
| 1,325
|
hpp
|
C++
|
src/include/Serialization.hpp
|
coetaur0/MPICapsule
|
427ffcd2ee00c576127390b1282f405a794c3376
|
[
"Apache-2.0"
] | null | null | null |
src/include/Serialization.hpp
|
coetaur0/MPICapsule
|
427ffcd2ee00c576127390b1282f405a794c3376
|
[
"Apache-2.0"
] | null | null | null |
src/include/Serialization.hpp
|
coetaur0/MPICapsule
|
427ffcd2ee00c576127390b1282f405a794c3376
|
[
"Apache-2.0"
] | null | null | null |
#ifndef __SERIALIZATION_H__
#define __SERIALIZATION_H__
#include <map>
#include <unordered_map>
#include <string>
#include <cereal/cereal.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/archives/binary.hpp>
template<typename Container>
class Serialization
{
public :
/**
\brief This method serializes the container it received as parameter
and returns it in the form of an std::string object.
\param container An STL container to be serialized.
\return An std::string object containing the serialized container.
*/
static std::string serialize(Container const& container){
std::stringstream ss;
cereal::BinaryOutputArchive oarchive(ss);
oarchive(container);
return ss.str();
}
/**
\brief This method deserializes the content of an std::string representing
a serialized container.
\param serializedContainer An std::string object which contains a serialized container.
\return The deserialized container of type 'Container' that was in the string.
*/
static Container deserialize(std::string const& serializedContainer){
std::stringstream ss(serializedContainer);
Container container;
cereal::BinaryInputArchive iarchive(ss);
iarchive(container);
return container;
}
};
#endif
| 25.980392
| 89
| 0.76
|
coetaur0
|
ff6bb205209b4365523602d463211594dbb9d585
| 1,546
|
cpp
|
C++
|
src/systems/systemmanager.cpp
|
lfowles/polarbear
|
3c008b3560a7b24c9e985bff0166650fd981e8a7
|
[
"MIT"
] | null | null | null |
src/systems/systemmanager.cpp
|
lfowles/polarbear
|
3c008b3560a7b24c9e985bff0166650fd981e8a7
|
[
"MIT"
] | null | null | null |
src/systems/systemmanager.cpp
|
lfowles/polarbear
|
3c008b3560a7b24c9e985bff0166650fd981e8a7
|
[
"MIT"
] | null | null | null |
#include <polarbear/systems/systemmanager.hpp>
void SystemManager::AddSystem(std::shared_ptr<System>& system)
{
systems.push_back(std::move(system));
};
void SystemManager::AddSystem(std::shared_ptr<System>&& system)
{
systems.push_back(std::move(system));
};
void SystemManager::AddSystem(System*&& system)
{
systems.push_back(std::shared_ptr<System>(system));
}
void SystemManager::AddEntity(Entity& entity)
{
// This is good enough for now, with a mostly static list of entities and components, but in the future this will need some sort of hook on AddComponent/RemoveComponent
auto entity_ptr = std::make_shared<Entity>(std::move(entity));
for (auto &system : systems)
{
system->entity_added(entity_ptr);
}
entities.push_back(entity_ptr);
};
void SystemManager::update(ms time_elapsed)
{
accumulated_time += time_elapsed;
while (accumulated_time > ms_per_update)
{
for (auto &system : systems)
{
system->update(ms_per_update);
}
accumulated_time -= ms_per_update;
}
};
void SystemManager::SetUpdateTime(s update_time)
{
ms_per_update = ms(update_time);
};
std::vector<std::shared_ptr<Entity>> SystemManager::GetEntities(std::bitset<max_components> mask)
{
auto matching_entities = std::vector<std::shared_ptr<Entity>>{};
for (auto& entity : entities)
{
if ((mask & entity->component_mask) == mask)
{
matching_entities.push_back(entity);
}
}
return matching_entities;
}
| 25.344262
| 172
| 0.677878
|
lfowles
|
ff6c88f69489274d6befffab8f4071b630e516e9
| 7,761
|
cpp
|
C++
|
UEngine/UEngine/Game Architecture/Object/Component/Material.cpp
|
yus1108/UnsungEngine2
|
c824c049069a0d8283f84b09af7ae0182d9a48c9
|
[
"MIT"
] | null | null | null |
UEngine/UEngine/Game Architecture/Object/Component/Material.cpp
|
yus1108/UnsungEngine2
|
c824c049069a0d8283f84b09af7ae0182d9a48c9
|
[
"MIT"
] | 4
|
2021-03-12T06:11:36.000Z
|
2021-03-19T11:09:06.000Z
|
UEngine/UEngine/Game Architecture/Object/Component/Material.cpp
|
yus1108/UnsungEngine2
|
c824c049069a0d8283f84b09af7ae0182d9a48c9
|
[
"MIT"
] | null | null | null |
#include "UEngine.h"
#include "Material.h"
void UEngine::Material::Awake()
{
colorBuffer = DXRenderer::DXConstantBuffer::Instantiate
(
GetGameObject()->GetScene()->ResourceManager.GetNextCBufferID(),
DXRenderer::Get(),
GetGameObject()->GetScene()->ResourceManager.GetCBufferPreset(typeid(Color).raw_name())
);
spriteBuffer = DXRenderer::DXConstantBuffer::Instantiate
(
GetGameObject()->GetScene()->ResourceManager.GetNextCBufferID(),
DXRenderer::Get(),
GetGameObject()->GetScene()->ResourceManager.GetCBufferPreset(typeid(UV).raw_name())
);
uv = UV{ 0, 0, 1, 1 };
colorBuffer->AttachData(&color.value, sizeof(Color));
spriteBuffer->AttachData(&uv.value, sizeof(UV));
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXConstantBuffer>(colorBuffer->UID, colorBuffer);
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXConstantBuffer>(spriteBuffer->UID, spriteBuffer);
}
void UEngine::Material::Update()
{
auto renderComponent = GetComponent<RenderComponent>();
if (renderComponent == nullptr) return;
if (renderObject != renderComponent->GetRenderObject())
{
renderObject = renderComponent->GetRenderObject();
if (renderObject == nullptr) return;
renderComponent->AddConstantBuffer(colorBuffer);
renderComponent->AddConstantBuffer(spriteBuffer);
if (imageTexture) renderComponent->AddImageTexture(imageTexture);
if (imageSampler) renderComponent->AddImageSampler(imageSampler);
}
}
void UEngine::Material::OnPreRender()
{
colorBuffer->Update(DXRenderer::Get()->GetImmediateDeviceContext());
spriteBuffer->Update(DXRenderer::Get()->GetImmediateDeviceContext());
}
void UEngine::Material::OnDestroy()
{
auto renderComponent = GetComponent<RenderComponent>();
if (renderComponent == nullptr) return;
if (renderObject != renderComponent->GetRenderObject())
{
renderObject = renderComponent->GetRenderObject();
if (renderObject == nullptr) return;
renderComponent->ClearConstantBuffers();
if (imageTexture) renderComponent->AddImageTexture(nullptr);
if (imageSampler) renderComponent->AddImageSampler(nullptr);
}
}
void UEngine::Material::DeSerialize(TiXmlNode* node)
{
Serializer::DeSerialize(node);
std::wstring fileName;
convert_utf8_to_unicode_string(fileName, this->fileName.value.c_str(), this->fileName.value.size());
using namespace std;
std::string delimiter = "\n";
std::list<std::string> tokens;
size_t pos = 0;
while ((pos = samplerName.value.find(delimiter)) != std::string::npos) {
tokens.emplace_back(samplerName.value.substr(0, pos));
samplerName.value.erase(0, pos + delimiter.length());
}
D3D11_SAMPLER_DESC desc;
desc.AddressU = static_cast<D3D11_TEXTURE_ADDRESS_MODE>(stoll(tokens.front())); tokens.pop_front();
desc.AddressV = static_cast<D3D11_TEXTURE_ADDRESS_MODE>(stoll(tokens.front())); tokens.pop_front();
desc.AddressW = static_cast<D3D11_TEXTURE_ADDRESS_MODE>(stoll(tokens.front())); tokens.pop_front();
desc.BorderColor[0] = stof(tokens.front()); tokens.pop_front();
desc.BorderColor[1] = stof(tokens.front()); tokens.pop_front();
desc.BorderColor[2] = stof(tokens.front()); tokens.pop_front();
desc.BorderColor[3] = stof(tokens.front()); tokens.pop_front();
desc.ComparisonFunc = static_cast<D3D11_COMPARISON_FUNC>(stoi(tokens.front())); tokens.pop_front();
desc.Filter = static_cast<D3D11_FILTER>(stoi(tokens.front())); tokens.pop_front();
desc.MaxAnisotropy = stoi(tokens.front()); tokens.pop_front();
desc.MaxLOD = stof(tokens.front()); tokens.pop_front();
desc.MinLOD = stof(tokens.front()); tokens.pop_front();
desc.MipLODBias = stof(tokens.front()); tokens.pop_front();
LoadImageMaterial(fileName, desc);
}
void UEngine::Material::LoadImageMaterial(std::wstring fileName)
{
// Sampler State
D3D11_SAMPLER_DESC samplerDesc;
ZeroMemory(&samplerDesc, sizeof(samplerDesc));
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.MaxLOD = FLT_MAX;
samplerDesc.MinLOD = -FLT_MAX;
samplerDesc.MipLODBias = 0;
this->fileName = fileName;
this->samplerName = DXRenderer::DXSamplerState::MakeName(samplerDesc);
auto scene = GetGameObject()->GetScene();
imageTexture = scene->ResourceManager.GetResource<DXRenderer::DXTexture>(this->fileName.value);
if (imageTexture == nullptr)
{
imageTexture = DXRenderer::DXTexture::Load(fileName);
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXTexture>(this->fileName.value, imageTexture);
}
imageSampler = scene->ResourceManager.GetResource<DXRenderer::DXSamplerState>(this->samplerName.value);
if (imageSampler == nullptr)
{
imageSampler = DXRenderer::DXSamplerState::Load(samplerDesc);
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXSamplerState>(samplerName.value, imageSampler);
}
color = Color{ 1, 1, 1, 1 };
if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageTexture(imageTexture);
if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageSampler(imageSampler);
}
void UEngine::Material::LoadImageMaterial(std::wstring fileName, D3D11_TEXTURE_ADDRESS_MODE addressMode, D3D11_FILTER filter)
{
// Sampler State
D3D11_SAMPLER_DESC samplerDesc;
ZeroMemory(&samplerDesc, sizeof(samplerDesc));
samplerDesc.AddressU = addressMode;
samplerDesc.AddressV = addressMode;
samplerDesc.AddressW = addressMode;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.Filter = filter;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.MaxLOD = FLT_MAX;
samplerDesc.MinLOD = -FLT_MAX;
samplerDesc.MipLODBias = 0;
this->fileName = fileName;
this->samplerName = DXRenderer::DXSamplerState::MakeName(samplerDesc);
auto scene = GetGameObject()->GetScene();
if (imageTexture == nullptr)
{
imageTexture = DXRenderer::DXTexture::Load(fileName);
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXTexture>(this->fileName.value, imageTexture);
}
imageSampler = scene->ResourceManager.GetResource<DXRenderer::DXSamplerState>(this->samplerName.value);
if (imageSampler == nullptr)
{
imageSampler = DXRenderer::DXSamplerState::Load(samplerDesc);
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXSamplerState>(samplerName.value, imageSampler);
}
color = Color{ 1, 1, 1, 1 };
if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageTexture(imageTexture);
if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageSampler(imageSampler);
}
void UEngine::Material::LoadImageMaterial(std::wstring fileName, D3D11_SAMPLER_DESC desc)
{
this->fileName = fileName;
this->samplerName = DXRenderer::DXSamplerState::MakeName(desc);
auto scene = GetGameObject()->GetScene();
imageTexture = scene->ResourceManager.GetResource<DXRenderer::DXTexture>(this->fileName.value);
if (imageTexture == nullptr)
{
imageTexture = DXRenderer::DXTexture::Load(fileName);
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXTexture>(this->fileName.value, imageTexture);
}
imageSampler = scene->ResourceManager.GetResource<DXRenderer::DXSamplerState>(this->samplerName.value);
if (imageSampler == nullptr)
{
imageSampler = DXRenderer::DXSamplerState::Load(desc);
GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXSamplerState>(samplerName.value, imageSampler);
}
color = Color{ 1, 1, 1, 1 };
if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageTexture(imageTexture);
if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageSampler(imageSampler);
}
| 40.212435
| 125
| 0.768329
|
yus1108
|
ff6f2098a03899851322502b167fe797341fbfe9
| 856
|
cpp
|
C++
|
libraries/chain/chronicler.cpp
|
joticajulian/koinos-chain
|
b5db60b427ebb97dabf1acf8108e94bbc75a46d4
|
[
"MIT"
] | null | null | null |
libraries/chain/chronicler.cpp
|
joticajulian/koinos-chain
|
b5db60b427ebb97dabf1acf8108e94bbc75a46d4
|
[
"MIT"
] | null | null | null |
libraries/chain/chronicler.cpp
|
joticajulian/koinos-chain
|
b5db60b427ebb97dabf1acf8108e94bbc75a46d4
|
[
"MIT"
] | null | null | null |
#include <koinos/chain/chronicler.hpp>
namespace koinos::chain {
void chronicler::set_session( std::shared_ptr< abstract_chronicler_session > s )
{
_session = s;
}
void chronicler::push_event( protocol::event_data&& ev )
{
ev.set_sequence( _seq_no );
bool within_session = false;
if ( auto session = _session.lock() )
{
within_session = true;
session->push_event( ev );
}
_events.emplace_back( std::make_pair( within_session, std::move( ev ) ) );
_seq_no++;
}
void chronicler::push_log( const std::string& message )
{
if ( auto session = _session.lock() )
session->push_log( message );
else
_logs.push_back( message );
}
const std::vector< event_bundle >& chronicler::events()
{
return _events;
}
const std::vector< std::string >& chronicler::logs()
{
return _logs;
}
} // koinos::chain
| 19.454545
| 80
| 0.661215
|
joticajulian
|
ff7238226c23eeb1e27a7abe7bf5ae38d12c630d
| 225
|
cpp
|
C++
|
src/RE/Misc/FixedStrings.cpp
|
fireundubh/CommonLibSSE-po3
|
cf30265f3cd3aa70a8eeff4d598754439e983ddd
|
[
"MIT"
] | 1
|
2021-08-30T20:33:43.000Z
|
2021-08-30T20:33:43.000Z
|
src/RE/Misc/FixedStrings.cpp
|
fireundubh/CommonLibSSE-po3
|
cf30265f3cd3aa70a8eeff4d598754439e983ddd
|
[
"MIT"
] | null | null | null |
src/RE/Misc/FixedStrings.cpp
|
fireundubh/CommonLibSSE-po3
|
cf30265f3cd3aa70a8eeff4d598754439e983ddd
|
[
"MIT"
] | null | null | null |
#include "RE/Misc/FixedStrings.h"
namespace RE
{
FixedStrings* FixedStrings::GetSingleton()
{
using func_t = decltype(&FixedStrings::GetSingleton);
REL::Relocation<func_t> func{ REL::ID(11308) };
return func();
}
}
| 18.75
| 55
| 0.706667
|
fireundubh
|
ff77a1e1532c4ce464df064e38c48546750665be
| 3,812
|
cpp
|
C++
|
asteroid/src/wrapper_glfw.cpp
|
Rekfuki/asteroidOpenGL
|
691ec2b2877d146d9b4a312dac894b2e8dafc014
|
[
"MIT"
] | 1
|
2021-08-02T02:26:53.000Z
|
2021-08-02T02:26:53.000Z
|
asteroid/src/wrapper_glfw.cpp
|
Rekfuki/asteroidOpenGL
|
691ec2b2877d146d9b4a312dac894b2e8dafc014
|
[
"MIT"
] | null | null | null |
asteroid/src/wrapper_glfw.cpp
|
Rekfuki/asteroidOpenGL
|
691ec2b2877d146d9b4a312dac894b2e8dafc014
|
[
"MIT"
] | 1
|
2021-08-02T02:27:11.000Z
|
2021-08-02T02:27:11.000Z
|
/**
wrapper_glfw.cpp
Modified from the OpenGL GLFW example to provide a wrapper GLFW class
and to include shader loader functions to include shaders as text files
Iain Martin August 2014
*/
#include "wrapper_glfw.h"
/* Inlcude some standard headers */
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
/* Constructor for wrapper object */
GLWrapper::GLWrapper(int width, int height, const char* title) {
this->width = width;
this->height = height;
this->title = title;
this->fps = 60;
this->running = true;
/* Initialise GLFW and exit if it fails */
if (!glfwInit())
{
cout << "Failed to initialize GLFW." << endl;
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_SAMPLES, 8);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef DEBUG
glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif
window = glfwCreateWindow(width, height, title, 0, 0);
if (!window) {
cout << "Could not open GLFW window." << endl;
glfwTerminate();
exit(EXIT_FAILURE);
}
/* Obtain an OpenGL context and assign to the just opened GLFW window */
glfwMakeContextCurrent(window);
/* Initialise GLLoad library. You must have obtained a current OpenGL */
if (!ogl_LoadFunctions())
{
cerr << "oglLoadFunctions() failed. Exiting" << endl;
glfwTerminate();
return;
}
/* Can set the Window title at a later time if you wish*/
glfwSetWindowTitle(window, title);
glfwSetInputMode(window, GLFW_STICKY_KEYS, true);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
/* Terminate GLFW on destruvtion of the wrapepr object */
GLWrapper::~GLWrapper() {
glfwTerminate();
}
/* Returns the GLFW window handle, required to call GLFW functions outside this class */
GLFWwindow* GLWrapper::getWindow()
{
return window;
}
/*
* Print OpenGL Version details
*/
void GLWrapper::DisplayVersion()
{
/* One way to get OpenGL version*/
int major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MAJOR_VERSION, &minor);
cout << "OpenGL Version = " << major << "." << minor << endl;
/* A more detailed way to the version strings*/
cout << "Vender: " << glGetString(GL_VENDOR) << endl;
cout << "Version:" << glGetString(GL_VERSION) << endl;
cout << "Renderer:" << glGetString(GL_RENDERER) << endl;
}
/*
GLFW_Main function normally starts the windows system, calls any init routines
and then starts the event loop which runs until the program ends
*/
int GLWrapper::eventLoop()
{
// Main loop
while (!glfwWindowShouldClose(window))
{
// Call function to draw your graphics
renderer();
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
/* Register an error callback function */
void GLWrapper::setErrorCallback(void(*func)(int error, const char* description))
{
glfwSetErrorCallback(func);
}
/* Register a display function that renders in the window */
void GLWrapper::setRenderer(void(*func)()) {
this->renderer = func;
}
/* Register a callback that runs after the window gets resized */
void GLWrapper::setReshapeCallback(void(*func)(GLFWwindow* window, int w, int h)) {
glfwSetFramebufferSizeCallback(window, func);
}
/* Register a callback to respond to keyboard events */
void GLWrapper::setKeyCallback(void(*func)(GLFWwindow* window, int key, int scancode, int action, int mods))
{
glfwSetKeyCallback(window, func);
}
/* Register a callback to respond to mouse darf events */
void GLWrapper::setMouseCallback(void(*func)(GLFWwindow* window, double xpos, double ypos))
{
glfwSetCursorPosCallback(window, func);
}
void GLWrapper::setWindowFocusCallback(void(*func)(GLFWwindow* window, int focused)) {
glfwSetWindowFocusCallback(window, func);
}
| 26.289655
| 108
| 0.729538
|
Rekfuki
|
ff7ade7c513008408294aa07a14e81873e322f55
| 302
|
cpp
|
C++
|
Codeforces/707A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
Codeforces/707A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
Codeforces/707A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
#include<stdio.h>
using namespace std;
int main(){
int x, y, i;
char t;
bool bnw = true;
scanf("%d %d", &x, &y);
for(i=0; i<x*y; i++){
scanf(" %c", &t);
if(t!='B' && t!='W' && t!='G') bnw=false;
}
printf(bnw ? "#Black&White\n" : "#Color\n");
return 0;
}
| 20.133333
| 49
| 0.440397
|
DT3264
|
ff7d4872d694567e752c3fcfa7090f7cfcda4718
| 4,670
|
cpp
|
C++
|
Source/WebCore/svg/SVGMPathElement.cpp
|
ijsf/DeniseEmbeddableWebKit
|
57dfc6783d60f8f59b7129874e60f84d8c8556c9
|
[
"BSD-3-Clause"
] | null | null | null |
Source/WebCore/svg/SVGMPathElement.cpp
|
ijsf/DeniseEmbeddableWebKit
|
57dfc6783d60f8f59b7129874e60f84d8c8556c9
|
[
"BSD-3-Clause"
] | 9
|
2020-04-18T18:47:18.000Z
|
2020-04-18T18:52:41.000Z
|
Source/WebCore/svg/SVGMPathElement.cpp
|
ijsf/DeniseEmbeddableWebKit
|
57dfc6783d60f8f59b7129874e60f84d8c8556c9
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "SVGMPathElement.h"
#include "Document.h"
#include "SVGAnimateMotionElement.h"
#include "SVGDocumentExtensions.h"
#include "SVGNames.h"
#include "SVGPathElement.h"
#include "XLinkNames.h"
namespace WebCore {
// Animated property definitions
DEFINE_ANIMATED_STRING(SVGMPathElement, XLinkNames::hrefAttr, Href, href)
DEFINE_ANIMATED_BOOLEAN(SVGMPathElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMPathElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(href)
REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
END_REGISTER_ANIMATED_PROPERTIES
inline SVGMPathElement::SVGMPathElement(const QualifiedName& tagName, Document& document)
: SVGElement(tagName, document)
{
ASSERT(hasTagName(SVGNames::mpathTag));
registerAnimatedPropertiesForSVGMPathElement();
}
Ref<SVGMPathElement> SVGMPathElement::create(const QualifiedName& tagName, Document& document)
{
return adoptRef(*new SVGMPathElement(tagName, document));
}
SVGMPathElement::~SVGMPathElement()
{
clearResourceReferences();
}
void SVGMPathElement::buildPendingResource()
{
clearResourceReferences();
if (!isConnected())
return;
String id;
Element* target = SVGURIReference::targetElementFromIRIString(href(), document(), &id);
if (!target) {
// Do not register as pending if we are already pending this resource.
if (document().accessSVGExtensions().isPendingResource(this, id))
return;
if (!id.isEmpty()) {
document().accessSVGExtensions().addPendingResource(id, this);
ASSERT(hasPendingResources());
}
} else if (target->isSVGElement()) {
// Register us with the target in the dependencies map. Any change of hrefElement
// that leads to relayout/repainting now informs us, so we can react to it.
document().accessSVGExtensions().addElementReferencingTarget(this, downcast<SVGElement>(target));
}
targetPathChanged();
}
void SVGMPathElement::clearResourceReferences()
{
document().accessSVGExtensions().removeAllTargetReferencesForElement(this);
}
Node::InsertionNotificationRequest SVGMPathElement::insertedInto(ContainerNode& rootParent)
{
SVGElement::insertedInto(rootParent);
if (rootParent.isConnected())
return InsertionShouldCallFinishedInsertingSubtree;
return InsertionDone;
}
void SVGMPathElement::finishedInsertingSubtree()
{
buildPendingResource();
}
void SVGMPathElement::removedFrom(ContainerNode& rootParent)
{
SVGElement::removedFrom(rootParent);
notifyParentOfPathChange(&rootParent);
if (rootParent.isConnected())
clearResourceReferences();
}
void SVGMPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
SVGElement::parseAttribute(name, value);
SVGURIReference::parseAttribute(name, value);
SVGExternalResourcesRequired::parseAttribute(name, value);
}
void SVGMPathElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (SVGURIReference::isKnownAttribute(attrName)) {
InstanceInvalidationGuard guard(*this);
buildPendingResource();
return;
}
SVGElement::svgAttributeChanged(attrName);
}
SVGPathElement* SVGMPathElement::pathElement()
{
Element* target = targetElementFromIRIString(href(), document());
if (is<SVGPathElement>(target))
return downcast<SVGPathElement>(target);
return nullptr;
}
void SVGMPathElement::targetPathChanged()
{
notifyParentOfPathChange(parentNode());
}
void SVGMPathElement::notifyParentOfPathChange(ContainerNode* parent)
{
if (is<SVGAnimateMotionElement>(parent))
downcast<SVGAnimateMotionElement>(*parent).updateAnimationPath();
}
} // namespace WebCore
| 31.554054
| 135
| 0.750107
|
ijsf
|
ff7ebf7b323e30d1a6a7139e29f0fb281f3510ac
| 5,047
|
hpp
|
C++
|
include/matrix.hpp
|
blockahead/CGMRES_cpp
|
13a44e0022fbda6ab85b2d04131c230668197859
|
[
"MIT"
] | 2
|
2021-12-21T09:03:04.000Z
|
2022-03-31T11:02:53.000Z
|
include/matrix.hpp
|
blockahead/CGMRES_cpp
|
13a44e0022fbda6ab85b2d04131c230668197859
|
[
"MIT"
] | null | null | null |
include/matrix.hpp
|
blockahead/CGMRES_cpp
|
13a44e0022fbda6ab85b2d04131c230668197859
|
[
"MIT"
] | null | null | null |
#pragma once
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define DEBUG_MODE
// ret = vec
inline void mov(double* ret, const double* vec, const int16_t row) {
int16_t i;
for (i = 0; i < row; i++) {
ret[i] = vec[i];
}
}
// ret = mat
inline void mov(double* ret, const double* mat, const int16_t row, const int16_t col) {
int16_t i;
for (i = 0; i < row * col; i++) {
ret[i] = mat[i];
}
}
// ret = vec1 + vec2
inline void add(double* ret, const double* vec1, const double* vec2, const int16_t row) {
int16_t i;
for (i = 0; i < row; i++) {
ret[i] = vec1[i] + vec2[i];
}
}
// ret = mat1 + mat2
inline void add(double* ret, const double* mat1, const double* mat2, const int16_t row, const int16_t col) {
int16_t i;
for (i = 0; i < row * col; i++) {
ret[i] = mat1[i] + mat2[i];
}
}
// ret = vec1 - vec2
inline void sub(double* ret, const double* vec1, const double* vec2, const int16_t row) {
int16_t i;
for (i = 0; i < row; i++) {
ret[i] = vec1[i] - vec2[i];
}
}
// ret = mat1 - mat2
inline void sub(double* ret, const double* mat1, const double* mat2, const int16_t row, const int16_t col) {
int16_t i;
for (i = 0; i < row * col; i++) {
ret[i] = mat1[i] - mat2[i];
}
}
// ret = vec * c
inline void mul(double* ret, const double* vec, const double c, const int16_t row) {
int16_t i;
for (i = 0; i < row; i++) {
ret[i] = vec[i] * c;
}
}
// ret = mat * c
inline void mul(double* ret, const double* mat, const double c, const int16_t row, const int16_t col) {
int16_t i;
for (i = 0; i < row * col; i++) {
ret[i] = mat[i] * c;
}
}
// ret = mat * vec
inline void mul(double* ret, const double* mat, const double* vec, const int16_t row, const int16_t col) {
int16_t i, j, idx;
#ifdef DEBUG_MODE
if (ret == vec) {
printf("%s pointer error !\n", __func__);
exit(-1);
}
#endif
for (i = 0; i < row; i++) {
ret[i] = 0.0;
}
for (j = 0; j < col; j++) {
for (i = 0; i < row; i++) {
idx = row * j + i;
ret[i] += mat[idx] * vec[j];
}
}
}
// ret = mat * mat
inline void mul(double* ret, const double* mat1, const double* mat2, const int16_t l, const int16_t row, const int16_t col) {
int16_t i, j, k, idx1, idx2, idx3;
#ifdef DEBUG_MODE
if (ret == mat1 || ret == mat2) {
printf("%s pointer error !\n", __func__);
exit(-1);
}
#endif
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
idx1 = col * i + j;
ret[idx1] = 0;
}
for (k = 0; k < l; k++) {
idx2 = col * i + k;
for (j = 0; j < col; j++) {
idx1 = col * i + j;
idx3 = col * k + j;
ret[idx1] += mat1[idx2] * mat2[idx3];
}
}
}
}
// ret = vec / c
inline void div(double* ret, const double* vec, const double c, const int16_t row) {
int16_t i;
double inv_c = 1.0 / c;
for (i = 0; i < row; i++) {
ret[i] = vec[i] * inv_c;
}
}
// ret = mat / c
inline void div(double* ret, const double* mat, const double c, const int16_t row, const int16_t col) {
int16_t i;
double inv_c = 1.0 / c;
for (i = 0; i < row * col; i++) {
ret[i] = mat[i] * inv_c;
}
}
// ret = norm(vec)
inline double norm(const double* vec, int16_t n) {
int16_t i;
double ret = 0;
for (i = 0; i < n; i++) {
ret += vec[i] * vec[i];
}
return sqrt(ret);
}
// ret = vec1' * vec2
inline double dot(const double* vec1, const double* vec2, const int16_t n) {
int16_t i;
double ret = 0;
for (i = 0; i < n; i++) {
ret += vec1[i] * vec2[i];
}
return ret;
}
// ret = sign(x)
inline double sign(const double x) { return (x < 0.0) ? -1.0 : 1.0; }
// ret = mat \ vec
// Gaussian elimination
inline void linsolve(double* vec, double* mat, const int16_t n) {
int16_t i, j, k, idx1, idx2, idx3;
int16_t row_max_i;
double row_max_val, buf;
for (k = 0; k < n - 1; k++) {
// Find i such that maximize A[i][k]
idx1 = n * k + k;
row_max_i = k;
row_max_val = fabs(mat[idx1]);
for (i = k + 1; i < n; i++) {
idx1 = n * k + i;
if (row_max_val < fabs(mat[idx1])) {
row_max_val = fabs(mat[idx1]);
row_max_i = i;
}
}
// Swap rows
if (row_max_i != k) {
buf = vec[k];
vec[k] = vec[row_max_i];
vec[row_max_i] = buf;
for (j = k; j < n; j++) {
idx1 = n * j + k;
idx2 = n * j + row_max_i;
buf = mat[idx1];
mat[idx1] = mat[idx2];
mat[idx2] = buf;
}
}
// Forward elimination
idx1 = n * k + k;
buf = 1.0 / mat[idx1];
for (i = k + 1; i < n; i++) {
idx1 = n * k + i;
mat[idx1] = mat[idx1] * buf;
for (j = k + 1; j < n; j++) {
idx2 = n * j + k;
idx3 = n * j + i;
mat[idx3] -= mat[idx1] * mat[idx2];
}
vec[i] -= mat[idx1] * vec[k];
}
}
// Backward elimination
for (i = n - 1; i >= 0; i--) {
for (j = n - 1; j > i; j--) {
idx1 = n * j + i;
vec[i] -= mat[idx1] * vec[j];
}
idx1 = n * i + i;
vec[i] /= mat[idx1];
}
}
| 22.53125
| 125
| 0.513176
|
blockahead
|
ff7fb9690e8d8095f4c504153fef19bbb2ad433f
| 43,691
|
cxx
|
C++
|
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.cxx
|
EnEff-BIM/EnEffBIM-Framework
|
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
|
[
"MIT"
] | 3
|
2016-05-30T15:12:16.000Z
|
2022-03-22T08:11:13.000Z
|
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.cxx
|
EnEff-BIM/EnEffBIM-Framework
|
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
|
[
"MIT"
] | 21
|
2016-06-13T11:33:45.000Z
|
2017-05-23T09:46:52.000Z
|
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.cxx
|
EnEff-BIM/EnEffBIM-Framework
|
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.hxx"
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior
//
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ZoneName_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ZoneName () const
{
return this->SimInfiltrationOrVentilation_ZoneName_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ZoneName_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ZoneName ()
{
return this->SimInfiltrationOrVentilation_ZoneName_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ZoneName (const SimInfiltrationOrVentilation_ZoneName_type& x)
{
this->SimInfiltrationOrVentilation_ZoneName_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ZoneName (const SimInfiltrationOrVentilation_ZoneName_optional& x)
{
this->SimInfiltrationOrVentilation_ZoneName_ = x;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ZoneName (::std::auto_ptr< SimInfiltrationOrVentilation_ZoneName_type > x)
{
this->SimInfiltrationOrVentilation_ZoneName_.set (x);
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ThermstatHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ThermstatHt () const
{
return this->SimInfiltrationOrVentilation_ThermstatHt_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ThermstatHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ThermstatHt ()
{
return this->SimInfiltrationOrVentilation_ThermstatHt_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ThermstatHt (const SimInfiltrationOrVentilation_ThermstatHt_type& x)
{
this->SimInfiltrationOrVentilation_ThermstatHt_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ThermstatHt (const SimInfiltrationOrVentilation_ThermstatHt_optional& x)
{
this->SimInfiltrationOrVentilation_ThermstatHt_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ComfHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ComfHt () const
{
return this->SimInfiltrationOrVentilation_ComfHt_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ComfHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ComfHt ()
{
return this->SimInfiltrationOrVentilation_ComfHt_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ComfHt (const SimInfiltrationOrVentilation_ComfHt_type& x)
{
this->SimInfiltrationOrVentilation_ComfHt_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_ComfHt (const SimInfiltrationOrVentilation_ComfHt_optional& x)
{
this->SimInfiltrationOrVentilation_ComfHt_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TempDiffThreshRpt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TempDiffThreshRpt () const
{
return this->SimInfiltrationOrVentilation_TempDiffThreshRpt_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TempDiffThreshRpt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TempDiffThreshRpt ()
{
return this->SimInfiltrationOrVentilation_TempDiffThreshRpt_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TempDiffThreshRpt (const SimInfiltrationOrVentilation_TempDiffThreshRpt_type& x)
{
this->SimInfiltrationOrVentilation_TempDiffThreshRpt_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TempDiffThreshRpt (const SimInfiltrationOrVentilation_TempDiffThreshRpt_optional& x)
{
this->SimInfiltrationOrVentilation_TempDiffThreshRpt_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_PowerPerPlume_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_PowerPerPlume () const
{
return this->SimInfiltrationOrVentilation_PowerPerPlume_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_PowerPerPlume_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_PowerPerPlume ()
{
return this->SimInfiltrationOrVentilation_PowerPerPlume_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_PowerPerPlume (const SimInfiltrationOrVentilation_PowerPerPlume_type& x)
{
this->SimInfiltrationOrVentilation_PowerPerPlume_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_PowerPerPlume (const SimInfiltrationOrVentilation_PowerPerPlume_optional& x)
{
this->SimInfiltrationOrVentilation_PowerPerPlume_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DesignEffectAreaDiff_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DesignEffectAreaDiff () const
{
return this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DesignEffectAreaDiff_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DesignEffectAreaDiff ()
{
return this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DesignEffectAreaDiff (const SimInfiltrationOrVentilation_DesignEffectAreaDiff_type& x)
{
this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DesignEffectAreaDiff (const SimInfiltrationOrVentilation_DesignEffectAreaDiff_optional& x)
{
this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical () const
{
return this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical ()
{
return this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical (const SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_type& x)
{
this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical (const SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_optional& x)
{
this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_FlrDiffType_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_FlrDiffType () const
{
return this->SimInfiltrationOrVentilation_FlrDiffType_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_FlrDiffType_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_FlrDiffType ()
{
return this->SimInfiltrationOrVentilation_FlrDiffType_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_FlrDiffType (const SimInfiltrationOrVentilation_FlrDiffType_type& x)
{
this->SimInfiltrationOrVentilation_FlrDiffType_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_FlrDiffType (const SimInfiltrationOrVentilation_FlrDiffType_optional& x)
{
this->SimInfiltrationOrVentilation_FlrDiffType_ = x;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_FlrDiffType (::std::auto_ptr< SimInfiltrationOrVentilation_FlrDiffType_type > x)
{
this->SimInfiltrationOrVentilation_FlrDiffType_.set (x);
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TransHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TransHt () const
{
return this->SimInfiltrationOrVentilation_TransHt_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TransHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TransHt ()
{
return this->SimInfiltrationOrVentilation_TransHt_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TransHt (const SimInfiltrationOrVentilation_TransHt_type& x)
{
this->SimInfiltrationOrVentilation_TransHt_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_TransHt (const SimInfiltrationOrVentilation_TransHt_optional& x)
{
this->SimInfiltrationOrVentilation_TransHt_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_NumbDiffPerZone_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_NumbDiffPerZone () const
{
return this->SimInfiltrationOrVentilation_NumbDiffPerZone_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_NumbDiffPerZone_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_NumbDiffPerZone ()
{
return this->SimInfiltrationOrVentilation_NumbDiffPerZone_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_NumbDiffPerZone (const SimInfiltrationOrVentilation_NumbDiffPerZone_type& x)
{
this->SimInfiltrationOrVentilation_NumbDiffPerZone_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_NumbDiffPerZone (const SimInfiltrationOrVentilation_NumbDiffPerZone_optional& x)
{
this->SimInfiltrationOrVentilation_NumbDiffPerZone_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const
{
return this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 ()
{
return this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x)
{
this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x)
{
this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const
{
return this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 ()
{
return this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x)
{
this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x)
{
this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const
{
return this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 ()
{
return this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x)
{
this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x)
{
this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const
{
return this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 ()
{
return this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x)
{
this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x)
{
this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x;
}
const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const
{
return this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 ()
{
return this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x)
{
this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x);
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x)
{
this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x;
}
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
// SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior
//
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior ()
: ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (),
SimInfiltrationOrVentilation_ZoneName_ (this),
SimInfiltrationOrVentilation_ThermstatHt_ (this),
SimInfiltrationOrVentilation_ComfHt_ (this),
SimInfiltrationOrVentilation_TempDiffThreshRpt_ (this),
SimInfiltrationOrVentilation_PowerPerPlume_ (this),
SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (this),
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (this),
SimInfiltrationOrVentilation_FlrDiffType_ (this),
SimInfiltrationOrVentilation_TransHt_ (this),
SimInfiltrationOrVentilation_NumbDiffPerZone_ (this),
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this)
{
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (const RefId_type& RefId)
: ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (RefId),
SimInfiltrationOrVentilation_ZoneName_ (this),
SimInfiltrationOrVentilation_ThermstatHt_ (this),
SimInfiltrationOrVentilation_ComfHt_ (this),
SimInfiltrationOrVentilation_TempDiffThreshRpt_ (this),
SimInfiltrationOrVentilation_PowerPerPlume_ (this),
SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (this),
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (this),
SimInfiltrationOrVentilation_FlrDiffType_ (this),
SimInfiltrationOrVentilation_TransHt_ (this),
SimInfiltrationOrVentilation_NumbDiffPerZone_ (this),
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this)
{
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (x, f, c),
SimInfiltrationOrVentilation_ZoneName_ (x.SimInfiltrationOrVentilation_ZoneName_, f, this),
SimInfiltrationOrVentilation_ThermstatHt_ (x.SimInfiltrationOrVentilation_ThermstatHt_, f, this),
SimInfiltrationOrVentilation_ComfHt_ (x.SimInfiltrationOrVentilation_ComfHt_, f, this),
SimInfiltrationOrVentilation_TempDiffThreshRpt_ (x.SimInfiltrationOrVentilation_TempDiffThreshRpt_, f, this),
SimInfiltrationOrVentilation_PowerPerPlume_ (x.SimInfiltrationOrVentilation_PowerPerPlume_, f, this),
SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (x.SimInfiltrationOrVentilation_DesignEffectAreaDiff_, f, this),
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (x.SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_, f, this),
SimInfiltrationOrVentilation_FlrDiffType_ (x.SimInfiltrationOrVentilation_FlrDiffType_, f, this),
SimInfiltrationOrVentilation_TransHt_ (x.SimInfiltrationOrVentilation_TransHt_, f, this),
SimInfiltrationOrVentilation_NumbDiffPerZone_ (x.SimInfiltrationOrVentilation_NumbDiffPerZone_, f, this),
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this),
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this),
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this),
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this),
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this)
{
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (e, f | ::xml_schema::flags::base, c),
SimInfiltrationOrVentilation_ZoneName_ (this),
SimInfiltrationOrVentilation_ThermstatHt_ (this),
SimInfiltrationOrVentilation_ComfHt_ (this),
SimInfiltrationOrVentilation_TempDiffThreshRpt_ (this),
SimInfiltrationOrVentilation_PowerPerPlume_ (this),
SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (this),
SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (this),
SimInfiltrationOrVentilation_FlrDiffType_ (this),
SimInfiltrationOrVentilation_TransHt_ (this),
SimInfiltrationOrVentilation_NumbDiffPerZone_ (this),
SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this),
SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this)
{
if ((f & ::xml_schema::flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false, true);
this->parse (p, f);
}
}
void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::flags f)
{
this->::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings::parse (p, f);
for (; p.more_content (); p.next_content (false))
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// SimInfiltrationOrVentilation_ZoneName
//
if (n.name () == "SimInfiltrationOrVentilation_ZoneName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< SimInfiltrationOrVentilation_ZoneName_type > r (
SimInfiltrationOrVentilation_ZoneName_traits::create (i, f, this));
if (!this->SimInfiltrationOrVentilation_ZoneName_)
{
this->SimInfiltrationOrVentilation_ZoneName_.set (r);
continue;
}
}
// SimInfiltrationOrVentilation_ThermstatHt
//
if (n.name () == "SimInfiltrationOrVentilation_ThermstatHt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_ThermstatHt_)
{
this->SimInfiltrationOrVentilation_ThermstatHt_.set (SimInfiltrationOrVentilation_ThermstatHt_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_ComfHt
//
if (n.name () == "SimInfiltrationOrVentilation_ComfHt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_ComfHt_)
{
this->SimInfiltrationOrVentilation_ComfHt_.set (SimInfiltrationOrVentilation_ComfHt_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_TempDiffThreshRpt
//
if (n.name () == "SimInfiltrationOrVentilation_TempDiffThreshRpt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_TempDiffThreshRpt_)
{
this->SimInfiltrationOrVentilation_TempDiffThreshRpt_.set (SimInfiltrationOrVentilation_TempDiffThreshRpt_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_PowerPerPlume
//
if (n.name () == "SimInfiltrationOrVentilation_PowerPerPlume" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_PowerPerPlume_)
{
this->SimInfiltrationOrVentilation_PowerPerPlume_.set (SimInfiltrationOrVentilation_PowerPerPlume_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_DesignEffectAreaDiff
//
if (n.name () == "SimInfiltrationOrVentilation_DesignEffectAreaDiff" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_)
{
this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_.set (SimInfiltrationOrVentilation_DesignEffectAreaDiff_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_DiffSlotAngFromVertexical
//
if (n.name () == "SimInfiltrationOrVentilation_DiffSlotAngFromVertexical" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_)
{
this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_.set (SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_FlrDiffType
//
if (n.name () == "SimInfiltrationOrVentilation_FlrDiffType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
::std::auto_ptr< SimInfiltrationOrVentilation_FlrDiffType_type > r (
SimInfiltrationOrVentilation_FlrDiffType_traits::create (i, f, this));
if (!this->SimInfiltrationOrVentilation_FlrDiffType_)
{
this->SimInfiltrationOrVentilation_FlrDiffType_.set (r);
continue;
}
}
// SimInfiltrationOrVentilation_TransHt
//
if (n.name () == "SimInfiltrationOrVentilation_TransHt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_TransHt_)
{
this->SimInfiltrationOrVentilation_TransHt_.set (SimInfiltrationOrVentilation_TransHt_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_NumbDiffPerZone
//
if (n.name () == "SimInfiltrationOrVentilation_NumbDiffPerZone" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_NumbDiffPerZone_)
{
this->SimInfiltrationOrVentilation_NumbDiffPerZone_.set (SimInfiltrationOrVentilation_NumbDiffPerZone_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2
//
if (n.name () == "SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_)
{
this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2
//
if (n.name () == "SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_)
{
this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2
//
if (n.name () == "SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_)
{
this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2
//
if (n.name () == "SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_)
{
this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this));
continue;
}
}
// SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2
//
if (n.name () == "SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral")
{
if (!this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_)
{
this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this));
continue;
}
}
break;
}
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior* SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (*this, f, c);
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
operator= (const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior& x)
{
if (this != &x)
{
static_cast< ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings& > (*this) = x;
this->SimInfiltrationOrVentilation_ZoneName_ = x.SimInfiltrationOrVentilation_ZoneName_;
this->SimInfiltrationOrVentilation_ThermstatHt_ = x.SimInfiltrationOrVentilation_ThermstatHt_;
this->SimInfiltrationOrVentilation_ComfHt_ = x.SimInfiltrationOrVentilation_ComfHt_;
this->SimInfiltrationOrVentilation_TempDiffThreshRpt_ = x.SimInfiltrationOrVentilation_TempDiffThreshRpt_;
this->SimInfiltrationOrVentilation_PowerPerPlume_ = x.SimInfiltrationOrVentilation_PowerPerPlume_;
this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_ = x.SimInfiltrationOrVentilation_DesignEffectAreaDiff_;
this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ = x.SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_;
this->SimInfiltrationOrVentilation_FlrDiffType_ = x.SimInfiltrationOrVentilation_FlrDiffType_;
this->SimInfiltrationOrVentilation_TransHt_ = x.SimInfiltrationOrVentilation_TransHt_;
this->SimInfiltrationOrVentilation_NumbDiffPerZone_ = x.SimInfiltrationOrVentilation_NumbDiffPerZone_;
this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_;
}
return *this;
}
SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::
~SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace ResourcesGeneral
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| 55.375158
| 256
| 0.784418
|
EnEff-BIM
|
ff81008893ca08c20159b89ea87eb5b18719f820
| 1,013
|
cpp
|
C++
|
802.cpp
|
zfang399/LeetCode-Problems
|
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
|
[
"MIT"
] | 8
|
2018-10-31T11:00:19.000Z
|
2020-07-31T05:25:06.000Z
|
802.cpp
|
zfang399/LeetCode-Problems
|
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
|
[
"MIT"
] | null | null | null |
802.cpp
|
zfang399/LeetCode-Problems
|
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
|
[
"MIT"
] | 2
|
2018-05-31T11:29:22.000Z
|
2019-09-11T06:34:40.000Z
|
class Solution {
public:
vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
bool finish = false;
vector<bool> outed(graph.size(), false);
while(!finish){
finish = true;
map<int,bool> zeroout;
for(int i = 0; i < graph.size(); i++){
if(graph[i].size() == 0 && !outed[i]){
outed[i] = true;
finish = false;
zeroout[i] = true;
}
}
for(int i = 0; i < graph.size(); i++){
for(int j = 0; j < graph[i].size(); j++){
if(zeroout[graph[i][j]]){
graph[i].erase(graph[i].begin() + j);
j--;
}
}
}
}
vector<int> ans;
for(int i = 0; i < graph.size(); i++){
if(graph[i].size() == 0){
ans.push_back(i);
}
}
return ans;
}
};
| 27.378378
| 63
| 0.358342
|
zfang399
|
ff82459288558066e464c5d47a60109a8bf0da7d
| 12,545
|
cpp
|
C++
|
source/Networking.cpp
|
MrPh1l/RocketPlugin
|
dab038ee6cd448df05805d894f45abefabbeeec3
|
[
"MIT"
] | null | null | null |
source/Networking.cpp
|
MrPh1l/RocketPlugin
|
dab038ee6cd448df05805d894f45abefabbeeec3
|
[
"MIT"
] | null | null | null |
source/Networking.cpp
|
MrPh1l/RocketPlugin
|
dab038ee6cd448df05805d894f45abefabbeeec3
|
[
"MIT"
] | null | null | null |
// Networking.cpp
// General networking calls for the RocketPlugin plugin.
//
// Author: Stanbroek
// Version: 0.6.3 15/7/20
#include "Networking.h"
#pragma comment(lib,"Ws2_32.lib")
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi.lib")
#include <regex>
/// <summary>Creates a thread to call functions on.</summary>
WorkerThread::WorkerThread()
{
wantExit = false;
thread = std::unique_ptr<std::thread>(new std::thread(std::bind(&WorkerThread::Entry, this)));
}
/// <summary>Waits for the thread to finish and removes it.</summary>
WorkerThread::~WorkerThread()
{
{
std::lock_guard<std::mutex> lock(queueMutex);
wantExit = true;
queuePending.notify_one();
}
thread->join();
}
/// <summary>Adds job_t's to the job queue to be execute on a sepperate thread.</summary>
/// <param name="job">function to be executed</param>
void WorkerThread::addJob(job_t job)
{
std::lock_guard<std::mutex> lock(queueMutex);
jobQueue.push_back(job);
queuePending.notify_one();
}
/// <summary>Main loop of the thread.</summary>
void WorkerThread::Entry()
{
job_t job;
while (true) {
{
std::unique_lock<std::mutex> lock(queueMutex);
queuePending.wait(lock, [&]() { return wantExit || !jobQueue.empty(); });
if (wantExit) {
return;
}
job = jobQueue.front();
jobQueue.pop_front();
}
job();
}
}
/// <summary>Checks whether the given IP is a valid ipv4.</summary>
/// <param name="addr">IP to validate</param>
/// <returns>Bool with is the IP is a valid ipv4 address</returns>
bool Networking::isValidIPv4(const char* IPAddr)
{
const std::regex ipv4_regex("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
std::string string = IPAddr;
std::smatch match;
if (std::regex_match(string, match, ipv4_regex, std::regex_constants::match_flag_type::format_default)) {
return true;
}
return false;
}
/// <summary>Checks whether the given IP is not an internal ipv4.</summary>
/// <param name="IPAddr">IP to validate</param>
/// <returns>Bool with is the IP is not an internal ipv4 address</returns>
bool Networking::isInternalIPv4(const char* IPAddr)
{
// 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
if (std::strncmp(IPAddr, "192.168.", 8) == 0) {
return true;
}
// 10.0.0.0 - 10.255.255.255 (10/8 prefix)
if (std::strncmp(IPAddr, "10.", 3) == 0) {
return true;
}
// 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
if (std::strncmp(IPAddr, "172.", 4) == 0) {
int i = atoi(IPAddr + 4);
if ((16 <= i) && (i <= 31)) {
return true;
}
}
return false;
}
/// <summary>Checks whether the given IP is in the Hamachi ipv4 address space.</summary>
/// <param name="IPAddr">IP to validate</param>
/// <returns>Bool with is the IP is in the Hamachi ipv4 address space</returns>
bool Networking::isHamachiAddr(const char* IPAddr)
{
// 25.0.0.0 - 25.255.255.255 (10/8 prefix)
if (std::strncmp(IPAddr, "25.", 3) == 0) {
return true;
}
return false;
}
/// <summary>Checks whether the given address is a valid domain name.</summary>
/// <remarks>https://regexr.com/3au3g</remarks>
/// <param name="addr">address to validate</param>
/// <returns>Bool with is the address is a valid domain name</returns>
bool Networking::isValidDomainName(const char* addr)
{
const std::regex domainname_regex("^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$");
std::string string = addr;
std::smatch match;
if (std::regex_match(string, match, domainname_regex, std::regex_constants::match_flag_type::format_default)) {
return true;
}
return false;
}
/// <summary>Gets the internal IP address of the user.</summary>
/// <returns>Internal IP address</returns>
std::string Networking::getInternalIPAddress()
{
int i;
std::string internalIPAddress;
// Variables used by GetIpAddrTable
PMIB_IPADDRTABLE pIPAddrTable;
DWORD dwSize = 0;
IN_ADDR IPAddr;
// Before calling AddIPAddress we use GetIpAddrTable to get
// an adapter to which we can add the IP.
pIPAddrTable = (MIB_IPADDRTABLE*)malloc(sizeof(MIB_IPADDRTABLE));
if (pIPAddrTable) {
// Make an initial call to GetIpAddrTable to get the
// necessary size into the dwSize variable
if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
free(pIPAddrTable);
pIPAddrTable = (MIB_IPADDRTABLE*)malloc(dwSize);
}
}
if (pIPAddrTable) {
// Make a second call to GetIpAddrTable to get the actual data we want
if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == NO_ERROR) {
for (i = 0; i < (int)pIPAddrTable->dwNumEntries; i++) {
if (pIPAddrTable->table[i].wType & MIB_IPADDR_PRIMARY) {
IPAddr.S_un.S_addr = (ULONG)pIPAddrTable->table[i].dwAddr;
char ipBuf[sizeof "255.255.255.255"];
internalIPAddress = inet_ntop(AF_INET, &IPAddr, ipBuf, sizeof ipBuf);
if (!isValidIPv4(internalIPAddress.c_str()) || !isInternalIPv4(internalIPAddress.c_str())) {
internalIPAddress.clear();
}
}
}
}
free(pIPAddrTable);
pIPAddrTable = NULL;
}
return internalIPAddress;
}
/// <summary>Tries to parse the external IP address from a http responce.</summary>
/// <param name="buffer">Http responce</param>
/// <returns>External IP address</returns>
std::string parseExternalIPAddressFromResponce(std::string buffer)
{
size_t contentLengthOffset = buffer.find("Content-Length:") + 16;
size_t contentLengthCount = buffer.find('\n', contentLengthOffset);
int contentLength = strtol(buffer.substr(contentLengthOffset, contentLengthCount).c_str(), NULL, 10);
size_t addrOffset = buffer.find("\r\n\r\n");
if (addrOffset == std::string::npos) {
return "";
}
return buffer.substr(addrOffset + 4, contentLength);
}
/// <summary>Tries to get the external IP address.</summary>
/// <param name="addr">Contains the external IP address when threaded</param>
/// <param name="threaded">Whether the action should be executed on another thread</param>
/// <returns>External IP address</returns>
std::string Networking::getExternalIPAddress(std::string host, std::string* addr, bool threaded)
{
if (threaded && addr == nullptr) {
return "";
}
if (threaded) {
std::thread(getExternalIPAddress, host, addr, false).detach();
return "";
}
// Initialize Winsock.
WSADATA wsaData = { 0 };
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
return "";
}
// Create a socket for sending data.
SOCKET sendSocket = INVALID_SOCKET;
sendSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sendSocket == INVALID_SOCKET) {
WSACleanup();
return "";
}
// Set up the addrDest structure with the IP address and port of the receiver.
addrinfo hints;
addrinfo* result = NULL;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(host.c_str(), NULL, &hints, &result) != 0) {
closesocket(sendSocket);
WSACleanup();
return "";
}
sockaddr_in addrDest;
addrDest = *(sockaddr_in*)result->ai_addr;
addrDest.sin_family = AF_INET;
addrDest.sin_port = htons(80);
if (connect(sendSocket, (sockaddr*)&addrDest, sizeof addrDest) == SOCKET_ERROR) {
closesocket(sendSocket);
WSACleanup();
return "";
}
// Send a datagram to the receiver
std::string sendBuf = "GET / HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n";
if (sendto(sendSocket, sendBuf.c_str(), (int)sendBuf.size(), 0, (sockaddr*)&addrDest, (int)sizeof addrDest) == SOCKET_ERROR) {
closesocket(sendSocket);
WSACleanup();
return "";
}
// Wait until data received or timeout.
fd_set fds;
FD_ZERO(&fds);
FD_SET(sendSocket, &fds);
struct timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
iResult = select(NULL, &fds, NULL, NULL, &tv);
if (iResult == SOCKET_ERROR) {
closesocket(sendSocket);
WSACleanup();
return "";
}
// Connection timedout.
else if (iResult == 0) {
closesocket(sendSocket);
WSACleanup();
return "";
}
// Set up the addrRetDest structure for the IP address and port from the receiver.
sockaddr_in addrRetDest;
int addrRetDestSize = sizeof addrRetDest;
// Recieve a datagram from the receiver.
char recvBuf[1024];
int recvBufLen = 1024;
if (recvfrom(sendSocket, recvBuf, recvBufLen, 0, (sockaddr*)&addrRetDest, &addrRetDestSize) == SOCKET_ERROR) {
closesocket(sendSocket);
WSACleanup();
return "";
}
closesocket(sendSocket);
WSACleanup();
std::string externalIPAddress = parseExternalIPAddressFromResponce(recvBuf);
if (!isValidIPv4(externalIPAddress.c_str()) || isInternalIPv4(externalIPAddress.c_str())) {
return "";
}
if (addr != nullptr) {
*addr = externalIPAddress;
}
return externalIPAddress;
}
/// <summary>Tries ping host to see if they are reachable.</summary>
/// <param name="IP">IP address of the host</param>
/// <param name="port">Port of the server</param>
/// <param name="threaded">Whether the action should be executed on another thread</param>
/// <returns>Bool with if the host was reachable</returns>
bool Networking::pingHost(std::string IP, unsigned short port, HostStatus* result, bool threaded)
{
if (threaded && result == nullptr) {
return false;
}
if (threaded) {
if (result != nullptr) {
*result = HostStatus::HOST_BUSY;
}
std::thread(pingHost, IP, port, result, false).detach();
return false;
}
// Initialize Winsock.
WSADATA wsaData = { 0 };
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
if (result != nullptr) {
*result = HostStatus::HOST_ERROR;
}
return false;
}
// Create a socket for sending data.
SOCKET sendSocket = INVALID_SOCKET;
sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sendSocket == INVALID_SOCKET) {
WSACleanup();
if (result != nullptr) {
*result = HostStatus::HOST_ERROR;
}
return false;
}
// Set up the addrDest structure with the IP address and port of the receiver.
sockaddr_in addrDest;
addrDest.sin_family = AF_INET;
addrDest.sin_port = htons(port);
if (inet_pton(addrDest.sin_family, IP.c_str(), &addrDest.sin_addr.s_addr) != 1) {
closesocket(sendSocket);
WSACleanup();
if (result != nullptr) {
*result = HostStatus::HOST_ERROR;
}
return false;
}
// Send a datagram to the receiver
const char* sendBuf = "Hey host guy are you alive?";
if (sendto(sendSocket, sendBuf, (int)strlen(sendBuf), 0, (sockaddr*)&addrDest, (int)sizeof addrDest) == SOCKET_ERROR) {
closesocket(sendSocket);
WSACleanup();
if (result != nullptr) {
*result = HostStatus::HOST_ERROR;
}
return false;
}
// Wait until data received or timeout.
fd_set fds;
FD_ZERO(&fds);
FD_SET(sendSocket, &fds);
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
iResult = select(NULL, &fds, NULL, NULL, &tv);
if (iResult == SOCKET_ERROR) {
closesocket(sendSocket);
WSACleanup();
if (result != nullptr) {
*result = HostStatus::HOST_ERROR;
}
return false;
}
// Connection timedout.
else if (iResult == 0) {
closesocket(sendSocket);
WSACleanup();
if (result != nullptr) {
*result = HostStatus::HOST_TIMEOUT;
}
return false;
}
closesocket(sendSocket);
WSACleanup();
if (result != nullptr) {
*result = HostStatus::HOST_ONLINE;
}
return true;
}
| 29.940334
| 142
| 0.612914
|
MrPh1l
|
ff85d5202952e4ee43c758bcdeb18564c49a3419
| 4,627
|
cpp
|
C++
|
AngioLib/Segment.cpp
|
ltedgar-ed/AngioFE_original
|
2a57f8dfec3bc31aa63bf33719359676899bbb2a
|
[
"MIT"
] | null | null | null |
AngioLib/Segment.cpp
|
ltedgar-ed/AngioFE_original
|
2a57f8dfec3bc31aa63bf33719359676899bbb2a
|
[
"MIT"
] | null | null | null |
AngioLib/Segment.cpp
|
ltedgar-ed/AngioFE_original
|
2a57f8dfec3bc31aa63bf33719359676899bbb2a
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////////////////
// Segment.cpp
///////////////////////////////////////////////////////////////////////
// Include:
#include "stdafx.h"
#include "Segment.h"
#include "vect3.h"
#include "angio3d.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
Segment::Segment() // Constructor for SEGMENT object
{
x[0]= 0; // x, y, z - Initialize the coordinates of the tips to 0
x[1]= 0;
y[0]= 0;
y[1]= 0;
z[0]= 0;
z[1]= 0;
x0[0]= 0; // x, y, z - Initialize the coordinates of the tips to 0
x0[1]= 0;
y0[0]= 0;
y0[1]= 0;
z0[0]= 0;
z0[1]= 0;
tip[0]= 0; // tip - Initialize the activity of the tips to 0
tip[1]= 0;
length = 0; // length - Initialize the length of the segment to 0
// phi1 = 0; // phi1, phi2 - Initialize the orientation angles of the segment to 0
// phi2 = 0;
label = 0; // label - Initialize label to 0
vessel = 0; // vessel - Initialize vessel to 0
BCdead = 0; // BCdead - Set boundary condition indicator to 'false'
TofBirth = 0; // TofBirth - Initialize time of birth to 0
Recent_branch = 0; // Recent_branch - Initialize branching indicator to 0
init_branch = false; // init)branch - Set initial branching flag to 'false'
sprout = 0; // sprout - Initialize sprout to 0
anast = 0;
elem_tagged = false;
bdyf_id[0] = -1;
bdyf_id[1] = -1;
mark_of_death = false;
death_label = 0;
tip_BC[0] = 0;
tip_BC[1] = 0;
tip_elem[0] = -1;
tip_elem[1] = -1;
seg_num = 0;
seg_conn[0][0] = 0;
seg_conn[0][1] = 0;
seg_conn[1][0] = 0;
seg_conn[1][1] = 0;
//line_num = 0;
}
Segment::~Segment() // Destructor for SEGMENT object
{
}
void Segment::findlength()
{
double new_length = sqrt(pow((x[1] - x[0]),2) + pow((y[1] - y[0]),2) + pow((z[1] - z[0]),2));
if (length < 0.0)
length = -new_length;
else
length = new_length;
uvect.x = x[1] - x[0];
uvect.y = y[1] - y[0];
uvect.z = z[1] - z[0];
if (length != 0)
uvect = uvect/uvect.norm();
return;
}
void Segment::findunit()
{
uvect.x = x[1] - x[0];
uvect.y = y[1] - y[0];
uvect.z = z[1] - z[0];
if (uvect.norm() != 0.0)
uvect = uvect/uvect.norm();
return;
}
//void Segment::findphi()
//{
// vect3 vvect, xvvect, zvvect;
//
// if (length == 0.0)
// return;
//
// vvect.x = x[1] - x[0];
// vvect.y = y[1] - y[0];
// vvect.z = z[1] - z[0];
// vvect = vvect/vvect.norm();
//
// xvvect = vect3(vvect.x, vvect.y, 0);
//
//// double phi10 = phi1;
//// double phi20 = phi2;
//
// // Calculate phi2
// phi2 = asin(vvect.z);
//
// double alt_phi2 = 0.;
//
// if (vvect.x < 0)
// if (phi2 > 0)
// alt_phi2 = pi - phi2;
// else if (phi2 < 0)
// alt_phi2 = -pi - phi2;
//
// if (fabs(phi20 - alt_phi2) < fabs(phi20 - phi2))
// phi2 = alt_phi2;
//
// // Calculate phi1
// double phi1_dot = 0.;
// phi1_dot = xvvect*vect3(1,0,0);
//
// if (cos(phi2) != 0.0)
// phi1 = acos(vvect.x/cos(phi2));
// else
// phi1 = acos(phi1_dot);
//
// if (vvect.x/cos(phi2) > 1)
// phi1 = 0;
// else if (vvect.x/cos(phi2) < -1)
// if (phi10 > 0)
// phi1 = pi;
// else if (phi10 < 0)
// phi1 = -pi;
//
// if (vvect.y < 0)
// phi1 = -phi1;
//
// if (vvect.norm() == 0.){
// phi1 = phi10;
// phi2 = phi20;}
//
// if (vvect.y == 0.)
// phi1 = phi10;
//
// if (vvect.z == 0.)
// phi2 = 0.;
//
// return;
//}
| 26.289773
| 236
| 0.376054
|
ltedgar-ed
|
ff8c88d46d362fdb777526683db6658185e2c709
| 1,168
|
cpp
|
C++
|
cf/Div2/D/Good Sequences/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
cf/Div2/D/Good Sequences/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
cf/Div2/D/Good Sequences/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
// Turn off synchronization between cin/cout and scanf/printf
ios_base::sync_with_stdio(false);
// Disable automatic flush of cout when reading from cin cin.tie(0);
cin.tie(0);
int n;
cin >> n;
vector<pair<int, int>>in;
vector<vector<int>>div(1e5+1);
vector<int>primes;
for (int i = 2; i <= 1e5; ++i) {
for(int p : primes){
if(p>400){ break;}
if(i%p==0){div[i].push_back(p);
if(div[i/p].size()==0){
div[i].push_back(i/p);
}}
}
if(!div[i].size()){primes.push_back(i);}
}
vector<int>mem(1e5+1, 0);
for (int i = 0; i < n; ++i) {
int cur;
cin >> cur;
if(div[cur].size()==0&&cur!=1){
mem[cur]++;
}
int newV=0;
for (int j = 0; j < div[cur].size(); ++j) {
newV=max(newV, mem[div[cur][j]]+1);
}
for (int j = 0; j < div[cur].size(); ++j) {
mem[div[cur][j]]=newV;
}
}
cout << max((int)1, *max_element(mem.begin(), mem.end()));
}
| 23.836735
| 72
| 0.472603
|
wdjpng
|
ff8cd1ddb41d789a274b35ed9e4c6a3ebe0e7d0c
| 478
|
cc
|
C++
|
page_240_44.cc
|
coder52/Cpp-Primer-Solutions-2013
|
e68d8a8cd4f12b1dbc269b152d955b5ebcf6d9aa
|
[
"MIT"
] | null | null | null |
page_240_44.cc
|
coder52/Cpp-Primer-Solutions-2013
|
e68d8a8cd4f12b1dbc269b152d955b5ebcf6d9aa
|
[
"MIT"
] | 42
|
2021-08-08T10:36:33.000Z
|
2021-08-29T20:35:37.000Z
|
page_240_44.cc
|
coder52/Cpp-Primer-Solutions-2013
|
e68d8a8cd4f12b1dbc269b152d955b5ebcf6d9aa
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
using namespace::std;
/* Page 240
Exercise 6.44: Rewrite the isShorter function from § 6.2.2 (p. 211) to be inline.
*/
// Put inline and constexpr Functions in Header Files.
inline const string &
shorterString(const string &s1, const string &s2){
return s1.size() <= s2.size() ? s1 : s2;
}
int main(int argc, char const *argv[]) {
string s1 = "aaaaaa";
string s2 = "bbbb";
std::cout<<(shorterString(s1,s2));
return 0;
}
| 17.703704
| 82
| 0.661088
|
coder52
|
ff8e893e905ad43b8b7ed22cc92087f7c96b1b96
| 3,824
|
cpp
|
C++
|
host_runtimes/linux_no_cma_test/test_ops.cpp
|
thenextged/uRDAI
|
119742ba032588586653d83937999b497c0a1ee9
|
[
"Apache-2.0"
] | 3
|
2020-07-15T07:31:25.000Z
|
2020-07-15T07:31:29.000Z
|
host_runtimes/linux_no_cma_test/test_ops.cpp
|
thenextged/uRDAI
|
119742ba032588586653d83937999b497c0a1ee9
|
[
"Apache-2.0"
] | null | null | null |
host_runtimes/linux_no_cma_test/test_ops.cpp
|
thenextged/uRDAI
|
119742ba032588586653d83937999b497c0a1ee9
|
[
"Apache-2.0"
] | null | null | null |
#include "rdai_api.h"
// ================= DATA
extern RDAI_Platform clockwork_platform;
static RDAI_Device clockwork_device = {
{ 1 },
{
{ "aha" },
{ "halide_hardware" },
{ "conv_3_3_clockwork" },
1
},
&clockwork_platform,
NULL,
1
};
static RDAI_Device *clockwork_platform_devices[2] = { &clockwork_device, NULL };
RDAI_Platform clockwork_platform = {
RDAI_PlatformType::RDAI_CLOCKWORK_PLATFORM,
{ 0 },
NULL,
clockwork_platform_devices
};
// ================= Helpers
static RDAI_Status make_status_error( RDAI_ErrorReason reason = RDAI_REASON_UNIMPLEMENTED )
{
RDAI_Status status;
status.status_code = RDAI_STATUS_ERROR;
status.error_reason = reason;
return status;
}
static RDAI_Status make_status_ok()
{
RDAI_Status status;
status.status_code = RDAI_STATUS_OK;
return status;
}
// ================= OPs
static RDAI_MemObject * op_mem_allocate( RDAI_MemObjectType mem_object_type,
size_t size,
RDAI_Device *device)
{
return NULL;
}
static RDAI_Status op_mem_free( RDAI_MemObject *mem_object )
{
return make_status_error();
}
static RDAI_Status op_mem_copy( RDAI_MemObject *src, RDAI_MemObject *dest )
{
return make_status_error();
}
static RDAI_Status op_mem_copy_async( RDAI_MemObject *src, RDAI_MemObject *dest )
{
return make_status_error();
}
static RDAI_MemObject *op_mem_crop( RDAI_MemObject *src, size_t offset, size_t cropped_size )
{
return NULL;
}
static RDAI_Status op_mem_free_crop( RDAI_MemObject *obj )
{
return make_status_error();
}
static RDAI_Platform *op_platform_create( void )
{
return &clockwork_platform;
}
static RDAI_Status op_platform_destroy( RDAI_Platform *platform )
{
return make_status_ok();
}
static RDAI_Status op_platform_init( RDAI_Platform *platform, void *user_data )
{
return make_status_error();
}
static RDAI_Status op_platform_deinit( RDAI_Platform *platform, void *user_data )
{
return make_status_error();
}
static RDAI_Status op_device_init( RDAI_Device *device, void *user_data )
{
return make_status_error();
}
static RDAI_Status op_device_deinit( RDAI_Device *device, void *user_data )
{
return make_status_error();
}
static RDAI_Status op_device_run( RDAI_Device *device, RDAI_MemObject **mem_object_list )
{
if( device && mem_object_list && mem_object_list[0] ) {
size_t num_els = 1;
while(mem_object_list[num_els]) num_els++;
RDAI_MemObject *output = mem_object_list[num_els - 1];
for(size_t i = 0; i < output->size; i++) {
output->host_ptr[i] = i & 0xFF;
}
return make_status_ok();
}
return make_status_error();
}
static RDAI_Status op_device_run_async( RDAI_Device *device, RDAI_MemObject **mem_object_list )
{
return op_device_run( device, mem_object_list );
}
static RDAI_Status op_sync( RDAI_AsyncHandle *handle )
{
if(handle && handle->platform) {
return make_status_ok();
}
return make_status_error();
}
// ======================== PlatformOps
RDAI_PlatformOps ops = {
.mem_allocate = op_mem_allocate,
.mem_free = op_mem_free,
.mem_copy = op_mem_copy,
.mem_copy_async = op_mem_copy_async,
.mem_crop = op_mem_crop,
.mem_free_crop = op_mem_free_crop,
.platform_create = op_platform_create,
.platform_destroy = op_platform_destroy,
.platform_init = op_platform_init,
.platform_deinit = op_platform_deinit,
.device_init = op_device_init,
.device_deinit = op_device_deinit,
.device_run = op_device_run,
.device_run_async = op_device_run_async,
.sync = op_sync
};
| 24.512821
| 95
| 0.667103
|
thenextged
|
ff91193a900bc6e04002c3c74880441102d4350f
| 4,956
|
cpp
|
C++
|
arduino-ntpd/GPSTimeSource.cpp
|
jonsl/arduino_sntp
|
b19220e877dcd64edc4b4c47ca9e00585abaed2b
|
[
"MIT"
] | 5
|
2020-12-17T13:07:46.000Z
|
2021-09-02T16:48:44.000Z
|
arduino-ntpd/GPSTimeSource.cpp
|
jonsl/arduino_sntp
|
b19220e877dcd64edc4b4c47ca9e00585abaed2b
|
[
"MIT"
] | null | null | null |
arduino-ntpd/GPSTimeSource.cpp
|
jonsl/arduino_sntp
|
b19220e877dcd64edc4b4c47ca9e00585abaed2b
|
[
"MIT"
] | 1
|
2019-02-25T09:40:09.000Z
|
2019-02-25T09:40:09.000Z
|
/*
* File: GPSTimeSource.cpp
* Description:
* A time source that reads the time from a NMEA-compliant GPS receiver.
* Author: Mooneer Salem <mooneer@gmail.com>
* License: New BSD License
*/
#include "config.h"
#ifdef ETH_RX_PIN
#include "utility/w5100.h"
#endif // ETH_RX_PIN
#include "GPSTimeSource.h"
#include "TimeUtilities.h"
GPSTimeSource *GPSTimeSource::Singleton_ = NULL;
volatile uint32_t overflows = 0;
volatile uint32_t overflowsRecv = 0;
void GPSTimeSource::enableInterrupts()
{
#ifdef ETH_RX_PIN
// Enable Ethernet interrupt first to reduce difference between the two timers.
// NOTE: NTP server must _always_ be initialized first to ensure that it occupies socket 0.
W5100.writeIMR(0x01);
#endif
Singleton_ = this;
pinMode(PPS_PIN, INPUT);
TCCR4A = 0 ; // Normal counting mode
TCCR4B = B010; // set prescale bits
TCCR4B |= _BV(ICES4); // enable input capture when pin goes high
TIMSK4 |= _BV(ICIE4); // enable input capture interrupt for timer 4
TIMSK4 |= _BV(TOIE4); // overflow interrupt
#ifdef ETH_RX_PIN
pinMode(ETH_RX_PIN, INPUT);
TCCR5A = 0 ; // Normal counting mode
TCCR5B = B010; // set prescale bits
// enable input capture when pin goes low (default).
TIMSK5 |= _BV(ICIE5); // enable input capture interrupt for timer 5
TIMSK5 |= _BV(TOIE5); // overflow interrupt
#endif
Serial.println("interrupts enabled");
}
void GPSTimeSource::PpsInterrupt()
{
// Get saved time value.
uint32_t tmrVal = (overflows << 16) | ICR4;
GPSTimeSource::Singleton_->microsecondsPerSecond_ =
(GPSTimeSource::Singleton_->microsecondsPerSecond_ +
(tmrVal - Singleton_->millisecondsOfLastUpdate_)) / 2;
GPSTimeSource::Singleton_->secondsSinceEpoch_++;
GPSTimeSource::Singleton_->fractionalSecondsSinceEpoch_ = 0;
GPSTimeSource::Singleton_->millisecondsOfLastUpdate_ = tmrVal;
}
void GPSTimeSource::RecvInterrupt()
{
// Get saved time value.
uint32_t tmrVal = (overflowsRecv << 16) | ICR5;
uint32_t tmrDiff = tmrVal - GPSTimeSource::Singleton_->millisecondsOfLastUpdate_;
GPSTimeSource::Singleton_->fractionalSecondsOfRecv_ =
(tmrDiff % GPSTimeSource::Singleton_->microsecondsPerSecond_) *
(0xFFFFFFFF / GPSTimeSource::Singleton_->microsecondsPerSecond_);
GPSTimeSource::Singleton_->secondsOfRecv_ = GPSTimeSource::Singleton_->secondsSinceEpoch_;
if (tmrDiff > GPSTimeSource::Singleton_->microsecondsPerSecond_)
{
++GPSTimeSource::Singleton_->secondsOfRecv_;
}
}
ISR(TIMER4_OVF_vect)
{
++overflows;
}
ISR(TIMER4_CAPT_vect)
{
GPSTimeSource::PpsInterrupt();
}
ISR(TIMER5_OVF_vect)
{
++overflowsRecv;
}
ISR(TIMER5_CAPT_vect)
{
GPSTimeSource::RecvInterrupt();
}
void GPSTimeSource::updateFractionalSeconds_(void)
{
// Calculate new fractional value based on system runtime
// since the EM-406 does not seem to return anything other than whole seconds.
uint32_t lastTime = (overflows << 16) | TCNT4;
uint32_t millisecondDifference = lastTime - millisecondsOfLastUpdate_;
fractionalSecondsSinceEpoch_ = (millisecondDifference % microsecondsPerSecond_) * (0xFFFFFFFF / microsecondsPerSecond_);
}
void GPSTimeSource::now(uint32_t *secs, uint32_t *fract)
{
while (dataSource_.available())
{
int c = dataSource_.read();
if (gps_.encode(c))
{
// Grab time from now-valid data.
int year;
byte month, day, hour, minutes, second, hundredths;
unsigned long fix_age;
gps_.crack_datetime(&year, &month, &day,
&hour, &minutes, &second, &hundredths, &fix_age);
gps_.f_get_position(&lat_, &long_);
// We don't want to use the time we've received if
// the fix is invalid.
if (fix_age != TinyGPS::GPS_INVALID_AGE && fix_age < 5000 && year >= 2013)
{
uint32_t tempSeconds =
TimeUtilities::numberOfSecondsSince1900Epoch(
year, month, day, hour, minutes, second);
if (tempSeconds != secondsSinceEpoch_)
{
secondsSinceEpoch_ = tempSeconds;
hasLocked_ = true;
}
}
else
{
// Set time to 0 if invalid.
// TODO: does the interface need an accessor for "invalid time"?
secondsSinceEpoch_ = 0;
fractionalSecondsSinceEpoch_ = 0;
}
}
}
updateFractionalSeconds_();
if (secs)
{
*secs = secondsSinceEpoch_;
}
if (fract)
{
*fract = fractionalSecondsSinceEpoch_;
}
}
| 30.592593
| 124
| 0.622074
|
jonsl
|
ff93253ed2e202bae31bc1427bd09cdbc0d4b6bb
| 4,565
|
cpp
|
C++
|
Projects/Core/EditContext.cpp
|
krisl/quip
|
a386f8bcecf59de9e9c7a6d6d8c077e49b72fb19
|
[
"MIT"
] | null | null | null |
Projects/Core/EditContext.cpp
|
krisl/quip
|
a386f8bcecf59de9e9c7a6d6d8c077e49b72fb19
|
[
"MIT"
] | null | null | null |
Projects/Core/EditContext.cpp
|
krisl/quip
|
a386f8bcecf59de9e9c7a6d6d8c077e49b72fb19
|
[
"MIT"
] | 1
|
2020-07-11T22:45:16.000Z
|
2020-07-11T22:45:16.000Z
|
#include "EditContext.hpp"
#include "Document.hpp"
#include "EditMode.hpp"
#include "JumpMode.hpp"
#include "Location.hpp"
#include "Mode.hpp"
#include "NormalMode.hpp"
#include "SearchMode.hpp"
#include "Selection.hpp"
#include "Transaction.hpp"
#include <memory>
namespace quip {
EditContext::EditContext(PopupService* popupService, StatusService* statusService, ScriptHost* scriptHost)
: EditContext(popupService, statusService, scriptHost, std::make_shared<Document>()) {
}
EditContext::EditContext(PopupService* popupService, StatusService* statusService, ScriptHost* scriptHost, std::shared_ptr<Document> document)
: m_document(document)
, m_fileTypeDatabase(*scriptHost)
, m_selections(Selection(Location(0, 0)))
, m_popupService(popupService)
, m_statusService(statusService) {
// Populate with standard file types.
m_fileTypeDatabase.registerFileType("Text", "text", {"txt", "text"});
m_fileTypeDatabase.registerFileType("Markdown", "markdown", {"md", "markdown"});
m_fileTypeDatabase.registerFileType("C++ Source", "cpp", {"cpp", "cxx"});
m_fileTypeDatabase.registerFileType("C++ Header", "cpp", {"hpp", "hxx"});
m_fileTypeDatabase.registerFileType("C Source", "cpp", {"c"});
m_fileTypeDatabase.registerFileType("C/C++ Header", "cpp", {"h"});
m_fileTypeDatabase.registerFileType("GLSL Shader Source", "glsl", {"fsh", "vsh"});
// Populate with standard modes.
m_modes.insert(std::make_pair("EditMode", std::make_shared<EditMode>()));
m_modes.insert(std::make_pair("JumpMode", std::make_shared<JumpMode>()));
m_modes.insert(std::make_pair("NormalMode", std::make_shared<NormalMode>()));
m_modes.insert(std::make_pair("SearchMode", std::make_shared<SearchMode>()));
enterMode("NormalMode");
}
Document& EditContext::document() {
return *m_document;
}
SelectionSet& EditContext::selections() {
return m_selections;
}
Mode& EditContext::mode() {
return *m_modeHistory.top();
}
const std::map<std::string, SelectionDrawInfo>& EditContext::overlays() const {
return m_overlays;
}
void EditContext::setOverlay(const std::string& name, const SelectionDrawInfo& overlay) {
m_overlays[name] = overlay;
}
void EditContext::clearOverlay(const std::string& name) {
auto cursor = m_overlays.find(name);
if (cursor != std::end(m_overlays)) {
m_overlays.erase(cursor);
}
}
void EditContext::enterMode(const std::string& name) {
enterMode(name, 0);
}
void EditContext::enterMode(const std::string& name, std::uint64_t how) {
std::map<std::string, std::shared_ptr<Mode>>::iterator cursor = m_modes.find(name);
if (cursor != m_modes.end()) {
m_modeHistory.push(cursor->second);
mode().enter(*this, how);
}
}
void EditContext::leaveMode() {
if (m_modeHistory.size() > 1) {
mode().exit(*this);
m_modeHistory.pop();
}
}
void EditContext::performTransaction(std::shared_ptr<Transaction> transaction) {
transaction->perform(*this);
m_onTransactionApplied.transmit(ChangeType::Do);
m_undoStack.push(transaction);
}
bool EditContext::canUndo() const noexcept {
return m_undoStack.size() > 0;
}
void EditContext::undo() {
if (canUndo()) {
m_undoStack.top()->rollback(*this);
m_onTransactionApplied.transmit(ChangeType::Undo);
m_redoStack.push(m_undoStack.top());
m_undoStack.pop();
}
}
bool EditContext::canRedo() const noexcept {
return m_redoStack.size() > 0;
}
void EditContext::redo() {
if (canRedo()) {
m_redoStack.top()->perform(*this);
m_onTransactionApplied.transmit(ChangeType::Redo);
m_undoStack.push(m_redoStack.top());
m_redoStack.pop();
}
}
bool EditContext::processKeyEvent(Key key, Modifiers modifiers) {
return mode().processKeyEvent(key, modifiers, *this);
}
bool EditContext::processKeyEvent(Key key, Modifiers modifiers, const std::string& text) {
return mode().processKeyEvent(key, modifiers, text, *this);
}
ViewController& EditContext::controller() {
return m_controller;
}
PopupService& EditContext::popupService() {
return *m_popupService;
}
StatusService& EditContext::statusService() {
return *m_statusService;
}
const FileTypeDatabase& EditContext::fileTypeDatabase() const {
return m_fileTypeDatabase;
}
Signal<void (ChangeType)>& EditContext::onTransactionApplied() {
return m_onTransactionApplied;
}
}
| 29.836601
| 144
| 0.679956
|
krisl
|
9112f5c47f4427c3c13786e2b27717a063c7a58a
| 481
|
hpp
|
C++
|
core/engine/inc/engine/component/GlBlendMaterialComponent.hpp
|
rawbby/WS20-CG-Pra-Dungeon-Crawler
|
4c1b372649a92fb08b8908054d82624ae2b68af5
|
[
"MIT"
] | null | null | null |
core/engine/inc/engine/component/GlBlendMaterialComponent.hpp
|
rawbby/WS20-CG-Pra-Dungeon-Crawler
|
4c1b372649a92fb08b8908054d82624ae2b68af5
|
[
"MIT"
] | null | null | null |
core/engine/inc/engine/component/GlBlendMaterialComponent.hpp
|
rawbby/WS20-CG-Pra-Dungeon-Crawler
|
4c1b372649a92fb08b8908054d82624ae2b68af5
|
[
"MIT"
] | null | null | null |
#pragma once
#include <engine/component/GlRenderComponent.hpp>
#include <engine/component/GlMaterialComponent.hpp>
#include <array>
namespace engine::component
{
/**
* Needed textures for OpenGl to render a object
* with multiple materials.
* Up to three materials are supported.
*/
struct GlBlendMaterialComponent
: public GlRenderComponent
{
std::array<Material, 3> materials{};
GLuint tex_blend = GL_NONE;
};
}
| 21.863636
| 52
| 0.669439
|
rawbby
|
91152d89bb1862b8e43622a4d3530c3269697936
| 10,518
|
cpp
|
C++
|
test/unit/detail/protocol/null_bitmap_traits.cpp
|
sehe/mysql
|
53da045c2c2c0f347ccd82888920d39d11f3f7a4
|
[
"BSL-1.0"
] | 1
|
2021-03-07T20:45:35.000Z
|
2021-03-07T20:45:35.000Z
|
test/unit/detail/protocol/null_bitmap_traits.cpp
|
sehe/mysql
|
53da045c2c2c0f347ccd82888920d39d11f3f7a4
|
[
"BSL-1.0"
] | null | null | null |
test/unit/detail/protocol/null_bitmap_traits.cpp
|
sehe/mysql
|
53da045c2c2c0f347ccd82888920d39d11f3f7a4
|
[
"BSL-1.0"
] | null | null | null |
//
// Copyright (c) 2019-2021 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "boost/mysql/detail/protocol/null_bitmap_traits.hpp"
#include "test_common.hpp"
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic/collection.hpp>
#include <array>
using boost::mysql::detail::null_bitmap_traits;
using boost::mysql::detail::stmt_execute_null_bitmap_offset;
using boost::mysql::detail::binary_row_null_bitmap_offset;
using namespace boost::unit_test;
using namespace boost::mysql::test;
BOOST_AUTO_TEST_SUITE(test_null_bitmap_traits)
// byte_count
struct byte_count_sample
{
std::size_t offset;
std::size_t num_fields;
std::size_t expected_value;
};
std::ostream& operator<<(std::ostream& os, const byte_count_sample& val)
{
return os << "(offset=" << val.offset << ", num_fields=" << val.num_fields << ")";
}
constexpr byte_count_sample all_byte_count_samples [] {
{ stmt_execute_null_bitmap_offset, 0, 0 },
{ stmt_execute_null_bitmap_offset, 1, 1 },
{ stmt_execute_null_bitmap_offset, 2, 1 },
{ stmt_execute_null_bitmap_offset, 3, 1 },
{ stmt_execute_null_bitmap_offset, 4, 1 },
{ stmt_execute_null_bitmap_offset, 5, 1 },
{ stmt_execute_null_bitmap_offset, 6, 1 },
{ stmt_execute_null_bitmap_offset, 7, 1 },
{ stmt_execute_null_bitmap_offset, 8, 1 },
{ stmt_execute_null_bitmap_offset, 9, 2 },
{ stmt_execute_null_bitmap_offset, 10, 2 },
{ stmt_execute_null_bitmap_offset, 11, 2 },
{ stmt_execute_null_bitmap_offset, 12, 2 },
{ stmt_execute_null_bitmap_offset, 13, 2 },
{ stmt_execute_null_bitmap_offset, 14, 2 },
{ stmt_execute_null_bitmap_offset, 15, 2 },
{ stmt_execute_null_bitmap_offset, 16, 2 },
{ stmt_execute_null_bitmap_offset, 17, 3 },
{ binary_row_null_bitmap_offset, 0, 1 },
{ binary_row_null_bitmap_offset, 1, 1 },
{ binary_row_null_bitmap_offset, 2, 1 },
{ binary_row_null_bitmap_offset, 3, 1 },
{ binary_row_null_bitmap_offset, 4, 1 },
{ binary_row_null_bitmap_offset, 5, 1 },
{ binary_row_null_bitmap_offset, 6, 1 },
{ binary_row_null_bitmap_offset, 7, 2 },
{ binary_row_null_bitmap_offset, 8, 2 },
{ binary_row_null_bitmap_offset, 9, 2 },
{ binary_row_null_bitmap_offset, 10, 2 },
{ binary_row_null_bitmap_offset, 11, 2 },
{ binary_row_null_bitmap_offset, 12, 2 },
{ binary_row_null_bitmap_offset, 13, 2 },
{ binary_row_null_bitmap_offset, 14, 2 },
{ binary_row_null_bitmap_offset, 15, 3 },
{ binary_row_null_bitmap_offset, 16, 3 },
{ binary_row_null_bitmap_offset, 17, 3 },
};
BOOST_DATA_TEST_CASE(byte_count, data::make(all_byte_count_samples))
{
null_bitmap_traits traits (sample.offset, sample.num_fields);
BOOST_TEST(traits.byte_count() == sample.expected_value);
}
// is_null
struct is_null_sample
{
std::size_t offset;
std::size_t pos;
bool expected;
};
std::ostream& operator<<(std::ostream& os, const is_null_sample& value)
{
return os << "(offset=" << value.offset << ", pos=" << value.pos << ")";
}
constexpr is_null_sample all_is_null_samples [] {
{ stmt_execute_null_bitmap_offset, 0, false },
{ stmt_execute_null_bitmap_offset, 1, false },
{ stmt_execute_null_bitmap_offset, 2, true },
{ stmt_execute_null_bitmap_offset, 3, false },
{ stmt_execute_null_bitmap_offset, 4, true },
{ stmt_execute_null_bitmap_offset, 5, true },
{ stmt_execute_null_bitmap_offset, 6, false },
{ stmt_execute_null_bitmap_offset, 7, true },
{ stmt_execute_null_bitmap_offset, 8, true },
{ stmt_execute_null_bitmap_offset, 9, true },
{ stmt_execute_null_bitmap_offset, 10, true },
{ stmt_execute_null_bitmap_offset, 11, true },
{ stmt_execute_null_bitmap_offset, 12, true },
{ stmt_execute_null_bitmap_offset, 13, true },
{ stmt_execute_null_bitmap_offset, 14, true },
{ stmt_execute_null_bitmap_offset, 15, true },
{ stmt_execute_null_bitmap_offset, 16, false },
{ binary_row_null_bitmap_offset, 0, true },
{ binary_row_null_bitmap_offset, 1, false },
{ binary_row_null_bitmap_offset, 2, true },
{ binary_row_null_bitmap_offset, 3, true },
{ binary_row_null_bitmap_offset, 4, false },
{ binary_row_null_bitmap_offset, 5, true },
{ binary_row_null_bitmap_offset, 6, true },
{ binary_row_null_bitmap_offset, 7, true },
{ binary_row_null_bitmap_offset, 8, true },
{ binary_row_null_bitmap_offset, 9, true },
{ binary_row_null_bitmap_offset, 10, true },
{ binary_row_null_bitmap_offset, 11, true },
{ binary_row_null_bitmap_offset, 12, true },
{ binary_row_null_bitmap_offset, 13, true },
{ binary_row_null_bitmap_offset, 14, false },
{ binary_row_null_bitmap_offset, 15, false },
{ binary_row_null_bitmap_offset, 16, false },
};
BOOST_DATA_TEST_CASE(is_null, data::make(all_is_null_samples))
{
std::array<std::uint8_t, 3> content { 0xb4, 0xff, 0x00 }; // 0b10110100, 0b11111111, 0b00000000
null_bitmap_traits traits (sample.offset, 17); // 17 fields
bool actual = traits.is_null(content.data(), sample.pos);
BOOST_TEST(actual == sample.expected);
}
BOOST_AUTO_TEST_CASE(is_null_one_field_stmt_execute_first_bit_zero)
{
std::uint8_t value = 0x00;
null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 1);
BOOST_TEST(!traits.is_null(&value, 0));
}
BOOST_AUTO_TEST_CASE(is_null_one_field_stmt_execute_first_bit_one)
{
std::uint8_t value = 0x01;
null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 1);
BOOST_TEST(traits.is_null(&value, 0));
}
BOOST_AUTO_TEST_CASE(is_null_one_field_binary_row_third_bit_zero)
{
std::uint8_t value = 0x00;
null_bitmap_traits traits (binary_row_null_bitmap_offset, 1);
BOOST_TEST(!traits.is_null(&value, 0));
}
BOOST_AUTO_TEST_CASE(is_null_one_field_binary_row_third_bit_one)
{
std::uint8_t value = 0x04; // 0b00000100
null_bitmap_traits traits (binary_row_null_bitmap_offset, 1);
BOOST_TEST(traits.is_null(&value, 0));
}
// set_null
struct set_null_sample
{
std::size_t offset;
std::size_t pos;
std::array<std::uint8_t, 3> expected;
constexpr set_null_sample(
std::size_t offset,
std::size_t pos,
const std::array<std::uint8_t, 3>& expected
) :
offset(offset),
pos(pos),
expected(expected)
{
};
};
std::ostream& operator<<(std::ostream& os, const set_null_sample& value)
{
return os << "(offset=" << value.offset << ", pos=" << value.pos << ")";
}
constexpr set_null_sample all_set_null_samples [] {
{ stmt_execute_null_bitmap_offset, 0, {0x01, 0, 0} },
{ stmt_execute_null_bitmap_offset, 1, {0x02, 0, 0} },
{ stmt_execute_null_bitmap_offset, 2, {0x04, 0, 0} },
{ stmt_execute_null_bitmap_offset, 3, {0x08, 0, 0} },
{ stmt_execute_null_bitmap_offset, 4, {0x10, 0, 0} },
{ stmt_execute_null_bitmap_offset, 5, {0x20, 0, 0} },
{ stmt_execute_null_bitmap_offset, 6, {0x40, 0, 0} },
{ stmt_execute_null_bitmap_offset, 7, {0x80, 0, 0} },
{ stmt_execute_null_bitmap_offset, 8, {0, 0x01, 0} },
{ stmt_execute_null_bitmap_offset, 9, {0, 0x02, 0} },
{ stmt_execute_null_bitmap_offset, 10, {0, 0x04, 0} },
{ stmt_execute_null_bitmap_offset, 11, {0, 0x08, 0} },
{ stmt_execute_null_bitmap_offset, 12, {0, 0x10, 0} },
{ stmt_execute_null_bitmap_offset, 13, {0, 0x20, 0} },
{ stmt_execute_null_bitmap_offset, 14, {0, 0x40, 0} },
{ stmt_execute_null_bitmap_offset, 15, {0, 0x80, 0} },
{ stmt_execute_null_bitmap_offset, 16, {0, 0, 0x01} },
{ binary_row_null_bitmap_offset, 0, {0x04, 0, 0} },
{ binary_row_null_bitmap_offset, 1, {0x08, 0, 0} },
{ binary_row_null_bitmap_offset, 2, {0x10, 0, 0} },
{ binary_row_null_bitmap_offset, 3, {0x20, 0, 0} },
{ binary_row_null_bitmap_offset, 4, {0x40, 0, 0} },
{ binary_row_null_bitmap_offset, 5, {0x80, 0, 0} },
{ binary_row_null_bitmap_offset, 6, {0, 0x01, 0} },
{ binary_row_null_bitmap_offset, 7, {0, 0x02, 0} },
{ binary_row_null_bitmap_offset, 8, {0, 0x04, 0} },
{ binary_row_null_bitmap_offset, 9, {0, 0x08, 0} },
{ binary_row_null_bitmap_offset, 10, {0, 0x10, 0} },
{ binary_row_null_bitmap_offset, 11, {0, 0x20, 0} },
{ binary_row_null_bitmap_offset, 12, {0, 0x40, 0} },
{ binary_row_null_bitmap_offset, 13, {0, 0x80, 0} },
{ binary_row_null_bitmap_offset, 14, {0, 0, 0x01} },
{ binary_row_null_bitmap_offset, 15, {0, 0, 0x02} },
{ binary_row_null_bitmap_offset, 16, {0, 0, 0x04} },
};
BOOST_DATA_TEST_CASE(set_null, data::make(all_set_null_samples))
{
std::array<std::uint8_t, 4> expected_buffer {}; // help detect buffer overruns
std::memcpy(expected_buffer.data(), sample.expected.data(), 3);
std::array<std::uint8_t, 4> actual_buffer {};
null_bitmap_traits traits (sample.offset, 17); // 17 fields
traits.set_null(actual_buffer.data(), sample.pos);
BOOST_TEST(expected_buffer == actual_buffer);
}
BOOST_AUTO_TEST_CASE(set_null_one_field_stmt_execute)
{
std::uint8_t value = 0;
null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 1);
traits.set_null(&value, 0);
BOOST_TEST(value == 1);
}
BOOST_AUTO_TEST_CASE(set_null_one_field_binary_row)
{
std::uint8_t value = 0;
null_bitmap_traits traits (binary_row_null_bitmap_offset, 1);
traits.set_null(&value, 0);
BOOST_TEST(value == 4);
}
BOOST_AUTO_TEST_CASE(set_null_multified_stmt_execute)
{
std::array<std::uint8_t, 4> expected_buffer { 0xb4, 0xff, 0x00, 0x00 };
std::array<std::uint8_t, 4> actual_buffer {};
null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 17); // 17 fields
for (std::size_t pos: {2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15})
{
traits.set_null(actual_buffer.data(), pos);
}
BOOST_TEST(expected_buffer == actual_buffer);
}
BOOST_AUTO_TEST_CASE(set_null_multified_binary_row)
{
std::array<std::uint8_t, 4> expected_buffer { 0xb4, 0xff, 0x00, 0x00 };
std::array<std::uint8_t, 4> actual_buffer {};
null_bitmap_traits traits (binary_row_null_bitmap_offset, 17); // 17 fields
for (std::size_t pos: {0, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13})
{
traits.set_null(actual_buffer.data(), pos);
}
BOOST_TEST(expected_buffer == actual_buffer);
}
BOOST_AUTO_TEST_SUITE_END() // test_null_bitmap_traits
| 37.166078
| 99
| 0.699848
|
sehe
|
91176873d0a36a54867dd4ff301e820abc49303d
| 32,254
|
hpp
|
C++
|
iguana/reflection.hpp
|
yangxingpping/iguana
|
bc11d40347e972f5ffcaa7289163f1012d6c8c41
|
[
"Apache-2.0"
] | 621
|
2017-03-12T08:49:01.000Z
|
2022-03-31T09:33:06.000Z
|
iguana/reflection.hpp
|
IndignantAngel/iguana
|
84849c3fba55fdf85edf2a600175961f5fcc7973
|
[
"Apache-2.0"
] | 43
|
2017-03-13T01:40:18.000Z
|
2022-02-21T16:13:50.000Z
|
iguana/reflection.hpp
|
IndignantAngel/iguana
|
84849c3fba55fdf85edf2a600175961f5fcc7973
|
[
"Apache-2.0"
] | 174
|
2017-02-09T02:00:30.000Z
|
2022-03-31T09:33:08.000Z
|
//
// Created by Qiyu on 17-6-5.
//
#ifndef IGUANA_REFLECTION_HPP
#define IGUANA_REFLECTION_HPP
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
#include <iomanip>
#include <map>
#include <vector>
#include <array>
#include <type_traits>
#include <functional>
#include <string_view>
#include "detail/itoa.hpp"
#include "detail/traits.hpp"
#include "detail/string_stream.hpp"
namespace iguana::detail {
/******************************************/
/* arg list expand macro, now support 120 args */
#define MAKE_ARG_LIST_1(op, arg, ...) op(arg)
#define MAKE_ARG_LIST_2(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_1(op, __VA_ARGS__))
#define MAKE_ARG_LIST_3(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_2(op, __VA_ARGS__))
#define MAKE_ARG_LIST_4(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_3(op, __VA_ARGS__))
#define MAKE_ARG_LIST_5(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_4(op, __VA_ARGS__))
#define MAKE_ARG_LIST_6(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_5(op, __VA_ARGS__))
#define MAKE_ARG_LIST_7(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_6(op, __VA_ARGS__))
#define MAKE_ARG_LIST_8(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_7(op, __VA_ARGS__))
#define MAKE_ARG_LIST_9(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_8(op, __VA_ARGS__))
#define MAKE_ARG_LIST_10(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_9(op, __VA_ARGS__))
#define MAKE_ARG_LIST_11(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_10(op, __VA_ARGS__))
#define MAKE_ARG_LIST_12(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_11(op, __VA_ARGS__))
#define MAKE_ARG_LIST_13(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_12(op, __VA_ARGS__))
#define MAKE_ARG_LIST_14(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_13(op, __VA_ARGS__))
#define MAKE_ARG_LIST_15(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_14(op, __VA_ARGS__))
#define MAKE_ARG_LIST_16(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_15(op, __VA_ARGS__))
#define MAKE_ARG_LIST_17(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_16(op, __VA_ARGS__))
#define MAKE_ARG_LIST_18(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_17(op, __VA_ARGS__))
#define MAKE_ARG_LIST_19(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_18(op, __VA_ARGS__))
#define MAKE_ARG_LIST_20(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_19(op, __VA_ARGS__))
#define MAKE_ARG_LIST_21(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_20(op, __VA_ARGS__))
#define MAKE_ARG_LIST_22(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_21(op, __VA_ARGS__))
#define MAKE_ARG_LIST_23(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_22(op, __VA_ARGS__))
#define MAKE_ARG_LIST_24(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_23(op, __VA_ARGS__))
#define MAKE_ARG_LIST_25(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_24(op, __VA_ARGS__))
#define MAKE_ARG_LIST_26(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_25(op, __VA_ARGS__))
#define MAKE_ARG_LIST_27(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_26(op, __VA_ARGS__))
#define MAKE_ARG_LIST_28(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_27(op, __VA_ARGS__))
#define MAKE_ARG_LIST_29(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_28(op, __VA_ARGS__))
#define MAKE_ARG_LIST_30(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_29(op, __VA_ARGS__))
#define MAKE_ARG_LIST_31(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_30(op, __VA_ARGS__))
#define MAKE_ARG_LIST_32(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_31(op, __VA_ARGS__))
#define MAKE_ARG_LIST_33(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_32(op, __VA_ARGS__))
#define MAKE_ARG_LIST_34(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_33(op, __VA_ARGS__))
#define MAKE_ARG_LIST_35(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_34(op, __VA_ARGS__))
#define MAKE_ARG_LIST_36(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_35(op, __VA_ARGS__))
#define MAKE_ARG_LIST_37(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_36(op, __VA_ARGS__))
#define MAKE_ARG_LIST_38(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_37(op, __VA_ARGS__))
#define MAKE_ARG_LIST_39(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_38(op, __VA_ARGS__))
#define MAKE_ARG_LIST_40(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_39(op, __VA_ARGS__))
#define MAKE_ARG_LIST_41(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_40(op, __VA_ARGS__))
#define MAKE_ARG_LIST_42(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_41(op, __VA_ARGS__))
#define MAKE_ARG_LIST_43(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_42(op, __VA_ARGS__))
#define MAKE_ARG_LIST_44(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_43(op, __VA_ARGS__))
#define MAKE_ARG_LIST_45(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_44(op, __VA_ARGS__))
#define MAKE_ARG_LIST_46(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_45(op, __VA_ARGS__))
#define MAKE_ARG_LIST_47(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_46(op, __VA_ARGS__))
#define MAKE_ARG_LIST_48(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_47(op, __VA_ARGS__))
#define MAKE_ARG_LIST_49(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_48(op, __VA_ARGS__))
#define MAKE_ARG_LIST_50(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_49(op, __VA_ARGS__))
#define MAKE_ARG_LIST_51(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_50(op, __VA_ARGS__))
#define MAKE_ARG_LIST_52(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_51(op, __VA_ARGS__))
#define MAKE_ARG_LIST_53(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_52(op, __VA_ARGS__))
#define MAKE_ARG_LIST_54(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_53(op, __VA_ARGS__))
#define MAKE_ARG_LIST_55(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_54(op, __VA_ARGS__))
#define MAKE_ARG_LIST_56(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_55(op, __VA_ARGS__))
#define MAKE_ARG_LIST_57(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_56(op, __VA_ARGS__))
#define MAKE_ARG_LIST_58(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_57(op, __VA_ARGS__))
#define MAKE_ARG_LIST_59(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_58(op, __VA_ARGS__))
#define MAKE_ARG_LIST_60(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_59(op, __VA_ARGS__))
#define MAKE_ARG_LIST_61(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_60(op, __VA_ARGS__))
#define MAKE_ARG_LIST_62(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_61(op, __VA_ARGS__))
#define MAKE_ARG_LIST_63(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_62(op, __VA_ARGS__))
#define MAKE_ARG_LIST_64(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_63(op, __VA_ARGS__))
#define MAKE_ARG_LIST_65(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_64(op, __VA_ARGS__))
#define MAKE_ARG_LIST_66(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_65(op, __VA_ARGS__))
#define MAKE_ARG_LIST_67(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_66(op, __VA_ARGS__))
#define MAKE_ARG_LIST_68(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_67(op, __VA_ARGS__))
#define MAKE_ARG_LIST_69(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_68(op, __VA_ARGS__))
#define MAKE_ARG_LIST_70(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_69(op, __VA_ARGS__))
#define MAKE_ARG_LIST_71(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_70(op, __VA_ARGS__))
#define MAKE_ARG_LIST_72(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_71(op, __VA_ARGS__))
#define MAKE_ARG_LIST_73(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_72(op, __VA_ARGS__))
#define MAKE_ARG_LIST_74(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_73(op, __VA_ARGS__))
#define MAKE_ARG_LIST_75(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_74(op, __VA_ARGS__))
#define MAKE_ARG_LIST_76(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_75(op, __VA_ARGS__))
#define MAKE_ARG_LIST_77(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_76(op, __VA_ARGS__))
#define MAKE_ARG_LIST_78(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_77(op, __VA_ARGS__))
#define MAKE_ARG_LIST_79(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_78(op, __VA_ARGS__))
#define MAKE_ARG_LIST_80(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_79(op, __VA_ARGS__))
#define MAKE_ARG_LIST_81(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_80(op, __VA_ARGS__))
#define MAKE_ARG_LIST_82(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_81(op, __VA_ARGS__))
#define MAKE_ARG_LIST_83(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_82(op, __VA_ARGS__))
#define MAKE_ARG_LIST_84(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_83(op, __VA_ARGS__))
#define MAKE_ARG_LIST_85(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_84(op, __VA_ARGS__))
#define MAKE_ARG_LIST_86(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_85(op, __VA_ARGS__))
#define MAKE_ARG_LIST_87(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_86(op, __VA_ARGS__))
#define MAKE_ARG_LIST_88(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_87(op, __VA_ARGS__))
#define MAKE_ARG_LIST_89(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_88(op, __VA_ARGS__))
#define MAKE_ARG_LIST_90(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_89(op, __VA_ARGS__))
#define MAKE_ARG_LIST_91(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_90(op, __VA_ARGS__))
#define MAKE_ARG_LIST_92(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_91(op, __VA_ARGS__))
#define MAKE_ARG_LIST_93(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_92(op, __VA_ARGS__))
#define MAKE_ARG_LIST_94(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_93(op, __VA_ARGS__))
#define MAKE_ARG_LIST_95(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_94(op, __VA_ARGS__))
#define MAKE_ARG_LIST_96(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_95(op, __VA_ARGS__))
#define MAKE_ARG_LIST_97(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_96(op, __VA_ARGS__))
#define MAKE_ARG_LIST_98(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_97(op, __VA_ARGS__))
#define MAKE_ARG_LIST_99(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_98(op, __VA_ARGS__))
#define MAKE_ARG_LIST_100(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_99(op, __VA_ARGS__))
#define MAKE_ARG_LIST_101(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_100(op, __VA_ARGS__))
#define MAKE_ARG_LIST_102(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_101(op, __VA_ARGS__))
#define MAKE_ARG_LIST_103(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_102(op, __VA_ARGS__))
#define MAKE_ARG_LIST_104(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_103(op, __VA_ARGS__))
#define MAKE_ARG_LIST_105(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_104(op, __VA_ARGS__))
#define MAKE_ARG_LIST_106(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_105(op, __VA_ARGS__))
#define MAKE_ARG_LIST_107(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_106(op, __VA_ARGS__))
#define MAKE_ARG_LIST_108(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_107(op, __VA_ARGS__))
#define MAKE_ARG_LIST_109(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_108(op, __VA_ARGS__))
#define MAKE_ARG_LIST_110(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_109(op, __VA_ARGS__))
#define MAKE_ARG_LIST_111(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_110(op, __VA_ARGS__))
#define MAKE_ARG_LIST_112(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_111(op, __VA_ARGS__))
#define MAKE_ARG_LIST_113(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_112(op, __VA_ARGS__))
#define MAKE_ARG_LIST_114(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_113(op, __VA_ARGS__))
#define MAKE_ARG_LIST_115(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_114(op, __VA_ARGS__))
#define MAKE_ARG_LIST_116(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_115(op, __VA_ARGS__))
#define MAKE_ARG_LIST_117(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_116(op, __VA_ARGS__))
#define MAKE_ARG_LIST_118(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_117(op, __VA_ARGS__))
#define MAKE_ARG_LIST_119(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_118(op, __VA_ARGS__))
#define MAKE_ARG_LIST_120(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_119(op, __VA_ARGS__))
#define ADD_VIEW(str) std::string_view(#str, sizeof(#str)-1)
#define SEPERATOR ,
#define CON_STR_1(element, ...) ADD_VIEW(element)
#define CON_STR_2(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_1(__VA_ARGS__))
#define CON_STR_3(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_2(__VA_ARGS__))
#define CON_STR_4(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_3(__VA_ARGS__))
#define CON_STR_5(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_4(__VA_ARGS__))
#define CON_STR_6(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_5(__VA_ARGS__))
#define CON_STR_7(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_6(__VA_ARGS__))
#define CON_STR_8(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_7(__VA_ARGS__))
#define CON_STR_9(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_8(__VA_ARGS__))
#define CON_STR_10(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_9(__VA_ARGS__))
#define CON_STR_11(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_10(__VA_ARGS__))
#define CON_STR_12(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_11(__VA_ARGS__))
#define CON_STR_13(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_12(__VA_ARGS__))
#define CON_STR_14(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_13(__VA_ARGS__))
#define CON_STR_15(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_14(__VA_ARGS__))
#define CON_STR_16(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_15(__VA_ARGS__))
#define CON_STR_17(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_16(__VA_ARGS__))
#define CON_STR_18(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_17(__VA_ARGS__))
#define CON_STR_19(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_18(__VA_ARGS__))
#define CON_STR_20(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_19(__VA_ARGS__))
#define CON_STR_21(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_20(__VA_ARGS__))
#define CON_STR_22(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_21(__VA_ARGS__))
#define CON_STR_23(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_22(__VA_ARGS__))
#define CON_STR_24(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_23(__VA_ARGS__))
#define CON_STR_25(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_24(__VA_ARGS__))
#define CON_STR_26(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_25(__VA_ARGS__))
#define CON_STR_27(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_26(__VA_ARGS__))
#define CON_STR_28(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_27(__VA_ARGS__))
#define CON_STR_29(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_28(__VA_ARGS__))
#define CON_STR_30(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_29(__VA_ARGS__))
#define CON_STR_31(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_30(__VA_ARGS__))
#define CON_STR_32(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_31(__VA_ARGS__))
#define CON_STR_33(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_32(__VA_ARGS__))
#define CON_STR_34(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_33(__VA_ARGS__))
#define CON_STR_35(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_34(__VA_ARGS__))
#define CON_STR_36(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_35(__VA_ARGS__))
#define CON_STR_37(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_36(__VA_ARGS__))
#define CON_STR_38(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_37(__VA_ARGS__))
#define CON_STR_39(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_38(__VA_ARGS__))
#define CON_STR_40(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_39(__VA_ARGS__))
#define CON_STR_41(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_40(__VA_ARGS__))
#define CON_STR_42(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_41(__VA_ARGS__))
#define CON_STR_43(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_42(__VA_ARGS__))
#define CON_STR_44(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_43(__VA_ARGS__))
#define CON_STR_45(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_44(__VA_ARGS__))
#define CON_STR_46(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_45(__VA_ARGS__))
#define CON_STR_47(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_46(__VA_ARGS__))
#define CON_STR_48(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_47(__VA_ARGS__))
#define CON_STR_49(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_48(__VA_ARGS__))
#define CON_STR_50(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_49(__VA_ARGS__))
#define CON_STR_51(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_50(__VA_ARGS__))
#define CON_STR_52(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_51(__VA_ARGS__))
#define CON_STR_53(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_52(__VA_ARGS__))
#define CON_STR_54(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_53(__VA_ARGS__))
#define CON_STR_55(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_54(__VA_ARGS__))
#define CON_STR_56(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_55(__VA_ARGS__))
#define CON_STR_57(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_56(__VA_ARGS__))
#define CON_STR_58(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_57(__VA_ARGS__))
#define CON_STR_59(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_58(__VA_ARGS__))
#define CON_STR_60(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_59(__VA_ARGS__))
#define CON_STR_61(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_60(__VA_ARGS__))
#define CON_STR_62(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_61(__VA_ARGS__))
#define CON_STR_63(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_62(__VA_ARGS__))
#define CON_STR_64(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_63(__VA_ARGS__))
#define CON_STR_65(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_64(__VA_ARGS__))
#define CON_STR_66(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_65(__VA_ARGS__))
#define CON_STR_67(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_66(__VA_ARGS__))
#define CON_STR_68(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_67(__VA_ARGS__))
#define CON_STR_69(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_68(__VA_ARGS__))
#define CON_STR_70(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_69(__VA_ARGS__))
#define CON_STR_71(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_70(__VA_ARGS__))
#define CON_STR_72(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_71(__VA_ARGS__))
#define CON_STR_73(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_72(__VA_ARGS__))
#define CON_STR_74(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_73(__VA_ARGS__))
#define CON_STR_75(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_74(__VA_ARGS__))
#define CON_STR_76(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_75(__VA_ARGS__))
#define CON_STR_77(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_76(__VA_ARGS__))
#define CON_STR_78(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_77(__VA_ARGS__))
#define CON_STR_79(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_78(__VA_ARGS__))
#define CON_STR_80(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_79(__VA_ARGS__))
#define CON_STR_81(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_80(__VA_ARGS__))
#define CON_STR_82(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_81(__VA_ARGS__))
#define CON_STR_83(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_82(__VA_ARGS__))
#define CON_STR_84(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_83(__VA_ARGS__))
#define CON_STR_85(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_84(__VA_ARGS__))
#define CON_STR_86(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_85(__VA_ARGS__))
#define CON_STR_87(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_86(__VA_ARGS__))
#define CON_STR_88(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_87(__VA_ARGS__))
#define CON_STR_89(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_88(__VA_ARGS__))
#define CON_STR_90(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_89(__VA_ARGS__))
#define CON_STR_91(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_90(__VA_ARGS__))
#define CON_STR_92(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_91(__VA_ARGS__))
#define CON_STR_93(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_92(__VA_ARGS__))
#define CON_STR_94(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_93(__VA_ARGS__))
#define CON_STR_95(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_94(__VA_ARGS__))
#define CON_STR_96(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_95(__VA_ARGS__))
#define CON_STR_97(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_96(__VA_ARGS__))
#define CON_STR_98(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_97(__VA_ARGS__))
#define CON_STR_99(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_98(__VA_ARGS__))
#define CON_STR_100(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_99(__VA_ARGS__))
#define CON_STR_101(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_100(__VA_ARGS__))
#define CON_STR_102(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_101(__VA_ARGS__))
#define CON_STR_103(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_102(__VA_ARGS__))
#define CON_STR_104(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_103(__VA_ARGS__))
#define CON_STR_105(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_104(__VA_ARGS__))
#define CON_STR_106(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_105(__VA_ARGS__))
#define CON_STR_107(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_106(__VA_ARGS__))
#define CON_STR_108(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_107(__VA_ARGS__))
#define CON_STR_109(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_108(__VA_ARGS__))
#define CON_STR_110(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_109(__VA_ARGS__))
#define CON_STR_111(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_110(__VA_ARGS__))
#define CON_STR_112(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_111(__VA_ARGS__))
#define CON_STR_113(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_112(__VA_ARGS__))
#define CON_STR_114(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_113(__VA_ARGS__))
#define CON_STR_115(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_114(__VA_ARGS__))
#define CON_STR_116(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_115(__VA_ARGS__))
#define CON_STR_117(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_116(__VA_ARGS__))
#define CON_STR_118(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_117(__VA_ARGS__))
#define CON_STR_119(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_118(__VA_ARGS__))
#define CON_STR_120(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_119(__VA_ARGS__))
#define RSEQ_N() \
119,118,117,116,115,114,113,112,111,110,\
109,108,107,106,105,104,103,102,101,100,\
99,98,97,96,95,94,93,92,91,90, \
89,88,87,86,85,84,83,82,81,80, \
79,78,77,76,75,74,73,72,71,70, \
69,68,67,66,65,64,63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
#define ARG_N(\
_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, _32, _33, _34, _35, _36, _37, _38, _39, _40, \
_41, _42, _43, _44, _45, _46, _47, _48, _49, _50, \
_51, _52, _53, _54, _55, _56, _57, _58, _59, _60, \
_61, _62, _63, _64, _65, _66, _67, _68, _69, _70, \
_71, _72, _73, _74, _75, _76, _77, _78, _79, _80, \
_81, _82, _83, _84, _85, _86, _87, _88, _89, _90, \
_91, _92, _93, _94, _95, _96, _97, _98, _99, _100, \
_101, _102, _103, _104, _105, _106, _107, _108, _109, _110, \
_111, _112, _113, _114, _115, _116, _117, _118, _119, N, ...) N
#define MARCO_EXPAND(...) __VA_ARGS__
#define APPLY_VARIADIC_MACRO(macro, ...) MARCO_EXPAND(macro(__VA_ARGS__))
#define ADD_REFERENCE(t) std::reference_wrapper<decltype(t)>(t)
#define ADD_REFERENCE_CONST(t) std::reference_wrapper<std::add_const_t<decltype(t)>>(t)
#define FIELD(t) t
#define MAKE_NAMES(...) #__VA_ARGS__,
//note use MACRO_CONCAT like A##_##B direct may cause marco expand error
#define MACRO_CONCAT(A, B) MACRO_CONCAT1(A, B)
#define MACRO_CONCAT1(A, B) A##_##B
#define MAKE_ARG_LIST(N, op, arg, ...) \
MACRO_CONCAT(MAKE_ARG_LIST, N)(op, arg, __VA_ARGS__)
#define GET_ARG_COUNT_INNER(...) MARCO_EXPAND(ARG_N(__VA_ARGS__))
#define GET_ARG_COUNT(...) GET_ARG_COUNT_INNER(__VA_ARGS__, RSEQ_N())
#define MAKE_STR_LIST(...) \
MACRO_CONCAT(CON_STR, GET_ARG_COUNT(__VA_ARGS__))(__VA_ARGS__)
#define MAKE_META_DATA_IMPL(STRUCT_NAME, ...) \
static auto iguana_reflect_members(STRUCT_NAME const&) \
{ \
struct reflect_members \
{ \
constexpr decltype(auto) static apply_impl(){\
return std::make_tuple(__VA_ARGS__);\
}\
using type = void;\
using size_type = std::integral_constant<size_t, GET_ARG_COUNT(__VA_ARGS__)>; \
constexpr static std::string_view name() { return std::string_view(#STRUCT_NAME, sizeof(#STRUCT_NAME)-1); }\
constexpr static size_t value() { return size_type::value; }\
constexpr static std::array<std::string_view, size_type::value> arr() { return arr_##STRUCT_NAME; }\
}; \
return reflect_members{}; \
}
#define MAKE_META_DATA(STRUCT_NAME, N, ...) \
constexpr inline std::array<std::string_view, N> arr_##STRUCT_NAME = { MARCO_EXPAND(MACRO_CONCAT(CON_STR, N)(__VA_ARGS__)) };\
MAKE_META_DATA_IMPL(STRUCT_NAME, MAKE_ARG_LIST(N, &STRUCT_NAME::FIELD, __VA_ARGS__))
}
namespace iguana
{
#define REFLECTION(STRUCT_NAME, ...) \
MAKE_META_DATA(STRUCT_NAME, GET_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)
template<typename T>
using Reflect_members = decltype(iguana_reflect_members(std::declval<T>()));
template <typename T, typename = void>
struct is_reflection : std::false_type
{
};
template <typename T>
struct is_reflection<T, std::void_t<typename Reflect_members<T>::type>> : std::true_type
{
};
template<typename T>
inline constexpr bool is_reflection_v = is_reflection<T>::value;
template<size_t I, typename T>
constexpr decltype(auto) get(T&& t)
{
using M = decltype(iguana_reflect_members(std::forward<T>(t)));
using U = decltype(std::forward<T>(t).*(std::get<I>(M::apply_impl())));
if constexpr(std::is_array_v<U>) {
auto s = std::forward<T>(t).*(std::get<I>(M::apply_impl()));
std::array<char, sizeof(U)> arr;
memcpy(arr.data(), s, arr.size());
return arr;
}
else
return std::forward<T>(t).*(std::get<I>(M::apply_impl()));
}
template <typename T, size_t ... Is>
constexpr auto get_impl(T const& t, std::index_sequence<Is...>)
{
return std::make_tuple(get<Is>(t)...);
}
template <typename T, size_t ... Is>
constexpr auto get_impl(T& t, std::index_sequence<Is...>)
{
return std::make_tuple(std::ref(get<Is>(t))...);
}
template <typename T>
constexpr auto get(T const& t)
{
using M = decltype(iguana_reflect_members(t));
return get_impl(t, std::make_index_sequence<M::value()>{});
}
template <typename T>
constexpr auto get_ref(T& t)
{
using M = decltype(iguana_reflect_members(t));
return get_impl(t, std::make_index_sequence<M::value()>{});
}
template<typename T, size_t I>
constexpr const std::string_view get_name()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
static_assert(I<M::value(), "out of range");
return M::arr()[I];
}
template<typename T>
constexpr const std::string_view get_name(size_t i)
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
// static_assert(I<M::value(), "out of range");
return M::arr()[i];
}
template<typename T>
constexpr const std::string_view get_name()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
return M::name();
}
template<typename T>
constexpr std::enable_if_t<is_reflection<T>::value, size_t> get_value()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
return M::value();
}
template<typename T>
constexpr std::enable_if_t<!is_reflection<T>::value, size_t> get_value()
{
return 1;
}
template<typename T>
constexpr auto get_array()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
return M::arr();
}
template<typename T>
constexpr auto get_index(std::string_view name)
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
constexpr auto arr = M::arr();
auto it = std::find_if(arr.begin(), arr.end(), [name](auto str){
return (str==name);
});
return std::distance(arr.begin(), it);
}
template <class Tuple, class F, std::size_t...Is>
void tuple_switch(std::size_t i, Tuple&& t, F&& f, std::index_sequence<Is...>) {
((i == Is && ((std::forward<F>(f)(std::get<Is>(std::forward<Tuple>(t)))), false)), ...);
}
//-------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------//
template <typename... Args, typename F, std::size_t... Idx>
constexpr void for_each(std::tuple<Args...>& t, F&& f, std::index_sequence<Idx...>)
{
(std::forward<F>(f)(std::get<Idx>(t), std::integral_constant<size_t, Idx>{}), ...);
}
template <typename... Args, typename F, std::size_t... Idx>
constexpr void for_each(const std::tuple<Args...>& t, F&& f, std::index_sequence<Idx...>)
{
(std::forward<F>(f)(std::get<Idx>(t), std::integral_constant<size_t, Idx>{}), ...);
}
template<typename T, typename F>
constexpr std::enable_if_t<is_reflection<T>::value> for_each(T&& t, F&& f)
{
using M = decltype(iguana_reflect_members(std::forward<T>(t)));
for_each(M::apply_impl(), std::forward<F>(f), std::make_index_sequence<M::value()>{});
}
template<typename T, typename F>
constexpr std::enable_if_t<is_tuple<std::decay_t<T>>::value> for_each(T&& t, F&& f)
{
//using M = decltype(iguana_reflect_members(std::forward<T>(t)));
constexpr const size_t SIZE = std::tuple_size_v<std::decay_t<T>>;
for_each(std::forward<T>(t), std::forward<F>(f), std::make_index_sequence<SIZE>{});
}
}
#endif //IGUANA_REFLECTION_HPP
| 65.159596
| 130
| 0.73163
|
yangxingpping
|
911b5303fdd55db62e8eaa831a6fa25bf472e1a6
| 467
|
cpp
|
C++
|
solutions/IWaP5vb1.cpp
|
luyencode/cpp-solutions
|
627397fb887654e9f5ee64cfb73d708f6f6706f7
|
[
"MIT"
] | 60
|
2021-04-10T11:17:33.000Z
|
2022-03-23T06:15:42.000Z
|
solutions/IWaP5vb1.cpp
|
letuankiet-29-10-2002/cpp-solutions
|
7d9cddf211af54ff207da883b469f4ddd75d5916
|
[
"MIT"
] | 1
|
2021-08-13T11:32:27.000Z
|
2021-08-13T11:32:27.000Z
|
solutions/IWaP5vb1.cpp
|
letuankiet-29-10-2002/cpp-solutions
|
7d9cddf211af54ff207da883b469f4ddd75d5916
|
[
"MIT"
] | 67
|
2021-04-10T17:32:50.000Z
|
2022-03-23T15:50:17.000Z
|
/*
Sưu tầm bởi @nguyenvanhieuvn
Thực hành nhiều bài tập hơn tại https://luyencode.net/
*/
#include<stdio.h>
#include<conio.h>
float Tinh(float x)
{
float ketqua;
if(x >= 5)
ketqua = 2 * x * x + 5 * x + 9;
else
ketqua = -2 * x * x + 4 * x - 9;
return ketqua;
}
int main()
{
float x;
printf("\nNhap x: ");
scanf("%f", &x);
float ketqua = Tinh(x);
printf("\nKet qua = %f", ketqua);
getch();
return 0;
}
| 16.103448
| 56
| 0.518201
|
luyencode
|
911dda215577af18a10fa68681fec3b0cdf9b744
| 8,752
|
cpp
|
C++
|
gpu/src/particleapp.cpp
|
Melodeathguy/ParticleSolver
|
5cccb54454427029f3c05156854a3337369995e1
|
[
"MIT"
] | 129
|
2015-07-06T16:57:03.000Z
|
2022-02-25T08:34:29.000Z
|
gpu/src/particleapp.cpp
|
Melodeathguy/ParticleSolver
|
5cccb54454427029f3c05156854a3337369995e1
|
[
"MIT"
] | null | null | null |
gpu/src/particleapp.cpp
|
Melodeathguy/ParticleSolver
|
5cccb54454427029f3c05156854a3337369995e1
|
[
"MIT"
] | 21
|
2015-07-07T05:52:08.000Z
|
2021-06-07T02:28:05.000Z
|
/*
* This class controls helper classes for rendering and
* updating the particle system.
*
* Mouse events, key events, window sizing, timing updates,
* and render calls are all received by this application then
* passed to the corresponding render or particlesystem class.
*/
#include <cuda_runtime.h>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QKeyEvent>
#include <random>
#include <unistd.h>
#include "particleapp.h"
#include "particlesystem.h"
#include "renderer.h"
#include "helper_math.h"
#include "util.cuh"
#define MAX_PARTICLES 15000 // (vbo size)
#define PARTICLE_RADIUS 0.25f
#define GRID_SIZE make_uint3(64, 64, 64) // 3D
ParticleApp::ParticleApp()
: m_particleSystem(NULL),
m_renderer(NULL),
m_mouseDownL(false),
m_mouseDownR(false),
m_fluidEmmiterOn(false),
m_timer(-1.f)
{
cudaInit();
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
m_renderer = new Renderer(m_particleSystem->getMinBounds(), m_particleSystem->getMaxBounds());
m_renderer->createVAO(m_particleSystem->getCurrentReadBuffer(),
m_particleSystem->getParticleRadius());
makeInitScene();
}
ParticleApp::~ParticleApp()
{
if (m_particleSystem)
delete m_particleSystem;
if (m_renderer)
delete m_renderer;
// cudaDeviceReset causes the driver to clean up all state. While
// not mandatory in normal operation, it is good practice. It is also
// needed to ensure correct operation when the application is being
// profiled. Calling cudaDeviceReset causes all profile data to be
// flushed before the application exits
cudaDeviceReset();
}
inline float frand()
{
return rand() / (float) RAND_MAX;
}
void ParticleApp::makeInitScene()
{
m_particleSystem->addRope(make_float3(0, 20, 0), make_float3(0, -.5, 0), .4f, 32, 1.f, true);
}
void ParticleApp::tick(float secs)
{
if (m_fluidEmmiterOn && m_timer <= 0.f)
{
m_particleSystem->addFluid(make_int3(-1,0,-1), make_int3(1,1,1), 1.f, 1.f, make_float3(0,0,1));
m_timer = 0.1f;
}
m_timer -= secs;
m_particleSystem->update(secs);
m_renderer->update(secs);
}
void ParticleApp::render()
{
m_renderer->render(m_particleSystem->getColorIndex(), m_particleSystem->getColors());
}
void ParticleApp::mousePressed(QMouseEvent *e, float x, float y)
{
// shoot a particle into the sceen on left mouse click
if (e->button() == Qt::LeftButton)
{
m_particleSystem->setParticleToAdd(m_renderer->getEye(), m_renderer->getDir(x, y) * 30.f, 2.f);
m_mouseDownL = true;
}
else if (e->button() == Qt::RightButton)
{
m_mouseDownR = true;
}
}
void ParticleApp::mouseReleased(QMouseEvent *e, float, float)
{
if (e->button() == Qt::LeftButton)
{
m_mouseDownL = false;
}
if (e->button() == Qt::RightButton)
{
m_mouseDownR = false;
}
}
void ParticleApp::mouseMoved(QMouseEvent *e, float deltaX, float deltaY)
{
m_renderer->mouseMoved(e, deltaX, deltaY);
}
void ParticleApp::mouseScrolled(QWheelEvent *) {}
void ParticleApp::keyPressed(QKeyEvent *e)
{
m_renderer->keyPressed(e);
}
void ParticleApp::keyReleased(QKeyEvent *e)
{
bool resetVbo = true;
float3 h, vec;
float angle;
// numbers 0-9 toggle different scenes
switch (e->key())
{
case Qt::Key_1: // single rope
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
makeInitScene();
break;
case Qt::Key_2: // single cloth
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
m_particleSystem->addHorizCloth(make_int2(0, -3), make_int2(6,3), make_float3(.5f,7.f,.5f), make_float2(.3f, .3f), 3.f, false);
break;
case Qt::Key_3: // two fluids, different densities
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-7, 0, -5), make_int3(7, 20, 5), 5);
m_particleSystem->addFluid(make_int3(-7, 0, -5), make_int3(7, 5, 5), 1.f, 2.f, colors[rand() % numColors]);
m_particleSystem->addFluid(make_int3(-7, 5, -5), make_int3(7, 10, 5), 1.f, 3.f, colors[rand() % numColors]);
break;
case Qt::Key_4: // one solid particle stack
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
m_particleSystem->addParticleGrid(make_int3(-3, 0, -3), make_int3(3, 20, 3), 1.f, false);
break;
case Qt::Key_5: // three solid particle stacks
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
m_particleSystem->addParticleGrid(make_int3(-10, 0, -3), make_int3(-7, 10, 3), 1.f, false);
m_particleSystem->addParticleGrid(make_int3(-3, 0, -3), make_int3(3, 10, 3), 1.f, false);
m_particleSystem->addParticleGrid(make_int3(7, 0, -3), make_int3(10, 10, 3), 1.f, false);
break;
case Qt::Key_6: // particles on cloth
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
m_particleSystem->addHorizCloth(make_int2(-10, -10), make_int2(10, 10), make_float3(.3f, 5.5f, .3f), make_float2(.1f, .1f), 10.f, true);
m_particleSystem->addParticleGrid(make_int3(-3, 6, -3), make_int3(3, 15, 3), 1.f, false);
break;
case Qt::Key_7: // fluid blob
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
m_particleSystem->addFluid(make_int3(-7, 6, -7), make_int3(7, 13, 7), 1.f, 1.5f, colors[rand() % numColors]);
break;
case Qt::Key_8: // combo scene
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
m_particleSystem->addHorizCloth(make_int2(14, -4), make_int2(24, 6), make_float3(.3f, 2.5f, .3f), make_float2(.25f, .25f), 10.f, true);
m_particleSystem->addHorizCloth(make_int2(10, -10), make_int2(25, -5), make_float3(.3f, 15.5f, .3f), make_float2(.25f, .25f), 3.f, false);
m_particleSystem->addRope(make_float3(-17, 20, -17), make_float3(0, -.5, 0.001f), .4f, 30, 1.f, true);
m_particleSystem->addRope(make_float3(-16, 20, -17), make_float3(0, 0, .5f), .4f, 50, 1.f, true);
m_particleSystem->addRope(make_float3(-17, 20, -16), make_float3(0, -.5, 0.001f), .4f, 40, 1.f, true);
m_particleSystem->addParticleGrid(make_int3(17, 6, 0), make_int3(21, 11, 4), 1.f, false);
m_particleSystem->addParticleGrid(make_int3(-12, 0, -20), make_int3(0, 12, -17), 1.f, false);
m_particleSystem->addParticleGrid(make_int3(-18, 0, -15), make_int3(-16, 9, -12), 1.f, false);
m_particleSystem->addStaticSphere(make_int3(5, 5, -10), make_int3(10, 10, -5), .5f);
break;
case Qt::Key_9: // ropes on immovable sphere
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
h = make_float3(0, 10, 0);
for(int i = 0; i < 50; i++)
{
angle = M_PI * i * 0.02f;
vec = make_float3(cos(angle), sin(angle), 0.f);
m_particleSystem->addRope(vec*5.f + h, vec*.5f, .35f, 30, 1.f, true);
}
m_particleSystem->addStaticSphere(make_int3(-4, 7, -4), make_int3(4, 16, 4), .5f);
break;
case Qt::Key_0: // empty scene
delete m_particleSystem;
m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5);
break;
case Qt::Key_Space: // toggle fluids at origin
m_fluidEmmiterOn = !m_fluidEmmiterOn;
break;
default:
resetVbo = false;
m_renderer->keyReleased(e);
break;
}
if (resetVbo)
{
m_renderer->createVAO(m_particleSystem->getCurrentReadBuffer(),
m_particleSystem->getParticleRadius());
}
}
void ParticleApp::resize(int w, int h)
{
m_renderer->resize(w, h);
}
| 37.242553
| 146
| 0.650708
|
Melodeathguy
|
9122a62e3892015827bf4daa1971dee8079bf138
| 4,527
|
cc
|
C++
|
measure_statistics_in_data.cc
|
JackMaguire/RobotsAsAGraph
|
23208be8cfc34cd1f4db9f3cb7b680286e690f07
|
[
"MIT"
] | null | null | null |
measure_statistics_in_data.cc
|
JackMaguire/RobotsAsAGraph
|
23208be8cfc34cd1f4db9f3cb7b680286e690f07
|
[
"MIT"
] | null | null | null |
measure_statistics_in_data.cc
|
JackMaguire/RobotsAsAGraph
|
23208be8cfc34cd1f4db9f3cb7b680286e690f07
|
[
"MIT"
] | null | null | null |
//g++ measure_statistics_in_data.cc -o measure_statistics_in_data --std=c++17 -I extern/RobotsCore/include/ -O3 -Wall -pedantic -Wextra -Wshadow
#include "deserialize.hh"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
#include <robots_core/forecasting.hh>
constexpr auto path_to_all_data = "data/all_data/";
constexpr auto outpath_to_training_data = "data/training_data.txt";
constexpr auto outpath_to_validation_data = "data/validation_data.txt";
//https://stackoverflow.com/questions/874134/find-out-if-string-ends-with-another-string-in-c
bool ends_with(
std::string const & value,
std::string const & ending
){
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
bool move_is_legal(
Key const move,
std::array< std::array< robots_core::ForecastResults, 3 >, 3 > const & forecasts
){
switch( move ){
case Key::Q: return forecasts[0][2].legal;
case Key::W: return forecasts[1][2].legal;
case Key::E: return forecasts[2][2].legal;
case Key::A: return forecasts[0][1].legal;
case Key::S: return forecasts[1][1].legal;
case Key::D: return forecasts[2][1].legal;
case Key::Z: return forecasts[0][0].legal;
case Key::X: return forecasts[1][0].legal;
case Key::C: return forecasts[2][0].legal;
default: return true;
}
}
int main(){
std::stringstream training_data;
std::stringstream validation_data;
int n_early_teleports = 0;
std::array< long long unsigned int, 10 > safe_move_hist;
safe_move_hist.fill( 0 );
std::array< std::array< long long unsigned int, 10 >, 3 > safe_move_hist_by_level;
for( auto & a : safe_move_hist_by_level ) a.fill( 0 );
auto bin_for_level =
[]( int const level ){
if( level <= 22 ) return 0;
else if( level <= 44 ) return 1;
else return 2;
};
int counter = 0;
for( auto const & entry : fs::directory_iterator( path_to_all_data ) ){
if( ends_with( entry.path(), "gz" ) ) continue;
//std::cout << entry.path() << std::endl;
bool const validation = counter == 0;
counter = (counter+1)%5;
std::stringstream & stream = (
validation ?
validation_data :
training_data
);
std::ifstream input( entry.path() ); //RAII close
for( std::string line; getline( input, line ); ) {
DataPoint const sample = deserialize( line );
//Skip move-less keys
if( sample.key == Key::NONE || sample.key == Key::DELETE || sample.key == Key::R || sample.key == Key::SPACE ) continue;
auto const forecasts = robots_core::forecast_all_moves(sample.game.board());
//Skip cascade situations
if( forecasts[1][1].cascade_safe ) continue;
//Skip illegal moves
if( not move_is_legal( sample.key, forecasts ) ) continue;
unsigned int num_safe_moves = 0;
for( auto const & f1 : forecasts ){
for( auto const & f : f1 ){
if( f.legal ) ++num_safe_moves;
}
}
//std::cout << "num_safe_moves: " << num_safe_moves << std::endl;
++safe_move_hist[ num_safe_moves ];
++safe_move_hist_by_level
[ bin_for_level( sample.level ) ]
[ num_safe_moves ];
//Skip obvious teleports
if( num_safe_moves == 0 ) continue;
if( num_safe_moves > 0 and sample.key == Key::T ) {
++n_early_teleports;
//upsample safe teleports
stream << line << '\n';
stream << line << '\n';
stream << line << '\n';
stream << line << '\n';
}
stream << line << '\n';
}
}
for( unsigned int i = 0; i < safe_move_hist.size(); ++i ){
std::cout << "safe_move_hist " << i << " " << safe_move_hist[i] << std::endl;
}
std::cout << "Levels 1-22:" << std::endl;
for( unsigned int i = 0; i < safe_move_hist_by_level[0].size(); ++i ){
std::cout << "safe_move_hist " << i << " " << safe_move_hist_by_level[0][i] << std::endl;
}
std::cout << "Levels 23-44:" << std::endl;
for( unsigned int i = 0; i < safe_move_hist_by_level[1].size(); ++i ){
std::cout << "safe_move_hist " << i << " " << safe_move_hist_by_level[1][i] << std::endl;
}
std::cout << "Levels 45-66:" << std::endl;
for( unsigned int i = 0; i < safe_move_hist_by_level[2].size(); ++i ){
std::cout << "safe_move_hist " << i << " " << safe_move_hist_by_level[2][i] << std::endl;
}
std::cout << "n_early_teleports: " << n_early_teleports << std::endl;
std::cout << training_data.str().size() << " " << validation_data.str().size() << std::endl;
}
| 30.18
| 144
| 0.631986
|
JackMaguire
|
91273f09df8a64f484be59b2685f8d58bd24ab5d
| 813
|
hpp
|
C++
|
TGEngine/io/Mouse.hpp
|
ThePixly/TGEngine
|
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
|
[
"Apache-2.0"
] | null | null | null |
TGEngine/io/Mouse.hpp
|
ThePixly/TGEngine
|
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
|
[
"Apache-2.0"
] | null | null | null |
TGEngine/io/Mouse.hpp
|
ThePixly/TGEngine
|
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "../util/VectorUtil.hpp"
#include "../util/Annotations.hpp"
#include <glm/glm.hpp>
namespace tg_io {
/*
* These variables can be used to track the mouses position
*/
extern glm::vec2 pos;
extern glm::vec2 delta;
/*
* These variables can be used to check if the buttons are down;
*/
extern bool FIRST_MOUSE_BUTTON;
extern bool SECOND_MOUSE_BUTTON;
extern bool THIRED_MOUSE_BUTTON;
/*
* Internal mouse handling list
*/
extern std::vector<void(*)(glm::vec2, glm::vec2)> mouse_handler;
/*
* Internal mouse handling method
*/
SINCE(0, 0, 3)
void inputupdate(glm::vec2 pos, glm::vec2 delta);
/*
* With this method you can add a Listener that is called everytime an input is detected
*/
SINCE(0, 0, 3)
void addListener(void(*mouse)(glm::vec2, glm::vec2));
}
| 21.972973
| 89
| 0.693727
|
ThePixly
|
912ee50bc6fea304044f5716f624130aa155d807
| 4,215
|
hpp
|
C++
|
test/inheritance.hpp
|
IRCAD/camp
|
fbbada73d6fd25c30f22a69f195c871757e362dd
|
[
"MIT"
] | 6
|
2017-12-27T03:13:29.000Z
|
2021-01-04T15:07:18.000Z
|
test/inheritance.hpp
|
fw4spl-org/camp
|
e70eca1d2bf7f20df782dacc5d6baa51ce364e12
|
[
"MIT"
] | 1
|
2021-10-19T14:03:39.000Z
|
2021-10-19T14:03:39.000Z
|
test/inheritance.hpp
|
IRCAD/camp
|
fbbada73d6fd25c30f22a69f195c871757e362dd
|
[
"MIT"
] | 1
|
2019-08-30T15:20:46.000Z
|
2019-08-30T15:20:46.000Z
|
/****************************************************************************
**
** This file is part of the CAMP library.
**
** The MIT License (MIT)
**
** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company.
** Contact: Tegesoft Information (contact@tegesoft.com)
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in
** all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
** THE SOFTWARE.
**
****************************************************************************/
#ifndef CAMPTEST_INHERITANCE_HPP
#define CAMPTEST_INHERITANCE_HPP
#include <camp/camptype.hpp>
#include <camp/class.hpp>
namespace InheritanceTest
{
struct MyClass1
{
MyClass1() : p1(10), po1(10) {}
virtual ~MyClass1() {}
int p1;
int f1() const {return 1;}
int po1;
int fo1() {return 1;}
CAMP_RTTI();
};
struct MyClass2
{
MyClass2() : p2(20), po2(20) {}
virtual ~MyClass2() {}
int p2;
int f2() const {return 2;}
virtual int fv() const {return p2;}
int po2;
int fo2() {return 2;}
CAMP_RTTI();
};
struct MyClass3 : public MyClass1, public MyClass2
{
MyClass3() : p3(30), po3(30) {}
virtual ~MyClass3() {}
int p3;
int f3() const {return 3;}
virtual int fv() const {return p3;}
int po3;
int fo3() {return 3;}
CAMP_RTTI();
};
struct MyClass4 : public MyClass3
{
MyClass4() : p4(40), po4(40) {}
virtual ~MyClass4() {}
int p4;
int f4() const {return 4;}
virtual int fv() const {return p4;}
int po4;
int fo4() {return 4;}
CAMP_RTTI();
};
void declare()
{
camp::Class::declare<MyClass1>("InheritanceTest::MyClass1")
.function("f1", &MyClass1::f1)
.property("p1", &MyClass1::p1)
.function("overridden", &MyClass1::fo1)
.property("overridden", &MyClass1::po1);
camp::Class::declare<MyClass2>("InheritanceTest::MyClass2")
.function("f2", &MyClass2::f2)
.property("p2", &MyClass2::p2)
.function("virtual", &MyClass2::fv)
.function("overridden", &MyClass2::fo2)
.property("overridden", &MyClass2::po2);
camp::Class::declare<MyClass3>("InheritanceTest::MyClass3")
.base<MyClass1>()
.base<MyClass2>()
.function("f3", &MyClass3::f3)
.property("p3", &MyClass3::p3)
.function("overridden", &MyClass3::fo3)
.property("overridden", &MyClass3::po3);
camp::Class::declare<MyClass4>("InheritanceTest::MyClass4")
.base<MyClass3>()
.function("f4", &MyClass4::f4)
.property("p4", &MyClass4::p4)
.function("overridden", &MyClass4::fo4)
.property("overridden", &MyClass4::po4);
}
}
CAMP_AUTO_TYPE(InheritanceTest::MyClass1, &InheritanceTest::declare)
CAMP_AUTO_TYPE(InheritanceTest::MyClass2, &InheritanceTest::declare)
CAMP_AUTO_TYPE(InheritanceTest::MyClass3, &InheritanceTest::declare)
CAMP_AUTO_TYPE(InheritanceTest::MyClass4, &InheritanceTest::declare)
#endif // CAMPTEST_INHERITANCE_HPP
| 34.268293
| 90
| 0.599763
|
IRCAD
|
91342f9c3f6c57c5228ee5914a86e8334b981890
| 4,262
|
hpp
|
C++
|
src/compressed-sensing/lib/include/Armadillo/armadillo_bits/glue_times_bones.hpp
|
HerrFroehlich/ns3-CompressedSensing
|
f5e4e56aeea97794695ecef6183bdaa1b72fd1de
|
[
"MIT"
] | null | null | null |
src/compressed-sensing/lib/include/Armadillo/armadillo_bits/glue_times_bones.hpp
|
HerrFroehlich/ns3-CompressedSensing
|
f5e4e56aeea97794695ecef6183bdaa1b72fd1de
|
[
"MIT"
] | null | null | null |
src/compressed-sensing/lib/include/Armadillo/armadillo_bits/glue_times_bones.hpp
|
HerrFroehlich/ns3-CompressedSensing
|
f5e4e56aeea97794695ecef6183bdaa1b72fd1de
|
[
"MIT"
] | null | null | null |
// Copyright (C) 2008-2012 NICTA (www.nicta.com.au)
// Copyright (C) 2008-2012 Conrad Sanderson
//
// This file is part of the Armadillo C++ library.
// It is provided without any warranty of fitness
// for any purpose. You can redistribute this file
// and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published
// by the Free Software Foundation, either version 3
// of the License or (at your option) any later version.
// (see http://www.opensource.org/licenses for more info)
//! \addtogroup glue_times
//! @{
//! \brief
//! Template metaprogram depth_lhs
//! calculates the number of Glue<Tx,Ty, glue_type> instances on the left hand side argument of Glue<Tx,Ty, glue_type>
//! i.e. it recursively expands each Tx, until the type of Tx is not "Glue<..,.., glue_type>" (i.e the "glue_type" changes)
template<typename glue_type, typename T1>
struct depth_lhs
{
static const uword num = 0;
};
template<typename glue_type, typename T1, typename T2>
struct depth_lhs< glue_type, Glue<T1,T2,glue_type> >
{
static const uword num = 1 + depth_lhs<glue_type, T1>::num;
};
template<bool is_eT_blas_type>
struct glue_times_redirect2_helper
{
template<typename T1, typename T2>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X);
};
template<>
struct glue_times_redirect2_helper<true>
{
template<typename T1, typename T2>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X);
};
template<uword N>
struct glue_times_redirect
{
template<typename T1, typename T2>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X);
};
template<>
struct glue_times_redirect<2>
{
template<typename T1, typename T2>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X);
};
template<>
struct glue_times_redirect<3>
{
template<typename T1, typename T2, typename T3>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue< Glue<T1,T2,glue_times>,T3,glue_times>& X);
};
template<>
struct glue_times_redirect<4>
{
template<typename T1, typename T2, typename T3, typename T4>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue< Glue< Glue<T1,T2,glue_times>, T3, glue_times>, T4, glue_times>& X);
};
//! Class which implements the immediate multiplication of two or more matrices
class glue_times
{
public:
template<typename T1, typename T2>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X);
template<typename T1>
arma_hot inline static void apply_inplace(Mat<typename T1::elem_type>& out, const T1& X);
template<typename T1, typename T2>
arma_hot inline static void apply_inplace_plus(Mat<typename T1::elem_type>& out, const Glue<T1, T2, glue_times>& X, const sword sign);
template<typename eT1, typename eT2>
inline static void apply_mixed(Mat<typename promote_type<eT1,eT2>::result>& out, const Mat<eT1>& X, const Mat<eT2>& Y);
template<typename eT, const bool do_trans_A, const bool do_trans_B>
arma_inline static uword mul_storage_cost(const Mat<eT>& A, const Mat<eT>& B);
template<typename eT, const bool do_trans_A, const bool do_trans_B, const bool do_scalar_times>
arma_hot inline static void apply(Mat<eT>& out, const Mat<eT>& A, const Mat<eT>& B, const eT val);
template<typename eT, const bool do_trans_A, const bool do_trans_B, const bool do_trans_C, const bool do_scalar_times>
arma_hot inline static void apply(Mat<eT>& out, const Mat<eT>& A, const Mat<eT>& B, const Mat<eT>& C, const eT val);
template<typename eT, const bool do_trans_A, const bool do_trans_B, const bool do_trans_C, const bool do_trans_D, const bool do_scalar_times>
arma_hot inline static void apply(Mat<eT>& out, const Mat<eT>& A, const Mat<eT>& B, const Mat<eT>& C, const Mat<eT>& D, const eT val);
};
class glue_times_diag
{
public:
template<typename T1, typename T2>
arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1, T2, glue_times_diag>& X);
};
//! @}
| 31.109489
| 149
| 0.725012
|
HerrFroehlich
|
9139519824739e375fe970eb2975f38416c31c21
| 4,381
|
cpp
|
C++
|
tasksexplorerd/task/system_helpers.cpp
|
astavonin/Tasks-Explorer
|
3feb2d9a0a4694812de6aa895a809899c62fe5c1
|
[
"BSD-3-Clause"
] | 40
|
2015-03-20T13:23:16.000Z
|
2021-07-20T14:17:21.000Z
|
tasksexplorerd/task/system_helpers.cpp
|
varenc/Tasks-Explorer
|
85558fad7dd48fd2f81bcc58193f5cb4a6aaf263
|
[
"BSD-3-Clause"
] | 7
|
2016-08-01T21:01:25.000Z
|
2018-04-28T10:34:03.000Z
|
tasksexplorerd/task/system_helpers.cpp
|
varenc/Tasks-Explorer
|
85558fad7dd48fd2f81bcc58193f5cb4a6aaf263
|
[
"BSD-3-Clause"
] | 9
|
2015-01-29T19:28:17.000Z
|
2018-04-30T19:08:52.000Z
|
#include "system_helpers.h"
#include <stdio.h>
#include <utils.h>
#include <prettyprint.hpp>
#include <string>
namespace tasks
{
proc_info_vec build_tasks_list()
{
static size_t maxProcsCount = 500;
bool done = false;
proc_info_vec procs( maxProcsCount );
static const int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
do
{
size_t length = maxProcsCount * sizeof( kinfo_proc );
sysctl( (int *)name, ( sizeof( name ) / sizeof( *name ) ) - 1,
&procs[0], &length, nullptr, 0 );
if( length != 0 )
{
done = true;
procs.resize( length / sizeof( kinfo_proc ) );
}
else
{
sysctl( (int *)name, ( sizeof( name ) / sizeof( *name ) ) - 1,
nullptr, &length, nullptr, 0 );
maxProcsCount = length / sizeof( kinfo_proc ) * 1.5;
procs.resize( maxProcsCount );
}
} while( !done );
return procs;
}
boost::optional<std::vector<char>> read_proc_args( pid_t pid, logger_ptr log )
{
boost::optional<std::vector<char>> res;
if( pid == 0 ) // we will not be able to extract data for kernel_task
return res;
static int argmax = [&log]() -> int {
int name[] = {CTL_KERN, KERN_ARGMAX, 0};
int argmax = 0;
size_t size = sizeof( argmax );
int ret = sysctl( name, 2, &argmax, &size, nullptr, 0 );
if( ret != 0 )
{
log->error( "{}: unable to get argmax, will use 1MB instead",
__func__ );
argmax = 1024 * 1024;
}
return argmax;
}();
std::vector<char> procargv( argmax );
int name[] = {CTL_KERN, KERN_PROCARGS2, pid};
size_t size = argmax;
int err = sysctl( name, 3, &procargv[0], &size, nullptr, 0 );
if( err != 0 )
log->warn( "{}: unable to get environment for PID {}", __func__, pid );
else
res = procargv;
return res;
}
proc_args parse_proc_args( const std::vector<char> &procargv,
logger_ptr /*log*/ )
{
proc_args parsedArgs;
if( procargv.size() < sizeof( int ) ) return parsedArgs;
const char *all_arguments = &procargv[0];
int argc = *( (int *)all_arguments );
parsedArgs.path_name.assign( all_arguments + sizeof( argc ) );
static const char app[] = ".app/";
auto appBegin = parsedArgs.path_name.rfind( app );
if( appBegin != std::string::npos )
{
auto nameBegin = parsedArgs.path_name.rfind( "/", appBegin ) + 1;
parsedArgs.app_name.assign( parsedArgs.path_name, nameBegin,
appBegin - nameBegin + sizeof( app ) - 2 );
}
else
{
auto execBegin = parsedArgs.path_name.rfind( "/" ) + 1;
parsedArgs.app_name.assign( parsedArgs.path_name, execBegin,
appBegin - execBegin );
}
all_arguments += sizeof( argc ) + parsedArgs.path_name.length();
while( *( ++all_arguments ) != '\0' )
{
}
while( *( ++all_arguments ) == '\0' )
{
}
if( argc > 0 )
{
const char *ptr = all_arguments;
for( int i = 0; i < argc; ++i )
{
std::string arg( ptr );
ptr += arg.length() + 1;
parsedArgs.argv.push_back( std::move( arg ) );
}
all_arguments = ptr;
}
all_arguments--;
do
{
if( *all_arguments == '\0' )
{
all_arguments++;
if( *all_arguments == '\0' )
break;
else
{
auto pos = strchr( all_arguments, '=' );
parsedArgs.env.emplace(
std::string( all_arguments, pos - all_arguments ),
std::string( pos + 1 ) );
}
}
all_arguments++;
} while( true );
return parsedArgs;
}
std::ostream &operator<<( std::ostream &os, const proc_args &p )
{
os << "struct proc_args(" << std::hex << &p << std::dec << ") \n{\n"
<< "app_name: " << p.app_name << "\n"
<< "path_name: " << p.path_name << "\n"
<< "argv(" << p.argv.size() << "):" << p.argv << "\n"
<< "env(" << p.env.size() << "):" << p.env << "\n"
<< "}";
return os;
}
}
| 27.904459
| 79
| 0.497375
|
astavonin
|
913af1bf9eb994c9987f4ae6755e8be3ee54b9ee
| 8,601
|
cpp
|
C++
|
3rdParty/iresearch/core/search/tfidf.cpp
|
specimen151/arangodb
|
1a3a31dace16293426a19364eb4d93c8f17c0d68
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
3rdParty/iresearch/core/search/tfidf.cpp
|
specimen151/arangodb
|
1a3a31dace16293426a19364eb4d93c8f17c0d68
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
3rdParty/iresearch/core/search/tfidf.cpp
|
specimen151/arangodb
|
1a3a31dace16293426a19364eb4d93c8f17c0d68
|
[
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC Corporation, 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.
///
/// Copyright holder is EMC Corporation
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////
#include <rapidjson/rapidjson/document.h> // for rapidjson::Document
#include "tfidf.hpp"
#include "scorers.hpp"
#include "analysis/token_attributes.hpp"
#include "index/index_reader.hpp"
#include "index/field_meta.hpp"
NS_LOCAL
irs::sort::ptr make_from_bool(
const rapidjson::Document& json,
const irs::string_ref& args) {
assert(json.IsBool());
PTR_NAMED(irs::tfidf_sort, ptr, json.GetBool());
return ptr;
}
irs::sort::ptr make_from_object(
const rapidjson::Document& json,
const irs::string_ref& args) {
assert(json.IsObject());
PTR_NAMED(irs::tfidf_sort, ptr);
#ifdef IRESEARCH_DEBUG
auto& scorer = dynamic_cast<irs::tfidf_sort&>(*ptr);
#else
auto& scorer = static_cast<irs::tfidf_sort&>(*ptr);
#endif
{
// optional bool
const auto* key= "with-norms";
if (json.HasMember(key)) {
if (!json[key].IsBool()) {
IR_FRMT_ERROR("Non-boolean value in '%s' while constructing tfidf scorer from jSON arguments: %s", key, args.c_str());
return nullptr;
}
scorer.normalize(json[key].GetBool());
}
}
return ptr;
}
irs::sort::ptr make_from_array(
const rapidjson::Document& json,
const irs::string_ref& args) {
assert(json.IsArray());
const auto array = json.GetArray();
const auto size = array.Size();
if (size > 1) {
// wrong number of arguments
IR_FRMT_ERROR(
"Wrong number of arguments while constructing tfidf scorer from jSON arguments (must be <= 1): %s",
args.c_str()
);
return nullptr;
}
// default args
auto norms = irs::tfidf_sort::WITH_NORMS();
// parse `with-norms` optional argument
if (!array.Empty()) {
auto& arg = array[0];
if (!arg.IsBool()) {
IR_FRMT_ERROR(
"Non-float value on position `0` while constructing bm25 scorer from jSON arguments: %s",
args.c_str()
);
return nullptr;
}
norms = arg.GetBool();
}
PTR_NAMED(irs::tfidf_sort, ptr, norms);
return ptr;
}
NS_END // LOCAL
NS_ROOT
NS_BEGIN(tfidf)
// empty frequency
const frequency EMPTY_FREQ;
struct idf final : basic_stored_attribute<float_t> {
DECLARE_ATTRIBUTE_TYPE();
DECLARE_FACTORY_DEFAULT();
idf() : basic_stored_attribute(1.f) { }
void clear() { value = 1.f; }
};
DEFINE_ATTRIBUTE_TYPE(iresearch::tfidf::idf);
DEFINE_FACTORY_DEFAULT(idf);
typedef tfidf_sort::score_t score_t;
class collector final : public iresearch::sort::collector {
public:
collector(bool normalize)
: normalize_(normalize) {
}
virtual void collect(
const sub_reader& segment,
const term_reader& field,
const attribute_view& term_attrs
) override {
UNUSED(segment);
UNUSED(field);
auto& meta = term_attrs.get<iresearch::term_meta>();
if (meta) {
docs_count += meta->docs_count;
}
}
virtual void finish(
attribute_store& filter_attrs,
const iresearch::index_reader& index
) override {
filter_attrs.emplace<tfidf::idf>()->value =
1 + float_t(std::log(index.docs_count() / double_t(docs_count + 1)));
// add norm attribute if requested
if (normalize_) {
filter_attrs.emplace<norm>();
}
}
private:
uint64_t docs_count = 0; // document frequency
bool normalize_;
}; // collector
class scorer : public iresearch::sort::scorer_base<tfidf::score_t> {
public:
DECLARE_FACTORY(scorer);
scorer(
iresearch::boost::boost_t boost,
const tfidf::idf* idf,
const frequency* freq)
: idf_(boost * (idf ? idf->value : 1.f)),
freq_(freq ? freq : &EMPTY_FREQ) {
assert(freq_);
}
virtual void score(byte_type* score_buf) override {
score_cast(score_buf) = tfidf();
}
protected:
FORCE_INLINE float_t tfidf() const {
return idf_ * float_t(std::sqrt(freq_->value));
}
private:
float_t idf_; // precomputed : boost * idf
const frequency* freq_;
}; // scorer
class norm_scorer final : public scorer {
public:
DECLARE_FACTORY(norm_scorer);
norm_scorer(
const iresearch::norm* norm,
iresearch::boost::boost_t boost,
const tfidf::idf* idf,
const frequency* freq)
: scorer(boost, idf, freq),
norm_(norm) {
assert(norm_);
}
virtual void score(byte_type* score_buf) override {
score_cast(score_buf) = tfidf() * norm_->read();
}
private:
const iresearch::norm* norm_;
}; // norm_scorer
class sort final: iresearch::sort::prepared_base<tfidf::score_t> {
public:
DECLARE_FACTORY(prepared);
sort(bool normalize) NOEXCEPT
: normalize_(normalize) {
}
virtual const flags& features() const override {
static const irs::flags FEATURES[] = {
irs::flags({ irs::frequency::type() }), // without normalization
irs::flags({ irs::frequency::type(), irs::norm::type() }), // with normalization
};
return FEATURES[normalize_];
}
virtual collector::ptr prepare_collector() const override {
return iresearch::sort::collector::make<tfidf::collector>(normalize_);
}
virtual scorer::ptr prepare_scorer(
const sub_reader& segment,
const term_reader& field,
const attribute_store& query_attrs,
const attribute_view& doc_attrs
) const override {
if (!doc_attrs.contains<frequency>()) {
return nullptr; // if there is no frequency then all the scores will be the same (e.g. filter irs::all)
}
auto& norm = query_attrs.get<iresearch::norm>();
if (norm && norm->reset(segment, field.meta().norm, *doc_attrs.get<document>())) {
return tfidf::scorer::make<tfidf::norm_scorer>(
&*norm,
boost::extract(query_attrs),
query_attrs.get<tfidf::idf>().get(),
doc_attrs.get<frequency>().get()
);
}
return tfidf::scorer::make<tfidf::scorer>(
boost::extract(query_attrs),
query_attrs.get<tfidf::idf>().get(),
doc_attrs.get<frequency>().get()
);
}
virtual void add(score_t& dst, const score_t& src) const override {
dst += src;
}
virtual bool less(const score_t& lhs, const score_t& rhs) const override {
return lhs < rhs;
}
private:
const std::function<bool(score_t, score_t)>* less_;
bool normalize_;
}; // sort
NS_END // tfidf
DEFINE_SORT_TYPE_NAMED(iresearch::tfidf_sort, "tfidf");
REGISTER_SCORER_JSON(irs::tfidf_sort, irs::tfidf_sort::make);
DEFINE_FACTORY_DEFAULT(irs::tfidf_sort);
/*static*/ sort::ptr tfidf_sort::make(const string_ref& args) {
if (args.null()) {
PTR_NAMED(tfidf_sort, ptr);
return ptr;
}
rapidjson::Document json;
if (json.Parse(args.c_str(), args.size()).HasParseError()) {
IR_FRMT_ERROR(
"Invalid jSON arguments passed while constructing tfidf scorer, arguments: %s",
args.c_str()
);
return nullptr;
}
switch (json.GetType()) {
case rapidjson::kFalseType:
case rapidjson::kTrueType:
return make_from_bool(json, args);
case rapidjson::kObjectType:
return make_from_object(json, args);
case rapidjson::kArrayType:
return make_from_array(json, args);
default: // wrong type
IR_FRMT_ERROR(
"Invalid jSON arguments passed while constructing tfidf scorer, arguments: %s",
args.c_str()
);
return nullptr;
}
}
tfidf_sort::tfidf_sort(bool normalize)
: sort(tfidf_sort::type()),
normalize_(normalize) {
}
sort::prepared::ptr tfidf_sort::prepare() const {
return tfidf::sort::make<tfidf::sort>(normalize_);
}
NS_END // ROOT
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
| 25.371681
| 126
| 0.633531
|
specimen151
|
913bcf95fe6d859ca7bb360d1e04594ce7e4686f
| 3,234
|
cpp
|
C++
|
src/widgets/updater.cpp
|
Kor-Hal/SisterRay
|
4e8482525a5d7f77dee186f438ddb16523a61e7e
|
[
"BSD-3-Clause"
] | null | null | null |
src/widgets/updater.cpp
|
Kor-Hal/SisterRay
|
4e8482525a5d7f77dee186f438ddb16523a61e7e
|
[
"BSD-3-Clause"
] | null | null | null |
src/widgets/updater.cpp
|
Kor-Hal/SisterRay
|
4e8482525a5d7f77dee186f438ddb16523a61e7e
|
[
"BSD-3-Clause"
] | null | null | null |
#include "updaters.h"
#include "../impl.h"
#include "../inventories/inventory_utils.h"
#include "../menus/battle_menu/battle_menu_utils.h"
void battleSpellNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto magics = getSrPartyMember(*BATTLE_ACTIVE_ACTOR_ID).srPartyMember->actorMagics;
if (magics[flatIndex].magicIndex == 0xFF) {
disableWidget(getChild(widget, std::string("ARW")));
disableWidget(getChild(widget, std::string("TXT")));
return;
}
enableWidget(getChild(widget, std::string("TXT")));
updateText(getChild(widget, std::string("TXT")), getCommandAction(CMD_MAGIC, magics[flatIndex].magicIndex).attackName.str());
updateTextColor(widget, COLOR_WHITE);
if (magics[flatIndex].allCount) {
enableWidget(getChild(widget, std::string("ARW")));
return;
}
disableWidget(getChild(widget, std::string("ARW")));
}
void battleSummonNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto summons = getSrPartyMember(*BATTLE_ACTIVE_ACTOR_ID).srPartyMember->actorSummons;
if (summons[flatIndex].magicIndex == 0xFF) {
disableWidget(getChild(widget, std::string("TXT")));
return;
}
enableWidget(getChild(widget, std::string("TXT")));
updateText(getChild(widget, std::string("TXT")), getCommandAction(CMD_SUMMON, summons[flatIndex].magicIndex).attackName.str());
updateTextColor(getChild(widget, std::string("TXT")), COLOR_WHITE);
}
void battleEskillNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto eSkills = getSrPartyMember(*BATTLE_ACTIVE_ACTOR_ID).srPartyMember->actorEnemySkills;
if (eSkills[flatIndex].magicIndex == 0xFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
updateText(widget, getCommandAction(CMD_ENEMY_SKILL, eSkills[flatIndex].magicIndex).attackName.str());
updateTextColor(widget, COLOR_WHITE);
}
void battleInventoryRowUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto itemID = gContext.battleInventory->getResource(flatIndex).item_id;
if (itemID == 0xFFFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
auto textColor = (isUsableInBattle(itemID)) ? COLOR_WHITE : COLOR_GRAY;
updateText(getChild(widget, std::string("TXT")), getNameFromItemID(itemID));
updateTextColor(getChild(widget, std::string("TXT")), textColor);
updateNumber(getChild(widget, std::string("AMT")), gContext.battleInventory->getResource(itemID).quantity);
updateNumberColor(getChild(widget, std::string("AMT")), textColor);
updateItemIcon(getChild(widget, std::string("ICN")), gContext.itemTypeData.getResource(itemID).itemIconType);
}
| 43.12
| 131
| 0.704391
|
Kor-Hal
|
913d013dea1393db53086d40db4c61179695401c
| 2,314
|
hh
|
C++
|
include/G4NRFPtrLevelVector.hh
|
jvavrek/NIMB2018
|
0aaf4143db2194b9f95002c681e4f860c8c76f7a
|
[
"MIT"
] | 4
|
2020-06-28T02:18:53.000Z
|
2022-01-17T07:54:31.000Z
|
include/G4NRFPtrLevelVector.hh
|
jvavrek/NIMB2018
|
0aaf4143db2194b9f95002c681e4f860c8c76f7a
|
[
"MIT"
] | 3
|
2018-08-16T18:49:53.000Z
|
2020-10-19T18:04:25.000Z
|
include/G4NRFPtrLevelVector.hh
|
jvavrek/NIMB2018
|
0aaf4143db2194b9f95002c681e4f860c8c76f7a
|
[
"MIT"
] | null | null | null |
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
// -------------------------------------------------------------------
// GEANT 4 class file
//
// CERN, Geneva, Switzerland
//
// File name: G4PtrLevelVector
//
// Author: Maria Grazia Pia (pia@genova.infn.it)
//
// Creation date: 25 October 1998
//
// Modifications:
//
// -------------------------------------------------------------------
#ifndef G4NRFPTRLEVELVECTOR_HH
#define G4NRFPTRLEVELVECTOR_HH
#include <vector>
#include "G4NRFNuclearLevel.hh"
typedef std::vector<G4NRFNuclearLevel *> G4NRFPtrLevelVector;
struct DeleteLevel { void operator () (G4NRFNuclearLevel * aL) {delete aL;} };
#endif
| 43.660377
| 78
| 0.513397
|
jvavrek
|
913f225bc3f4b445f01494fe4359be3f599d914c
| 599
|
cpp
|
C++
|
tools/pngbb.cpp
|
hemantasapkota/lotech
|
46598a7c37dfd7cd424e2426564cc32533e1cfd6
|
[
"curl"
] | 9
|
2015-06-28T05:47:33.000Z
|
2021-06-29T13:35:48.000Z
|
tools/pngbb.cpp
|
hemantasapkota/lotech
|
46598a7c37dfd7cd424e2426564cc32533e1cfd6
|
[
"curl"
] | 5
|
2015-01-10T02:56:53.000Z
|
2018-07-27T03:21:14.000Z
|
tools/pngbb.cpp
|
hemantasapkota/lotech
|
46598a7c37dfd7cd424e2426564cc32533e1cfd6
|
[
"curl"
] | 3
|
2015-04-01T14:48:54.000Z
|
2015-11-12T11:52:50.000Z
|
/*
* ./pngbb in.png out.png.
* Reads in.png and generates out.png which contains only the pixels
* in the bounding box of in.png, along with a private chunk containing the
* bounding box information (see ltWriteImage function).
*/
#include "lt.h"
int main(int argc, const char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage error: expecting exactly 2 args.\n");
exit(1);
}
LTImageBuffer *buf = ltReadImage(argv[1], "pngbb");
if (buf != NULL) {
ltWriteImage(argv[2], buf);
delete buf;
return 0;
} else {
return 1;
}
}
| 26.043478
| 75
| 0.601002
|
hemantasapkota
|
913fd0228ee7e7f5e6a0caf4929b975cf235d293
| 2,726
|
cpp
|
C++
|
lib/lib_info.cpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 10
|
2017-12-21T05:20:40.000Z
|
2021-09-18T05:14:01.000Z
|
lib/lib_info.cpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 2
|
2017-12-21T07:31:54.000Z
|
2021-06-23T08:52:35.000Z
|
lib/lib_info.cpp
|
GreyMerlin/owl_cpp
|
ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6
|
[
"BSL-1.0"
] | 7
|
2016-02-17T13:20:31.000Z
|
2021-11-08T09:30:43.000Z
|
/** @file "/owlcpp/lib/lib_info.cpp"
part of owlcpp project.
@n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt.
@n Copyright Mikhail K Levin 2012
*******************************************************************************/
#ifndef OWLCPP_SOURCE
#define OWLCPP_SOURCE
#endif
#include <sstream>
#include "owlcpp/lib_info.hpp"
#include "boost/preprocessor/stringize.hpp"
#ifndef OWLCPP_NAME
#define OWLCPP_NAME owlcpp
#endif
#ifndef OWLCPP_DESCRIPTION
#define OWLCPP_DESCRIPTION
#endif
#ifndef OWLCPP_VERSION_1
#define OWLCPP_VERSION_1 0
#endif
#ifndef OWLCPP_VERSION_2
#define OWLCPP_VERSION_2 0
#endif
#ifndef OWLCPP_VERSION_3
#define OWLCPP_VERSION_3 0
#endif
#ifndef OWLCPP_VERSION_EXTRA
#define OWLCPP_VERSION_EXTRA ???
#endif
#ifndef OWLCPP_VERSION_DIRTY
#define OWLCPP_VERSION_DIRTY 0
#endif
#ifndef OWLCPP_BUILD
#define OWLCPP_BUILD 0
#endif
namespace owlcpp { namespace{
std::string make_version_str() {
std::ostringstream str;
str
<< 'v' << OWLCPP_VERSION_1 << '.'
<< OWLCPP_VERSION_2 << '.' << OWLCPP_VERSION_3
;
const std::string e = std::string(BOOST_PP_STRINGIZE(OWLCPP_VERSION_EXTRA));
if( ! e.empty() ) str << '-' << e;
if( OWLCPP_VERSION_DIRTY ) str << '~';
return str.str();
}
}//namespace anonymous
/*
*******************************************************************************/
std::string const& Lib_info::name() {
static const std::string s = std::string(BOOST_PP_STRINGIZE(OWLCPP_NAME));
return s;
}
/*
*******************************************************************************/
std::string const& Lib_info::version() {
static const std::string s = make_version_str();
return s;
}
/*
*******************************************************************************/
std::string const& Lib_info::description() {
static const std::string s = std::string(BOOST_PP_STRINGIZE(OWLCPP_DESCRIPTION));
return s;
}
/*
*******************************************************************************/
int Lib_info::version_1() {return OWLCPP_VERSION_1;}
/*
*******************************************************************************/
int Lib_info::version_2() {return OWLCPP_VERSION_2;}
/*
*******************************************************************************/
int Lib_info::version_3() {return OWLCPP_VERSION_3;}
/*
*******************************************************************************/
std::string const& Lib_info::version_e() {
static const std::string s = std::string(BOOST_PP_STRINGIZE(OWLCPP_VERSION_EXTRA));
return s;
}
/*
*******************************************************************************/
int Lib_info::build() {return OWLCPP_BUILD;}
}//namespace owlcpp
| 25.961905
| 86
| 0.535216
|
GreyMerlin
|
91439ce4efbfbc3dd757cc7d00ea7d088f63defe
| 870
|
cpp
|
C++
|
src/source/uselibhoard.cpp
|
dark0z/Hoard
|
5afe855606e60ba255915d5cd816474815fc8844
|
[
"ECL-2.0",
"Apache-2.0"
] | 827
|
2015-01-13T20:39:45.000Z
|
2022-03-29T06:31:59.000Z
|
src/source/uselibhoard.cpp
|
dark0z/Hoard
|
5afe855606e60ba255915d5cd816474815fc8844
|
[
"ECL-2.0",
"Apache-2.0"
] | 41
|
2015-01-25T21:37:58.000Z
|
2022-03-15T09:10:24.000Z
|
src/source/uselibhoard.cpp
|
dark0z/Hoard
|
5afe855606e60ba255915d5cd816474815fc8844
|
[
"ECL-2.0",
"Apache-2.0"
] | 107
|
2015-01-19T20:41:53.000Z
|
2022-01-25T16:30:38.000Z
|
/* -*- C++ -*- */
/*
The Hoard Multiprocessor Memory Allocator
www.hoard.org
Author: Emery Berger, http://www.emeryberger.com
Copyright (c) 1998-2020 Emery Berger
See the LICENSE file at the top-level directory of this
distribution and at http://github.com/emeryberger/Hoard.
*/
// Link this code with your executable to use winhoard.
#if defined(_WIN32)
#include <windows.h>
//#include <iostream>
#if defined(_WIN64)
#pragma comment(linker, "/include:ReferenceHoard")
#else
#pragma comment(linker, "/include:_ReferenceHoard")
#endif
extern "C" {
__declspec(dllimport) int ReferenceWinWrapperStub;
void ReferenceHoard()
{
LoadLibraryA ("libhoard.dll");
#if 0
if (lib == NULL) {
std::cerr << "Startup error code = " << GetLastError() << std::endl;
abort();
}
#endif
ReferenceWinWrapperStub = 1;
}
}
#endif
| 18.125
| 74
| 0.673563
|
dark0z
|
9144a4b4925780bf0db15600aae9e2f643a63e8b
| 9,459
|
cpp
|
C++
|
Code/Libraries/Core/src/windowwrapper.cpp
|
kas1e/Eldritch
|
032b4ac52f7508c89efa407d6fe60f40c6281fd9
|
[
"Zlib"
] | null | null | null |
Code/Libraries/Core/src/windowwrapper.cpp
|
kas1e/Eldritch
|
032b4ac52f7508c89efa407d6fe60f40c6281fd9
|
[
"Zlib"
] | null | null | null |
Code/Libraries/Core/src/windowwrapper.cpp
|
kas1e/Eldritch
|
032b4ac52f7508c89efa407d6fe60f40c6281fd9
|
[
"Zlib"
] | null | null | null |
#include "core.h"
#include "windowwrapper.h"
#include "mathcore.h"
#if BUILD_WINDOWS_NO_SDL
#include <Windows.h>
#endif
#include <stdio.h>
#include <proto/dos.h>
#if BUILD_SDL
#ifdef PANDORA
#include <SDL2/SDL.h>
#else
#include "SDL2/SDL.h"
#endif
#endif
#include <memory.h>
Window::Window()
#if BUILD_WINDOWS_NO_SDL
: m_hWnd(NULL),
m_hDC(NULL),
m_hInstance(NULL),
m_WndClassEx(),
m_Style(0)
#endif
#if BUILD_SDL
: m_Window(nullptr)
#endif
,
m_Inited(false) {
#if BUILD_WINDOWS_NO_SDL
memset(&m_WndClassEx, 0, sizeof(WNDCLASSEX));
#endif
}
Window::~Window() {
if (m_Inited) {
Free();
}
}
#if BUILD_WINDOWS_NO_SDL
// TODO: Add some failure handling, and meaningful return values
int Window::Init(const char* Title, const char* ClassName, DWORD Style,
DWORD ExStyle, int Width, int Height, HINSTANCE hInstance,
WNDPROC WndProc /*= NULL*/, uint Icon /*= 0*/,
int ScreenWidth /*= 0*/, int ScreenHeight /*= 0*/) {
XTRACE_FUNCTION;
if (m_Inited) {
return 1;
}
m_hInstance = hInstance;
m_Style = Style;
m_WndClassEx.cbSize = sizeof(WNDCLASSEX);
m_WndClassEx.style = CS_HREDRAW | CS_VREDRAW;
m_WndClassEx.lpfnWndProc = (WndProc != NULL) ? WndProc : DefWindowProc;
m_WndClassEx.hInstance = hInstance;
m_WndClassEx.hIcon =
(Icon == 0 ? NULL : LoadIcon(hInstance, MAKEINTRESOURCE(Icon)));
m_WndClassEx.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW),
IMAGE_CURSOR, 0, 0, LR_SHARED);
m_WndClassEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
m_WndClassEx.lpszMenuName = NULL;
m_WndClassEx.lpszClassName = ClassName;
m_WndClassEx.hIconSm = NULL;
RegisterClassEx(&m_WndClassEx);
// Adjust dimensions to accommodate borders
RECT WindowRect;
WindowRect.left = 0;
WindowRect.right = Width;
WindowRect.top = 0;
WindowRect.bottom = Height;
AdjustWindowRect(&WindowRect, Style, false);
int AdjustedWidth = WindowRect.right - WindowRect.left;
int AdjustedHeight = WindowRect.bottom - WindowRect.top;
// Center window, or just position in top-left if it won't fit
const int WindowX = Max(0, (ScreenWidth - AdjustedWidth) >> 1);
const int WindowY = Max(0, (ScreenHeight - AdjustedHeight) >> 1);
// Let calling code know what the window will look like.
// We don't have an hWnd yet, but we can call the WindowProc directly.
if (WndProc) {
POINT NotifySize;
NotifySize.x = AdjustedWidth;
NotifySize.y = AdjustedHeight;
WPARAM wParam = 0;
LPARAM lParam = reinterpret_cast<LPARAM>(&NotifySize);
WndProc(0, WM_NOTIFY_SIZE, wParam, lParam);
}
m_hWnd = CreateWindowEx(ExStyle, ClassName, Title, Style, WindowX, WindowY,
AdjustedWidth, AdjustedHeight, NULL, NULL,
m_hInstance, NULL);
ASSERT(m_hWnd);
#if BUILD_DEV
GetWindowRect(m_hWnd, &WindowRect);
ASSERT(WindowRect.right - WindowRect.left == AdjustedWidth);
ASSERT(WindowRect.bottom - WindowRect.top == AdjustedHeight);
#endif
m_hDC = GetDC(m_hWnd);
m_Inited = true;
return 0;
}
#endif
#if BUILD_SDL
int Window::Init(const char* Title, uint Flags, int Width, int Height) {
XTRACE_FUNCTION;
if (m_Inited) {
return 1;
}
m_Window = SDL_CreateWindow(Title, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, Width, Height, Flags);
ASSERT(m_Window);
m_Inited = true;
return 0;
}
#endif
#if BUILD_WINDOWS_NO_SDL
// TODO: Add some failure handling, and meaningful return values
int Window::Show(int nCmdShow) {
ShowWindow(m_hWnd, nCmdShow);
SetWindowPos(m_hWnd, HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE); // Make sure we're on top
UpdateWindow(m_hWnd);
return 0;
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetStyle(DWORD Style) {
if (m_Inited) {
m_Style = Style;
SetWindowLongPtr(m_hWnd, GWL_STYLE, Style);
ShowWindow(m_hWnd, SW_SHOWNA);
// UpdateWindow( m_hWnd );
// SetWindowPos( m_hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE |
// SWP_NOZORDER | SWP_SHOWWINDOW );
}
return 0;
}
#endif
#if BUILD_SDL
int Window::Show() {
SDL_ShowWindow(m_Window);
return 0;
}
#endif
// TODO: Add some failure handling, and meaningful return values
int Window::Free() {
#if BUILD_WINDOWS_NO_SDL
char TempName[256];
GetClassName(m_hWnd, TempName, 256);
if (m_Inited) {
ReleaseDC(m_hWnd, m_hDC);
CHECK(DestroyWindow(m_hWnd));
CHECK(UnregisterClass(TempName, m_hInstance));
m_Inited = false;
return 0;
}
return 1;
#endif
#if BUILD_SDL
if (m_Window) {
SDL_DestroyWindow(m_Window);
m_Inited = false;
return 0;
} else {
return 1;
}
#endif
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetPosition(int x, int y) {
if (m_Inited) {
#if BUILD_WINDOWS_NO_SDL
SetWindowPos(m_hWnd, HWND_NOTOPMOST, x, y, 0, 0, SWP_NOSIZE);
#endif
#if BUILD_SDL
SDL_SetWindowPosition(m_Window, x, y);
#endif
}
return 0;
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetSize(int Width, int Height, bool AdjustForStyle) {
if (!m_Inited) {
return 0;
}
#if BUILD_WINDOWS_NO_SDL
RECT WindowRect;
WindowRect.left = 0;
WindowRect.right = Width;
WindowRect.top = 0;
WindowRect.bottom = Height;
if (AdjustForStyle) {
AdjustWindowRect(&WindowRect, m_Style, false);
Width = WindowRect.right - WindowRect.left;
Height = WindowRect.bottom - WindowRect.top;
}
{
POINT NotifySize;
NotifySize.x = Width;
NotifySize.y = Height;
WPARAM wParam = 0;
LPARAM lParam = reinterpret_cast<LPARAM>(&NotifySize);
SendMessage(m_hWnd, WM_NOTIFY_SIZE, wParam, lParam);
}
// NOTE: This is just to update the size, it does *not* position window at (0,
// 0) (SWP_NOMOVE flag).
const BOOL Success =
SetWindowPos(m_hWnd, HWND_NOTOPMOST, 0, 0, Width, Height, SWP_NOMOVE);
ASSERT(Success);
Unused(Success);
#if BUILD_DEV
GetWindowRect(m_hWnd, &WindowRect);
ASSERT(WindowRect.right - WindowRect.left == Width);
ASSERT(WindowRect.bottom - WindowRect.top == Height);
#endif
#endif // BUILD_WINDOWS_NO_SDL
#if BUILD_SDL
Unused(AdjustForStyle);
SDL_SetWindowSize(m_Window, Width, Height);
#endif
return 0;
}
int Window::SetSize(int Width, int Height, int ScreenWidth, int ScreenHeight,
bool AdjustForStyle) {
if (!m_Inited) {
return 0;
}
#if BUILD_WINDOWS_NO_SDL
RECT WindowRect;
WindowRect.left = 0;
WindowRect.right = Width;
WindowRect.top = 0;
WindowRect.bottom = Height;
if (AdjustForStyle) {
AdjustWindowRect(&WindowRect, m_Style, false);
Width = WindowRect.right - WindowRect.left;
Height = WindowRect.bottom - WindowRect.top;
}
// Center window, or just position in top-left if it won't fit
const int WindowX = Max(0, (ScreenWidth - Width) >> 1);
const int WindowY = Max(0, (ScreenHeight - Height) >> 1);
{
POINT NotifySize;
NotifySize.x = Width;
NotifySize.y = Height;
WPARAM wParam = 0;
LPARAM lParam = reinterpret_cast<LPARAM>(&NotifySize);
SendMessage(m_hWnd, WM_NOTIFY_SIZE, wParam, lParam);
}
const BOOL Success =
SetWindowPos(m_hWnd, HWND_NOTOPMOST, WindowX, WindowY, Width, Height, 0);
ASSERT(Success);
Unused(Success);
#if BUILD_DEV
GetWindowRect(m_hWnd, &WindowRect);
ASSERT(WindowRect.right - WindowRect.left == Width);
ASSERT(WindowRect.bottom - WindowRect.top == Height);
#endif
#endif // BUILD_WINDOWS_NO_SDL
#if BUILD_SDL
Unused(AdjustForStyle);
Unused(ScreenWidth);
Unused(ScreenHeight);
SDL_SetWindowSize(m_Window, Width, Height);
//IDOS->Delay(5);
SDL_SetWindowPosition(m_Window, SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED);
#endif
return 0;
}
// TODO: Add some failure handling, and meaningful return values
int Window::SetTitleText(const char* Text) {
if (m_Inited) {
#if BUILD_WINDOWS_NO_SDL
SetWindowText(m_hWnd, Text);
#endif
#if BUILD_SDL
SDL_SetWindowTitle(m_Window, Text);
#endif
}
return 0;
}
bool Window::HasFocus() const {
#if BUILD_WINDOWS_NO_SDL
return GetForegroundWindow() == m_hWnd;
#endif
#if BUILD_SDL
if (m_Inited) {
#ifdef PANDORA
// On Pandora, SDL2 use FB access, so no real Windows / multitask here...
return true;
#else
const Uint32 WindowFlags = SDL_GetWindowFlags(m_Window);
return (WindowFlags & SDL_WINDOW_INPUT_FOCUS) != 0;
#endif
} else {
return false;
}
#endif
}
void Window::SetBordered(const bool Bordered) {
#if BUILD_WINDOWS_NO_SDL
const DWORD StyleFlags =
Bordered ? (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX)
: WS_POPUP;
SetStyle(StyleFlags);
#endif
#if BUILD_SDL
SDL_SetWindowBordered(m_Window, Bordered ? SDL_TRUE : SDL_FALSE);
#endif
}
// NOTE: Used with SDL in place of managing display directly.
void Window::SetFullscreen(const bool Fullscreen) {
#if BUILD_WINDOWS_NO_SDL
Unused(Fullscreen);
#endif
#if BUILD_SDL
// NOTE: SDL also has a SDL_WINDOW_FULLSCREEN_DESKTOP for borderless
// "fullscreen windowed" mode,
// but I assume that would be redundant with the stuff I'm already doing to
// update window border.
SDL_SetWindowDisplayMode(m_Window, nullptr);
SDL_SetWindowFullscreen(m_Window, Fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
#endif
}
| 25.291444
| 80
| 0.689608
|
kas1e
|
9146e18996dd7ddcd5ff9bb6298e0de82f32c413
| 683
|
hpp
|
C++
|
tests/headers/doggo-or-null.hpp
|
j-channings/rust-bindgen
|
56e8cf97c9368e0bc9f20f5f66ca2a3773ab97b3
|
[
"BSD-3-Clause"
] | 1,848
|
2018-11-22T06:08:21.000Z
|
2022-03-31T10:54:10.000Z
|
tests/headers/doggo-or-null.hpp
|
j-channings/rust-bindgen
|
56e8cf97c9368e0bc9f20f5f66ca2a3773ab97b3
|
[
"BSD-3-Clause"
] | 845
|
2016-06-22T21:55:20.000Z
|
2018-10-31T15:50:10.000Z
|
tests/headers/doggo-or-null.hpp
|
j-channings/rust-bindgen
|
56e8cf97c9368e0bc9f20f5f66ca2a3773ab97b3
|
[
"BSD-3-Clause"
] | 274
|
2018-11-23T17:46:29.000Z
|
2022-03-27T04:52:37.000Z
|
// bindgen-flags: --opaque-type DoggoOrNull --with-derive-partialeq --with-derive-hash -- -std=c++14
class Doggo {
int x;
};
class Null {};
/**
* This type is an opaque union. Unions can't derive anything interesting like
* Debug or Default, even if their layout can, because it would require knowing
* which variant is in use. Opaque unions still end up as a `union` in the Rust
* bindings, but they just have one variant. Even so, can't derive. We should
* probably emit an opaque struct for opaque unions... but until then, we have
* this test to make sure that opaque unions don't derive and still compile.
*/
union DoggoOrNull {
Doggo doggo;
Null none;
};
| 32.52381
| 100
| 0.711567
|
j-channings
|
91507b9134518b80e1815709a4ff2ece9644e3da
| 214
|
hpp
|
C++
|
src/App/Configuration.hpp
|
psiberx/cp2077-tweak-xl
|
ed974dc664092c8d1f8831c39a5c5b2634ddf72e
|
[
"MIT"
] | 6
|
2022-03-01T03:46:46.000Z
|
2022-03-31T21:12:31.000Z
|
src/App/Configuration.hpp
|
psiberx/cp2077-tweak-xl
|
ed974dc664092c8d1f8831c39a5c5b2634ddf72e
|
[
"MIT"
] | null | null | null |
src/App/Configuration.hpp
|
psiberx/cp2077-tweak-xl
|
ed974dc664092c8d1f8831c39a5c5b2634ddf72e
|
[
"MIT"
] | null | null | null |
#pragma once
#include "stdafx.hpp"
#include "Core/Facades/Runtime.hpp"
namespace App::Configuration
{
inline std::filesystem::path GetTweaksDir()
{
return Core::Runtime::GetRootDir() / L"r6" / L"tweaks";
}
}
| 16.461538
| 59
| 0.705607
|
psiberx
|
9154bf90e1c29faee6cf9a7df244edf60f80908d
| 1,781
|
hpp
|
C++
|
Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp
|
p-adic/cpp
|
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
|
[
"MIT"
] | 2
|
2020-09-13T07:31:22.000Z
|
2022-03-26T08:37:32.000Z
|
Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp
|
p-adic/cpp
|
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
|
[
"MIT"
] | null | null | null |
Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp
|
p-adic/cpp
|
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
|
[
"MIT"
] | null | null | null |
// c:/Users/user/Documents/Programming/Mathematics/Function/Computable/Expression/List/Body/a_Body.hpp
#pragma once
#include "a.hpp"
#include "../a.hpp"
#include "../../Variable/a.hpp"
#include "../../a.hpp"
#include "../a_Body.hpp"
#include "../../Variable/a_Body.hpp"
#include "../../a_Body.hpp"
#include "../../../Type/Guide/Valid/a_Body.hpp"
template <typename VArg> inline ExpressionOfComputableFunction<void>::ExpressionOfComputableFunction( const WrappedTypes<VArg>& ) : SyntaxOfComputableFunction( ExpressionString() , VariableString() , LdotsString() , GetTypeSyntax<VArg>().Get() ) {}
template <typename... VA>
ExpressionOfComputableFunction<void>::ExpressionOfComputableFunction( const ExpressionOfComputableFunction<VA>&... va ) : SyntaxOfComputableFunction( ExpressionString() , ListString() , va.Get()... )
{
VLTree<string>& t = Ref();
VLTree<string>::iterator itr_insert = t.LeftMostNode();
VLTree<string>::const_iterator itr = itr_insert;
itr++;
const uint& size = t.size();
uint i = 1;
string argument_name = "";
string argument_type_name = "";
if( size > 2 ){
argument_name = "( ";
}
TRY_CATCH
(
{
while( i < size ){
if( i > 1 ){
argument_name += " , ";
argument_type_name += " \\times ";
}
auto itr_copy = itr;
argument_name += SyntaxToString( itr_copy , 2 );
argument_type_name += SyntaxToString( itr_copy , 2 );
itr++;
i++;
}
} ,
const ErrorType& e ,
CALL_P( e , i , argument_name , argument_type_name )
);
if( size > 2 ){
argument_name += " )";
}
t.insert( itr_insert , argument_type_name );
t.insert( itr_insert , argument_name );
}
| 22.833333
| 249
| 0.613139
|
p-adic
|
91572fbae81e4c5c4e5530024cfe094c7435fa7c
| 1,612
|
cpp
|
C++
|
Day12/Graph_topSortKahnAlgo.cpp
|
tejaswini212/100-Days-Of-Algo
|
ae90e91e302e2f1c9b1c067416fcb0bc42b12e99
|
[
"MIT"
] | 1
|
2022-03-31T13:49:46.000Z
|
2022-03-31T13:49:46.000Z
|
Day12/Graph_topSortKahnAlgo.cpp
|
tejaswini212/100-Days-Of-Algo
|
ae90e91e302e2f1c9b1c067416fcb0bc42b12e99
|
[
"MIT"
] | null | null | null |
Day12/Graph_topSortKahnAlgo.cpp
|
tejaswini212/100-Days-Of-Algo
|
ae90e91e302e2f1c9b1c067416fcb0bc42b12e99
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
class Graph{
int V;
list<int> *adj;
public:
Graph(int V){
this->V = V;
adj = new list<int> [V];
}
void addEdge(int u,int v){
adj[u].push_back(v);
}
void topSort();
};
void Graph::topSort(){
//vector to store indegrees of all the nodes
vector<int> in_degree(V,0);
for(int u=0;u<V;u++){
list<int>::iterator itr;
for(itr=adj[u].begin();itr!=adj[u].end();itr++){
in_degree[*itr]++;
}
}
//queue is created and all nodes with indegree equal to zero are enqueued
queue<int> q;
for(int i=0;i<V;i++)
if(in_degree[i]==0)
q.push(i);
//vector to store topological order
vector<int> top_order;
int countVisited=0;
while(!q.empty()){
int u=q.front();
q.pop();
top_order.push_back(u);
list<int>::iterator itr;
for(itr=adj[u].begin();itr!=adj[u].end();itr++)
if(--in_degree[*itr]==0)
q.push(*itr);
countVisited++;
}
if(countVisited!=V){
cout<<"There exists a cycle in a graph\n";
}
else{
cout<<"Below is the topological sort of given graph:\n";
for(int i=0;i<V;i++)
cout<<top_order[i]<<" ";
cout<<"\n";
}
}
int main(){
Graph g(6);
g.addEdge(0,1);
g.addEdge(1,5);
g.addEdge(2,5);
g.addEdge(2,4);
g.addEdge(1,4);
g.addEdge(4,3);
g.addEdge(3,0);
g.topSort();
return 0;
}
| 19.658537
| 77
| 0.485112
|
tejaswini212
|
915be2ee2f6f333f2a943562f1c8e1fd228b778a
| 489
|
cpp
|
C++
|
sg/renderer/materials/ThinGlass.cpp
|
ebachard/ospray_studio
|
78928c93b482f9f95aa300c8f58c728dadedbe2f
|
[
"Apache-2.0"
] | 52
|
2018-10-09T23:56:32.000Z
|
2022-03-25T09:27:40.000Z
|
sg/renderer/materials/ThinGlass.cpp
|
ebachard/ospray_studio
|
78928c93b482f9f95aa300c8f58c728dadedbe2f
|
[
"Apache-2.0"
] | 11
|
2018-11-19T18:51:47.000Z
|
2022-03-28T14:03:57.000Z
|
sg/renderer/materials/ThinGlass.cpp
|
ebachard/ospray_studio
|
78928c93b482f9f95aa300c8f58c728dadedbe2f
|
[
"Apache-2.0"
] | 8
|
2019-02-10T00:16:24.000Z
|
2022-02-17T19:50:15.000Z
|
// Copyright 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "../Material.h"
namespace ospray {
namespace sg {
struct OSPSG_INTERFACE ThinGlass : public Material
{
ThinGlass();
~ThinGlass() override = default;
};
OSP_REGISTER_SG_NODE_NAME(ThinGlass, thinGlass);
// ThinGlass definitions //////////////////////////////////////////////////
ThinGlass::ThinGlass() : Material("thinGlass")
{
}
} // namespace sg
} // namespace ospray
| 18.807692
| 77
| 0.615542
|
ebachard
|
915dd98f431a89b44683368c0710b1869d5a1d3e
| 31,792
|
cpp
|
C++
|
src/ScreenManager.cpp
|
graemephi/etterna
|
b984fe493d9f7ac84a35af3e6f80f16607aceb09
|
[
"MIT"
] | null | null | null |
src/ScreenManager.cpp
|
graemephi/etterna
|
b984fe493d9f7ac84a35af3e6f80f16607aceb09
|
[
"MIT"
] | null | null | null |
src/ScreenManager.cpp
|
graemephi/etterna
|
b984fe493d9f7ac84a35af3e6f80f16607aceb09
|
[
"MIT"
] | null | null | null |
/*
* We maintain a pool of "prepared" screens, which are screens previously loaded
* to be available on demand.
*
* When a screen pops off the stack that's in g_setPersistantScreens, it goes to
* the prepared list. If that screen is used again before it's deleted, it'll
* be reused.
*
* Typically, the first screen in a group will prepare all of the nearby screens
* it may load. When it loads one, the prepared screen will be used.
*
* A group of screens may only want to preload some screens, and not others,
* while still considering those screens part of the same group. For example,
* an attract loop typically has several very lightweight screens and a few
* expensive screens. Preloading the lightweight screens can improve
* responsiveness, but preloading the expensive screens may use too much memory
* and take too long to load all at once. By calling GroupScreen(), entering
* these screens will not trigger cleanup.
*
* Example uses:
* - ScreenOptions1 preloads ScreenOptions2, and persists both. Moving from
* Options1 and Options2 and back is instant and reuses both.
* - ScreenMenu groups and persists itself and ScreenSubmenu. ScreenSubmenu
* is not preloaded, so it will be loaded on demand the first time it's used,
* but will remain loaded if it returns to ScreenMenu.
* - ScreenSelectMusic groups itself and ScreenPlayerOptions, and persists only
* ScreenSelectMusic. This will cause SSMusic will be loaded once, and SPO
* to be loaded on demand.
* - ScreenAttract1 preloads and persists ScreenAttract1, 3, 5 and 7, and
* groups 1 through 7. 1, 3, 5 and 7 will remain in memory; the rest will be
* loaded on demand.
*
* If a screen is added to the screen stack that isn't in the current screen
* group (added to by GroupScreen), the screen group is reset: all prepared
* screens are unloaded and the persistence list is cleared.
*
* Note that not all screens yet support reuse in this way; proper use of
* BeginScreen is required. This will misbehave if a screen pushes another
* screen that's already in use lower on the stack, but that's not useful; it
* would allow infinite screen recursion.
*
* SM_GainFocus/SM_LoseFocus: These are sent to screens when they become the
* topmost screen, or stop being the topmost screen.
*
* A few subtleties:
*
* With delayed screens (eg. ScreenGameplay being pre-loaded by ScreenStage),
* SM_GainFocus isn't sent until the loaded screen actually is activated (put on
* the stack).
*
* With normal screen loads, the new screen is loaded before the old screen is
* destroyed. This means that the old dtor is called *after* the new ctor. If
* some global properties (eg. GAMESTATE) are being unset by the old screen's
* destructor, and set by the new screen's constructor, they'll happen in the
* wrong order. Use SM_GainFocus and SM_LoseFocus, instead.
*
* SM_LoseFocus is always sent after SM_GainFocus, and vice-versa: you can't
* gain focus if you already have it, and you can't lose focus if you don't have
* it.
*/
#include "global.h"
#include "ActorUtil.h"
#include "FontManager.h"
#include "Foreach.h"
#include "GameSoundManager.h"
#include "InputEventPlus.h"
#include "Preference.h"
#include "RageDisplay.h"
#include "RageLog.h"
#include "RageTextureManager.h"
#include "RageUtil.h"
#include "Screen.h"
#include "ScreenDimensions.h"
#include "ScreenManager.h"
#include "SongManager.h"
#include "ThemeManager.h"
ScreenManager* SCREENMAN =
NULL; // global and accessible from anywhere in our program
static Preference<bool> g_bDelayedScreenLoad("DelayedScreenLoad", false);
// static Preference<bool> g_bPruneFonts( "PruneFonts", true );
// Screen registration
static map<RString, CreateScreenFn>* g_pmapRegistrees = NULL;
/** @brief Utility functions for the ScreenManager. */
namespace ScreenManagerUtil {
// in draw order first to last
struct LoadedScreen
{
Screen* m_pScreen;
/* Normally true. If false, the screen is owned by another screen
* and was given to us for use, and it's not ours to free. */
bool m_bDeleteWhenDone;
ScreenMessage m_SendOnPop;
LoadedScreen()
{
m_pScreen = NULL;
m_bDeleteWhenDone = true;
m_SendOnPop = SM_None;
}
};
Actor* g_pSharedBGA; // BGA object that's persistent between screens
RString m_sPreviousTopScreen;
vector<LoadedScreen> g_ScreenStack; // bottommost to topmost
vector<Screen*> g_OverlayScreens;
set<RString> g_setGroupedScreens;
set<RString> g_setPersistantScreens;
vector<LoadedScreen> g_vPreparedScreens;
vector<Actor*> g_vPreparedBackgrounds;
// Add a screen to g_ScreenStack. This is the only function that adds to
// g_ScreenStack.
void
PushLoadedScreen(const LoadedScreen& ls)
{
LOG->Trace("PushScreen: \"%s\"", ls.m_pScreen->GetName().c_str());
LOG->MapLog("ScreenManager::TopScreen",
"Top Screen: %s",
ls.m_pScreen->GetName().c_str());
// Be sure to push the screen first, so GetTopScreen returns the screen
// during BeginScreen.
g_ScreenStack.push_back(ls);
// Set the name of the loading screen.
{
LuaThreadVariable var1("PreviousScreen", m_sPreviousTopScreen);
LuaThreadVariable var2("LoadingScreen", ls.m_pScreen->GetName());
ls.m_pScreen->BeginScreen();
}
// If this is the new top screen, save the name.
if (g_ScreenStack.size() == 1)
m_sPreviousTopScreen = ls.m_pScreen->GetName();
SCREENMAN->RefreshCreditsMessages();
SCREENMAN->PostMessageToTopScreen(SM_GainFocus, 0);
}
bool
ScreenIsPrepped(const RString& sScreenName)
{
FOREACH(LoadedScreen, g_vPreparedScreens, s)
{
if (s->m_pScreen->GetName() == sScreenName)
return true;
}
return false;
}
/* If the named screen is loaded, remove it from the prepared list and
* return it in ls. */
bool
GetPreppedScreen(const RString& sScreenName, LoadedScreen& ls)
{
FOREACH(LoadedScreen, g_vPreparedScreens, s)
{
if (s->m_pScreen->GetName() == sScreenName) {
ls = *s;
g_vPreparedScreens.erase(s);
return true;
}
}
return false;
}
void
BeforeDeleteScreen()
{
// Deleting a screen can take enough time to cause a frame skip.
SCREENMAN->ZeroNextUpdate();
}
/* If we're deleting a screen, it's probably releasing texture and other
* resources, so trigger cleanups. */
void
AfterDeleteScreen()
{
/* Now that we've actually deleted a screen, it makes sense to clear out
* cached textures. */
TEXTUREMAN->DeleteCachedTextures();
/* Cleanup song data. This can free up a fair bit of memory, so do it
* after deleting screens. */
SONGMAN->Cleanup();
}
/* Take ownership of all screens and backgrounds that are owned by
* us (this excludes screens where m_bDeleteWhenDone is false).
* Clear the prepared lists. The contents of apOut must be
* freed by the caller. */
void
GrabPreparedActors(vector<Actor*>& apOut)
{
FOREACH(LoadedScreen, g_vPreparedScreens, s)
if (s->m_bDeleteWhenDone)
apOut.push_back(s->m_pScreen);
g_vPreparedScreens.clear();
FOREACH(Actor*, g_vPreparedBackgrounds, a)
apOut.push_back(*a);
g_vPreparedBackgrounds.clear();
g_setGroupedScreens.clear();
g_setPersistantScreens.clear();
}
/* Called when changing screen groups. Delete all prepared screens,
* reset the screen group and list of persistant screens. */
void
DeletePreparedScreens()
{
vector<Actor*> apActorsToDelete;
GrabPreparedActors(apActorsToDelete);
BeforeDeleteScreen();
FOREACH(Actor*, apActorsToDelete, a)
SAFE_DELETE(*a);
AfterDeleteScreen();
}
} // namespace ScreenManagerUtil;
using namespace ScreenManagerUtil;
RegisterScreenClass::RegisterScreenClass(const RString& sClassName,
CreateScreenFn pfn)
{
if (g_pmapRegistrees == NULL)
g_pmapRegistrees = new map<RString, CreateScreenFn>;
map<RString, CreateScreenFn>::iterator iter =
g_pmapRegistrees->find(sClassName);
ASSERT_M(
iter == g_pmapRegistrees->end(),
ssprintf("Screen class '%s' already registered.", sClassName.c_str()));
(*g_pmapRegistrees)[sClassName] = pfn;
}
ScreenManager::ScreenManager()
{
// Register with Lua.
{
Lua* L = LUA->Get();
lua_pushstring(L, "SCREENMAN");
this->PushSelf(L);
lua_settable(L, LUA_GLOBALSINDEX);
LUA->Release(L);
}
g_pSharedBGA = new Actor;
m_bReloadOverlayScreensAfterInput = false;
m_bZeroNextUpdate = false;
m_PopTopScreen = SM_Invalid;
m_OnDonePreparingScreen = SM_Invalid;
}
ScreenManager::~ScreenManager()
{
LOG->Trace("ScreenManager::~ScreenManager()");
LOG->UnmapLog("ScreenManager::TopScreen");
SAFE_DELETE(g_pSharedBGA);
for (unsigned i = 0; i < g_ScreenStack.size(); i++) {
if (g_ScreenStack[i].m_bDeleteWhenDone)
SAFE_DELETE(g_ScreenStack[i].m_pScreen);
}
g_ScreenStack.clear();
DeletePreparedScreens();
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
SAFE_DELETE(g_OverlayScreens[i]);
g_OverlayScreens.clear();
// Unregister with Lua.
LUA->UnsetGlobal("SCREENMAN");
}
// This is called when we start up, and when the theme changes or is reloaded.
void
ScreenManager::ThemeChanged()
{
LOG->Trace("ScreenManager::ThemeChanged");
// reload common sounds
m_soundStart.Load(THEME->GetPathS("Common", "start"));
m_soundCoin.Load(THEME->GetPathS("Common", "coin"), true);
m_soundCancel.Load(THEME->GetPathS("Common", "cancel"), true);
m_soundInvalid.Load(THEME->GetPathS("Common", "invalid"));
m_soundScreenshot.Load(THEME->GetPathS("Common", "screenshot"));
// reload song manager colors (to avoid crashes) -aj
SONGMAN->ResetGroupColors();
ReloadOverlayScreens();
// force recreate of new BGA
SAFE_DELETE(g_pSharedBGA);
g_pSharedBGA = new Actor;
}
void
ScreenManager::ReloadOverlayScreens()
{
// unload overlay screens
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
SAFE_DELETE(g_OverlayScreens[i]);
g_OverlayScreens.clear();
// reload overlay screens
RString sOverlays = THEME->GetMetric("Common", "OverlayScreens");
vector<RString> asOverlays;
split(sOverlays, ",", asOverlays);
for (unsigned i = 0; i < asOverlays.size(); i++) {
Screen* pScreen = MakeNewScreen(asOverlays[i]);
if (pScreen) {
LuaThreadVariable var2("LoadingScreen", pScreen->GetName());
pScreen->BeginScreen();
g_OverlayScreens.push_back(pScreen);
}
}
this->RefreshCreditsMessages();
}
void
ScreenManager::ReloadOverlayScreensAfterInputFinishes()
{
m_bReloadOverlayScreensAfterInput = true;
}
Screen*
ScreenManager::GetTopScreen()
{
if (g_ScreenStack.empty())
return NULL;
return g_ScreenStack[g_ScreenStack.size() - 1].m_pScreen;
}
Screen*
ScreenManager::GetScreen(int iPosition)
{
if (iPosition >= (int)g_ScreenStack.size())
return NULL;
return g_ScreenStack[iPosition].m_pScreen;
}
bool
ScreenManager::AllowOperatorMenuButton() const
{
FOREACH(LoadedScreen, g_ScreenStack, s)
{
if (!s->m_pScreen->AllowOperatorMenuButton())
return false;
}
return true;
}
bool
ScreenManager::IsScreenNameValid(RString const& name) const
{
if (name.empty() || !THEME->HasMetric(name, "Class")) {
return false;
}
RString ClassName = THEME->GetMetric(name, "Class");
return g_pmapRegistrees->find(ClassName) != g_pmapRegistrees->end();
}
bool
ScreenManager::IsStackedScreen(const Screen* pScreen) const
{
// True if the screen is in the screen stack, but not the first.
for (unsigned i = 1; i < g_ScreenStack.size(); ++i)
if (g_ScreenStack[i].m_pScreen == pScreen)
return true;
return false;
}
bool
ScreenManager::get_input_redirected(PlayerNumber pn)
{
if (static_cast<size_t>(pn) >= m_input_redirected.size()) {
return false;
}
return m_input_redirected[pn];
}
void
ScreenManager::set_input_redirected(PlayerNumber pn, bool redir)
{
while (static_cast<size_t>(pn) >= m_input_redirected.size()) {
m_input_redirected.push_back(false);
}
m_input_redirected[pn] = redir;
}
/* Pop the top screen off the stack, sending SM_LoseFocus messages and
* returning the message the popped screen wants sent to the new top
* screen. Does not send SM_GainFocus. */
ScreenMessage
ScreenManager::PopTopScreenInternal(bool bSendLoseFocus)
{
if (g_ScreenStack.empty())
return SM_None;
LoadedScreen ls = g_ScreenStack.back();
g_ScreenStack.erase(g_ScreenStack.end() - 1, g_ScreenStack.end());
if (bSendLoseFocus)
ls.m_pScreen->HandleScreenMessage(SM_LoseFocus);
ls.m_pScreen->EndScreen();
if (g_setPersistantScreens.find(ls.m_pScreen->GetName()) !=
g_setPersistantScreens.end()) {
// Move the screen back to the prepared list.
g_vPreparedScreens.push_back(ls);
} else {
if (ls.m_bDeleteWhenDone) {
BeforeDeleteScreen();
SAFE_DELETE(ls.m_pScreen);
AfterDeleteScreen();
}
}
if (g_ScreenStack.size())
LOG->MapLog("ScreenManager::TopScreen",
"Top Screen: %s",
g_ScreenStack.back().m_pScreen->GetName().c_str());
else
LOG->UnmapLog("ScreenManager::TopScreen");
return ls.m_SendOnPop;
}
void
ScreenManager::Update(float fDeltaTime)
{
// Pop the top screen, if PopTopScreen was called.
if (m_PopTopScreen != SM_Invalid) {
ScreenMessage SM = m_PopTopScreen;
m_PopTopScreen = SM_Invalid;
ScreenMessage SM2 = PopTopScreenInternal();
SendMessageToTopScreen(SM_GainFocus);
SendMessageToTopScreen(SM);
SendMessageToTopScreen(SM2);
}
/* Screens take some time to load. If we don't do this, then screens
* receive an initial update that includes all of the time they spent
* loading, which will chop off their tweens.
*
* We don't want to simply cap update times; for example, the stage
* screen sets a 4 second timer, preps the gameplay screen, and then
* displays the prepped screen after the timer runs out; this lets the
* load time be masked (as long as the load takes less than 4 seconds).
* If we cap that large update delta from the screen load, the update
* to load the new screen will come after 4 seconds plus the load time.
*
* So, let's just zero the first update for every screen. */
ASSERT(!g_ScreenStack.empty() ||
m_sDelayedScreen !=
""); // Why play the game if there is nothing showing?
Screen* pScreen = g_ScreenStack.empty() ? NULL : GetTopScreen();
bool bFirstUpdate = pScreen && pScreen->IsFirstUpdate();
/* Loading a new screen can take seconds and cause a big jump on the new
* Screen's first update. Clamp the first update delta so that the
* animations don't jump. */
if ((pScreen != nullptr) && m_bZeroNextUpdate) {
LOG->Trace("Zeroing this update. Was %f", fDeltaTime);
fDeltaTime = 0;
m_bZeroNextUpdate = false;
}
// Update screens.
{
for (unsigned i = 0; i < g_ScreenStack.size(); i++)
g_ScreenStack[i].m_pScreen->Update(fDeltaTime);
g_pSharedBGA->Update(fDeltaTime);
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
g_OverlayScreens[i]->Update(fDeltaTime);
}
/* The music may be started on the first update. If we're reading from a CD,
* it might not start immediately. Make sure we start playing the sound
* before continuing, since it's strange to start rendering before the music
* starts. */
if (bFirstUpdate)
SOUND->Flush();
/* If we're currently inside a background screen load, and m_sDelayedScreen
* is set, then the screen called SetNewScreen before we finished preparing.
* Postpone it until we're finished loading. */
if (m_sDelayedScreen.size() != 0) {
LoadDelayedScreen();
}
}
void
ScreenManager::Draw()
{
/* If it hasn't been updated yet, skip the render. We can't call Update(0),
* since that'll confuse the "zero out the next update after loading a
* screen logic. If we don't render, don't call BeginFrame or EndFrame. That
* way, we won't clear the buffer, and we won't wait for vsync. */
if (g_ScreenStack.size() && g_ScreenStack.back().m_pScreen->IsFirstUpdate())
return;
if (!DISPLAY->BeginFrame())
return;
DISPLAY->CameraPushMatrix();
DISPLAY->LoadMenuPerspective(
0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_CENTER_X, SCREEN_CENTER_Y);
g_pSharedBGA->Draw();
DISPLAY->CameraPopMatrix();
for (unsigned i = 0; i < g_ScreenStack.size();
i++) // Draw all screens bottom to top
g_ScreenStack[i].m_pScreen->Draw();
for (unsigned i = 0; i < g_OverlayScreens.size(); i++)
g_OverlayScreens[i]->Draw();
DISPLAY->EndFrame();
}
void
ScreenManager::Input(const InputEventPlus& input)
{
// LOG->Trace( "ScreenManager::Input( %d-%d, %d-%d, %d-%d, %d-%d )",
// DeviceI.device, DeviceI.button, GameI.controller, GameI.button,
// MenuI.player, MenuI.button, StyleI.player, StyleI.col );
// First, give overlay screens a shot at the input. If Input returns
// true, it handled the input, so don't pass it further.
for (unsigned i = 0; i < g_OverlayScreens.size(); ++i) {
Screen* pScreen = g_OverlayScreens[i];
bool handled = pScreen->Input(input);
// Pass input to the screen and lua. Contention shouldn't be a problem
// because anybody setting an input callback is probably doing it to
// do something in addition to whatever the screen does.
if (pScreen->PassInputToLua(input) || handled) {
if (m_bReloadOverlayScreensAfterInput) {
ReloadOverlayScreens();
m_bReloadOverlayScreensAfterInput = false;
}
return;
}
}
// Pass input to the topmost screen. If we have a new top screen pending,
// don't send to the old screen, but do send to overlay screens.
if (m_sDelayedScreen != "")
return;
if (g_ScreenStack.empty())
return;
if (!get_input_redirected(input.pn)) {
g_ScreenStack.back().m_pScreen->Input(input);
}
g_ScreenStack.back().m_pScreen->PassInputToLua(input);
}
// Just create a new screen; don't do any associated cleanup.
Screen*
ScreenManager::MakeNewScreen(const RString& sScreenName)
{
RageTimer t;
LOG->Trace("Loading screen: \"%s\"", sScreenName.c_str());
RString sClassName = THEME->GetMetric(sScreenName, "Class");
map<RString, CreateScreenFn>::iterator iter =
g_pmapRegistrees->find(sClassName);
if (iter == g_pmapRegistrees->end()) {
LuaHelpers::ReportScriptErrorFmt(
"Screen \"%s\" has an invalid class \"%s\".",
sScreenName.c_str(),
sClassName.c_str());
return NULL;
}
this->ZeroNextUpdate();
CreateScreenFn pfn = iter->second;
Screen* ret = pfn(sScreenName);
LOG->Trace("Loaded \"%s\" (\"%s\") in %f",
sScreenName.c_str(),
sClassName.c_str(),
t.GetDeltaTime());
return ret;
}
void
ScreenManager::PrepareScreen(const RString& sScreenName)
{
// If the screen is already prepared, stop.
if (ScreenIsPrepped(sScreenName))
return;
Screen* pNewScreen = MakeNewScreen(sScreenName);
if (pNewScreen == NULL) {
return;
}
{
LoadedScreen ls;
ls.m_pScreen = pNewScreen;
g_vPreparedScreens.push_back(ls);
}
/* Don't delete previously prepared versions of the screen's background,
* and only prepare it if it's different than the current background
* and not already loaded. */
RString sNewBGA = THEME->GetPathB(sScreenName, "background");
if (!sNewBGA.empty() && sNewBGA != g_pSharedBGA->GetName()) {
Actor* pNewBGA = NULL;
FOREACH(Actor*, g_vPreparedBackgrounds, a)
{
if ((*a)->GetName() == sNewBGA) {
pNewBGA = *a;
break;
}
}
// Create the new background before deleting the previous so that we
// keep any common textures loaded.
if (pNewBGA == NULL) {
LOG->Trace("Loading screen background \"%s\"", sNewBGA.c_str());
Actor* pActor = ActorUtil::MakeActor(sNewBGA);
if (pActor != NULL) {
pActor->SetName(sNewBGA);
g_vPreparedBackgrounds.push_back(pActor);
}
}
}
// Prune any unused fonts now that we have had a chance to reference the
// fonts
/*
if(g_bPruneFonts) {
FONT->PruneFonts();
}
*/
// TEXTUREMAN->DiagnosticOutput();
}
void
ScreenManager::GroupScreen(const RString& sScreenName)
{
g_setGroupedScreens.insert(sScreenName);
}
void
ScreenManager::PersistantScreen(const RString& sScreenName)
{
g_setPersistantScreens.insert(sScreenName);
}
void
ScreenManager::SetNewScreen(const RString& sScreenName)
{
ASSERT(sScreenName != "");
m_sDelayedScreen = sScreenName;
}
/* Activate the screen and/or its background, if either are loaded.
* Return true if both were activated. */
bool
ScreenManager::ActivatePreparedScreenAndBackground(const RString& sScreenName)
{
bool bLoadedBoth = true;
// Find the prepped screen.
if (GetTopScreen() == NULL || GetTopScreen()->GetName() != sScreenName) {
LoadedScreen ls;
if (!GetPreppedScreen(sScreenName, ls)) {
bLoadedBoth = false;
} else {
PushLoadedScreen(ls);
}
}
// Find the prepared shared background (if any), and activate it.
RString sNewBGA = THEME->GetPathB(sScreenName, "background");
if (sNewBGA != g_pSharedBGA->GetName()) {
Actor* pNewBGA = NULL;
if (sNewBGA.empty()) {
pNewBGA = new Actor;
} else {
FOREACH(Actor*, g_vPreparedBackgrounds, a)
{
if ((*a)->GetName() == sNewBGA) {
pNewBGA = *a;
g_vPreparedBackgrounds.erase(a);
break;
}
}
}
/* If the BGA isn't loaded yet, load a dummy actor. If we're not going
* to use the same BGA for the new screen, always move the old BGA back
* to g_vPreparedBackgrounds now. */
if (pNewBGA == NULL) {
bLoadedBoth = false;
pNewBGA = new Actor;
}
/* Move the old background back to the prepared list, or delete it if
* it's a blank actor. */
if (g_pSharedBGA->GetName() == "")
delete g_pSharedBGA;
else
g_vPreparedBackgrounds.push_back(g_pSharedBGA);
g_pSharedBGA = pNewBGA;
g_pSharedBGA->PlayCommand("On");
}
return bLoadedBoth;
}
void
ScreenManager::LoadDelayedScreen()
{
RString sScreenName = m_sDelayedScreen;
m_sDelayedScreen = "";
if (!IsScreenNameValid(sScreenName)) {
LuaHelpers::ReportScriptError(
"Tried to go to invalid screen: " + sScreenName, "INVALID_SCREEN");
return;
}
// Pop the top screen, if any.
ScreenMessage SM = PopTopScreenInternal();
/* If the screen is already prepared, activate it before performing any
* cleanup, so it doesn't get deleted by cleanup. */
bool bLoaded = ActivatePreparedScreenAndBackground(sScreenName);
vector<Actor*> apActorsToDelete;
if (g_setGroupedScreens.find(sScreenName) == g_setGroupedScreens.end()) {
/* It's time to delete all old prepared screens. Depending on
* DelayedScreenLoad, we can either delete the screens before or after
* we load the new screen. Either way, we must remove them from the
* prepared list before we prepare new screens.
* If DelayedScreenLoad is true, delete them now; this lowers memory
* requirements, but results in redundant loads as we unload common
* data. */
if (g_bDelayedScreenLoad)
DeletePreparedScreens();
else
GrabPreparedActors(apActorsToDelete);
}
// If the screen wasn't already prepared, load it.
if (!bLoaded) {
PrepareScreen(sScreenName);
// Screens may not call SetNewScreen from the ctor or Init(). (We don't
// do this check inside PrepareScreen; that may be called from a thread
// for concurrent loading, and the main thread may call SetNewScreen
// during that time.) Emit an error instead of asserting. -Kyz
if (!m_sDelayedScreen.empty()) {
LuaHelpers::ReportScriptError(
"Setting a new screen during an InitCommand is not allowed.");
m_sDelayedScreen = "";
}
bLoaded = ActivatePreparedScreenAndBackground(sScreenName);
ASSERT(bLoaded);
}
if (!apActorsToDelete.empty()) {
BeforeDeleteScreen();
FOREACH(Actor*, apActorsToDelete, a)
SAFE_DELETE(*a);
AfterDeleteScreen();
}
MESSAGEMAN->Broadcast(Message_ScreenChanged);
SendMessageToTopScreen(SM);
}
void
ScreenManager::AddNewScreenToTop(const RString& sScreenName,
ScreenMessage SendOnPop)
{
// Load the screen, if it's not already prepared.
PrepareScreen(sScreenName);
// Find the prepped screen.
LoadedScreen ls;
bool screen_load_success = GetPreppedScreen(sScreenName, ls);
ASSERT_M(
screen_load_success,
ssprintf("ScreenManager::AddNewScreenToTop: Failed to load screen %s",
sScreenName.c_str()));
ls.m_SendOnPop = SendOnPop;
if (g_ScreenStack.size())
g_ScreenStack.back().m_pScreen->HandleScreenMessage(SM_LoseFocus);
PushLoadedScreen(ls);
}
void
ScreenManager::PopTopScreen(ScreenMessage SM)
{
ASSERT(g_ScreenStack.size() > 0);
m_PopTopScreen = SM;
}
/* Clear the screen stack; only used before major, unusual state changes,
* such as resetting the game or jumping to the service menu. Don't call
* from inside a screen. */
void
ScreenManager::PopAllScreens()
{
// Make sure only the top screen receives LoseFocus.
bool bFirst = true;
while (!g_ScreenStack.empty()) {
PopTopScreenInternal(bFirst);
bFirst = false;
}
DeletePreparedScreens();
}
void
ScreenManager::PostMessageToTopScreen(ScreenMessage SM, float fDelay)
{
Screen* pTopScreen = GetTopScreen();
if (pTopScreen != NULL)
pTopScreen->PostScreenMessage(SM, fDelay);
}
void
ScreenManager::SendMessageToTopScreen(ScreenMessage SM)
{
Screen* pTopScreen = GetTopScreen();
if (pTopScreen != NULL)
pTopScreen->HandleScreenMessage(SM);
}
void
ScreenManager::SystemMessage(const RString& sMessage)
{
LOG->Trace("%s", sMessage.c_str());
Message msg("SystemMessage");
msg.SetParam("Message", sMessage);
msg.SetParam("NoAnimate", false);
MESSAGEMAN->Broadcast(msg);
}
void
ScreenManager::SystemMessageNoAnimate(const RString& sMessage)
{
// LOG->Trace( "%s", sMessage.c_str() ); // don't log because the caller
// is likely calling us every frame
Message msg("SystemMessage");
msg.SetParam("Message", sMessage);
msg.SetParam("NoAnimate", true);
MESSAGEMAN->Broadcast(msg);
}
void
ScreenManager::HideSystemMessage()
{
MESSAGEMAN->Broadcast("HideSystemMessage");
}
void
ScreenManager::RefreshCreditsMessages()
{
MESSAGEMAN->Broadcast("RefreshCreditText");
}
void
ScreenManager::ZeroNextUpdate()
{
m_bZeroNextUpdate = true;
/* Loading probably took a little while. Let's reset stats. This prevents
* us from displaying an unnaturally low FPS value, and the next FPS value
* we display will be accurate, which makes skips in the initial tween-ins
* more apparent. */
DISPLAY->ResetStats();
}
/** @brief Offer a quick way to play any critical sound. */
#define PLAY_CRITICAL(snd) \
\
{ \
RageSoundParams p; \
p.m_bIsCriticalSound = true; \
(snd).Play(false, &p); \
\
}
/* Always play these sounds, even if we're in a silent attract loop. */
void
ScreenManager::PlayInvalidSound()
{
PLAY_CRITICAL(m_soundInvalid);
}
void
ScreenManager::PlayStartSound()
{
PLAY_CRITICAL(m_soundStart);
}
void
ScreenManager::PlayCoinSound()
{
PLAY_CRITICAL(m_soundCoin);
}
void
ScreenManager::PlayCancelSound()
{
PLAY_CRITICAL(m_soundCancel);
}
void
ScreenManager::PlayScreenshotSound()
{
PLAY_CRITICAL(m_soundScreenshot);
}
#undef PLAY_CRITICAL
void
ScreenManager::PlaySharedBackgroundOffCommand()
{
g_pSharedBGA->PlayCommand("Off");
}
// lua start
#include "LuaBinding.h"
/** @brief Allow Lua to have access to the ScreenManager. */
class LunaScreenManager : public Luna<ScreenManager>
{
public:
// Note: PrepareScreen binding is not allowed; loading data inside
// Lua causes the Lua lock to be held for the duration of the load,
// which blocks concurrent rendering
static void ValidateScreenName(lua_State* L, RString& name)
{
if (name == "") {
RString errstr = "Screen name is empty.";
SCREENMAN->SystemMessage(errstr);
luaL_error(L, errstr.c_str());
}
RString ClassName = THEME->GetMetric(name, "Class");
if (g_pmapRegistrees->find(ClassName) == g_pmapRegistrees->end()) {
RString errstr = "Screen \"" + name + "\" has an invalid class \"" +
ClassName + "\".";
SCREENMAN->SystemMessage(errstr);
luaL_error(L, errstr.c_str());
}
}
static int SetNewScreen(T* p, lua_State* L)
{
RString screen = SArg(1);
ValidateScreenName(L, screen);
p->SetNewScreen(screen);
COMMON_RETURN_SELF;
}
static int GetTopScreen(T* p, lua_State* L)
{
Actor* pScreen = p->GetTopScreen();
if (pScreen != NULL)
pScreen->PushSelf(L);
else
lua_pushnil(L);
return 1;
}
static int SystemMessage(T* p, lua_State* L)
{
p->SystemMessage(SArg(1));
COMMON_RETURN_SELF;
}
static int ScreenIsPrepped(T* p, lua_State* L)
{
lua_pushboolean(L, ScreenManagerUtil::ScreenIsPrepped(SArg(1)));
return 1;
}
static int ScreenClassExists(T* p, lua_State* L)
{
lua_pushboolean(
L, g_pmapRegistrees->find(SArg(1)) != g_pmapRegistrees->end());
return 1;
}
static int AddNewScreenToTop(T* p, lua_State* L)
{
RString screen = SArg(1);
ValidateScreenName(L, screen);
ScreenMessage SM = SM_None;
if (lua_gettop(L) >= 2 && !lua_isnil(L, 2)) {
RString sMessage = SArg(2);
SM = ScreenMessageHelpers::ToScreenMessage(sMessage);
}
p->AddNewScreenToTop(screen, SM);
COMMON_RETURN_SELF;
}
// static int GetScreenStackSize( T* p, lua_State *L ) { lua_pushnumber( L,
// ScreenManagerUtil::g_ScreenStack.size() ); return 1; }
static int ReloadOverlayScreens(T* p, lua_State* L)
{
p->ReloadOverlayScreens();
COMMON_RETURN_SELF;
}
static int get_input_redirected(T* p, lua_State* L)
{
PlayerNumber pn = Enum::Check<PlayerNumber>(L, 1);
lua_pushboolean(L, p->get_input_redirected(pn));
return 1;
}
static int set_input_redirected(T* p, lua_State* L)
{
PlayerNumber pn = Enum::Check<PlayerNumber>(L, 1);
p->set_input_redirected(pn, BArg(2));
COMMON_RETURN_SELF;
}
#define SCRMAN_PLAY_SOUND(sound_name) \
static int Play##sound_name(T* p, lua_State* L) \
{ \
p->Play##sound_name(); \
COMMON_RETURN_SELF; \
}
SCRMAN_PLAY_SOUND(InvalidSound);
SCRMAN_PLAY_SOUND(StartSound);
SCRMAN_PLAY_SOUND(CoinSound);
SCRMAN_PLAY_SOUND(CancelSound);
SCRMAN_PLAY_SOUND(ScreenshotSound);
#undef SCRMAN_PLAY_SOUND
LunaScreenManager()
{
ADD_METHOD(SetNewScreen);
ADD_METHOD(GetTopScreen);
ADD_METHOD(SystemMessage);
ADD_METHOD(ScreenIsPrepped);
ADD_METHOD(ScreenClassExists);
ADD_METHOD(AddNewScreenToTop);
// ADD_METHOD( GetScreenStackSize );
ADD_METHOD(ReloadOverlayScreens);
ADD_METHOD(PlayInvalidSound);
ADD_METHOD(PlayStartSound);
ADD_METHOD(PlayCoinSound);
ADD_METHOD(PlayCancelSound);
ADD_METHOD(PlayScreenshotSound);
ADD_GET_SET_METHODS(input_redirected);
}
};
LUA_REGISTER_CLASS(ScreenManager)
// lua end
/*
* (c) 2001-2003 Chris Danford, Glenn Maynard
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 28.693141
| 80
| 0.71474
|
graemephi
|
915f5ac519c0366f24fa768b0db8dffd7d45f472
| 21,519
|
cpp
|
C++
|
code/appRenderState.cpp
|
robbitay/ConstPort
|
d948ceb5f0e22504640578e3ef31e3823b29c1c3
|
[
"Unlicense"
] | null | null | null |
code/appRenderState.cpp
|
robbitay/ConstPort
|
d948ceb5f0e22504640578e3ef31e3823b29c1c3
|
[
"Unlicense"
] | null | null | null |
code/appRenderState.cpp
|
robbitay/ConstPort
|
d948ceb5f0e22504640578e3ef31e3823b29c1c3
|
[
"Unlicense"
] | null | null | null |
/*
File: appRenderState.cpp
Author: Taylor Robbins
Date: 06\13\2017
Description:
** Lots of functions that facilitate drawing different
** primitives and common things
#included from app.cpp
*/
void InitializeRenderState()
{
Assert(renderState != nullptr);
ClearPointer(renderState);
Vertex_t squareVertices[] =
{
{ {0.0f, 0.0f, 0.0f}, NewVec4(NewColor(Color_White)), {0.0f, 0.0f} },
{ {1.0f, 0.0f, 0.0f}, NewVec4(NewColor(Color_White)), {1.0f, 0.0f} },
{ {0.0f, 1.0f, 0.0f}, NewVec4(NewColor(Color_White)), {0.0f, 1.0f} },
{ {0.0f, 1.0f, 0.0f}, NewVec4(NewColor(Color_White)), {0.0f, 1.0f} },
{ {1.0f, 0.0f, 0.0f}, NewVec4(NewColor(Color_White)), {1.0f, 0.0f} },
{ {1.0f, 1.0f, 0.0f}, NewVec4(NewColor(Color_White)), {1.0f, 1.0f} },
};
renderState->squareBuffer = CreateVertexBuffer(squareVertices, ArrayCount(squareVertices));
renderState->gradientTexture = LoadTexture("Resources/Textures/gradient.png", false, false);
renderState->circleTexture = LoadTexture("Resources/Sprites/circle.png", false, false);
Color_t textureData = {Color_White};
renderState->dotTexture = CreateTexture((u8*)&textureData, 1, 1);
renderState->viewport = NewRec(0, 0, (r32)RenderScreenSize.x, (r32)RenderScreenSize.y);
renderState->worldMatrix = Mat4_Identity;
renderState->viewMatrix = Mat4_Identity;
renderState->projectionMatrix = Mat4_Identity;
renderState->doGrayscaleGradient = false;
renderState->useAlphaTexture = false;
renderState->sourceRectangle = NewRec(0, 0, 1, 1);
renderState->depth = 1.0f;
renderState->circleRadius = 0.0f;
renderState->circleInnerRadius = 0.0f;
renderState->color = NewColor(Color_White);
renderState->secondaryColor = NewColor(Color_White);
}
//+================================================================+
//| State Change Functions |
//+================================================================+
void RsUpdateShader()
{
Assert(renderState->boundShader != nullptr);
if (renderState->boundBuffer != nullptr)
{
glBindVertexArray(renderState->boundShader->vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, renderState->boundBuffer->id);
glVertexAttribPointer(renderState->boundShader->locations.positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)0);
glVertexAttribPointer(renderState->boundShader->locations.colorAttrib, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)sizeof(v3));
glVertexAttribPointer(renderState->boundShader->locations.texCoordAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)(sizeof(v3)+sizeof(v4)));
}
if (renderState->boundTexture != nullptr)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderState->boundTexture->id);
glUniform1i(renderState->boundShader->locations.diffuseTexture, 0);
glUniform2f(renderState->boundShader->locations.textureSize, (r32)renderState->boundTexture->width, (r32)renderState->boundTexture->height);
}
if (renderState->boundAlphaTexture != nullptr)
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, renderState->boundAlphaTexture->id);
glUniform1i(renderState->boundShader->locations.alphaTexture, 1);
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 1);
}
else
{
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 0);
}
if (renderState->boundFrameBuffer != nullptr)
{
glBindFramebuffer(GL_FRAMEBUFFER, renderState->boundFrameBuffer->id);
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
glUniformMatrix4fv(renderState->boundShader->locations.worldMatrix, 1, GL_FALSE, &renderState->worldMatrix.values[0][0]);
glUniformMatrix4fv(renderState->boundShader->locations.viewMatrix, 1, GL_FALSE, &renderState->viewMatrix.values[0][0]);
glUniformMatrix4fv(renderState->boundShader->locations.projectionMatrix, 1, GL_FALSE, &renderState->projectionMatrix.values[0][0]);
glUniform1i(renderState->boundShader->locations.doGrayscaleGradient, renderState->doGrayscaleGradient ? 1 : 0);
glUniform4f(renderState->boundShader->locations.sourceRectangle, renderState->sourceRectangle.x, renderState->sourceRectangle.y, renderState->sourceRectangle.width, renderState->sourceRectangle.height);
glUniform1f(renderState->boundShader->locations.circleRadius, renderState->circleRadius);
glUniform1f(renderState->boundShader->locations.circleInnerRadius, renderState->circleInnerRadius);
v4 colorVec = NewVec4(renderState->color);
glUniform4f(renderState->boundShader->locations.diffuseColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
colorVec = NewVec4(renderState->secondaryColor);
glUniform4f(renderState->boundShader->locations.secondaryColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
}
void RsBindShader(const Shader_t* shaderPntr)
{
renderState->boundShader = shaderPntr;
glUseProgram(shaderPntr->programId);
}
void RsBindFont(const Font_t* fontPntr)
{
renderState->boundFont = fontPntr;
}
void RsBindTexture(const Texture_t* texturePntr)
{
renderState->boundTexture = texturePntr;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, renderState->boundTexture->id);
glUniform1i(renderState->boundShader->locations.diffuseTexture, 0);
glUniform2f(renderState->boundShader->locations.textureSize, (r32)renderState->boundTexture->width, (r32)renderState->boundTexture->height);
}
void RsBindAlphaTexture(const Texture_t* texturePntr)
{
renderState->boundAlphaTexture = texturePntr;
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, renderState->boundAlphaTexture->id);
glUniform1i(renderState->boundShader->locations.alphaTexture, 1);
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 1);
}
void RsDisableAlphaTexture()
{
renderState->boundAlphaTexture = nullptr;
glUniform1i(renderState->boundShader->locations.useAlphaTexture, 0);
}
void RsBindBuffer(const VertexBuffer_t* vertBufferPntr)
{
renderState->boundBuffer = vertBufferPntr;
glBindVertexArray(renderState->boundShader->vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, vertBufferPntr->id);
glVertexAttribPointer(renderState->boundShader->locations.positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)0);
glVertexAttribPointer(renderState->boundShader->locations.colorAttrib, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)sizeof(v3));
glVertexAttribPointer(renderState->boundShader->locations.texCoordAttrib, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex_t), (void*)(sizeof(v3)+sizeof(v4)));
}
void RsBindFrameBuffer(const FrameBuffer_t* frameBuffer)
{
renderState->boundFrameBuffer = frameBuffer;
if (frameBuffer == nullptr)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer->id);
}
}
void RsSetWorldMatrix(const mat4& worldMatrix)
{
renderState->worldMatrix = worldMatrix;
glUniformMatrix4fv(renderState->boundShader->locations.worldMatrix, 1, GL_FALSE, &worldMatrix.values[0][0]);
}
void RsSetViewMatrix(const mat4& viewMatrix)
{
renderState->viewMatrix = viewMatrix;
glUniformMatrix4fv(renderState->boundShader->locations.viewMatrix, 1, GL_FALSE, &viewMatrix.values[0][0]);
}
void RsSetProjectionMatrix(const mat4& projectionMatrix)
{
renderState->projectionMatrix = projectionMatrix;
glUniformMatrix4fv(renderState->boundShader->locations.projectionMatrix, 1, GL_FALSE, &projectionMatrix.values[0][0]);
}
void RsSetViewport(rec viewport)
{
renderState->viewport = viewport;
#if DOUBLE_RESOLUTION
glViewport(
(i32)renderState->viewport.x*2,
(i32)(RenderScreenSize.y*2 - renderState->viewport.height*2 - renderState->viewport.y*2),
(i32)renderState->viewport.width*2,
(i32)renderState->viewport.height*2
);
#else
glViewport(
(i32)renderState->viewport.x,
(i32)(RenderScreenSize.y - renderState->viewport.height - renderState->viewport.y),
(i32)renderState->viewport.width,
(i32)renderState->viewport.height
);
#endif
mat4 projMatrix;
projMatrix = Mat4Scale(NewVec3(2.0f/viewport.width, -2.0f/viewport.height, 1.0f));
projMatrix = Mat4Multiply(projMatrix, Mat4Translate(NewVec3(-viewport.width/2.0f, -viewport.height/2.0f, 0.0f)));
projMatrix = Mat4Multiply(projMatrix, Mat4Translate(NewVec3(-renderState->viewport.x, -renderState->viewport.y, 0.0f)));
RsSetProjectionMatrix(projMatrix);
}
void RsSetColor(Color_t color)
{
renderState->color = color;
v4 colorVec = NewVec4(color);
glUniform4f(renderState->boundShader->locations.diffuseColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
}
void RsSetSecondaryColor(Color_t color)
{
renderState->secondaryColor = color;
v4 colorVec = NewVec4(color);
glUniform4f(renderState->boundShader->locations.secondaryColor, colorVec.r, colorVec.g, colorVec.b, colorVec.a);
}
void RsSetSourceRectangle(rec sourceRectangle)
{
renderState->sourceRectangle = sourceRectangle;
glUniform4f(renderState->boundShader->locations.sourceRectangle, sourceRectangle.x, sourceRectangle.y, sourceRectangle.width, sourceRectangle.height);
}
void RsSetGradientEnabled(bool doGradient)
{
renderState->doGrayscaleGradient = doGradient;
glUniform1i(renderState->boundShader->locations.doGrayscaleGradient, doGradient ? 1 : 0);
}
void RsSetCircleRadius(r32 radius, r32 innerRadius = 0.0f)
{
renderState->circleRadius = radius;
renderState->circleInnerRadius = innerRadius;
glUniform1f(renderState->boundShader->locations.circleRadius, radius);
glUniform1f(renderState->boundShader->locations.circleInnerRadius, innerRadius);
}
void RsSetDepth(r32 depth)
{
renderState->depth = depth;
}
void RsBegin(const Shader_t* startShader, const Font_t* startFont, rec viewport)
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GEQUAL, 0.1f);
RsBindShader(startShader);
RsBindFont(startFont);
RsBindTexture(&renderState->dotTexture);
RsBindBuffer(&renderState->squareBuffer);
RsBindFrameBuffer(nullptr);
RsDisableAlphaTexture();
RsSetWorldMatrix(Matrix4_Identity);
RsSetViewMatrix(Matrix4_Identity);
RsSetProjectionMatrix(Matrix4_Identity);
RsSetViewport(viewport);
RsSetColor(NewColor(Color_White));
RsSetSecondaryColor(NewColor(Color_White));
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetGradientEnabled(false);
RsSetCircleRadius(0.0f, 0.0f);
RsSetDepth(1.0f);
}
// +--------------------------------------------------------------+
// | Drawing Functions |
// +--------------------------------------------------------------+
void RsClearColorBuffer(Color_t clearColor)
{
v4 clearColorVec = NewVec4(clearColor);
glClearColor(clearColorVec.x, clearColorVec.y, clearColorVec.z, clearColorVec.w);
glClear(GL_COLOR_BUFFER_BIT);
}
void RsClearDepthBuffer(r32 clearDepth)
{
glClearDepth(clearDepth);
glClear(GL_DEPTH_BUFFER_BIT);
}
void RsDrawTexturedRec(rec rectangle, Color_t color)
{
RsBindTexture(renderState->boundTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color);
mat4 worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)), //Position
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f))); //Scale
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawTexturedRec(rec rectangle, Color_t color, rec sourceRectangle)
{
rec realSourceRec = NewRec(
sourceRectangle.x / (r32)renderState->boundTexture->width,
sourceRectangle.y / (r32)renderState->boundTexture->height,
sourceRectangle.width / (r32)renderState->boundTexture->width,
sourceRectangle.height / (r32)renderState->boundTexture->height);
RsSetSourceRectangle(realSourceRec);
RsBindTexture(renderState->boundTexture);
RsSetColor(color);
mat4 worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)), //Position
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f))); //Scale
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawRectangle(rec rectangle, Color_t color)
{
RsBindTexture(&renderState->dotTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color);
mat4 worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)), //Position
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f))); //Scale
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawButton(rec rectangle, Color_t backgroundColor, Color_t borderColor, r32 borderWidth = 1.0f)
{
RsDrawRectangle(rectangle, backgroundColor);
RsDrawRectangle(NewRec(rectangle.x, rectangle.y, rectangle.width, borderWidth), borderColor);
RsDrawRectangle(NewRec(rectangle.x, rectangle.y, borderWidth, rectangle.height), borderColor);
RsDrawRectangle(NewRec(rectangle.x, rectangle.y + rectangle.height - borderWidth, rectangle.width, borderWidth), borderColor);
RsDrawRectangle(NewRec(rectangle.x + rectangle.width - borderWidth, rectangle.y, borderWidth, rectangle.height), borderColor);
}
void RsDrawGradient(rec rectangle, Color_t color1, Color_t color2, Dir2_t direction)
{
RsBindTexture(&renderState->gradientTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color1);
RsSetSecondaryColor(color2);
RsSetGradientEnabled(true);
mat4 worldMatrix = Mat4_Identity;
switch (direction)
{
case Dir2_Right:
default:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x, rectangle.y, renderState->depth)),
Mat4Scale(NewVec3(rectangle.width, rectangle.height, 1.0f)));
} break;
case Dir2_Left:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x + rectangle.width, rectangle.y, renderState->depth)),
Mat4Scale(NewVec3(-rectangle.width, rectangle.height, 1.0f)));
} break;
case Dir2_Down:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x + rectangle.width, rectangle.y, renderState->depth)),
Mat4RotateZ(ToRadians(90)),
Mat4Scale(NewVec3(rectangle.height, rectangle.width, 1.0f)));
} break;
case Dir2_Up:
{
worldMatrix = Mat4Multiply(
Mat4Translate(NewVec3(rectangle.x + rectangle.width, rectangle.y + rectangle.height, renderState->depth)),
Mat4RotateZ(ToRadians(90)),
Mat4Scale(NewVec3(-rectangle.height, rectangle.width, 1.0f)));
} break;
};
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
RsSetGradientEnabled(false);
}
void RsDrawLine(v2 p1, v2 p2, r32 thickness, Color_t color)
{
RsBindTexture(&renderState->dotTexture);
RsSetSourceRectangle(NewRec(0, 0, 1, 1));
RsSetColor(color);
r32 length = Vec2Length(p2 - p1);
r32 rotation = AtanR32(p2.y - p1.y, p2.x - p1.x);
mat4 worldMatrix = Mat4_Identity;
worldMatrix = Mat4Multiply(Mat4Translate(NewVec3(0.0f, -0.5f, 0.0f)), worldMatrix); //Centering
worldMatrix = Mat4Multiply(Mat4Scale(NewVec3(length, thickness, 1.0f)), worldMatrix); //Scale
worldMatrix = Mat4Multiply(Mat4RotateZ(rotation), worldMatrix); //Rotation
worldMatrix = Mat4Multiply(Mat4Translate(NewVec3(p1.x, p1.y, renderState->depth)), worldMatrix); //Position
RsSetWorldMatrix(worldMatrix);
RsBindBuffer(&renderState->squareBuffer);
glDrawArrays(GL_TRIANGLES, 0, renderState->squareBuffer.numVertices);
}
void RsDrawCircle(v2 center, r32 radius, Color_t color)
{
RsSetCircleRadius(1.0f, 0.0f);
RsDrawRectangle(NewRec(center.x - radius, center.y - radius, radius*2, radius*2), color);
RsSetCircleRadius(0.0f, 0.0f);
}
void RsDrawDonut(v2 center, r32 radius, r32 innerRadius, Color_t color)
{
r32 realInnerRadius = ClampR32(innerRadius / radius, 0.0f, 1.0f);
RsSetCircleRadius(1.0f, realInnerRadius);
RsDrawRectangle(NewRec(center.x - radius, center.y - radius, radius*2, radius*2), color);
RsSetCircleRadius(0.0f, 0.0f);
}
void RsDrawCharacter(u32 charIndex, v2 bottomLeft, Color_t color, r32 scale = 1.0f)
{
const FontCharInfo_t* charInfo = &renderState->boundFont->chars[charIndex];
rec sourceRectangle = NewRec((r32)charInfo->x, (r32)charInfo->y, (r32)charInfo->width, (r32)charInfo->height);
rec drawRectangle = NewRec(
bottomLeft.x + scale*charInfo->offset.x,
bottomLeft.y + scale*charInfo->offset.y,
scale*charInfo->width,
scale*charInfo->height);
if (renderState->boundTexture != &renderState->boundFont->bitmap)
{
RsBindTexture(&renderState->boundFont->bitmap);
}
RsDrawTexturedRec(drawRectangle, color, sourceRectangle);
}
void RsDrawHexCharacter(u8 hexValue, v2 bottomLeft, Color_t color, r32 scale = 1.0f)
{
const Font_t* boundFont = renderState->boundFont;
const FontCharInfo_t* spaceCharInfo = &boundFont->chars[GetFontCharIndex(boundFont, ' ')];
rec charRec = NewRec(bottomLeft.x, bottomLeft.y + boundFont->maxExtendDown*scale - (boundFont->lineHeight-1)*scale, spaceCharInfo->advanceX*scale, (boundFont->lineHeight-1)*scale);
charRec.x = (r32)RoundR32(charRec.x);
charRec.y = (r32)RoundR32(charRec.y);
RsDrawRectangle(charRec, color);
RsDrawRectangle(NewRec(charRec.x, charRec.y, 1, charRec.height), GC->colors.textBackground);
// RsDrawButton(charRec, NewColor(Color_TransparentBlack), color, 1.0f);
r32 innerCharScale = scale*5/8;
char upperHexChar = UpperHexChar(hexValue);
char lowerHexChar = LowerHexChar(hexValue);
u32 upperCharIndex = GetFontCharIndex(boundFont, upperHexChar);
const FontCharInfo_t* upperCharInfo = &boundFont->chars[upperCharIndex];
u32 lowerCharIndex = GetFontCharIndex(boundFont, lowerHexChar);
const FontCharInfo_t* lowerCharInfo = &boundFont->chars[lowerCharIndex];
v2 charPosUpper = charRec.topLeft + NewVec2(1, upperCharInfo->height*innerCharScale + 1);
v2 charPosLower = charRec.topLeft + NewVec2(charRec.width - lowerCharInfo->width*innerCharScale - 1, charRec.height - 1);
// RsDrawCharacter(upperCharIndex, charPosUpper, color, innerCharScale);
// RsDrawCharacter(lowerCharIndex, charPosLower, color, innerCharScale);
RsDrawCharacter(upperCharIndex, charPosUpper, GC->colors.textBackground, innerCharScale);
RsDrawCharacter(lowerCharIndex, charPosLower, GC->colors.textBackground, innerCharScale);
}
void RsDrawString(const char* string, u32 numCharacters, v2 position, Color_t color, r32 scale = 1.0f, Alignment_t alignment = Alignment_Left)
{
RsBindTexture(&renderState->boundFont->bitmap);
v2 stringSize = MeasureString(renderState->boundFont, string, numCharacters);
v2 currentPos = position;
switch (alignment)
{
case Alignment_Center: currentPos.x -= stringSize.x/2; break;
case Alignment_Right: currentPos.x -= stringSize.x; break;
case Alignment_Left: break;
};
for (u32 cIndex = 0; cIndex < numCharacters; cIndex++)
{
if (string[cIndex] == '\t')
{
u32 spaceIndex = GetFontCharIndex(renderState->boundFont, ' ');
currentPos.x += renderState->boundFont->chars[spaceIndex].advanceX * GC->tabWidth * scale;
}
else if (IsCharClassPrintable(string[cIndex]) == false)
{
//Draw
RsDrawHexCharacter(string[cIndex], currentPos, color, scale);
u32 spaceIndex = GetFontCharIndex(renderState->boundFont, ' ');
currentPos.x += renderState->boundFont->chars[spaceIndex].advanceX * scale;
}
else
{
u32 charIndex = GetFontCharIndex(renderState->boundFont, string[cIndex]);
RsDrawCharacter(charIndex, currentPos, color, scale);
currentPos.x += renderState->boundFont->chars[charIndex].advanceX * scale;
}
}
}
void RsDrawString(const char* nullTermString, v2 position, Color_t color, r32 scale = 1.0f, Alignment_t alignment = Alignment_Left)
{
RsDrawString(nullTermString, (u32)strlen(nullTermString), position, color, scale, alignment);
}
void RsPrintString(v2 position, Color_t color, r32 scale, const char* formatString, ...)
{
char printBuffer[256] = {};
va_list args;
va_start(args, formatString);
u32 length = (u32)vsnprintf(printBuffer, 256-1, formatString, args);
va_end(args);
RsDrawString(printBuffer, length, position, color, scale);
}
void RsDrawFormattedString(const char* string, u32 numCharacters, v2 position, r32 maxWidth, Color_t color, Alignment_t alignment = Alignment_Left, bool preserveWords = true)
{
u32 cIndex = 0;
v2 drawPos = position;
while (cIndex < numCharacters)
{
u32 numChars = FindNextFormatChunk(renderState->boundFont, &string[cIndex], numCharacters - cIndex, maxWidth, preserveWords);
if (numChars == 0) { numChars = 1; }
while (numChars > 1 && IsCharClassWhitespace(string[cIndex + numChars-1]))
{
numChars--;
}
RsDrawString(&string[cIndex], numChars, drawPos, color, 1.0f, alignment);
if (cIndex+numChars < numCharacters && string[cIndex+numChars] == '\r')
{
numChars++;
}
if (cIndex+numChars < numCharacters && string[cIndex+numChars] == '\n')
{
numChars++;
}
while (cIndex+numChars < numCharacters && string[cIndex+numChars] == ' ')
{
numChars++;
}
drawPos.y += renderState->boundFont->lineHeight;
cIndex += numChars;
}
}
void RsDrawFormattedString(const char* nullTermString, v2 position, r32 maxWidth, Color_t color, Alignment_t alignment = Alignment_Left, bool preserveWords = true)
{
u32 numCharacters = (u32)strlen(nullTermString);
RsDrawFormattedString(nullTermString, numCharacters, position, maxWidth, color, alignment, preserveWords);
}
| 37.165803
| 203
| 0.749291
|
robbitay
|
916178b1de3174af3714a7802e13933ca253674e
| 3,321
|
cpp
|
C++
|
iniparser.cpp
|
IvanSafonov/iniparser
|
6aad81d1a607aaf64c4e26ea9c3f6a877a40ae2f
|
[
"MIT"
] | 1
|
2020-10-18T23:56:43.000Z
|
2020-10-18T23:56:43.000Z
|
iniparser.cpp
|
IvanSafonov/iniparser
|
6aad81d1a607aaf64c4e26ea9c3f6a877a40ae2f
|
[
"MIT"
] | null | null | null |
iniparser.cpp
|
IvanSafonov/iniparser
|
6aad81d1a607aaf64c4e26ea9c3f6a877a40ae2f
|
[
"MIT"
] | null | null | null |
#include "iniparser.h"
#include <fstream>
#include <regex>
#include <algorithm>
#include <set>
using namespace std;
IniParser::IniParser()
{
}
IniParser::~IniParser()
{
}
bool IniParser::load(const std::string &fileName) {
ifstream file;
file.open(fileName);
if (!file)
return false;
regex rxComment{R"(^\s*[;#].*$)"};
regex rxSection{R"(^\s*\[([^\]]+)\])"};
regex rxOption{R"(^\s*([^=\s]+)\s*=\s*(.*)$)"};
regex rxValueQuoted{R"r(^"([^"]*)"(\s*|\s*[;#].*)$)r"};
regex rxValueStripComment{R"(^([^;#]*).*$)"};
regex rxTrim{R"(^\s+|\s+$)"};
string section = "default";
for (string line; getline(file, line);) {
if (regex_match(line, rxComment))
continue;
smatch matches;
if (regex_search(line, matches, rxSection)) {
section = regex_replace(matches[1].str(), rxTrim, "");
toLower(section);
data[section] = map<string, string>();
continue;
}
if (regex_search(line, matches, rxOption)) {
string option = regex_replace(matches[1].str(), rxTrim, "");
toLower(option);
string rawValue = matches[2].str();
if (regex_search(rawValue, matches, rxValueQuoted))
data[section][option] = matches[1].str();
else if (regex_search(rawValue, matches, rxValueStripComment))
data[section][option] = regex_replace(matches[1].str(), rxTrim, "");
}
}
return true;
}
std::list<std::string> IniParser::sections() const
{
list<string> sections;
for (auto &i : data)
sections.push_back(i.first);
return sections;
}
std::list<std::string> IniParser::options(const std::string §ion) const
{
list<string> options;
auto sectionIt = data.find(section);
if (sectionIt == data.end())
return options;
for (auto &i : sectionIt->second)
options.push_back(i.first);
return options;
}
std::string IniParser::get(const std::string §ion, const std::string &option,
const std::string &def) const
{
auto sectionIt = data.find(section);
if (sectionIt == data.end())
return def;
auto &sec = sectionIt->second;
auto optionIt = sec.find(option);
if (optionIt == sec.end())
return def;
return optionIt->second;
}
bool IniParser::getBool(const std::string §ion, const std::string &option, bool def) const
{
string value = get(section, option);
if (value.empty())
return def;
toLower(value);
static const set<string> trueValues = {"on", "true", "1", "enable"};
return trueValues.find(value) != trueValues.end();
}
int IniParser::getInt(const std::string §ion, const std::string &option, int def) const
{
string value = get(section, option);
if (value.empty())
return def;
try {
return stoi(value);
} catch (...) {}
return def;
}
double IniParser::getDouble(const std::string §ion, const std::string &option, double def) const
{
string value = get(section, option);
if (value.empty())
return def;
try {
return stod(value);
} catch (...) {}
return def;
}
void IniParser::toLower(std::string &str) const
{
transform(str.begin(), str.end(), str.begin(), ::tolower);
}
| 25.945313
| 100
| 0.587173
|
IvanSafonov
|
91659fa248100b19731dd229ae7fa7cfe3a79a15
| 740
|
cpp
|
C++
|
src/projections/Mercator.cpp
|
Kuhlwein/Demiurge
|
0981f1d267efed87d51e2b328a93e1fa0be1158d
|
[
"MIT"
] | 6
|
2020-09-23T19:49:07.000Z
|
2022-01-08T15:53:55.000Z
|
src/projections/Mercator.cpp
|
Kuhlwein/Demiurge
|
0981f1d267efed87d51e2b328a93e1fa0be1158d
|
[
"MIT"
] | null | null | null |
src/projections/Mercator.cpp
|
Kuhlwein/Demiurge
|
0981f1d267efed87d51e2b328a93e1fa0be1158d
|
[
"MIT"
] | 1
|
2020-09-23T17:53:26.000Z
|
2020-09-23T17:53:26.000Z
|
//
// Created by kuhlwein on 7/5/20.
//
#include "Project.h"
#include "Mercator.h"
Mercator::Mercator(Project *project) : AbstractCanvas(project) {
}
glm::vec2 Mercator::inverseTransform(glm::vec2 coord) {
float theta = coord.x;
float phi = 2*atan(exp(coord.y))-M_PI/2;
return glm::vec2(theta,phi);
}
Shader *Mercator::inverseShader() {
return Shader::builder()
.include(def_pi).create(R"(
vec2 inverseshader(vec2 coord, inout bool outOfBounds) {
float theta = coord.x;
float phi = 2*atan(exp(coord.y))-M_PI/2;
//if (abs(phi)>89.0/180*M_PI) outOfBounds=true;
return vec2(theta,phi);
}
)");
}
glm::vec2 Mercator::getScale() {
return glm::vec2(M_PI,M_PI);
}
glm::vec2 Mercator::getLimits() {
return glm::vec2(1,3);
}
| 18.974359
| 64
| 0.677027
|
Kuhlwein
|
916beb4c7c82d6dfcd78be0842fa09b3639164ef
| 9,470
|
cxx
|
C++
|
java/jni/direct_bt/DBTGattChar.cxx
|
sgothel/direct_bt
|
e19a11a60d509a42a1a1167a2b7215345784e462
|
[
"MIT"
] | 10
|
2020-09-03T16:23:12.000Z
|
2022-03-10T13:51:40.000Z
|
java/jni/direct_bt/DBTGattChar.cxx
|
sgothel/direct_bt
|
e19a11a60d509a42a1a1167a2b7215345784e462
|
[
"MIT"
] | null | null | null |
java/jni/direct_bt/DBTGattChar.cxx
|
sgothel/direct_bt
|
e19a11a60d509a42a1a1167a2b7215345784e462
|
[
"MIT"
] | 3
|
2020-09-03T05:21:46.000Z
|
2020-09-04T18:44:00.000Z
|
/*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2020 Gothel Software e.K.
* Copyright (c) 2020 ZAFENA AB
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "jau_direct_bt_DBTGattChar.h"
#include <jau/debug.hpp>
#include "helper_base.hpp"
#include "helper_dbt.hpp"
#include "direct_bt/BTDevice.hpp"
#include "direct_bt/BTAdapter.hpp"
using namespace direct_bt;
using namespace jau;
jstring Java_jau_direct_1bt_DBTGattChar_toStringImpl(JNIEnv *env, jobject obj) {
try {
BTGattChar *nativePtr = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(nativePtr->getJavaObject(), E_FILE_LINE);
return from_string_to_jstring(env, nativePtr->toString());
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return nullptr;
}
void Java_jau_direct_1bt_DBTGattChar_deleteImpl(JNIEnv *env, jobject obj, jlong nativeInstance) {
(void)obj;
try {
BTGattChar *characteristic = castInstance<BTGattChar>(nativeInstance);
(void)characteristic;
// No delete: Service instance owned by BTGattService -> BTDevice
} catch(...) {
rethrow_and_raise_java_exception(env);
}
}
static const std::string _descriptorClazzCtorArgs("(JLjau/direct_bt/DBTGattChar;Ljava/lang/String;S[B)V");
jobject Java_jau_direct_1bt_DBTGattChar_getDescriptorsImpl(JNIEnv *env, jobject obj) {
try {
BTGattChar *characteristic = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
jau::darray<BTGattDescRef> & descriptorList = characteristic->descriptorList;
// BTGattDesc(final long nativeInstance, final BTGattChar characteristic,
// final String type_uuid, final short handle, final byte[] value)
// BTGattDesc(final long nativeInstance, final BTGattChar characteristic,
// final String type_uuid, final short handle, final byte[] value)
std::function<jobject(JNIEnv*, jclass, jmethodID, BTGattDesc *)> ctor_desc =
[](JNIEnv *env_, jclass clazz, jmethodID clazz_ctor, BTGattDesc *descriptor)->jobject {
// prepare adapter ctor
std::shared_ptr<BTGattChar> _characteristic = descriptor->getGattCharChecked();
JavaGlobalObj::check(_characteristic->getJavaObject(), E_FILE_LINE);
jobject jcharacteristic = JavaGlobalObj::GetObject(_characteristic->getJavaObject());
const jstring juuid = from_string_to_jstring(env_, descriptor->type->toUUID128String());
java_exception_check_and_throw(env_, E_FILE_LINE);
const size_t value_size = descriptor->value.size();
jbyteArray jval = env_->NewByteArray((jsize)value_size);
env_->SetByteArrayRegion(jval, 0, (jsize)value_size, (const jbyte *)descriptor->value.get_ptr());
java_exception_check_and_throw(env_, E_FILE_LINE);
jobject jdesc = env_->NewObject(clazz, clazz_ctor, (jlong)descriptor, jcharacteristic,
juuid, (jshort)descriptor->handle, jval);
java_exception_check_and_throw(env_, E_FILE_LINE);
JNIGlobalRef::check(jdesc, E_FILE_LINE);
std::shared_ptr<JavaAnon> jDescRef = descriptor->getJavaObject(); // GlobalRef
JavaGlobalObj::check(jDescRef, E_FILE_LINE);
env_->DeleteLocalRef(juuid);
env_->DeleteLocalRef(jval);
env_->DeleteLocalRef(jdesc);
return JavaGlobalObj::GetObject(jDescRef);
};
return convert_vector_sharedptr_to_jarraylist<jau::darray<BTGattDescRef>, BTGattDesc>(
env, descriptorList, _descriptorClazzCtorArgs.c_str(), ctor_desc);
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return nullptr;
}
jbyteArray Java_jau_direct_1bt_DBTGattChar_readValueImpl(JNIEnv *env, jobject obj) {
try {
BTGattChar *characteristic = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
POctets res(BTGattHandler::number(BTGattHandler::Defaults::MAX_ATT_MTU), 0, jau::endian::little);
if( !characteristic->readValue(res) ) {
ERR_PRINT("Characteristic readValue failed: %s", characteristic->toString().c_str());
return env->NewByteArray((jsize)0);
}
const size_t value_size = res.size();
jbyteArray jres = env->NewByteArray((jsize)value_size);
env->SetByteArrayRegion(jres, 0, (jsize)value_size, (const jbyte *)res.get_ptr());
java_exception_check_and_throw(env, E_FILE_LINE);
return jres;
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return nullptr;
}
jboolean Java_jau_direct_1bt_DBTGattChar_writeValueImpl(JNIEnv *env, jobject obj, jbyteArray jval, jboolean withResponse) {
try {
if( nullptr == jval ) {
throw IllegalArgumentException("byte array null", E_FILE_LINE);
}
const int value_size = env->GetArrayLength(jval);
if( 0 == value_size ) {
return JNI_TRUE;
}
BTGattChar *characteristic = getJavaUplinkObject<BTGattChar>(env, obj);
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
JNICriticalArray<uint8_t, jbyteArray> criticalArray(env); // RAII - release
uint8_t * value_ptr = criticalArray.get(jval, criticalArray.Mode::NO_UPDATE_AND_RELEASE);
if( NULL == value_ptr ) {
throw InternalError("GetPrimitiveArrayCritical(byte array) is null", E_FILE_LINE);
}
TROOctets value(value_ptr, value_size, jau::endian::little);
bool res;
if( withResponse ) {
res = characteristic->writeValue(value);
} else {
res = characteristic->writeValueNoResp(value);
}
if( !res ) {
ERR_PRINT("Characteristic writeValue(withResponse %d) failed: %s",
withResponse, characteristic->toString().c_str());
return JNI_FALSE;
}
return JNI_TRUE;
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return JNI_FALSE;
}
jboolean Java_jau_direct_1bt_DBTGattChar_configNotificationIndicationImpl(JNIEnv *env, jobject obj,
jboolean enableNotification, jboolean enableIndication, jbooleanArray jEnabledState) {
try {
BTGattChar *characteristic = getJavaUplinkObjectUnchecked<BTGattChar>(env, obj);
if( nullptr == characteristic ) {
if( !enableNotification && !enableIndication ) {
// OK to have native characteristic being shutdown @ disable
DBG_PRINT("Characteristic's native instance has been deleted");
return false;
}
throw IllegalStateException("Characteristic's native instance deleted", E_FILE_LINE);
}
JavaGlobalObj::check(characteristic->getJavaObject(), E_FILE_LINE);
if( nullptr == jEnabledState ) {
throw IllegalArgumentException("boolean array null", E_FILE_LINE);
}
const int state_size = env->GetArrayLength(jEnabledState);
if( 2 > state_size ) {
throw IllegalArgumentException("boolean array smaller than 2, length "+std::to_string(state_size), E_FILE_LINE);
}
JNICriticalArray<jboolean, jbooleanArray> criticalArray(env); // RAII - release
jboolean * state_ptr = criticalArray.get(jEnabledState, criticalArray.Mode::UPDATE_AND_RELEASE);
if( NULL == state_ptr ) {
throw InternalError("GetPrimitiveArrayCritical(boolean array) is null", E_FILE_LINE);
}
bool cccdEnableResult[2];
bool res = characteristic->configNotificationIndication(enableNotification, enableIndication, cccdEnableResult);
DBG_PRINT("BTGattChar::configNotificationIndication Config Notification(%d), Indication(%d): Result %d",
cccdEnableResult[0], cccdEnableResult[1], res);
state_ptr[0] = cccdEnableResult[0];
state_ptr[1] = cccdEnableResult[1];
return res;
} catch(...) {
rethrow_and_raise_java_exception(env);
}
return JNI_FALSE;
}
| 45.311005
| 124
| 0.667476
|
sgothel
|
916f77bb5ca21ef3f1ea64a0025bfdcb97ca475b
| 252
|
cpp
|
C++
|
src/BarProject/TCPClient.cpp
|
gallowstree/ArduinoMazeNavV2
|
fdd35ce066cb4c3d78496beeda2ef831f7fb6713
|
[
"MIT"
] | null | null | null |
src/BarProject/TCPClient.cpp
|
gallowstree/ArduinoMazeNavV2
|
fdd35ce066cb4c3d78496beeda2ef831f7fb6713
|
[
"MIT"
] | null | null | null |
src/BarProject/TCPClient.cpp
|
gallowstree/ArduinoMazeNavV2
|
fdd35ce066cb4c3d78496beeda2ef831f7fb6713
|
[
"MIT"
] | null | null | null |
#include "TCPClient.h"
TCPClient::TCPClient(){}
int TCPClient::connect(char * host, int port)
{
return client.connect(host,port);
}
void TCPClient::sendData(String data)
{
client.print(data);
}
void TCPClient::close()
{
client.stop();
}
| 14
| 45
| 0.674603
|
gallowstree
|
917261d0dc69ebc96ab34b4c739bffcdb1ae675b
| 7,485
|
cpp
|
C++
|
utils/cluster.cpp
|
adam-lafontaine/AugmentedAI
|
a4736ce59963ee86313a5936aaf09f0f659e4184
|
[
"MIT"
] | null | null | null |
utils/cluster.cpp
|
adam-lafontaine/AugmentedAI
|
a4736ce59963ee86313a5936aaf09f0f659e4184
|
[
"MIT"
] | null | null | null |
utils/cluster.cpp
|
adam-lafontaine/AugmentedAI
|
a4736ce59963ee86313a5936aaf09f0f659e4184
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2021 Adam Lafontaine
*/
#include "cluster_config.hpp"
#include <cstdlib>
#include <algorithm>
#include <random>
#include <iterator>
#include <iostream>
#include <functional>
namespace cluster
{
//======= TYPES ===================
typedef struct ClusterCount // used for tracking the number of times a given result is found
{
cluster_result_t result;
unsigned count;
} cluster_count_t;
using closest_t = std::function<distance_result_t(data_row_t const& data, value_row_list_t const& value_list)>;
using cluster_once_t = std::function<cluster_result_t(data_row_list_t const& x_list, size_t num_clusters)>;
//======= HELPERS ====================
static size_t max_value(index_list_t const& list)
{
return *std::max_element(list.begin(), list.end());
}
// convert a list of data_row_t to value_row_t
static value_row_list_t to_value_row_list(data_row_list_t const& data_row_list)
{
auto list = make_value_row_list(data_row_list.size(), data_row_list[0].size());
for (size_t i = 0; i < data_row_list.size(); ++i)
{
auto data_row = data_row_list[i];
for (size_t j = 0; j < data_row.size(); ++j)
list[i][j] = data_to_value(data_row[j]);
}
return list;
}
// selects random data to be used as centroids
static value_row_list_t random_values(data_row_list_t const& x_list, size_t num_clusters)
{
// C++ 17 std::sample
data_row_list_t samples;
samples.reserve(num_clusters);
std::sample(x_list.begin(), x_list.end(), std::back_inserter(samples),
num_clusters, std::mt19937{ std::random_device{}() });
return to_value_row_list(samples);
}
// assigns a cluster index to each data point
static cluster_result_t assign_clusters(data_row_list_t const& x_list, value_row_list_t& centroids, closest_t const& closest)
{
index_list_t x_clusters;
x_clusters.reserve(x_list.size());
double total_distance = 0;
for (auto const& x_data : x_list)
{
auto c = closest(x_data, centroids);
x_clusters.push_back(c.index);
total_distance += c.distance;
}
cluster_result_t res = { std::move(x_clusters), std::move(centroids), total_distance / x_list.size() };
return res;
}
// finds new centroids based on the averages of data clustered together
static value_row_list_t calc_centroids(data_row_list_t const& x_list, index_list_t const& x_clusters, size_t num_clusters)
{
const auto data_size = x_list[0].size();
auto values = make_value_row_list(num_clusters, data_size);
std::vector<unsigned> counts(num_clusters, 0);
for (size_t i = 0; i < x_list.size(); ++i)
{
const auto cluster_index = x_clusters[i];
++counts[cluster_index];
for (size_t d = 0; d < data_size; ++d)
values[cluster_index][d] += data_to_value(x_list[i][d]); // totals for each cluster
}
for (size_t k = 0; k < num_clusters; ++k)
{
for (size_t d = 0; d < data_size; ++d)
values[k][d] = values[k][d] / counts[k]; // convert to average
}
return values;
}
// re-label cluster assignments so that they are consistent accross iterations
static void relabel_clusters(cluster_result_t& result, size_t num_clusters)
{
std::vector<uint8_t> flags(num_clusters, 0); // tracks if cluster index has been mapped
std::vector<size_t> map(num_clusters, 0); // maps old cluster index to new cluster index
const auto all_flagged = [&]()
{
for (auto const flag : flags)
{
if (!flag)
return false;
}
return true;
};
size_t i = 0;
size_t label = 0;
for (; label < num_clusters && i < result.x_clusters.size() && !all_flagged(); ++i)
{
size_t c = result.x_clusters[i];
if (flags[c])
continue;
map[c] = label;
flags[c] = 1;
++label;
}
// re-label cluster assignments
for (i = 0; i < result.x_clusters.size(); ++i)
{
size_t c = result.x_clusters[i];
result.x_clusters[i] = map[c];
}
}
//======= CLUSTERING ALGORITHMS ==========================
// returns the result with the smallest distance
static cluster_result_t cluster_min_distance(data_row_list_t const& x_list, size_t num_clusters, cluster_once_t const& cluster_once)
{
auto result = cluster_once(x_list, num_clusters);
auto min = result;
for (size_t i = 0; i < CLUSTER_ATTEMPTS; ++i)
{
result = cluster_once(x_list, num_clusters);
if (result.average_distance < min.average_distance)
min = std::move(result);
}
return min;
}
/*
// returns the most popular result
// stops when the same result has been found for more than half of the attempts
static cluster_result_t cluster_max_count(data_row_list_t const& x_list, size_t num_clusters, cluster_once_t const& cluster_once)
{
std::vector<cluster_count_t> counts;
counts.reserve(CLUSTER_ATTEMPTS);
auto result = cluster_once(x_list, num_clusters);
counts.push_back({ std::move(result), 1 });
for (size_t i = 0; i < CLUSTER_ATTEMPTS; ++i)
{
result = cluster_once(x_list, num_clusters);
bool add_clusters = true;
for (auto& c : counts)
{
if (list_distance(result.x_clusters, c.result.x_clusters) != 0)
continue;
++c.count;
if (c.count > CLUSTER_ATTEMPTS / 2)
return c.result;
add_clusters = false;
break;
}
if (add_clusters)
{
counts.push_back({ std::move(result), 1 });
}
}
auto constexpr comp = [](cluster_count_t const& lhs, cluster_count_t const& rhs) { return lhs.count < rhs.count; };
auto const best = *std::max_element(counts.begin(), counts.end(), comp);
return best.result;
}
*/
//======= CLASS METHODS ==============================
distance_result_t Cluster::closest(data_row_t const& data, value_row_list_t const& value_list) const
{
distance_result_t res = { 0, m_dist_func(data, value_list[0]) };
for (size_t i = 1; i < value_list.size(); ++i)
{
auto dist = m_dist_func(data, value_list[i]);
if (dist < res.distance)
{
res.distance = dist;
res.index = i;
}
}
return res;
}
size_t Cluster::find_centroid(data_row_t const& data, value_row_list_t const& centroids) const
{
auto result = closest(data, centroids);
return result.index;
}
cluster_result_t Cluster::cluster_once(data_row_list_t const& x_list, size_t num_clusters) const
{
const auto closest_f = [&](data_row_t const& data, value_row_list_t const& value_list) // TODO: why?
{
return closest(data, value_list);
};
auto centroids = random_values(x_list, num_clusters); // start with random centroids
auto result = assign_clusters(x_list, centroids, closest_f);
relabel_clusters(result, num_clusters);
for (size_t i = 0; i < CLUSTER_ITERATIONS; ++i)
{
centroids = calc_centroids(x_list, result.x_clusters, num_clusters);
auto res_try = assign_clusters(x_list, centroids, closest_f);
if (max_value(res_try.x_clusters) < num_clusters - 1)
continue;
auto res_old = std::move(result);
result = std::move(res_try);
relabel_clusters(result, num_clusters);
if (list_distance(res_old.x_clusters, result.x_clusters) == 0)
return result;
}
return result;
}
value_row_list_t Cluster::cluster_data(data_row_list_t const& x_list, size_t num_clusters) const
{
// wrap member function in a lambda to pass it to algorithm
const auto cluster_once_f = [&](data_row_list_t const& x_list, size_t num_clusters) // TODO: why?
{
return cluster_once(x_list, num_clusters);
};
auto result = cluster_min_distance(x_list, num_clusters, cluster_once_f);
return result.centroids;
}
}
| 25.287162
| 133
| 0.685237
|
adam-lafontaine
|
91782ac2f1e95b4ebad4dd7b7014dabf54da8541
| 1,199
|
hpp
|
C++
|
modules/scene_manager/include/map_msgs/srv/save_map__request__traits.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
modules/scene_manager/include/map_msgs/srv/save_map__request__traits.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 3
|
2019-11-14T12:20:06.000Z
|
2020-08-07T13:51:10.000Z
|
modules/scene_manager/include/map_msgs/srv/save_map__request__traits.hpp
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
// generated from rosidl_generator_cpp/resource/msg__traits.hpp.em
// generated code does not contain a copyright notice
#ifndef MAP_MSGS__SRV__SAVE_MAP__REQUEST__TRAITS_HPP_
#define MAP_MSGS__SRV__SAVE_MAP__REQUEST__TRAITS_HPP_
#include <stdint.h>
#include <type_traits>
namespace rosidl_generator_traits
{
#ifndef __ROSIDL_GENERATOR_CPP_TRAITS
#define __ROSIDL_GENERATOR_CPP_TRAITS
template<typename T>
inline const char * data_type();
template<typename T>
struct has_fixed_size : std::false_type {};
template<typename T>
struct has_bounded_size : std::false_type {};
#endif // __ROSIDL_GENERATOR_CPP_TRAITS
#include "map_msgs/srv/save_map__request__struct.hpp"
template<>
struct has_fixed_size<map_msgs::srv::SaveMap_Request>
: std::integral_constant<bool, has_fixed_size<std_msgs::msg::String>::value> {};
template<>
struct has_bounded_size<map_msgs::srv::SaveMap_Request>
: std::integral_constant<bool, has_bounded_size<std_msgs::msg::String>::value> {};
template<>
inline const char * data_type<map_msgs::srv::SaveMap_Request>()
{
return "map_msgs::srv::SaveMap_Request";
}
} // namespace rosidl_generator_traits
#endif // MAP_MSGS__SRV__SAVE_MAP__REQUEST__TRAITS_HPP_
| 25.510638
| 84
| 0.803169
|
Omnirobotic
|
9179a4fe75d7fdbe342b6748d90b659676d8ef49
| 2,328
|
cpp
|
C++
|
src/RotationControl.cpp
|
rustyducks/navigation
|
2c549072173b05ebc750c7a0b05dd41833f44ceb
|
[
"MIT"
] | null | null | null |
src/RotationControl.cpp
|
rustyducks/navigation
|
2c549072173b05ebc750c7a0b05dd41833f44ceb
|
[
"MIT"
] | null | null | null |
src/RotationControl.cpp
|
rustyducks/navigation
|
2c549072173b05ebc750c7a0b05dd41833f44ceb
|
[
"MIT"
] | null | null | null |
#include "Navigation/RotationControl.h"
#include "Navigation/Parameters.h"
namespace rd {
RotationControl::RotationControl(const PositionControlParameters ¶ms) : PositionControlBase(params), state_(eRotationControlState::ACCELERATE) {}
Speed RotationControl::computeSpeed(const PointOriented &robotPose, const Speed &robotSpeed, double dt, double) {
double rotationSpeed = 0.;
Angle diff = targetAngle_ - robotPose.theta();
double angleToStop;
if (state_ == eRotationControlState::ACCELERATE) {
if (diff < 0) {
rotationSpeed = robotSpeed.vtheta() - params_.maxRotationalAcceleration * dt;
} else {
rotationSpeed = robotSpeed.vtheta() + params_.maxRotationalAcceleration * dt;
}
if (std::abs(rotationSpeed) >= params_.maxRotationalSpeed) {
state_ = eRotationControlState::CRUISING;
rotationSpeed = std::min(params_.maxRotationalSpeed, std::max(-params_.maxRotationalSpeed, rotationSpeed));
}
angleToStop = 0.5 * robotSpeed.vtheta() * robotSpeed.vtheta() / params_.maxRotationalAcceleration;
if (angleToStop + dt * std::abs(rotationSpeed) >= std::abs(diff.value())) {
state_ = eRotationControlState::DECELERATE;
}
}
if (state_ == eRotationControlState::CRUISING) {
if (diff < 0) {
rotationSpeed = -params_.maxRotationalSpeed;
} else {
rotationSpeed = params_.maxRotationalSpeed;
}
angleToStop = 0.5 * robotSpeed.vtheta() * robotSpeed.vtheta() / params_.maxRotationalAcceleration;
if (angleToStop + dt * std::abs(robotSpeed.vtheta()) >= std::abs(diff.value())) {
state_ = eRotationControlState::DECELERATE;
}
}
if (state_ == eRotationControlState::DECELERATE) {
if (diff < 0) {
rotationSpeed = std::min(-params_.minRotationalSpeed, robotSpeed.vtheta() + params_.maxRotationalAcceleration * dt);
} else {
rotationSpeed = std::max(params_.minRotationalSpeed, robotSpeed.vtheta() - params_.maxRotationalAcceleration * dt);
}
if (std::abs(diff.value()) <= params_.admittedAnglePositionError) {
rotationSpeed = 0.;
isGoalReached_ = true;
}
}
return Speed(0.0, 0.0, rotationSpeed);
}
void RotationControl::setTargetAngle(const Angle &angle) {
targetAngle_ = angle;
state_ = eRotationControlState::ACCELERATE;
isGoalReached_ = false;
}
} // namespace rd
| 39.457627
| 149
| 0.705756
|
rustyducks
|
917b5cf644038138fc496999557aa6c0a78590d0
| 1,123
|
cpp
|
C++
|
paint/src/Tool.cpp
|
nickveys/opengl-play
|
a297b4ea804255fd54e4b1e78fb7d79d3e185b23
|
[
"MIT"
] | null | null | null |
paint/src/Tool.cpp
|
nickveys/opengl-play
|
a297b4ea804255fd54e4b1e78fb7d79d3e185b23
|
[
"MIT"
] | null | null | null |
paint/src/Tool.cpp
|
nickveys/opengl-play
|
a297b4ea804255fd54e4b1e78fb7d79d3e185b23
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <glut.h>
#include "Paintable.h"
#include "Tool.h"
/* default tool setup */
struct color4f Tool::color = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat Tool::size = 2.0f;
GLfloat Tool::width = 2.0f;
bool Tool::fill = false;
Tool::Tool() {
mouseCurrentlyDown = false;
}
void Tool::mouseDown(struct point2f p) {
mouseCurrentlyDown = true;
}
void Tool::mouseMove(struct point2f p) {
/* do nothing */
}
void Tool::mouseUp(struct point2f p) {
/* ignore up clicks from clicking the menus */
if(mouseCurrentlyDown) {
mouseCurrentlyDown = false;
}
}
void Tool::setColor(GLfloat r, GLfloat g, GLfloat b) {
color.r = r;
color.g = g;
color.b = b;
}
void Tool::notifyIntermediatePaintableCreated(Paintable* p) {
std::vector< ToolListener* >::const_iterator itr = toolListeners.begin();
while(itr != toolListeners.end()) {
(*itr)->intermediatePaintableCreated(p);
itr++;
}
}
void Tool::notifyFinalPaintableCreated(Paintable* p) {
std::vector< ToolListener* >::const_iterator itr = toolListeners.begin();
while(itr != toolListeners.end()) {
(*itr)->finalPaintableCreated(p);
itr++;
}
}
| 20.796296
| 74
| 0.684773
|
nickveys
|
9186428070d989d125f328ed02f09eb3d5f7dcb3
| 436
|
cpp
|
C++
|
Code/766_Toeplitz_Matrix.cpp
|
DCOLIVERSUN/LeetCode
|
e0ef5ed8a267d81cc794914c3c1f22b013a32871
|
[
"MIT"
] | 1
|
2019-11-12T08:15:33.000Z
|
2019-11-12T08:15:33.000Z
|
Code/766_Toeplitz_Matrix.cpp
|
DCOLIVERSUN/LeetCode
|
e0ef5ed8a267d81cc794914c3c1f22b013a32871
|
[
"MIT"
] | null | null | null |
Code/766_Toeplitz_Matrix.cpp
|
DCOLIVERSUN/LeetCode
|
e0ef5ed8a267d81cc794914c3c1f22b013a32871
|
[
"MIT"
] | null | null | null |
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return false;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (i > 0 && j > 0 && matrix[i - 1][j - 1] != matrix[i][j]) {
return false;
}
}
}
return true;
}
};
| 29.066667
| 77
| 0.417431
|
DCOLIVERSUN
|
918881110005b3a420df0881b6c52546869c3bbd
| 537
|
cpp
|
C++
|
RightL.cpp
|
imor/Quadris
|
85b119c887b5473a15a1aaaecf4a772e2aff2359
|
[
"MIT"
] | null | null | null |
RightL.cpp
|
imor/Quadris
|
85b119c887b5473a15a1aaaecf4a772e2aff2359
|
[
"MIT"
] | null | null | null |
RightL.cpp
|
imor/Quadris
|
85b119c887b5473a15a1aaaecf4a772e2aff2359
|
[
"MIT"
] | null | null | null |
#include "RightL.h"
using namespace std;
RightL::RightL(int originX, int originY, Texture* texture) :
Tetramino(originX, originY, 2, texture)
{
setOrigin(originX, originY);
}
void RightL::setOrigin(int x, int y)
{
blockPositions[0].setX(x + texture->getWidth());
blockPositions[0].setY(y - texture->getHeight());
blockPositions[1].setX(x - texture->getWidth());
blockPositions[1].setY(y);
blockPositions[2].setX(x);
blockPositions[2].setY(y);
blockPositions[3].setX(x + texture->getWidth());
blockPositions[3].setY(y);
}
| 21.48
| 60
| 0.705773
|
imor
|
9189dea489df2bca4d92dda3fc1578a81f88a6f5
| 5,716
|
cpp
|
C++
|
tests/client/client.cpp
|
cthulhu-irl/touca-cpp
|
97392a1f84c7a92211ee86bcb527637a6c9a5cba
|
[
"Apache-2.0"
] | 12
|
2021-06-27T01:44:49.000Z
|
2022-03-11T10:08:34.000Z
|
sdk/cpp/tests/client/client.cpp
|
trytouca/trytouca
|
eae38a96407d1ecac543c5a5fb05cbbe632ddfca
|
[
"Apache-2.0"
] | 8
|
2021-06-25T13:05:29.000Z
|
2022-03-26T20:28:14.000Z
|
sdk/cpp/tests/client/client.cpp
|
trytouca/trytouca
|
eae38a96407d1ecac543c5a5fb05cbbe632ddfca
|
[
"Apache-2.0"
] | 4
|
2021-06-25T11:31:12.000Z
|
2022-03-16T05:50:52.000Z
|
// Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
#include "touca/client/detail/client.hpp"
#include "catch2/catch.hpp"
#include "tests/devkit/tmpfile.hpp"
#include "touca/devkit/resultfile.hpp"
#include "touca/devkit/utils.hpp"
using namespace touca;
std::string save_and_read_back(const touca::ClientImpl& client) {
TmpFile file;
CHECK_NOTHROW(client.save(file.path, {}, DataFormat::JSON, true));
return detail::load_string_file(file.path.string());
}
ElementsMap save_and_load_back(const touca::ClientImpl& client) {
TmpFile file;
CHECK_NOTHROW(client.save(file.path, {}, DataFormat::FBS, true));
ResultFile resultFile(file.path);
return resultFile.parse();
}
TEST_CASE("empty client") {
touca::ClientImpl client;
REQUIRE(client.is_configured() == false);
CHECK(client.configuration_error().empty() == true);
REQUIRE_NOTHROW(client.configure({{"api-key", "some-secret-key"},
{"api-url", "http://localhost:8081"},
{"team", "myteam"},
{"suite", "mysuite"},
{"version", "myversion"},
{"offline", "true"}}));
CHECK(client.is_configured() == true);
CHECK(client.configuration_error().empty() == true);
// Calling post for a client with no testcase should fail.
SECTION("post") {
REQUIRE_NOTHROW(client.post());
CHECK(client.post() == false);
}
SECTION("save") {
const auto& output = save_and_read_back(client);
CHECK(output == "[]");
}
}
#if _POSIX_C_SOURCE >= 200112L
TEST_CASE("configure with environment variables") {
touca::ClientImpl client;
client.configure();
CHECK(client.is_configured() == true);
setenv("TOUCA_API_KEY", "some-key", 1);
setenv("TOUCA_API_URL", "https://api.touca.io/@/some-team/some-suite", 1);
client.configure({{"version", "myversion"}, {"offline", "true"}});
CHECK(client.is_configured() == true);
CHECK(client.configuration_error() == "");
CHECK(client.options().api_key == "some-key");
CHECK(client.options().team == "some-team");
CHECK(client.options().suite == "some-suite");
unsetenv("TOUCA_API_KEY");
unsetenv("TOUCA_API_URL");
}
#endif
TEST_CASE("using a configured client") {
touca::ClientImpl client;
const touca::ClientImpl::OptionsMap options_map = {{"team", "myteam"},
{"suite", "mysuite"},
{"version", "myversion"},
{"offline", "true"}};
REQUIRE_NOTHROW(client.configure(options_map));
REQUIRE(client.is_configured() == true);
CHECK(client.configuration_error().empty() == true);
SECTION("testcase switch") {
CHECK_NOTHROW(client.add_hit_count("ignored-key"));
CHECK(client.declare_testcase("some-case"));
CHECK_NOTHROW(client.add_hit_count("some-key"));
CHECK(client.declare_testcase("some-other-case"));
CHECK_NOTHROW(client.add_hit_count("some-other-key"));
CHECK(client.declare_testcase("some-case"));
CHECK_NOTHROW(client.add_hit_count("some-other-key"));
const auto& content = save_and_load_back(client);
REQUIRE(content.count("some-case"));
REQUIRE(content.count("some-other-case"));
CHECK(content.at("some-case")->overview().keysCount == 2);
CHECK(content.at("some-other-case")->overview().keysCount == 1);
}
SECTION("results") {
client.declare_testcase("some-case");
const auto& v1 = data_point::boolean(true);
CHECK_NOTHROW(client.check("some-value", v1));
CHECK_NOTHROW(client.add_hit_count("some-other-value"));
CHECK_NOTHROW(client.add_array_element("some-array-value", v1));
const auto& content = save_and_read_back(client);
const auto& expected =
R"("results":[{"key":"some-array-value","value":"[true]"},{"key":"some-other-value","value":"1"},{"key":"some-value","value":"true"}])";
CHECK_THAT(content, Catch::Contains(expected));
}
/**
* bug
*/
SECTION("assumptions") {
client.declare_testcase("some-case");
const auto& v1 = data_point::boolean(true);
CHECK_NOTHROW(client.assume("some-value", v1));
const auto& content = save_and_read_back(client);
const auto& expected = R"([])";
CHECK_THAT(content, Catch::Contains(expected));
}
SECTION("metrics") {
const auto& tc = client.declare_testcase("some-case");
CHECK(tc->metrics().empty());
CHECK_NOTHROW(client.start_timer("a"));
CHECK(tc->metrics().empty());
CHECK_THROWS_AS(client.stop_timer("b"), std::invalid_argument);
CHECK_NOTHROW(client.start_timer("b"));
CHECK(tc->metrics().empty());
CHECK_NOTHROW(client.stop_timer("b"));
CHECK(tc->metrics().size() == 1);
CHECK(tc->metrics().count("b"));
const auto& content = save_and_read_back(client);
const auto& expected =
R"("results":[],"assertion":[],"metrics":[{"key":"b","value":"0"}])";
CHECK_THAT(content, Catch::Contains(expected));
}
SECTION("forget_testcase") {
client.declare_testcase("some-case");
const auto& v1 = data_point::boolean(true);
client.check("some-value", v1);
client.assume("some-assertion", v1);
client.start_timer("some-metric");
client.stop_timer("some-metric");
client.forget_testcase("some-case");
const auto& content = save_and_read_back(client);
CHECK_THAT(content, Catch::Contains(R"([])"));
}
/**
* Calling post when client is locally configured should throw exception.
*/
SECTION("post") {
REQUIRE_NOTHROW(client.declare_testcase("mycase"));
REQUIRE_NOTHROW(client.post());
REQUIRE(client.post() == false);
}
}
| 36.877419
| 144
| 0.635934
|
cthulhu-irl
|
918afeef8fa01a15e812d1e95c8ec82f6aafec8f
| 3,050
|
cpp
|
C++
|
src/Utility/Box.cpp
|
heltena/KYEngine
|
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
|
[
"MIT"
] | null | null | null |
src/Utility/Box.cpp
|
heltena/KYEngine
|
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
|
[
"MIT"
] | null | null | null |
src/Utility/Box.cpp
|
heltena/KYEngine
|
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
|
[
"MIT"
] | null | null | null |
#include <KYEngine/Utility/Box.h>
#include <algorithm>
Box::Box()
{
m_values[0] = 0.0f;
m_values[1] = 0.0f;
m_values[2] = 1.0f;
m_values[3] = 1.0f;
}
Box::Box(const Box& other)
{
for(int i = 0; i < 4; i++)
m_values[i] = other.m_values[i];
}
Box::Box(float width, float height)
{
m_values[0] = 0.0f;
m_values[1] = 0.0f;
m_values[2] = width;
m_values[3] = height;
}
Box::Box(float left, float top, float width, float height)
{
m_values[0] = left;
m_values[1] = top;
m_values[2] = width;
m_values[3] = height;
}
float& Box::operator[](int index)
{
return m_values[index];
}
float Box::operator[](int index) const
{
return m_values[index];
}
Box& Box::operator=(const Box& other)
{
for(int i = 0; i < 4; i++)
m_values[i] = other.m_values[i];
return *this;
}
Box& Box::addSize(double width, double height, bool center)
{
if (center) {
m_values[0] -= width / 2.;
m_values[1] -= height / 2.;
}
m_values[2] += width;
m_values[3] += height;
return *this;
}
Box& Box::unionWith(const Box& other)
{
float right = std::max(m_values[0] + m_values[2], other.m_values[0] + other.m_values[2]);
float bottom = std::max(m_values[1] + m_values[3], other.m_values[1] + other.m_values[3]);
m_values[0] = std::min(m_values[0], other.m_values[0]);
m_values[1] = std::min(m_values[1], other.m_values[1]);
m_values[2] = right - m_values[0];
m_values[3] = bottom - m_values[1];
return *this;
}
Box& Box::scale(const Vector4& scale)
{
m_values[2] *= scale[0];
m_values[3] *= scale[1];
return *this;
}
Box& Box::translate(const Vector4& offset)
{
m_values[0] += offset[0];
m_values[1] += offset[1];
return *this;
}
Box Box::intersection(const Box& other) const
{
float f[2], t[2];
for(int i = 0; i < 2; i++) {
float a = m_values[i];
float b = m_values[i] + m_values[2 + i];
float c = other.m_values[i];
float d = other.m_values[i] + other.m_values[2 + i];
if (a > b)
std::swap(a, b);
if (c > d)
std::swap(c, d);
if (a > c) {
std::swap(a, c);
std::swap(b, d);
}
if (b < c) // a----b c----d
return Box(0, 0, 0, 0);
if (b == c) { // a----b/c----d
f[i] = b;
t[i] = b;
} else if (b < d) { // a----c===b---d
f[i] = c;
t[i] = b;
} else { // a----c===d----b
f[i] = c;
t[i] = d;
}
}
return Box(f[0], f[1], t[0] - f[0], t[1] - f[1]);
}
bool Box::contains(const Vector4& pos) const
{
return (pos[0] >= m_values[0])
&& (pos[0] <= m_values[0] + m_values[2])
&& (pos[1] >= m_values[1])
&& (pos[1] <= m_values[1] + m_values[3]);
}
std::ostream& Box::write(std::ostream& out) const
{
return out
<< "(" << m_values[0]
<< ", " << m_values[1]
<< ", " << m_values[2]
<< ", " << m_values[3]
<< ")";
}
std::ostream& operator<<(std::ostream& out, const Box& item) {
return item.write(out);
}
| 20.469799
| 91
| 0.518689
|
heltena
|
9260ab5bc8b6ee92be0a168c054a8a2687c38ba9
| 5,583
|
hpp
|
C++
|
third_party/boost/simd/arch/common/generic/function/all_reduce.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | 6
|
2018-02-25T22:23:33.000Z
|
2021-01-15T15:13:12.000Z
|
third_party/boost/simd/arch/common/generic/function/all_reduce.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/boost/simd/arch/common/generic/function/all_reduce.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | 7
|
2017-12-12T12:36:31.000Z
|
2020-02-10T14:27:07.000Z
|
//==================================================================================================
/**
Copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_ALL_REDUCE_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_GENERIC_FUNCTION_ALL_REDUCE_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>
#include <boost/simd/function/shuffle.hpp>
#include <boost/simd/function/combine.hpp>
#include <boost/simd/detail/dispatch/detail/declval.hpp>
#include <boost/simd/detail/nsm.hpp>
namespace boost { namespace simd { namespace detail
{
namespace tt = nsm::type_traits;
//------------------------------------------------------------------------------------------------
// This meta-permutation implements the butterfly pattern required for log-tree based reductions.
//
// V is a vector of cardinal 4 : [ v0 | v1 | v2 | v3 ]
// The log-tree reduction will require : [ v2 | v3 | v0 | v1 ]
// and : [ v3 | v2 | v1 | v0 ]
//
// Basically this requires permuting cardinal/2^n value at each iteration
// stopping when only 1 element is left to be permuted.
//------------------------------------------------------------------------------------------------
template<int Step> struct butterfly_perm
{
template<typename I, typename>
struct apply : tt::integral_constant<int,(I::value >= Step) ? I::value-Step : I::value+Step>
{};
};
template<int Step> struct butterfly
{
using next_t = butterfly<Step/2>;
template<typename Op, typename V>
BOOST_FORCEINLINE
auto operator()(Op const& op, V const& a0) const BOOST_NOEXCEPT
-> decltype( next_t{}( op, op(a0, boost::simd::shuffle< butterfly_perm<Step> >(a0)) ) )
{
next_t next;
return next( op, op(a0, boost::simd::shuffle< butterfly_perm<Step> >(a0)) );
}
};
template<> struct butterfly<1>
{
template<typename Op, typename V>
BOOST_FORCEINLINE
auto operator()(Op const& op, V const& a0) const BOOST_NOEXCEPT
-> decltype( op(boost::simd::shuffle< butterfly_perm<1> >(a0),a0) )
{
return op(boost::simd::shuffle< butterfly_perm<1> >(a0),a0);
}
};
} } }
namespace boost { namespace simd { namespace ext
{
namespace bs = boost::simd;
namespace bd = boost::dispatch;
BOOST_DISPATCH_OVERLOAD_FALLBACK ( ( typename BinOp, typename Neutral
, typename Arg, typename Ext
)
, tag::all_reduce_
, bd::cpu_
, bd::elementwise_<BinOp>
, bs::pack_<bd::unspecified_<Neutral>, Ext>
, bs::pack_<bd::unspecified_<Arg>, Ext>
)
{
using function_t = bd::functor<BinOp>;
using result_t = decltype( bd::functor<BinOp>()( bd::detail::declval<Arg>()
, bd::detail::declval<Neutral>()
)
);
// ---------------------------------------------------------------------------------------------
// singleton case
template<typename K, typename N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, K const&, nsm::list<N> const&
)
{
return op( z, a0 );
}
// ---------------------------------------------------------------------------------------------
// Native case
template<typename N0, typename N1, typename... N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, native_storage const&, nsm::list<N0,N1,N...> const&
)
{
return op(detail::butterfly<Arg::static_size/2>{}(op,a0),z);
}
// ---------------------------------------------------------------------------------------------
// Aggregate case
template<typename N0, typename N1, typename... N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, aggregate_storage const&, nsm::list<N0,N1,N...> const&
)
{
auto r = detail::all_reduce(op,z.storage()[0],a0.storage()[0]);
r = detail::all_reduce(op,r,a0.storage()[1]);
return combine(r,r);
}
// ---------------------------------------------------------------------------------------------
// Scalar case
template<typename N0, typename N1, typename... N> static BOOST_FORCEINLINE
result_t fold_( function_t const& op, Neutral const& z, Arg const& a0
, scalar_storage const&, nsm::list<N0,N1,N...> const&
)
{
auto r = op( bs::extract<0>(a0), z );
r = op( bs::extract<1>(a0), r );
(void)std::initializer_list<bool> { ((r = op(bs::extract<N::value>(a0),r)),true)... };
return result_t(r);
}
BOOST_FORCEINLINE result_t
operator()(function_t const& op, Neutral const& z, Arg const& a0) const
{
return fold_(op, z, a0, typename Arg::storage_kind{}, typename Arg::traits::static_range{});
}
};
} } }
#endif
| 39.595745
| 100
| 0.491671
|
SylvainCorlay
|
9262bfebc838c82d6139563fb0628222f4d5e53f
| 952
|
hpp
|
C++
|
engine/include/core/event/providers/glfw.hpp
|
dorosch/engine
|
0cd277675264f848ac141f7e5663242bd7b43438
|
[
"MIT"
] | null | null | null |
engine/include/core/event/providers/glfw.hpp
|
dorosch/engine
|
0cd277675264f848ac141f7e5663242bd7b43438
|
[
"MIT"
] | null | null | null |
engine/include/core/event/providers/glfw.hpp
|
dorosch/engine
|
0cd277675264f848ac141f7e5663242bd7b43438
|
[
"MIT"
] | null | null | null |
#ifndef __GLFW_EVENT_PROVIDER_HPP__
#define __GLFW_EVENT_PROVIDER_HPP__
#ifndef GLEW_STATIC
#define GLEW_STATIC
#endif
#include <memory>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "core/event/provider.hpp"
#include "core/event/observer.hpp"
#include "tools/logger.hpp"
using namespace Tool::Logger;
namespace Engine {
namespace Event {
class GLFWEventProvider : public EventProvider {
protected:
std::unique_ptr<Logger> logger = std::make_unique<Logger>("glfwe");
public:
void MouseEventCallback() {};
void KeyboardEventCallback() {};
void MouseEventCallback(GLFWwindow *, int, int, int);
void KeyboardEventCallback(GLFWwindow *, int, int, int, int);
static void MouseEventCallbackStatic(GLFWwindow *, int, int, int);
static void KeyboardEventCallbackStatic(GLFWwindow *, int, int, int, int);
};
}
}
#endif
| 24.410256
| 86
| 0.667017
|
dorosch
|
9265d78d773141c87ee53a31fa84206aa2c43596
| 691
|
cpp
|
C++
|
atcoder/abc/abc160/d.cpp
|
yu3mars/proconVSCodeGcc
|
fcf36165bb14fb6f555664355e05dd08d12e426b
|
[
"MIT"
] | null | null | null |
atcoder/abc/abc160/d.cpp
|
yu3mars/proconVSCodeGcc
|
fcf36165bb14fb6f555664355e05dd08d12e426b
|
[
"MIT"
] | null | null | null |
atcoder/abc/abc160/d.cpp
|
yu3mars/proconVSCodeGcc
|
fcf36165bb14fb6f555664355e05dd08d12e426b
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main()
{
int n,x,y;
cin>>n>>x>>y;
x--;
y--;
vector<int> ans(n);
for (int j = 0; j < n; j++)
{
for (int i = 0; i < j; i++)//i<j
{
int d = min(j-i,abs(i-x)+abs(j-y)+1);
ans[d]++;
}
}
for (int i = 1; i < n; i++)
{
cout<<ans[i]<<endl;
}
return 0;
}
| 18.184211
| 58
| 0.442836
|
yu3mars
|
92665ce36db6b634ce075c8c1fbefa63428da6cd
| 5,619
|
cpp
|
C++
|
src/tools/download.cpp
|
alexandria-org/alexandria
|
ca0c890fea3ba931ad849ded95d6187838718a4c
|
[
"MIT"
] | 113
|
2022-02-12T00:07:52.000Z
|
2022-03-28T08:02:39.000Z
|
src/tools/download.cpp
|
alexandria-org/alexandria
|
ca0c890fea3ba931ad849ded95d6187838718a4c
|
[
"MIT"
] | 8
|
2021-09-26T07:52:47.000Z
|
2022-03-28T06:56:02.000Z
|
src/tools/download.cpp
|
alexandria-org/alexandria
|
ca0c890fea3ba931ad849ded95d6187838718a4c
|
[
"MIT"
] | 5
|
2022-03-18T22:20:50.000Z
|
2022-03-25T15:41:06.000Z
|
/*
* MIT License
*
* Alexandria.org
*
* Copyright (c) 2021 Josef Cullhed, <info@alexandria.org>, et al.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "download.h"
#include "transfer/transfer.h"
#include "file/tsv_file_remote.h"
#include "profiler/profiler.h"
#include "algorithm/algorithm.h"
#include "url_link/link.h"
#include "common/system.h"
#include "config.h"
#include "logger/logger.h"
#include <math.h>
#include <unordered_set>
#include <future>
using namespace std;
namespace tools {
const size_t max_num_batches = 24;
vector<string> download_batch(const string &batch) {
file::tsv_file_remote warc_paths_file(string("crawl-data/") + batch + "/warc.paths.gz");
vector<string> warc_paths;
warc_paths_file.read_column_into(0, warc_paths);
vector<string> files_to_download;
for (const string &str : warc_paths) {
string warc_path = str;
const size_t pos = warc_path.find(".warc.gz");
if (pos != string::npos) {
warc_path.replace(pos, 8, ".gz");
}
files_to_download.push_back(warc_path);
//if (files_to_download.size() == 100) break;
}
return transfer::download_gz_files_to_disk(files_to_download);
}
unordered_set<size_t> make_url_set_one_thread(const vector<string> &files) {
unordered_set<size_t> result;
for (const string &file_path : files) {
ifstream infile(file_path);
string line;
while (getline(infile, line)) {
const url_link::link link(line);
result.insert(link.target_url().hash());
}
}
return result;
}
unordered_set<size_t> make_url_set(const vector<string> &files) {
unordered_set<size_t> total_result;
size_t idx = 0;
for (const string &file_path : files) {
ifstream infile(file_path);
string line;
while (getline(infile, line)) {
const url_link::link link(line);
total_result.insert(link.target_url().hash());
}
cout << "size: " << total_result.size() << " done " << (++idx) << "/" << files.size() << endl;
}
return total_result;
}
void upload_cache(size_t file_index, size_t thread_id, const string &data, size_t node_id) {
const string filename = "crawl-data/NODE-" + to_string(node_id) + "-small/files/" + to_string(thread_id) + "-" + to_string(file_index) + "-" +
to_string(profiler::now_micro()) + ".gz";
int error = transfer::upload_gz_file(filename, data);
if (error == transfer::ERROR) {
LOG_INFO("Upload failed!");
}
}
void parse_urls_with_links_thread(const vector<string> &warc_paths, const unordered_set<size_t> &url_set) {
const size_t max_cache_size = 150000;
size_t thread_id = common::thread_id();
size_t file_index = 1;
LOG_INFO("url_set.size() == " + to_string(url_set.size()));
vector<vector<string>> cache(max_num_batches);
for (const string &warc_path : warc_paths) {
ifstream infile(warc_path);
string line;
while (getline(infile, line)) {
const URL url(line.substr(0, line.find("\t")));
if (url_set.count(url.hash())) {
const size_t node_id = url.host_hash() % max_num_batches;
cache[node_id].push_back(line);
}
}
for (size_t node_id = 0; node_id < max_num_batches; node_id++) {
if (cache[node_id].size() > max_cache_size) {
const string cache_data = boost::algorithm::join(cache[node_id], "\n");
cache[node_id].clear();
upload_cache(file_index++, thread_id, cache_data, node_id);
}
}
}
for (size_t node_id = 0; node_id < max_num_batches; node_id++) {
if (cache[node_id].size() > 0) {
const string cache_data = boost::algorithm::join(cache[node_id], "\n");
cache[node_id].clear();
upload_cache(file_index++, thread_id, cache_data, node_id);
}
}
}
void upload_urls_with_links(const vector<string> &local_files, const unordered_set<size_t> &url_set) {
size_t num_threads = 24;
vector<vector<string>> thread_input;
algorithm::vector_chunk(local_files, ceil((double)local_files.size() / num_threads), thread_input);
vector<thread> threads;
for (size_t i = 0; i < thread_input.size(); i++) {
threads.emplace_back(thread(parse_urls_with_links_thread, thread_input[i], cref(url_set)));
}
for (thread &one_thread : threads) {
one_thread.join();
}
}
void prepare_batch(size_t batch_num) {
const vector<string> files = download_batch("NODE-" + to_string(batch_num));
const vector<string> link_files = download_batch("LINK-" + to_string(batch_num));
unordered_set<size_t> url_set = make_url_set(link_files);
upload_urls_with_links(files, url_set);
transfer::delete_downloaded_files(link_files);
transfer::delete_downloaded_files(files);
}
}
| 31.216667
| 144
| 0.706531
|
alexandria-org
|
926861ad88d7db25eab56ca1d0a06a75875b4bde
| 1,208
|
cpp
|
C++
|
source/Vertex.cpp
|
nicovanbentum/Scatter
|
72fc7386767d8c058c55fbe15055ea9397d018e1
|
[
"MIT"
] | null | null | null |
source/Vertex.cpp
|
nicovanbentum/Scatter
|
72fc7386767d8c058c55fbe15055ea9397d018e1
|
[
"MIT"
] | null | null | null |
source/Vertex.cpp
|
nicovanbentum/Scatter
|
72fc7386767d8c058c55fbe15055ea9397d018e1
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "Vertex.h"
namespace scatter {
VkVertexInputBindingDescription Vertex::getBindingDescription() {
VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
std::array<VkVertexInputAttributeDescription, 3> Vertex::getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 3> attributeDescription{};
attributeDescription[0].binding = 0;
attributeDescription[0].location = 0;
attributeDescription[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescription[0].offset = offsetof(Vertex, pos);
attributeDescription[1].binding = 0;
attributeDescription[1].location = 1;
attributeDescription[1].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescription[1].offset = offsetof(Vertex, texcoord);
attributeDescription[2].binding = 0;
attributeDescription[2].location = 2;
attributeDescription[2].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescription[2].offset = offsetof(Vertex, normal);
return attributeDescription;
}
} // scatter
| 35.529412
| 85
| 0.768212
|
nicovanbentum
|
92689b10d3ff9b104ba3bd3674e40b0e241afca0
| 677
|
cpp
|
C++
|
src/expressions/data/tuple.cpp
|
rationalis-petra/hydra
|
a1c14e560f5f1c64983468e5fd0be7b32824971d
|
[
"MIT"
] | 2
|
2021-01-14T11:19:02.000Z
|
2021-03-07T03:08:08.000Z
|
src/expressions/data/tuple.cpp
|
rationalis-petra/hydra
|
a1c14e560f5f1c64983468e5fd0be7b32824971d
|
[
"MIT"
] | null | null | null |
src/expressions/data/tuple.cpp
|
rationalis-petra/hydra
|
a1c14e560f5f1c64983468e5fd0be7b32824971d
|
[
"MIT"
] | null | null | null |
#include <string>
#include <typeinfo>
#include "utils.hpp"
#include "expressions.hpp"
using namespace std;
using namespace expr;
using namespace interp;
Parent* Tuple::parent;
int Tuple::size() {
return values.size();
}
Object* Tuple::operator[](int i) {
return values[i];
}
void Tuple::mark_node() {
if (marked) return;
Object::mark_node();
for (Object* o : values) {
o->mark_node();
}
}
string Tuple::to_string(LocalRuntime &r, LexicalScope &s) {
string out = "(|";
for (unsigned i = 0; i < values.size() ; i++) {
out += modulus_to_string(values[i], r, s);
if (i != values.size() - 1)
out += " ";
}
out += "|)";
return out;
}
| 16.512195
| 59
| 0.60709
|
rationalis-petra
|
92692c9d8c5f392980f8924a8e025eb6f1fea978
| 2,903
|
cc
|
C++
|
src/quantsystem/engine/real_time/backtesting_real_time_handler.cc
|
ydxt25/QuantSystem
|
b4298121ce8fbe13d8fe7fcaf502565736df9bfe
|
[
"Apache-2.0"
] | 49
|
2016-11-03T20:51:45.000Z
|
2022-03-30T22:34:25.000Z
|
src/quantsystem/engine/real_time/backtesting_real_time_handler.cc
|
seepls/QuantSystem
|
b4298121ce8fbe13d8fe7fcaf502565736df9bfe
|
[
"Apache-2.0"
] | null | null | null |
src/quantsystem/engine/real_time/backtesting_real_time_handler.cc
|
seepls/QuantSystem
|
b4298121ce8fbe13d8fe7fcaf502565736df9bfe
|
[
"Apache-2.0"
] | 33
|
2016-07-17T05:19:59.000Z
|
2022-03-07T17:45:57.000Z
|
/*
* \copyright Copyright 2015 All Rights Reserved.
* \license @{
*
* 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 <thread>
#include <chrono>
#include <functional>
#include "quantsystem/common/util/stl_util.h"
#include "quantsystem/common/securities/security.h"
#include "quantsystem/engine/real_time/backtesting_real_time_handler.h"
namespace quantsystem {
using securities::Security;
namespace engine {
namespace realtime {
BacktestingRealTimeHandler::BacktestingRealTimeHandler(
IAlgorithm* algorithm,
AlgorithmNodePacket* job)
: exit_triggered_(false),
algorithm_(algorithm),
job_(job) {
is_active_ = true;
}
BacktestingRealTimeHandler::~BacktestingRealTimeHandler() {
STLDeleteElements(&events_);
}
void RealTimeEventHelper(IAlgorithm* algorithm, const Security* security) {
algorithm->OnEndOfDay();
algorithm->OnEndOfDay(security->symbol());
}
void BacktestingRealTimeHandler::SetupEvents(const DateTime& date) {
ClearEvents();
vector<const Security*> securities;
algorithm_->securities()->Values(&securities);
for (int i = 0; i < securities.size(); ++i) {
const Security* security = securities[i];
RealTimeEvent::CallBackType* func = new RealTimeEvent::CallBackType(
std::bind(RealTimeEventHelper, algorithm_, security));
AddEvent(new RealTimeEvent(security->exchange()->market_close() -
TimeSpan::FromMinutes(10), func));
}
}
void BacktestingRealTimeHandler::Run() {
is_active_ = true;
while (!exit_triggered_) {
std::this_thread::sleep_for(std::chrono::seconds(50));
}
is_active_ = false;
}
void BacktestingRealTimeHandler::AddEvent(RealTimeEvent* new_event) {
events_.push_back(new_event);
}
void BacktestingRealTimeHandler::ScanEvents() {
for (int i = 0; i < events_.size(); ++i) {
events_[i]->Scan(time_);
}
}
void BacktestingRealTimeHandler::ResetEvents() {
for (int i = 0; i < events_.size(); ++i) {
events_[i]->Reset();
}
}
void BacktestingRealTimeHandler::ClearEvents() {
STLDeleteElements(&events_);
}
void BacktestingRealTimeHandler::SetTime(const DateTime& time) {
if (time_ != time) {
SetupEvents(time);
ResetEvents();
}
time_ = time;
ScanEvents();
}
void BacktestingRealTimeHandler::Exit() {
exit_triggered_ = true;
}
} // namespace realtime
} // namespace engine
} // namespace quantsystem
| 27.647619
| 75
| 0.715122
|
ydxt25
|
926e2857a2c0ccf45687d2691699f2bec4ea0bd4
| 552
|
cpp
|
C++
|
src/srbpy/alignment/Straight.cpp
|
billhu0228/SmartRoadBridgePy
|
4a5d34028a2612aef846b580733bf6f488110798
|
[
"MIT"
] | 2
|
2020-08-05T10:46:45.000Z
|
2020-08-11T11:05:18.000Z
|
src/srbpy/alignment/Straight.cpp
|
billhu0228/SmartRoadBridgePy
|
4a5d34028a2612aef846b580733bf6f488110798
|
[
"MIT"
] | null | null | null |
src/srbpy/alignment/Straight.cpp
|
billhu0228/SmartRoadBridgePy
|
4a5d34028a2612aef846b580733bf6f488110798
|
[
"MIT"
] | 1
|
2020-08-26T07:50:22.000Z
|
2020-08-26T07:50:22.000Z
|
#include "Straight.h"
Straight::Straight(void)
{
__length = 0;
}
Straight::Straight(double length, Vector& st, Angle& sdir, EITypeID idd, LeftRightEnum lr)
:PQXElement(idd, st, sdir, lr)
{
__length = length;
}
Vector Straight::get_point_on_curve(double l_from_st) const
{
double x = l_from_st;
double y = 0;
Vector res = Vector(y, x).rotate2d(start_angle * -1);
return start_point + res;
}
//
//double Straight::length() const
//{
// return __length;
//}
Angle Straight::end_angle() const
{
return Angle(start_angle.GetRadian());
}
| 14.526316
| 90
| 0.690217
|
billhu0228
|
9278f72097cce6b4a6663e1e031f062163dfde3b
| 1,017
|
cpp
|
C++
|
question_solution/first_time/1057.cpp
|
xiaoland/CaiojSolution
|
a12c505235d70b414071ea894fa72cddbcfabc6d
|
[
"Apache-2.0"
] | 1
|
2020-09-24T13:35:45.000Z
|
2020-09-24T13:35:45.000Z
|
question_solution/first_time/1057.cpp
|
xiaoland/CaiojSolution
|
a12c505235d70b414071ea894fa72cddbcfabc6d
|
[
"Apache-2.0"
] | null | null | null |
question_solution/first_time/1057.cpp
|
xiaoland/CaiojSolution
|
a12c505235d70b414071ea894fa72cddbcfabc6d
|
[
"Apache-2.0"
] | null | null | null |
// author: Lan_zhijiang
// description: 含价值的填满型背包1
// 二维数组版
// 背包问题就是要你作出在限制条件下的最佳组合选择
// 解决背包问题最朴素的方法就是列出所有可能性
// 但根据题目条件的不同,都有不同的优化
// 我们还要特别注意节省内存,将自己的算法进行简化,找出多余的部分(比如将二维数组转为一维数组来使用)
// 要检查草稿有没有错误,按着你写的代码再来自己执行一遍,不要弄错了
#include <cstdio>
#include <cstring>
#include <algorithm> // 背包问题要用的max
using namespace std; // algotithm不可少
int n, m[101], t[101], tl;
int out[101][1001];
void read_in() {
scanf("%d%d", &tl, &n);
for(int i = 1; i<=n; i++) {
scanf("%d%d", &t[i], &m[i]);
}
}
int main() {
read_in();
for(int i = 1; i<=n; i++) { // 将时间=0或宝石=0的地方都填上0(任何一个为0都没意义)
out[i][0] = 0;
}
for(int i = 1; i<=tl; i++) {
out[0][i] = 0;
}
for(int i = 1; i<=n; i++) {
for(int j = 1; j<=tl; j++) {
if(j<t[i]) {
out[i][j] = out[i-1][j];
}
else {
out[i][j] = max(out[i-1][j], out[i-1][j - t[i]]+m[i]);
}
}
}
printf("%d\n", out[n][tl]);
return 0;
}
| 20.34
| 70
| 0.485742
|
xiaoland
|
927dbb2399b605df98f94cee47e40d5d50c710a6
| 4,397
|
cpp
|
C++
|
src/engine/subsystems/physics/bullet/bullet_physics_body.cpp
|
ukrainskiysergey/BallMaze
|
84d211ec0733fff7d2b13d5ffce707fb1813fe4e
|
[
"MIT"
] | null | null | null |
src/engine/subsystems/physics/bullet/bullet_physics_body.cpp
|
ukrainskiysergey/BallMaze
|
84d211ec0733fff7d2b13d5ffce707fb1813fe4e
|
[
"MIT"
] | null | null | null |
src/engine/subsystems/physics/bullet/bullet_physics_body.cpp
|
ukrainskiysergey/BallMaze
|
84d211ec0733fff7d2b13d5ffce707fb1813fe4e
|
[
"MIT"
] | null | null | null |
#include "engine/subsystems/physics/bullet/bullet_physics_body.h"
#include "engine/subsystems/physics/bullet/bullet_physics_world.h"
#include "engine/subsystems/physics/bullet/bullet_collision_shape.h"
BulletPhysicsBody::BulletPhysicsBody(BulletPhysicsWorld* world, const std::shared_ptr<BulletCollisionShape>& shape, const vec3& position, const Quaternion& rotation, float mass)
: world(world),
shape(shape),
motionState(std::make_unique<btDefaultMotionState>(
btTransform(
btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()),
btVector3(position.getX(), position.getY(), position.getZ()))))
{
btVector3 inertia(0, 0, 0);
if (mass != 0.0f)
shape->getCollisionShape()->calculateLocalInertia(mass, inertia);
btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, motionState.get(), shape->getCollisionShape(), inertia);
rigidBody = std::make_unique<btRigidBody>(rigidBodyCI);
rigidBody->setUserPointer(this);
rigidBody->setActivationState(DISABLE_DEACTIVATION);
world->getDynamicsWorld()->addRigidBody(rigidBody.get());
}
BulletPhysicsBody::~BulletPhysicsBody()
{
world->getDynamicsWorld()->removeRigidBody(rigidBody.get());
}
Transform BulletPhysicsBody::getWorldTransform() const
{
btTransform transform;
motionState->getWorldTransform(transform);
auto origin = transform.getOrigin();
auto rotation = transform.getRotation();
return Transform({ origin.getX(), origin.getY(), origin.getZ() }, Quaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()));
}
void BulletPhysicsBody::setWorldTransform(const Transform& transform)
{
btTransform bulletTransform(
btQuaternion(transform.rotation.getX(), transform.rotation.getY(), transform.rotation.getZ(), transform.rotation.getW()),
btVector3(transform.position.getX(), transform.position.getY(), transform.position.getZ()));
rigidBody->setWorldTransform(bulletTransform);
motionState->setWorldTransform(bulletTransform);
}
void BulletPhysicsBody::setPosition(const vec3& position)
{
auto& transform = rigidBody->getWorldTransform();
transform.setOrigin(btVector3(position.getX(), position.getY(), position.getZ()));
rigidBody->setWorldTransform(transform);
motionState->setWorldTransform(transform);
}
void BulletPhysicsBody::setRotation(const Quaternion& rotation)
{
auto& transform = rigidBody->getWorldTransform();
transform.setRotation(btQuaternion(rotation.getX(), rotation.getY(), rotation.getZ(), rotation.getW()));
rigidBody->setWorldTransform(transform);
motionState->setWorldTransform(transform);
}
void BulletPhysicsBody::setFriction(float friction)
{
rigidBody->setFriction(friction);
}
void BulletPhysicsBody::setRollingFriction(float rollingFriction)
{
rigidBody->setRollingFriction(rollingFriction);
}
void BulletPhysicsBody::setSpinningFriction(float spinningFriction)
{
rigidBody->setSpinningFriction(spinningFriction);
}
void BulletPhysicsBody::setRestitution(float restitution)
{
rigidBody->setRestitution(restitution);
}
void BulletPhysicsBody::clearForces()
{
rigidBody->clearForces();
}
void BulletPhysicsBody::applyTorque(const vec3& torque)
{
rigidBody->applyTorque(btVector3(torque.getX(), torque.getY(), torque.getZ()));
}
void BulletPhysicsBody::applyTorqueImpulse(const vec3& torque)
{
rigidBody->applyTorqueImpulse(btVector3(torque.getX(), torque.getY(), torque.getZ()));
}
void BulletPhysicsBody::applyCentralForce(const vec3& force)
{
rigidBody->applyCentralForce(btVector3(force.getX(), force.getY(), force.getZ()));
}
void BulletPhysicsBody::applyCentralImpulse(const vec3& impulse)
{
rigidBody->applyCentralImpulse(btVector3(impulse.getX(), impulse.getY(), impulse.getZ()));
}
void BulletPhysicsBody::disableContactResponse()
{
rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_NO_CONTACT_RESPONSE);
}
void BulletPhysicsBody::stop()
{
clearForces();
rigidBody->setLinearVelocity(btVector3(0.0f, 0.0f, 0.0f));
rigidBody->setAngularVelocity(btVector3(0.0f, 0.0f, 0.0f));
}
void BulletPhysicsBody::setKinematic(bool kinematic)
{
if (kinematic)
rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
else
rigidBody->setCollisionFlags(rigidBody->getCollisionFlags() & ~btCollisionObject::CF_KINEMATIC_OBJECT);
}
btRigidBody* BulletPhysicsBody::getBulletRigidBody() const
{
return rigidBody.get();
}
| 33.06015
| 177
| 0.784398
|
ukrainskiysergey
|
927ee1dd68f0d5636217928373823f6fb4c03469
| 2,762
|
cpp
|
C++
|
Core/JPetTreeHeader/JPetTreeHeaderTest.cpp
|
Alvarness/j-pet-framework
|
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
|
[
"Apache-2.0"
] | null | null | null |
Core/JPetTreeHeader/JPetTreeHeaderTest.cpp
|
Alvarness/j-pet-framework
|
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
|
[
"Apache-2.0"
] | null | null | null |
Core/JPetTreeHeader/JPetTreeHeaderTest.cpp
|
Alvarness/j-pet-framework
|
899ab32bf9a7f4daecaf8ed2dd7c8bc8922e73bd
|
[
"Apache-2.0"
] | null | null | null |
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTreeHeaderTest
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "./JPetTreeHeader/JPetTreeHeader.h"
BOOST_AUTO_TEST_SUITE(JPetTreeHeaderSuite)
BOOST_AUTO_TEST_CASE(emptyHeader){
JPetTreeHeader treeHeader;
BOOST_REQUIRE_EQUAL(treeHeader.getRunNumber(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getBaseFileName(), "filename not set" );
BOOST_REQUIRE_EQUAL(treeHeader.getSourcePosition(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getStagesNb(), 0 );
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(0).fModuleName, "module not set");
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(10).fModuleDescription, "description not set");
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(12).fModuleVersion, -1);
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(12).fCreationTime, "-1");
BOOST_REQUIRE_EQUAL(treeHeader.getVariable( "" ), "");
}
BOOST_AUTO_TEST_CASE(checkingEmptyStage){
JPetTreeHeader treeHeader;
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fModuleName, treeHeader.getProcessingStageInfo(0).fModuleName);
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fModuleDescription, treeHeader.getProcessingStageInfo(0).fModuleDescription);
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fModuleVersion, treeHeader.getProcessingStageInfo(0).fModuleVersion);
BOOST_REQUIRE_EQUAL(treeHeader.emptyProcessingStageInfo().fCreationTime, treeHeader.getProcessingStageInfo(0).fCreationTime);
}
BOOST_AUTO_TEST_CASE(headerWithNumber){
JPetTreeHeader treeHeader(345);
BOOST_REQUIRE_EQUAL(treeHeader.getRunNumber(), 345 );
}
BOOST_AUTO_TEST_CASE(headerWithStageInfo){
JPetTreeHeader treeHeader;
treeHeader.addStageInfo("name", "myDescription", 3, "time_stamp");
BOOST_REQUIRE_EQUAL(treeHeader.getStagesNb(), 1);
BOOST_REQUIRE_EQUAL(treeHeader.getRunNumber(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getBaseFileName(), "filename not set" );
BOOST_REQUIRE_EQUAL(treeHeader.getSourcePosition(), -1 );
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(0).fModuleName, "name");
BOOST_REQUIRE_EQUAL(treeHeader.getProcessingStageInfo(0).fModuleDescription, "myDescription");
}
BOOST_AUTO_TEST_CASE(simpleTest){
JPetTreeHeader treeHeader;
treeHeader.setBaseFileName("baseFileName");
BOOST_REQUIRE_EQUAL(treeHeader.getBaseFileName(), "baseFileName");
treeHeader.setSourcePosition(2);
BOOST_REQUIRE_EQUAL(treeHeader.getSourcePosition(), 2);
}
BOOST_AUTO_TEST_CASE(headerWithVariable){
JPetTreeHeader treeHeader;
treeHeader.setVariable("name", "value");
BOOST_REQUIRE_EQUAL(treeHeader.getVariable("name"), "value");
BOOST_REQUIRE_EQUAL(treeHeader.getVariable("blank name"), "");
}
BOOST_AUTO_TEST_SUITE_END()
| 43.15625
| 136
| 0.828747
|
Alvarness
|
92819c144d2f05f814acab0151720fdb297a3f01
| 18,098
|
cpp
|
C++
|
source/common/engine/stringtable.cpp
|
Quake-Backup/Raze
|
16c81f0b1f409436ebf576d2c23f2459a29b34b4
|
[
"RSA-MD"
] | 1
|
2022-03-30T15:53:09.000Z
|
2022-03-30T15:53:09.000Z
|
source/common/engine/stringtable.cpp
|
Quake-Backup/Raze
|
16c81f0b1f409436ebf576d2c23f2459a29b34b4
|
[
"RSA-MD"
] | null | null | null |
source/common/engine/stringtable.cpp
|
Quake-Backup/Raze
|
16c81f0b1f409436ebf576d2c23f2459a29b34b4
|
[
"RSA-MD"
] | null | null | null |
/*
** stringtable.cpp
** Implements the FStringTable class
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** 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.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <string.h>
#include "stringtable.h"
#include "cmdlib.h"
#include "filesystem.h"
#include "sc_man.h"
#include "printf.h"
#include "i_interface.h"
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::LoadStrings (const char *language)
{
int lastlump, lump;
lastlump = 0;
while ((lump = fileSystem.FindLump("LMACROS", &lastlump)) != -1)
{
readMacros(lump);
}
lastlump = 0;
while ((lump = fileSystem.FindLump ("LANGUAGE", &lastlump)) != -1)
{
auto lumpdata = fileSystem.GetFileData(lump);
if (!ParseLanguageCSV(lump, lumpdata))
LoadLanguage (lump, lumpdata);
}
UpdateLanguage(language);
allMacros.Clear();
}
//==========================================================================
//
// This was tailored to parse CSV as exported by Google Docs.
//
//==========================================================================
TArray<TArray<FString>> FStringTable::parseCSV(const TArray<uint8_t> &buffer)
{
const size_t bufLength = buffer.Size();
TArray<TArray<FString>> data;
TArray<FString> row;
TArray<char> cell;
bool quoted = false;
/*
auto myisspace = [](int ch) { return ch == '\t' || ch == '\r' || ch == '\n' || ch == ' '; };
while (*vcopy && myisspace((unsigned char)*vcopy)) vcopy++; // skip over leaading whitespace;
auto vend = vcopy + strlen(vcopy);
while (vend > vcopy && myisspace((unsigned char)vend[-1])) *--vend = 0; // skip over trailing whitespace
*/
for (size_t i = 0; i < bufLength; ++i)
{
if (buffer[i] == '"')
{
// Double quotes inside a quoted string count as an escaped quotation mark.
if (quoted && i < bufLength - 1 && buffer[i + 1] == '"')
{
cell.Push('"');
i++;
}
else if (cell.Size() == 0 || quoted)
{
quoted = !quoted;
}
}
else if (buffer[i] == ',')
{
if (!quoted)
{
cell.Push(0);
ProcessEscapes(cell.Data());
row.Push(cell.Data());
cell.Clear();
}
else
{
cell.Push(buffer[i]);
}
}
else if (buffer[i] == '\r')
{
// Ignore all CR's.
}
else if (buffer[i] == '\n' && !quoted)
{
cell.Push(0);
ProcessEscapes(cell.Data());
row.Push(cell.Data());
data.Push(std::move(row));
cell.Clear();
}
else
{
cell.Push(buffer[i]);
}
}
// Handle last line without linebreak
if (cell.Size() > 0 || row.Size() > 0)
{
cell.Push(0);
ProcessEscapes(cell.Data());
row.Push(cell.Data());
data.Push(std::move(row));
}
return data;
}
//==========================================================================
//
//
//
//==========================================================================
bool FStringTable::readMacros(int lumpnum)
{
auto lumpdata = fileSystem.GetFileData(lumpnum);
auto data = parseCSV(lumpdata);
for (unsigned i = 1; i < data.Size(); i++)
{
auto macroname = data[i][0];
auto language = data[i][1];
if (macroname.IsEmpty() || language.IsEmpty()) continue;
FStringf combined_name("%s/%s", language.GetChars(), macroname.GetChars());
FName name = combined_name.GetChars();
StringMacro macro;
for (int k = 0; k < 4; k++)
{
macro.Replacements[k] = data[i][k+2];
}
allMacros.Insert(name, macro);
}
return true;
}
//==========================================================================
//
//
//
//==========================================================================
bool FStringTable::ParseLanguageCSV(int lumpnum, const TArray<uint8_t> &buffer)
{
if (buffer.Size() < 11) return false;
if (strnicmp((const char*)buffer.Data(), "default,", 8) && strnicmp((const char*)buffer.Data(), "identifier,", 11 )) return false;
auto data = parseCSV(buffer);
int labelcol = -1;
int filtercol = -1;
TArray<std::pair<int, unsigned>> langrows;
bool hasDefaultEntry = false;
if (data.Size() > 0)
{
for (unsigned column = 0; column < data[0].Size(); column++)
{
auto &entry = data[0][column];
if (entry.CompareNoCase("filter") == 0)
{
filtercol = column;
}
else if (entry.CompareNoCase("identifier") == 0)
{
labelcol = column;
}
else
{
auto languages = entry.Split(" ", FString::TOK_SKIPEMPTY);
for (auto &lang : languages)
{
if (lang.CompareNoCase("default") == 0)
{
langrows.Push(std::make_pair(column, default_table));
hasDefaultEntry = true;
}
else if (lang.Len() < 4)
{
lang.ToLower();
langrows.Push(std::make_pair(column, MAKE_ID(lang[0], lang[1], lang[2], 0)));
}
}
}
}
for (unsigned i = 1; i < data.Size(); i++)
{
auto &row = data[i];
if (filtercol > -1)
{
auto filterstr = row[filtercol];
if (filterstr.IsNotEmpty())
{
bool ok = false;
if (sysCallbacks.CheckGame)
{
auto filter = filterstr.Split(" ", FString::TOK_SKIPEMPTY);
for (auto& entry : filter)
{
if (sysCallbacks.CheckGame(entry))
{
ok = true;
break;
}
}
}
if (!ok) continue;
}
}
FName strName = row[labelcol].GetChars();
if (hasDefaultEntry)
{
DeleteForLabel(lumpnum, strName);
}
for (auto &langentry : langrows)
{
auto str = row[langentry.first];
if (str.Len() > 0)
{
InsertString(lumpnum, langentry.second, strName, str);
}
else
{
DeleteString(langentry.second, strName);
}
}
}
}
return true;
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::LoadLanguage (int lumpnum, const TArray<uint8_t> &buffer)
{
bool errordone = false;
TArray<uint32_t> activeMaps;
FScanner sc;
bool hasDefaultEntry = false;
sc.OpenMem("LANGUAGE", buffer);
sc.SetCMode (true);
while (sc.GetString ())
{
if (sc.Compare ("["))
{ // Process language identifiers
activeMaps.Clear();
hasDefaultEntry = false;
sc.MustGetString ();
do
{
size_t len = sc.StringLen;
if (len != 2 && len != 3)
{
if (len == 1 && sc.String[0] == '~')
{
// deprecated and ignored
sc.ScriptMessage("Deprecated option '~' found in language list");
sc.MustGetString ();
continue;
}
if (len == 1 && sc.String[0] == '*')
{
activeMaps.Clear();
activeMaps.Push(global_table);
}
else if (len == 7 && stricmp (sc.String, "default") == 0)
{
activeMaps.Clear();
activeMaps.Push(default_table);
hasDefaultEntry = true;
}
else
{
sc.ScriptError ("The language code must be 2 or 3 characters long.\n'%s' is %lu characters long.",
sc.String, len);
}
}
else
{
if (activeMaps.Size() != 1 || (activeMaps[0] != default_table && activeMaps[0] != global_table))
activeMaps.Push(MAKE_ID(tolower(sc.String[0]), tolower(sc.String[1]), tolower(sc.String[2]), 0));
}
sc.MustGetString ();
} while (!sc.Compare ("]"));
}
else
{ // Process string definitions.
if (activeMaps.Size() == 0)
{
// LANGUAGE lump is bad. We need to check if this is an old binary
// lump and if so just skip it to allow old WADs to run which contain
// such a lump.
if (!sc.isText())
{
if (!errordone) Printf("Skipping binary 'LANGUAGE' lump.\n");
errordone = true;
return;
}
sc.ScriptError ("Found a string without a language specified.");
}
bool skip = false;
if (sc.Compare("$"))
{
sc.MustGetStringName("ifgame");
sc.MustGetStringName("(");
sc.MustGetString();
skip |= (!sysCallbacks.CheckGame || !sysCallbacks.CheckGame(sc.String));
sc.MustGetStringName(")");
sc.MustGetString();
}
FName strName (sc.String);
sc.MustGetStringName ("=");
sc.MustGetString ();
FString strText (sc.String, ProcessEscapes (sc.String));
sc.MustGetString ();
while (!sc.Compare (";"))
{
ProcessEscapes (sc.String);
strText += sc.String;
sc.MustGetString ();
}
if (!skip)
{
if (hasDefaultEntry)
{
DeleteForLabel(lumpnum, strName);
}
// Insert the string into all relevant tables.
for (auto map : activeMaps)
{
InsertString(lumpnum, map, strName, strText);
}
}
}
}
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::DeleteString(int langid, FName label)
{
allStrings[langid].Remove(label);
}
//==========================================================================
//
// This deletes all older entries for a given label. This gets called
// when a string in the default table gets updated.
//
//==========================================================================
void FStringTable::DeleteForLabel(int lumpnum, FName label)
{
decltype(allStrings)::Iterator it(allStrings);
decltype(allStrings)::Pair *pair;
auto filenum = fileSystem.GetFileContainer(lumpnum);
while (it.NextPair(pair))
{
auto entry = pair->Value.CheckKey(label);
if (entry && entry->filenum < filenum)
{
pair->Value.Remove(label);
}
}
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::InsertString(int lumpnum, int langid, FName label, const FString &string)
{
const char *strlangid = (const char *)&langid;
TableElement te = { fileSystem.GetFileContainer(lumpnum), { string, string, string, string } };
ptrdiff_t index;
while ((index = te.strings[0].IndexOf("@[")) >= 0)
{
auto endindex = te.strings[0].IndexOf(']', index);
if (endindex == -1)
{
Printf("Bad macro in %s : %s\n", strlangid, label.GetChars());
break;
}
FString macroname(te.strings[0].GetChars() + index + 2, endindex - index - 2);
FStringf lookupstr("%s/%s", strlangid, macroname.GetChars());
FStringf replacee("@[%s]", macroname.GetChars());
FName lookupname(lookupstr.GetChars(), true);
auto replace = allMacros.CheckKey(lookupname);
for (int i = 0; i < 4; i++)
{
const char *replacement = replace? replace->Replacements[i].GetChars() : "";
te.strings[i].Substitute(replacee, replacement);
}
}
allStrings[langid].Insert(label, te);
}
//==========================================================================
//
//
//
//==========================================================================
void FStringTable::UpdateLanguage(const char *language)
{
if (language) activeLanguage = language;
else language = activeLanguage.GetChars();
size_t langlen = strlen(language);
int LanguageID = (langlen < 2 || langlen > 3) ?
MAKE_ID('e', 'n', 'u', '\0') :
MAKE_ID(language[0], language[1], language[2], '\0');
currentLanguageSet.Clear();
auto checkone = [&](uint32_t lang_id)
{
auto list = allStrings.CheckKey(lang_id);
if (list && currentLanguageSet.FindEx([&](const auto &element) { return element.first == lang_id; }) == currentLanguageSet.Size())
currentLanguageSet.Push(std::make_pair(lang_id, list));
};
checkone(override_table);
checkone(global_table);
checkone(LanguageID);
checkone(LanguageID & MAKE_ID(0xff, 0xff, 0, 0));
checkone(default_table);
}
//==========================================================================
//
// Replace \ escape sequences in a string with the escaped characters.
//
//==========================================================================
size_t FStringTable::ProcessEscapes (char *iptr)
{
char *sptr = iptr, *optr = iptr, c;
while ((c = *iptr++) != '\0')
{
if (c == '\\')
{
c = *iptr++;
if (c == 'n')
c = '\n';
else if (c == 'c')
c = TEXTCOLOR_ESCAPE;
else if (c == 'r')
c = '\r';
else if (c == 't')
c = '\t';
else if (c == 'x')
{
c = 0;
for (int i = 0; i < 2; i++)
{
char cc = *iptr++;
if (cc >= '0' && cc <= '9')
c = (c << 4) + cc - '0';
else if (cc >= 'a' && cc <= 'f')
c = (c << 4) + 10 + cc - 'a';
else if (cc >= 'A' && cc <= 'F')
c = (c << 4) + 10 + cc - 'A';
else
{
iptr--;
break;
}
}
if (c == 0) continue;
}
else if (c == '\n')
continue;
}
*optr++ = c;
}
*optr = '\0';
return optr - sptr;
}
//==========================================================================
//
// Checks if the given key exists in any one of the default string tables that are valid for all languages.
// To replace IWAD content this condition must be true.
//
//==========================================================================
bool FStringTable::exists(const char *name)
{
if (name == nullptr || *name == 0)
{
return false;
}
FName nm(name, true);
if (nm != NAME_None)
{
uint32_t defaultStrings[] = { default_table, global_table, override_table };
for (auto mapid : defaultStrings)
{
auto map = allStrings.CheckKey(mapid);
if (map)
{
auto item = map->CheckKey(nm);
if (item) return true;
}
}
}
return false;
}
//==========================================================================
//
// Finds a string by name and returns its value
//
//==========================================================================
const char *FStringTable::GetString(const char *name, uint32_t *langtable, int gender) const
{
if (name == nullptr || *name == 0)
{
return nullptr;
}
if (gender == -1 && sysCallbacks.GetGender) gender = sysCallbacks.GetGender();
if (gender < 0 || gender > 3) gender = 0;
FName nm(name, true);
if (nm != NAME_None)
{
for (auto map : currentLanguageSet)
{
auto item = map.second->CheckKey(nm);
if (item)
{
if (langtable) *langtable = map.first;
auto c = item->strings[gender].GetChars();
if (c && *c == '$' && c[1] == '$')
return GetString(c + 2, langtable, gender);
return c;
}
}
}
return nullptr;
}
//==========================================================================
//
// Finds a string by name in a given language
//
//==========================================================================
const char *FStringTable::GetLanguageString(const char *name, uint32_t langtable, int gender) const
{
if (name == nullptr || *name == 0)
{
return nullptr;
}
if (gender == -1 && sysCallbacks.GetGender) gender = sysCallbacks.GetGender();
if (gender < 0 || gender > 3) gender = 0;
FName nm(name, true);
if (nm != NAME_None)
{
auto map = allStrings.CheckKey(langtable);
if (map == nullptr) return nullptr;
auto item = map->CheckKey(nm);
if (item)
{
return item->strings[gender].GetChars();
}
}
return nullptr;
}
bool FStringTable::MatchDefaultString(const char *name, const char *content) const
{
// This only compares the first line to avoid problems with bad linefeeds. For the few cases where this feature is needed it is sufficient.
auto c = GetLanguageString(name, FStringTable::default_table);
if (!c) return false;
// Check a secondary key, in case the text comparison cannot be done due to needed orthographic fixes (see Harmony's exit text)
FStringf checkkey("%s_CHECK", name);
auto cc = GetLanguageString(checkkey, FStringTable::default_table);
if (cc) c = cc;
return (c && !strnicmp(c, content, strcspn(content, "\n\r\t")));
}
//==========================================================================
//
// Finds a string by name and returns its value. If the string does
// not exist, returns the passed name instead.
//
//==========================================================================
const char *FStringTable::operator() (const char *name) const
{
const char *str = operator[] (name);
return str ? str : name;
}
//==========================================================================
//
// Find a string with the same exact text. Returns its name.
// This does not need to check genders, it is only used by
// Dehacked on the English table for finding stock strings.
//
//==========================================================================
const char *StringMap::MatchString (const char *string) const
{
StringMap::ConstIterator it(*this);
StringMap::ConstPair *pair;
while (it.NextPair(pair))
{
if (pair->Value.strings[0].CompareNoCase(string) == 0)
{
return pair->Key.GetChars();
}
}
return nullptr;
}
FStringTable GStrings;
| 26.191027
| 140
| 0.539728
|
Quake-Backup
|
928294383946e7e2df7d4757bcc7c02cc26b1caf
| 3,323
|
cpp
|
C++
|
src/dropbox/sharing/SharingMountFolderError.cpp
|
slashdotted/dropboxQt
|
63d43fa882cec8fb980a2aab2464a2d7260b8089
|
[
"MIT"
] | 17
|
2016-12-03T09:12:29.000Z
|
2020-06-20T22:08:44.000Z
|
src/dropbox/sharing/SharingMountFolderError.cpp
|
slashdotted/dropboxQt
|
63d43fa882cec8fb980a2aab2464a2d7260b8089
|
[
"MIT"
] | 8
|
2017-01-05T17:50:16.000Z
|
2021-08-06T18:56:29.000Z
|
src/dropbox/sharing/SharingMountFolderError.cpp
|
slashdotted/dropboxQt
|
63d43fa882cec8fb980a2aab2464a2d7260b8089
|
[
"MIT"
] | 8
|
2017-09-13T17:28:40.000Z
|
2020-07-27T00:41:44.000Z
|
/**********************************************************
DO NOT EDIT
This file was generated from stone specification "sharing"
Part of "Ardi - the organizer" project.
osoft4ardi@gmail.com
www.prokarpaty.net
***********************************************************/
#include "dropbox/sharing/SharingMountFolderError.h"
namespace dropboxQt{
namespace sharing{
///MountFolderError
MountFolderError::operator QJsonObject()const{
QJsonObject js;
this->toJson(js, "");
return js;
}
void MountFolderError::toJson(QJsonObject& js, QString name)const{
switch(m_tag){
case MountFolderError_ACCESS_ERROR:{
if(!name.isEmpty())
js[name] = QString("access_error");
m_access_error.toJson(js, "access_error");
}break;
case MountFolderError_INSIDE_SHARED_FOLDER:{
if(!name.isEmpty())
js[name] = QString("inside_shared_folder");
}break;
case MountFolderError_INSUFFICIENT_QUOTA:{
if(!name.isEmpty())
js[name] = QString("insufficient_quota");
js["insufficient_quota"] = (QJsonObject)m_insufficient_quota;
}break;
case MountFolderError_ALREADY_MOUNTED:{
if(!name.isEmpty())
js[name] = QString("already_mounted");
}break;
case MountFolderError_NO_PERMISSION:{
if(!name.isEmpty())
js[name] = QString("no_permission");
}break;
case MountFolderError_NOT_MOUNTABLE:{
if(!name.isEmpty())
js[name] = QString("not_mountable");
}break;
case MountFolderError_OTHER:{
if(!name.isEmpty())
js[name] = QString("other");
}break;
}//switch
}
void MountFolderError::fromJson(const QJsonObject& js){
QString s = js[".tag"].toString();
if(s.compare("access_error") == 0){
m_tag = MountFolderError_ACCESS_ERROR;
m_access_error.fromJson(js["access_error"].toObject());
}
else if(s.compare("inside_shared_folder") == 0){
m_tag = MountFolderError_INSIDE_SHARED_FOLDER;
}
else if(s.compare("insufficient_quota") == 0){
m_tag = MountFolderError_INSUFFICIENT_QUOTA;
m_insufficient_quota.fromJson(js["insufficient_quota"].toObject());
}
else if(s.compare("already_mounted") == 0){
m_tag = MountFolderError_ALREADY_MOUNTED;
}
else if(s.compare("no_permission") == 0){
m_tag = MountFolderError_NO_PERMISSION;
}
else if(s.compare("not_mountable") == 0){
m_tag = MountFolderError_NOT_MOUNTABLE;
}
else if(s.compare("other") == 0){
m_tag = MountFolderError_OTHER;
}
}
QString MountFolderError::toString(bool multiline)const
{
QJsonObject js;
toJson(js, "MountFolderError");
QJsonDocument doc(js);
QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact));
return s;
}
std::unique_ptr<MountFolderError> MountFolderError::factory::create(const QByteArray& data)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject js = doc.object();
std::unique_ptr<MountFolderError> rv = std::unique_ptr<MountFolderError>(new MountFolderError);
rv->fromJson(js);
return rv;
}
}//sharing
}//dropboxQt
| 29.669643
| 99
| 0.616611
|
slashdotted
|
9286be102837112c957c8b89fb5642cf1d8e72e7
| 3,631
|
h++
|
C++
|
css/grammar/position.h++
|
rubenvb/skui
|
5bda2d73232eb7a763ba9d788c7603298767a7d7
|
[
"MIT"
] | 19
|
2016-10-13T22:44:31.000Z
|
2021-12-28T20:28:15.000Z
|
css/grammar/position.h++
|
rubenvb/skui
|
5bda2d73232eb7a763ba9d788c7603298767a7d7
|
[
"MIT"
] | 1
|
2021-05-16T15:15:22.000Z
|
2021-05-16T17:01:26.000Z
|
css/grammar/position.h++
|
rubenvb/skui
|
5bda2d73232eb7a763ba9d788c7603298767a7d7
|
[
"MIT"
] | 4
|
2017-03-07T05:37:02.000Z
|
2018-06-05T03:14:48.000Z
|
/**
* The MIT License (MIT)
*
* Copyright © 2019 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#ifndef SKUI_CSS_GRAMMAR_POSITION_H
#define SKUI_CSS_GRAMMAR_POSITION_H
#include "css/length.h++"
#include "css/position.h++"
#include "css/grammar/as.h++"
#include "css/grammar/length.h++"
#include <core/debug.h++>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/adapted/struct.hpp>
#include <boost/fusion/adapted/struct/adapt_struct_named.hpp>
BOOST_FUSION_ADAPT_STRUCT(skui::css::position,
x,
y)
BOOST_FUSION_ADAPT_STRUCT(skui::css::length_with_offset,
value,
offset)
namespace skui::css::grammar
{
namespace x3 = boost::spirit::x3;
constexpr auto swap_x_y = [](auto& context)
{
css::position& position = x3::_attr(context);
std::swap(position.x, position.y);
};
struct horizontal_relative_position_table : x3::symbols<css::length>
{
horizontal_relative_position_table();
} const horizontal_relative_position;
struct vertical_relative_position_table : x3::symbols<css::length>
{
vertical_relative_position_table();
} const vertical_relative_position;
const auto horizontal_position = x3::rule<struct horizontal_position, css::length_with_offset>{"horizontal_position"}
= horizontal_relative_position >> -length_percentage
| x3::lit('0') >> x3::attr(css::length{}) >> x3::attr(css::length{})
| length_percentage >> x3::attr(css::length{})
;
const auto vertical_position = x3::rule<struct vertical_position, css::length_with_offset>{"vertical_position"}
= vertical_relative_position >> -length_percentage
| x3::lit('0') >> x3::attr(css::length{}) >> x3::attr(css::length{})
| length_percentage >> x3::attr(css::length{})
;
//| vertical_relative_position
const auto position = x3::rule<struct position_, css::position>{"position"}
%= horizontal_position >> vertical_position
| (vertical_position >> horizontal_position)[swap_x_y]
| horizontal_position >> x3::attr(css::length_with_offset{{50, unit::percentage}, {}})
| (vertical_position >> x3::attr(css::length_with_offset{{50, unit::percentage}, {}}))[swap_x_y]
;
}
#endif
| 41.261364
| 119
| 0.645001
|
rubenvb
|
9287a02a7a544d3aaeafe4518ec15a307887a178
| 6,347
|
cpp
|
C++
|
app/parse_kml.cpp
|
JaviBonilla/SolarPILOT
|
c535313484018597e8029202e764ec8e834839a5
|
[
"MIT"
] | 26
|
2018-03-21T17:26:44.000Z
|
2022-02-07T05:55:47.000Z
|
app/parse_kml.cpp
|
JaviBonilla/SolarPILOT
|
c535313484018597e8029202e764ec8e834839a5
|
[
"MIT"
] | 38
|
2018-03-09T17:54:49.000Z
|
2022-01-28T16:28:29.000Z
|
app/parse_kml.cpp
|
JaviBonilla/SolarPILOT
|
c535313484018597e8029202e764ec8e834839a5
|
[
"MIT"
] | 11
|
2018-03-17T09:36:51.000Z
|
2022-02-02T10:13:47.000Z
|
/*******************************************************************************************************
* Copyright 2018 Alliance for Sustainable Energy, LLC
*
* NOTICE: This software was developed at least in part by Alliance for Sustainable Energy, LLC
* ("Alliance") under Contract No. DE-AC36-08GO28308 with the U.S. Department of Energy and the U.S.
* The Government retains for itself and others acting on its behalf a nonexclusive, paid-up,
* irrevocable worldwide license in the software to reproduce, prepare derivative works, distribute
* copies to the public, perform publicly and display publicly, and to permit others to do so.
*
* 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, the above government
* rights notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, the above government
* rights notice, this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. The entire corresponding source code of any redistribution, with or without modification, by a
* research entity, including but not limited to any contracting manager/operator of a United States
* National Laboratory, any institution of higher learning, and any non-profit organization, must be
* made publicly available under this license for as long as the redistribution is made available by
* the research entity.
*
* 4. Redistribution of this software, without modification, must refer to the software by the same
* designation. Redistribution of a modified version of this software (i) may not refer to the modified
* version by the same designation, or by any confusingly similar designation, and (ii) must refer to
* the underlying software originally provided by Alliance as "Solar Power tower Integrated Layout and
* Optimization Tool" or "SolarPILOT". Except to comply with the foregoing, the terms "Solar Power
* tower Integrated Layout and Optimization Tool", "SolarPILOT", or any confusingly similar
* designation may not be used to refer to any modified version of this software or any modified
* version of the underlying software originally provided by Alliance without the prior written consent
* of Alliance.
*
* 5. The name of the copyright holder, contributors, the United States Government, the United States
* Department of Energy, or any of their employees may not 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 HOLDER,
* CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR
* EMPLOYEES, 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.
*******************************************************************************************************/
/*
Library for parsing KML files (Google Earth format), based on XML.
code.google.com/p/libkml/
https://developers.google.com/kml/documentation/kmlreference
*/
#include "parse_kml.h"
#include <wx/string.h>
#include <rapidxml.hpp>
#include "gui_util.h"
using namespace rapidxml;
void ParseKML(wxString &file, double &tower_lat, double &tower_lon, std::vector<sp_point> &poly)
{
/*
Parse the KML polygon and create a formatted polygon to be used by the bounds grid.
The format for the bounds grid is:
[POLY][P]x1,y1,z1[P]x2,y2,z2...
The "poly" vector is NOT CLEARED by this method. Be sure to clear it before calling, if needed.
*/
//We have to copy the file onto the heap as a char* since the xml parser points to permanent
//memory locations. The wxString buffers are temporary.
char *fstr = new char[file.size()+1];
strncpy(fstr, (const char*)file.mb_str(), file.size());
fstr[file.size()] = 0; //Null terminator
xml_document<> doc;
doc.parse<0>(fstr);
xml_node<> *node = doc.first_node()->first_node("Document")->first_node("Placemark");
double
tlatr = tower_lat*D2R,
tlonr = tower_lon*D2R,
r_earth = 6371009.; //Radius of the earth in meters
while(node != 0)
{
wxString coords = (std::string)node->
first_node("Polygon")->
first_node("outerBoundaryIs")->
first_node("LinearRing")->
first_node("coordinates")->value();
coords.Trim(false); //Remove leading tabs and newlines
coords.Trim(); //Remove trailing junk
//Construct the polygon
std::vector<std::string> pp = split(coords.ToStdString(), " ");
for(unsigned int i=0; i<pp.size(); i++)
{
//Convert point values into doubles
std::vector<std::string> ps = split(pp.at(i),",");
double
plat, plon;
to_double(ps.at(1), &plat);
to_double(ps.at(0), &plon);
plat *= D2R;
plon *= D2R;
//Convert degrees into meters
double dist = r_earth*acos( sin(tlatr)*sin(plat) + cos(tlatr)*cos(plat)*cos(tlonr - plon) );
double dy = (plat < tlatr ? -1. : 1.)*r_earth*acos( sin(tlatr)*sin(plat) + cos(tlatr)*cos(plat) );
double dx = (plon < tlonr ? -1. : 1.)*sqrt( pow(dist, 2) - pow(dy, 2) );
poly.push_back(sp_point(dx, dy, 0.));
}
//Update to the new sibling node
node = node->next_sibling();
}
delete [] fstr;
}
| 46.328467
| 110
| 0.676067
|
JaviBonilla
|
92881cb14b49dc3defa4400678c987491d0cbee3
| 714
|
cpp
|
C++
|
lucas/tep/2019-1/Contest4/f.cpp
|
medeiroslucas/lo-and-behold-pp
|
d2be16f9b108b501fd9fccf173e741c93350cee4
|
[
"MIT"
] | 2
|
2019-09-09T00:34:40.000Z
|
2019-09-09T17:35:19.000Z
|
lucas/tep/2019-1/Contest4/f.cpp
|
medeiroslucas/lo-and-behold-pp
|
d2be16f9b108b501fd9fccf173e741c93350cee4
|
[
"MIT"
] | null | null | null |
lucas/tep/2019-1/Contest4/f.cpp
|
medeiroslucas/lo-and-behold-pp
|
d2be16f9b108b501fd9fccf173e741c93350cee4
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const double oo = 100000000;
int main(){
int N;
double max=-oo, min=oo, area;
pair<double, double> p, pontos;
cin >> N >> p.first >> p.second;
while(N--){
cin >> pontos.first >> pontos.second;
if(hypot(p.first - pontos.first, p.second - pontos.second) > max){
max = hypot(p.first - pontos.first, p.second - pontos.second);
}
if(hypot(p.first - pontos.first, p.second - pontos.second) < min){
min = hypot(p.first - pontos.first, p.second - pontos.second);
}
}
area = PI*(max*max - min*min);
printf("%.10lf\n", area);
return 0;
}
| 21
| 74
| 0.556022
|
medeiroslucas
|
928946ea867daf7caf6944d0c51edfee2527dd3b
| 1,712
|
cpp
|
C++
|
Tries/Tries_Creation.cpp
|
susantabiswas/placementPrep
|
22a7574206ddc63eba89517f7b68a3d2f4d467f5
|
[
"MIT"
] | 19
|
2018-12-02T05:59:44.000Z
|
2021-07-24T14:11:54.000Z
|
Tries/Tries_Creation.cpp
|
susantabiswas/placementPrep
|
22a7574206ddc63eba89517f7b68a3d2f4d467f5
|
[
"MIT"
] | null | null | null |
Tries/Tries_Creation.cpp
|
susantabiswas/placementPrep
|
22a7574206ddc63eba89517f7b68a3d2f4d467f5
|
[
"MIT"
] | 13
|
2019-04-25T16:20:00.000Z
|
2021-09-06T19:50:04.000Z
|
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
//trie structure
struct TrieNode
{
struct TrieNode* child[26];
bool is_str_end;
};
//to create a trieNode type node
struct TrieNode* createNode()
{
struct TrieNode *t=new struct TrieNode;
if(t)
{
t->is_str_end=false;
for (int i = 0; i < 26; ++i)
{
t->child[i]=NULL;
}
return t;
}
else
return NULL;
}
//to insert a new character in the Trie ,if it is already present then ignore and
//keep on traversing else insert the key
void InsertNode(struct TrieNode *root,string word)
{
int index; //for storing the index of the character in a-z
struct TrieNode *t=root;
for(int i=0;i<word.length();i++)
{
index=word[i]-'a';
if(t->child[index]==NULL)
t->child[index]=createNode();
t=t->child[index];
}
//when finally the string end
t->is_str_end=true;
}
//searches the string in the Trie
bool searchString(struct TrieNode *root,string word)
{
int index;
struct TrieNode *t=root;
for (int i = 0; i <word.length(); ++i)
{
index=word[i]-'a';
if(t->child[index]==NULL)
{
return false;
}
t=t->child[index];
}
if(t!=NULL && t->is_str_end==true)
return true;
}
int main()
{
// Input keys (use only 'a' through 'z' and lower case)
string word[8] = {"the", "a", "there", "answer", "any",
"by", "bye", "their"};
struct TrieNode *root = createNode();
// Construct trie
for (int i = 0; i < sizeof(word)/sizeof(string); i++)
InsertNode(root, word[0]);
// Search for different keys
cout<<"them:"<<searchString(root,"thek")<<endl;
return 0;
}
| 19.906977
| 81
| 0.595794
|
susantabiswas
|
928a1b8acf955a585769bd23c02264da1badaafa
| 11,662
|
cpp
|
C++
|
redgpu_memory_allocator_functions.cpp
|
procedural/redgpu_memory_allocator_dma
|
4eedd04b9983cde624e91dd1ec4294ac2de73697
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
redgpu_memory_allocator_functions.cpp
|
procedural/redgpu_memory_allocator_dma
|
4eedd04b9983cde624e91dd1ec4294ac2de73697
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
redgpu_memory_allocator_functions.cpp
|
procedural/redgpu_memory_allocator_dma
|
4eedd04b9983cde624e91dd1ec4294ac2de73697
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
#include "redgpu_memory_allocator_functions.h"
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetPhysicalDeviceProperties2(RedContext context, unsigned gpuIndex, VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2 * pProperties) {
// NOTE(Constantine): Hardcoded for memorymanagement_vk.cpp:292
VkPhysicalDeviceMaintenance3Properties * maintenance3 = (VkPhysicalDeviceMaintenance3Properties *)pProperties->pNext;
maintenance3->maxMemoryAllocationSize = context->gpus[gpuIndex].maxMemoryAllocateBytesCount;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetPhysicalDeviceMemoryProperties(RedContext context, unsigned gpuIndex, VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties * pMemoryProperties) {
VkPhysicalDeviceMemoryProperties properties = {};
properties.memoryTypeCount = context->gpus[gpuIndex].memoryTypesCount;
properties.memoryHeapCount = context->gpus[gpuIndex].memoryHeapsCount;
for (unsigned i = 0; i < context->gpus[gpuIndex].memoryTypesCount; i += 1) {
RedMemoryType memoryType = context->gpus[gpuIndex].memoryTypes[i];
properties.memoryTypes[i].heapIndex = memoryType.memoryHeapIndex;
if (memoryType.isGpuVram == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
}
if (memoryType.isCpuMappable == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
}
if (memoryType.isCpuCoherent == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
}
if (memoryType.isCpuCached == 1) {
properties.memoryTypes[i].propertyFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
}
}
for (unsigned i = 0; i < context->gpus[gpuIndex].memoryHeapsCount; i += 1) {
RedMemoryHeap memoryHeap = context->gpus[gpuIndex].memoryHeaps[i];
properties.memoryHeaps[i].size = memoryHeap.memoryBytesCount;
if (memoryHeap.isGpuVram == 1) {
properties.memoryHeaps[i].flags |= VK_MEMORY_HEAP_DEVICE_LOCAL_BIT;
}
}
pMemoryProperties[0] = properties;
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkAllocateMemory(RedContext context, unsigned gpuIndex, VkDevice device, const VkMemoryAllocateInfo * pAllocateInfo, const VkAllocationCallbacks * pAllocator, VkDeviceMemory * pMemory, const char * name) {
RedStatuses statuses = {};
if (context->gpus[gpuIndex].memoryTypes[pAllocateInfo->memoryTypeIndex].isCpuMappable == 1) {
// NOTE(Constantine): Pass array from DMA to RMA in future.
RedHandleArray array = 0;
redMemoryAllocateMappable(context, (RedHandleGpu)device, name, 0, array, pAllocateInfo->allocationSize, pAllocateInfo->memoryTypeIndex, 0, (RedHandleMemory *)pMemory, &statuses, 0, 0, 0);
} else {
redMemoryAllocate(context, (RedHandleGpu)device, name, pAllocateInfo->allocationSize, pAllocateInfo->memoryTypeIndex, 0, 0, 0, (RedHandleMemory *)pMemory, &statuses, 0, 0, 0);
}
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkFreeMemory(RedContext context, unsigned gpuIndex, VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks * pAllocator) {
redMemoryFree(context, (RedHandleGpu)device, (RedHandleMemory)memory, 0, 0, 0);
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkMapMemory(RedContext context, unsigned gpuIndex, VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, VkMemoryMapFlags flags, void ** ppData) {
RedStatuses statuses = {};
redMemoryMap(context, (RedHandleGpu)device, (RedHandleMemory)memory, offset, size, ppData, &statuses, 0, 0, 0);
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkUnmapMemory(RedContext context, unsigned gpuIndex, VkDevice device, VkDeviceMemory memory) {
redMemoryUnmap(context, (RedHandleGpu)device, (RedHandleMemory)memory, 0, 0, 0);
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkBindBufferMemory2(RedContext context, unsigned gpuIndex, VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfo * pBindInfos) {
RedStatuses statuses = {};
redMemorySet(context, (RedHandleGpu)device, bindInfoCount, (const RedMemoryArray *)pBindInfos, 0, 0, &statuses, 0, 0, 0);
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkBindImageMemory2(RedContext context, unsigned gpuIndex, VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo * pBindInfos) {
RedStatuses statuses = {};
redMemorySet(context, (RedHandleGpu)device, 0, 0, bindInfoCount, (const RedMemoryImage *)pBindInfos, &statuses, 0, 0, 0);
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetBufferMemoryRequirements2(RedContext context, unsigned gpuIndex, VkDevice device, const RedVkBuffer * pInfo, VkMemoryRequirements2 * pMemoryRequirements) {
pMemoryRequirements->memoryRequirements.size = pInfo->memoryBytesCount;
pMemoryRequirements->memoryRequirements.alignment = pInfo->memoryBytesAlignment;
pMemoryRequirements->memoryRequirements.memoryTypeBits = pInfo->memoryTypesSupported;
// NOTE(Constantine): Explicitly ignoring VkMemoryDedicatedRequirements in pMemoryRequirements->pNext.
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkGetImageMemoryRequirements2(RedContext context, unsigned gpuIndex, VkDevice device, const RedVkImage * pInfo, VkMemoryRequirements2 * pMemoryRequirements) {
pMemoryRequirements->memoryRequirements.size = pInfo->memoryBytesCount;
pMemoryRequirements->memoryRequirements.alignment = pInfo->memoryBytesAlignment;
pMemoryRequirements->memoryRequirements.memoryTypeBits = pInfo->memoryTypesSupported;
// NOTE(Constantine): Explicitly ignoring VkMemoryDedicatedRequirements in pMemoryRequirements->pNext.
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkCreateBuffer(RedContext context, unsigned gpuIndex, VkDevice device, const VkBufferCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, RedVkBuffer * pBuffer) {
RedStatuses statuses = {};
// NOTE(Constantine): Pass structuredBufferElementBytesCount from DMA to RMA in future.
uint64_t structuredBufferElementBytesCount = 0;
// NOTE(Constantine): Pass initialAccess from DMA to RMA in future.
RedAccessBitflags initialAccess = 0;
RedArray array = {};
redCreateArray(context, (RedHandleGpu)device, "REDGPU Memory Allocator DMA", (RedArrayType)pCreateInfo->usage, pCreateInfo->size, structuredBufferElementBytesCount, initialAccess, (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT || pCreateInfo->queueFamilyIndexCount == 0) ? -1 : pCreateInfo->pQueueFamilyIndices[0], 0, &array, &statuses, 0, 0, 0);
RedVkBuffer * anArray = (RedVkBuffer *)&array;
pBuffer[0] = anArray[0];
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkDestroyBuffer(RedContext context, unsigned gpuIndex, VkDevice device, VkBuffer buffer, const VkAllocationCallbacks * pAllocator) {
redDestroyArray(context, (RedHandleGpu)device, (RedHandleArray)buffer, 0, 0, 0);
}
REDGPU_DECLSPEC VkResult REDGPU_API rmaDmaVkCreateImage(RedContext context, unsigned gpuIndex, VkDevice device, const VkImageCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, RedVkImage * pImage) {
RedStatuses statuses = {};
RedImageDimensions imageDimensions = RED_IMAGE_DIMENSIONS_2D;
if (pCreateInfo->imageType == VK_IMAGE_TYPE_1D) {
imageDimensions = RED_IMAGE_DIMENSIONS_1D;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_2D && ((pCreateInfo->flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) == VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT)) {
imageDimensions = RED_IMAGE_DIMENSIONS_2D_WITH_TEXTURE_DIMENSIONS_CUBE_AND_CUBE_LAYERED;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_2D) {
imageDimensions = RED_IMAGE_DIMENSIONS_2D;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_3D && ((pCreateInfo->flags & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT) == VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT)) {
imageDimensions = RED_IMAGE_DIMENSIONS_3D_WITH_TEXTURE_DIMENSIONS_2D_AND_2D_LAYERED;
} else if (pCreateInfo->imageType == VK_IMAGE_TYPE_3D) {
imageDimensions = RED_IMAGE_DIMENSIONS_3D;
}
RedAccessBitflags restrictToAccess = 0;
if ((pCreateInfo->usage & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) == VK_IMAGE_USAGE_TRANSFER_SRC_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_COPY_R;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT) == VK_IMAGE_USAGE_TRANSFER_DST_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_COPY_W;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_SAMPLED_BIT) == VK_IMAGE_USAGE_SAMPLED_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_STRUCT_RESOURCE_NON_FRAGMENT_STAGE_R | RED_ACCESS_BITFLAG_STRUCT_RESOURCE_FRAGMENT_STAGE_R;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT) == VK_IMAGE_USAGE_STORAGE_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_STRUCT_RESOURCE_W;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) == VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_OUTPUT_COLOR_W;
}
if ((pCreateInfo->usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) == VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
restrictToAccess |= RED_ACCESS_BITFLAG_OUTPUT_DEPTH_RW;
if ((RedFormat)pCreateInfo->format == RED_FORMAT_DEPTH_24_UINT_TO_FLOAT_0_1_STENCIL_8_UINT ||
(RedFormat)pCreateInfo->format == RED_FORMAT_DEPTH_32_FLOAT_STENCIL_8_UINT)
{
restrictToAccess |= RED_ACCESS_BITFLAG_OUTPUT_STENCIL_RW;
}
}
// NOTE(Constantine): Pass initialAccess from DMA to RMA in future.
RedAccessBitflags initialAccess = 0;
RedImage image = {};
redCreateImage(context, (RedHandleGpu)device, "REDGPU Memory Allocator DMA", imageDimensions, (RedFormat)pCreateInfo->format, pCreateInfo->extent.width, pCreateInfo->extent.height, pCreateInfo->extent.depth, pCreateInfo->mipLevels, pCreateInfo->arrayLayers, (RedMultisampleCountBitflag)pCreateInfo->samples, restrictToAccess, initialAccess, (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT || pCreateInfo->queueFamilyIndexCount == 0) ? -1 : pCreateInfo->pQueueFamilyIndices[0], 0, &image, &statuses, 0, 0, 0);
RedVkImage * anImage = (RedVkImage *)ℑ
pImage[0] = anImage[0];
return (VkResult)statuses.statusError;
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkDestroyImage(RedContext context, unsigned gpuIndex, VkDevice device, VkImage image, const VkAllocationCallbacks * pAllocator) {
redDestroyImage(context, (RedHandleGpu)device, (RedHandleImage)image, 0, 0, 0);
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkCmdInsertDebugUtilsLabelEXT(RedContext context, unsigned gpuIndex, VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT * pLabelInfo) {
RedCallProceduresAndAddresses callPAs;
redGetCallProceduresAndAddresses(context, context->gpus[gpuIndex].gpu, &callPAs, 0, 0, 0, 0);
redCallMark(callPAs.redCallMark, (RedHandleCalls)commandBuffer, pLabelInfo->pLabelName);
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkCmdBeginDebugUtilsLabelEXT(RedContext context, unsigned gpuIndex, VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT * pLabelInfo) {
RedCallProceduresAndAddresses callPAs;
redGetCallProceduresAndAddresses(context, context->gpus[gpuIndex].gpu, &callPAs, 0, 0, 0, 0);
redCallMarkSet(callPAs.redCallMarkSet, (RedHandleCalls)commandBuffer, pLabelInfo->pLabelName);
}
REDGPU_DECLSPEC void REDGPU_API rmaDmaVkCmdEndDebugUtilsLabelEXT(RedContext context, unsigned gpuIndex, VkCommandBuffer commandBuffer) {
RedCallProceduresAndAddresses callPAs;
redGetCallProceduresAndAddresses(context, context->gpus[gpuIndex].gpu, &callPAs, 0, 0, 0, 0);
redCallMarkEnd(callPAs.redCallMarkEnd, (RedHandleCalls)commandBuffer);
}
| 66.261364
| 518
| 0.799005
|
procedural
|
928af9ec5d4404c56d6ddffcaa048fc46f6a94ab
| 1,347
|
cpp
|
C++
|
src/server/db/db.cpp
|
ETinyfish/TEST
|
255014beb178878d8b0a466e0fd61fc26c1d8445
|
[
"MIT"
] | null | null | null |
src/server/db/db.cpp
|
ETinyfish/TEST
|
255014beb178878d8b0a466e0fd61fc26c1d8445
|
[
"MIT"
] | null | null | null |
src/server/db/db.cpp
|
ETinyfish/TEST
|
255014beb178878d8b0a466e0fd61fc26c1d8445
|
[
"MIT"
] | 1
|
2021-06-30T05:55:32.000Z
|
2021-06-30T05:55:32.000Z
|
#include "db.h"
#include <muduo/base/Logging.h>
// 数据库配置信息
static string server = "127.0.0.1";
static string user = "root";
static string password = "123";
static string dbname = "chat_server";
// 初始化数据库连接
MySQL::MySQL()
{
_conn = mysql_init(nullptr);
}
// 释放数据库连接资源
MySQL::~MySQL()
{
if (_conn != nullptr)
mysql_close(_conn);
}
// 连接数据库
bool MySQL::connect()
{
MYSQL *p = mysql_real_connect(_conn, server.c_str(), user.c_str(),
password.c_str(), dbname.c_str(), 3306, nullptr, 0);
if (p != nullptr)
{
// C和C++代码默认的编码字符是ASCII,如果不设置,从MySQL上拉下来的中文显示?
mysql_query(_conn, "set names gbk");
LOG_INFO << "connect mysql success!";
}
else
{
LOG_INFO << "connect mysql fail!";
}
return p;
}
// 更新操作
bool MySQL::update(string sql)
{
if (mysql_query(_conn, sql.c_str()))
{
LOG_INFO << __FILE__ << ":" << __LINE__ << ":"
<< sql << "更新失败!";
return false;
}
return true;
}
// 查询操作
MYSQL_RES *MySQL::query(string sql)
{
if (mysql_query(_conn, sql.c_str()))
{
LOG_INFO << __FILE__ << ":" << __LINE__ << ":"
<< sql << "查询失败!";
return nullptr;
}
return mysql_use_result(_conn);
}
// 获取连接
MYSQL* MySQL::getConnection()
{
return _conn;
}
| 18.708333
| 86
| 0.550854
|
ETinyfish
|
928e626c06d50a9f27688bf16d0ef3c097dd3c35
| 3,912
|
hpp
|
C++
|
src/dtl/bitmap/util/buffer.hpp
|
harald-lang/tree-encoded-bitmaps
|
a4ab056f2cefa7843b27c736833b08977b56649c
|
[
"Apache-2.0"
] | 29
|
2020-06-18T12:51:42.000Z
|
2022-02-22T07:38:24.000Z
|
src/dtl/bitmap/util/buffer.hpp
|
marcellus-saputra/Thuja
|
8443320a6d0e9a20bb6b665f0befc6988978cafd
|
[
"Apache-2.0"
] | null | null | null |
src/dtl/bitmap/util/buffer.hpp
|
marcellus-saputra/Thuja
|
8443320a6d0e9a20bb6b665f0befc6988978cafd
|
[
"Apache-2.0"
] | 2
|
2021-04-07T13:43:34.000Z
|
2021-06-09T04:49:39.000Z
|
#pragma once
//===----------------------------------------------------------------------===//
#include <dtl/dtl.hpp>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <type_traits>
//===----------------------------------------------------------------------===//
namespace dtl {
//===----------------------------------------------------------------------===//
/// A simple memory buffer which allows allocations without initialization.
template<
typename _word_type,
typename _alloc = std::allocator<_word_type>>
class buffer {
using word_type = _word_type;
static constexpr std::size_t word_bitlength = sizeof(word_type) * 8;
static constexpr uintptr_t cache_line_size = 64; // bytes
static constexpr auto elements_per_cache_line =
cache_line_size / sizeof(word_type);
/// The number of elements.
std::size_t size_;
/// Pointer to the buffer.
word_type* ptr_;
/// Cache line aligned pointer to the buffer.
word_type* aligned_ptr_;
/// The allocator.
_alloc allocator_;
static inline word_type*
get_aligned_ptr(word_type* ptr) {
const uintptr_t adjust_by =
(reinterpret_cast<uintptr_t>(ptr) % cache_line_size) == 0
? 0
: cache_line_size - (reinterpret_cast<uintptr_t>(ptr) % cache_line_size);
auto p = reinterpret_cast<word_type*>(
reinterpret_cast<uintptr_t>(ptr) + adjust_by);
return reinterpret_cast<word_type*>(
__builtin_assume_aligned(p, cache_line_size));
}
inline void
do_allocate() {
ptr_ = allocator_.allocate(size_ + elements_per_cache_line);
aligned_ptr_ = get_aligned_ptr(ptr_);
}
inline void
do_deallocate() {
if (ptr_ != nullptr) {
allocator_.deallocate(ptr_, size_ + elements_per_cache_line);
}
}
public:
/// C'tor
explicit buffer(std::size_t size, u1 init = true, const _alloc& alloc = _alloc())
: size_(size), ptr_(nullptr), allocator_(alloc) {
do_allocate();
if (init) {
std::memset(aligned_ptr_, 0, size_ * sizeof(word_type));
}
}
buffer(const buffer& other)
: size_(other.size_), ptr_(nullptr), aligned_ptr_(nullptr),
allocator_(other.allocator_) {
do_allocate();
std::memcpy(aligned_ptr_, other.aligned_ptr_, size_ * sizeof(word_type));
}
buffer(buffer&& other) noexcept
: size_(other.size_), ptr_(other.ptr_), aligned_ptr_(other.aligned_ptr_),
allocator_(std::move(other.allocator_)) {
other.ptr_ = nullptr;
other.aligned_ptr_ = nullptr;
}
buffer& operator=(const buffer& other) {
assert(ptr_ != other.ptr_);
if (size_ == other.size_) {
std::memcpy(aligned_ptr_, other.aligned_ptr_, size_ * sizeof(word_type));
}
else {
do_deallocate();
size_ = other.size_;
allocator_ = other.allocator_;
do_allocate();
std::memcpy(aligned_ptr_, other.aligned_ptr_, size_ * sizeof(word_type));
}
return *this;
}
buffer& operator=(buffer&& other) noexcept {
if (this != &other) {
do_deallocate();
size_ = other.size_;
allocator_ = std::move(other.allocator_);
ptr_ = other.ptr_;
aligned_ptr_ = other.aligned_ptr_;
other.ptr_ = nullptr;
other.aligned_ptr_ = nullptr;
}
return *this;
}
~buffer() noexcept {
do_deallocate();
}
inline std::size_t
size() const noexcept {
return size_;
}
/// Return a pointer to the buffer.
inline word_type*
data() noexcept {
return reinterpret_cast<word_type*>(
__builtin_assume_aligned(aligned_ptr_, cache_line_size));
}
/// Return a const pointer to the buffer.
inline const word_type*
data() const noexcept {
return reinterpret_cast<const word_type*>(
__builtin_assume_aligned(aligned_ptr_, cache_line_size));
}
};
//===----------------------------------------------------------------------===//
} // namespace dtl
| 28.764706
| 83
| 0.615798
|
harald-lang
|
928f19d3da027bd21bfeaa4efcc8f7acc0190ac1
| 4,032
|
cc
|
C++
|
cmd/pyxisd/main.cc
|
eLong-INF/pyxis
|
304820eb72bd62d3c211c3423f62dc87b535bb3c
|
[
"BSD-3-Clause"
] | 9
|
2016-07-21T01:45:17.000Z
|
2016-08-26T03:20:25.000Z
|
cmd/pyxisd/main.cc
|
eLong-opensource/pyxis
|
304820eb72bd62d3c211c3423f62dc87b535bb3c
|
[
"BSD-3-Clause"
] | null | null | null |
cmd/pyxisd/main.cc
|
eLong-opensource/pyxis
|
304820eb72bd62d3c211c3423f62dc87b535bb3c
|
[
"BSD-3-Clause"
] | null | null | null |
#include <pyxis/server/server.h>
#include <pyxis/rpc/server.h>
#include <pyxis/server/fake_raft.h>
#include <sofa/pbrpc/pbrpc.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/inspect/Inspector.h>
#include <raft/core/transporter/sofarpc.h>
#include <raft/core/server.h>
#include <toft/base/string/algorithm.h>
#include <toft/base/binary_version.h>
#include <boost/scoped_ptr.hpp>
DEFINE_string(pyxis_list, "", "address list of pyxis servers(host1:port1,host2:port2)");
DEFINE_string(pyxis_listen_addr, "0.0.0.0:7000", "pyxis listen address");
DEFINE_string(raft_listen_addr, "0.0.0.0:7001", "raft listen address");
DEFINE_int32(pprof, 9982, "port of pprof");
DEFINE_string(dbdir, "db", "leveldb dir");
DEFINE_int32(session_interval, 1000, "session check interval");
DEFINE_int32(max_timeout, 2 * 60 * 1000, "max session timeout");
DEFINE_int32(min_timeout, 5 * 1000, "max session timeout");
DEFINE_int32(rpc_channel_size, 1024, "rpc channel size");
// for raft
DEFINE_string(raft_list, "", "address list of raft servers(host1:port1,host2:port2)");
DEFINE_string(snapshotdir, "snapshot", "snapshot dir");
DEFINE_uint64(snapshot_size, 1000000, "commit log size to take snapshot.");
DEFINE_uint64(snapshot_interval, 3600 * 24, " take snapshot interval in second.");
DEFINE_int32(max_commit_size, 200, "max commit size in one loop");
DEFINE_string(raftlog, "raftlog", "raft log dir");
DEFINE_bool(force_flush, false, "force flush in raft log");
DEFINE_int32(election_timeout, 1000, "election timeout in ms");
DEFINE_int32(heartbeat_timeout, 50, "heartbeat timeout in ms");
DEFINE_int32(myid, 0, "my id");
int main(int argc, char* argv[])
{
toft::SetupBinaryVersion();
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
std::vector<std::string> raftList;
std::vector<std::string> pyxisList;
toft::SplitString(FLAGS_raft_list, ",", &raftList);
toft::SplitString(FLAGS_pyxis_list, ",", &pyxisList);
pyxis::Options options;
options.DBDir = FLAGS_dbdir;
options.SessionCheckInterval = FLAGS_session_interval;
options.MaxSessionTimeout = FLAGS_max_timeout;
options.MinSessionTimeout = FLAGS_min_timeout;
options.SnapshotDir = FLAGS_snapshotdir;
options.MyID = FLAGS_myid;
options.AddrList = pyxisList;
uint32_t myid = FLAGS_myid;
uint32_t myindex = myid - 1;
CHECK(myid > 0);
CHECK(myid <= pyxisList.size());
CHECK(myid <= raftList.size());
// 监控线程
boost::scoped_ptr<muduo::net::EventLoopThread> inspectThread;
boost::scoped_ptr<muduo::net::Inspector> inspector;
if (FLAGS_pprof != 0) {
inspectThread.reset(new muduo::net::EventLoopThread);
inspector.reset(new muduo::net::Inspector(inspectThread->startLoop(),
muduo::net::InetAddress(FLAGS_pprof),
"inspect"));
}
raft::sofarpc::Transporter trans;
raft::Options raft_options;
raft_options.MyID = FLAGS_myid;
raft_options.RaftLogDir = FLAGS_raftlog;
raft_options.SnapshotLogSize = FLAGS_snapshot_size;
raft_options.SnapshotInterval = FLAGS_snapshot_interval;
raft_options.ForceFlush = FLAGS_force_flush;
raft_options.MaxCommitSize = FLAGS_max_commit_size;
raft_options.HeartbeatTimeout = FLAGS_heartbeat_timeout;
raft_options.ElectionTimeout = FLAGS_election_timeout;
raft::Server raftServer(raft_options, &trans);
raft::sofarpc::RpcServer raftRpcServer(FLAGS_raft_listen_addr, raftServer.RpcEventChannel());
for (size_t i = 0; i < raftList.size(); i++) {
if (i == myindex) {
continue;
}
trans.AddPeer(raftList[i]);
raftServer.AddPeer(raftList[i]);
}
// raft初始化
pyxis::Server pyxisServer(options, &raftServer);
muduo::net::EventLoop loop;
pyxis::rpc::Server rpcServer(&loop, FLAGS_pyxis_listen_addr, &pyxisServer);
rpcServer.Start();
pyxisServer.Start();
raftRpcServer.Start();
raftServer.Start();
loop.loop();
return 0;
}
| 36
| 95
| 0.728423
|
eLong-INF
|
9293c46352416bbd95d09069fc83fffa2697e1e4
| 1,756
|
cpp
|
C++
|
tests/unit/resource_manager_tests.cpp
|
aaroncblack/Umpire
|
5089a55aeed8b269112125e917f08b10e1797ae5
|
[
"MIT"
] | null | null | null |
tests/unit/resource_manager_tests.cpp
|
aaroncblack/Umpire
|
5089a55aeed8b269112125e917f08b10e1797ae5
|
[
"MIT"
] | null | null | null |
tests/unit/resource_manager_tests.cpp
|
aaroncblack/Umpire
|
5089a55aeed8b269112125e917f08b10e1797ae5
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory
//
// Created by David Beckingsale, david@llnl.gov
// LLNL-CODE-747640
//
// All rights reserved.
//
// This file is part of Umpire.
//
// For details, see https://github.com/LLNL/Umpire
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "umpire/ResourceManager.hpp"
TEST(ResourceManager, Constructor) {
umpire::ResourceManager& rm = umpire::ResourceManager::getInstance();
(void) rm;
SUCCEED();
}
TEST(ResourceManager, findAllocationRecord)
{
auto& rm = umpire::ResourceManager::getInstance();
auto alloc = rm.getAllocator("HOST");
const size_t size = 1024 * 1024;
const size_t offset = 1024;
char* ptr = static_cast<char*>(alloc.allocate(size));
const umpire::util::AllocationRecord* rec = rm.findAllocationRecord(ptr + offset);
ASSERT_EQ(ptr, rec->ptr);
alloc.deallocate(ptr);
ASSERT_THROW(rm.findAllocationRecord(nullptr), umpire::util::Exception);
}
TEST(ResourceManager, getAllocatorByName)
{
auto& rm = umpire::ResourceManager::getInstance();
EXPECT_NO_THROW({
auto alloc = rm.getAllocator("HOST");
UMPIRE_USE_VAR(alloc);
});
ASSERT_THROW(
rm.getAllocator("BANANA"),
umpire::util::Exception);
}
TEST(ResourceManager, getAllocatorById)
{
auto& rm = umpire::ResourceManager::getInstance();
EXPECT_NO_THROW({
auto alloc = rm.getAllocator(0);
UMPIRE_USE_VAR(alloc);
});
ASSERT_THROW(
rm.getAllocator(-4),
umpire::util::Exception);
}
| 24.054795
| 84
| 0.642369
|
aaroncblack
|
92944939250c28298b5f6815e0ada8e39adcf980
| 8,198
|
hh
|
C++
|
Project/headers/HelperFunctions.hh
|
anshuman1811/cs687-reinforcementlearning
|
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
|
[
"MIT"
] | null | null | null |
Project/headers/HelperFunctions.hh
|
anshuman1811/cs687-reinforcementlearning
|
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
|
[
"MIT"
] | null | null | null |
Project/headers/HelperFunctions.hh
|
anshuman1811/cs687-reinforcementlearning
|
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream> // For console i/o
#include <vector> // For vectors, not including linear algebra
#include <random> // For random number generation
#include <algorithm> // For min/max functions
// Additional libraries that you will have to download.
// First is Eigen, which we use for linear algebra: http://eigen.tuxfamily.org/index.php?title=Main_Page
#include <Eigen/Dense>
// Second is Boost, which we use for ibeta_inv: https://www.boost.org/
#include <boost/math/special_functions/beta.hpp>
// Typically these shouldn't be in a .hpp file.
using namespace std;
using namespace Eigen;
using namespace boost::math;
// This function returns the inverse of Student's t CDF using the degrees of
// freedom in nu for the corresponding probabilities in p. That is, it is
// a C++ implementation of Matlab's tinv function: https://www.mathworks.com/help/stats/tinv.html
// To see how this was created, see the "quantile" block here: https://www.boost.org/doc/libs/1_58_0/libs/math/doc/html/math_toolkit/dist_ref/dists/students_t_dist.html
double tinv(double p, unsigned int nu) {
double x = ibeta_inv((double)nu / 2.0, 0.5, 2.0 * min(p, 1.0 - p));
return sign(p - 0.5) * sqrt((double)nu * (1.0 - x) / x);
}
// Get the sample standard deviation of the vector v (an Eigen::VectorXd)
double stddev(const VectorXd& v) {
double mu = v.mean(), result = 0; // Get the sample mean
for (unsigned int i = 0; i < v.size(); i++)
result += (v[i] - mu) * (v[i] - mu); // Compute the sum of the squared differences between samples and the sample mean
result = sqrt(result / (v.size() - 1.0)); // Get the sample variance by dividing by the number of samples minus one, and then the sample standard deviation by taking the square root.
return result; // Return the value that we've computed.
}
// Assuming v holds i.i.d. samples of a random variable, compute
// a (1-delta)-confidence upper bound on the expected value of the random
// variable using Student's t-test. That is:
// sampleMean + sampleStandardDeviation/sqrt(n) * tinv(1-delta, n-1),
// where n is the number of points in v.
//
// If numPoints is provided, then ttestUpperBound predicts what its output would be if it were to
// be run using a new vector, v, containing numPoints values sampled from the same distribution as
// the points in v.
double ttestUpperBound(const VectorXd& v, const double& delta, const int numPoints = -1) {
unsigned int n = (numPoints == -1 ? (unsigned int)v.size() : (unsigned int)numPoints); // Set n to be numPoints if it was provided, and the number of points in v otherwise.
return v.mean() + (numPoints != -1 ? 2.0 : 1.0) * stddev(v) / sqrt((double)n) * tinv(1.0 - delta, n - 1u);
}
double ttestLowerBound(const VectorXd& v, const double& delta, const int numPoints = -1) {
unsigned int n = (numPoints == -1 ? (unsigned int)v.size() : (unsigned int)numPoints); // Set n to be numPoints if it was provided, and the number of points in v otherwise.
return v.mean() - (numPoints != -1 ? 2.0 : 1.0) * stddev(v) / sqrt((double)n) * tinv(1.0 - delta, n - 1u);
}
/*
This function implements CMA-ES (http://en.wikipedia.org/wiki/CMA-ES). Return
value is the minimizer / maximizer. This code is written for brevity, not clarity.
See the link above for a description of what this code is doing.
*/
VectorXd CMAES(
const VectorXd& initialMean, // Starting point of the search
const double& initialSigma, // Initial standard deviation of the search around initialMean
const unsigned int& numIterations, // Number of iterations to run before stopping
// f, below, is the function to be optimized. Its first argument is the solution, the middle arguments are variables required by f (listed below), and the last is a random number generator.
double(*f)(const VectorXd& theta, const void* params[], mt19937_64& generator),
const void* params[], // Parrameters of f other than theta
const bool& minimize, // If true, we will try to minimize f. Otherwise we will try to maximize f
mt19937_64& generator) // The random number generator to use
{
// Define all of the terms that we will use in the iterations
unsigned int N = (unsigned int)initialMean.size(), lambda = 4 + (unsigned int)floor(3.0 * log(N)), hsig;
double sigma = initialSigma, mu = lambda / 2.0, eigeneval = 0, chiN = pow(N, 0.5) * (1.0 - 1.0 / (4.0 * N) + 1.0 / (21.0 * N * N));
VectorXd xmean = initialMean, weights((unsigned int)mu);
for (unsigned int i = 0; i < (unsigned int)mu; i++)
weights[i] = i + 1;
weights = log(mu + 1.0 / 2.0) - weights.array().log();
mu = floor(mu);
weights = weights / weights.sum();
double mueff = weights.sum() * weights.sum() / weights.dot(weights), cc = (4.0 + mueff / N) / (N + 4.0 + 2.0 * mueff / N), cs = (mueff + 2.0) / (N + mueff + 5.0), c1 = 2.0 / ((N + 1.3) * (N + 1.3) + mueff), cmu = min(1.0 - c1, 2.0 * (mueff - 2.0 + 1.0 / mueff) / ((N + 2.0) * (N + 2.0) + mueff)), damps = 1.0 + 2.0 * max(0.0, sqrt((mueff - 1.0) / (N + 1.0)) - 1.0) + cs;
VectorXd pc = VectorXd::Zero(N), ps = VectorXd::Zero(N), D = VectorXd::Ones(N), DSquared = D, DInv = 1.0 / D.array(), xold, oneOverD;
for (unsigned int i = 0; i < DSquared.size(); i++)
DSquared[i] *= DSquared[i];
MatrixXd B = MatrixXd::Identity(N, N), C = B * DSquared.asDiagonal() * B.transpose(), invsqrtC = B * DInv.asDiagonal() * B.transpose(), arx(N, (int)lambda), repmat(xmean.size(), (int)(mu + .1)), artmp, arxSubMatrix(N, (int)(mu + .1));
vector<double> arfitness(lambda);
vector<unsigned int> arindex(lambda);
// Perform the iterations
for (unsigned int counteval = 0; counteval < numIterations;) {
cout << "Sampling Population" << endl;
// Sample the population
for (unsigned int k = 0; k < lambda; k++) {
normal_distribution<double> distribution(0, 1);
VectorXd randomVector(N);
for (unsigned int i = 0; i < N; i++)
randomVector[i] = D[i] * distribution(generator);
arx.col(k) = xmean + sigma * B * randomVector;
}
// Evaluate the population
vector<VectorXd> fInputs(lambda);
for (unsigned int i = 0; i < lambda; i++) {
cout << "Evaluating Candidate " << counteval+i << "/" << numIterations << endl;
fInputs[i] = arx.col(i);
cout << "Theta: " << fInputs[i].transpose() << endl;
arfitness[i] = (minimize ? 1 : -1) * f(fInputs[i], params, generator);
}
// Update the population distribution
counteval += lambda;
xold = xmean;
for (unsigned int i = 0; i < lambda; ++i)
arindex[i] = i;
std::sort(arindex.begin(), arindex.end(), [&arfitness](unsigned int i1, unsigned int i2) {return arfitness[i1] < arfitness[i2]; });
for (unsigned int col = 0; col < (unsigned int)mu; col++)
arxSubMatrix.col(col) = arx.col(arindex[col]);
xmean = arxSubMatrix * weights;
ps = (1.0 - cs) * ps + sqrt(cs * (2.0 - cs) * mueff) * invsqrtC * (xmean - xold) / sigma;
hsig = (ps.norm() / sqrt(1.0 - pow(1.0 - cs, 2.0 * counteval / lambda)) / (double)chiN < 1.4 + 2.0 / (N + 1.0) ? 1 : 0);
pc = (1 - cc) * pc + hsig * sqrt(cc * (2 - cc) * mueff) * (xmean - xold) / sigma;
for (unsigned int i = 0; i < repmat.cols(); i++)
repmat.col(i) = xold;
artmp = (1.0 / sigma) * (arxSubMatrix - repmat);
C = (1 - c1 - cmu) * C + c1 * (pc * pc.transpose() + (1u - hsig) * cc * (2 - cc) * C) + cmu * artmp * weights.asDiagonal() * artmp.transpose();
sigma = sigma * exp((cs / damps) * (ps.norm() / (double)chiN - 1.0));
if ((double)counteval - eigeneval > (double)lambda / (c1 + cmu) / (double)N / 10.0) {
eigeneval = counteval;
for (unsigned int r = 0; r < C.rows(); r++)
for (unsigned int c = r + 1; c < C.cols(); c++)
C(r, c) = C(c, r);
EigenSolver<MatrixXd> es(C);
D = C.eigenvalues().real();
B = es.eigenvectors().real();
D = D.array().sqrt();
for (unsigned int i = 0; i < B.cols(); i++)
B.col(i) = B.col(i).normalized();
oneOverD = 1.0 / D.array();
invsqrtC = B * oneOverD.asDiagonal() * B.transpose();
}
} // End loop over iterations
return arx.col(arindex[0]);
}
| 58.978417
| 372
| 0.633081
|
anshuman1811
|
92957e83fd0e8838a7f92589057c12265ed6de25
| 35,911
|
cpp
|
C++
|
src/ttauri/tokenizer.cpp
|
prollings/ttauri
|
51aa748eb52b72a06038ffa12952523cf3d4f9b6
|
[
"BSL-1.0"
] | null | null | null |
src/ttauri/tokenizer.cpp
|
prollings/ttauri
|
51aa748eb52b72a06038ffa12952523cf3d4f9b6
|
[
"BSL-1.0"
] | null | null | null |
src/ttauri/tokenizer.cpp
|
prollings/ttauri
|
51aa748eb52b72a06038ffa12952523cf3d4f9b6
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Take Vos 2019-2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#include "tokenizer.hpp"
namespace tt {
enum class tokenizer_state_t: uint8_t {
Initial,
Name,
MinusOrPlus, // Could be the start of a number, or an operator starting with '+' or '-'.
Zero, // Could be part of a number with a base.
Dot, // Could be the start of a floating point number, or the '.' operator.
Number, // Could be some kind of number without a base.
DashAfterNumber, // Could be a date.
ColonAfterNumber, // Could be a time.
DashAfterInteger, // Integer followed by a operator starting with '-'
ColonAfterInteger, // Integer followed by a operator starting with ':'
Float,
Date,
Time,
DQuote, // Could be the start of a string, an empty string, or block string.
DoubleDQuote, // Is an empty string or a block string.
String,
StringEscape,
BlockString,
BlockStringDQuote,
BlockStringDoubleDQuote,
BlockStringCaptureDQuote,
BlockStringEscape,
Slash, // Could be the start of a LineComment, BlockComment, or an operator.
LineComment,
BlockComment,
BlockCommentMaybeEnd, // Found a '*' possibly end of comment.
OperatorFirstChar,
OperatorSecondChar,
OperatorThirdChar,
Sentinal
};
constexpr size_t NR_TOKENIZER_STATES = static_cast<size_t>(tokenizer_state_t::Sentinal);
enum class tokenizer_action_t: uint8_t {
Idle = 0x00,
Capture = 0x01, // Capture this character.
Start = 0x02, // Start the capture queue.
Read = 0x04, // Read next character, before processing next state. This will also advance the location.
Found = 0x08, // Token Found.
Tab = 0x10, // Move the location modulo 8 to the right.
LineFeed = 0x20, // Move to the next line.
Poison = 0x80, // Cleared.
};
constexpr uint16_t get_offset(tokenizer_state_t state, char c = '\0') noexcept {
return (static_cast<uint16_t>(state) << 8) | static_cast<uint8_t>(c);
}
constexpr tokenizer_action_t operator|(tokenizer_action_t lhs, tokenizer_action_t rhs)
{
return static_cast<tokenizer_action_t>(static_cast<uint8_t>(lhs) | static_cast<uint8_t>(rhs));
}
constexpr tokenizer_action_t operator|(tokenizer_action_t lhs, char rhs)
{
switch (rhs) {
case '\n': return lhs | tokenizer_action_t::LineFeed;
case '\f': return lhs | tokenizer_action_t::LineFeed;
case '\t': return lhs | tokenizer_action_t::Tab;
default: return lhs | tokenizer_action_t::Idle;
}
}
constexpr bool operator>=(tokenizer_action_t lhs, tokenizer_action_t rhs)
{
return (static_cast<uint8_t>(lhs) & static_cast<uint8_t>(rhs)) == static_cast<uint8_t>(rhs);
}
struct tokenizer_transition_t {
tokenizer_state_t next;
tokenizer_action_t action;
char c;
tokenizer_name_t name;
constexpr tokenizer_transition_t(
char c,
tokenizer_state_t next = tokenizer_state_t::Initial,
tokenizer_action_t action = tokenizer_action_t::Idle,
tokenizer_name_t name = tokenizer_name_t::NotAssigned
) :
next(next), action(action), c(c), name(name) {}
constexpr tokenizer_transition_t() :
next(tokenizer_state_t::Initial), action(tokenizer_action_t::Idle), c('\0'), name(tokenizer_name_t::NotAssigned) {}
};
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Name()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isNameNext(c) || c == '-') {
transition.next = tokenizer_state_t::Name;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Name;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_MinusOrPlus()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '0') {
transition.next = tokenizer_state_t::Zero;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (isDigit(c) || c == '.') {
transition.next = tokenizer_state_t::Number;
} else {
transition.next = tokenizer_state_t::OperatorSecondChar;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Dot()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Float;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Operator;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Zero()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == 'x' || c == 'X' || c == 'd' || c == 'D' || c == 'o' || c == 'O' || c == 'b' || c == 'B') {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Number;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Number()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (c == '_' || c == '\'') {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read;
} else if (c == '.') {
transition.next = tokenizer_state_t::Float;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (c == '-') {
transition.next = tokenizer_state_t::DashAfterNumber;
transition.action = tokenizer_action_t::Read;
} else if (c == ':') {
transition.next = tokenizer_state_t::ColonAfterNumber;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::IntegerLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DashAfterNumber()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {'-'};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Date;
transition.action = tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::DashAfterInteger;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::IntegerLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_ColonAfterNumber()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {':'};
if (isDigit(c)) {
transition.next = tokenizer_state_t::Time;
transition.action = tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::ColonAfterInteger;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::IntegerLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DashAfterInteger()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
tokenizer_transition_t transition = {'-'};
transition.next = tokenizer_state_t::OperatorSecondChar;
transition.action = tokenizer_action_t::Start | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_ColonAfterInteger()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
tokenizer_transition_t transition = {':'};
transition.next = tokenizer_state_t::OperatorSecondChar;
transition.action = tokenizer_action_t::Start | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Date()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c) || c == '-') {
transition.next = tokenizer_state_t::Date;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::DateLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Time()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c) || c == ':' || c == '.') {
transition.next = tokenizer_state_t::Time;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::TimeLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Float()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (isDigit(c) || c == 'e' || c == 'E' || c == '-') {
transition.next = tokenizer_state_t::Float;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
} else if (c == '_' || c == '\'') {
transition.next = tokenizer_state_t::Float;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::FloatLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Slash()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '/') {
transition.next = tokenizer_state_t::LineComment;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Start;
} else if (c == '*') {
transition.next = tokenizer_state_t::BlockComment;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Start;
} else {
transition.next = tokenizer_state_t::OperatorSecondChar;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_LineComment()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
} else if (isLinefeed(c)) {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read | c;
} else {
transition.next = tokenizer_state_t::LineComment;
transition.action = tokenizer_action_t::Read | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockComment()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInBlockComment;
} else if (c == '*') {
transition.next = tokenizer_state_t::BlockCommentMaybeEnd;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockComment;
transition.action = tokenizer_action_t::Read | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockCommentMaybeEnd()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInBlockComment;
} else if (c == '/') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read;
} else if (c == '*') {
transition.next = tokenizer_state_t::BlockCommentMaybeEnd;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockComment;
transition.action = tokenizer_action_t::Read | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::DoubleDQuote;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::String;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_DoubleDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read;
} else {
// Empty string.
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::StringLiteral;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_String()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
} else if (isLinefeed(c)) {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start | c;
transition.name = tokenizer_name_t::ErrorLFInString;
} else if (c == '\\') {
transition.next = tokenizer_state_t::StringEscape;
transition.action = tokenizer_action_t::Read;
} else if (c == '"') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read;
transition.name = tokenizer_name_t::StringLiteral;
} else {
transition.next = tokenizer_state_t::String;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | c;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_StringEscape()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '\0':
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
r[i] = transition;
continue;
case 'a': transition.c = '\a'; break;
case 'b': transition.c = '\b'; break;
case 'f': transition.c = '\f'; break;
case 'n': transition.c = '\n'; break;
case 'r': transition.c = '\r'; break;
case 't': transition.c = '\t'; break;
case 'v': transition.c = '\v'; break;
}
transition.next = tokenizer_state_t::String;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockString()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
} else if (c == '"') {
transition.next = tokenizer_state_t::BlockStringDQuote;
transition.action = tokenizer_action_t::Read;
} else if (isWhitespace(c)) {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | c;
} else if (c == '\\') {
transition.next = tokenizer_state_t::BlockStringEscape;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::BlockStringDoubleDQuote;
transition.action = tokenizer_action_t::Read;
} else {
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Capture;
transition.c = '"';
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringDoubleDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '"') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read;
transition.name = tokenizer_name_t::StringLiteral;
} else {
transition.next = tokenizer_state_t::BlockStringCaptureDQuote;
transition.action = tokenizer_action_t::Capture;
transition.c = '"';
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringCaptureDQuote()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Capture;
transition.c = '"';
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_BlockStringEscape()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '\0':
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::ErrorEOTInString;
r[i] = transition;
continue;
case 'a': transition.c = '\a'; break;
case 'b': transition.c = '\b'; break;
case 'f': transition.c = '\f'; break;
case 'n': transition.c = '\n'; break;
case 'r': transition.c = '\r'; break;
case 't': transition.c = '\t'; break;
case 'v': transition.c = '\v'; break;
}
transition.next = tokenizer_state_t::BlockString;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_OperatorThirdChar()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '>':
case '=':
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture;
transition.name = tokenizer_name_t::Operator;
break;
default:
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Operator;
}
r[i] = transition;
}
return r;
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_OperatorSecondChar()
{
#define LAST_CHAR\
transition.next = tokenizer_state_t::Initial;\
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture;\
transition.name = tokenizer_name_t::Operator
#define MORE_CHARS\
transition.next = tokenizer_state_t::OperatorThirdChar;\
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '=': MORE_CHARS; break; // Possible: <=>
case '<': MORE_CHARS; break; // Possible: <<=
case '>': MORE_CHARS; break; // Possible: >>=
case '-': LAST_CHAR; break;
case '+': LAST_CHAR; break;
case '*': LAST_CHAR; break;
case '&': LAST_CHAR; break;
case '|': LAST_CHAR; break;
case '^': LAST_CHAR; break;
default:
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::Operator;
}
r[i] = transition;
}
return r;
#undef LAST_CHAR
#undef MORE_CHARS
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_OperatorFirstChar()
{
#define LAST_CHAR\
transition.next = tokenizer_state_t::Initial;\
transition.action = tokenizer_action_t::Found | tokenizer_action_t::Read | tokenizer_action_t::Capture;\
transition.name = tokenizer_name_t::Operator
#define MORE_CHARS\
transition.next = tokenizer_state_t::OperatorSecondChar;\
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
switch (c) {
case '.': LAST_CHAR; break;
case ';': LAST_CHAR; break;
case ',': LAST_CHAR; break;
case '(': LAST_CHAR; break;
case ')': LAST_CHAR; break;
case '[': LAST_CHAR; break;
case ']': LAST_CHAR; break;
case '{': LAST_CHAR; break;
case '}': LAST_CHAR; break;
case '?': LAST_CHAR; break;
case '@': LAST_CHAR; break;
case '$': LAST_CHAR; break;
case '~': LAST_CHAR; break;
case '!': MORE_CHARS; break; // Possible: !=
case '<': MORE_CHARS; break; // Possible: <=>, <=, <-, <<, <>, <<=
case '>': MORE_CHARS; break; // Possible: >=, >>, >>=
case '=': MORE_CHARS; break; // Possible: ==, =>
case '+': MORE_CHARS; break; // Possible: ++, +=
case '-': MORE_CHARS; break; // Possible: --, ->, -=
case '*': MORE_CHARS; break; // Possible: **
case '%': MORE_CHARS; break; // Possible: %=
case '/': MORE_CHARS; break; // Possible: /=
case '|': MORE_CHARS; break; // Possible: ||, |=
case '&': MORE_CHARS; break; // Possible: &&, &=
case '^': MORE_CHARS; break; // Possible: ^=
case ':': MORE_CHARS; break; // Possible: :=
default:
// If we don't recognize the operator, it means this character is invalid.
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture;
transition.name = tokenizer_name_t::ErrorInvalidCharacter;
}
r[i] = transition;
}
return r;
#undef LAST_CHAR
#undef MORE_CHARS
}
constexpr std::array<tokenizer_transition_t,256> calculateTransitionTable_Initial()
{
std::array<tokenizer_transition_t,256> r{};
for (uint16_t i = 0; i < r.size(); i++) {
ttlet c = static_cast<char>(i);
tokenizer_transition_t transition = {c};
if (c == '\0') {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Found;
transition.name = tokenizer_name_t::End;
} else if (isNameFirst(c)) {
transition.next = tokenizer_state_t::Name;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '-' || c == '+') {
transition.next = tokenizer_state_t::MinusOrPlus;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '0') {
transition.next = tokenizer_state_t::Zero;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (isDigit(c)) {
transition.next = tokenizer_state_t::Number;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '.') {
transition.next = tokenizer_state_t::Dot;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else if (c == '"') {
transition.next = tokenizer_state_t::DQuote;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Start;
} else if (isWhitespace(c)) {
transition.next = tokenizer_state_t::Initial;
transition.action = tokenizer_action_t::Read | c;
} else if (c == '#') {
transition.next = tokenizer_state_t::LineComment;
transition.action = tokenizer_action_t::Read;
} else if (c == '/') {
transition.next = tokenizer_state_t::Slash;
transition.action = tokenizer_action_t::Read | tokenizer_action_t::Capture | tokenizer_action_t::Start;
} else {
transition.next = tokenizer_state_t::OperatorFirstChar;
}
r[i] = transition;
}
return r;
}
constexpr size_t TRANSITION_TABLE_SIZE = NR_TOKENIZER_STATES * 256;
using transitionTable_t = std::array<tokenizer_transition_t,TRANSITION_TABLE_SIZE>;
constexpr transitionTable_t calculateTransitionTable()
{
#define CALCULATE_SUB_TABLE(x)\
i = get_offset(tokenizer_state_t::x);\
for (ttlet t: calculateTransitionTable_ ## x()) { r[i++] = t; }
transitionTable_t r{};
// Poisson the table, to make sure all sub tables have been initialized.
for (size_t i = 0; i < r.size(); i++) {
r[i].action = tokenizer_action_t::Poison;
}
size_t i = 0;
CALCULATE_SUB_TABLE(Initial);
CALCULATE_SUB_TABLE(Name);
CALCULATE_SUB_TABLE(MinusOrPlus);
CALCULATE_SUB_TABLE(Zero);
CALCULATE_SUB_TABLE(Dot);
CALCULATE_SUB_TABLE(Number);
CALCULATE_SUB_TABLE(DashAfterNumber);
CALCULATE_SUB_TABLE(ColonAfterNumber);
CALCULATE_SUB_TABLE(DashAfterInteger);
CALCULATE_SUB_TABLE(ColonAfterInteger);
CALCULATE_SUB_TABLE(Date);
CALCULATE_SUB_TABLE(Time);
CALCULATE_SUB_TABLE(Float);
CALCULATE_SUB_TABLE(DQuote);
CALCULATE_SUB_TABLE(DoubleDQuote);
CALCULATE_SUB_TABLE(String);
CALCULATE_SUB_TABLE(StringEscape);
CALCULATE_SUB_TABLE(BlockString);
CALCULATE_SUB_TABLE(BlockStringDQuote);
CALCULATE_SUB_TABLE(BlockStringDoubleDQuote);
CALCULATE_SUB_TABLE(BlockStringCaptureDQuote);
CALCULATE_SUB_TABLE(BlockStringEscape);
CALCULATE_SUB_TABLE(Slash);
CALCULATE_SUB_TABLE(LineComment);
CALCULATE_SUB_TABLE(BlockComment);
CALCULATE_SUB_TABLE(BlockCommentMaybeEnd);
CALCULATE_SUB_TABLE(OperatorFirstChar);
CALCULATE_SUB_TABLE(OperatorSecondChar);
CALCULATE_SUB_TABLE(OperatorThirdChar);
return r;
#undef CALCULATE_SUB_TABLE
}
constexpr bool optimizeTransitionTableOnce(transitionTable_t &r)
{
bool foundOptimization = false;
for (size_t i = 0; i < r.size(); i++) {
auto &transition = r[i];
if (transition.action == tokenizer_action_t::Idle) {
foundOptimization = true;
transition = r[get_offset(transition.next, static_cast<char>(i & 0xff))];
}
}
return foundOptimization;
}
constexpr transitionTable_t optimizeTransitionTable(transitionTable_t transitionTable)
{
for (int i = 0; i < 10; i++) {
if (!optimizeTransitionTableOnce(transitionTable)) {
break;
}
}
return transitionTable;
}
constexpr bool checkTransitionTable(transitionTable_t const &r)
{
for (size_t i = 0; i < r.size(); i++) {
if (r[i].action >= tokenizer_action_t::Poison) {
return false;
}
}
return true;
}
constexpr transitionTable_t buildTransitionTable()
{
constexpr auto transitionTable = calculateTransitionTable();
static_assert(checkTransitionTable(transitionTable), "Not all entries in transition table where assigned.");
return optimizeTransitionTable(transitionTable);
}
constexpr transitionTable_t transitionTable = buildTransitionTable();
struct tokenizer {
using iterator = typename std::string_view::const_iterator;
tokenizer_state_t state;
iterator index;
iterator end;
parse_location location;
parse_location captureLocation;
tokenizer(iterator begin, iterator end) :
state(tokenizer_state_t::Initial), index(begin), end(end) {}
/*! Parse a token.
*/
[[nodiscard]] token_t getNextToken() {
auto token = token_t{};
auto transition = tokenizer_transition_t{};
while (index != end) {
transition = transitionTable[get_offset(state, *index)];
state = transition.next;
auto action = transition.action;
if (action >= tokenizer_action_t::Start) {
token.location = location;
token.value.clear();
}
if (action >= tokenizer_action_t::Capture) {
token.value += transition.c;
}
if (action >= tokenizer_action_t::Read) {
if (action >= tokenizer_action_t::LineFeed) {
location.increment_line();
} else if (action >= tokenizer_action_t::Tab) {
location.tab_column();
} else {
location.increment_column();
}
++index;
}
if (action >= tokenizer_action_t::Found) {
token.name = transition.name;
return token;
}
}
// Complete the token at the current state. Or an end-token at the initial state.
if (state == tokenizer_state_t::Initial) {
// Mark the current offset as the position of the end-token.
token.location = location;
token.value.clear();
}
transition = transitionTable[get_offset(state)];
state = transition.next;
token.name = transition.name;
return token;
}
/*! Parse all tokens.
*/
[[nodiscard]] std::vector<token_t> getTokens() noexcept {
std::vector<token_t> r;
tokenizer_name_t token_name;
do {
ttlet token = getNextToken();
token_name = token.name;
r.push_back(std::move(token));
} while (token_name != tokenizer_name_t::End);
return r;
}
};
[[nodiscard]] std::vector<token_t> parseTokens(std::string_view::const_iterator first, std::string_view::const_iterator last) noexcept
{
return tokenizer(first, last).getTokens();
}
[[nodiscard]] std::vector<token_t> parseTokens(std::string_view text) noexcept
{
return parseTokens(text.cbegin(), text.cend());
}
}
| 34.266221
| 147
| 0.621147
|
prollings
|
92973dda4203cd24ca131457c4d824ecb2cbf27f
| 453
|
cpp
|
C++
|
window-move-1.cpp
|
ADITYA-CS/ncurse
|
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
|
[
"MIT"
] | null | null | null |
window-move-1.cpp
|
ADITYA-CS/ncurse
|
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
|
[
"MIT"
] | null | null | null |
window-move-1.cpp
|
ADITYA-CS/ncurse
|
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
|
[
"MIT"
] | null | null | null |
#include <ncurses.h>
#define TSIZE 18
int main() {
WINDOW *b;
int maxx, maxy, y, x;
initscr();
bkgd('.');
refresh();
getmaxyx(stdscr, maxy, maxx);
x = (maxx-TSIZE) >> 1;
b = newwin(1, TSIZE, 0, x);
waddstr(b, "I'm getting sick!");
for(y=0; y < maxy; y++){
mvwin(b, y, x);
wrefresh(b);
touchline(stdscr,y-1,1);
refresh();
getch();
}
endwin();
return 0;
}
| 15.1
| 36
| 0.470199
|
ADITYA-CS
|
929c9124c54184211afececa21d22ef6b9b03edc
| 8,663
|
cpp
|
C++
|
tests/unit/src/common/stream_channel.cpp
|
WeiDaiWD/APSI
|
b799d7a21d69867c07e91a3fd610f13e17cf91f5
|
[
"MIT"
] | 72
|
2021-05-04T11:25:58.000Z
|
2022-03-31T07:32:57.000Z
|
tests/unit/src/common/stream_channel.cpp
|
WeiDaiWD/APSI
|
b799d7a21d69867c07e91a3fd610f13e17cf91f5
|
[
"MIT"
] | 16
|
2021-05-06T07:58:34.000Z
|
2022-03-28T22:54:51.000Z
|
tests/unit/src/common/stream_channel.cpp
|
WeiDaiWD/APSI
|
b799d7a21d69867c07e91a3fd610f13e17cf91f5
|
[
"MIT"
] | 13
|
2021-05-04T06:44:40.000Z
|
2022-03-16T03:12:54.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// STD
#include <string>
#include <thread>
#include <utility>
// SEAL
#include "seal/keygenerator.h"
#include "seal/publickey.h"
// APSI
#include "apsi/network/stream_channel.h"
#include "apsi/powers.h"
#include "apsi/util/utils.h"
// Google Test
#include "gtest/gtest.h"
using namespace std;
using namespace seal;
using namespace apsi;
using namespace apsi::network;
namespace APSITests {
namespace {
shared_ptr<PSIParams> get_params()
{
static shared_ptr<PSIParams> params = nullptr;
if (!params) {
PSIParams::ItemParams item_params;
item_params.felts_per_item = 8;
PSIParams::TableParams table_params;
table_params.hash_func_count = 3;
table_params.max_items_per_bin = 16;
table_params.table_size = 512;
PSIParams::QueryParams query_params;
query_params.query_powers = { 1, 3, 5 };
size_t pmd = 4096;
PSIParams::SEALParams seal_params;
seal_params.set_poly_modulus_degree(pmd);
seal_params.set_coeff_modulus(CoeffModulus::Create(pmd, { 40, 40 }));
seal_params.set_plain_modulus(65537);
params =
make_shared<PSIParams>(item_params, table_params, query_params, seal_params);
}
return params;
}
shared_ptr<CryptoContext> get_context()
{
static shared_ptr<CryptoContext> context = nullptr;
if (!context) {
context = make_shared<CryptoContext>(*get_params());
KeyGenerator keygen(*context->seal_context());
context->set_secret(keygen.secret_key());
RelinKeys rlk;
keygen.create_relin_keys(rlk);
context->set_evaluator(move(rlk));
}
return context;
}
} // namespace
class StreamChannelTests : public ::testing::Test {
protected:
StreamChannelTests()
{}
~StreamChannelTests()
{}
};
TEST_F(StreamChannelTests, SendReceiveParms)
{
stringstream stream1;
stringstream stream2;
StreamChannel svr(/* istream */ stream1, /* ostream */ stream2);
StreamChannel clt(/* istream */ stream2, /* ostream */ stream1);
unique_ptr<SenderOperation> sop = make_unique<SenderOperationParms>();
// Send a parms operation
clt.send(move(sop));
sop = svr.receive_operation(get_context()->seal_context());
ASSERT_NE(nullptr, sop);
ASSERT_EQ(SenderOperationType::sop_parms, sop->type());
// Create a parms response
auto rsop_parms = make_unique<SenderOperationResponseParms>();
rsop_parms->params = make_unique<PSIParams>(*get_params());
unique_ptr<SenderOperationResponse> rsop = move(rsop_parms);
svr.send(move(rsop));
// Receive the parms response
rsop = clt.receive_response(SenderOperationType::sop_parms);
rsop_parms.reset(dynamic_cast<SenderOperationResponseParms *>(rsop.release()));
// We received valid parameters
ASSERT_EQ(get_params()->item_bit_count(), rsop_parms->params->item_bit_count());
ASSERT_EQ(svr.bytes_sent(), clt.bytes_received());
ASSERT_EQ(svr.bytes_received(), clt.bytes_sent());
}
TEST_F(StreamChannelTests, SendReceiveOPRFTest)
{
stringstream stream1;
stringstream stream2;
StreamChannel svr(/* istream */ stream1, /* ostream */ stream2);
StreamChannel clt(/* istream */ stream2, /* ostream */ stream1);
// Fill a data buffer
vector<unsigned char> oprf_data(256);
for (size_t i = 0; i < oprf_data.size(); i++) {
oprf_data[i] = static_cast<unsigned char>(i);
}
auto sop_oprf = make_unique<SenderOperationOPRF>();
sop_oprf->data = oprf_data;
unique_ptr<SenderOperation> sop = move(sop_oprf);
// Send an OPRF operation
clt.send(move(sop));
// Receive the operation
sop = svr.receive_operation(get_context()->seal_context());
ASSERT_EQ(SenderOperationType::sop_oprf, sop->type());
sop_oprf.reset(dynamic_cast<SenderOperationOPRF *>(sop.release()));
// Validate the data
ASSERT_EQ(256, sop_oprf->data.size());
for (size_t i = 0; i < sop_oprf->data.size(); i++) {
ASSERT_EQ(static_cast<char>(sop_oprf->data[i]), static_cast<char>(i));
}
// Create an OPRF response
auto rsop_oprf = make_unique<SenderOperationResponseOPRF>();
rsop_oprf->data = oprf_data;
unique_ptr<SenderOperationResponse> rsop = move(rsop_oprf);
svr.send(move(rsop));
// Receive the OPRF response
rsop = clt.receive_response(SenderOperationType::sop_oprf);
rsop_oprf.reset(dynamic_cast<SenderOperationResponseOPRF *>(rsop.release()));
// Validate the data
ASSERT_EQ(256, rsop_oprf->data.size());
for (size_t i = 0; i < rsop_oprf->data.size(); i++) {
ASSERT_EQ(static_cast<char>(rsop_oprf->data[i]), static_cast<char>(i));
}
ASSERT_EQ(svr.bytes_sent(), clt.bytes_received());
ASSERT_EQ(svr.bytes_received(), clt.bytes_sent());
}
TEST_F(StreamChannelTests, SendReceiveQuery)
{
stringstream stream1;
stringstream stream2;
StreamChannel svr(/* istream */ stream1, /* ostream */ stream2);
StreamChannel clt(/* istream */ stream2, /* ostream */ stream1);
auto sop_query = make_unique<SenderOperationQuery>();
sop_query->relin_keys = *get_context()->relin_keys();
sop_query->data[0].push_back(get_context()->encryptor()->encrypt_zero_symmetric());
sop_query->data[123].push_back(get_context()->encryptor()->encrypt_zero_symmetric());
unique_ptr<SenderOperation> sop = move(sop_query);
// Send a query operation
clt.send(move(sop));
// Receive the operation
sop = svr.receive_operation(get_context()->seal_context());
ASSERT_EQ(SenderOperationType::sop_query, sop->type());
sop_query.reset(dynamic_cast<SenderOperationQuery *>(sop.release()));
// Are we able to extract the relinearization keys?
ASSERT_NO_THROW(auto rlk = sop_query->relin_keys.extract_if_local());
// Check for query ciphertexts
ASSERT_EQ(2, sop_query->data.size());
ASSERT_FALSE(sop_query->data.at(0).empty());
ASSERT_EQ(1, sop_query->data[0].size());
auto query_ct0 = sop_query->data[0][0].extract_if_local();
ASSERT_FALSE(sop_query->data.at(123).empty());
ASSERT_EQ(1, sop_query->data[123].size());
auto query_ct123 = sop_query->data[123][0].extract_if_local();
// Create a query response
auto rsop_query = make_unique<SenderOperationResponseQuery>();
rsop_query->package_count = 2;
unique_ptr<SenderOperationResponse> rsop = move(rsop_query);
svr.send(move(rsop));
// Receive the query response
rsop = clt.receive_response(SenderOperationType::sop_query);
rsop_query.reset(dynamic_cast<SenderOperationResponseQuery *>(rsop.release()));
// Validate the data
ASSERT_EQ(2, rsop_query->package_count);
// Send two ResultPackages
auto rp = make_unique<ResultPackage>();
rp->bundle_idx = 0;
rp->label_byte_count = 0;
rp->nonce_byte_count = 0;
rp->psi_result = query_ct0;
svr.send(move(rp));
rp = make_unique<ResultPackage>();
rp->bundle_idx = 123;
rp->label_byte_count = 80;
rp->nonce_byte_count = 4;
rp->psi_result = query_ct123;
rp->label_result.push_back(query_ct123);
svr.send(move(rp));
// Receive two packages
rp = clt.receive_result(get_context()->seal_context());
ASSERT_EQ(0, rp->bundle_idx);
ASSERT_EQ(0, rp->label_byte_count);
ASSERT_EQ(0, rp->bundle_idx);
ASSERT_TRUE(rp->label_result.empty());
rp = clt.receive_result(get_context()->seal_context());
ASSERT_EQ(123, rp->bundle_idx);
ASSERT_EQ(80, rp->label_byte_count);
ASSERT_EQ(4, rp->nonce_byte_count);
ASSERT_EQ(1, rp->label_result.size());
ASSERT_EQ(svr.bytes_sent(), clt.bytes_received());
ASSERT_EQ(svr.bytes_received(), clt.bytes_sent());
}
} // namespace APSITests
| 34.791165
| 97
| 0.62184
|
WeiDaiWD
|
92a19ff157a16ed176e06a96c8483de43e7e9d8c
| 944
|
cpp
|
C++
|
QuickGUI/src/QuickGUIOgreEquivalents.cpp
|
VisualEntertainmentAndTechnologies/VENT-QuickGUI
|
7c687193001bcf914bd4a9947644915091ea8723
|
[
"Unlicense"
] | 3
|
2017-01-12T19:22:01.000Z
|
2017-05-06T09:55:39.000Z
|
QuickGUI/src/QuickGUIOgreEquivalents.cpp
|
VisualEntertainmentAndTechnologies/VENT-QuickGUI
|
7c687193001bcf914bd4a9947644915091ea8723
|
[
"Unlicense"
] | null | null | null |
QuickGUI/src/QuickGUIOgreEquivalents.cpp
|
VisualEntertainmentAndTechnologies/VENT-QuickGUI
|
7c687193001bcf914bd4a9947644915091ea8723
|
[
"Unlicense"
] | null | null | null |
#include "QuickGUIOgreEquivalents.h"
namespace QuickGUI
{
const Vector2 Vector2::ZERO( 0, 0 );
const Vector3 Vector3::ZERO( 0, 0, 0 );
bool ColourValue::operator==(const ColourValue& rhs) const
{
return (r == rhs.r &&
g == rhs.g &&
b == rhs.b &&
a == rhs.a);
}
//---------------------------------------------------------------------
bool ColourValue::operator!=(const ColourValue& rhs) const
{
return !(*this == rhs);
}
const ColourValue ColourValue::ZERO = ColourValue(0.0,0.0,0.0,0.0);
const ColourValue ColourValue::Black = ColourValue(0.0,0.0,0.0);
const ColourValue ColourValue::White = ColourValue(1.0,1.0,1.0);
const ColourValue ColourValue::Red = ColourValue(1.0,0.0,0.0);
const ColourValue ColourValue::Green = ColourValue(0.0,1.0,0.0);
const ColourValue ColourValue::Blue = ColourValue(0.0,0.0,1.0);
}
| 32.551724
| 76
| 0.555085
|
VisualEntertainmentAndTechnologies
|
92a418fadf9b8d9424d20df7b0066158eedf5d88
| 11,026
|
hpp
|
C++
|
common/cxx/config_cxx/include/config_cxx/yaml_wrapper.hpp
|
csitarichie/someip_cyclone_dds_bridge
|
2ccaaa6e2484a938b08562497431df61ab23769f
|
[
"MIT"
] | null | null | null |
common/cxx/config_cxx/include/config_cxx/yaml_wrapper.hpp
|
csitarichie/someip_cyclone_dds_bridge
|
2ccaaa6e2484a938b08562497431df61ab23769f
|
[
"MIT"
] | null | null | null |
common/cxx/config_cxx/include/config_cxx/yaml_wrapper.hpp
|
csitarichie/someip_cyclone_dds_bridge
|
2ccaaa6e2484a938b08562497431df61ab23769f
|
[
"MIT"
] | null | null | null |
#include <memory>
#include <string>
#include <variant>
#include <vector>
#include "adstutil_cxx/compiler_diagnostics.hpp"
ADST_DISABLE_CLANG_WARNING("unused-parameter")
#include <adstutil_cxx/static_string.hpp>
ADST_RESTORE_CLANG_WARNING()
#include "adstutil_cxx/error_handler.hpp"
struct yaml_parser_s;
using yaml_parser_t = yaml_parser_s;
namespace sstr = ak_toolkit::static_str;
namespace adst::common {
/**
* Parse a YAML document and give access to the fields.
*/
class YamlWrapper
{
// not copyable or movable
YamlWrapper(const YamlWrapper&) = delete;
YamlWrapper(YamlWrapper&&) = delete;
YamlWrapper& operator=(const YamlWrapper&) = delete;
YamlWrapper& operator=(YamlWrapper&&) = delete;
public:
/**
* Creates Yaml object which provides access path key type of representation of the file.
*
* In case both static doc and file name is provided then file is read first if file does not exists or null
* than static doc is used if both is NULL or file can not be read and static doc is NULL error is called.
*
* @param onErrorCallBack Error callback. This function will typically never return (e.g. by calling exit/abort).
* @param staticDoc if it is not NULL and file can not be read or NULL then reads from the Static Doc.
* @param fileName if it is not NULL wrapper reads from file if file exists.
*
*/
explicit YamlWrapper(const OnErrorCallBack& onErrorCallBack, const std::string& staticDoc,
const std::string& fileName);
~YamlWrapper() = default;
/**
* Getter for floating point values. The function has to be called with a specific type
* template. In floating point case e.g. ''getValue<double>''.
*
* @param accessPath See details at getValueImpl.
* @param separator See details at getValueImpl.
* @return Pair of which the first is a valid/invalid bool flag and the second is the actual data.
*/
template <typename T, typename std::enable_if<std::is_floating_point<T>::value, T>::type* = nullptr>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
char* id;
auto val = getValueImpl(accessPath, separator);
T ret = strtof(val, &id);
return std::make_pair(*id == '\0', ret);
}
/**
* Getter for signed integer (not bool) values. See above for details.
*/
template <typename T,
typename std::enable_if<
std::is_integral<T>::value && std::is_signed<T>::value && !std::is_same<T, bool>::value, T>::type = 0>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
char* id;
auto val = getValueImpl(accessPath, separator);
T ret = strtol(val, &id, 0);
return std::make_pair(*id == '\0', ret);
}
/**
* Getter for unsigned integer (not bool) values. See above for details.
*/
template <typename T, typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
!std::is_same<T, bool>::value,
T>::type = 0>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
char* id;
auto val = getValueImpl(accessPath, separator);
T ret = strtoul(val, &id, 0);
return std::make_pair(*id == '\0', ret);
}
/**
* Getter for boolean type values. Internally, this getter accepts true, True and 1 as true, and
* false, False and 0 as false. See :cpp:func:`YamlWrapper::getValueImpl` for more details.
*/
template <typename T, typename std::enable_if<std::is_same<T, bool>::value, T>::type = 0>
std::pair<bool, T> getValue(const std::string& accessPath, const char separator = '/') const
{
auto value = std::string{getValueImpl(accessPath, separator)};
if (value == "true" || value == "True" || value == "1") {
return std::make_pair<bool, T>(true, true);
}
if (value == "false" || value == "False" || value == "0") {
return std::make_pair<bool, T>(true, false);
}
return std::make_pair<bool, T>(false, false);
}
/**
* Getter for string values. This function can be used for any value type. See above for
* details.
*/
template <typename T, typename = typename std::enable_if<std::is_same<T, std::string>::value>::type>
std::pair<bool, const T> getValue(const std::string& accessPath, const char separator = '/') const
{
auto retStr = getValueImpl(accessPath, separator);
return std::make_pair((retStr == std::string{NOT_FOUND}) ? false : true, std::string{retStr});
}
private:
/**
* Abstract base class for every YAML node. All other nodes derive from this. Each node may have
* a key which is used to identify the exact node. The key can be empty and a number too in case
* of sequence elements.
*/
class YamlNode
{
protected:
/**
* enum class for each types of nodes. The root node is always a DOC. Other nodes follow obviously.
*/
enum class Type
{
VALUE,
SEQUENCE,
MAPPING,
DOC
};
private:
// not copyable or movable
YamlNode(const YamlNode&) = delete;
YamlNode(YamlNode&&) = delete;
YamlNode& operator=(const YamlNode&) = delete;
YamlNode& operator=(YamlNode&&) = delete;
/// The wrapper constuctor needs access to the fields.
friend class YamlWrapper;
const Type type_; /// The type of the node. See above
const std::string value_; /// At scalars this is the real value, at other cases it's "<ClassName>Value"
protected:
/// The parent of the node in case of MAPPING and SEQUENCE type nodes.
YamlNode& parent_;
/// The children of the node if this is a MAPPING or a SEQUENCE type node.
std::vector<std::unique_ptr<YamlNode>> children_;
/// The name (key) of the node which can be used to identify the node.
const std::string name_;
public:
/**
* The more common constructor needs a parent node, a key, a type and a value.
*
* @param aParent Parent node.
* @param aName Name (key) which will be used for identification.
* @param aType Type of the node.
* @param aValue Value of the node, which is most meaningful in case of scalars (leaf nodes).
*/
explicit YamlNode(YamlNode& aParent, const std::string& aName, Type aType, const std::string& aValue)
: type_(aType)
, value_(aValue)
, parent_(aParent)
, name_(aName)
{
}
/**
* Construct a root node. Sets the type to DOC and the parent to
* itself. This is because the root node is the parent of itself (we
* cannot have a reference to NULL).
*/
explicit YamlNode()
: type_(Type::DOC)
, value_("YamlDocValue")
, parent_(*this)
{
}
/**
* Getter function for the node key.
*
* @return Node key.
*/
const std::string& getKey() const
{
return name_;
}
/**
* Getter function for the node type.
*
* @return Node type.
*/
Type getType() const
{
return type_;
}
/**
* Getter function for the the node value.
*
* @return the value of the node
*/
const std::string& getValue() const
{
return value_;
}
virtual ~YamlNode() = 0;
}; // class YamlNode
/**
* Concrete class for the doc (root) node. Shall not be used for other node types.
*/
class YamlDoc : public YamlNode
{
public:
explicit YamlDoc()
: YamlNode()
{
}
};
/**
* The mapping node. This is not an actual std::map but represents a YAML mapping. A mapping
* node's children can be VALUE, MAPPING or SEQUENCE type nodes. Searching on it takes O(n)
* time, where n is the number of elements.
*/
class YamlMapping : public YamlNode
{
public:
explicit YamlMapping(YamlNode& aParent, const std::string& aName)
: YamlNode(aParent, aName, YamlNode::Type::MAPPING, "YamlMappingValue")
{
}
};
/**
* The sequence node. It's child nodes are stored in order and can be VALUE, MAPPING and
* SEQUENCE type nodes.
*/
class YamlSequence : public YamlNode
{
public:
explicit YamlSequence(YamlNode& aParent, const std::string& aName)
: YamlNode(aParent, aName, YamlNode::Type::SEQUENCE, "YamlSequenceValue")
{
}
};
/**
* The value node. Actual VALUEs are stored in this type of nodes.
*/
class YamlValue : public YamlNode
{
public:
explicit YamlValue(YamlNode& aParent, const std::string& aName, const std::string& aValue)
: YamlNode(aParent, aName, YamlNode::Type::VALUE, aValue)
{
}
};
/**
* Retrieves node value as string from the node tree. This is the core functionality for
* accessing node values (since internally all node values are represented as strings).
*
* @param accessPath Access path to the node. Nested maps should be searched with their
* respective keys, sequences should be searched by index.
* @param separator Separator which is used between access path elements for nested node
* searching.
*/
const char* getValueImpl(const std::string& accessPath, char separator) const;
/**
* Parse the YAML doc from file and create the node tree.
* @param fileName path to the file to read.
* @return true in case of success otherwise false
*/
bool initFromFile(const std::string& fileName);
/**
* Parse the YAML doc from static 0 terminated c string and create the node tree.
* @param builtInDoc the compiled in config doc useful for tests where no extra file is provided.
* @return true in case of success otherwise false
*/
bool initFromConstString(const std::string& builtInDoc);
bool parse(yaml_parser_t* parser);
/// The root node. All other nodes are children of this node.
std::unique_ptr<YamlNode> root_ = std::make_unique<YamlDoc>();
/// Used as node value in case the actual node cannot be found.
static constexpr auto NOT_FOUND = sstr::literal("Not Found");
/// Default error callback function.
const OnErrorCallBack& onErrorCallBack_;
};
inline YamlWrapper::YamlNode::~YamlNode()
{
}
} // namespace adst::common
| 34.782334
| 120
| 0.605024
|
csitarichie
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.