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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bdf08b121e490d05aef5f59dae483c52964089f8 | 709 | cpp | C++ | STL/string/C/memchr.cpp | bayusamudra5502/PustakaCpp | ac67e47374740b4923dd135d67f4bf987d4010b4 | [
"MIT"
] | null | null | null | STL/string/C/memchr.cpp | bayusamudra5502/PustakaCpp | ac67e47374740b4923dd135d67f4bf987d4010b4 | [
"MIT"
] | null | null | null | STL/string/C/memchr.cpp | bayusamudra5502/PustakaCpp | ac67e47374740b4923dd135d67f4bf987d4010b4 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef struct{
char nama[50];
char kelas[50];
} IDENTITAS;
int main(){
IDENTITAS *siswa; // Sekalian belajar pointer lah :v
// siswa = (IDENTITAS*) malloc(sizeof(IDENTITAS)); // #include <cstdlib> (Gaya Bahasa C)
siswa = new IDENTITAS(); //Gaya c++
strcpy(siswa->nama, "Bayu Samudra");
strcpy(siswa->kelas, "11 IPA 2");
char* Nama = (char*) siswa->nama;
char* ptr = (char*) memchr(Nama,'a',50);
cout << ptr << endl; // Setara dengan printf("%s\n", ptr);
printf("%s\n\n", ptr);
cout << *ptr << endl; // Setara dengan printf("%C\n", *ptr);
printf("%C\n", *ptr);
return 0;
} | 27.269231 | 93 | 0.558533 | bayusamudra5502 |
bdf44695e767d57356d4e626cdc1b3d2aaa6b52d | 783 | cpp | C++ | projects/Phantom/phantom/lang/MemberAnonymousStruct.cpp | vlmillet/phantom | e5579ea52dafded64fd2fe88aabfdf8a73534918 | [
"MIT"
] | 12 | 2019-12-26T00:55:39.000Z | 2020-12-03T14:46:56.000Z | projects/Phantom/phantom/lang/MemberAnonymousStruct.cpp | vlmillet/Phantom | e5579ea52dafded64fd2fe88aabfdf8a73534918 | [
"MIT"
] | null | null | null | projects/Phantom/phantom/lang/MemberAnonymousStruct.cpp | vlmillet/Phantom | e5579ea52dafded64fd2fe88aabfdf8a73534918 | [
"MIT"
] | 1 | 2020-12-09T11:47:13.000Z | 2020-12-09T11:47:13.000Z | // license [
// This file is part of the Phantom project. Copyright 2011-2020 Vivien Millet.
// Distributed under the MIT license. Text available here at
// https://github.com/vlmillet/phantom
// ]
/* ******************* Includes ****************** */
#include "MemberAnonymousStruct.h"
#include "Type.h"
/* *********************************************** */
namespace phantom
{
namespace lang
{
MemberAnonymousStruct::MemberAnonymousStruct(Modifiers modifiers /*= 0*/, uint a_uiFlags /*= 0*/)
: MemberAnonymousSection(modifiers, a_uiFlags)
{
}
void MemberAnonymousStruct::computeSizeAndAlignment(size_t& a_uiSize, size_t& a_uiAlignment) const
{
Type::AlignmentComputer().alignStruct(m_DataElements, a_uiSize, a_uiAlignment);
}
} // namespace lang
} // namespace phantom
| 27.964286 | 98 | 0.66539 | vlmillet |
bdf6fc6043842805abd9cf148159e597e67da2e5 | 5,243 | cpp | C++ | plugins/GUI/guidriverAndroidGLES/src/guidriverAndroidGLES_pluginAPI.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 5 | 2016-04-18T23:12:51.000Z | 2022-03-06T05:12:07.000Z | plugins/GUI/guidriverAndroidGLES/src/guidriverAndroidGLES_pluginAPI.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 2 | 2015-10-09T19:13:25.000Z | 2018-12-25T17:16:54.000Z | plugins/GUI/guidriverAndroidGLES/src/guidriverAndroidGLES_pluginAPI.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 15 | 2015-02-23T16:35:28.000Z | 2022-03-25T13:40:33.000Z | /*
* guidriverAndroidGLES: module implementing GLES based window management for Android
* Copyright (C) 2002 - 2011. Dinand Vanvelzen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#ifndef GUCEF_GUI_CGUIGLOBAL_H
#include "gucefGUI_CGuiGlobal.h"
#define GUCEF_GUI_CGUIGLOBAL_H
#endif /* GUCEF_GUI_CGUIGLOBAL_H ? */
#ifndef GUCEF_GUI_CWINDOWMANAGER_H
#include "gucefGUI_CWindowManager.h"
#define GUCEF_GUI_CWINDOWMANAGER_H
#endif /* GUCEF_GUI_CWINDOWMANAGER_H ? */
#ifndef GUIDRIVERANDROIDGLES_CANDROIDWINDOWMANAGERIMP_H
#include "guidriverAndroidGLES_CAndroidWindowManagerImp.h"
#define GUIDRIVERANDROIDGLES_CANDROIDWINDOWMANAGERIMP_H
#endif /* GUIDRIVERANDROIDGLES_CANDROIDWINDOWMANAGERIMP_H ? */
#include "guidriverAndroidGLES_pluginAPI.h"
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GUCEF {
namespace GUIDRIVERANDROIDGLES {
/*-------------------------------------------------------------------------//
// //
// GLOBAL VARS //
// //
//-------------------------------------------------------------------------*/
static TAndroidWindowManagerImpPtr androidGlesWindowManager = new CAndroidWindowManagerImp();
/*-------------------------------------------------------------------------//
// //
// UTILITIES //
// //
//-------------------------------------------------------------------------*/
CORE::Int32 GUCEF_PLUGIN_CALLSPEC_PREFIX
GUCEFPlugin_Load( CORE::UInt32 argc, const char** argv ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{GUCEF_TRACE;
GUI::CGuiGlobal::Instance()->GetWindowManager().RegisterBackend( "AndroidGLES", androidGlesWindowManager );
return 1;
}
/*--------------------------------------------------------------------------*/
void GUCEF_PLUGIN_CALLSPEC_PREFIX
GUCEFPlugin_Unload( void ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{GUCEF_TRACE;
GUI::CGuiGlobal::Instance()->GetWindowManager().UnregisterBackend( "AndroidGLES" );
}
/*--------------------------------------------------------------------------*/
void GUCEF_PLUGIN_CALLSPEC_PREFIX
GUCEFPlugin_GetVersion( CORE::TVersion* versionInfo ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{GUCEF_TRACE;
versionInfo->major = 0;
versionInfo->minor = 1;
versionInfo->patch = 0;
versionInfo->release = 0;
}
/*--------------------------------------------------------------------------*/
const char* GUCEF_PLUGIN_CALLSPEC_PREFIX
GUCEFPlugin_GetCopyright( void ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{GUCEF_TRACE;
return "Copyright (C) Dinand Vanvelzen, released under LGPLv3";
}
/*--------------------------------------------------------------------------*/
const char* GUCEF_PLUGIN_CALLSPEC_PREFIX
GUCEFPlugin_GetDescription( void ) GUCEF_PLUGIN_CALLSPEC_SUFFIX
{GUCEF_TRACE;
return "Window management backend for Android using GLES";
}
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace GUIDRIVERANDROIDGLES */
}; /* namespace GUCEF */
/*--------------------------------------------------------------------------*/ | 42.97541 | 112 | 0.424948 | amvb |
da041e2b4a00631e4fd41ed8e818991b51e58ea5 | 750 | cpp | C++ | code/Thistle/source/thistle.cpp | pospeselr/SiCKL | e6b3b022df168cb7b853e233967407ff28dd8d1b | [
"MIT"
] | null | null | null | code/Thistle/source/thistle.cpp | pospeselr/SiCKL | e6b3b022df168cb7b853e233967407ff28dd8d1b | [
"MIT"
] | null | null | null | code/Thistle/source/thistle.cpp | pospeselr/SiCKL | e6b3b022df168cb7b853e233967407ff28dd8d1b | [
"MIT"
] | null | null | null | #include "thistle.hpp"
#include "thistle_error.hpp"
using ruff::translate_exceptions;
static spark_context_t* g_spark_context = nullptr;
RUFF_EXPORT void thistle_begin_session(thistle_error_t** error)
{
return translate_exceptions(error, [&]()
{
RUFF_THROW_IF_FALSE(g_spark_context == nullptr);
g_spark_context = spark_create_context(SPARK_THROW_ON_ERROR());
spark_set_current_context(g_spark_context, SPARK_THROW_ON_ERROR());
});
}
RUFF_EXPORT void thistle_end_session(thistle_error_t** error)
{
return translate_exceptions(error, [&]()
{
RUFF_THROW_IF_NULL(g_spark_context);
spark_destroy_context(g_spark_context, SPARK_THROW_ON_ERROR());
g_spark_context = nullptr;
});
} | 27.777778 | 75 | 0.734667 | pospeselr |
da057295d0031327a3dba640abc770e6f0340e15 | 21,633 | cc | C++ | client/client.cc | dubey/weaver | 56a42fd2d0bbb14867ba792ca5461d16310a7387 | [
"BSD-3-Clause"
] | 163 | 2015-01-02T03:51:38.000Z | 2022-03-21T23:06:39.000Z | client/client.cc | dubey/weaver | 56a42fd2d0bbb14867ba792ca5461d16310a7387 | [
"BSD-3-Clause"
] | 1 | 2015-04-08T23:17:06.000Z | 2015-04-24T15:25:26.000Z | client/client.cc | dubey/weaver | 56a42fd2d0bbb14867ba792ca5461d16310a7387 | [
"BSD-3-Clause"
] | 20 | 2015-02-17T19:24:05.000Z | 2020-10-29T01:59:18.000Z | /*
* ===============================================================
* Description: Client methods implementation.
*
* Created: 03/19/2014 11:58:26 PM
*
* Author: Ayush Dubey, dubey@cs.cornell.edu
*
* Copyright (C) 2013, Cornell University, see the LICENSE file
* for licensing agreement
* ===============================================================
*/
#include <random>
#include <dlfcn.h>
#include "common/utils.h"
#include "common/message.h"
#include "common/config_constants.h"
#include "node_prog/dynamic_prog_table.h"
#include "client/client_constants.h"
#include "client/client.h"
using node_prog::Node_Parameters_Base;
#define CLIENTLOG std::cerr << __FILE__ << ":" << __LINE__ << " "
// ugly, declared only to get rid of undefined symbol error
// not used in client
DECLARE_CONFIG_CONSTANTS;
using cl::client;
using transaction::pending_update;
client :: client(const char *coordinator="127.0.0.1", uint16_t port=5200, const char *config_file="/etc/weaver.yaml")
: m_sm(coordinator, port)
, cur_tx_id(UINT64_MAX)
, tx_id_ctr(0)
, handle_ctr(0)
, init(true)
, logging(false)
{
if (!init_config_constants(config_file)) {
CLIENTLOG << "weaver_client: error in init_config_constants, config file=" << config_file << std::endl;
init = false;
std::string except_message = "could not initialize configuration constants from file ";
except_message += config_file;
throw weaver_client_exception(except_message);
}
std::random_device rd;
std::mt19937_64 generator(rd());
std::uniform_int_distribution<uint64_t> distribution(0, NumVts-1);
vtid = distribution(generator);
CLIENTLOG << "client vt = " << vtid << std::endl;
if (!m_sm.get_unique_number(myid)) {
init = false;
std::string except_message = "could not contact Weaver server manager";
throw weaver_client_exception(except_message);
}
if (myid <= MaxNumServers) {
init = false;
std::string except_message = "internal error in initialization, myid=" + std::to_string(myid);
throw weaver_client_exception(except_message);
}
myid_str = std::to_string(myid);
int try_sm = 0;
replicant_returncode rc;
while (!maintain_sm_connection(rc)) {
std::cerr << "weaver_client: retry server manager connection #" << try_sm++ << std::endl;
init = false;
if (try_sm == 10) {
init = false;
std::string except_message = "multiple server manager connection attempts failed";
throw weaver_client_exception(except_message);
}
}
comm.reset(new cl::comm_wrapper(myid, *m_sm.config()));
#define INIT_PROG(lib, name, prog_handle) \
reg_code = register_node_prog(lib, prog_handle); \
if (reg_code != WEAVER_CLIENT_SUCCESS) { \
WDEBUG << "unsuccessful node prog register, " \
<< " name=" << name \
<< " lib=" << lib \
<< " returncode=" << weaver_client_returncode_to_string(reg_code) \
<< std::endl; \
} \
WDEBUG << "registered prog name=" << name << " handle=" << prog_handle << std::endl; \
m_built_in_progs[name] = prog_handle;
std::string prog_handle;
weaver_client_returncode reg_code;
INIT_PROG("/usr/local/lib/libweavertraversepropsprog.so", "traverse_props_prog", prog_handle);
INIT_PROG("/usr/local/lib/libweavernninferprog.so", "nn_infer_prog", prog_handle);
}
// call once per application, even with multiple clients
void
client :: initialize_logging()
{
logging = true;
}
#define CHECK_INIT \
if (!init) { \
return WEAVER_CLIENT_INITERROR; \
}
#define CHECK_ACTIVE_TX \
if (cur_tx_id == UINT64_MAX) { \
return WEAVER_CLIENT_NOACTIVETX; \
}
#define CHECK_AUX_INDEX \
if (!AuxIndex) { \
return WEAVER_CLIENT_NOAUXINDEX; \
}
weaver_client_returncode
client :: fail_tx(weaver_client_returncode code)
{
cur_tx_id = UINT64_MAX;
cur_tx.clear();
return code;
}
weaver_client_returncode
client :: begin_tx()
{
CHECK_INIT;
if (cur_tx_id != UINT64_MAX) {
return WEAVER_CLIENT_ACTIVETX;
} else {
cur_tx_id = ++tx_id_ctr;
return WEAVER_CLIENT_SUCCESS;
}
}
void
client :: print_cur_tx()
{
if (!logging) {
return;
}
CLIENTLOG << "Current transaction details:" << std::endl;
for (auto upd: cur_tx) {
switch (upd->type) {
case transaction::NODE_CREATE_REQ:
CLIENTLOG << "NODE CREATE" << std::endl;
CLIENTLOG << "\thandle = " << upd->handle << std::endl;
break;
case transaction::EDGE_CREATE_REQ:
CLIENTLOG << "EDGE CREATE" << std::endl;
CLIENTLOG << "\thandle = " << upd->handle;
CLIENTLOG << "\tstart node,alias = " << upd->handle1 << "," << upd->alias1
<< " end node,alias = " << upd->handle2 << "," << upd->alias2 << std::endl;
break;
case transaction::NODE_DELETE_REQ:
CLIENTLOG << "NODE DELETE" << std::endl;
CLIENTLOG << "\tnode,alias = " << upd->handle1 << "," << upd->alias1 << std::endl;
break;
case transaction::EDGE_DELETE_REQ:
CLIENTLOG << "EDGE DELETE" << std::endl;
CLIENTLOG << "\tedge = " << upd->handle1 << std::endl;
CLIENTLOG << "\tnode,alias = " << upd->handle2 << "," << upd->alias2 << std::endl;
break;
case transaction::NODE_SET_PROPERTY:
CLIENTLOG << "NODE SET PROPERTY" << std::endl;
CLIENTLOG << "\tnode,alias = " << upd->handle1 << "," << upd->alias1 << std::endl;
CLIENTLOG << "\tkey,value = " << *upd->key << "," << *upd->value << std::endl;
break;
case transaction::EDGE_SET_PROPERTY:
CLIENTLOG << "EDGE SET PROPERTY" << std::endl;
CLIENTLOG << "\tedge = " << upd->handle1 << std::endl;
CLIENTLOG << "\tnode,alias = " << upd->handle2 << "," << upd->alias2 << std::endl;
CLIENTLOG << "\tkey,value = " << *upd->key << "," << *upd->value << std::endl;
break;
case transaction::ADD_AUX_INDEX:
CLIENTLOG << "ADD ALIAS" << std::endl;
CLIENTLOG << "\tnode,alias = " << upd->handle1 << "," << upd->handle << std::endl;
break;
}
}
}
weaver_client_returncode
client :: create_node(std::string &handle, const std::vector<std::string> &aliases)
{
CHECK_INIT;
CHECK_ACTIVE_TX;
std::shared_ptr<pending_update> upd = std::make_shared<pending_update>();
upd->type = transaction::NODE_CREATE_REQ;
if (handle == "") {
handle = generate_handle();
}
upd->handle = handle;
cur_tx.emplace_back(upd);
for (const std::string &a: aliases) {
add_alias(a, upd->handle);
}
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: create_edge(std::string &handle, const std::string &node1, const std::string &node1_alias, const std::string &node2, const std::string &node2_alias)
{
CHECK_INIT;
CHECK_ACTIVE_TX;
std::shared_ptr<pending_update> upd = std::make_shared<pending_update>();
upd->type = transaction::EDGE_CREATE_REQ;
if (handle == "") {
handle = generate_handle();
}
upd->handle = handle;
upd->handle1 = node1;
upd->handle2 = node2;
upd->alias1 = node1_alias;
upd->alias2 = node2_alias;
cur_tx.emplace_back(upd);
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: delete_node(const std::string &node, const std::string &alias)
{
CHECK_INIT;
CHECK_ACTIVE_TX;
std::shared_ptr<pending_update> upd = std::make_shared<pending_update>();
upd->type = transaction::NODE_DELETE_REQ;
upd->handle1 = node;
upd->alias1 = alias;
cur_tx.emplace_back(upd);
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: delete_edge(const std::string &edge, const std::string &node, const std::string &alias)
{
CHECK_INIT;
CHECK_ACTIVE_TX;
std::shared_ptr<pending_update> upd = std::make_shared<pending_update>();
upd->type = transaction::EDGE_DELETE_REQ;
upd->handle1 = edge;
upd->handle2 = node;
upd->alias2 = alias;
cur_tx.emplace_back(upd);
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: set_node_property(const std::string &node, const std::string &alias, std::string key, std::string value)
{
CHECK_INIT;
CHECK_ACTIVE_TX;
std::shared_ptr<pending_update> upd = std::make_shared<pending_update>();
upd->type = transaction::NODE_SET_PROPERTY;
upd->handle1 = node;
upd->alias1 = alias;
upd->key.reset(new std::string(std::move(key)));
upd->value.reset(new std::string(std::move(value)));
cur_tx.emplace_back(upd);
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: set_edge_property(const std::string &node, const std::string &alias, const std::string &edge,
std::string key, std::string value)
{
CHECK_INIT;
CHECK_ACTIVE_TX;
std::shared_ptr<pending_update> upd = std::make_shared<pending_update>();
upd->type = transaction::EDGE_SET_PROPERTY;
upd->handle1 = edge;
upd->handle2 = node;
upd->alias2 = alias;
upd->key.reset(new std::string(std::move(key)));
upd->value.reset(new std::string(std::move(value)));
cur_tx.emplace_back(upd);
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: add_alias(const std::string &alias, const std::string &node)
{
CHECK_INIT;
CHECK_ACTIVE_TX;
CHECK_AUX_INDEX;
std::shared_ptr<pending_update> upd = std::make_shared<pending_update>();
upd->type = transaction::ADD_AUX_INDEX;
upd->handle = alias;
upd->handle1 = node;
cur_tx.emplace_back(upd);
return WEAVER_CLIENT_SUCCESS;
}
#undef CHECK_AUX_INDEX
weaver_client_returncode
client :: end_tx()
{
CHECK_INIT;
CHECK_ACTIVE_TX;
bool retry;
bool success;
weaver_client_returncode tx_code = WEAVER_CLIENT_SUCCESS;
message::message recv_msg;
// currently no retry on timeout/disrupted, pass error to client
// so it is responsibility of client to ensure that they do not reexec tx that was completed
do {
message::message msg;
msg.prepare_message(message::CLIENT_TX_INIT, nullptr, cur_tx_id, cur_tx);
busybee_returncode send_code = send_coord(msg.buf);
if (send_code == BUSYBEE_DISRUPTED) {
reconfigure();
return fail_tx(WEAVER_CLIENT_DISRUPTED);
} else if (send_code != BUSYBEE_SUCCESS) {
return fail_tx(WEAVER_CLIENT_INTERNALMSGERROR);
}
busybee_returncode recv_code = recv_coord(&recv_msg.buf);
switch (recv_code) {
case BUSYBEE_TIMEOUT:
case BUSYBEE_DISRUPTED:
reconfigure();
return fail_tx(WEAVER_CLIENT_DISRUPTED);
break;
case BUSYBEE_SUCCESS:
success = true;
retry = false;
break;
default:
success = false;
retry = false;
}
} while (retry);
if (success) {
message::msg_type mtype = recv_msg.unpack_message_type();
assert(mtype == message::CLIENT_TX_SUCCESS || mtype == message::CLIENT_TX_ABORT);
if (mtype == message::CLIENT_TX_ABORT) {
success = false;
tx_code = WEAVER_CLIENT_ABORT;
}
}
if (!success) {
print_cur_tx();
}
cur_tx_id = UINT64_MAX;
cur_tx.clear();
return tx_code;
}
weaver_client_returncode
client :: abort_tx()
{
CHECK_INIT;
CHECK_ACTIVE_TX;
cur_tx_id = UINT64_MAX;
cur_tx.clear();
return WEAVER_CLIENT_SUCCESS;
}
#undef CHECK_ACTIVE_TX
weaver_client_returncode
client :: run_node_prog(const std::string &prog_type,
std::vector<std::pair<std::string, std::shared_ptr<Node_Parameters_Base>>> &initial_args,
std::shared_ptr<Node_Parameters_Base> &return_param)
{
CHECK_INIT;
message::message msg;
busybee_returncode send_code, recv_code;
auto prog_iter = m_dyn_prog_map.find(prog_type);
if (prog_iter == m_dyn_prog_map.end()) {
WDEBUG << "did not find node prog " << prog_type << std::endl;
return WEAVER_CLIENT_BADPROGTYPE;
}
void *prog_handle = (void*)prog_iter->second.get();
#ifdef weaver_benchmark_
msg.prepare_message(message::CLIENT_NODE_PROG_REQ, prog_handle, prog_type, initial_args);
send_code = send_coord(msg.buf);
if (send_code != BUSYBEE_SUCCESS) {
return WEAVER_CLIENT_INTERNALMSGERROR;
}
recv_code = recv_coord(&msg.buf);
if (recv_code != BUSYBEE_SUCCESS) {
return WEAVER_CLIENT_INTERNALMSGERROR;
}
#else
bool retry;
do {
msg.prepare_message(message::CLIENT_NODE_PROG_REQ, prog_handle, prog_type, initial_args);
send_code = send_coord(msg.buf);
if (send_code == BUSYBEE_DISRUPTED) {
reconfigure();
return WEAVER_CLIENT_DISRUPTED;
} else if (send_code != BUSYBEE_SUCCESS) {
return WEAVER_CLIENT_INTERNALMSGERROR;
}
recv_code = recv_coord(&msg.buf);
switch (recv_code) {
case BUSYBEE_TIMEOUT:
case BUSYBEE_DISRUPTED:
reconfigure();
retry = true;
break;
case BUSYBEE_SUCCESS:
if (msg.unpack_message_type() == message::NODE_PROG_RETRY) {
retry = true;
} else {
retry = false;
}
break;
default:
return WEAVER_CLIENT_INTERNALMSGERROR;
}
} while (retry);
#endif
std::string return_prog_type;
uint64_t ignore_req_id, ignore_vt_ptr;
auto ret_status = msg.unpack_message_type();
if (ret_status == message::NODE_PROG_RETURN) {
msg.unpack_message(message::NODE_PROG_RETURN,
prog_handle,
return_prog_type,
ignore_req_id,
ignore_vt_ptr,
return_param);
assert(return_prog_type == prog_type);
return WEAVER_CLIENT_SUCCESS;
} else {
return WEAVER_CLIENT_NOTFOUND;
}
}
weaver_client_returncode
client :: traverse_props_program(std::vector<std::pair<std::string, node_prog::traverse_props_params>> &initial_args,
node_prog::traverse_props_params &return_param)
{
std::vector<std::pair<std::string, std::shared_ptr<Node_Parameters_Base>>> ptr_args;
for (auto &p: initial_args) {
if (p.second.node_props.size() != (p.second.edge_props.size()+1)) {
return WEAVER_CLIENT_LOGICALERROR;
}
auto param_ptr = std::make_shared<node_prog::traverse_props_params>(p.second);
auto base_ptr = std::dynamic_pointer_cast<Node_Parameters_Base>(param_ptr);
ptr_args.emplace_back(std::make_pair(p.first, base_ptr));
}
std::shared_ptr<Node_Parameters_Base> return_base_ptr;
weaver_client_returncode retcode = run_node_prog(m_built_in_progs["traverse_props_prog"], ptr_args, return_base_ptr);
auto return_param_ptr = std::dynamic_pointer_cast<node_prog::traverse_props_params>(return_base_ptr);
return_param = *return_param_ptr;
return retcode;
}
weaver_client_returncode
client :: nn_infer(std::string &start_node,
std::string &end_node,
node_prog::nn_params &args,
node_prog::nn_params &ret)
{
args.network_description.first = start_node;
args.network_description.second = end_node;
auto param_ptr = std::make_shared<node_prog::nn_params>(args);
auto base_ptr = std::dynamic_pointer_cast<Node_Parameters_Base>(param_ptr);
std::vector<std::pair<std::string, std::shared_ptr<Node_Parameters_Base>>> ptr_args(1, std::make_pair(start_node, base_ptr));
std::shared_ptr<Node_Parameters_Base> return_base_ptr;
weaver_client_returncode retcode = run_node_prog(m_built_in_progs["nn_infer_prog"], ptr_args, return_base_ptr);
auto return_param_ptr = std::dynamic_pointer_cast<node_prog::nn_params>(return_base_ptr);
ret = *return_param_ptr;
return retcode;
}
weaver_client_returncode
client :: register_node_prog(const std::string &so_file,
std::string &prog_handle)
{
std::ifstream read_f;
read_f.open(so_file, std::ifstream::in | std::ifstream::binary);
if (!read_f) {
return WEAVER_CLIENT_NOTFOUND;
}
read_f.seekg(0, read_f.end);
size_t file_sz = read_f.tellg();
read_f.seekg(0, read_f.beg);
std::vector<uint8_t> buf(file_sz);
read_f.read((char*)&buf[0], file_sz);
read_f.close();
// dlsym in to client for (un)packing functions
void *prog_ptr = dlopen(so_file.c_str(), RTLD_NOW);
if (prog_ptr == NULL) {
WDEBUG << "dlopen error: " << dlerror() << std::endl;
return WEAVER_CLIENT_DLOPENERROR;
}
// calc prog handle as sha256(so file)
prog_handle = weaver_util::sha256_chararr(buf, file_sz);
// dlsym all functions and store in a client ds
auto prog_table = std::make_shared<dynamic_prog_table>(prog_ptr);
m_dyn_prog_map[prog_handle] = prog_table;
// send register node prog request to gatekeeper
message::message msg;
msg.prepare_message(message::REGISTER_NODE_PROG, nullptr, prog_handle, buf);
send_coord(msg.buf);
busybee_returncode recv_code = recv_coord(&msg.buf);
if (recv_code != BUSYBEE_SUCCESS) {
return WEAVER_CLIENT_INTERNALMSGERROR;
}
auto ret_status = msg.unpack_message_type();
if (ret_status == message::REGISTER_NODE_PROG_SUCCESSFUL) {
return WEAVER_CLIENT_SUCCESS;
} else {
assert(ret_status == message::REGISTER_NODE_PROG_FAILED);
return WEAVER_CLIENT_DLOPENERROR;
}
}
weaver_client_returncode
client :: start_migration()
{
CHECK_INIT;
message::message msg;
msg.prepare_message(message::START_MIGR);
send_coord(msg.buf);
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: single_stream_migration()
{
CHECK_INIT;
message::message msg;
msg.prepare_message(message::ONE_STREAM_MIGR);
send_coord(msg.buf);
if (recv_coord(&msg.buf) != BUSYBEE_SUCCESS) {
return WEAVER_CLIENT_INTERNALMSGERROR;
}
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: exit_weaver()
{
CHECK_INIT;
message::message msg;
msg.prepare_message(message::EXIT_WEAVER);
send_coord(msg.buf);
return WEAVER_CLIENT_SUCCESS;
}
weaver_client_returncode
client :: get_node_count(std::vector<uint64_t> &node_count)
{
CHECK_INIT;
node_count.clear();
while(true) {
message::message msg;
msg.prepare_message(message::CLIENT_NODE_COUNT);
busybee_returncode send_code = send_coord(msg.buf);
if (send_code == BUSYBEE_DISRUPTED) {
reconfigure();
continue;
} else if (send_code != BUSYBEE_SUCCESS) {
return WEAVER_CLIENT_INTERNALMSGERROR;
}
busybee_returncode recv_code = recv_coord(&msg.buf);
switch (recv_code) {
case BUSYBEE_DISRUPTED:
case BUSYBEE_TIMEOUT:
reconfigure();
break;
case BUSYBEE_SUCCESS:
msg.unpack_message(message::NODE_COUNT_REPLY, nullptr, node_count);
return WEAVER_CLIENT_SUCCESS;
default:
return WEAVER_CLIENT_INTERNALMSGERROR;
}
}
}
#undef CHECK_INIT
bool
client :: aux_index()
{
return AuxIndex;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
busybee_returncode
client :: send_coord(std::auto_ptr<e::buffer> buf)
{
return comm->send(vtid, buf);
}
busybee_returncode
client :: recv_coord(std::auto_ptr<e::buffer> *buf)
{
busybee_returncode ret;
while (true) {
ret = comm->recv(buf);
switch (ret) {
case BUSYBEE_SUCCESS:
case BUSYBEE_TIMEOUT:
return ret;
case BUSYBEE_INTERRUPTED:
continue;
default:
return ret;
}
}
}
#pragma GCC diagnostic pop
std::string
client :: generate_handle()
{
std::string s = std::to_string(handle_ctr++);
s += myid_str;
return s;
}
bool
client :: maintain_sm_connection(replicant_returncode &rc)
{
if (!m_sm.ensure_configuration(&rc))
{
return false;
}
return true;
}
void
client :: reconfigure()
{
uint32_t try_sm = 0;
replicant_returncode rc;
while (!maintain_sm_connection(rc)) {
if (logging) {
if (rc == REPLICANT_INTERRUPTED) {
CLIENTLOG << "signal received";
} else if (rc == REPLICANT_TIMEOUT) {
CLIENTLOG << "operation timed out";
} else {
CLIENTLOG << "coordinator failure: " << m_sm.error_message();
}
CLIENTLOG << "retry sm connection " << try_sm << std::endl;
}
try_sm++;
}
comm.reset(new cl::comm_wrapper(myid, *m_sm.config()));
comm->reconfigure(*m_sm.config());
}
| 28.921123 | 158 | 0.623446 | dubey |
da079fe5b9ed290d7468fcbeab4cfe934049bda4 | 3,742 | cpp | C++ | src/shadereditor/src/shadereditor/vdialogconfig.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/shadereditor/src/shadereditor/vdialogconfig.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/shadereditor/src/shadereditor/vdialogconfig.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z |
#include "cbase.h"
#include "editorCommon.h"
static const char *blendNames[] = {
"None",
"Blend enabled",
"Blend inverted",
"Blend additive",
"Alpha test",
"Alpha to coverage",
};
static const int blendIDx[] = {
ABLEND_NONE,
ABLEND_SIMPLE,
ABLEND_SIMPLE_INVERTED,
ABLEND_ADDITIVE,
ABLEND_ALPHATEST,
ABLEND_ALPHA2COVERAGE,
};
const int numAblendModes = ARRAYSIZE(blendNames);
CDialog_GeneralConfig::CDialog_GeneralConfig(CNodeView *n, Panel *parent) : Frame(parent, "_config") {
pNodeView = n;
GenericShaderData *setup = &n->GetDataForModify();
SetSizeable(false);
SetVisible(true);
SetMouseInputEnabled(true);
SetKeyBoardInputEnabled(true);
SetAutoDelete(true);
Activate();
m_pRadBut_Sm2 = new RadioButton(this, "rad_1", "SM 2.0b");
m_pRadBut_Sm3 = new RadioButton(this, "rad_2", "SM 3.0");
m_pRadBut_Sm2->SetSubTabPosition(1);
m_pRadBut_Sm3->SetSubTabPosition(1);
m_pCBut_DepthTest = new CheckButton(this, "depthtest", "Depth testing");
m_pCBut_DepthWrite = new CheckButton(this, "depthwrite", "Depth writing");
m_pCBut_sRGBWrite = new CheckButton(this, "srgbwrite", "write sRGB");
m_pCBox_AlphaBlend = new ComboBox(this, "alphablend", numAblendModes, false);
for (int i = 0; i < numAblendModes; i++)
m_pCBox_AlphaBlend->AddItem(blendNames[i], NULL);
Assert(numAblendModes == m_pCBox_AlphaBlend->GetItemCount());
m_pCBox_Cullmode = new ComboBox(this, "cullmode", 5, false);
m_pCBox_Cullmode->AddItem("CW", NULL);
m_pCBox_Cullmode->AddItem("CCW", NULL);
//m_pCBox_Cullmode->AddItem( "Double", NULL );
m_pCBox_Cullmode->AddItem("Off", NULL);
LoadControlSettings("shadereditorui/vgui/dialog_config.res");
if (setup->shader->iShaderModel == SM_30)
m_pRadBut_Sm3->SetSelected(true);
else
m_pRadBut_Sm2->SetSelected(true);
m_pCBut_DepthTest->SetSelected(setup->shader->iDepthtestmode == DEPTHTEST_NORMAL);
m_pCBut_DepthWrite->SetSelected(setup->shader->iDepthwritemode == DEPTHWRITE_NORMAL);
m_pCBox_Cullmode->ActivateItem(setup->shader->iCullmode);
m_pCBut_sRGBWrite->SetSelected(setup->shader->bsRGBWrite);
for (int i = 0; i < numAblendModes; i++) {
if (blendIDx[i] == setup->shader->iAlphablendmode) {
m_pCBox_AlphaBlend->ActivateItem(i);
break;
}
}
SetTitle("Shader settings", true);
DoModal();
SetDeleteSelfOnClose(true);
}
CDialog_GeneralConfig::~CDialog_GeneralConfig() {
}
void CDialog_GeneralConfig::OnCommand(const char *cmd) {
if (!Q_stricmp(cmd, "save")) {
OnSave();
Close();
} else if (!Q_stricmp(cmd, "close")) {
Close();
}
}
void CDialog_GeneralConfig::PerformLayout() {
BaseClass::PerformLayout();
SetCloseButtonVisible(false);
SetSize(400, 300);
MoveToCenterOfScreen();
}
void CDialog_GeneralConfig::OnSave() {
Assert(numAblendModes == m_pCBox_AlphaBlend->GetItemCount() &&
m_pCBox_AlphaBlend->GetActiveItem() < numAblendModes);
GenericShaderData *setup = &pNodeView->GetDataForModify();
setup->shader->iAlphablendmode = blendIDx[m_pCBox_AlphaBlend->GetActiveItem()];
setup->shader->iCullmode = m_pCBox_Cullmode->GetActiveItem();
setup->shader->iDepthtestmode = m_pCBut_DepthTest->IsSelected() ? DEPTHTEST_NORMAL : DEPTHTEST_OFF;
setup->shader->iDepthwritemode = m_pCBut_DepthWrite->IsSelected() ? DEPTHWRITE_NORMAL : DEPTHWRITE_OFF;
setup->shader->iShaderModel = m_pRadBut_Sm3->IsSelected() ? SM_30 : SM_20B;
setup->shader->bsRGBWrite = m_pCBut_sRGBWrite->IsSelected();
pNodeView->MakeSolversDirty();
}
| 31.711864 | 107 | 0.683057 | cstom4994 |
da09f66117140485d8d119639c5745821b4e15ff | 2,293 | cpp | C++ | src/game/client/neotokyo/vgui/neoframe.cpp | L-Leite/neotokyo-re | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 4 | 2017-08-29T15:39:53.000Z | 2019-06-04T07:37:48.000Z | src/game/client/neotokyo/vgui/neoframe.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | null | null | null | src/game/client/neotokyo/vgui/neoframe.cpp | Ochii/neotokyo | a45cdcb9027ffe8af72cf1f8e22976375e6b1e0a | [
"Unlicense"
] | 1 | 2021-08-10T20:01:00.000Z | 2021-08-10T20:01:00.000Z | #include "cbase.h"
#include "neoframe.h"
#include <vgui/ISurface.h>
#include "neobutton.h"
#include "neoimagebutton.h"
#include "neoiconpanel.h"
namespace vgui
{
CNeoFrame::CNeoFrame( Panel* parent, const char *panelName ) : Frame( parent, panelName )
{
ISurface* pSurface = surface();
SetScheme( scheme()->LoadSchemeFromFile( "resource/ClientScheme.res", "ClientScheme" ) );
m_iCornerTextureId = pSurface->CreateNewTextureID();
pSurface->DrawSetTextureFile( m_iCornerTextureId, "vgui/ngui_corner", true, false );
m_iTitleBarTextureId = pSurface->CreateNewTextureID();
pSurface->DrawSetTextureFile( m_iTitleBarTextureId, "vgui/ngui_titlebar", true, false );
m_iBodyTextureId = pSurface->CreateNewTextureID();
pSurface->DrawSetTextureFile( m_iBodyTextureId, "vgui/ngui_body", true, false );
SetMoveable( false );
SetSizeable( false );
SetPaintBackgroundEnabled( false );
InvalidateLayout();
}
CNeoFrame::~CNeoFrame()
{
}
bool CNeoFrame::IsVisible()
{
return BaseClass::IsVisible();
}
void CNeoFrame::SetParent( VPANEL newParent )
{
BaseClass::SetParent( newParent );
}
void CNeoFrame::ApplySchemeSettings( IScheme *pScheme )
{
}
void CNeoFrame::PaintBackground()
{
BaseClass::PaintBackground();
}
void CNeoFrame::Paint()
{
int wide, tall;
GetSize( wide, tall );
surface()->DrawSetColor( 255, 255, 255, 255 );
surface()->DrawSetTexture( m_iCornerTextureId );
surface()->DrawTexturedRect( 0, 0, 16, 16 );
surface()->DrawSetTexture( m_iTitleBarTextureId );
surface()->DrawTexturedRect( 16, 0, wide, 16 );
surface()->DrawSetTexture( m_iBodyTextureId );
surface()->DrawTexturedRect( 0, 16, wide, tall );
surface()->DrawSetColor( 0, 0, 0, 255 );
surface()->DrawFilledRect( 0, tall - 1, wide, tall );
surface()->DrawFilledRect( wide - 1, 0, wide, tall );
BaseClass::Paint();
}
Panel *CNeoFrame::CreateControlByName( const char *controlName )
{
if ( !V_strcmp( controlName, "NButton" ) || !V_strcmp( controlName, "Button" ) )
return new CNButton( nullptr, "NButton", "" );
else if ( !V_strcmp( controlName, "NImageButton" ) )
return new CNImageButton( nullptr, "NImageButton", "" );
else if ( !V_strcmp( controlName, "IconPanel" ) )
return new IconPanel( this, "IconPanel" );
return BaseClass::CreateControlByName( controlName );
}
} | 24.923913 | 90 | 0.71522 | L-Leite |
da0b6cc6de542adb2130739b6051d69e196ff3e7 | 5,195 | cc | C++ | nb/mbe/internal/vocoder/ch_decode.cc | go-voice/voice | f5275d2171e170f3712897734a43fc3c214c4840 | [
"MIT"
] | null | null | null | nb/mbe/internal/vocoder/ch_decode.cc | go-voice/voice | f5275d2171e170f3712897734a43fc3c214c4840 | [
"MIT"
] | null | null | null | nb/mbe/internal/vocoder/ch_decode.cc | go-voice/voice | f5275d2171e170f3712897734a43fc3c214c4840 | [
"MIT"
] | null | null | null | /*
* Project 25 IMBE Encoder/Decoder Fixed-Point implementation
* Developed by Pavel Yazev E-mail: pyazev@gmail.com
* Version 1.0 (c) Copyright 2009
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* The software 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; see the file COPYING. If not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Boston, MA
* 02110-1301, USA.
*/
#include "typedef.h"
#include "globals.h"
#include "imbe.h"
#include "basic_op.h"
#include "ch_decode.h"
#include "aux_sub.h"
void decode_frame_vector(IMBE_PARAM *imbe_param, Word16 *frame_vector)
{
Word16 bit_stream[BIT_STREAM_LEN];
Word16 i, vec_num, tmp, tmp1, tmp2, bit_thr, shift;
Word16 *b_ptr, *ba_ptr, index0;
Word32 L_tmp;
imbe_param->b_vec[0] = (shr(frame_vector[0], 4) & 0xFC) | (shr(frame_vector[7], 1) & 0x3);
if (imbe_param->b_vec[0] < 0 || imbe_param->b_vec[0] > 207)
return; // If we return here IMBE parameters from previous frame will be used (frame repeating)
tmp = ((imbe_param->b_vec[0] & 0xFF) << 1) + 0x4F; // Convert b_vec[0] to unsigned Q15.1 format and add 39.5
//imbe_param->ff = 4./((double)imbe_param->b_vec[0] + 39.5);
// Calculate fundamental frequency with higher precession
shift = norm_s(tmp);
tmp1 = tmp << shift;
tmp2 = div_s(0x4000, tmp1);
imbe_param->fund_freq = L_shr(L_deposit_h(tmp2), 11 - shift);
L_tmp = L_sub(0x40000000, L_mult(tmp1, tmp2));
tmp2 = div_s(extract_l(L_shr(L_tmp, 2)), tmp1);
L_tmp = L_shr(L_deposit_l(tmp2), 11 - shift - 2);
imbe_param->fund_freq = L_add(imbe_param->fund_freq, L_tmp);
//printf("%X %X \n", imbe_param->fund_freq, (Word32)(imbe_param->ff * (double)((UWord32)1<<31)));
tmp = (tmp + 0x2) >> 3; // Calculate (b0 + 39.5 + 1)/4
imbe_param->num_harms = ((UWord32)CNST_0_9254_Q0_16 * tmp) >> 16;
if(imbe_param->num_harms <= 36)
imbe_param->num_bands = extract_h((UWord32)(imbe_param->num_harms + 2) * CNST_0_33_Q0_16); // fix((L+2)/3)
else
imbe_param->num_bands = NUM_BANDS_MAX;
// Convert input vector (from b_3 to b_L+1) to bit stream
bit_stream[0] = (frame_vector[0] & 0x4)?1:0;
bit_stream[1] = (frame_vector[0] & 0x2)?1:0;
bit_stream[2] = (frame_vector[0] & 0x1)?1:0;
bit_stream[BIT_STREAM_LEN - 3] = (frame_vector[7] & 0x40)?1:0;
bit_stream[BIT_STREAM_LEN - 2] = (frame_vector[7] & 0x20)?1:0;
bit_stream[BIT_STREAM_LEN - 1] = (frame_vector[7] & 0x10)?1:0;
index0 = 3 + 3 * 12 - 1;
for(vec_num = 3; vec_num >= 1; vec_num--)
{
tmp = frame_vector[vec_num];
for(i = 0; i < 12; i++)
{
bit_stream[index0] = (tmp & 0x1)?1:0;
tmp >>= 1;
index0--;
}
}
index0 = 3 + 3 * 12 + 3 * 11 - 1;
for(vec_num = 6; vec_num >= 4; vec_num--)
{
tmp = frame_vector[vec_num];
for(i = 0; i < 11; i++)
{
bit_stream[index0] = (tmp & 0x1)?1:0;
tmp >>= 1;
index0--;
}
}
// Rebuild b1
index0 = 3 + 3 * 12;
tmp = 0;
for(i = 0; i < imbe_param->num_bands; i++)
tmp = (tmp << 1) | bit_stream[index0++];
imbe_param->b_vec[1] = tmp;
// Rebuild b2
tmp = 0;
tmp |= bit_stream[index0++] << 1;
tmp |= bit_stream[index0++];
imbe_param->b_vec[2] = (frame_vector[0] & 0x38) | (tmp << 1) | (shr(frame_vector[7], 3) & 0x01);
// Shift the rest of sequence
tmp = imbe_param->num_bands + 2; // shift
for(; index0 < BIT_STREAM_LEN; index0++)
bit_stream[index0 - tmp] = bit_stream[index0];
// Priority ReScanning
b_ptr = &imbe_param->b_vec[3];
ba_ptr = imbe_param->bit_alloc;
for(i = 0; i < B_NUM; i++)
ba_ptr[i] = b_ptr[i] = 0;
// Unpack bit allocation table's item
get_bit_allocation(imbe_param->num_harms, imbe_param->bit_alloc);
index0 = 0;
bit_thr = (imbe_param->num_harms == 0xb)?9:ba_ptr[0];
while(index0 < BIT_STREAM_LEN - imbe_param->num_bands - 2)
{
for(i = 0; i < imbe_param->num_harms - 1; i++)
if(bit_thr && bit_thr <= ba_ptr[i])
b_ptr[i] = (b_ptr[i] << 1) | bit_stream[index0++];
bit_thr--;
}
// Synchronization Bit Decoding
imbe_param->b_vec[imbe_param->num_harms + 2] = frame_vector[7] & 1;
}
void v_uv_decode(IMBE_PARAM *imbe_param)
{
Word16 num_harms;
Word16 num_bands;
Word16 vu_vec, *p_v_uv_dsn, mask, i, uv_cnt;
num_harms = imbe_param->num_harms;
num_bands = imbe_param->num_bands;
vu_vec = imbe_param->b_vec[1];
p_v_uv_dsn = imbe_param->v_uv_dsn;
mask = 1 << (num_bands - 1);
v_zap(p_v_uv_dsn, NUM_HARMS_MAX);
i = 0; uv_cnt = 0;
while(num_harms--)
{
if(vu_vec & mask)
*p_v_uv_dsn++ = 1;
else
{
*p_v_uv_dsn++ = 0;
uv_cnt++;
}
if(++i == 3)
{
if(num_bands > 1)
{
num_bands--;
mask >>= 1;
}
i = 0;
}
}
imbe_param->l_uv = uv_cnt;
}
| 27.930108 | 146 | 0.635419 | go-voice |
da0f748b42735aea05519bdc45685d64c52fff8c | 744 | cpp | C++ | Challenge-2021-06/03_maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-06/03_maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-06/03_maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | #include "../header.h"
class Solution {
public:
int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& verticalCuts) {
horizontalCuts.push_back(0);
verticalCuts.push_back(0);
horizontalCuts.push_back(h);
verticalCuts.push_back(w);
sort(horizontalCuts.begin(), horizontalCuts.end());
sort(verticalCuts.begin(), verticalCuts.end());
long mh = 0;
for (int i = 0; i < horizontalCuts.size() - 1; ++i) {
mh = max(mh, (long)(horizontalCuts[i+1] - horizontalCuts[i]));
}
long mw = 0;
for (int i = 0; i < verticalCuts.size() - 1; ++i) {
mw = max(mw, (long)(verticalCuts[i+1] - verticalCuts[i]));
}
return (mh * mw) % 1000000007;
}
}; | 33.818182 | 87 | 0.581989 | qiufengyu |
da1d2d957ca4231f3acc9b11a9d19591616097aa | 6,373 | cpp | C++ | tests/coreTests/TestHMDNSResult.cpp | tkraiser/NetCHASM | 6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4 | [
"Apache-2.0"
] | 13 | 2019-06-06T01:14:30.000Z | 2022-03-03T05:57:51.000Z | tests/coreTests/TestHMDNSResult.cpp | tkraiser/NetCHASM | 6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4 | [
"Apache-2.0"
] | 7 | 2019-07-23T18:31:20.000Z | 2021-05-26T12:57:34.000Z | tests/coreTests/TestHMDNSResult.cpp | tkraiser/NetCHASM | 6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4 | [
"Apache-2.0"
] | 12 | 2019-06-27T13:58:03.000Z | 2021-12-23T07:43:06.000Z | // Copyright 2019, Oath Inc.
// Licensed under the terms of the Apache 2.0 license. See LICENSE file in the root of the distribution for licensing details.
#include "TestHMDNSResult.h"
#include "HMDNSCache.h"
#include "HMStateManager.h"
#include "HMEventLoopQueue.h"
#include "common.h"
#include <unistd.h>
#include <arpa/inet.h>
#include <set>
using namespace std;
CPPUNIT_TEST_SUITE_REGISTRATION(TESTNAME);
void TESTNAME::setUp()
{
setupCommon();
}
void TESTNAME::tearDown()
{
teardownCommon();
}
void TESTNAME::test_get_address()
{
HMDNSResult results;
HMIPAddress ip, ip_recv;
in_addr addr;
addr.s_addr = inet_addr("192,168.1.1");
ip.set((char*) &addr, AF_INET);
set<HMIPAddress> ips;
ips.insert(ip);
results.updateQuery(ips);
CPPUNIT_ASSERT_EQUAL(true, results.getAddress(ip_recv));
CPPUNIT_ASSERT_EQUAL(ip.addr4(), ip_recv.addr4());
}
void TESTNAME::test_get_addresses()
{
HMDNSResult results;
HMIPAddress ip, ip1, ip_recv;
in_addr addr;
set<HMIPAddress> ips;
addr.s_addr = inet_addr("192.168.1.1");
ip.set((char*) &addr, AF_INET);
ips.insert(ip);
addr.s_addr = inet_addr("192.168.1.2");
ip1.set((char*) &addr, AF_INET);
ips.insert(ip1);
results.updateQuery(ips);
set<HMIPAddress> addresses;
CPPUNIT_ASSERT_EQUAL(true, results.getAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(2, (int )addresses.size());
CPPUNIT_ASSERT(addresses.find(ip) != addresses.end());
CPPUNIT_ASSERT(addresses.find(ip1) != addresses.end());
}
void TESTNAME::test_next_query()
{
HMDNSResult results;
uint64_t query_timeout = 500;
results.updateTimeouts(100, query_timeout);
HMTimeStamp start_time = results.startQuery();
HMTimeStamp next_time = results.nextQueryTime();
CPPUNIT_ASSERT_EQUAL(start_time.getTimeSinceEpoch() + query_timeout,
next_time.getTimeSinceEpoch());
CPPUNIT_ASSERT_EQUAL(HM_CHECK_IN_PROGRESS, results.getQueryState());
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
next_time = results.nextQueryTime();
CPPUNIT_ASSERT(
(start_time.getTimeSinceEpoch() + query_timeout)
< next_time.getTimeSinceEpoch());
CPPUNIT_ASSERT_EQUAL(HM_CHECK_IN_PROGRESS, results.getQueryState());
}
void TESTNAME::test_next_query1()
{
HMDNSResult results;
uint64_t dns_timeout = 500;
results.updateTimeouts(dns_timeout, 100);
HMTimeStamp result_time = HMTimeStamp::now();
results.finishQuery(true);
HMTimeStamp next_time = results.nextQueryTime();
CPPUNIT_ASSERT(
(result_time.getTimeSinceEpoch() + dns_timeout)
>= next_time.getTimeSinceEpoch());
CPPUNIT_ASSERT_EQUAL(HM_CHECK_INACTIVE, results.getQueryState());
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
next_time = results.nextQueryTime();
CPPUNIT_ASSERT(
(result_time.getTimeSinceEpoch() + dns_timeout)
< next_time.getTimeSinceEpoch());
CPPUNIT_ASSERT_EQUAL(HM_CHECK_INACTIVE, results.getQueryState());
}
void TESTNAME::test_next_query2()
{
HMDNSResult results;
uint64_t dns_timeout = 500;
results.updateTimeouts(dns_timeout, 100);
HMTimeStamp result_time = HMTimeStamp::now();
results.finishQuery(false);
HMTimeStamp next_time = results.nextQueryTime();
CPPUNIT_ASSERT(
(result_time.getTimeSinceEpoch() + dns_timeout)
>= next_time.getTimeSinceEpoch());
CPPUNIT_ASSERT_EQUAL(HM_CHECK_FAILED, results.getQueryState());
}
void TESTNAME::test_queue_query()
{
HMDNSResult results;
results.queueQuery();
CPPUNIT_ASSERT_EQUAL(HM_CHECK_QUEUED, results.getQueryState());
}
void TESTNAME::test_get_exp_addresses()
{
HMDNSResult results;
set<HMIPAddress> ips;
HMIPAddress ip, ip1, ip_recv;
in_addr addr;
addr.s_addr = inet_addr("192.168.1.1");
ip.set((char*) &addr, AF_INET);
addr.s_addr = inet_addr("192.168.1.2");
ip1.set((char*) &addr, AF_INET);
ips.insert(ip);
ips.insert(ip1);
results.updateQuery(ips);
set<HMIPAddress> addresses;
CPPUNIT_ASSERT_EQUAL(true, results.getAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(2, (int )addresses.size());
CPPUNIT_ASSERT(addresses.find(ip) != addresses.end());
CPPUNIT_ASSERT(addresses.find(ip1) != addresses.end());
HMIPAddress ip2, ip3;
ips.clear();
addr.s_addr = inet_addr("192.168.1.3");
ip2.set((char*) &addr, AF_INET);
addr.s_addr = inet_addr("192.168.1.4");
ip3.set((char*) &addr, AF_INET);
ips.insert(ip2);
ips.insert(ip3);
results.updateQuery(ips);
addresses.clear();
CPPUNIT_ASSERT_EQUAL(true, results.getAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(2, (int )addresses.size());
CPPUNIT_ASSERT(addresses.find(ip2) != addresses.end());
CPPUNIT_ASSERT(addresses.find(ip3) != addresses.end());
addresses.clear();
CPPUNIT_ASSERT_EQUAL(true, results.getExpiredAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(2, (int )addresses.size());
CPPUNIT_ASSERT(addresses.find(ip) != addresses.end());
CPPUNIT_ASSERT(addresses.find(ip1) != addresses.end());
results.updateQuery(ips);
addresses.clear();
CPPUNIT_ASSERT_EQUAL(true, results.getAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(2, (int )addresses.size());
CPPUNIT_ASSERT(addresses.find(ip2) != addresses.end());
CPPUNIT_ASSERT(addresses.find(ip3) != addresses.end());
addresses.clear();
CPPUNIT_ASSERT_EQUAL(false, results.getExpiredAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(0, (int )addresses.size());
HMIPAddress ip4;
ips.clear();
addr.s_addr = inet_addr("192.168.1.4");
ip3.set((char*) &addr, AF_INET);
addr.s_addr = inet_addr("192.168.1.5");
ip4.set((char*) &addr, AF_INET);
ips.insert(ip3);
ips.insert(ip4);
results.updateQuery(ips);
addresses.clear();
CPPUNIT_ASSERT_EQUAL(true, results.getAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(2, (int )addresses.size());
CPPUNIT_ASSERT(addresses.find(ip3) != addresses.end());
CPPUNIT_ASSERT(addresses.find(ip4) != addresses.end());
addresses.clear();
CPPUNIT_ASSERT_EQUAL(true, results.getExpiredAddresses(addresses));
CPPUNIT_ASSERT_EQUAL(1, (int )addresses.size());
CPPUNIT_ASSERT(addresses.find(ip2) != addresses.end());
}
| 32.025126 | 126 | 0.694649 | tkraiser |
da1d851d028d3d7b0ca854bcbbe15e803d9b711e | 2,350 | cpp | C++ | src/main/cpp/Commands/DriveWithJoystick.cpp | Volxz/barebonesFRC | db22e69f66b0606142beb55615147505f56e8cd4 | [
"MIT"
] | 2 | 2018-07-28T17:30:42.000Z | 2018-09-12T18:14:20.000Z | src/main/cpp/Commands/DriveWithJoystick.cpp | frc5024/Prototype | cf219c7354a6258f55717a28572ddc2d3437ac3f | [
"MIT"
] | 2 | 2018-09-23T01:03:48.000Z | 2019-08-30T19:11:10.000Z | src/main/cpp/Commands/DriveWithJoystick.cpp | frc5024/Prototype | cf219c7354a6258f55717a28572ddc2d3437ac3f | [
"MIT"
] | 2 | 2018-07-28T14:53:16.000Z | 2018-09-20T19:52:51.000Z | // Include Required Files
#include <Commands/DriveWithJoystick.hpp> // Header File
#include <math.h> // STD math lib
#include <Utilities/Log.hpp> // LOG tool. Used for printing to the RIOlog console
#include "../RobotCFG.hpp" // Robot-wide configuration file
DriveWithJoystick::DriveWithJoystick() {
LOG("[DriveWithJoystick] Constructed");
if (CommandBase::pDriveTrain != nullptr) {
Requires(CommandBase::pDriveTrain);
} else {
LOG("[DriveWithJoystick] driveTrain is null!");
}
return;
}
DriveWithJoystick::~DriveWithJoystick() {
LOG("[DriveWithJoystick] Destroyed");
return;
}
void DriveWithJoystick::Initialize() {
LOG("[DriveWithJoystick] Initialized");
// Store pointer to SmartDashboard in table
table = NetworkTable::GetTable("SmartDashboard");
this->isReverse = false;
return;
}
void DriveWithJoystick::Execute() {
// Pointer to Xbox Controller
frc::XboxController* pJoyDrive = CommandBase::pOI->GetJoystickDrive();
// Trigger Reverse Mode if X Button Tapped
if (pJoyDrive->GetXButtonReleased()) {
this->isReverse = !this->isReverse;
}
// The Y-axis goes from -1 (forward) to 1 (backwards) but we want to
// set motor from 1 (forward) to -1 (reverse) so multiply by -1
double xSpeed = pJoyDrive->GetY(XboxController::kLeftHand) * -1; // Speed = Joustick Y Axis
double zRotation = pJoyDrive->GetX(XboxController::kLeftHand); // Rotation = Joystick X Axis
// Set Slow and Reverse Modes
double dSlow = (pJoyDrive->GetBumper(XboxController::kRightHand)) ? 0.5 : 1;
double dReverse = (this->isReverse) ? -1 : 1;
// Joystick Deadzone
if (fabs(xSpeed) <= XBOX_DEADZONE_LEFT_JOY) {
xSpeed = 0.0;
}
if (fabs(zRotation) <= XBOX_DEADZONE_LEFT_JOY) {
zRotation = 0.0;
}
// Calculate final speed and rotation
xSpeed = (xSpeed * dSlow * dReverse);
zRotation = (zRotation * dSlow);
// If the vision mode is enabled, get info from table and store in vars
if(Vision && pJoyDrive->GetBButton()){
double Speed, Rotation;
std::tie(Speed, Rotation) = GetMotorSpeeds(table); // Get Movement Data
xSpeed = Speed;
zRotation = Rotation;
}
// Call DriveTrain
CommandBase::pDriveTrain->ArcadeDrive(xSpeed, zRotation);
return;
}
bool DriveWithJoystick::IsFinished() {
return false;
}
void DriveWithJoystick::End() {
return;
}
void DriveWithJoystick::Interrupted() {
return;
}
| 25.543478 | 94 | 0.709787 | Volxz |
da1e059a75ec9a2080562f0b71ee8fcfdf63c04d | 51,610 | cpp | C++ | src/Automata/BuchiAutomaton.cpp | vhavlena/ranker | 837a98b462ea92769c82bf6f1678cc40d63937b0 | [
"MIT"
] | null | null | null | src/Automata/BuchiAutomaton.cpp | vhavlena/ranker | 837a98b462ea92769c82bf6f1678cc40d63937b0 | [
"MIT"
] | null | null | null | src/Automata/BuchiAutomaton.cpp | vhavlena/ranker | 837a98b462ea92769c82bf6f1678cc40d63937b0 | [
"MIT"
] | null | null | null | #include "BuchiAutomaton.h"
#include <boost/math/special_functions/factorials.hpp>
/*
* Rename states and symbols of the automaton to numbers (symbols are renamed
* by the explicit map).
* @param mpsymbol Explicit map assigning numbers to original symbols
* @param start Starting number for states
* @return Renamed automaton
*/
template <typename State, typename Symbol>
BuchiAutomaton<int, int> BuchiAutomaton<State, Symbol>::renameAutDict(map<Symbol, int>& mpsymbol, int start)
{
int stcnt = start;
//int symcnt = 0;
std::map<State, int> mpstate;
//std::map<Symbol, int> mpsymbol;
std::set<int> rstate;
Delta<int, int> rtrans;
std::set<int> rfin;
std::set<int> rini;
set<int> rsym;
VecTrans<int, int> ftrans;
this->invRenameMap = std::vector<State>(this->states.size() + start);
for(const auto& st : this->states)
{
auto it = mpstate.find(st);
this->invRenameMap[stcnt] = st;
if(it == mpstate.end())
{
mpstate[st] = stcnt++;
}
}
for(const auto& t : this->alph)
{
rsym.insert(mpsymbol[t]);
}
rstate = Aux::mapSet(mpstate, this->states);
rini = Aux::mapSet(mpstate, this->initials);
rfin = Aux::mapSet(mpstate, this->finals);
for(auto& p : this->trans)
{
int val = mpsymbol[p.first.second];
std::set<int> to = Aux::mapSet(mpstate, p.second);
rtrans.insert({std::make_pair(mpstate[p.first.first], val), to});
}
for(unsigned i = 0; i < this->accTrans.size(); i++)
{
ftrans.push_back({ .from = mpstate[this->accTrans[i].from],
.to = mpstate[this->accTrans[i].to],
.symbol = mpsymbol[this->accTrans[i].symbol] });
}
auto ret = BuchiAutomaton<int, int>(rstate, rfin, rini, rtrans, ftrans, rsym);
this->renameStateMap = mpstate;
this->renameSymbolMap = mpsymbol;
std::set<std::pair<int, int> > rdirSim, roddSim;
for(auto item : this->directSim)
{
rdirSim.insert({mpstate[item.first], mpstate[item.second]});
}
for(auto item : this->oddRankSim)
{
roddSim.insert({mpstate[item.first], mpstate[item.second]});
}
ret.setDirectSim(rdirSim);
ret.setOddRankSim(roddSim);
ret.setAPPattern(this->apsPattern);
return ret;
}
/*
* Abstract function converting the automaton to string.
* @param stateStr Function converting a state to string
* @param symStr Function converting a symbol to string
* @return String representation of the automaton
*/
template <typename State, typename Symbol>
std::string BuchiAutomaton<State, Symbol>::toStringWith(std::function<std::string(State)>& stateStr,
std::function<std::string(Symbol)>& symStr)
{
std::string str = "";
for (auto p : this->initials)
str += stateStr(p) + "\n";
for (auto p : this->trans)
{
for(auto d : p.second)
str += symStr(p.first.second) + "," + stateStr(p.first.first)
+ "->" + stateStr(d) + "\n";
}
for(auto p : this->finals)
str += stateStr(p) + "\n";
for(const auto& tr : this->accTrans)
str += symStr(tr.symbol) + "," + stateStr(tr.from)
+ "->" + stateStr(tr.to) + "\n";
if(str.back() == '\n')
str.pop_back();
return str;
}
/*
* Abstract function converting the automaton to gff format.
* @param stateStr Function converting a state to string
* @param symStr Function converting a symbol to string
* @return Gff representation of the automaton
*/
template <typename State, typename Symbol>
std::string BuchiAutomaton<State, Symbol>::toGffWith(std::function<std::string(State)>& stateStr,
std::function<std::string(Symbol)>& symStr)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
int tid = 0;
std::string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
str += "<structure label-on=\"transition\" type=\"fa\">\n";
str += "<alphabet type=\"classical\">\n";
for(auto s : this->getAlphabet())
str += "<symbol>" + symStr(s) + "</symbol>\n";
str += "</alphabet>\n";
str += "<stateset>\n";
for(auto st : this->states)
str += "<state sid=\"" + stateStr(st) + "\"></state>\n";
str += "</stateset>\n";
str += "<acc type=\"buchi\">\n";
for(auto p : this->finals)
str += "<stateID>" + stateStr(p) + "</stateID>\n";
str += "</acc>\n";
str += "<initialStateSet>\n";
for(auto p : this->initials)
str += "<stateID>" + stateStr(p) + "</stateID>\n";
str += "</initialStateSet>\n";
str += "<transitionset>\n";
for (auto p : this->trans)
{
for(auto d : p.second)
{
str += "<transition tid=\"" + std::to_string(tid++) + "\">\n";
str += "<from>" + stateStr(p.first.first) + "</from>\n<to>" + stateStr(d) +
+ "</to>\n<read>" + symStr(p.first.second) + "</read>\n";
str += "</transition>";
}
}
str += "</transitionset>\n";
str += "</structure>\n";
return str;
}
/*
* Function converting the automaton <string, string> to gff format.
* @return Gff representation of the automaton
*/
template <>
std::string BuchiAutomaton<std::string, std::string>::toGff(){
std::function<std::string(std::string)> f1 = [&] (std::string x) {return x;};
std::function<std::string(std::string)> f2 = [&] (std::string x) {return x;};
return toGffWith(f1, f2);
}
template<>
std::string BuchiAutomaton<int, int>::toGff(){
std::function<std::string(int)> f1 = [&] (int x) {return std::to_string(x);};
std::function<std::string(int)> f2 = [&] (int x) {return std::to_string(x);};
return toGffWith(f1, f2);
}
/*
* Function converting the automaton <int, string> to hoa format.
* @return Hoa representation of the automaton
*/
template <>
std::string BuchiAutomaton<int, string>::toHOA()
{
// TODO: enter correct symbols (now not retained while doing renameAut)
std::string res;
size_t alph_size = this->alph.size();
res += "HOA: v1\n";
res += "States: " + std::to_string(this->states.size()) + "\n";
// renumber states to be a continuous sequence
std::map<int, size_t> state_to_seq;
size_t state_cnt = 0;
for (auto st : this->states) {
state_to_seq.insert({st, state_cnt++});
}
// initial states
for (auto st : this->initials) {
res += "Start: " + std::to_string(state_to_seq[st]) + "\n";
}
res += "acc-name: Buchi\n";
res += "Acceptance: 1 Inf(0)\n";
res += "properties: trans-labels explicit-labels\n";
res += "AP: " + std::to_string(alph_size);
// renumber symbols
std::map<string, size_t> symb_to_pos;
size_t symb_cnt = 0;
for (auto symb : this->alph) {
res += " \"" + symb + "\"";
symb_to_pos.insert({symb, symb_cnt++});
}
// transitions
res += "\n--BODY--\n";
for (auto st : this->states) {
size_t seq_st = state_to_seq[st];
res += "State: " + std::to_string(seq_st);
if (this->finals.find(st) != this->finals.end()) {
res += " {0}";
}
res += "\n";
for (auto symb : this->alph) {
auto it = this->trans.find({st, symb});
if (it == this->trans.end() || it->second.empty()) continue;
// construct the string for the symbol first (composed of atomic propositions)
std::string symb_str;
symb_str += "[";
if (this->apsPattern.size() == 0)
{
symb_str += "t";
}
else
{
bool first = true;
for (size_t i = 0; i < alph_size; ++i) {
if (first) first = false;
else symb_str += " & ";
if (symb_to_pos[symb] != i) symb_str += "!";
symb_str += std::to_string(i);
}
}
symb_str += "]";
for (auto dst : it->second) {
Transition<int, string> tr = { .from = st, .to = dst, .symbol = symb};
if(std::find(this->accTrans.begin(), this->accTrans.end(), tr) != this->accTrans.end())
res += symb_str + " " + std::to_string(state_to_seq[dst]) + " {0} \n";
else
res += symb_str + " " + std::to_string(state_to_seq[dst]) + "\n";
}
}
}
res += "--END--\n";
return res;
}
/*
* Function converting the automaton <int, APSymbol> to hoa format.
* @return Hoa representation of the automaton
*/
template <>
std::string BuchiAutomaton<int, APSymbol>::toHOA()
{
std::string res;
//size_t alph_size = this->alph.size();
res += "HOA: v1\n";
res += "States: " + std::to_string(this->states.size()) + "\n";
// renumber states to be a continuous sequence
std::map<int, size_t> state_to_seq;
size_t state_cnt = 0;
for (auto st : this->states) {
state_to_seq.insert({st, state_cnt++});
}
// initial states
for (auto st : this->initials) {
res += "Start: " + std::to_string(state_to_seq[st]) + "\n";
}
res += "acc-name: Buchi\n";
res += "Acceptance: 1 Inf(0)\n";
res += "properties: trans-labels explicit-labels";
if (!this->isTBA()) res += " state-acc\n";
else res += "\n";
res += "AP: " + std::to_string(this->apsPattern.size());
for (const auto& item : this->apsPattern){
res += " \"" + item + "\"";
}
// transitions
res += "\n--BODY--\n";
for (auto st : this->states) {
size_t seq_st = state_to_seq[st];
res += "State: " + std::to_string(seq_st);
if (this->finals.find(st) != this->finals.end()) {
res += " {0}";
}
res += "\n";
for (auto symb : this->alph) {
auto it = this->trans.find({st, symb});
if (it == this->trans.end() || it->second.empty()) continue;
for (auto dst : it->second) {
Transition<int, APSymbol> tr = { .from = st, .to = dst, .symbol = symb};
if(std::find(this->accTrans.begin(), this->accTrans.end(), tr) != this->accTrans.end())
res += "[" + (this->apsPattern.size() > 0 ? symb.toString() : "t") + "] " + std::to_string(state_to_seq[dst]) + " {0} \n";
else
res += "[" + (this->apsPattern.size() > 0 ? symb.toString() : "t") + "] " + std::to_string(state_to_seq[dst]) + "\n";
}
}
}
res += "--END--\n";
return res;
}
template <>
std::string BuchiAutomaton<int, int>::toHOA(std::map<int, int> sccs)
{
std::string res;
size_t alph_size = this->alph.size();
res += "HOA: v1\n";
res += "States: " + std::to_string(this->states.size()) + "\n";
// renumber states to be a continuous sequence
std::map<int, size_t> state_to_seq;
size_t state_cnt = 0;
for (auto st : this->states) {
state_to_seq.insert({st, state_cnt++});
}
// initial states
for (auto st : this->initials) {
res += "Start: " + std::to_string(state_to_seq[st]) + "\n";
}
res += "acc-name: Buchi\n";
res += "Acceptance: 1 Inf(0)\n";
res += "properties: trans-labels explicit-labels";
if (!this->isTBA()) res += " state-acc\n";
else res += "\n";
res += "AP: " + std::to_string(alph_size);
// renumber symbols
std::map<string, size_t> symb_to_pos;
size_t symb_cnt = 0;
for (auto symb : this->alph) {
res += " \"" + std::to_string(symb) + "\"";
symb_to_pos.insert({std::to_string(symb), symb_cnt++});
}
// transitions
res += "\n--BODY--\n";
for (auto st : this->states) {
size_t seq_st = state_to_seq[st];
res += "State: " + std::to_string(seq_st);
// state label
res += " \"" + std::to_string(sccs[st]) + "\"";
/*for (auto scc : sccs){
if (scc.states.find(st) != scc.states.end()){
res += " \"" + std::to_string(scc.rank) + "\"";
break;
}
}*/
if (this->finals.find(st) != this->finals.end()) {
res += " {0}";
}
res += "\n";
for (auto symb : this->alph) {
auto it = this->trans.find({st, symb});
if (it == this->trans.end() || it->second.empty()) continue;
// construct the string for the symbol first (composed of atomic propositions)
std::string symb_str;
symb_str += "[";
if (this->apsPattern.size() == 0)
{
symb_str += "t";
}
else {
bool first = true;
for (size_t i = 0; i < alph_size; ++i) {
if (first) first = false;
else symb_str += " & ";
if (symb_to_pos[std::to_string(symb)] != i) symb_str += "!";
symb_str += std::to_string(i);
}
}
symb_str += "]";
for (auto dst : it->second) {
Transition<int, int> tr = { .from = st, .to = dst, .symbol = symb };
if(std::find(this->accTrans.begin(), this->accTrans.end(), tr) != this->accTrans.end())
res += symb_str + " " + std::to_string(state_to_seq[dst]) + " {0} \n";
else
res += symb_str + " " + std::to_string(state_to_seq[dst]) + "\n";
}
}
}
res += "--END--\n";
return res;
}
/*
* Abstract function converting the automaton to graphwiz format.
* @param stateStr Function converting a state to string
* @param symStr Function converting a symbol to string
* @return Graphwiz representation of the automaton
*/
template <typename State, typename Symbol>
std::string BuchiAutomaton<State, Symbol>::toGraphwizWith(std::function<std::string(State)>& stateStr,
std::function<std::string(Symbol)>& symStr)
{
std::string str = "digraph \" Automaton \" { rankdir=LR;\n { rank = LR }\n";
str += "node [shape = doublecircle];\n";
for(auto p : this->finals)
str += "\"" + stateStr(p) + "\"\n";
str += "node [shape = circle];";
for(auto st : this->states)
str += "\"" + stateStr(st) + "\"\n";
str += "\"init0\";\n";
for (auto p : this->initials)
str += "\"init0\" -> \"" + stateStr(p) + "\"\n";
for (auto p : this->trans)
{
for(auto d : p.second)
{
std::string isAcc = "";
Transition<State, Symbol> tr = { .from = p.first.first, .to = d, .symbol = p.first.second };
if(std::find(this->accTrans.begin(), this->accTrans.end(), tr) != this->accTrans.end())
isAcc = "\\n{0}";
str += "\"" + stateStr(p.first.first) + "\" -> \"" + stateStr(d) +
+ "\" [label = \"" + symStr(p.first.second) + isAcc + "\"];\n";
}
}
str += "}\n";
return str;
}
/*
* Function converting the automaton <int, int> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<int, int>::toGraphwiz()
{
std::function<std::string(int)> f1 = [=] (int x) {return std::to_string(x);};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <StateSch, int> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<StateSch, int>::toGraphwiz()
{
std::function<std::string(StateSch)> f1 = [&] (StateSch x) {return x.toString();};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <StateSemiDet, int> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<StateSemiDet, int>::toGraphwiz()
{
std::function<std::string(StateSemiDet)> f1 = [&] (StateSemiDet x) {return x.toString();};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <StateSemiDet, APSymbol> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<StateSemiDet, APSymbol>::toGraphwiz()
{
std::function<std::string(StateSemiDet)> f1 = [&] (StateSemiDet x) {return x.toString();};
std::function<std::string(APSymbol)> f2 = [&] (APSymbol x) {return x.toString();};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <pair<StateGcoBA, int>, APSymbol> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<pair<StateGcoBA, int>, APSymbol>::toGraphwiz()
{
std::function<std::string(pair<StateGcoBA, int>)> f1 = [&] (pair<StateGcoBA, int> x)
{
return "(" + x.first.toString() + " " + std::to_string(x.second) + ")";
};
std::function<std::string(APSymbol)> f2 = [=] (APSymbol x) {return x.toString();};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <StateGcoBA, int>> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<StateGcoBA, int>::toGraphwiz()
{
std::function<std::string(StateGcoBA)> f1 = [&] (StateGcoBA x)
{
return x.toString();
};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <string, string> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<std::string, std::string>::toGraphwiz()
{
std::function<std::string(std::string)> f1 = [&] (std::string x) {return x;};
std::function<std::string(std::string)> f2 = [&] (std::string x) {return x;};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <tuple<int, int, bool>, int> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<tuple<int, int, bool>, int>::toGraphwiz()
{
std::function<std::string(tuple<int, int, bool>)> f1 = [&] (tuple<int, int, bool> x)
{
return "(" + std::to_string(std::get<0>(x)) + " " +
std::to_string(std::get<1>(x)) + " " + std::to_string(std::get<2>(x)) + ")";
};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <tuple<StateSch, int, bool>, int> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<tuple<StateSch, int, bool>, int>::toGraphwiz()
{
std::function<std::string(tuple<StateSch, int, bool>)> f1 = [&] (tuple<StateSch, int, bool> x)
{
return "(" + std::get<0>(x).toString() + " " +
std::to_string(std::get<1>(x)) + " " + std::to_string(std::get<2>(x)) + ")";
};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <pair<StateSch, int>, APSymbol> to graphwiz format.
* @return Graphwiz representation of the automaton
*/
template <>
std::string BuchiAutomaton<pair<StateSch, int>, APSymbol>::toGraphwiz()
{
std::function<std::string(pair<StateSch, int>)> f1 = [&] (pair<StateSch, int> x)
{
return "(" + x.first.toString() + " " + std::to_string(x.second) + ")";
};
std::function<std::string(APSymbol)> f2 = [=] (APSymbol x) {return x.toString();};
return toGraphwizWith(f1, f2);
}
template <>
std::string BuchiAutomaton<StateSD, int>::toGraphwiz()
{
std::function<std::string(StateSD)> f1 = [&] (StateSD x) {return x.toString();};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toGraphwizWith(f1, f2);
}
/*
* Function converting the automaton <int, int> to string.
* @return String representation of the automaton
*/
template <>
std::string BuchiAutomaton<int, int>::toString()
{
std::function<std::string(int)> f1 = [=] (int x) {return std::to_string(x);};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toStringWith(f1, f2);
}
/*
* Function converting the automaton <string, string> to string.
* @return String representation of the automaton
*/
template <>
std::string BuchiAutomaton<std::string, std::string>::toString()
{
std::function<std::string(std::string)> f1 = [&] (std::string x) {return x;};
std::function<std::string(std::string)> f2 = [&] (std::string x) {return x;};
return toStringWith(f1, f2);
}
/*
* Function converting the automaton <StateKV, int> to string.
* @return String representation of the automaton
*/
template <>
std::string BuchiAutomaton<StateKV, int>::toString()
{
std::function<std::string(StateKV)> f1 = [&] (StateKV x) {return x.toString();};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toStringWith(f1, f2);
}
/*
* Function converting the automaton <StateKV, int> to string.
* @return String representation of the automaton
*/
template <>
std::string BuchiAutomaton<StateGcoBA, int>::toString()
{
std::function<std::string(StateGcoBA)> f1 = [&] (StateGcoBA x) {return x.toString();};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toStringWith(f1, f2);
}
/*
* Function converting the automaton <tuple<int, int, bool>, int> to string.
* @return String representation of the automaton
*/
template <>
std::string BuchiAutomaton<tuple<int, int, bool>, int>::toString()
{
std::function<std::string(tuple<int, int, bool>)> f1 = [&] (tuple<int, int, bool> x)
{
return "(" + std::to_string(std::get<0>(x)) + " " +
std::to_string(std::get<1>(x)) + " " + std::to_string(std::get<2>(x)) + ")";
};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toStringWith(f1, f2);
}
/*
* Function converting the automaton <StateSch, int> to string.
* @return String representation of the automaton
*/
template <>
std::string BuchiAutomaton<StateSch, int>::toString()
{
std::function<std::string(StateSch)> f1 = [&] (StateSch x) {return x.toString();};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toStringWith(f1, f2);
}
template <>
std::string BuchiAutomaton<StateSD, int>::toString()
{
std::function<std::string(StateSD)> f1 = [&] (StateSD x) {return x.toString();};
std::function<std::string(int)> f2 = [=] (int x) {return std::to_string(x);};
return toStringWith(f1, f2);
}
/*
* Function converting the automaton <int, APSymbol> to string.
* @return String representation of the automaton
*/
template <>
std::string BuchiAutomaton<int, APSymbol>::toString()
{
std::function<std::string(int)> f1 = [=] (int x) {return std::to_string(x);};
std::function<std::string(APSymbol)> f2 = [&] (APSymbol x) {return x.toString();};
return toStringWith(f1, f2);
}
/*
* Remove unreachable and nonaccepting states from the automaton (in place
* modification, assumes states numbered from 0 with no gaps).
*/
template <>
void BuchiAutomaton<int, int>::removeUseless()
{
vector<vector<int> > adjList(this->states.size());
vector<vector<int> > revList(this->states.size());
vector<VertItem> vrt;
set<pair<int, int> > accTrSet;
for(const auto& tr : this->accTrans)
{
accTrSet.insert({tr.from, tr.to});
}
getAutGraphComponents(adjList, vrt);
for(unsigned i = 0; i < adjList.size(); i++)
{
for(auto dst : adjList[i])
revList[dst].push_back(i);
}
AutGraph gr(adjList, vrt, this->finals);
gr.computeSCCs(accTrSet);
set<int> fin;
for(auto s : gr.getFinalComponents())
{
fin.insert(s.begin(), s.end());
}
set<int> reach = gr.reachableVertices(this->getInitials());
set<int> backreach = gr.reachableVertices(revList, fin);
set<int> ret;
std::set_intersection(reach.begin(),reach.end(),backreach.begin(),
backreach.end(), std::inserter(ret, ret.begin()));
restriction(ret);
}
/*
* Restrict the automaton wrt given states (in place modification).
* @param st States that remain in the automaton
*/
template <typename State, typename Symbol>
void BuchiAutomaton<State, Symbol>::restriction(set<State>& st)
{
Transitions newtrans;
set<State> newfin;
set<State> newini;
VecTrans<State, Symbol> ftrans;
for(const auto& tr : this->trans)
{
if(st.find(tr.first.first) == st.end())
continue;
set<State> dst;
std::set_intersection(tr.second.begin(),tr.second.end(),st.begin(),
st.end(), std::inserter(dst, dst.begin()));
newtrans[tr.first] = dst;
}
for(const auto& tr : this->accTrans)
{
if(st.find(tr.to) == st.end() || st.find(tr.from) == st.end())
continue;
ftrans.push_back(tr);
}
std::set_intersection(this->finals.begin(),this->finals.end(),st.begin(),
st.end(), std::inserter(newfin, newfin.begin()));
std::set_intersection(this->initials.begin(),this->initials.end(),st.begin(),
st.end(), std::inserter(newini, newini.begin()));
this->trans = newtrans;
this->states = st;
this->finals = newfin;
this->initials = newini;
this->accTrans = ftrans;
}
/*
* Complete the automaton (in place modification)
* @param trap New (possibly) trap state
* @param fin Should be the trap state final?
*/
template <typename State, typename Symbol>
void BuchiAutomaton<State, Symbol>::complete(State trap, bool fin)
{
bool modif = false;
set<State> trSet({trap});
if(this->states.empty())
{
modif = true;
this->initials.insert(trap);
}
for(State st : this->states)
{
for(Symbol s : this->alph)
{
auto pr = std::make_pair(st, s);
if(this->trans.find(pr) == this->trans.end() || this->trans[pr].size() == 0)
{
modif = true;
this->trans[pr] = trSet;
}
}
}
if(modif)
{
for(Symbol s : this->alph)
{
auto pr = std::make_pair(trap, s);
this->trans[pr] = trSet;
}
this->states.insert(trap);
if(fin)
this->finals.insert(trap);
}
}
/*
* Complete the automaton wrt all subsets of atomic propositions (in
* place modification)
*/
template <>
void BuchiAutomaton<int, APSymbol>::completeAPComplement()
{
this->complete(this->getStates().size(), false);
set<APSymbol> allsyms;
APSymbol tmp(this->getAPPattern().size());
bool first = true;
set<int> diff;
for(const APSymbol& s : this->getAlphabet())
{
if(first)
{
tmp = s;
first = false;
}
else
{
for(unsigned i = 0; i < this->getAPPattern().size(); i++)
{
if(tmp.ap[i] != s.ap[i])
{
diff.insert(i);
tmp.ap[i] = 2;
}
}
}
}
for(unsigned i = 0; i < this->getAPPattern().size(); i++)
{
if(tmp.ap[i] != 2)
{
APSymbol sym(this->getAPPattern().size(), 2);
sym.ap[i] = !tmp.ap[i];
allsyms.insert(sym);
}
}
if(this->getAlphabet().size() <= 1)
{
allsyms.insert(tmp);
}
if(diff.size() > 0)
{
vector<int> cnum;
for(const int & t : diff)
cnum.push_back(t);
for(const auto& s : Aux::getAllSubsets(cnum))
{
APSymbol sym = tmp;
for(const int& t : cnum)
sym.ap[t] = 0;
for(const int& t : s)
sym.ap[t] = 1;
allsyms.insert(sym);
}
}
this->setAlphabet(allsyms);
this->complete(this->getStates().size(), true);
// if(this->getAPPattern().size() > 0)
// {
// vector<int> cnum(this->getAPPattern().size());
// std::iota(cnum.begin(), cnum.end(), 0);
// for(const auto& s : Aux::getAllSubsets(cnum))
// {
// APSymbol sym(this->getAPPattern().size());
// for(const int& t : s)
// sym.ap[t] = 1;
// allsyms.insert(sym);
// }
// }
// this->setAlphabet(allsyms);
// this->complete(this->getStates().size(), true);
}
/*
* Compute the odd rank simulation (stores in this->oddRankSim)
* @param cl Closure of states
*/
template <typename State, typename Symbol>
void BuchiAutomaton<State, Symbol>::computeRankSim(std::set<State>& cl)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
StateRelation rel = this->directSim;
bool add = false;
std::map<Symbol, bool> ignore;
for(Symbol s : this->alph)
{
ignore[s] = false;
for(State st : cl)
{
if(this->trans[{st, s}].size() == 0)
ignore[s] = true;
}
}
do {
add = false;
transitiveClosure(rel, cl);
for(State st1 : this->states)
{
if(this->finals.find(st1) != this->finals.end())
continue;
for(State st2 : this->states)
{
if(this->finals.find(st2) != this->finals.end())
continue;
bool der = deriveRankConstr(st1, st2, rel);
if(der)
add = true;
}
}
} while(add);
this->oddRankSim = rel;
}
/*
* Function checking wheather odd rank sim contains equivalent pairs.
* @param cl Closure of states
*/
template <typename State, typename Symbol>
bool BuchiAutomaton<State, Symbol>::containsRankSimEq(std::set<State>& cl)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
this->computeRankSim(cl);
for(auto& item : this->oddRankSim)
{
if(item.first == item.second)
continue;
if(this->oddRankSim.find({item.second, item.first}) != this->oddRankSim.end())
return true;
}
return false;
}
/*
* Function computing transitive closure of give relation
* @param rel Relation (out parameter)
* @param cl Closure of states (for computation of odd rank simulation)
*/
template <typename State, typename Symbol>
void BuchiAutomaton<State, Symbol>::transitiveClosure(
BuchiAutomaton<State, Symbol>::StateRelation& rel, std::set<State>& cl)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
unsigned s = rel.size();
do
{
s = rel.size();
for(const auto& p1 : rel)
{
if(cl.find(p1.first) == cl.end() || cl.find(p1.second) == cl.end())
continue;
for(const auto& p2 : rel)
{
if(cl.find(p2.first) == cl.end() || cl.find(p2.second) == cl.end())
continue;
if(p1.second == p2.first)
rel.insert({p1.first, p2.second});
}
}
} while(s != rel.size());
}
/*
* Get constraints for two states wrt odd rank simulation
* @param st1 First state
* @param st2 Second state
* @param rel odd rank simulation
*/
template <typename State, typename Symbol>
bool BuchiAutomaton<State, Symbol>::deriveRankConstr(State& st1, State& st2,
BuchiAutomaton<State, Symbol>::StateRelation& rel)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
bool leq = true;
bool geq = true;
bool ret = false;
//bool fwdlq = false;
//bool fwdgq = false;
StateRelation nw;
for(Symbol sym : this->alph)
{
set<State> dst1 = this->trans[{st1, sym}];
set<State> dst2 = this->trans[{st2, sym}];
if(!isRankLeq(dst1, dst2, rel) /*&& !ignore[sym]*/)
leq = false;
if(!isRankLeq(dst2, dst1, rel) /*&& !ignore[sym]*/)
geq = false;
//propagateFwd(st1, st2, dst1, dst2, rel, nw);
}
if(leq) nw.insert({st1, st2});
if(geq) nw.insert({st2, st1});
for(auto it : nw)
{
if(rel.find(it) == rel.end())
ret = true;
rel.insert(it);
}
return ret;
}
/*
* Propagate odd rank sim values to successor states (obsolete)
*/
template <typename State, typename Symbol>
void BuchiAutomaton<State, Symbol>::propagateFwd(State& st1, State& st2,
std::set<State>& set1, std::set<State>& set2,
BuchiAutomaton<State, Symbol>::StateRelation& rel,
BuchiAutomaton<State, Symbol>::StateRelation& nw)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
std::set<State> fset1, fset2;
std::set_difference(set1.begin(), set1.end(), this->finals.begin(), this->finals.end(),
std::inserter(fset1, fset1.begin()));
std::set_difference(set2.begin(), set2.end(), this->finals.begin(), this->finals.end(),
std::inserter(fset2, fset2.begin()));
if(fset1.size() == 1 && fset2.size() == 1 && rel.find({st1, st2}) != rel.end())
nw.insert({*(fset1.begin()), *(fset2.begin())});
if(fset1.size() == 1 && fset2.size() == 1 && rel.find({st2, st1}) != rel.end())
nw.insert({*(fset2.begin()), *(fset1.begin())});
}
/*
* Are all states of set1 bigger than all states of set2?
* @param set1 First set of states
* @param set2 Second set of states
* @param rel Rank simulation (or relation in general)
* @return set1 >=(forall, forall) sett2
*/
template <typename State, typename Symbol>
bool BuchiAutomaton<State, Symbol>::isRankLeq(std::set<State>& set1, std::set<State>& set2,
BuchiAutomaton<State, Symbol>::StateRelation& rel)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
for(State st1 : set1)
{
if(this->finals.find(st1) != this->finals.end())
continue;
for(State st2 : set2)
{
if(this->finals.find(st2) != this->finals.end())
continue;
if(rel.find({st1, st2}) == rel.end())
return false;
}
}
return true;
}
/*
* Get eventually reachable states
* @params sls States containing self-loops over the whole alphabet
* @return Set of eventually reachable states
*/
template <typename State, typename Symbol>
set<State> BuchiAutomaton<State, Symbol>::getEventReachable(set<State>& sls)
{
BuchiAutomaton<int, int> renAutBA = this->renameAut();
vector<vector<int>> adjList(this->states.size());
std::set<int> ini = renAutBA.getInitials();
vector<VertItem> vrt;
std::stack<int> stack;
std::set<int> done;
std::set<State> ret;
std::vector<int> sccSizeMp(this->states.size());
for(int i : ini)
stack.push(i);
renAutBA.getAutGraphComponents(adjList, vrt);
AutGraph gr(adjList, vrt, renAutBA.getFinals());
gr.computeSCCs();
for(auto& scc : gr.getAllComponents())
{
for(auto &st : scc)
{
if(scc.size() == 1 && sls.find(this->invRenameMap[st]) == sls.end())
sccSizeMp[st] = 0;
else
{
sccSizeMp[st] = scc.size();
done.insert(st);
}
}
}
done = gr.reachableVertices(done);
for(int st : done)
{
ret.insert(this->invRenameMap[st]);
}
return ret;
}
/*
* Get states closing a cycle in the automaton graph
* @params slignore States containing self-loops to be ignored
* @return Set of states closing a cycle
*/
template <typename State, typename Symbol>
set<State> BuchiAutomaton<State, Symbol>::getCycleClosingStates(set<State>& slignore)
{
set<State> ret;
std::stack<State> stack;
set<State> done;
for(const State& in : this->initials)
stack.push(in);
while(stack.size() > 0)
{
State tst = stack.top();
stack.pop();
done.insert(tst);
for(const Symbol& alp : this->alph)
{
for(const State& d : this->trans[{tst, alp}])
{
if(d == tst && slignore.find(d) != slignore.end())
continue;
if(done.find(d) != done.end())
{
if(this->reachWithRestriction(d, tst, done, ret))
ret.insert(d);
}
else
{
stack.push(d);
}
}
}
}
return ret;
}
/*
* Accept the automaton empty language (assumes states numbered from 0
* with no gaps).
*/
template <>
bool BuchiAutomaton<int, int>::isEmpty()
{
vector<vector<int> > adjList(this->states.size());
vector<VertItem> vrt;
getAutGraphComponents(adjList, vrt);
set<pair<int, int> > accTrSet;
for(const auto& tr : this->accTrans)
{
accTrSet.insert({tr.from, tr.to});
}
AutGraph gr(adjList, vrt, this->finals);
gr.computeSCCs(accTrSet);
set<int> fin;
for(auto s : gr.getFinalComponents())
{
fin.insert(s.begin(), s.end());
}
set<int> in;
set<int> tmp = AutGraph::reachableVertices(adjList, this->getInitials());
set_intersection(fin.begin(), fin.end(), tmp.begin(), tmp.end(),
std::inserter(in, in.begin()));
if(in.size() > 0)
return false;
return true;
}
/*
* Compute intersection (product) with another BA
* @param other Other BA
* @return BA accepting intersection of both languages
*/
template <typename State, typename Symbol>
BuchiAutomaton<tuple<State, int, bool>, Symbol> BuchiAutomaton<State, Symbol>::productBA(BuchiAutomaton<int, Symbol>& other)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
typedef tuple<State, int, bool> ProdState;
set<ProdState> nstates;
set<ProdState> nini;
stack<ProdState> stack;
set<State> fin1 = this->getFinals();
set<int> fin2 = other.getFinals();
auto tr1 = this->getTransitions();
auto tr2 = other.getTransitions();
map<std::pair<ProdState, Symbol>, set<ProdState>> ntr;
set<ProdState> nfin;
for(const State& st1 : this->getInitials())
{
for(const int& st2 : other.getInitials())
{
stack.push({st1, st2, 0});
nstates.insert({st1, st2, 0});
nini.insert({st1, st2, 0});
}
}
while(stack.size() > 0)
{
ProdState act = stack.top();
stack.pop();
for(const Symbol& sym : this->getAlphabet())
{
set<ProdState> dst;
for(const State& d1 : tr1[{std::get<0>(act), sym}])
{
for(const int& d2 : tr2[{std::get<1>(act), sym}])
{
if(!std::get<2>(act) && fin1.find(d1) != fin1.end())
{
dst.insert({d1, d2, 1});
}
else if(std::get<2>(act) && fin2.find(d2) != fin2.end())
{
dst.insert({d1, d2, 0});
}
else
{
dst.insert({d1, d2, std::get<2>(act)});
}
}
}
for(auto& item : dst)
{
if(nstates.find(item) == nstates.end())
{
nstates.insert(item);
stack.push(item);
}
}
ntr[{act, sym}] = dst;
}
}
for(const State& st1 : this->getStates())
{
for(const int& f2 : fin2)
{
nstates.insert({st1, f2, 1});
nfin.insert({st1, f2, 1});
}
}
return BuchiAutomaton<tuple<State, int, bool>, Symbol>(nstates, nfin, nini, ntr);
}
/*
* Get cartesian product with another BA (assuming the second BA has all states final)
* @param other Other BA
* @return cartesian product of two BAs
*/
template <typename State, typename Symbol>
BuchiAutomaton<pair<State, int>, Symbol> BuchiAutomaton<State, Symbol>::cartProductBA(BuchiAutomaton<int, Symbol>& other)
{
/*
TODO: add support for accepting transitions
*/
assert(this->accTrans.size() == 0);
typedef pair<State, int> ProdState;
set<ProdState> nstates;
set<ProdState> nini;
stack<ProdState> stack;
set<State> fin1 = this->getFinals();
set<int> fin2 = other.getFinals();
auto tr1 = this->getTransitions();
auto tr2 = other.getTransitions();
map<std::pair<ProdState, Symbol>, set<ProdState>> ntr;
set<ProdState> nfin;
for(const State& st1 : this->getInitials())
{
for(const int& st2 : other.getInitials())
{
stack.push({st1, st2});
nstates.insert({st1, st2});
nini.insert({st1, st2});
}
}
while(stack.size() > 0)
{
ProdState act = stack.top();
stack.pop();
for(const Symbol& sym : this->getAlphabet())
{
set<ProdState> dst;
for(const State& d1 : tr1[{act.first, sym}])
{
for(const int& d2 : tr2[{act.second, sym}])
{
dst.insert({d1, d2});
}
}
for(auto& item : dst)
{
if(nstates.find(item) == nstates.end())
{
if(fin1.find(item.first) != fin1.end())
nfin.insert(item);
nstates.insert(item);
stack.push(item);
}
}
ntr[{act, sym}] = dst;
}
}
return BuchiAutomaton<pair<State, int>, Symbol>(nstates, nfin, nini, ntr);
}
/*
* Compute union (nondeterministic) with another BA
* @param other Other BA
* @return BA accepting intersection of both languages
*/
template <typename State, typename Symbol>
BuchiAutomaton<State, Symbol> BuchiAutomaton<State, Symbol>::unionBA(BuchiAutomaton<State, Symbol>& other)
{
/*
TODO: add support for accepting transitions
*/
//assert(this->accTrans.size() == 0);
set<State> nstates;
set<State> nini;
Transitions ntr(this->getTransitions());
set<State> nfin;
VecTransG finTrans(this->getFinTrans());
set_union(this->getStates().begin(), this->getStates().end(), other.getStates().begin(),
other.getStates().end(), std::inserter(nstates, nstates.begin()));
set_union(this->getInitials().begin(), this->getInitials().end(), other.getInitials().begin(),
other.getInitials().end(), std::inserter(nini, nini.begin()));
set_union(this->getFinals().begin(), this->getFinals().end(), other.getFinals().begin(),
other.getFinals().end(), std::inserter(nfin, nfin.begin()));
finTrans.insert(finTrans.end(), other.getFinTrans().begin(), other.getFinTrans().end());
// merge transitions
for (auto it = other.getTransitions().begin(); it != other.getTransitions().end(); it++){
if (ntr.find(it->first) != ntr.end())
ntr[it->first].insert(it->second.begin(), it->second.end());
else
ntr.insert({it->first, it->second});
}
return BuchiAutomaton<State, Symbol>(nstates, nfin, nini, ntr, finTrans, this->getAlphabet(), this->apsPattern);
}
/*
* Get reversed BA (reverse directions of transitions, initials became
* finals and vice versa)
* @return Reversed BA
*/
template <typename State, typename Symbol>
BuchiAutomaton<State, Symbol> BuchiAutomaton<State, Symbol>::reverseBA()
{
Transitions rev = this->getReverseTransitions();
VecTrans<State, Symbol> revAccTr;
for(const auto& tr : this->accTrans)
{
revAccTr.push_back({ .from = tr.to, .to = tr.from, .symbol = tr.symbol });
}
return BuchiAutomaton(this->getStates(), this->getInitials(), this->getFinals(), rev, revAccTr, this->getAlphabet());
}
/*
* Get automaton with renamed states to StateSch (debug only)
* @param mpst Map assigning original (int) states back to StateSch
* @return Renamed BA
*/
template <>
BuchiAutomaton<StateSch, int> BuchiAutomaton<int, int>::getComplStructure(std::map<int, StateSch>& mpst)
{
std::set<StateSch> rstate;
Delta<StateSch, int> rtrans;
std::set<StateSch> rfin;
std::set<StateSch> rini;
rstate = Aux::mapSet(mpst, this->states);
rini = Aux::mapSet(mpst, this->initials);
rfin = Aux::mapSet(mpst, this->finals);
for(auto& p : this->trans)
{
std::set<StateSch> to = Aux::mapSet(mpst, p.second);
rtrans.insert({std::make_pair(mpst[p.first.first], p.first.second), to});
}
auto ret = BuchiAutomaton<StateSch, int>(rstate, rfin, rini, rtrans);
return ret;
}
template <typename State, typename Symbol>
map<State, set<Symbol> > BuchiAutomaton<State, Symbol>::getPredSymbolMap()
{
auto trans = this->getTransitions();
map<State, set<Symbol>> ret;
for(const State& s : this->getStates())
{
ret[s] = set<Symbol>();
for(const Symbol& sym : this->getAlphabet())
{
if(trans[{s, sym}].size() > 0)
ret[s].insert(sym);
}
}
return ret;
}
template <typename State, typename Symbol>
map<State, set<Symbol>> BuchiAutomaton<State, Symbol>::getReverseSymbolMap(){
auto trans = this->getReverseTransitions();
map<State, set<Symbol>> ret;
for(const State& s : this->getStates())
{
ret[s] = set<Symbol>();
for(const Symbol& sym : this->getAlphabet())
{
if(trans[{s, sym}].size() > 0)
ret[s].insert(sym);
}
}
return ret;
}
template <>
BuchiAutomaton<int, int> BuchiAutomaton<int, int>::copyStateAcc(int start)
{
auto origTrans = this->getTransitions();
Delta<int,int> trans(origTrans.begin(), origTrans.end());
map<int,int> stMap;
set<int> fins;
set<int> orig = this->getStates();
set<int> states(orig.begin(), orig.end());
for(const int& s : this->getStates())
{
stMap[s] = start;
states.insert(start);
start++;
}
for(auto &p : this->getTransitions())
{
set<int> dst = Aux::mapSet(stMap, p.second);
trans.insert({std::make_pair(stMap[p.first.first], p.first.second), dst});
}
for(auto &p : this->getTransitions())
{
set<int> dst = Aux::mapSet(stMap, p.second);
if(dst.size() > 0)
{
trans[p.first].insert(dst.begin(), dst.end());
}
}
for(const auto& f : this->getFinals())
{
fins.insert(stMap[f]);
}
return BuchiAutomaton(states, fins, this->getInitials(), trans, this->getAlphabet(), this->getAPPattern());
}
/*
* Set of all successors.
* @param states Set of states to get successors
* @param symbol Symbol
* @return Set of successors over symbol
*/
template <typename State, typename Symbol>
set<State> BuchiAutomaton<State, Symbol>::succSet(const set<State>& states, const Symbol& symbol)
{
set<State> ret;
for(const State& st : states)
{
set<State> dst = this->getTransitions()[std::make_pair(st, symbol)];
ret.insert(dst.begin(), dst.end());
}
return ret;
}
/*
* Semideterminize the given automaton
* @return Modified structure with equivalent language
*/
template <>
BuchiAutomaton<StateSemiDet, APSymbol> BuchiAutomaton<int, APSymbol>::semideterminize()
{
/*
TODO: add support for accepting transitions
*/
assert(this->getFinTrans().size() == 0);
std::stack<StateSemiDet> stack;
set<StateSemiDet> comst;
set<StateSemiDet> initials;
set<StateSemiDet> finals;
//set<StateSch> succ;
set<APSymbol> alph = getAlphabet();
map<std::pair<StateSemiDet, APSymbol>, set<StateSemiDet> > mp;
map<std::pair<StateSemiDet, APSymbol>, set<StateSemiDet> >::iterator it;
for(const int& i : this->getInitials())
{
StateSemiDet init = {i, {set<int>(), set<int>()}, true};
stack.push(init);
comst.insert(init);
initials.insert(init);
}
set<int> fins = this->getFinals();
set<int> ignore;
set<int> closingStates = this->getCycleClosingStates(ignore);
while(stack.size() > 0)
{
StateSemiDet st = stack.top();
stack.pop();
if(!st.isWaiting && st.tight.first == st.tight.second && st.tight.first.size() > 0)
{
finals.insert(st);
}
for(APSymbol const & sym : alph)
{
set<StateSemiDet> dst;
if(st.isWaiting)
{
auto pr = std::make_pair(st.waiting, sym);
set<int> tmpDst = this->getTransitions()[pr];
for(const int& d : tmpDst)
{
StateSemiDet s1 = { d, {set<int>(), set<int>()}, true };
dst.insert(s1);
//if(closingStates.find(st.waiting) != closingStates.end())
{
StateSemiDet s2 = { -1, {set<int>({d}), set<int>()}, false };
dst.insert(s2);
}
}
}
else
{
if(st.tight.first != st.tight.second)
{
set<int> succ = succSet(st.tight.first, sym);
set<int> succ2;
std::set_intersection(succ.begin(), succ.end(), fins.begin(), fins.end(),
std::inserter(succ2, succ2.begin()));
set<int> tmpsucc = succSet(st.tight.second, sym);
succ2.insert(tmpsucc.begin(), tmpsucc.end());
StateSemiDet s = { -1, {succ, succ2}, false };
dst.insert(s);
}
else
{
set<int> succ = succSet(st.tight.first, sym);
set<int> succ2;
std::set_intersection(succ.begin(), succ.end(), fins.begin(), fins.end(),
std::inserter(succ2, succ2.begin()));
StateSemiDet s = { -1, {succ, succ2}, false };
dst.insert(s);
}
}
for(const StateSemiDet& d : dst)
{
if(comst.find(d) == comst.end())
{
stack.push(d);
comst.insert(d);
}
}
auto pr = std::make_pair(st, sym);
mp[pr] = dst;
}
}
return BuchiAutomaton<StateSemiDet, APSymbol>(comst, finals,
initials, mp, alph, this->getAPPattern());
}
template <>
BuchiAutomaton<int, int> BuchiAutomaton<int, int>::removeUselessRename()
{
map<int, int> id;
for(auto al : this->getAlphabet())
id[al] = al;
BuchiAutomaton<int, int> renptr = this->renameAutDict(id);
renptr.removeUseless();
return renptr.renameAutDict(id);
}
template<typename State, typename Symbol>
BuchiAutomaton<int, Symbol> BuchiAutomaton<State,Symbol>::reduce()
{
//assert(!this->isTBA() && "Reduce not supported for TBAs");
assert(this->directSim.size() > 0 && "Simulation is not computed");
map<State, int> stmap;
set<set<State>> eqcl = Aux::getEqClasses(this->directSim, this->getStates());
set<int> nst;
set<int> nini;
set<int> nfin;
Delta<int, Symbol> ntr;
int i = 0;
for(const auto& cl : eqcl)
{
nst.insert(i);
for(const State& st : cl)
stmap[st] = i;
i++;
}
nini = Aux::mapSet(stmap, this->initials);
nfin = Aux::mapSet(stmap, this->finals);
for(auto& p : this->trans)
{
Symbol val = p.first.second;
std::set<int> to = Aux::mapSet(stmap, p.second);
ntr[{ stmap[p.first.first], val} ].insert(to.begin(), to.end());
}
BuchiAutomaton<int, Symbol> ret(nst, nfin, nini, ntr, this->getAlphabet(), this->getAPPattern());
VecTrans<int, Symbol> newTrans;
for (auto tr : this->getFinTrans()){
Transition<int, Symbol> tmp = {.from = stmap[tr.from], .to = stmap[tr.to], .symbol = tr.symbol};
newTrans.push_back(tmp);
}
ret.setFinTrans(newTrans);
return ret;
}
template<typename State, typename Symbol>
BuchiAutomaton<int, Symbol> BuchiAutomaton<State,Symbol>::toTBA()
{
//assert(!this->isTBA() && "Reduce not supported for TBAs");
map<State, int> stmap;
map<State, set<Symbol>> predSyms = this->getPredSymbolMap();
map<State, set<Symbol>> predSymsRev = this->getReverseSymbolMap();
Delta<State, Symbol> revTr = this->getReverseTransitions();
set<pair<State,State>> eqRel;
for(const State& p : this->getStates())
{
for(const State& q : this->getStates())
{
if(predSyms[p] != predSyms[q])
continue;
bool add = true;
for(const Symbol& s : predSyms[p])
{
if(this->trans[{p,s}] != this->trans[{q,s}])
{
add = false;
break;
}
}
if(add) eqRel.insert({p,q});
}
}
set<set<State>> eqcl = Aux::getEqClasses(eqRel, this->getStates());
set<int> nst;
set<int> nini;
set<int> nfin;
set<State> generateFinTrans;
Delta<int, Symbol> ntr;
VecTrans<int, Symbol> accTrans;
int i = 0;
for(const auto& cl : eqcl)
{
nst.insert(i);
for(const State& st : cl)
stmap[st] = i;
if(std::includes(this->finals.begin(), this->finals.end(), cl.begin(), cl.end()))
{
nfin.insert(i);
}
else
{
for(const State& st : cl)
{
if(this->finals.find(st) != this->finals.end())
generateFinTrans.insert(st);
}
}
i++;
}
for(const State& src : generateFinTrans)
{
for(const Symbol& s : predSymsRev[src])
{
for(const State& dest : revTr[{src, s}])
{
Transition<int, Symbol> tr = {.from = stmap[dest], .to = stmap[src], .symbol = s};
accTrans.push_back(tr);
}
}
}
nini = Aux::mapSet(stmap, this->initials);
for(auto& p : this->trans)
{
Symbol val = p.first.second;
std::set<int> to = Aux::mapSet(stmap, p.second);
ntr[{ stmap[p.first.first], val} ].insert(to.begin(), to.end());
}
return BuchiAutomaton<int, Symbol>(nst, nfin, nini, ntr, accTrans, this->getAlphabet(), this->getAPPattern());
}
template<>
BuchiAutomaton<int, APSymbol> BuchiAutomaton<int,int>::toAPBA(map<int, string>& symName)
{
map<int, APSymbol> symToPos;
set<APSymbol> newAlph;
vector<string> apPat;
int cnt = 0;
int num = this->getAlphabet().size();
for(int sym : this->getAlphabet())
{
APSymbol ap(num);
ap.ap[cnt] = 1;
symToPos[sym] = ap;
newAlph.insert(ap);
apPat.push_back(symName[sym]);
cnt++;
}
auto ret = renameAlphabet(symToPos);
ret.setAPPattern(apPat);
return ret;
}
template class BuchiAutomaton<int, int>;
template class BuchiAutomaton<std::string, std::string>;
template class BuchiAutomaton<StateSch, int>;
template class BuchiAutomaton<int, APSymbol>;
template class BuchiAutomaton<StateSch, APSymbol>;
template class BuchiAutomaton<StateGcoBA, int>;
template class BuchiAutomaton<StateGcoBA, APSymbol>;
template class BuchiAutomaton<StateSemiDet, int>;
template class BuchiAutomaton<StateSemiDet, APSymbol>;
template class BuchiAutomaton<StateSD, int>;
template class BuchiAutomaton<StateSD, APSymbol>;
| 27.37931 | 132 | 0.610521 | vhavlena |
da21bfd3597a3856380aa86245a7a1f532cc2d79 | 989 | cpp | C++ | metrics/config.cpp | linhanwang/cppmetrics | d40797c41ef0686302111c3473c6d670efc8620a | [
"MIT"
] | null | null | null | metrics/config.cpp | linhanwang/cppmetrics | d40797c41ef0686302111c3473c6d670efc8620a | [
"MIT"
] | null | null | null | metrics/config.cpp | linhanwang/cppmetrics | d40797c41ef0686302111c3473c6d670efc8620a | [
"MIT"
] | null | null | null | #include <metrics/config.h>
#include <metrics/counter.h>
#include <metrics/gauge.h>
#include <metrics/histogram.h>
#include <array>
#include <string>
namespace metrics {
// clang-format off
// --------------------Counters--------------------------
std::array<std::string, NumCounters> counter_keys = {
"CounterPlaceOrder",
"CounterCancelOrder",
"CounterTest"
};
std::array<Counter, NumCounters> counter_arr;
// --------------------Gauges--------------------------
std::array<std::string, NumGauges> gauge_keys = {
"GaugePnl",
"GaugeTest"
};
std::array<Gauge, NumGauges> gauge_arr;
// --------------------Histograms--------------------------
std::array<std::string, NumHistograms> histogram_keys = {
"HistogramMsgLatency",
"HistogramTimeUsed",
"HistogramTest"
};
std::array<Histogram, NumHistograms> histogram_arr = {
Histogram{50, 0, 1000},
Histogram{1000, 0, 20'000},
Histogram{50, 0, 1000}
};
// clang-format on
} // namespace metrics | 23.547619 | 59 | 0.595551 | linhanwang |
da264e470a8bdf0152440d4d41cf2e64af6ab9f6 | 14,066 | cpp | C++ | src/cpp/server/http/HttpConnection.cpp | ey6es/witgap | 8f4af7adbde6bb172b4c66c0969e6f5d8736e7cb | [
"BSD-2-Clause"
] | 2 | 2017-06-24T03:47:12.000Z | 2017-08-11T00:04:46.000Z | src/cpp/server/http/HttpConnection.cpp | ey6es/witgap | 8f4af7adbde6bb172b4c66c0969e6f5d8736e7cb | [
"BSD-2-Clause"
] | null | null | null | src/cpp/server/http/HttpConnection.cpp | ey6es/witgap | 8f4af7adbde6bb172b4c66c0969e6f5d8736e7cb | [
"BSD-2-Clause"
] | null | null | null | //
// $Id$
#include <QBuffer>
#include <QCryptographicHash>
#include <QTcpSocket>
#include "ServerApp.h"
#include "http/HttpConnection.h"
#include "http/HttpManager.h"
HttpConnection::HttpConnection (ServerApp* app, QTcpSocket* socket) :
QObject(app->httpManager()),
_app(app),
_socket(socket),
_unmasker(new MaskFilter(socket, this)),
_stream(socket),
_address(socket->peerAddress()),
_webSocketPaused(false),
_closeSent(false)
{
// take over ownership of the socket
_socket->setParent(this);
// connect initial slots
connect(socket, SIGNAL(readyRead()), SLOT(readRequest()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(deleteLater()));
connect(socket, SIGNAL(disconnected()), SLOT(deleteLater()));
// log the connection
qDebug() << "HTTP connection opened." << _address;
}
HttpConnection::~HttpConnection ()
{
// log the destruction
QString error;
QDebug base = qDebug() << "HTTP connection closed." << _address;
if (_socket->error() != QAbstractSocket::UnknownSocketError) {
base << _socket->errorString();
}
}
bool HttpConnection::isWebSocketRequest ()
{
return _requestHeaders.value("Upgrade") == "websocket";
}
QList<FormData> HttpConnection::parseFormData () const
{
// make sure we have the correct MIME type
QList<QByteArray> elements = _requestHeaders.value("Content-Type").split(';');
if (elements.at(0).trimmed() != "multipart/form-data") {
return QList<FormData>();
}
// retrieve the boundary marker
QByteArray boundary;
for (int ii = 1, nn = elements.size(); ii < nn; ii++) {
QByteArray element = elements.at(ii).trimmed();
if (element.startsWith("boundary")) {
boundary = element.mid(element.indexOf('=') + 1).trimmed();
break;
}
}
QByteArray start = "--" + boundary;
QByteArray end = "\r\n--" + boundary + "--\r\n";
QList<FormData> data;
QBuffer buffer(const_cast<QByteArray*>(&_requestContent));
buffer.open(QIODevice::ReadOnly);
while (buffer.canReadLine()) {
QByteArray line = buffer.readLine().trimmed();
if (line == start) {
FormData datum;
while (buffer.canReadLine()) {
QByteArray line = buffer.readLine().trimmed();
if (line.isEmpty()) {
// content starts after this line
int idx = _requestContent.indexOf(end, buffer.pos());
if (idx == -1) {
qWarning() << "Missing end boundary." << _address;
return data;
}
datum.second = _requestContent.mid(buffer.pos(), idx - buffer.pos());
data.append(datum);
buffer.seek(idx + end.length());
} else {
// it's a header element
int idx = line.indexOf(':');
if (idx == -1) {
qWarning() << "Invalid header line." << _address << line;
continue;
}
datum.first.insert(line.left(idx).trimmed(), line.mid(idx + 1).trimmed());
}
}
}
}
return data;
}
void HttpConnection::respond (
const char* code, const QByteArray& content, const char* contentType, const Headers& headers)
{
_socket->write("HTTP/1.1 ");
_socket->write(code);
_socket->write("\r\n");
int csize = content.size();
for (Headers::const_iterator it = headers.constBegin(), end = headers.constEnd();
it != end; it++) {
_socket->write(it.key());
_socket->write(": ");
_socket->write(it.value());
_socket->write("\r\n");
}
if (csize > 0) {
_socket->write("Content-Length: ");
_socket->write(QByteArray::number(csize));
_socket->write("\r\n");
_socket->write("Content-Type: ");
_socket->write(contentType);
_socket->write("\r\n");
}
_socket->write("Connection: close\r\n\r\n");
if (csize > 0) {
_socket->write(content);
}
// make sure we receive no further read notifications
_socket->disconnect(SIGNAL(readyRead()), this);
_socket->disconnectFromHost();
}
void HttpConnection::switchToWebSocket (const char* protocol)
{
_socket->write("HTTP/1.1 101 Switching Protocols\r\n");
_socket->write("Upgrade: websocket\r\n");
_socket->write("Connection: Upgrade\r\n");
_socket->write("Sec-WebSocket-Accept: ");
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(_requestHeaders.value("Sec-WebSocket-Key"));
hash.addData("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); // from WebSocket draft RFC
_socket->write(hash.result().toBase64());
if (protocol != 0) {
_socket->write("\r\nSec-WebSocket-Protocol: ");
_socket->write(protocol);
}
_socket->write("\r\n\r\n");
// connect socket, start reading frames
setWebSocketPaused(false);
}
void HttpConnection::setWebSocketPaused (bool paused)
{
if (_webSocketPaused = paused) {
_socket->disconnect(this, SLOT(readFrames()));
} else {
connect(_socket, SIGNAL(readyRead()), SLOT(readFrames()));
readFrames();
}
}
void HttpConnection::closeWebSocket (quint16 reasonCode, const char* reason)
{
if (reasonCode == NoReason) {
writeFrameHeader(ConnectionClose);
} else {
int rlen = (reason == 0) ? 0 : qstrlen(reason);
writeFrameHeader(ConnectionClose, 2 + rlen);
_stream << reasonCode;
if (rlen > 0) {
_socket->write(reason);
}
}
_closeSent = true;
}
void HttpConnection::readRequest ()
{
if (!_socket->canReadLine()) {
return;
}
// parse out the method and resource
QByteArray line = _socket->readLine().trimmed();
if (line.startsWith("HEAD")) {
_requestOperation = QNetworkAccessManager::HeadOperation;
} else if (line.startsWith("GET")) {
_requestOperation = QNetworkAccessManager::GetOperation;
} else if (line.startsWith("PUT")) {
_requestOperation = QNetworkAccessManager::PutOperation;
} else if (line.startsWith("POST")) {
_requestOperation = QNetworkAccessManager::PostOperation;
} else if (line.startsWith("DELETE")) {
_requestOperation = QNetworkAccessManager::DeleteOperation;
} else {
qWarning() << "Unrecognized HTTP operation." << _address << line;
respond("400 Bad Request", "Unrecognized operation.");
return;
}
int idx = line.indexOf(' ') + 1;
_requestUrl.setEncodedUrl(line.mid(idx, line.lastIndexOf(' ') - idx));
// switch to reading the header
_socket->disconnect(this, SLOT(readRequest()));
connect(_socket, SIGNAL(readyRead()), SLOT(readHeaders()));
// read any headers immediately available
readHeaders();
}
void HttpConnection::readHeaders ()
{
while (_socket->canReadLine()) {
QByteArray line = _socket->readLine();
QByteArray trimmed = line.trimmed();
if (trimmed.isEmpty()) {
_socket->disconnect(this, SLOT(readHeaders()));
QByteArray clength = _requestHeaders.value("Content-Length");
if (clength.isEmpty()) {
_app->httpManager()->handleRequest(this, "", _requestUrl.path());
} else {
_requestContent.resize(clength.toInt());
connect(_socket, SIGNAL(readyRead()), SLOT(readContent()));
// read any content immediately available
readContent();
}
return;
}
char first = line.at(0);
if (first == ' ' || first == '\t') { // continuation
_requestHeaders[_lastRequestHeader].append(trimmed);
continue;
}
int idx = trimmed.indexOf(':');
if (idx == -1) {
qWarning() << "Invalid header." << _address << trimmed;
respond("400 Bad Request", "The header was malformed.");
return;
}
_lastRequestHeader = trimmed.left(idx);
QByteArray& value = _requestHeaders[_lastRequestHeader];
if (!value.isEmpty()) {
value.append(", ");
}
value.append(trimmed.mid(idx + 1).trimmed());
}
}
void HttpConnection::readContent ()
{
int size = _requestContent.size();
if (_socket->bytesAvailable() < size) {
return;
}
_socket->read(_requestContent.data(), size);
_socket->disconnect(this, SLOT(readContent()));
_app->httpManager()->handleRequest(this, "", _requestUrl.path());
}
void HttpConnection::readFrames()
{
// read as many messages as are available
while (maybeReadFrame());
}
bool HttpConnection::maybeReadFrame ()
{
// make sure we have at least the first two bytes
qint64 available = _socket->bytesAvailable();
if (available < 2 || _webSocketPaused) {
return false;
}
// read the first two, which tell us whether we need more for the length
quint8 finalOpcode, maskLength;
_stream >> finalOpcode;
_stream >> maskLength;
available -= 2;
int byteLength = maskLength & 0x7F;
bool masked = (maskLength & 0x80) != 0;
int baseLength = (masked ? 4 : 0);
int length = -1;
if (byteLength == 127) {
if (available >= 8) {
quint64 longLength;
_stream >> longLength;
if (available >= baseLength + 8 + longLength) {
length = longLength;
} else {
unget(_socket, longLength & 0xFFFFFFFF);
unget(_socket, longLength >> 32);
}
}
} else if (byteLength == 126) {
if (available >= 2) {
quint16 shortLength;
_stream >> shortLength;
if (available >= baseLength + 2 + shortLength) {
length = shortLength;
} else {
_socket->ungetChar(shortLength & 0xFF);
_socket->ungetChar(shortLength >> 8);
}
}
} else if (available >= baseLength + byteLength) {
length = byteLength;
}
if (length == -1) {
_socket->ungetChar(maskLength);
_socket->ungetChar(finalOpcode);
return false;
}
// read the mask and set it in the filter
quint32 mask = 0;
if (masked) {
_stream >> mask;
}
_unmasker->setMask(mask);
// if not final, add to continuing message
FrameOpcode opcode = (FrameOpcode)(finalOpcode & 0x0F);
if ((finalOpcode & 0x80) == 0) {
if (opcode != ContinuationFrame) {
_continuingOpcode = opcode;
}
_continuingMessage += _unmasker->read(length);
return true;
}
// if continuing, add to and read from buffer
QIODevice* device = _unmasker;
FrameOpcode copcode = opcode;
if (opcode == ContinuationFrame) {
_continuingMessage += _unmasker->read(length);
device = new QBuffer(&_continuingMessage, this);
device->open(QIODevice::ReadOnly);
copcode = _continuingOpcode;
}
// act according to opcode
switch (copcode) {
case TextFrame:
emit webSocketMessageAvailable(device, length, true);
break;
case BinaryFrame:
emit webSocketMessageAvailable(device, length, false);
break;
case ConnectionClose:
// if this is not a response to our own close request, send a close reply
if (!_closeSent) {
closeWebSocket(GoingAway);
}
if (length >= 2) {
QDataStream stream(device);
quint16 reasonCode;
stream >> reasonCode;
emit webSocketClosed(reasonCode, device->read(length - 2));
} else {
emit webSocketClosed(0, QByteArray());
}
_socket->disconnectFromHost();
break;
case Ping:
// send the pong out immediately
writeFrameHeader(Pong, length, true);
_socket->write(device->read(length));
break;
case Pong:
qWarning() << "Got unsolicited WebSocket pong." << _address << device->read(length);
break;
default:
qWarning() << "Received unknown WebSocket opcode." << _address << opcode <<
device->read(length);
break;
}
// clear the continuing message buffer
if (opcode == ContinuationFrame) {
_continuingMessage.clear();
delete device;
}
return true;
}
void HttpConnection::writeFrameHeader (FrameOpcode opcode, int size, bool final)
{
if (_closeSent) {
qWarning() << "Writing frame header after close message." << _address << opcode;
return;
}
_socket->putChar((final ? 0x80 : 0x0) | opcode);
if (size < 126) {
_socket->putChar(size);
} else if (size < 65536) {
_socket->putChar(126);
_stream << (quint16)size;
} else {
_socket->putChar(127);
_stream << (quint64)size;
}
}
MaskFilter::MaskFilter (QIODevice* device, QObject* parent) :
QIODevice(parent),
_device(device)
{
open(ReadOnly);
}
void MaskFilter::setMask (quint32 mask)
{
_mask[0] = (mask >> 24);
_mask[1] = (mask >> 16) & 0xFF;
_mask[2] = (mask >> 8) & 0xFF;
_mask[3] = mask & 0xFF;
_position = 0;
reset();
}
qint64 MaskFilter::bytesAvailable () const
{
return _device->bytesAvailable() + QIODevice::bytesAvailable();
}
qint64 MaskFilter::readData (char* data, qint64 maxSize)
{
qint64 bytes = _device->read(data, maxSize);
for (char* end = data + bytes; data < end; data++) {
*data ^= _mask[_position];
_position = (_position + 1) % 4;
}
return bytes;
}
qint64 MaskFilter::writeData (const char* data, qint64 maxSize)
{
return _device->write(data, maxSize);
}
| 29.92766 | 97 | 0.577918 | ey6es |
da275a58a51b51647548ebb195f5e2cd634084e0 | 10,163 | cc | C++ | build/X86_MESI_Two_Level/cpu/o3/O3CPU.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | build/X86_MESI_Two_Level/cpu/o3/O3CPU.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86_MESI_Two_Level/cpu/o3/O3CPU.py.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_O3CPU[] = {
120,156,165,152,89,115,27,55,18,128,65,74,166,14,203,214,
101,217,241,61,190,233,67,86,108,199,142,227,56,137,117,218,
76,100,73,30,82,113,69,47,172,225,0,20,97,13,103,232,
1,70,22,183,178,85,91,229,125,221,170,60,236,79,216,31,
178,143,251,184,255,104,183,187,49,32,65,217,113,42,137,40,
141,6,31,26,141,110,28,141,6,67,150,255,140,195,223,51,
143,49,149,194,11,135,223,2,219,99,44,42,176,157,2,43,
96,185,200,246,138,172,150,191,13,153,183,33,182,55,204,162,
97,182,51,220,147,57,98,106,134,217,94,137,69,37,182,83,
234,213,140,64,205,17,38,134,89,179,192,120,137,253,157,177,
247,140,253,180,51,202,248,8,171,150,71,161,91,249,63,248,
41,23,224,77,99,177,145,201,136,175,198,251,134,224,227,150,
121,29,129,199,82,160,196,242,214,182,1,99,240,216,124,176,
220,18,225,158,72,53,186,178,34,82,185,15,104,107,59,180,
30,14,99,43,244,240,31,240,38,24,58,6,150,237,20,209,
213,157,33,52,12,172,68,171,160,72,118,130,123,121,177,68,
197,97,91,28,97,98,148,201,49,6,238,128,35,239,139,108,
103,220,146,17,198,71,137,28,37,50,193,56,192,113,34,199,
28,114,148,200,113,135,76,16,153,116,200,49,34,83,86,243,
113,198,39,137,76,91,50,197,248,52,145,25,75,102,24,159,
37,50,235,232,57,65,228,132,67,230,136,204,57,228,36,145,
147,14,57,69,228,148,211,251,103,68,62,115,100,78,19,57,
237,144,51,68,206,56,228,44,145,179,142,158,115,68,206,57,
50,231,137,156,183,228,2,227,23,137,92,112,100,60,34,23,
29,61,151,136,120,14,185,76,228,146,67,174,16,185,76,228,
10,19,87,113,201,241,171,4,175,57,202,175,17,185,238,144,
235,68,110,56,170,110,16,41,59,164,76,228,166,109,117,147,
241,91,68,110,57,122,110,19,185,109,91,221,97,124,158,200,
29,135,220,37,50,239,76,226,2,145,187,14,249,156,200,130,
37,247,24,191,79,228,115,34,247,152,184,207,248,3,34,15,
172,204,23,140,63,36,242,133,37,143,24,255,146,200,67,135,
60,38,242,200,18,248,253,138,200,151,150,60,97,252,107,34,
143,29,242,148,200,87,184,5,118,158,48,241,53,227,223,176,
211,124,155,189,41,177,100,154,21,196,83,38,31,163,115,39,
160,54,134,8,98,90,10,104,249,140,90,126,227,44,226,69,
34,223,90,178,196,248,50,145,239,28,155,86,136,60,35,178,
200,248,42,227,107,68,150,44,121,206,248,11,34,203,68,86,
24,175,48,254,61,145,85,71,230,7,34,107,142,204,58,145,
231,142,204,75,34,47,28,153,13,34,21,43,179,201,248,22,
145,239,137,252,192,196,58,227,175,152,120,201,36,72,66,192,
243,169,118,211,206,77,62,58,223,177,55,16,108,170,84,183,
197,120,13,195,201,206,43,230,87,203,63,66,104,242,49,62,
169,73,120,132,157,108,33,121,176,192,49,132,221,109,181,66,
12,113,246,111,25,3,24,74,66,208,170,150,139,240,178,161,
75,24,2,101,91,198,187,101,140,115,38,36,14,161,162,72,
25,130,15,122,93,104,37,109,1,143,120,183,155,45,236,138,
246,195,249,102,119,65,165,225,66,222,39,69,204,187,157,174,
62,10,194,109,209,78,210,110,189,157,112,113,19,21,96,111,
172,248,113,115,52,3,115,144,108,152,238,145,213,210,76,80,
201,47,89,35,254,128,37,199,65,56,21,111,51,153,138,122,
24,132,45,161,230,127,167,49,254,168,29,149,63,101,200,52,
182,200,58,157,36,213,117,29,236,137,122,178,47,210,123,125,
91,36,169,60,6,143,74,44,181,12,34,47,76,178,88,203,
255,32,198,241,92,70,235,189,45,104,175,36,90,163,230,232,
160,10,97,124,61,157,120,77,161,195,150,199,69,20,116,169,
198,23,113,208,254,160,230,58,234,87,42,19,11,171,7,34,
204,180,88,120,157,74,45,26,65,184,247,49,37,203,73,187,
45,245,161,26,57,106,77,90,35,248,78,114,221,146,207,16,
158,233,193,70,214,108,138,212,83,242,47,194,147,177,215,232,
106,161,164,103,71,205,200,188,205,68,38,122,34,109,25,166,
201,124,210,81,94,71,164,243,186,149,138,128,171,147,3,158,
112,227,173,177,239,198,167,93,25,144,61,57,224,203,64,213,
92,207,156,195,53,19,253,241,37,23,127,171,199,212,216,249,
177,30,63,168,234,207,219,64,213,68,223,221,126,151,125,53,
191,214,185,153,22,92,71,212,160,63,96,159,108,160,238,91,
127,80,84,24,33,83,229,149,101,172,69,26,195,42,132,42,
13,235,174,178,250,218,83,58,216,21,55,21,110,169,21,169,
58,65,111,242,105,49,24,77,166,140,113,168,223,155,97,39,
112,160,179,56,212,50,65,189,219,176,202,189,78,146,68,191,
53,172,161,113,223,152,124,97,192,189,84,36,41,196,57,187,
216,250,99,152,15,153,233,24,65,245,109,22,40,187,84,113,
147,17,173,165,65,199,139,2,45,226,176,171,102,250,11,193,
193,242,8,10,223,65,97,9,157,186,203,186,153,64,207,96,
228,187,32,229,138,204,204,98,25,6,232,159,186,245,107,13,
224,15,229,15,137,159,195,104,147,181,27,32,153,52,189,40,
9,120,190,57,68,172,83,41,148,58,63,32,160,116,146,138,
65,9,73,241,255,246,128,88,39,10,66,161,112,160,84,75,
54,181,23,112,14,22,139,38,54,14,49,219,85,21,28,154,
86,146,69,28,6,175,35,98,142,46,123,251,50,137,140,93,
32,109,36,5,39,235,209,50,229,93,55,6,40,15,200,155,
76,233,188,40,127,249,239,16,35,149,131,174,44,24,115,101,
172,180,178,221,227,146,130,30,189,78,42,184,12,161,30,76,
36,51,26,40,184,31,68,146,195,248,115,137,105,55,57,191,
30,64,63,20,132,192,20,163,80,7,141,200,132,15,117,10,
253,32,168,132,246,42,43,110,221,233,1,131,252,124,201,44,
209,188,40,137,161,95,93,29,28,182,86,87,193,196,68,30,
238,129,93,96,169,216,149,10,182,131,58,60,190,86,176,9,
110,106,56,64,97,61,67,155,190,60,221,37,106,139,254,243,
213,90,189,82,93,164,83,53,72,219,244,255,224,241,35,117,
241,227,234,194,208,233,242,202,128,12,14,98,154,209,30,58,
52,255,255,198,249,247,6,132,15,109,15,187,150,112,15,85,
95,214,188,190,32,45,123,180,191,102,162,174,166,45,3,32,
18,57,153,202,219,152,13,210,73,34,25,154,83,126,43,72,
181,68,115,132,9,214,40,180,94,125,229,85,91,65,138,26,
183,72,84,114,180,238,138,83,143,122,97,202,97,198,123,146,
65,10,219,26,125,158,203,229,42,135,213,168,203,253,154,79,
41,176,134,248,155,75,135,53,92,113,170,62,161,130,102,206,
135,3,152,251,73,3,6,125,58,111,150,7,22,163,140,132,
226,172,157,143,17,13,210,82,26,196,48,66,91,118,93,211,
210,92,141,105,57,214,170,155,222,75,202,138,60,204,138,34,
74,63,48,106,143,219,244,227,95,38,253,128,236,236,52,92,
233,48,27,254,27,228,131,67,116,33,46,224,117,250,175,144,
12,235,34,230,205,63,195,133,119,8,47,144,144,44,193,189,
81,31,193,171,35,60,223,179,97,168,170,151,216,207,5,76,
125,81,108,132,193,145,13,137,37,190,151,88,125,196,169,26,
27,172,50,112,156,229,197,113,22,79,65,255,227,236,249,11,
152,108,188,118,154,219,124,181,140,33,116,195,199,5,224,227,
90,113,174,222,152,35,45,166,237,218,250,18,221,194,223,37,
233,30,6,1,90,44,226,64,234,205,120,53,77,33,137,65,
13,89,7,119,185,37,179,40,30,164,241,102,28,117,55,227,
117,104,100,56,69,54,220,201,24,133,87,125,127,211,127,226,
229,151,117,47,1,89,47,79,171,32,48,192,124,1,92,244,
95,122,176,221,46,81,154,68,86,169,124,231,149,233,128,197,
76,203,199,112,239,35,246,177,95,141,97,126,45,136,148,160,
116,143,190,35,8,243,47,4,80,72,234,134,143,51,73,5,
174,27,228,38,164,120,117,56,80,134,115,207,40,159,54,214,
138,168,73,29,252,209,100,17,7,7,162,117,238,229,114,39,
251,39,170,192,101,205,10,211,133,169,226,100,161,4,159,137,
194,89,248,204,14,29,41,80,215,214,73,149,135,151,50,58,
74,147,80,175,227,137,89,175,211,130,173,99,74,158,69,88,
164,108,183,219,17,196,195,131,131,122,11,214,49,120,140,115,
21,70,129,82,176,23,90,9,247,113,52,124,252,150,196,31,
183,99,69,59,133,148,111,199,74,238,194,246,167,66,0,161,
105,95,106,179,53,40,223,166,132,149,134,107,185,27,70,66,
105,28,23,147,103,213,18,10,39,43,120,108,19,54,185,208,
0,198,76,66,138,119,31,136,154,172,96,0,99,151,116,66,
188,198,83,158,90,82,209,132,250,42,172,32,186,13,16,123,
133,177,147,208,172,211,175,201,202,140,182,41,219,177,11,103,
157,158,93,62,99,245,14,226,163,61,87,141,73,61,157,38,
133,249,80,231,97,110,199,201,229,71,123,6,247,149,218,246,
144,165,245,173,183,94,245,32,106,148,152,104,213,146,60,211,
50,28,87,27,207,19,58,163,115,220,74,154,34,206,255,187,
134,121,199,153,92,219,222,130,196,141,218,173,136,102,144,69,
58,39,88,217,204,232,181,231,171,9,153,31,154,5,17,184,
239,144,113,192,244,128,101,69,249,90,191,140,41,217,186,201,
200,72,137,25,108,7,162,16,38,99,208,91,127,166,77,174,
101,17,46,224,245,87,171,230,20,164,82,181,87,66,157,112,
44,173,136,14,237,185,42,230,75,180,61,150,192,23,19,18,
142,25,17,170,199,224,164,52,238,71,74,69,234,144,117,212,
97,113,7,105,29,238,46,50,49,123,97,125,173,90,163,142,
177,80,173,86,76,97,196,156,25,112,172,40,50,18,222,183,
224,224,175,196,218,23,187,198,144,28,173,97,86,65,16,15,
196,58,55,35,189,97,42,151,151,177,134,66,25,217,89,133,
144,67,38,198,110,61,29,228,64,42,61,71,115,17,24,124,
75,80,185,106,163,94,155,6,216,44,0,103,179,170,241,96,
36,75,65,136,36,242,195,111,194,32,24,146,28,96,216,1,
55,104,227,153,138,222,1,107,230,180,173,43,86,246,184,45,
247,69,114,125,96,89,46,51,217,3,125,161,156,153,53,229,
200,153,99,183,119,234,146,178,90,146,165,184,212,98,189,180,
69,190,64,204,130,130,143,103,57,173,240,70,175,17,77,81,
44,32,135,129,51,218,191,56,16,185,127,127,248,166,239,98,
174,97,171,95,224,129,145,186,84,156,28,198,207,76,17,62,
5,248,152,103,97,102,168,247,94,116,254,219,247,194,92,239,
45,151,203,75,99,249,167,215,110,168,84,152,30,153,238,179,
194,161,79,113,130,234,102,11,99,197,141,242,152,29,128,246,
195,187,176,170,100,44,242,133,52,102,88,7,99,187,162,49,
193,82,154,28,116,125,60,96,252,103,189,51,179,201,242,175,
156,254,204,56,81,15,79,205,105,244,45,38,249,116,181,156,
42,140,195,103,202,252,21,255,15,160,216,27,75,
};
EmbeddedPython embedded_m5_objects_O3CPU(
"m5/objects/O3CPU.py",
"/home/hongyu/gem5-fy/src/cpu/o3/O3CPU.py",
"m5.objects.O3CPU",
data_m5_objects_O3CPU,
2541,
6242);
} // anonymous namespace
| 57.744318 | 66 | 0.6626 | hoho20000000 |
da2a558a04a056022ed85842d70ea520484946a9 | 56 | hpp | C++ | src/boost_fusion_sequence_intrinsic_value_at.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_fusion_sequence_intrinsic_value_at.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_fusion_sequence_intrinsic_value_at.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/fusion/sequence/intrinsic/value_at.hpp>
| 28 | 55 | 0.821429 | miathedev |
da2c9a77307d69ebec5e3dc5b6ca812c83bcd4d4 | 1,867 | cpp | C++ | rawdev/Partition.cpp | NicolaiNyberg/rawdev | 93069ea7a95d5fc1662ac14bd00e9e69f4220b8f | [
"BSD-3-Clause"
] | 2 | 2016-07-15T14:50:33.000Z | 2021-06-21T05:53:08.000Z | rawdev/Partition.cpp | NicolaiNyberg/rawdev | 93069ea7a95d5fc1662ac14bd00e9e69f4220b8f | [
"BSD-3-Clause"
] | null | null | null | rawdev/Partition.cpp | NicolaiNyberg/rawdev | 93069ea7a95d5fc1662ac14bd00e9e69f4220b8f | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2016, Nicolai R. Nyberg
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. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Partition.h"
#include "Finders.h"
HRESULT Partition::Open(bool isRead, DWORD desiredAccess, DWORD devFlags, HANDLE & h) const
{
auto d = FindDrive(disk);
if (!d) return ERROR_FILE_NOT_FOUND;
auto hr = d->Open(isRead, desiredAccess, devFlags, h);
if (hr) return hr;
if (!SetPosition(h, offset))
return GetLastError();
return 0;
}
| 41.488889 | 91 | 0.78361 | NicolaiNyberg |
da3e450ee4ebba4325448b288dade730d02bb22d | 17,900 | cc | C++ | apps/node_creator.cc | imonlius/interactive-neurons | da8cbdad8cf5595a2be1b48125ecad5e6c802f2c | [
"MIT"
] | 2 | 2020-05-10T00:29:17.000Z | 2020-05-16T21:55:31.000Z | apps/node_creator.cc | imonlius/interactive-neurons | da8cbdad8cf5595a2be1b48125ecad5e6c802f2c | [
"MIT"
] | null | null | null | apps/node_creator.cc | imonlius/interactive-neurons | da8cbdad8cf5595a2be1b48125ecad5e6c802f2c | [
"MIT"
] | null | null | null | // Copyright (c) 2020 Simon Liu. All rights reserved.
#include <cinder/CinderImGui.h>
#include <imnodes.h>
#include "mnist-utilities.h"
#include "node_creator.h"
using neurons::Node;
namespace neurons::spawner {
bool SpawnMnistDataNode(neurons::Network& network,
const std::string& data_directory, dim_t batch_size) {
// Initialize DataNode of the Network
af::array train_x;
af::array train_y;
af::array test_x;
af::array test_y;
// train_x and train_y are passed as references
std::tie(train_x, train_y) =
mnist_utilities::load_dataset(data_directory, false);
std::tie(test_x, test_y) =
mnist_utilities::load_dataset(data_directory,true);
// Hold out the validation sets
auto valid_x = train_x(af::span, af::span, 0,
af::seq(0, mnist_utilities::kValSize - 1));
train_x = train_x(af::span, af::span, 0,
af::seq(mnist_utilities::kValSize, mnist_utilities::kTrainSize - 1));
auto valid_y = train_y(
af::seq(0, mnist_utilities::kValSize - 1));
train_y = train_y(
af::seq(mnist_utilities::kValSize,mnist_utilities::kTrainSize - 1));
// Make the BatchDatasets
auto train_set = fl::BatchDataset(std::make_shared<fl::TensorDataset>(
std::vector<af::array>{train_x, train_y}), batch_size);
auto valid_set = fl::BatchDataset(std::make_shared<fl::TensorDataset>(
std::vector<af::array>{valid_x, valid_y}), batch_size);
auto test_set = fl::BatchDataset(std::make_shared<fl::TensorDataset>(
std::vector<af::array>{test_x, test_y}), batch_size);
network.AddNode(std::make_unique<fl::BatchDataset>(train_set),
std::make_unique<fl::BatchDataset>(valid_set),
std::make_unique<fl::BatchDataset>(test_set));
return true;
}
// Spawn an Activation Node of the passed NodeType. If type does not
// correspond to a valid activation node type, do nothing. Returns true
// if successful.
bool SpawnActivationNode(neurons::Network& network, neurons::NodeType type) {
std::unique_ptr<fl::Module> module;
switch (type) {
case Sigmoid:
module = std::make_unique<fl::Sigmoid>(fl::Sigmoid());
break;
case Tanh:
module = std::make_unique<fl::Tanh>(fl::Tanh());
break;
case HardTanh:
module = std::make_unique<fl::HardTanh>(fl::HardTanh());
break;
case ReLU:
module = std::make_unique<fl::ReLU>(fl::ReLU());
break;
case LeakyReLU:
module = std::make_unique<fl::LeakyReLU>(fl::LeakyReLU());
break;
case ELU:
module = std::make_unique<fl::ELU>(fl::ELU());
break;
case ThresholdReLU:
module = std::make_unique<fl::ThresholdReLU>(fl::ThresholdReLU());
break;
case GatedLinearUnit:
module = std::make_unique<fl::GatedLinearUnit>(fl::GatedLinearUnit());
break;
case LogSoftmax:
module = std::make_unique<fl::LogSoftmax>(fl::LogSoftmax());
break;
case Log:
module = std::make_unique<fl::Log>(fl::Log());
break;
default:
// if no activation node is selected
return false;
}
network.AddNode(type, std::move(module));
return true;
}
// Spawn an Loss Node of the passed NodeType. If type does not
// correspond to a valid loss node type, do nothing. Returns true
// if successful.
bool SpawnLossNode(neurons::Network& network, neurons::NodeType type) {
std::unique_ptr<fl::BinaryModule> module;
switch (type) {
case CategoricalCrossEntropy:
module = std::make_unique<fl::CategoricalCrossEntropy>(
fl::CategoricalCrossEntropy());
break;
case MeanAbsoluteError:
module = std::make_unique<fl::MeanAbsoluteError>(fl::MeanAbsoluteError());
break;
case MeanSquaredError:
module = std::make_unique<fl::MeanSquaredError>(fl::MeanSquaredError());
break;
default:
// if no loss node is selected
return false;
}
network.AddNode(type, std::move(module));
return true;
}
// Starts pop-up configuration for a new BatchNorm Node.
// Returns true if spawning was successful. Sets freeze_editor to whether
// method is currently controlling the GUI.
bool SpawnBatchNormNode(neurons::Network& network, bool& freeze_editor) {
bool node_created = false;
ImGui::OpenPopup("BatchNorm");
if (ImGui::BeginPopupModal("BatchNorm")) {
static int int_args[2]; // must be static to be preserved between draws
static double double_args[2];
static bool bool_args[2];
const std::string labels[] = {"Feature Axis", "Feature Size",
"Momentum", "Epsilon", "Affine",
"Track Stats"};
for (size_t i = 0; i < 6; ++i) {
ImGui::Text("%s", labels[i].c_str());
std::string label = "##" + labels[i]; // ## makes invis. label
if (i < 2) {
ImGui::InputInt(label.c_str(), &int_args[i]);
} else if (i < 4) {
// subtract 2 from index to account for separate array
ImGui::InputDouble(label.c_str(), &double_args[i - 2]);
} else {
// subtract 4 from index to account for separate array
ImGui::Checkbox(label.c_str(), &bool_args[i - 4]);
}
}
if (ImGui::Button("Cancel")) {
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Add Node")) {
// arguments valid if Feature Axis >= 0 and Feature Size > 0
bool args_valid = (int_args[0] >= 0 && int_args[1] > 0);
if (args_valid) {
network.AddNode(BatchNorm, std::make_unique<fl::BatchNorm>(
fl::BatchNorm(int_args[0], int_args[1], double_args[0],
double_args[1], bool_args[0], bool_args[1])));
node_created = true;
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
}
ImGui::EndPopup();
}
return node_created;
}
// Starts pop-up configuration for a new LayerNorm Node.
// Returns true if spawning was successful. Sets freeze_editor to whether
// method is currently controlling the GUI.
bool SpawnLayerNormNode(neurons::Network& network, bool& freeze_editor) {
bool node_created = false;
ImGui::OpenPopup("LayerNorm");
if (ImGui::BeginPopupModal("LayerNorm")) {
static int axis; // must be static to be preserved between draws
static double epsilon;
static bool affine;
// for axisSize, uses fl::kLnVariableAxisSize
const std::string labels[] = {"Normalization Axis", "Epsilon", "Affine"};
ImGui::Text("%s", labels[0].c_str());
ImGui::InputInt(("##" + labels[0]).c_str(), &axis);
ImGui::Text("%s", labels[1].c_str());
ImGui::InputDouble(("##" + labels[1]).c_str(), &epsilon);
ImGui::Text("%s", labels[2].c_str());
ImGui::Checkbox(("##" + labels[2]).c_str(), &affine);
if (ImGui::Button("Cancel")) {
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Add Node")) {
// arguments valid if Feature Axis >= 0
bool args_valid = (axis >= 0);
if (args_valid) {
network.AddNode(LayerNorm, std::make_unique<fl::LayerNorm>(
fl::LayerNorm(axis, epsilon, affine, fl::kLnVariableAxisSize)));
node_created = true;
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
}
ImGui::EndPopup();
}
return node_created;
}
// Starts pop-up configuration for a new Dropout Node.
// Returns true if spawning was successful. Sets freeze_editor to whether
// method is currently controlling the GUI.
bool SpawnDropoutNode(neurons::Network& network, bool& freeze_editor) {
bool node_created = false;
ImGui::OpenPopup("Dropout");
if (ImGui::BeginPopupModal("Dropout")) {
static double ratio; // must be static to be preserved between draws
const std::string labels[] = {"Dropout Ratio"};
ImGui::Text("%s", labels[0].c_str());
// ## makes invis. label
ImGui::InputDouble(("##" + labels[0]).c_str(), &ratio);
if (ImGui::Button("Cancel")) {
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Add Node")) {
// Check that arguments are valid
bool args_valid = (ratio >= 0 && ratio < 1);
if (args_valid) {
network.AddNode(Dropout,std::make_unique<fl::Dropout>(
fl::Dropout(ratio)));
node_created = true;
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
}
ImGui::EndPopup();
}
return node_created;
}
// Starts pop-up configuration for a new View Node.
// Returns true if spawning was successful. Sets freeze_editor to whether
// method is currently controlling the GUI.
bool SpawnViewNode(neurons::Network& network, bool& freeze_editor) {
bool node_created = false;
ImGui::OpenPopup("View");
if (ImGui::BeginPopupModal("View")) {
static int dims[4];
const std::string labels[] = {"Dimension 1", "Dimension 2",
"Dimension 3", "Dimenison 4"};
for (size_t i = 0; i < 4; ++i ) {
ImGui::Text("%s", labels[i].c_str());
std::string label = "##" + labels[i]; // ## makes invis. label
ImGui::InputInt(label.c_str(), &dims[i]);
}
if (ImGui::Button("Cancel")) {
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Add Node")) {
// Check that arguments are valid
bool args_valid = true;
// View must have either nonnegative or -1 arguments
size_t num_negative_one = 0;
for (int dim : dims) {
if (dim == -1) {
++num_negative_one;
} else if (dim < 0) {
args_valid = false;
}
}
// View can only have one -1 argument
if (num_negative_one > 1) {
args_valid = false;
}
if (args_valid) {
network.AddNode(View, std::make_unique<fl::View>(
fl::View(af::dim4(
dims[0], dims[1], dims[2], dims[3]))));
node_created = true;
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
}
ImGui::EndPopup();
}
return node_created;
}
// Starts pop-up configuration for a new Conv2D Node.
// Returns true if spawning was successful. Sets freeze_editor to whether
// method is currently controlling the GUI.
bool SpawnConv2DNode(neurons::Network& network, bool& freeze_editor) {
bool node_created = false;
ImGui::OpenPopup("Conv2D");
if (ImGui::BeginPopupModal("Conv2D")) {
static int n_args[10]; // must be static to be preserved between draws
static bool bias;
const std::string labels[] = {"Input Channels", "Output Channels",
"Kernel X-dim Size", "Kernel Y-dim Size",
"Conv X-dim Stride", "Conv Y-dim Stride",
"Zero-Padding X-dim", "Zero-Padding Y-dim",
"Conv X-dim Dilation", "Conv Y-Dim Dilation"};
for (size_t i = 0; i < 10; ++i) {
ImGui::Text("%s", labels[i].c_str());
std::string label = "##" + labels[i]; // ## makes invis. label
ImGui::InputInt(label.c_str(), &n_args[i]);
}
ImGui::Checkbox("Learnable Bias: ", &bias);
if (ImGui::Button("Cancel")) {
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Add Node")) {
// Check that arguments are valid
bool args_valid = true;
for (size_t i = 0; i < 10; ++i) {
// zero-padding can be >= -1, everything else must be positive.
// zero-padding of -1 uses smallest possible padding such that
// out_size = ceil(in_size / stride)
if (!(n_args[i] > 0 || ((i == 6 || i == 7) && n_args[i] >= -1))) {
args_valid = false;
}
}
if (args_valid) {
network.AddNode(Conv2D,std::make_unique<fl::Conv2D>(
fl::Conv2D(n_args[0], n_args[1], n_args[2],
n_args[3],n_args[4], n_args[5], n_args[6],
n_args[7], n_args[8],n_args[9], bias)));
node_created = true;
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
}
ImGui::EndPopup();
}
return node_created;
}
// Starts pop-up configuration for a new Pool2D Node.
// Returns true if spawning was successful. Sets freeze_editor to whether
// method is currently controlling the GUI.
bool SpawnPool2DNode(neurons::Network& network, bool& freeze_editor) {
bool node_created = false;
ImGui::OpenPopup("Pool2D");
if (ImGui::BeginPopupModal("Pool2D")) {
static int n_args[6]; // must be static to be preserved between draws
const std::string labels[] = {
"Pooling Window X-dim", "Pooling Window Y-dim",
"Stride X-dim", "Stride Y-dim",
"Zero-Padding X-dim", "Zero-Padding Y-dim", "Pooling Mode"};
static std::string pooling_mode;
const std::string modes[] = {"MAX", "AVG_INCLUDE_PADDING",
"AVG_EXCLUDE_PADDING"};
for (size_t i = 0; i < 6; ++i) {
ImGui::Text("%s", labels[i].c_str());
std::string label = "##" + labels[i]; // ## makes invis. label
ImGui::InputInt(label.c_str(), &n_args[i]);
}
// Get the Pooling Mode from a dropdown selection
// derived from github.com/ocornut/imgui/issues/1658
ImGui::Text("%s", labels[6].c_str());
if (ImGui::BeginCombo(("##" + labels[6]).c_str(), pooling_mode.data())) {
for (const auto & mode : modes) {
bool is_selected = (pooling_mode == mode);
if (ImGui::Selectable(mode.c_str(), is_selected)) {
pooling_mode = mode;
}
if (is_selected) {
// sets the initial focus of the list when opened
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
// translate pooling_mode string into PoolingMode
fl::PoolingMode pooling;
if (pooling_mode == "MAX") {
pooling = fl::PoolingMode::MAX;
} else if (pooling_mode == "AVG_INCLUDE_POOLING") {
pooling = fl::PoolingMode::AVG_INCLUDE_PADDING;
} else {
pooling = fl::PoolingMode::AVG_EXCLUDE_PADDING;
}
if (ImGui::Button("Cancel")) {
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Add Node")) {
// Check that arguments are valid
// All fields must be greater than 0, except padding which must be >= -1
// zero-padding of -1 uses smallest possible padding such that
// out_size = ceil(in_size / stride)
bool args_valid = n_args[0] > 0 && n_args[1] > 0 && n_args[2] > 0 &&
n_args[3] > 0 && n_args[4] >= -1 && n_args[5] >= -1;
if (args_valid) {
network.AddNode(Pool2D, std::make_unique<fl::Pool2D>(
fl::Pool2D(n_args[0], n_args[1], n_args[2],
n_args[3],n_args[4], n_args[5], pooling)));
node_created = true;
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
}
ImGui::EndPopup();
}
return node_created;
}
// Starts pop-up configuration for a new Linear Node.
// Returns true if spawning was successful. Sets freeze_editor to whether
// method is currently controlling the GUI.
bool SpawnLinearNode(neurons::Network& network, bool& freeze_editor) {
bool node_created = false;
ImGui::OpenPopup("Linear");
if (ImGui::BeginPopupModal("Linear")) {
static int n_args[2]; // must be static to be preserved between draws
static bool bias;
const std::string labels[] = {"Input Size", "Output Size"};
for (size_t i = 0; i < 2; ++i) {
ImGui::Text("%s", labels[i].c_str());
std::string label = "##" + labels[i]; // ## makes invis. label
ImGui::InputInt(label.c_str(), &n_args[i]);
}
ImGui::Checkbox("Learnable Bias: ", &bias);
if (ImGui::Button("Cancel")) {
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Add Node")) {
// Check that arguments are valid
bool args_valid = (n_args[0] > 0 && n_args[1] > 0);
if (args_valid) {
network.AddNode(Linear,std::make_unique<fl::Linear>(
fl::Linear(n_args[0], n_args[1], bias)));
node_created = true;
freeze_editor = false;
ImGui::CloseCurrentPopup();
}
}
ImGui::EndPopup();
}
return node_created;
}
bool SpawnModuleNode(neurons::Network& network, neurons::NodeType type,
bool& freeze_editor) {
const std::vector config_types =
{BatchNorm, LayerNorm, Dropout, View, Conv2D, Pool2D, Linear};
// check if node requires a config pop up window.
if (std::find(config_types.begin(), config_types.end(), type) !=
config_types.end()) {
freeze_editor = true;
// default window spawn size is too small for editing
ImVec2 window_size = ImVec2(300, 300);
ImGui::SetNextWindowContentSize(window_size);
}
switch (type) {
case Sigmoid:
case Tanh:
case HardTanh:
case ReLU:
case LeakyReLU:
case ELU:
case ThresholdReLU:
case GatedLinearUnit:
case LogSoftmax:
case Log:
return SpawnActivationNode(network, type);
case CategoricalCrossEntropy:
case MeanAbsoluteError:
case MeanSquaredError:
return SpawnLossNode(network, type);
case BatchNorm:
return SpawnBatchNormNode(network, freeze_editor);
case LayerNorm:
return SpawnLayerNormNode(network, freeze_editor);
case Dropout:
return SpawnDropoutNode(network, freeze_editor);
case View:
return SpawnViewNode(network, freeze_editor);
case Conv2D:
return SpawnConv2DNode(network, freeze_editor);
case Pool2D:
return SpawnPool2DNode(network, freeze_editor);
case Linear:
return SpawnLinearNode(network, freeze_editor);
default:
return false;
}
}
} // namespace neurons::spawner | 32.904412 | 80 | 0.616201 | imonlius |
da43153b09481a6b64db4163963ca5576d975259 | 440 | hpp | C++ | Next Power of Two/include/powersOfTwo.hpp | sinamoghimi73/LazyCpp | 429b3481856c3be0a37dbcb3b3c05d3f71310e2f | [
"MIT"
] | 1 | 2021-07-11T18:30:03.000Z | 2021-07-11T18:30:03.000Z | Next Power of Two/include/powersOfTwo.hpp | sinamoghimi73/LazyCpp | 429b3481856c3be0a37dbcb3b3c05d3f71310e2f | [
"MIT"
] | null | null | null | Next Power of Two/include/powersOfTwo.hpp | sinamoghimi73/LazyCpp | 429b3481856c3be0a37dbcb3b3c05d3f71310e2f | [
"MIT"
] | null | null | null | //
// powersOfTwo.hpp
// Math
//
#ifndef powersOfTwo_h
#define powersOfTwo_h
#include <algorithm>
#include <vector>
namespace math {
bool isPowerOfTwo(int number) { return number && !(number & (number - 1)); }
int nextPowerOfTwo(int number) {
if (isPowerOfTwo(number))
return number;
int twosPower{1};
while (twosPower < number)
twosPower <<= 1;
return twosPower;
}
} // namespace math
#endif /* powersOfTwo_h */
| 14.666667 | 76 | 0.670455 | sinamoghimi73 |
da4cb9fb3310cd42b8428597f08a82a72eea53cd | 1,377 | hpp | C++ | apps/launcher/graphicspage.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/launcher/graphicspage.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/launcher/graphicspage.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #ifndef GRAPHICSPAGE_H
#define GRAPHICSPAGE_H
#include <QWidget>
#include <OgreRoot.h>
#include <OgreRenderSystem.h>
#include <components/ogreinit/ogreinit.hpp>
#include "ui_graphicspage.h"
namespace Files { struct ConfigurationManager; }
namespace Launcher
{
class GraphicsSettings;
class GraphicsPage : public QWidget, private Ui::GraphicsPage
{
Q_OBJECT
public:
GraphicsPage(Files::ConfigurationManager &cfg, GraphicsSettings &graphicsSettings, QWidget *parent = 0);
void saveSettings();
bool loadSettings();
public slots:
void rendererChanged(const QString &renderer);
void screenChanged(int screen);
private slots:
void slotFullScreenChanged(int state);
void slotStandardToggled(bool checked);
private:
OgreInit::OgreInit mOgreInit;
Ogre::Root *mOgre;
Ogre::RenderSystem *mSelectedRenderSystem;
Ogre::RenderSystem *mOpenGLRenderSystem;
Ogre::RenderSystem *mDirect3DRenderSystem;
Files::ConfigurationManager &mCfgMgr;
GraphicsSettings &mGraphicsSettings;
QStringList getAvailableOptions(const QString &key, Ogre::RenderSystem *renderer);
QStringList getAvailableResolutions(int screen);
QRect getMaximumResolution();
bool setupOgre();
bool setupSDL();
};
}
#endif
| 23.741379 | 112 | 0.693537 | Bodillium |
da5496dbc745f0c0f3b16b78bc2ef3adb17e62e5 | 491 | hxx | C++ | src/include/Settings.hxx | michael-gober/Smart_Symbolic_Graphing_Calculator | 56caaab9076d553de1fee24bb0e4f9e691c07e64 | [
"MIT"
] | null | null | null | src/include/Settings.hxx | michael-gober/Smart_Symbolic_Graphing_Calculator | 56caaab9076d553de1fee24bb0e4f9e691c07e64 | [
"MIT"
] | null | null | null | src/include/Settings.hxx | michael-gober/Smart_Symbolic_Graphing_Calculator | 56caaab9076d553de1fee24bb0e4f9e691c07e64 | [
"MIT"
] | 1 | 2021-11-20T21:25:15.000Z | 2021-11-20T21:25:15.000Z | #ifndef SETTINGS_HXX
#define SETTINGS_HXX
#include <lvgl/lvgl.h>
#include <calc_conf.h>
#if ENABLE_MCP_KEYPAD
#include <wiringPi.h>
#include <softPwm.h>
#endif
#include <stdlib.h>
#include <cstdio>
// #include "utils.hxx"
enum {
LV_MENU_ITEM_BUILDER_VARIANT_1,
LV_MENU_ITEM_BUILDER_VARIANT_2
};
typedef uint8_t lv_menu_builder_variant_t;
//static void switch_handler(lv_event_t * e);
//static void slider_event_cb(lv_event_t * e);
void createSettingsTab(lv_obj_t* parent);
#endif | 20.458333 | 46 | 0.773931 | michael-gober |
da56c172e745d9540553e4edce727aa1fe89662f | 2,080 | cxx | C++ | MUON/MUONrec/AliMUONVClusterServer.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | MUON/MUONrec/AliMUONVClusterServer.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | MUON/MUONrec/AliMUONVClusterServer.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
/// \class AliMUONVClusterServer
///
/// Interface of a cluster finder for combined tracking
///
/// The tracking, when in needs for clusters, will ask the cluster server
/// to add clusters, from a given region in a given chamber, to an existing
/// clusterstore, using the
///
/// Clusterize(Int_t chamberId, AliMUONVClusterStore& clusterStore, const AliMpArea& area)
///
/// method
///
/// Cluster server must be instructed (at the beginning of each event)
/// about which digits to use, using the
///
/// UseDigitStore(const AliMUONVDigitStore& digitStore)
///
/// method.
///
/// \author Laurent Aphecetche, Subatech
#include "AliMUONVClusterServer.h"
/// \cond CLASSIMP
ClassImp(AliMUONVClusterServer)
/// \endcond
//_____________________________________________________________________________
AliMUONVClusterServer::AliMUONVClusterServer()
{
/// ctor
}
//_____________________________________________________________________________
AliMUONVClusterServer::~AliMUONVClusterServer()
{
/// dtor
}
| 37.142857 | 90 | 0.618269 | AllaMaevskaya |
da57dc11f6e9455b654944a2ba35f9263bc6423e | 2,788 | cpp | C++ | OfferReview/OfferReview/Sort/01_bubbleSort/BubbleSort.cpp | chm994483868/HMDailyLearningRecord | 95ff0a5347927ce4527bcdd70374e5be22bfc60d | [
"MIT"
] | 2 | 2021-06-26T08:07:04.000Z | 2021-08-03T06:05:40.000Z | OfferReview/OfferReview/Sort/01_bubbleSort/BubbleSort.cpp | chm994483868/HMDailyLearningRecord | 95ff0a5347927ce4527bcdd70374e5be22bfc60d | [
"MIT"
] | null | null | null | OfferReview/OfferReview/Sort/01_bubbleSort/BubbleSort.cpp | chm994483868/HMDailyLearningRecord | 95ff0a5347927ce4527bcdd70374e5be22bfc60d | [
"MIT"
] | null | null | null | //
// BubbleSort.cpp
// OfferReview
//
// Created by CHM on 2020/8/4.
// Copyright © 2020 CHM. All rights reserved.
//
#include "BubbleSort.hpp"
int sum(int n) {
return n > 1? sum(n - 1) + n: 1;
}
void BubbleSort::bubbleSort(int nums[], int count) {
if (nums == nullptr || count <= 0) {
return;
}
int k = count - 1;
for (int i = 0; i < count - 1; ++i) {
bool noExchange = true;
int n = 0;
for (int j = 0; j < k; ++j) {
if (nums[j] > nums[j + 1]) {
swap(&nums[j], &nums[j + 1]);
noExchange = false;
n = j;
}
}
if (noExchange) {
break;
}
k = n;
}
//if (nums == nullptr || count <= 0) {
// return;
//}
//
//int k = count - 1; // 第二层循环的边界
//for (int i = 0; i < count - 1; ++i) {
// bool noExchange = true; // 标记一趟比较操作下来是否发生过交换,如果没有的话表示当前序列已经有序
// int n = 0; // 记录一趟排序中最后一次交换的两个相邻元素的最小下标,此后该最小下标以后的数据就都是有序的
// for (int j = 0; j < k; ++j) {
// if (nums[j] > nums[j + 1]) {
// swap(&nums[j], &nums[j + 1]);
// noExchange = false;
// n = j;
// }
// }
//
// if (noExchange) {
// break;
// }
// k = n; // 更新 k 值
//}
}
// 测试代码
void BubbleSort::test(char* testName, int nums[], int count) {
printf("%s begins: \n", testName);
printArray("", nums, count);
bubbleSort(nums, count);
printArray("", nums, count);
}
void BubbleSort::test1() {
int nums[9] = {4, 6, 1, 2, 9, 10, 20, 1, 1};
test("test1", nums, 9);
}
void BubbleSort::test2() {
int nums[8] = {1, 2, 3, 4, 5, 6, 7, 8};
test("test2", nums, 8);
}
void BubbleSort::test3() {
int nums[5] = {5, 4, 3, 2, 1};
test("test3", nums, 5);
}
void BubbleSort::test4() {
int nums[8] = {-4, 6, -2, 9, 10, -20, 1, -1};
test("test4", nums, 8);
}
void BubbleSort::test5() {
int nums[2] = {4, 2};
test("test5", nums, 2);
}
void BubbleSort::test6() {
int nums[] = {};
test("test5", nums, 0);
}
void BubbleSort::Test() {
test1();
test2();
test3();
test4();
test5();
test6();
}
//if (nums == nullptr || count <= 0) {
// return;
//}
//
//int k = count - 1; // 第二层循环的边界
//for (int i = 0; i < count - 1; ++i) {
// bool noExchange = true; // 标记一趟比较操作下来是否发生过交换,如果没有的话表示当前序列已经有序
// int n = 0; // 记录一趟排序中最后一次交换的两个相邻元素的最小下标,此后该最小下标以后的数据就都是有序的
// for (int j = 0; j < k; ++j) {
// if (nums[j] > nums[j + 1]) {
// swap(&nums[j], &nums[j + 1]);
// noExchange = false;
// n = j;
// }
// }
//
// if (noExchange) {
// break;
// }
// k = n; // 更新 k 值
//}
| 21.612403 | 71 | 0.445122 | chm994483868 |
da583ef22a4c40fc35c590c384b1ee57d11778d1 | 1,081 | cpp | C++ | examples/echo/tcpecho.cpp | Tonvey/HuoLun | f05e0faae6d397b18bf7ba198bc55c3a57844ee6 | [
"BSD-2-Clause"
] | null | null | null | examples/echo/tcpecho.cpp | Tonvey/HuoLun | f05e0faae6d397b18bf7ba198bc55c3a57844ee6 | [
"BSD-2-Clause"
] | null | null | null | examples/echo/tcpecho.cpp | Tonvey/HuoLun | f05e0faae6d397b18bf7ba198bc55c3a57844ee6 | [
"BSD-2-Clause"
] | null | null | null | #include "Huolun.h"
#include "HuolunCore/HTCPListenerComponent.h"
#include "HuolunCore/HTCPDataComponent.h"
#include "util/EchoLayer.hpp"
#include <iostream>
using namespace std;
//Factory create the next layer of new socket data component
class MyLayerFactory
:public HLayerFactory
{
public:
virtual HLayer *CreateLayer(HTCPDataComponent *dataComp)
{
auto echo = CreateObject<EchoLayer>();
echo->SetDstLayer(dataComp);
return echo;
}
};
void usage(std::string argv0)
{
cerr<<"Usage : "<<argv0<<" <bind port>"<<endl;
}
int main(int argc, char **argv)
{
if(argc!=2)
{
usage(argv[0]);
return -1;
}
uint16_t port=8899;
port = std::atoi(argv[1]);
Huolun core;
if(!core.Initialize())
{
cerr<<"Huolun init fail"<<endl;
return -1;
}
auto fact = CreateObject<MyLayerFactory>();
auto listen = CreateObject<HTCPListenerComponent>(port,fact);
core.RegisterChannel(listen);
fact->Release();
listen->Release();
core.Run();
core.Finish();
return 0;
}
| 23 | 65 | 0.635523 | Tonvey |
da5acfce2e340bab5dd5cfd12d94e23048341a27 | 9,822 | hpp | C++ | src/ttauri/GUI/draw_context.hpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | src/ttauri/GUI/draw_context.hpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | src/ttauri/GUI/draw_context.hpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | // Copyright Take Vos 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)
// Copyright 2020 Pokitec
// All rights reserved.
#pragma once
#include "gui_device_vulkan.hpp"
#include "gui_window.hpp"
#include "theme.hpp"
#include "pipeline_image_image.hpp"
#include "pipeline_flat_device_shared.hpp"
#include "pipeline_box_device_shared.hpp"
#include "pipeline_image_device_shared.hpp"
#include "pipeline_SDF_device_shared.hpp"
#include "pipeline_flat_vertex.hpp"
#include "pipeline_box_vertex.hpp"
#include "pipeline_image_vertex.hpp"
#include "pipeline_SDF_vertex.hpp"
#include "../numeric_array.hpp"
#include "../aarect.hpp"
#include "../vspan.hpp"
#include "../text/shaped_text.hpp"
#include "../color/color.hpp"
#include <type_traits>
namespace tt {
/** Draw context for drawing using the TTauri shaders.
*/
class draw_context {
public:
/// Foreground color.
color line_color = color(1.0, 1.0, 1.0, 1.0);
/// Fill color.
color fill_color = color(0.0, 0.0, 0.0, 0.0);
/// Size of lines.
float line_width = 1.0;
/** Shape of the corners of a box.
* The vector holds information for each corner:
* - x: left-bottom
* - y: right-bottom
* - z: left-top
* - w: right-top
*
* The value means:
* - zero: Sharp corner
* - positive: Rounded corner of that radius
* - negative: Cur corner of that radius
*/
f32x4 corner_shapes = f32x4{0.0, 0.0, 0.0, 0.0};
/** The clipping rectangle when drawing.
* The clipping rectangle is passes as-is to the pipelines and
* is not modified by the transform.
*/
aarect clipping_rectangle;
/** Transform used on the given coordinates.
* The z-axis translate is used for specifying the elevation
* (inverse depth buffer) of the shape.
*/
matrix3 transform = geo::identity{};
draw_context(
gui_window &window,
aarect scissor_rectangle,
vspan<pipeline_flat::vertex> &flatVertices,
vspan<pipeline_box::vertex> &boxVertices,
vspan<pipeline_image::vertex> &imageVertices,
vspan<pipeline_SDF::vertex> &sdfVertices) noexcept :
_window(&window),
_scissor_rectangle(scissor_rectangle),
_flat_vertices(&flatVertices),
_box_vertices(&boxVertices),
_image_vertices(&imageVertices),
_sdf_vertices(&sdfVertices),
line_color(0.0, 1.0, 0.0, 1.0),
fill_color(1.0, 1.0, 0.0, 1.0),
line_width(theme::global->borderWidth),
corner_shapes(),
clipping_rectangle(static_cast<f32x4>(window.extent))
{
_flat_vertices->clear();
_box_vertices->clear();
_image_vertices->clear();
_sdf_vertices->clear();
}
draw_context(draw_context const &rhs) noexcept = default;
draw_context(draw_context &&rhs) noexcept = default;
draw_context &operator=(draw_context const &rhs) noexcept = default;
draw_context &operator=(draw_context &&rhs) noexcept = default;
~draw_context() = default;
gui_window &window() const noexcept
{
tt_axiom(_window);
return *_window;
}
gui_device &device() const noexcept
{
auto device = window().device();
tt_axiom(device);
return *device;
}
/** Draw a polygon with four corners of one color.
* This function will draw a polygon between the four given points.
* This will use the current:
* - transform, to transform each point.
* - clippingRectangle
* - fillColor
*/
void draw_filled_quad(f32x4 p1, f32x4 p2, f32x4 p3, f32x4 p4) const noexcept
{
tt_axiom(_flat_vertices != nullptr);
_flat_vertices->emplace_back(transform * p1, clipping_rectangle, fill_color);
_flat_vertices->emplace_back(transform * p2, clipping_rectangle, fill_color);
_flat_vertices->emplace_back(transform * p3, clipping_rectangle, fill_color);
_flat_vertices->emplace_back(transform * p4, clipping_rectangle, fill_color);
}
/** Draw a rectangle of one color.
* This function will draw the given rectangle.
* This will use the current:
* - transform, to transform each corner of the rectangle.
* - clippingRectangle
* - fillColor
*/
void draw_filled_quad(aarect r) const noexcept
{
draw_filled_quad(r.corner<0>(), r.corner<1>(), r.corner<2>(), r.corner<3>());
}
/** Draw an axis aligned box
* This function will draw the given box.
* This will use the current:
* - transform, to transform the opposite corner (rotation is not recommended).
* - clippingRectangle
* - fillColor
* - borderSize
* - borderColor
* - shadowSize
* - cornerShapes
*/
void draw_box(aarect box) const noexcept
{
tt_axiom(_box_vertices != nullptr);
pipeline_box::device_shared::placeVertices(
*_box_vertices, transform * box, fill_color, line_width, line_color, corner_shapes, clipping_rectangle);
}
/** Draw an axis aligned box
* This function will shrink to include the size of the border inside
* the given rectangle. This will make the border be drawn sharply.
*
* This will also adjust rounded corners to the shrunk box.
*
* This function will draw the given box.
* This will use the current:
* - transform, to transform the opposite corner (rotation is not recommended).
* - clipping_rectangle
* - fill_color
* - border_size
* - border_color
* - corner_shapes
*/
void draw_box_with_border_inside(aarect rectangle) const noexcept
{
tt_axiom(_box_vertices != nullptr);
ttlet shrink_value = line_width * 0.5f;
ttlet new_rectangle = shrink(rectangle, shrink_value);
ttlet new_corner_shapes =
f32x4{std::max(0.0f, corner_shapes.x() - shrink_value),
std::max(0.0f, corner_shapes.y() - shrink_value),
std::max(0.0f, corner_shapes.z() - shrink_value),
std::max(0.0f, corner_shapes.w() - shrink_value)};
pipeline_box::device_shared::placeVertices(
*_box_vertices, transform * new_rectangle, fill_color, line_width, line_color, new_corner_shapes, clipping_rectangle);
}
/** Draw an axis aligned box
* This function will expand to include the size of the border outside
* the given rectangle. This will make the border be drawn sharply.
*
* This will also adjust rounded corners to the shrunk box.
*
* This function will draw the given box.
* This will use the current:
* - transform, to transform the opposite corner (rotation is not recommended).
* - clippingRectangle
* - fillColor
* - borderSize
* - borderColor
* - shadowSize
* - cornerShapes
*/
void draw_box_with_border_outside(aarect rectangle) const noexcept
{
tt_axiom(_box_vertices != nullptr);
ttlet shrink_value = line_width * 0.5f;
ttlet new_rectangle = expand(rectangle, shrink_value);
ttlet new_corner_shapes =
f32x4{std::max(0.0f, corner_shapes.x() - shrink_value),
std::max(0.0f, corner_shapes.y() - shrink_value),
std::max(0.0f, corner_shapes.z() - shrink_value),
std::max(0.0f, corner_shapes.w() - shrink_value)};
pipeline_box::device_shared::placeVertices(
*_box_vertices, transform * new_rectangle, fill_color, line_width, line_color, new_corner_shapes, clipping_rectangle);
}
/** Draw an image
* This function will draw an image.
* This will use the current:
* - transform, to transform the image.
* - clippingRectangle
*/
void draw_image(pipeline_image::Image &image) const noexcept
{
tt_axiom(_image_vertices != nullptr);
image.placeVertices(*_image_vertices, transform, clipping_rectangle);
}
/** Draw shaped text.
* This function will draw the shaped text.
* The SDF-image-atlas needs to be prepared ahead of time.
* This will use the current:
* - transform, to transform the shaped-text's bounding box
* - clippingRectangle
*
* @param text The shaped text to draw.
* @param useContextColor When true display the text in the context's color, if false use text style color
*/
void draw_text(shaped_text const &text, bool useContextColor = false) const noexcept
{
tt_axiom(_sdf_vertices != nullptr);
if (useContextColor) {
narrow_cast<gui_device_vulkan &>(device()).SDFPipeline->placeVertices(
*_sdf_vertices, text, transform, clipping_rectangle, line_color);
} else {
narrow_cast<gui_device_vulkan &>(device()).SDFPipeline->placeVertices(
*_sdf_vertices, text, transform, clipping_rectangle);
}
}
void draw_glyph(font_glyph_ids const &glyph, aarect box) const noexcept
{
tt_axiom(_sdf_vertices != nullptr);
narrow_cast<gui_device_vulkan &>(device()).SDFPipeline->placeVertices(
*_sdf_vertices, glyph, transform * box, line_color, clipping_rectangle);
}
[[nodiscard]] friend bool overlaps(draw_context const &context, aarect const &rectangle) noexcept
{
return overlaps(context._scissor_rectangle, rectangle);
}
private:
gui_window *_window;
public:
aarect _scissor_rectangle;
private:
vspan<pipeline_flat::vertex> *_flat_vertices;
vspan<pipeline_box::vertex> *_box_vertices;
vspan<pipeline_image::vertex> *_image_vertices;
vspan<pipeline_SDF::vertex> *_sdf_vertices;
};
} // namespace tt
| 33.986159 | 130 | 0.655366 | prollings |
da5d9efe3ca0bf33f1659138cce138062b57df69 | 11,100 | cc | C++ | src/XmlFonts.cc | flexpaper/pdf2json | b671b647a7e487b021744f330b8dd2d6ccfa8103 | [
"Linux-OpenIB"
] | 278 | 2015-05-01T05:33:42.000Z | 2022-03-26T15:51:30.000Z | src/XmlFonts.cc | flexpaper/pdf2json | b671b647a7e487b021744f330b8dd2d6ccfa8103 | [
"Linux-OpenIB"
] | 46 | 2015-09-14T17:03:45.000Z | 2021-03-31T09:52:48.000Z | src/XmlFonts.cc | flexpaper/pdf2json | b671b647a7e487b021744f330b8dd2d6ccfa8103 | [
"Linux-OpenIB"
] | 49 | 2015-08-10T01:49:21.000Z | 2022-03-23T07:32:59.000Z | #include "XmlFonts.h"
#include "GlobalParams.h"
#include "UnicodeMap.h"
#include <stdio.h>
#ifndef _WIN32
#include <unistd.h>
#endif
struct Fonts{
char *Fontname;
char *name;
};
const int font_num=13;
static Fonts fonts[font_num+1]={
{"Courier", "Courier" },
{"Courier-Bold", "Courier"},
{"Courier-BoldOblique", "Courier"},
{"Courier-Oblique", "Courier"},
{"Helvetica", "Helvetica"},
{"Helvetica-Bold", "Helvetica"},
{"Helvetica-BoldOblique", "Helvetica"},
{"Helvetica-Oblique", "Helvetica"},
{"Symbol", "Symbol" },
{"Times-Bold", "Times" },
{"Times-BoldItalic", "Times" },
{"Times-Italic", "Times" },
{"Times-Roman", "Times" },
{" " , "Times" },
};
#define xoutRound(x) ((int)(x + 0.5))
extern GBool xml;
GString* XmlFont::DefaultFont=new GString("Times"); // Arial,Helvetica,sans-serif
XmlFontColor::XmlFontColor(GfxRGB rgb){
/*
r=static_cast<int>(255*rgb.r);
g=static_cast<int>(255*rgb.g);
b=static_cast<int>(255*rgb.b);
*/
r=colToByte(rgb.r);
g=colToByte(rgb.g);
b=colToByte(rgb.b);
if (!(Ok(r)&&Ok(b)&&Ok(g))) {printf("Error : Bad color \n");r=0;g=0;b=0;}
}
GString *XmlFontColor::convtoX(unsigned int xcol) const{
GString *xret=new GString();
char tmp;
unsigned int k;
k = (xcol/16);
if ((k>=0)&&(k<10)) tmp=(char) ('0'+k); else tmp=(char)('a'+k-10);
xret->append(tmp);
k = (xcol%16);
if ((k>=0)&&(k<10)) tmp=(char) ('0'+k); else tmp=(char)('a'+k-10);
xret->append(tmp);
return xret;
}
GString *XmlFontColor::toString() const{
GString *tmp=new GString("#");
GString *tmpr=convtoX(r);
GString *tmpg=convtoX(g);
GString *tmpb=convtoX(b);
tmp->append(tmpr);
tmp->append(tmpg);
tmp->append(tmpb);
delete tmpr;
delete tmpg;
delete tmpb;
return tmp;
}
XmlFont::XmlFont(GString* ftname,int _size, double _charspace, GfxRGB rgb){
//if (col) color=XmlFontColor(col);
//else color=XmlFontColor();
color=XmlFontColor(rgb);
GString *fontname = NULL;
charspace = _charspace;
if( ftname ){
fontname = new GString(ftname);
FontName=new GString(ftname);
}
else {
fontname = NULL;
FontName = NULL;
}
lineSize = -1;
size=(_size-1);
italic = gFalse;
bold = gFalse;
oblique = gFalse;
if (fontname){
if (strstr(fontname->lowerCase()->getCString(),"bold")) bold=gTrue;
if (strstr(fontname->lowerCase()->getCString(),"italic")) italic=gTrue;
if (strstr(fontname->lowerCase()->getCString(),"oblique")) oblique=gTrue;
/*||strstr(fontname->lowerCase()->getCString(),"oblique")) italic=gTrue;*/
int i=0;
while (strcmp(ftname->getCString(),fonts[i].Fontname)&&(i<font_num))
{
i++;
}
pos=i;
delete fontname;
}
if (!DefaultFont) DefaultFont=new GString(fonts[font_num].name);
}
XmlFont::XmlFont(const XmlFont& x){
size=x.size;
lineSize=x.lineSize;
italic=x.italic;
oblique=x.oblique;
bold=x.bold;
pos=x.pos;
charspace=x.charspace;
color=x.color;
if (x.FontName) FontName=new GString(x.FontName);
}
XmlFont::~XmlFont(){
if (FontName) delete FontName;
}
XmlFont& XmlFont::operator=(const XmlFont& x){
if (this==&x) return *this;
size=x.size;
lineSize=x.lineSize;
italic=x.italic;
oblique=x.oblique;
bold=x.bold;
pos=x.pos;
color=x.color;
charspace=x.charspace;
if (FontName) delete FontName;
if (x.FontName) FontName=new GString(x.FontName);
return *this;
}
void XmlFont::clear(){
if(DefaultFont) delete DefaultFont;
DefaultFont = NULL;
}
/*
This function is used to compare font uniquily for insertion into
the list of all encountered fonts
*/
GBool XmlFont::isEqual(const XmlFont& x) const{
return ((size==x.size) && (lineSize==x.lineSize) && (charspace==x.charspace) &&
(pos==x.pos) && (bold==x.bold) && (oblique==x.oblique) && (italic==x.italic) &&
(color.isEqual(x.getColor())));
}
/*
This one is used to decide whether two pieces of text can be joined together
and therefore we don't care about bold/italics properties
*/
GBool XmlFont::isEqualIgnoreBold(const XmlFont& x) const{
return ((size==x.size) &&
(color.isEqual(x.getColor())));
}
GString* XmlFont::getFontName(){
if (pos!=font_num) return new GString(fonts[pos].name);
else return new GString(DefaultFont);
// return new GString(FontName);
}
GString* XmlFont::getFullName(){
if (FontName)
return new GString(FontName);
else return new GString(DefaultFont);
}
void XmlFont::setDefaultFont(GString* defaultFont){
if (DefaultFont) delete DefaultFont;
DefaultFont=new GString(defaultFont);
}
GString* XmlFont::getDefaultFont(){
return DefaultFont;
}
// this method if plain wrong todo
GString* XmlFont::HtmlFilter(Unicode* u, int uLen) {
GString *tmp = new GString();
UnicodeMap *uMap;
char buf[8];
int n;
// get the output encoding
if (!(uMap = globalParams->getTextEncoding())) {
return tmp;
}
for (int i = 0; i < uLen; ++i) {
switch (u[i])
{
case '"': tmp->append("""); break;
case '&': tmp->append("&"); break;
case '<': tmp->append("<"); break;
case '>': tmp->append(">"); break;
default:
{
// convert unicode to string
if ((n = uMap->mapUnicode(u[i], buf, sizeof(buf))) > 0) {
tmp->append(buf, n);
}
}
}
}
uMap->decRefCnt();
return tmp;
}
GString* XmlFont::simple(XmlFont* font, Unicode* content, int uLen){
GString *cont=HtmlFilter (content, uLen);
/*if (font.isBold()) {
cont->insert(0,"<b>",3);
cont->append("</b>",4);
}
if (font.isItalic()) {
cont->insert(0,"<i>",3);
cont->append("</i>",4);x.oblique
} */
return cont;
}
XmlFontAccu::XmlFontAccu(){
accu=new GVector<XmlFont>();
}
XmlFontAccu::~XmlFontAccu(){
if (accu) delete accu;
}
int XmlFontAccu::AddFont(const XmlFont& font){
GVector<XmlFont>::iterator i;
for (i=accu->begin();i!=accu->end();i++)
{
if (font.isEqual(*i))
{
return (int)(i-(accu->begin()));
}
}
accu->push_back(font);
return (accu->size()-1);
}
static GString* EscapeSpecialChars( GString* s)
{
GString* tmp = NULL;
for( int i = 0, j = 0; i < s->getLength(); i++, j++ ){
const char *replace = NULL;
switch ( s->getChar(i) ){
case '"': replace = "\\u0022"; break;
case '\\': replace = "\\u005C"; break;
case '<': replace = "\\u003C"; break;
case '>': replace = "\\u003E"; break;
case '\'': replace = "\\u0027"; break;
case '&': replace = "\\u0026"; break;
case 0x01: replace = ""; break;
case 0x02: replace = ""; break;
case 0x03: replace = ""; break;
case 0x04: replace = ""; break;
case 0x05: replace = ""; break;
case 0x06: replace = ""; break;
case 0x07: replace = ""; break;
case 0x08: replace = ""; break;
case 0x09: replace = ""; break;
case 0x0a: replace = ""; break;
case 0x0b: replace = ""; break;
case 0x0c: replace = ""; break;
case 0x0d: replace = ""; break;
case 0x0e: replace = ""; break;
case 0x0f: replace = ""; break;
case 0x10: replace = ""; break;
case 0x11: replace = ""; break;
case 0x12: replace = ""; break;
case 0x13: replace = ""; break;
case 0x14: replace = ""; break;
case 0x15: replace = ""; break;
case 0x16: replace = ""; break;
case 0x17: replace = ""; break;
case 0x18: replace = ""; break;
case 0x19: replace = ""; break;
case 0x1a: replace = ""; break;
case 0x1b: replace = ""; break;
case 0x1c: replace = ""; break;
case 0x1d: replace = ""; break;
case 0x1e: replace = ""; break;
case 0x1f: replace = ""; break;
default: continue;
}
if( replace ){
if( !tmp ) tmp = new GString( s );
if( tmp ){
tmp->del( j, 1 );
int l = strlen( replace );
tmp->insert( j, replace, l );
j += l - 1;
}
}
}
return tmp ? tmp : s;
}
// get CSS font name for font #i
GString* XmlFontAccu::getCSStyle(int i, GString* content){
GString *tmp;
GString *iStr=GString::fromInt(i);
if (!xml) {
tmp = new GString("<span class=\"ft");
tmp->append(iStr);
tmp->append("\">");
tmp->append(content);
tmp->append("</span>");
} else {
tmp = EscapeSpecialChars(content);
//tmp->append(content);
}
delete iStr;
return tmp;
}
// get CSS font definition for font #i
GString* XmlFontAccu::CSStyle(int i,GBool textAsJSON){
GString *tmp=new GString();
GString *iStr=GString::fromInt(i);
GVector<XmlFont>::iterator g=accu->begin();
g+=i;
XmlFont font=*g;
GString *Size=GString::fromInt(font.getSize());
GString *colorStr=font.getColor().toString();
GString *fontName=font.getFontName();
GString *lSize;
double _charspace = font.getCharSpace();
char *cspace = new char [20];
sprintf(cspace,"%0.05f",_charspace);
if (xml && !textAsJSON) {
tmp->append("<fontspec id=\"");
tmp->append(iStr);
tmp->append("\" size=\"");
tmp->append(Size);
tmp->append("\" family=\"");
tmp->append(fontName); //font.getFontName());
tmp->append("\" color=\"");
tmp->append(colorStr);
tmp->append("\"/>");
}else if(textAsJSON){
tmp->append("{\"fontspec\":\"");
tmp->append(iStr);
tmp->append("\",\"size\":\"");
tmp->append(Size);
tmp->append("\",\"family\":\"");
tmp->append(fontName); //font.getFontName());
tmp->append("\",\"color\":\"");
tmp->append(colorStr);
tmp->append("\"}");
}
delete fontName;
delete colorStr;
delete iStr;
delete Size;
delete cspace;
return tmp;
}
| 27.959698 | 112 | 0.517658 | flexpaper |
da610bd3ac859867f71e0a1d36911d18ea1604e0 | 1,855 | cpp | C++ | io/FileInputStream.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | 3 | 2019-04-20T10:16:36.000Z | 2021-03-21T19:51:38.000Z | io/FileInputStream.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | null | null | null | io/FileInputStream.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | 2 | 2020-04-18T20:04:24.000Z | 2021-09-19T05:07:41.000Z | #include "FileInputStream.h"
#include "StdioEx.h"
#include "FileNotFoundException.h"
#include <assert.h>
#include "config.h"
//-----------------------------------------------------------------------------
using namespace lang;
//-----------------------------------------------------------------------------
namespace io
{
class FileInputStream::FileInputStreamImpl :
public Object
{
public:
FILE* file;
String name;
FileInputStreamImpl( FILE* file, const String& name )
{
this->file = file;
this->name = name;
}
~FileInputStreamImpl()
{
close();
}
void close()
{
if ( file )
{
fclose( file );
file = 0;
}
}
};
//-----------------------------------------------------------------------------
FileInputStream::FileInputStream( const String& filename )
{
FILE* handle = fopen( filename, "rb" );
if ( !handle )
throw FileNotFoundException( Format("Failed to open file for reading: {0}",filename) );
m_this = new FileInputStreamImpl( handle, filename );
}
FileInputStream::~FileInputStream()
{
}
void FileInputStream::close()
{
if ( m_this )
{
m_this->close();
}
}
long FileInputStream::read( void* data, long size )
{
long bytes = fread( data, 1, size, m_this->file );
if ( bytes < size && ferror(m_this->file) )
throw IOException( Format("Failed to read from file: {0}",m_this->name) );
return bytes;
}
long FileInputStream::available() const
{
long cur = ftell( m_this->file );
fseek( m_this->file, 0, SEEK_END );
long end = ftell( m_this->file );
fseek( m_this->file, cur, SEEK_SET );
if ( ferror(m_this->file) )
throw IOException( Format("Failed to seek file position: {0}",m_this->name) );
return end-cur;
}
String FileInputStream::toString() const
{
return m_this->name;
}
} // io
| 19.123711 | 90 | 0.545553 | Andrewich |
da634c368b3a0a29c30f66ff098f84b99287efa1 | 1,713 | cc | C++ | Codeforces/358 Division 2/Problem C/C.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/358 Division 2/Problem C/C.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/358 Division 2/Problem C/C.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define foreach(it, v) for(__typeof((v).begin()) it=(v).begin(); it != (v).end(); ++it)
#define meta __FUNCTION__,__LINE__
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
using namespace std;
const long double PI = 3.1415926535897932384626433832795;
template<typename S, typename T>
ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;}
template<typename T>
ostream& operator<<(ostream& out,vector<T> const& v){
int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;}
void tr(){cout << endl;}
template<typename S, typename ... Strings>
void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);}
typedef long long ll;
typedef pair<int,int> pii;
const int N = 100100;
vector<pii> g[N];
ll a[N];
int s[N];
int res;
void dfs(int cur, int prev){
s[cur] = 1;
foreach(it, g[cur]){
if(it->fi == prev) continue;
dfs(it->fi, cur);
s[cur] += s[it->fi];
}
}
void dfs2(int cur, int prev, ll mx){
if(mx > a[cur]){
res += s[cur];
return;
}
foreach(it, g[cur]){
if(it->fi == prev) continue;
dfs2(it->fi, cur, max(mx+it->se, 0ll));
}
}
int main(){ _
int n;
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i];
}
for(int i = 1; i < n; i++){
int p, c;
cin >> p >> c;
g[p].pb(mp(i+1,c));
g[i+1].pb(mp(p,c));
}
dfs(1, -1);
dfs2(1,-1, 0);
cout << res << endl;
return 0;
}
| 19.465909 | 97 | 0.58669 | VastoLorde95 |
da6e53b2547e59fa9387918bfc120b88de19ddfb | 1,525 | cpp | C++ | src/openloco/objects/objectmgr.cpp | IntelOrca/OpenLoco | 9a72b10522a6b20c68bbf90e12c8aeb6089a043a | [
"MIT"
] | null | null | null | src/openloco/objects/objectmgr.cpp | IntelOrca/OpenLoco | 9a72b10522a6b20c68bbf90e12c8aeb6089a043a | [
"MIT"
] | null | null | null | src/openloco/objects/objectmgr.cpp | IntelOrca/OpenLoco | 9a72b10522a6b20c68bbf90e12c8aeb6089a043a | [
"MIT"
] | null | null | null | #include "objectmgr.h"
#include "../interop/interop.hpp"
using namespace openloco::interop;
namespace openloco::objectmgr
{
loco_global_array<cargo_object*, 32, 0x0050C700> _cargoObjects;
// 0x00470F3C
void load_index()
{
call(0x00470F3C);
}
cargo_object* get_cargo_object(size_t id)
{
return _cargoObjects[id];
}
size_t get_max_objects(object_type type)
{
static size_t counts[] = {
1, // interface,
128, // sound,
1, // currency,
32, // steam,
8, // rock,
1, // water,
32, // surface,
1, // town_name,
32, // cargo,
32, // wall,
16, // train_signal,
4, // level_crossing,
1, // street_light,
16, // tunnel,
8, // bridge,
16, // train_station,
8, // track_extra,
8, // track,
16, // road_station,
4, // road_extra,
8, // road,
8, // airport,
8, // dock,
224, // vehicle,
64, // tree,
1, // snow,
1, // climate,
1, // hill_shapes,
128, // building,
1, // scaffolding,
16, // industry,
1, // region,
32, // competitors,
1 // scenario_text,
};
return counts[(size_t)type];
};
}
| 24.596774 | 67 | 0.419016 | IntelOrca |
da70ff3007720261a2b8a57f69eb0de419ef2aeb | 36,007 | cpp | C++ | src/ExtFilterModifySurface/FeatureConvincedDenoising.cpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | 4 | 2016-06-03T18:41:43.000Z | 2020-04-17T20:28:58.000Z | src/ExtFilterModifySurface/FeatureConvincedDenoising.cpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | null | null | null | src/ExtFilterModifySurface/FeatureConvincedDenoising.cpp | voxie-viewer/voxie | d2b5e6760519782e9ef2e51f5322a3baa0cb1198 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-2022 The Voxie Authors
*
* 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 "FeatureConvincedDenoising.hpp"
#include <cmath>
#include "FastEffectiveDPFilter.hpp"
#include "TaubinFiltering.hpp"
// TODO: Get rid of QtGui?
#include <QtGui/QVector3D>
FeatureConvincedDenoising::FeatureConvincedDenoising(
vx::Array2<float> vertices, vx::Array2<const uint32_t> triangles) {
Q_UNUSED(vertices); // TODO
Q_UNUSED(triangles); // TODO
}
void FeatureConvincedDenoising::compute(
vx::Array2<float>& vertices, vx::Array2<const uint32_t>& triangles,
int maxExtensions,
vx::ClaimedOperation<de::uni_stuttgart::Voxie::ExternalOperationRunFilter>&
prog) {
maxExtensionSteps = maxExtensions;
createCopies(vertices, triangles);
setParameters(vertices, triangles, prog);
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(0.18, vx::emptyOptions()));
TaubinFiltering taubin(taubinIterations, 0.6);
taubin.compute(vertices, triangles, prog);
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(0.22, vx::emptyOptions()));
FastEffectiveDPFilter fed;
fed.compute(vertices, triangles, 0.4, fedIterations, prog);
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(0.32, vx::emptyOptions()));
qDebug() << "FED completed";
setUpNeighbours(vertices, triangles);
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(0.35, vx::emptyOptions()));
qDebug() << "neighbours set up";
calculateNormals(vertices, triangles);
findCandidateEdges(minFeatureEdgeAngle);
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(0.35, vx::emptyOptions()));
formFeatureLines(vertices);
refineLines(vertices);
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(0.38, vx::emptyOptions()));
filter(vertices, triangles, prog);
applyFilterResult(vertices);
}
void FeatureConvincedDenoising::applyFilterResult(vx::Array2<float>& vertices) {
for (size_t i = 0; i < vertices.size<0>(); i++) {
vertices(i, 0) = verticesCopy.at(i).x();
vertices(i, 1) = verticesCopy.at(i).y();
vertices(i, 2) = verticesCopy.at(i).z();
}
}
void FeatureConvincedDenoising::filter(
vx::Array2<float> vertices, vx::Array2<const uint32_t> triangles,
vx::ClaimedOperation<de::uni_stuttgart::Voxie::ExternalOperationRunFilter>&
prog) {
Q_UNUSED(vertices); // TODO
Q_UNUSED(triangles); // TODO
for (int i = 0; i < trianglesCopy.size(); i++) {
isotropicTriangleNeighbourhoods.append(
buildIsotropicTriangleNeighbourhood(i));
}
for (int i = 0; i < filterIterations; i++) {
calculateTriangleInfo();
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(
0.38 + 0.62 * (double)(i + 0.05) / (double)filterIterations,
vx::emptyOptions()));
generateGuidingNormals();
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(
0.38 + 0.62 * (double)(i + 0.25) / (double)filterIterations,
vx::emptyOptions()));
filterNormals();
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(
0.38 + 0.62 * (double)(i + 0.8) / (double)filterIterations,
vx::emptyOptions()));
calculateDiffs();
HANDLEDBUSPENDINGREPLY(prog.opGen().SetProgress(
0.38 + 0.62 * (double)(i + 0.95) / (double)filterIterations,
vx::emptyOptions()));
updateVertices();
}
}
void FeatureConvincedDenoising::updateVertices() {
for (int i = 0; i < verticesCopy.size(); i++) {
if (diffs.at(i).length() < meanLength) {
verticesCopy[i] = verticesCopy.at(i) + diffs.at(i);
}
}
}
void FeatureConvincedDenoising::filterNormals() {
for (int j = 0; j < bilateralFilterIterations; j++) {
for (int i = 0; i < trianglesCopy.size(); i++) {
QVector3D filteredNormal(0, 0, 0);
QList<int> neighbourhood = isotropicTriangleNeighbourhoods.at(i);
for (int k = 0; k < neighbourhood.size(); k++) {
double weight = 0;
double distance =
(centroids.at(i) - centroids.at(neighbourhood.at(k))).length();
double normalsDifference =
(guidingNormals.at(i) - guidingNormals.at(neighbourhood.at(k)))
.length();
weight = areas.at(neighbourhood.at(k));
weight = weight * evaluateGaussian(distance, sigmaSpacial);
weight = weight * evaluateGaussian(normalsDifference, sigmaSignal);
filteredNormal += weight * normalsForFilter.at(neighbourhood.at(k));
}
filteredNormal = filteredNormal * 20000;
filteredNormal.normalize();
filteredNormals.append(filteredNormal);
}
for (int i = 0; i < trianglesCopy.size(); i++) {
normalsForFilter[i] = filteredNormals.at(i);
}
filteredNormals.clear();
}
for (int i = 0; i < trianglesCopy.size(); i++) {
filteredNormals.append(normalsForFilter.at(i));
}
}
void FeatureConvincedDenoising::calculateDiffs() {
for (int i = 0; i < verticesCopy.size(); i++) {
QList<int> neighbourhood = buildIsotropicVertexNeighbourhood(i);
if (neighbourhood.size() < 4) {
diffs.append(QVector3D(0, 0, 0));
continue;
}
QVector3D diff(0, 0, 0);
for (int j = 0; j < neighbourhood.size(); j++) {
double weight = QVector3D().dotProduct(
filteredNormals.at(neighbourhood.at(j)),
(centroids.at(neighbourhood.at(j)) - verticesCopy.at(i)));
diff = diff + weight * filteredNormals.at(neighbourhood.at(j));
}
diff = diff / neighbourhood.size();
diffs.append(diff);
}
}
double FeatureConvincedDenoising::evaluateGaussian(double difference,
double sigma) {
double result = 0.0;
result = exp(-(difference * difference) / (2 * sigma * sigma));
return result;
}
void FeatureConvincedDenoising::generateGuidingNormals() {
for (int i = 0; i < trianglesCopy.size(); i++) {
QList<int> neighbourhood = buildFeatureAwareNeighbourhood(i);
QVector3D normal(0, 0, 0);
for (int j = 0; j < neighbourhood.size(); j++) {
int index = neighbourhood.at(j);
normal = normal + (areas.at(index) * normalsForFilter.at(index));
}
normal = normal * 2000;
normal.normalize();
guidingNormals.append(normal);
}
}
void FeatureConvincedDenoising::calculateTriangleInfo() {
diffs.clear();
centroids.clear();
normalsForFilter.clear();
guidingNormals.clear();
filteredNormals.clear();
areas.clear();
for (int i = 0; i < trianglesCopy.size(); i++) {
QVector3D first = verticesCopy.at(trianglesCopy.at(i).first);
QVector3D second = verticesCopy.at(trianglesCopy.at(i).second);
QVector3D third = verticesCopy.at(trianglesCopy.at(i).third);
QVector3D centroid = (first + second + third) / 3;
centroids.append(centroid);
QVector3D normal =
QVector3D().normal(first * 500, second * 500, third * 500);
normalsForFilter.append(normal);
QVector3D direction = first - second;
direction = direction * 5000;
direction.normalize();
double area = (first - second).length() *
third.distanceToLine(first, direction) / 2.0;
areas.append(area);
}
}
/**
* @brief FeatureConvincedDenoising::buildIsotropicNeighbourhood bildet eine
* isotrope Nachbarschaft um vertex, diese beinhaltet den 1-Ring um Vertex sowie
* die Dreiecke jenseits der nicht anliegenden Kante dieser Dreiecke
* @param vertex
* @return
*/
QList<int> FeatureConvincedDenoising::buildIsotropicVertexNeighbourhood(
int vertex) {
QList<int> neighbourTriangles;
QList<int> neighbourVertices;
QList<Edge> _edges = nodes.at(vertex).edges.values();
for (int i = 0; i < _edges.size(); i++) {
int edge = _edges.at(i).index;
if (edges.at(edge).vertexOne == vertex) {
neighbourVertices.append(edges.at(edge).vertexTwo);
} else if (edges.at(edge).vertexTwo == vertex) {
neighbourVertices.append(edges.at(edge).vertexOne);
} else {
qDebug() << "not a neighbouring edge!";
}
}
for (int i = 0; i < neighbourVertices.size(); i++) {
QList<Edge> theseEdges = nodes.at(neighbourVertices.at(i)).edges.values();
for (int j = 0; j < theseEdges.size(); j++) {
int edge = theseEdges.at(j).index;
if ((neighbourVertices.contains(edges.at(edge).vertexOne)) &&
(neighbourVertices.contains(edges.at(edge).vertexTwo)) &&
!(neighbourTriangles.contains(edges.at(edge).triangleOne))) {
neighbourTriangles.append(edges.at(edge).triangleOne);
neighbourTriangles.append(edges.at(edge).triangleTwo);
}
}
}
return neighbourTriangles;
}
QList<int> FeatureConvincedDenoising::buildIsotropicTriangleNeighbourhood(
int triangle) {
QList<int> neighbourhood;
QList<int> facetQueue;
neighbourhood.append(triangle);
facetQueue.append(triangle);
while (!(facetQueue.isEmpty()) &&
(neighbourhood.size() < maxNeighbourhoodSize)) {
int facet = facetQueue.first();
facetQueue.removeAt(0);
QList<int> vertices;
vertices.append(trianglesCopy.at(facet).first);
vertices.append(trianglesCopy.at(facet).second);
vertices.append(trianglesCopy.at(facet).third);
// for each vertex, find edge in triangle, append other triangle of that
// edge if non-feature edge add if one of the triangles is already in the nh
// and the other isn't
for (int i = 0; i < 3; i++) {
QList<Edge> edgesThis = nodes.at(vertices.at(i)).edges.values();
for (int j = 0; j < edgesThis.size(); j++) {
int edge = edgesThis.at(j).index;
if (neighbourhood.contains(edges.at(edge).triangleOne) &&
!(neighbourhood.contains(edges.at(edge).triangleTwo))) {
neighbourhood.append(edges.at(edge).triangleTwo);
facetQueue.append(edges.at(edge).triangleTwo);
if (neighbourhood.size() == maxNeighbourhoodSize) {
return neighbourhood;
}
} else if (neighbourhood.contains(edges.at(edge).triangleTwo) &&
!(neighbourhood.contains(edges.at(edge).triangleOne))) {
neighbourhood.append(edges.at(edge).triangleOne);
facetQueue.append(edges.at(edge).triangleOne);
if (neighbourhood.size() == maxNeighbourhoodSize) {
return neighbourhood;
}
}
}
}
}
return neighbourhood;
}
/**
* @brief FeatureConvincedDenoising::buildFeatureAwareNeighbourhood erstellt
* eine Nachbarschaft um das Dreieck triangle ohne dabei eine Feature-Edge zu
* überqueren, diese ist höchstens maxNeighbourhoodSize groß, kleiner falls das
* Dreieck enger von Feature-Edges umgeben ist
* @param triangle index des Dreiecks
* @return die Liste mit den Indizes der Dreiecke in der Nachbarschaft
*/
QList<int> FeatureConvincedDenoising::buildFeatureAwareNeighbourhood(
int triangle) {
QList<int> neighbourhood;
QList<int> facetQueue;
neighbourhood.append(triangle);
facetQueue.append(triangle);
while (!(facetQueue.isEmpty()) &&
(neighbourhood.size() < maxNeighbourhoodSize)) {
int facet = facetQueue.first();
facetQueue.removeAt(0);
QList<int> vertices;
vertices.append(trianglesCopy.at(facet).first);
vertices.append(trianglesCopy.at(facet).second);
vertices.append(trianglesCopy.at(facet).third);
// for each vertex, find edge in triangle, append other triangle of that
// edge if non-feature edge add if one of the triangles is already in the nh
// and the other isn't
for (int i = 0; i < 3; i++) {
QList<Edge> edgesThis = nodes.at(vertices.at(i)).edges.values();
for (int j = 0; j < edgesThis.size(); j++) {
int edge = edgesThis.at(j).index;
if (edges.at(edge).feature || edges.at(edge).extension) {
continue;
}
if (neighbourhood.contains(edges.at(edge).triangleOne) &&
!(neighbourhood.contains(edges.at(edge).triangleTwo))) {
neighbourhood.append(edges.at(edge).triangleTwo);
facetQueue.append(edges.at(edge).triangleTwo);
if (neighbourhood.size() == maxNeighbourhoodSize) {
return neighbourhood;
}
} else if (neighbourhood.contains(edges.at(edge).triangleTwo) &&
!(neighbourhood.contains(edges.at(edge).triangleOne))) {
neighbourhood.append(edges.at(edge).triangleOne);
facetQueue.append(edges.at(edge).triangleOne);
if (neighbourhood.size() == maxNeighbourhoodSize) {
return neighbourhood;
}
}
}
}
}
return neighbourhood;
}
void FeatureConvincedDenoising::findCandidateEdges(double threshold) {
double threshAngle = std::acos(threshold);
for (int i = 0; i < edges.size(); i++) {
Edge e = edges[i];
edges[i].angleCosine = std::abs(QVector3D().dotProduct(
normals.at(e.triangleOne), normals.at(e.triangleTwo)));
double angle = std::acos(edges[i].angleCosine);
if (angle > threshAngle) {
edges[i].feature = true;
edges[i].lineParent = -1;
edges[i].saliency = 0;
edges[i].iLine = 0;
edges[i].dThisEdge = 0;
edges[i].lineNeighbourOne = -1;
edges[i].lineNeighbourTwo = -1;
edges[i].directionDiffOne = -1;
edges[i].directionDiffTwo = -1;
edges[i].lineLength = 0;
candidateEdges.append(i);
}
}
}
void FeatureConvincedDenoising::formFeatureLines(vx::Array2<float> vertices) {
for (int i = 0; i < candidateEdges.size(); i++) {
insertEdge(vertices, candidateEdges.at(i));
}
}
void FeatureConvincedDenoising::insertEdge(vx::Array2<float> vertices,
int index) {
// diese Kante als (1-)Line aufsetzen
edges[index].lineParent = index;
edges[index].lineLength = 1;
edges[index].dThisEdge = std::abs((normals.at(edges[index].triangleOne) -
normals.at(edges[index].triangleTwo))
.length());
edges[index].iLine = 0.0;
edges[index].dLine = edges.at(index).dThisEdge;
edges[index].saliency = 0.0;
appendAtVertex(vertices, index, edges.at(index).vertexOne);
appendAtVertex(vertices, index, edges.at(index).vertexTwo);
}
void FeatureConvincedDenoising::appendAtVertex(vx::Array2<float> vertices,
int edge, int vertex) {
QList<Edge> e = nodes.at(vertex).edges.values();
QList<int> candidates;
for (int i = 0; i < e.length(); i++) {
int currentEdge = e.at(i).index;
if (!edges.at(currentEdge).feature) {
continue;
}
if (!(edges.at(currentEdge).lineParent >= 0)) {
continue;
}
if (angleBetweenEdges(vertices, edges.at(currentEdge), edges.at(edge)) <
lineAngleThreshold) {
continue;
}
if (currentEdge == edge) {
continue;
}
candidates.append(currentEdge);
}
double bestSaliency = 0;
int bestCandidate = -1;
int thisHead = followToLineHead(edge);
for (int i = 0; i < candidates.size(); i++) {
int currentHead = followToLineHead(candidates.at(i));
double dPot = 0;
double iPot = 0;
int lengthPot = 0;
followPathToBeCutOff(vertices, dPot, iPot, lengthPot, candidates.at(i),
vertex);
dPot = dPot + edges.at(thisHead).dLine;
// qDebug() << "Potentielles D: " << dPot;
iPot = iPot + edges.at(thisHead).iLine * edges.at(thisHead).lineLength +
std::cos(3.14 - angleBetweenEdges(vertices, edges.at(edge),
edges.at(candidates.at(i))));
// qDebug() << "Winkel: " << angleBetweenEdges(vertices,
// edges.at(edge), edges.at(candidates.at(i))); qDebug() <<
// "Potentielles I: " << iPot;
iPot = iPot / (edges.at(thisHead).lineLength + lengthPot - 1);
// qDebug() << "Potentielles I: " << iPot;
double saliencyPot = dPot * iPot;
// qDebug() << "Potentielle Saliency: " << saliencyPot;
// qDebug() << "Aktuelle Saliency: " <<
// edges.at(currentHead).saliency;
if (saliencyPot > bestSaliency &&
saliencyPot > edges.at(currentHead).saliency) {
bestSaliency = saliencyPot;
bestCandidate = candidates.at(i);
}
}
//(re-)arrange the line
if (bestCandidate >= 0 && (bestCandidate != thisHead)) {
int oldNeighbour = -1;
if (edges.at(bestCandidate).vertexOne == vertex) {
oldNeighbour = edges.at(bestCandidate).lineNeighbourOne;
} else {
oldNeighbour = edges.at(bestCandidate).lineNeighbourTwo;
}
if (oldNeighbour > -1) {
if (edges.at(oldNeighbour).vertexOne == vertex) {
edges[oldNeighbour].lineNeighbourOne = -1;
} else {
edges[oldNeighbour].lineNeighbourTwo = -1;
}
double dNei = 0;
double iNei = 0;
int lengthNei = 0;
setNewHead(vertices, oldNeighbour, dNei, iNei, lengthNei, oldNeighbour,
vertex);
}
double dCan = 0;
double iCan = 0;
int lengthCan = 0;
int newHead = followPathToBeCutOff(vertices, dCan, iCan, lengthCan,
bestCandidate, vertex);
if (edges.at(edge).vertexOne == vertex) {
edges[edge].lineNeighbourOne = bestCandidate;
} else if (edges.at(edge).vertexTwo == vertex) {
edges[edge].lineNeighbourTwo = bestCandidate;
} else {
qDebug() << "not a neighbour!";
}
if (edges.at(bestCandidate).vertexOne == vertex) {
edges[bestCandidate].lineNeighbourOne = edge;
} else if (edges.at(bestCandidate).vertexTwo == vertex) {
edges[bestCandidate].lineNeighbourTwo = edge;
} else {
qDebug() << "not a neighbour!";
}
double dNew = 0;
double iNew = 0;
int lengthNew = 0;
int lastVertex = -1;
if (edges.at(newHead).lineNeighbourOne == -1) {
lastVertex = edges.at(newHead).vertexOne;
} else {
lastVertex = edges.at(newHead).vertexTwo;
}
setNewHead(vertices, newHead, dNew, iNew, lengthNew, newHead, lastVertex);
}
}
void FeatureConvincedDenoising::refineLines(vx::Array2<float> vertices) {
// resetFeatureEdges(vertices);
extendLines(vertices);
removeWrongFeatureEdges();
}
// TODO: remove?
void FeatureConvincedDenoising::resetFeatureEdges(vx::Array2<float> vertices) {
for (int i = 0; i < candidateEdges.size(); i++) {
int edge = candidateEdges.at(i);
// entspricht for each (proper) feature line
if ((edges.at(edge).lineParent == edge) &&
(edges.at(edge).lineLength > 10)) {
resetLine(vertices, edge);
}
}
}
// TODO: remove?
void FeatureConvincedDenoising::resetLine(vx::Array2<float> vertices,
int head) {
Q_UNUSED(vertices); // TODO
Q_UNUSED(head); // TODO
}
void FeatureConvincedDenoising::extendLines(vx::Array2<float> vertices) {
for (int i = 0; i < candidateEdges.size(); i++) {
int edge = candidateEdges.at(i);
// entspricht for each (proper) feature line
if ((edges.at(edge).lineParent == edge) &&
(edges.at(edge).lineLength > minimumLineLenghth)) {
extendLine(vertices, edge);
}
}
}
void FeatureConvincedDenoising::extendLine(vx::Array2<float> vertices,
int head) {
int dartEnd = -1;
if (edges.at(head).lineNeighbourOne < 0) {
dartEnd = edges.at(head).vertexOne;
} else if (edges.at(head).lineNeighbourTwo < 0) {
dartEnd = edges.at(head).vertexTwo;
}
int oppositeEnd = traverseLineToOppositeEnd(vertices, head, dartEnd);
int opDartEnd = -1;
if (edges.at(oppositeEnd).lineNeighbourOne < 0) {
opDartEnd = edges.at(oppositeEnd).vertexOne;
} else if (edges.at(oppositeEnd).lineNeighbourTwo < 0) {
opDartEnd = edges.at(oppositeEnd).vertexTwo;
}
if (extendLineEnd(vertices, head, dartEnd, maxExtensionSteps)) {
}
if (extendLineEnd(vertices, oppositeEnd, opDartEnd, maxExtensionSteps)) {
}
}
bool FeatureConvincedDenoising::extendLineEnd(vx::Array2<float> vertices,
int edge, int vertex,
int remainingSteps) {
QList<Edge> neighbourEdges = nodes.at(vertex).edges.values();
if (remainingSteps == 0) {
return false;
}
for (int i = 0; i < neighbourEdges.size(); i++) {
int neighbourEdge = neighbourEdges.at(i).index;
if (neighbourEdge == edge) {
continue;
}
if (angleBetweenEdges(vertices, edges.at(edge), edges.at(neighbourEdge)) >
extensionAngle) {
if (edges.at(neighbourEdge).feature &&
edges.at(followToLineHead(neighbourEdge)).lineLength >
minimumLineLenghth) {
edges[edge].extension = true;
return true;
}
int otherVertex = -1;
if (edges.at(neighbourEdge).vertexOne == vertex) {
otherVertex = edges.at(neighbourEdge).vertexTwo;
} else if (edges.at(neighbourEdge).vertexTwo == vertex) {
otherVertex = edges.at(neighbourEdge).vertexOne;
}
if (extendLineEnd(vertices, neighbourEdge, otherVertex,
remainingSteps - 1)) {
edges[neighbourEdge].extension = true;
return true;
}
}
}
return false;
}
void FeatureConvincedDenoising::removeWrongFeatureEdges() {
for (int i = 0; i < candidateEdges.size(); i++) {
int head = followToLineHead(candidateEdges.at(i));
if (edges.at(head).lineLength < minimumLineLenghth) {
edges[candidateEdges.at(i)].feature = false;
}
}
}
int FeatureConvincedDenoising::findSharedVertex(int eOne, int eTwo) {
if ((edges.at(eOne).vertexOne == edges.at(eTwo).vertexOne) ||
(edges.at(eOne).vertexOne == edges.at(eTwo).vertexTwo)) {
return edges.at(eOne).vertexOne;
} else if ((edges.at(eOne).vertexTwo == edges.at(eTwo).vertexOne) ||
(edges.at(eOne).vertexTwo == edges.at(eTwo).vertexTwo)) {
return edges.at(eOne).vertexTwo;
} else {
qDebug() << "no shared Vertex";
return -1;
}
}
void FeatureConvincedDenoising::setUpNeighbours(
vx::Array2<float> vertices, vx::Array2<const uint32_t> triangles) {
for (size_t i = 0; i < vertices.size<0>(); i++) {
neighbours.append(QMap<int, Edge>());
Node n;
n.vertex = i;
nodes.append(n);
}
for (size_t i = 0; i < triangles.size<0>(); i++) {
int one = triangles(i, 0);
int two = triangles(i, 1);
int three = triangles(i, 2);
nodes[one].triangles.append(i);
nodes[two].triangles.append(i);
nodes[three].triangles.append(i);
setUpEdge(one, two, i);
setUpEdge(one, three, i);
setUpEdge(two, three, i);
}
}
void FeatureConvincedDenoising::setUpEdge(int one, int two, int triangle) {
int ne = 0;
int co = 0;
if (neighbours.at(one).contains(two)) {
Edge e = neighbours[one][two];
edges[e.index].triangleTwo = triangle;
edges[e.index].feature = false;
edges[e.index].extension = false;
co++;
} else {
Edge e;
e.feature = false;
e.extension = false;
e.vertexOne = std::min(one, two);
e.vertexTwo = std::max(one, two);
e.triangleOne = triangle;
e.index = edges.size();
nodes[one].edges.insert(e);
nodes[two].edges.insert(e);
neighbours[one].insert(two, e);
neighbours[two].insert(one, e);
e.lineParent = -1;
e.saliency = 0;
e.iLine = 0;
e.dThisEdge = 0;
e.lineNeighbourOne = -1;
e.lineNeighbourTwo = -1;
e.directionDiffOne = -1;
e.directionDiffTwo = -1;
e.dLine = 0;
e.lineLength = 0;
edges.append(e);
ne++;
}
if (ne == co) {
qDebug() << "!Fehler!";
}
}
void FeatureConvincedDenoising::calculateNormals(
vx::Array2<float> vertices, vx::Array2<const uint32_t> triangles) {
for (size_t i = 0; i < triangles.size<0>(); i++) {
QVector3D first(vertices(triangles(i, 0), 0), vertices(triangles(i, 0), 1),
vertices(triangles(i, 0), 2));
QVector3D second(vertices(triangles(i, 1), 0), vertices(triangles(i, 1), 1),
vertices(triangles(i, 1), 2));
QVector3D third(vertices(triangles(i, 2), 0), vertices(triangles(i, 2), 1),
vertices(triangles(i, 2), 2));
QVector3D normal = QVector3D().normal(
first * 500, second * 500, third * 500); // TODO: bessere Lösung hier
normals.append(normal);
}
}
void FeatureConvincedDenoising::createCopies(
vx::Array2<float> vertices, vx::Array2<const uint32_t> triangles) {
for (size_t i = 0; i < vertices.size<0>(); i++) {
QVector3D vec(vertices(i, 0), vertices(i, 1), vertices(i, 2));
verticesCopy.append(vec);
}
for (size_t i = 0; i < triangles.size<0>(); i++) {
Triangle tri;
tri.first = triangles(i, 0);
tri.second = triangles(i, 1);
tri.third = triangles(i, 2);
trianglesCopy.append(tri);
}
}
/*
* ermittelt den Winkel (in Bogenmaß) zwischen zwei Kanten, wenn die Kanten
* einen Vertex teilen gibt sonst als Winkel 0 zurück
*/
double FeatureConvincedDenoising::angleBetweenEdges(vx::Array2<float> vertices,
Edge e1, Edge e2) {
QVector3D vectorOne;
QVector3D vectorTwo;
if (e1.vertexOne == e2.vertexOne) {
vectorOne =
QVector3D(vertices(e1.vertexTwo, 0) - vertices(e1.vertexOne, 0),
vertices(e1.vertexTwo, 1) - vertices(e1.vertexOne, 1),
vertices(e1.vertexTwo, 2) - vertices(e1.vertexOne, 2));
vectorTwo =
QVector3D(vertices(e2.vertexTwo, 0) - vertices(e2.vertexOne, 0),
vertices(e2.vertexTwo, 1) - vertices(e2.vertexOne, 1),
vertices(e2.vertexTwo, 2) - vertices(e2.vertexOne, 2));
} else if (e1.vertexOne == e2.vertexTwo) {
vectorOne =
QVector3D(vertices(e1.vertexTwo, 0) - vertices(e1.vertexOne, 0),
vertices(e1.vertexTwo, 1) - vertices(e1.vertexOne, 1),
vertices(e1.vertexTwo, 2) - vertices(e1.vertexOne, 2));
vectorTwo =
QVector3D(vertices(e2.vertexOne, 0) - vertices(e2.vertexTwo, 0),
vertices(e2.vertexOne, 1) - vertices(e2.vertexTwo, 1),
vertices(e2.vertexOne, 2) - vertices(e2.vertexTwo, 2));
} else if (e1.vertexTwo == e2.vertexOne) {
vectorOne =
QVector3D(vertices(e1.vertexOne, 0) - vertices(e1.vertexTwo, 0),
vertices(e1.vertexOne, 1) - vertices(e1.vertexTwo, 1),
vertices(e1.vertexOne, 2) - vertices(e1.vertexTwo, 2));
vectorTwo =
QVector3D(vertices(e2.vertexTwo, 0) - vertices(e2.vertexOne, 0),
vertices(e2.vertexTwo, 1) - vertices(e2.vertexOne, 1),
vertices(e2.vertexTwo, 2) - vertices(e2.vertexOne, 2));
} else if (e1.vertexTwo == e2.vertexTwo) {
vectorOne =
QVector3D(vertices(e1.vertexOne, 0) - vertices(e1.vertexTwo, 0),
vertices(e1.vertexOne, 1) - vertices(e1.vertexTwo, 1),
vertices(e1.vertexOne, 2) - vertices(e1.vertexTwo, 2));
vectorTwo =
QVector3D(vertices(e2.vertexOne, 0) - vertices(e2.vertexTwo, 0),
vertices(e2.vertexOne, 1) - vertices(e2.vertexTwo, 1),
vertices(e2.vertexOne, 2) - vertices(e2.vertexTwo, 2));
} else {
return 0.0;
}
vectorOne.normalize();
vectorTwo.normalize();
double angle = std::acos(QVector3D().dotProduct(vectorOne, vectorTwo));
return angle;
}
/*
* findet den Kopf der Feature Line, in der index ist (dieser hat sich selbst
* als parent setzt auch direkt fuer alle Edges auf dem Weg zum Kopf diesen
* direkt als parent um die Suchzeit weiter kurz zu halten
*
*/
int FeatureConvincedDenoising::followToLineHead(int index) {
if (index < 0) {
qDebug() << "not a line member";
return -1;
}
if (edges[index].index == edges[index].lineParent) {
return index;
}
edges[index].lineParent = followToLineHead(edges[index].lineParent);
return edges[index].lineParent;
}
/*
* folgt der Feature Line weg vom angegebenen Knoten bis zu deren Ende und
* ermittelt dabei die Eigenschaften dieses Lineabschnitts
*/
int FeatureConvincedDenoising::followPathToBeCutOff(
vx::Array2<float> vertices, double& dToBeCutOff, double& iToBeCutOff,
int& lengthToBeCutOff, int edge, int awayFromNode) {
dToBeCutOff += edges.at(edge).dThisEdge;
lengthToBeCutOff++;
if (awayFromNode == edges.at(edge).vertexOne) {
if (edges.at(edge).lineNeighbourTwo >= 0) {
iToBeCutOff += std::cos(
3.14 - angleBetweenEdges(vertices, edges.at(edge),
edges.at(edges.at(edge).lineNeighbourTwo)));
return followPathToBeCutOff(
vertices, dToBeCutOff, iToBeCutOff, lengthToBeCutOff,
edges.at(edge).lineNeighbourTwo, edges.at(edge).vertexTwo);
}
}
if (awayFromNode == edges.at(edge).vertexTwo) {
if (edges.at(edge).lineNeighbourOne >= 0) {
iToBeCutOff += std::cos(
3.14 - angleBetweenEdges(vertices, edges.at(edge),
edges.at(edges.at(edge).lineNeighbourOne)));
return followPathToBeCutOff(
vertices, dToBeCutOff, iToBeCutOff, lengthToBeCutOff,
edges.at(edge).lineNeighbourOne, edges.at(edge).vertexOne);
}
}
return edge;
}
/*
* Setzt newHead als neuen Kopf der Linie, die dort an der Kante edge startet
* und vom Knoten awayFromNode wegfuehrt, updatet sämtliche Groeßen dieser neuen
* Line und setzt fuer alle Kanten den Parent direkt auf den neuen Kopf
*/
void FeatureConvincedDenoising::setNewHead(vx::Array2<float> vertices,
int newHead, double& newD,
double& newI, int& newLength,
int edge, int awayFromNode) {
newD += edges.at(edge).dThisEdge;
edges[edge].lineParent = newHead;
newLength++;
if (awayFromNode == edges.at(edge).vertexOne) {
if (edges.at(edge).lineNeighbourTwo >= 0 &&
!(edges.at(edge).lineNeighbourTwo == newHead)) {
newI += std::cos(
3.14 - angleBetweenEdges(vertices, edges.at(edge),
edges.at(edges.at(edge).lineNeighbourTwo)));
setNewHead(vertices, newHead, newD, newI, newLength,
edges.at(edge).lineNeighbourTwo, edges.at(edge).vertexTwo);
}
}
if (awayFromNode == edges.at(edge).vertexTwo) {
if (edges.at(edge).lineNeighbourOne >= 0 &&
!(edges.at(edge).lineNeighbourOne == newHead)) {
newI += std::cos(
3.14 - angleBetweenEdges(vertices, edges.at(edge),
edges.at(edges.at(edge).lineNeighbourOne)));
setNewHead(vertices, newHead, newD, newI, newLength,
edges.at(edge).lineNeighbourOne, edges.at(edge).vertexOne);
}
}
edges[newHead].dLine = newD;
if (newLength > 1) {
edges[newHead].iLine = newI / (newLength - 1);
}
edges[newHead].saliency = edges[newHead].iLine * newD;
edges[newHead].lineLength = newLength;
}
int FeatureConvincedDenoising::traverseLineToOppositeEnd(
vx::Array2<float> vertices, int start, int awayFromNode) {
if (awayFromNode == edges.at(start).vertexOne) {
if (edges.at(start).lineNeighbourTwo >= 0) {
return traverseLineToOppositeEnd(vertices,
edges.at(start).lineNeighbourTwo,
edges.at(start).vertexTwo);
}
}
if (awayFromNode == edges.at(start).vertexTwo) {
if (edges.at(start).lineNeighbourOne >= 0) {
return traverseLineToOppositeEnd(vertices,
edges.at(start).lineNeighbourOne,
edges.at(start).vertexOne);
}
}
return start;
}
void FeatureConvincedDenoising::setParameters(
vx::Array2<float> vertices, vx::Array2<const uint32_t> triangles,
vx::ClaimedOperation<de::uni_stuttgart::Voxie::ExternalOperationRunFilter>&
prog) {
for (size_t i = 0; i < vertices.size<0>(); i++) {
laplacians.append(QVector3D(0, 0, 0));
lapNeighbours.append(0);
}
double mselNoisy = 0;
computeNoise(vertices, triangles, mselNoisy);
meanLength = sqrt(mselNoisy);
FastEffectiveDPFilter filter;
filter.compute(vertices, triangles, 0.4, 4, prog);
double mselClean = 0;
computeNoise(vertices, triangles, mselClean);
double noise =
sqrt((mselNoisy * mselNoisy) / (2 * mselClean * mselClean) - 0.5);
resetVertices(vertices);
if (noise < 0.1) {
taubinIterations = 0;
fedIterations = 5;
minFeatureEdgeAngle = 0.75;
bilateralFilterIterations = 3;
filterIterations = 3;
} else if (noise < 0.25) {
taubinIterations = 1;
fedIterations = 8;
minFeatureEdgeAngle = 0.85;
bilateralFilterIterations = 4;
filterIterations = 4;
} else if (noise < 0.45) {
taubinIterations = 2;
fedIterations = 10;
minFeatureEdgeAngle = 0.82;
bilateralFilterIterations = 6;
filterIterations = 6;
} else {
taubinIterations = 2;
fedIterations = 12;
minFeatureEdgeAngle = 0.78;
bilateralFilterIterations = 8;
filterIterations = 8;
}
lineAngleThreshold = 2.5; // experiment
sigmaSpacial = sqrt(mselClean); //??
sigmaSignal = 0.35;
maxNeighbourhoodSize = 12;
minimumLineLenghth = 2;
extensionAngle = lineAngleThreshold;
}
void FeatureConvincedDenoising::computeNoise(
vx::Array2<float> vertices, vx::Array2<const uint32_t> triangles,
double& msel) {
for (int i = 0; i < trianglesCopy.size(); i++) {
QVector3D first(vertices(triangles(i, 0), 0), vertices(triangles(i, 0), 1),
vertices(triangles(i, 0), 2));
QVector3D second(vertices(triangles(i, 1), 0), vertices(triangles(i, 1), 1),
vertices(triangles(i, 1), 2));
QVector3D third(vertices(triangles(i, 2), 0), vertices(triangles(i, 2), 1),
vertices(triangles(i, 2), 2));
double edgeLenght = (first - second).length();
edgeLenght = edgeLenght * edgeLenght;
msel += edgeLenght;
edgeLenght = (first - third).length();
edgeLenght = edgeLenght * edgeLenght;
msel += edgeLenght;
edgeLenght = (second - third).length();
edgeLenght = edgeLenght * edgeLenght;
msel += edgeLenght;
laplacians[triangles(i, 0)] += (second - first) + (third - first);
laplacians[triangles(i, 1)] += (first - second) + (third - second);
laplacians[triangles(i, 2)] += (first - third) + (second - third);
lapNeighbours[triangles(i, 0)] += 2;
lapNeighbours[triangles(i, 1)] += 2;
lapNeighbours[triangles(i, 2)] += 2;
}
msel = msel / (trianglesCopy.size() * 3);
for (int i = 0; i < laplacians.length(); i++) {
if (lapNeighbours.at(i) > 0) {
meanLaplacian += laplacians.at(i).length() / lapNeighbours.at(i);
}
}
meanLaplacian /= laplacians.size();
}
void FeatureConvincedDenoising::resetVertices(vx::Array2<float>& vertices) {
for (int i = 0; i < verticesCopy.size(); i++) {
vertices(i, 0) = verticesCopy.at(i).x();
vertices(i, 1) = verticesCopy.at(i).y();
vertices(i, 2) = verticesCopy.at(i).z();
}
}
| 35.30098 | 80 | 0.634627 | voxie-viewer |
da7167b4bc175e444057d257763b7221b6630bc4 | 119 | cpp | C++ | TBGame/sfml_app.cpp | Alexander3006/TBGame | d4a73d0e76d3ef1bf894a325840a4d16c507d574 | [
"Apache-2.0"
] | null | null | null | TBGame/sfml_app.cpp | Alexander3006/TBGame | d4a73d0e76d3ef1bf894a325840a4d16c507d574 | [
"Apache-2.0"
] | null | null | null | TBGame/sfml_app.cpp | Alexander3006/TBGame | d4a73d0e76d3ef1bf894a325840a4d16c507d574 | [
"Apache-2.0"
] | null | null | null | #include <SFML/Graphics.hpp>
#include "GameManager.h"
int main()
{
GameManager game;
game.StartMenu();
return 0;
} | 11.9 | 28 | 0.697479 | Alexander3006 |
da72549b78468ab4136ac37a958007079d6e758b | 912 | cpp | C++ | HackatonServer/app/testConvert/main.cpp | Engilian/3BF6PP | 0edaaeb9cd4181dfd673ade96b8bd8b65e0a3970 | [
"Apache-2.0"
] | null | null | null | HackatonServer/app/testConvert/main.cpp | Engilian/3BF6PP | 0edaaeb9cd4181dfd673ade96b8bd8b65e0a3970 | [
"Apache-2.0"
] | null | null | null | HackatonServer/app/testConvert/main.cpp | Engilian/3BF6PP | 0edaaeb9cd4181dfd673ade96b8bd8b65e0a3970 | [
"Apache-2.0"
] | null | null | null | #include <QCoreApplication>
#include <QDebug>
#include <pfactory/pfactory.h>
#include <xl_to_json_converter.h>
#include <xl_to_json_converter_task.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
try {
pf::FactoryExp::inst()->add<xl::XlToJsonConverter>( "xl::XlToJsonConverter" );
} catch (...) { }
try {
auto converter = pf::FactoryExp::inst()->create<xl::XlToJsonConverter>();
auto task = converter->start( "c:\\test.xlsx", "родившиеся", "c:\\" );
QObject::connect ( task.get(), &xl::XlToJsonConverterTask::finished,
[task]{
qDebug() << task->status();
QCoreApplication::exit( 0 );
});
QObject::connect ( task.get(), &xl::XlToJsonConverterTask::progressChanged,
[task]{
qDebug() << task->progress();
});
return a.exec();
} catch (...) {
}
return a.exec();
}
| 24.648649 | 82 | 0.58443 | Engilian |
da764f5e2ec794bb9f29bc83e7f8bcb398aea08d | 782 | hh | C++ | CppPool/cpp_d10/ex03/AMateria.hh | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 40 | 2018-01-28T14:23:27.000Z | 2022-03-05T15:57:47.000Z | CppPool/cpp_d10/ex03/AMateria.hh | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 1 | 2021-10-05T09:03:51.000Z | 2021-10-05T09:03:51.000Z | CppPool/cpp_d10/ex03/AMateria.hh | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 73 | 2019-01-07T18:47:00.000Z | 2022-03-31T08:48:38.000Z | //
// AMateria.hh for AMetaria in /home/gwendoline/Epitech/Tek2/Piscine_cpp/piscine_cpp_d10/ex06
//
// Made by Gwendoline Rodriguez
// Login <gwendoline@epitech.net>
//
// Started on Fri Jan 15 16:29:55 2016 Gwendoline Rodriguez
// Last update Fri Jan 15 16:56:33 2016 Gwendoline Rodriguez
//
#ifndef AMATERIA_HH
#define AMATERIA_HH
class AMateria
{
private:
unsigned int xp_;
std::string const type;
public:
AMateria();
AMetaria(AMetaria const &);
AMateria(std::string const & type);
AMateria& operator=(AMateria const &);
virtual ~AMateria();
std::string const & getType() const; //Returns the materia type
unsigned int getXP() const; //Returns the Materia’s xp14
virtual AMateria* clone() const = 0;
virtual void use(ICharacter& target);
};
#endif
| 22.342857 | 93 | 0.719949 | 667MARTIN |
da7b77477bb015f50380a03161481d333cccb0e0 | 636 | cpp | C++ | Engine/Input/Input.cpp | ryanvanrooyen/GameFramework | 56ec1fe66964b2963cbdb2ba04640be47de59cc7 | [
"Apache-2.0"
] | null | null | null | Engine/Input/Input.cpp | ryanvanrooyen/GameFramework | 56ec1fe66964b2963cbdb2ba04640be47de59cc7 | [
"Apache-2.0"
] | null | null | null | Engine/Input/Input.cpp | ryanvanrooyen/GameFramework | 56ec1fe66964b2963cbdb2ba04640be47de59cc7 | [
"Apache-2.0"
] | null | null | null |
#include "Input.hpp"
#include "Core/Engine.hpp"
#include "Core/Window.hpp"
namespace Game
{
bool Input::IsKeyPressed(KeyCode key)
{
return Engine::Instance()->ActiveWindow()->IsKeyPressed(key);
}
bool Input::IsMousePressed(MouseCode button)
{
return Engine::Instance()->ActiveWindow()->IsMousePressed(button);
}
std::pair<double, double> Input::GetMousePosition()
{
return Engine::Instance()->ActiveWindow()->GetMousePosition();
}
double Input::GetMouseX()
{
return Engine::Instance()->ActiveWindow()->GetMouseX();
}
double Input::GetMouseY()
{
return Engine::Instance()->ActiveWindow()->GetMouseY();
}
} | 16.736842 | 70 | 0.701258 | ryanvanrooyen |
da824fe767cabfa0e650463377120d29a7acf67c | 29,223 | hpp | C++ | include/fiction/layouts/cartesian_layout.hpp | ElderDelp/fiction | f16bf67bbfd94e5a3d5b6b5cd9cbce5275e44ce8 | [
"MIT"
] | null | null | null | include/fiction/layouts/cartesian_layout.hpp | ElderDelp/fiction | f16bf67bbfd94e5a3d5b6b5cd9cbce5275e44ce8 | [
"MIT"
] | null | null | null | include/fiction/layouts/cartesian_layout.hpp | ElderDelp/fiction | f16bf67bbfd94e5a3d5b6b5cd9cbce5275e44ce8 | [
"MIT"
] | null | null | null | //
// Created by marcel on 31.03.21.
//
#ifndef FICTION_CARTESIAN_LAYOUT_HPP
#define FICTION_CARTESIAN_LAYOUT_HPP
#include "fiction/layouts/coordinates.hpp"
#include "fiction/utils/range.hpp"
#include <mockturtle/networks/detail/foreach.hpp>
#include <algorithm>
#include <cstdint>
#include <memory>
#include <set>
#include <utility>
namespace fiction
{
/**
* A layout type that utilizes offset coordinates to represent a Cartesian grid. Its faces are organized in the
* following way:
*
* \verbatim
+-------+-------+-------+-------+
| | | | |
| (0,0) | (1,0) | (2,0) | (3,0) |
| | | | |
+-------+-------+-------+-------+
| | | | |
| (0,1) | (1,1) | (2,1) | (3,1) |
| | | | |
+-------+-------+-------+-------+
| | | | |
| (0,2) | (1,2) | (2,2) | (3,2) |
| | | | |
+-------+-------+-------+-------+
\endverbatim
*
* @tparam OffsetCoordinateType The coordinate implementation to be used. Offset coordinates are required.
*/
template <typename OffsetCoordinateType>
class cartesian_layout
{
public:
#pragma region Types and constructors
using coordinate = OffsetCoordinateType;
using aspect_ratio = OffsetCoordinateType;
struct cartesian_layout_storage
{
explicit cartesian_layout_storage(const aspect_ratio& ar) noexcept : dimension{ar} {};
aspect_ratio dimension;
};
static constexpr auto min_fanin_size = 0u;
static constexpr auto max_fanin_size = 3u;
using base_type = cartesian_layout;
using storage = std::shared_ptr<cartesian_layout_storage>;
/**
* Standard constructor. The given aspect ratio points to the highest possible coordinate in the layout. That means
* in the ASCII layout above ar = (3,2). Consequently, with ar = (0,0), the layout has exactly one coordinate.
*
* @param ar Highest possible position in the layout.
*/
explicit cartesian_layout(const aspect_ratio& ar = {}) : strg{std::make_shared<cartesian_layout_storage>(ar)} {}
/**
* Copy constructor from another layout's storage.
*
* @param s Storage of another cartesian_layout.
*/
explicit cartesian_layout(std::shared_ptr<cartesian_layout_storage> s) : strg{std::move(s)} {}
#pragma endregion
#pragma region Structural properties
/**
* Returns the layout's x-dimension, i.e., returns the biggest x-value that still belongs to the layout.
*
* @return x-dimension.
*/
[[nodiscard]] auto x() const noexcept
{
return strg->dimension.x;
}
/**
* Returns the layout's y-dimension, i.e., returns the biggest y-value that still belongs to the layout.
*
* @return y-dimension.
*/
[[nodiscard]] auto y() const noexcept
{
return strg->dimension.y;
}
/**
* Returns the layout's z-dimension, i.e., returns the biggest z-value that still belongs to the layout.
*
* @return z-dimension.
*/
[[nodiscard]] auto z() const noexcept
{
return strg->dimension.z;
}
/**
* Returns the layout's number of faces which are equal to (x + 1) * (y + 1).
*
* @return Area of layout.
*/
[[nodiscard]] auto area() const noexcept
{
return (x() + 1) * (y() + 1);
}
/**
* Updates the layout's dimensions, effectively resizing it.
*
* @param ar New aspect ratio.
*/
void resize(const aspect_ratio& ar) noexcept
{
strg->dimension = ar;
}
#pragma endregion
#pragma region Cardinal operations
/**
* Returns the coordinate that is directly adjacent in northern direction of a given coordinate c, i.e., the face
* whose y-dimension is lower by 1. If c's y-dimension is already at minimum, c is returned instead.
*
* @param c Coordinate whose northern counterpart is desired.
* @return Coordinate adjacent and north of c.
*/
[[nodiscard]] constexpr OffsetCoordinateType north(const OffsetCoordinateType& c) const noexcept
{
if (c.y == 0ull)
return c;
auto nc = c;
--nc.y;
return nc;
}
/**
* Returns the coordinate that is located in north-eastern direction of a given coordinate c, i.e., the face
* whose x-dimension is higher by 1 and whose y-dimension is lower by 1. If c's x-dimension is already at maximum or
* c's y-dimension is already at minimum, c is returned instead.
*
* @param c Coordinate whose north-eastern counterpart is desired.
* @return Coordinate directly north-eastern of c.
*/
[[nodiscard]] constexpr OffsetCoordinateType north_east(const OffsetCoordinateType& c) const noexcept
{
if (c.x == x() || c.y == 0ull)
return c;
auto nec = c;
++nec.x;
--nec.y;
return nec;
}
/**
* Returns the coordinate that is directly adjacent in eastern direction of a given coordinate c, i.e., the face
* whose x-dimension is higher by 1. If c's x-dimension is already at maximum, c is returned instead.
*
* @param c Coordinate whose eastern counterpart is desired.
* @return Coordinate adjacent and east of c.
*/
[[nodiscard]] OffsetCoordinateType east(const OffsetCoordinateType& c) const noexcept
{
auto ec = c;
if (c.x > x())
ec.d = 1;
else if (c.x < x())
++ec.x;
return ec;
}
/**
* Returns the coordinate that is located in south-eastern direction of a given coordinate c, i.e., the face
* whose x-dimension and y-dimension are higher by 1. If c's x-dimension or y-dimension are already at maximum, c is
* returned instead.
*
* @param c Coordinate whose south-eastern counterpart is desired.
* @return Coordinate directly south-eastern of c.
*/
[[nodiscard]] OffsetCoordinateType south_east(const OffsetCoordinateType& c) const noexcept
{
auto sec = c;
if (c.x > x() || c.y > y())
sec.d = 1;
else if (c.x < x() && c.y < y())
{
++sec.x;
++sec.y;
}
return sec;
}
/**
* Returns the coordinate that is directly adjacent in southern direction of a given coordinate c, i.e., the face
* whose y-dimension is higher by 1. If c's y-dimension is already at maximum, c is returned instead.
*
* @param c Coordinate whose southern counterpart is desired.
* @return Coordinate adjacent and south of c.
*/
[[nodiscard]] OffsetCoordinateType south(const OffsetCoordinateType& c) const noexcept
{
auto sc = c;
if (c.y > y())
sc.d = 1;
else if (c.y < y())
++sc.y;
return sc;
}
/**
* Returns the coordinate that is located in south-western direction of a given coordinate c, i.e., the face
* whose x-dimension is lower by 1 and whose y-dimension is higher by 1. If c's x-dimension is already at minimum or
* c's y-dimension is already at maximum, c is returned instead.
*
* @param c Coordinate whose south-western counterpart is desired.
* @return Coordinate directly south-western of c.
*/
[[nodiscard]] OffsetCoordinateType south_west(const OffsetCoordinateType& c) const noexcept
{
auto swc = c;
if (c.y > y())
swc.d = 1;
else if (c.x > 0ull && c.y < y())
{
--swc.x;
++swc.y;
}
return swc;
}
/**
* Returns the coordinate that is directly adjacent in western direction of a given coordinate c, i.e., the face
* whose x-dimension is lower by 1. If c's x-dimension is already at minimum, c is returned instead.
*
* @param c Coordinate whose western counterpart is desired.
* @return Coordinate adjacent and west of c.
*/
[[nodiscard]] constexpr OffsetCoordinateType west(const OffsetCoordinateType& c) const noexcept
{
if (c.x == 0ull)
return c;
auto wc = c;
--wc.x;
return wc;
}
/**
* Returns the coordinate that is located in north-western direction of a given coordinate c, i.e., the face
* whose x-dimension and y-dimension are lower by 1. If c's x-dimension or y-dimension are already at minimum, c is
* returned instead.
*
* @param c Coordinate whose north-western counterpart is desired.
* @return Coordinate directly north-western of c.
*/
[[nodiscard]] constexpr OffsetCoordinateType north_west(const OffsetCoordinateType& c) const noexcept
{
if (c.x == 0ull || c.y == 0ull)
return c;
auto nwc = c;
--nwc.x;
--nwc.y;
return nwc;
}
/**
* Returns the coordinate that is directly above a given coordinate c, i.e., the face whose z-dimension is higher
* by 1. If c's z-dimension is already at maximum, c is returned instead.
*
* @param c Coordinate whose above counterpart is desired.
* @return Coordinate directly above c.
*/
[[nodiscard]] OffsetCoordinateType above(const OffsetCoordinateType& c) const noexcept
{
auto ac = c;
if (c.z > z())
ac.d = 1;
else if (c.z < z())
++ac.z;
return ac;
}
/**
* Returns the coordinate that is directly below a given coordinate c, i.e., the face whose z-dimension is lower
* by 1. If c's z-dimension is already at minimum, c is returned instead.
*
* @param c Coordinate whose below counterpart is desired.
* @return Coordinate directly below c.
*/
[[nodiscard]] constexpr OffsetCoordinateType below(const OffsetCoordinateType& c) const noexcept
{
if (c.z == 0ull)
return c;
auto bc = c;
--bc.z;
return bc;
}
/**
* Returns true iff coordinate c2 is directly north of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is directly north of c1.
*/
[[nodiscard]] constexpr bool is_north_of(const OffsetCoordinateType& c1,
const OffsetCoordinateType& c2) const noexcept
{
return c1 != c2 && north(c1) == c2;
}
/**
* Returns true iff coordinate c2 is directly east of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is directly east of c1.
*/
[[nodiscard]] bool is_east_of(const OffsetCoordinateType& c1, const OffsetCoordinateType& c2) const noexcept
{
return c1 != c2 && east(c1) == c2;
}
/**
* Returns true iff coordinate c2 is directly south of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is directly south of c1.
*/
[[nodiscard]] bool is_south_of(const OffsetCoordinateType& c1, const OffsetCoordinateType& c2) const noexcept
{
return c1 != c2 && south(c1) == c2;
}
/**
* Returns true iff coordinate c2 is directly west of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is directly west of c1.
*/
[[nodiscard]] constexpr bool is_west_of(const OffsetCoordinateType& c1,
const OffsetCoordinateType& c2) const noexcept
{
return c1 != c2 && west(c1) == c2;
}
/**
* Returns true iff coordinate c2 is either directly north, east, south, or west of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is either directly north, east, south, or west of c1.
*/
[[nodiscard]] bool is_adjacent_of(const OffsetCoordinateType& c1, const OffsetCoordinateType& c2) const noexcept
{
return is_north_of(c1, c2) || is_east_of(c1, c2) || is_south_of(c1, c2) || is_west_of(c1, c2);
}
/**
* Similar to is_adjacent_of but also considers c1's elevation, i.e., if c2 is adjacent to above(c1) or below(c1).
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is either directly north, east, south, or west of c1 or c1's elevations.
*/
[[nodiscard]] bool is_adjacent_elevation_of(const OffsetCoordinateType& c1,
const OffsetCoordinateType& c2) const noexcept
{
return is_adjacent_of(c1, c2) || is_adjacent_of(above(c1), c2) || is_adjacent_of(below(c1), c2);
}
/**
* Returns true iff coordinate c2 is directly above coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is directly above c1.
*/
[[nodiscard]] bool is_above(const OffsetCoordinateType& c1, const OffsetCoordinateType& c2) const noexcept
{
return c1 != c2 && above(c1) == c2;
}
/**
* Returns true iff coordinate c2 is directly below coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is directly below c1.
*/
[[nodiscard]] constexpr bool is_below(const OffsetCoordinateType& c1, const OffsetCoordinateType& c2) const noexcept
{
return c1 != c2 && below(c1) == c2;
}
/**
* Returns true iff coordinate c2 is somewhere north of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is somewhere north of c1.
*/
[[nodiscard]] constexpr bool is_northwards_of(const OffsetCoordinateType& c1,
const OffsetCoordinateType& c2) const noexcept
{
return (c1.z == c2.z) && (c1.y > c2.y) && (c1.x == c2.x);
}
/**
* Returns true iff coordinate c2 is somewhere east of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is somewhere east of c1.
*/
[[nodiscard]] constexpr bool is_eastwards_of(const OffsetCoordinateType& c1,
const OffsetCoordinateType& c2) const noexcept
{
return (c1.z == c2.z) && (c1.y == c2.y) && (c1.x < c2.x);
}
/**
* Returns true iff coordinate c2 is somewhere south of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is somewhere south of c1.
*/
[[nodiscard]] constexpr bool is_southwards_of(const OffsetCoordinateType& c1,
const OffsetCoordinateType& c2) const noexcept
{
return (c1.z == c2.z) && (c1.y < c2.y) && (c1.x == c2.x);
}
/**
* Returns true iff coordinate c2 is somewhere west of coordinate c1.
*
* @param c1 Base coordinate.
* @param c2 Coordinate to test for its location in relation to c1.
* @return True iff c2 is somewhere west of c1.
*/
[[nodiscard]] constexpr bool is_westwards_of(const OffsetCoordinateType& c1,
const OffsetCoordinateType& c2) const noexcept
{
return (c1.z == c2.z) && (c1.y == c2.y) && (c1.x > c2.x);
}
/**
* Returns whether the given coordinate is located at the layout's northern border where y is minimal.
*
* @param c Coordinate to check for border location.
* @return True iff c is located at the layout's northern border.
*/
[[nodiscard]] constexpr bool is_at_northern_border(const OffsetCoordinateType& c) const noexcept
{
return c.y == 0ull;
}
/**
* Returns whether the given coordinate is located at the layout's eastern border where x is maximal.
*
* @param c Coordinate to check for border location.
* @return True iff c is located at the layout's northern border.
*/
[[nodiscard]] bool is_at_eastern_border(const OffsetCoordinateType& c) const noexcept
{
return c.x == x();
}
/**
* Returns whether the given coordinate is located at the layout's southern border where y is maximal.
*
* @param c Coordinate to check for border location.
* @return True iff c is located at the layout's southern border.
*/
[[nodiscard]] bool is_at_southern_border(const OffsetCoordinateType& c) const noexcept
{
return c.y == y();
}
/**
* Returns whether the given coordinate is located at the layout's western border where x is minimal.
*
* @param c Coordinate to check for border location.
* @return True iff c is located at the layout's western border.
*/
[[nodiscard]] constexpr bool is_at_western_border(const OffsetCoordinateType& c) const noexcept
{
return c.x == 0ull;
}
/**
* Returns whether the given coordinate is located at any of the layout's borders where x or y are either minimal or
* maximal.
*
* @param c Coordinate to check for border location.
* @return True iff c is located at any of the layout's borders.
*/
[[nodiscard]] bool is_at_any_border(const OffsetCoordinateType& c) const noexcept
{
return is_at_northern_border(c) || is_at_eastern_border(c) || is_at_southern_border(c) ||
is_at_western_border(c);
}
/**
* Returns the coordinate with the same x and z values as a given coordinate but that is located at the layout's
* northern border.
*
* @param c Coordinate whose border counterpart is desired.
* @return The northern border equivalent of c.
*/
[[nodiscard]] OffsetCoordinateType northern_border_of(const OffsetCoordinateType& c) const noexcept
{
return {c.x, 0ull, c.z};
}
/**
* Returns the coordinate with the same y and z values as a given coordinate but that is located at the layout's
* eastern border.
*
* @param c Coordinate whose border counterpart is desired.
* @return The eastern border equivalent of c.
*/
[[nodiscard]] OffsetCoordinateType eastern_border_of(const OffsetCoordinateType& c) const noexcept
{
return {x(), c.y, c.z};
}
/**
* Returns the coordinate with the same x and z values as a given coordinate but that is located at the layout's
* southern border.
*
* @param c Coordinate whose border counterpart is desired.
* @return The southern border equivalent of c.
*/
[[nodiscard]] OffsetCoordinateType southern_border_of(const OffsetCoordinateType& c) const noexcept
{
return {c.x, y(), c.z};
}
/**
* Returns the coordinate with the same y and z values as a given coordinate but that is located at the layout's
* western border.
*
* @param c Coordinate whose border counterpart is desired.
* @return The western border equivalent of c.
*/
[[nodiscard]] OffsetCoordinateType western_border_of(const OffsetCoordinateType& c) const noexcept
{
return {0ull, c.y, c.z};
}
/**
* Returns whether the given coordinate is located in the ground layer where z is minimal.
*
* @param c Coordinate to check for elevation.
* @return True iff c is in ground layer.
*/
[[nodiscard]] constexpr bool is_ground_layer(const OffsetCoordinateType& c) const noexcept
{
return c.z == 0ull;
}
/**
* Returns whether the given coordinate is located in a crossing layer where z is not minimal.
*
* @param c Coordinate to check for elevation.
* @return True iff c is in a crossing layer.
*/
[[nodiscard]] constexpr bool is_crossing_layer(const OffsetCoordinateType& c) const noexcept
{
return c.z > 0;
}
/**
* Returns whether the given coordinate is located within the layout bounds.
*
* @param c Coordinate to check for boundary.
* @return True iff c is located within the layout bounds.
*/
[[nodiscard]] constexpr bool is_within_bounds(const OffsetCoordinateType& c) const noexcept
{
return c.x <= x() && c.y <= y() && c.z <= z();
}
#pragma endregion
#pragma region Iteration
/**
* Returns a range of all coordinates accessible in the layout between start and stop. If no values are provided,
* all coordinates in the layout will be included. The returned iterator range points to the first and last
* coordinate, respectively. The range object can be used within a for-each loop. Incrementing the iterator is
* equivalent to nested for loops in the order z, y, x. Consequently, the iteration will happen inside out, i.e., x
* will be iterated first, then y, then z.
*
* @param start First coordinate to include in the range of all coordinates.
* @param stop Last coordinate to include in the range of all coordinates.
* @return An iterator range from start to stop. If they are not provided, the first/last coordinate is used as a
* default.
*/
[[nodiscard]] auto coordinates(const OffsetCoordinateType& start = {}, const OffsetCoordinateType& stop = {}) const
{
return range_t{std::make_pair(
offset::coord_iterator{strg->dimension, start.is_dead() ? OffsetCoordinateType{0, 0} : start},
offset::coord_iterator{strg->dimension, stop.is_dead() ? strg->dimension.get_dead() : stop})};
}
/**
* Applies a function to all coordinates accessible in the layout between start and stop. The iteration order is the
* same as for the coordinates function.
*
* @tparam Fn Functor type that has to comply with the restrictions imposed by mockturtle::foreach_element.
* @param fn Functor to apply to each coordinate in the range.
* @param start First coordinate to include in the range of all coordinates.
* @param stop Last coordinate to include in the range of all coordinates.
*/
template <typename Fn>
void foreach_coordinate(Fn&& fn, const OffsetCoordinateType& start = {},
const OffsetCoordinateType& stop = {}) const
{
mockturtle::detail::foreach_element(
offset::coord_iterator{strg->dimension, start.is_dead() ? OffsetCoordinateType{0, 0} : start},
offset::coord_iterator{strg->dimension, stop.is_dead() ? strg->dimension.get_dead() : stop}, fn);
}
/**
* Returns a range of all coordinates accessible in the layout's ground layer between start and stop. The iteration
* order is the same as for the coordinates function but without the z dimension.
*
* @param start First coordinate to include in the range of all ground coordinates.
* @param stop Last coordinate to include in the range of all ground coordinates.
* @return An iterator range from start to stop. If they are not provided, the first/last coordinate in the ground
* layer is used as a default.
*/
[[nodiscard]] auto ground_coordinates(const OffsetCoordinateType& start = {},
const OffsetCoordinateType& stop = {}) const
{
assert(start.z == 0 && stop.z == 0);
const auto ground_layer = aspect_ratio{x(), y(), 0};
return range_t{
std::make_pair(offset::coord_iterator{ground_layer, start.is_dead() ? OffsetCoordinateType{0, 0} : start},
offset::coord_iterator{ground_layer, stop.is_dead() ? ground_layer.get_dead() : stop})};
}
/**
* Applies a function to all coordinates accessible in the layout's ground layer between start and stop. The
* iteration order is the same as for the ground_coordinates function.
*
* @tparam Fn Functor type that has to comply with the restrictions imposed by mockturtle::foreach_element.
* @param fn Functor to apply to each coordinate in the range.
* @param start First coordinate to include in the range of all ground coordinates.
* @param stop Last coordinate to include in the range of all ground coordinates.
*/
template <typename Fn>
void foreach_ground_coordinate(Fn&& fn, const OffsetCoordinateType& start = {},
const OffsetCoordinateType& stop = {}) const
{
assert(start.z == 0 && stop.z == 0);
const auto ground_layer = aspect_ratio{x(), y(), 0};
mockturtle::detail::foreach_element(
offset::coord_iterator{ground_layer, start.is_dead() ? OffsetCoordinateType{0, 0} : start},
offset::coord_iterator{ground_layer, stop.is_dead() ? ground_layer.get_dead() : stop}, fn);
}
/**
* Returns a container of a given type that contains all coordinates that are adjacent to a given one. Thereby, only
* cardinal directions are being considered, i.e., the container contains all coordinates ac for which
* is_adjacent(c, ac) returns true.
*
* Coordinates that are outside of the layout bounds are not considered. Thereby, the size of the returned container
* is at max 4.
*
* @tparam Container Container type that has to provide an insert member function.
* @param c Coordinate whose adjacent ones are desired.
* @return A container of type Container that contains all of c's adjacent coordinates.
*/
template <typename Container>
Container adjacent_coordinates(const OffsetCoordinateType& c) const noexcept
{
Container cnt{};
const auto add_if_not_c = [&c, &cnt](const auto& cardinal)
{
if (cardinal != c)
{
cnt.insert(cnt.end(), cardinal);
}
};
add_if_not_c(north(c));
add_if_not_c(east(c));
add_if_not_c(south(c));
add_if_not_c(west(c));
return cnt;
}
/**
* Applies a function to all coordinates adjacent to a given one in accordance with adjacent_coordinates.
*
* @tparam Fn Functor type that has to comply with the restrictions imposed by mockturtle::foreach_element.
* @param c Coordinate whose adjacent ones are desired.
* @param fn Functor to apply to each of c's adjacent coordinates.
*/
template <typename Fn>
void foreach_adjacent_coordinate(const OffsetCoordinateType& c, Fn&& fn) const
{
const auto adj = adjacent_coordinates<std::set<OffsetCoordinateType>>(c);
mockturtle::detail::foreach_element(adj.cbegin(), adj.cend(), fn);
}
/**
* Returns a container of a given type that contains all coordinates pairs of opposing adjacent coordinates with
* respect to a given one. In this Cartesian layout, the container will contain (north(c), south(c)) and (east(c),
* west(c)).
*
* This function comes in handy when straight lines on the layout are to be examined.
*
* Coordinates outside of the layout bounds are not being considered.
*
* @tparam Container Container type that has to provide an insert member function and holds pairs of coordinates.
* @param c Coordinate whose opposite ones are desired.
* @return A container of type Container that contains pairs of c's opposing coordinates.
*/
template <typename Container>
Container adjacent_opposite_coordinates(const OffsetCoordinateType& c) const noexcept
{
Container cnt{};
const auto add_if_not_c = [&c, &cnt](OffsetCoordinateType cardinal1, OffsetCoordinateType cardinal2)
{
if (cardinal1 != c && cardinal2 != c)
{
cnt.insert(cnt.end(), {std::move(cardinal1), std::move(cardinal2)});
}
};
add_if_not_c(north(c), south(c));
add_if_not_c(east(c), west(c));
return cnt;
}
/**
* Applies a function to all opposing coordinate pairs adjacent to a given one in accordance with
* adjacent_opposite_coordinates.
*
* @tparam Fn Functor type that has to comply with the restrictions imposed by mockturtle::foreach_element.
* @param c Coordinate whose opposite adjacent ones are desired.
* @param fn Functor to apply to each of c's opposite adjacent coordinate pairs.
*/
template <typename Fn>
void foreach_adjacent_opposite_coordinates(const OffsetCoordinateType& c, Fn&& fn) const
{
const auto adj =
adjacent_opposite_coordinates<std::set<std::pair<OffsetCoordinateType, OffsetCoordinateType>>>(c);
mockturtle::detail::foreach_element(adj.cbegin(), adj.cend(), fn);
}
#pragma endregion
private:
storage strg;
};
} // namespace fiction
#endif // FICTION_CARTESIAN_LAYOUT_HPP
| 38.100391 | 120 | 0.627417 | ElderDelp |
da8a3533e46589d70e81fbf044dc6f7c0a0bde61 | 535 | cpp | C++ | Small_2D_Game_Semester_Project_Windows/main.cpp | Sziperd/Portfolio | 38eb86c9c3aca0457f15cc83ac16fccd968a9b3e | [
"Apache-2.0"
] | null | null | null | Small_2D_Game_Semester_Project_Windows/main.cpp | Sziperd/Portfolio | 38eb86c9c3aca0457f15cc83ac16fccd968a9b3e | [
"Apache-2.0"
] | null | null | null | Small_2D_Game_Semester_Project_Windows/main.cpp | Sziperd/Portfolio | 38eb86c9c3aca0457f15cc83ac16fccd968a9b3e | [
"Apache-2.0"
] | null | null | null | #include "Glowny.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
clock_t TimeZero; //dostep do clocka systemowego aby gra dzialala w takiej samej predkosci na szybszym jak i wolniejszym sprzecie oraz aby mozliwe bylo losowanie liczby (potrzebne do ruchow NPC)
double deltaTime = 0;
int main()
{
_CrtDumpMemoryLeaks();
Glowny game;
if (game.ConstructConsole(128, 120, 5, 5))
//if (game.ConstructConsole(256, 240, 4, 4))
game.Start();
_CrtDumpMemoryLeaks();
return 0;
} | 21.4 | 195 | 0.697196 | Sziperd |
da8ac975ec6d3b5a38308ec07b9d3888dfd29d29 | 2,475 | cpp | C++ | p399/p399.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | 1 | 2019-10-07T05:00:21.000Z | 2019-10-07T05:00:21.000Z | p399/p399.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | p399/p399.cpp | suzyz/leetcode_practice | e22dc5a81e065dc962e5561b14ac84b9a2302e8a | [
"MIT"
] | null | null | null | class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
unordered_map<string,int> m;
int n = 0;
vector<vector<pair<int,double>>> g;
for (int i = 0; i < equations.size(); ++i)
{
string x = equations[i].first;
string y = equations[i].second;
if (m.count(x) == 0)
{
m[x] = n++;
g.push_back(vector<pair<int,double>>());
}
if (m.count(y) == 0)
{
m[y] = n++;
g.push_back(vector<pair<int,double>>());
}
g[m[x]].push_back(make_pair(m[y],values[i]));
g[m[y]].push_back(make_pair(m[x],1.0/values[i]));
}
vector<bool> calculated(n,false);
vector<vector<double>> dist(n,vector<double>(n,-1));
vector<double> res(queries.size(),-1);
for (int i = 0; i < queries.size(); ++i)
{
string a = queries[i].first;
string b = queries[i].second;
if (m.count(a) == 0 || m.count(b) == 0)
continue;
int x = m[a];
int y = m[b];
if (x == y)
res[i] = 1;
else
if (calculated[x])
res[i] = dist[x][y];
else
if (calculated[y])
res[i] = 1.0/dist[y][x];
else
{
calculated[x] = true;
dijkstra(x,n,g,dist);
res[i] = dist[x][y];
}
}
return res;
}
void dijkstra(int s,int n,vector<vector<pair<int,double>>> &g,vector<vector<double>> &dist)
{
vector<bool> vis(n,false);
dist[s][s] = 0;
vis[s] = true;
for (int i = 0; i < g[s].size(); ++i)
{
int y = g[s][i].first;
double d = g[s][i].second;
if (dist[s][y] < -1e-6 || dist[s][y] > d)
dist[s][y] = d;
}
for (int i = 0; i < n; ++i)
{
int k = -1;
double mind = 1e100;
for (int j = 0; j < n; ++j)
if (!vis[j] && dist[s][j] > -1e-6 && dist[s][j] < mind)
{
k = j;
mind = dist[s][j];
}
if (k == -1)
return;
vis[k] = true;
for (int j = 0; j < g[k].size(); ++j)
{
int y = g[k][j].first;
if (!vis[y])
{
double d = g[k][j].second;
if (dist[s][y] < -1e-6 || dist[s][y] > mind * d)
dist[s][y] = mind * d;
}
}
}
}
};
| 24.029126 | 135 | 0.423434 | suzyz |
da930fc3656a174b321c1292958fa1611b628451 | 816 | cpp | C++ | examples/drums+grids/main.cpp | marcelbienvu/MabiluObjects | 16b9bda2bebaba34550748c5a17b92361d6de241 | [
"MIT"
] | null | null | null | examples/drums+grids/main.cpp | marcelbienvu/MabiluObjects | 16b9bda2bebaba34550748c5a17b92361d6de241 | [
"MIT"
] | null | null | null | examples/drums+grids/main.cpp | marcelbienvu/MabiluObjects | 16b9bda2bebaba34550748c5a17b92361d6de241 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <Audio.h>
#include <MabiluObjects.h>
Grids seq;
Kick kick;
Hihat hh;
Snare sd;
AudioMixer4 mixer;
AudioOutputI2S dac;
AudioConnection con0(seq, 2, hh, 0);
AudioConnection con1(seq, 1, sd, 0);
AudioConnection con2(seq, 0, kick, 0);
AudioConnection con3(kick, 0, mixer, 0);
AudioConnection con4(hh, 0, mixer, 1);
AudioConnection con5(sd, 0, mixer, 2);
AudioConnection con6(mixer, 0, dac, 0);
AudioConnection con7(mixer, 0, dac, 1);
void setup() {
Serial.begin(115200);
AudioMemory(12);
mixer.gain(0, 0.3f);
mixer.gain(1, 0.3f);
mixer.gain(2, 0.3f);
}
void loop() {
seq.density(1, analogRead(14) >> 2);
Serial.print(AudioProcessorUsage());
Serial.print("\t");
Serial.println(AudioMemoryUsage());
} | 24 | 40 | 0.633578 | marcelbienvu |
daa42a714ae94a962f02dd1a5493ead00c3d59ef | 2,841 | cpp | C++ | mipe3d/src/Mipe3DInput.cpp | mipelius/mipe3d | 4c25d9e86928a67ea71139e87a3c99bbe11228f7 | [
"MIT"
] | null | null | null | mipe3d/src/Mipe3DInput.cpp | mipelius/mipe3d | 4c25d9e86928a67ea71139e87a3c99bbe11228f7 | [
"MIT"
] | null | null | null | mipe3d/src/Mipe3DInput.cpp | mipelius/mipe3d | 4c25d9e86928a67ea71139e87a3c99bbe11228f7 | [
"MIT"
] | null | null | null | // Copyright (c) Miika Pelkonen. All rights reserved.
// Licensed under the MIT License.
#include "Mipe3DInput.h"
#include "Mipe3DEngine.h"
#include "Mipe3DLog.h"
#include "Mipe3DRenderSystem.h"
#include <cassert>
#include <SDL_keyboard.h>
#include <SDL_keycode.h>
#include <SDL_mouse.h>
#include <SDL_events.h>
namespace mipe3d
{
// ------------------------ keyboard ------------------------
static SDL_Keycode convertKeyToSDLScancode(Key key)
{
switch (key)
{
case Key::UP: return SDL_SCANCODE_UP;
case Key::DOWN: return SDL_SCANCODE_DOWN;
case Key::LEFT: return SDL_SCANCODE_LEFT;
case Key::RIGHT: return SDL_SCANCODE_RIGHT;
case Key::W: return SDL_SCANCODE_W;
case Key::S: return SDL_SCANCODE_S;
case Key::A: return SDL_SCANCODE_A;
case Key::D: return SDL_SCANCODE_D;
case Key::SPACE: return SDL_SCANCODE_SPACE;
case Key::ESC: return SDL_SCANCODE_ESCAPE;
default:
return SDL_SCANCODE_UNKNOWN;
}
}
Keyboard::Keyboard()
{
}
Keyboard::~Keyboard()
{
}
bool Keyboard::isKeyDown(Key key) const
{
auto scancode = convertKeyToSDLScancode(key);
const Uint8* state = SDL_GetKeyboardState(NULL);
if (scancode == SDL_SCANCODE_UNKNOWN)
{
return false;
}
else
{
return state[scancode];
}
}
// ------------------------ mouse ------------------------
Mouse::Mouse()
{
}
Mouse::~Mouse()
{
}
void Mouse::setCursorVisible(bool visible)
{
SDL_ShowCursor(visible ? SDL_ENABLE : SDL_DISABLE);
}
void Mouse::setCursorPosition(glm::ivec2 position)
{
SDL_WarpMouseInWindow(
renderSystem().m_window,
position.x,
position.y);
}
glm::ivec2 Mouse::getCursorPosition() const
{
glm::ivec2 result;
SDL_GetMouseState(&result.x, &result.y);
return result;
}
bool Mouse::isLeftButtonDown() const
{
auto state = SDL_GetMouseState(NULL, NULL);
return state & SDL_BUTTON(SDL_BUTTON_LEFT);
}
bool Mouse::isRightButtonDown() const
{
auto state = SDL_GetMouseState(NULL, NULL);
return state & SDL_BUTTON(SDL_BUTTON_RIGHT);
}
// ------------------------ input ------------------------
Input::Input()
{
m_keyboard = new Keyboard();
m_mouse = new Mouse();
}
Input::~Input()
{
delete m_keyboard;
delete m_mouse;
}
bool Input::startUp()
{
// SDL_INIT_VIDEO is initialized in RenderSystem::startUp()
// which seems to initialize keyboard and mouse as well
// ---> no need to do anything here
return true;
}
bool Input::shutDown()
{
// Input::startUp() did nothing,
// so we don't do anything here either
return true;
}
void Input::update()
{
}
const Keyboard& Input::keyboard() const
{
return *m_keyboard;
}
Mouse& Input::mouse() const
{
return *m_mouse;
}
Input& input()
{
return *(engine().m_input);
}
} // namespace mipe3d | 18.448052 | 63 | 0.638156 | mipelius |
daadcee6b0d8c3ec14dd7586422a80fea8a0465c | 4,069 | cpp | C++ | core/src/view/Renderer3DModule.cpp | schulzch/megamol | c440ad06f388f151c13833d5d1a7653131bda2be | [
"BSD-3-Clause"
] | null | null | null | core/src/view/Renderer3DModule.cpp | schulzch/megamol | c440ad06f388f151c13833d5d1a7653131bda2be | [
"BSD-3-Clause"
] | null | null | null | core/src/view/Renderer3DModule.cpp | schulzch/megamol | c440ad06f388f151c13833d5d1a7653131bda2be | [
"BSD-3-Clause"
] | null | null | null | /*
* Renderer3DModule.cpp
*
* Copyright (C) 2018, 2020 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "mmcore/view/Renderer3DModule.h"
#include "mmcore/view/AbstractView.h"
#include "mmcore/view/CallRender3D.h"
namespace megamol::core::view {
/*
* Renderer3DModule::Renderer3DModule
*/
Renderer3DModule::Renderer3DModule(void) : RendererModule<CallRender3D, Module>() {
// Callback should already be set by RendererModule
this->MakeSlotAvailable(&this->chainRenderSlot);
// Callback should already be set by RendererModule
this->MakeSlotAvailable(&this->renderSlot);
}
/*
* Renderer3DModule::~Renderer3DModule
*/
Renderer3DModule::~Renderer3DModule(void) {
// intentionally empty
}
/*
* Renderer3DModule::GetExtentsChain
*/
bool Renderer3DModule::GetExtentsChain(CallRender3D& call) {
CallRender3D* chainedCall = this->chainRenderSlot.CallAs<CallRender3D>();
if (chainedCall != nullptr) {
// copy the incoming call to the output
*chainedCall = call;
// set bounding boxes to invalid before calling to the right, in case the chained renderer
// does not provide them at all. this would result in the possibly outdated bounding box
// from the left hand side being used
chainedCall->AccessBoundingBoxes().Clear();
// chain through the get extents call
(*chainedCall)(view::AbstractCallRender::FnGetExtents);
}
// TODO extents magic
// get our own extents
// set bounding boxes to invalid before getting own extent, in case the function
// does not provide them at all. this would result in the possibly outdated bounding box
// from the left hand side being used
call.AccessBoundingBoxes().Clear();
this->GetExtents(call);
if (chainedCall != nullptr) {
const auto& mybb = call.AccessBoundingBoxes().BoundingBox();
const auto& otherbb = chainedCall->AccessBoundingBoxes().BoundingBox();
const auto& mycb = call.AccessBoundingBoxes().ClipBox();
const auto& othercb = chainedCall->AccessBoundingBoxes().ClipBox();
auto newbb = mybb;
auto newcb = mycb;
if (call.GetBoundingBoxes().IsBoundingBoxValid() && chainedCall->GetBoundingBoxes().IsBoundingBoxValid()) {
newbb.Union(otherbb);
} else if (chainedCall->GetBoundingBoxes().IsBoundingBoxValid()) {
newbb = otherbb; // just override for the call
} // we ignore the other two cases as they both lead to usage of the already set mybb
if (call.GetBoundingBoxes().IsClipBoxValid() && chainedCall->GetBoundingBoxes().IsClipBoxValid()) {
newcb.Union(othercb);
} else if (chainedCall->GetBoundingBoxes().IsClipBoxValid()) {
newcb = othercb; // just override for the call
} // we ignore the other two cases as they both lead to usage of the already set mycb
call.AccessBoundingBoxes().SetBoundingBox(newbb);
call.AccessBoundingBoxes().SetClipBox(newcb);
// TODO machs richtig
call.SetTimeFramesCount(chainedCall->TimeFramesCount());
}
return true;
}
/*
* Renderer3DModule::RenderChain
*/
bool Renderer3DModule::RenderChain(CallRender3D& call) {
auto leftSlotParent = call.PeekCallerSlot()->Parent();
std::shared_ptr<const view::AbstractView> viewptr =
std::dynamic_pointer_cast<const view::AbstractView>(leftSlotParent);
this->PreRender(call);
CallRender3D* chainedCall = this->chainRenderSlot.CallAs<CallRender3D>();
if (chainedCall != nullptr) {
// copy the incoming call to the output
*chainedCall = call;
// chain through the render call
(*chainedCall)(view::AbstractCallRender::FnRender);
call = *chainedCall;
}
// render our own stuff
this->Render(call);
return true;
}
/*
* Renderer3DModule::PreRender
*/
void Renderer3DModule::PreRender(CallRender3D& call) {
// intentionally empty
}
} // namespace megamol::core::view
| 32.293651 | 115 | 0.676825 | schulzch |
dab1928006f911bb7f5c72f82ff7aa25b6605d60 | 1,521 | cpp | C++ | android-28/android/content/UriPermission.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/content/UriPermission.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/content/UriPermission.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../net/Uri.hpp"
#include "../os/Parcel.hpp"
#include "../../JString.hpp"
#include "./UriPermission.hpp"
namespace android::content
{
// Fields
JObject UriPermission::CREATOR()
{
return getStaticObjectField(
"android.content.UriPermission",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
jlong UriPermission::INVALID_TIME()
{
return getStaticField<jlong>(
"android.content.UriPermission",
"INVALID_TIME"
);
}
// QJniObject forward
UriPermission::UriPermission(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
jint UriPermission::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
jlong UriPermission::getPersistedTime() const
{
return callMethod<jlong>(
"getPersistedTime",
"()J"
);
}
android::net::Uri UriPermission::getUri() const
{
return callObjectMethod(
"getUri",
"()Landroid/net/Uri;"
);
}
jboolean UriPermission::isReadPermission() const
{
return callMethod<jboolean>(
"isReadPermission",
"()Z"
);
}
jboolean UriPermission::isWritePermission() const
{
return callMethod<jboolean>(
"isWritePermission",
"()Z"
);
}
JString UriPermission::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
void UriPermission::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::content
| 18.107143 | 77 | 0.668639 | YJBeetle |
dab2919b614729d811fc3991242455a135c25089 | 402 | cpp | C++ | C++/uri1029.cpp | AugustoDipNiloy/Uri-Solution | 7f455395bbbe55edce8d12afd80fa5ebd03d17a1 | [
"MIT"
] | 1 | 2020-11-09T17:06:43.000Z | 2020-11-09T17:06:43.000Z | C++/uri1029.cpp | AugustoDipNiloy/Uri-Solution | 7f455395bbbe55edce8d12afd80fa5ebd03d17a1 | [
"MIT"
] | null | null | null | C++/uri1029.cpp | AugustoDipNiloy/Uri-Solution | 7f455395bbbe55edce8d12afd80fa5ebd03d17a1 | [
"MIT"
] | 2 | 2020-07-29T09:33:29.000Z | 2020-08-02T08:44:36.000Z | #include <bits/stdc++.h>
using namespace std;
int con;
int fib(int a);
int main(void)
{
int T;
cin >> T;
for(int i = 0, n; i < T; i++){
cin >> n;
con = 0;
cout << "fib(" << n << ") = " << con - 1 << " calls = " << fib(n) << endl;
}
return 0;
}
int fib(int n)
{
con++;
if(n == 0 || n == 1)
return n;
return fib(n - 1) + fib(n - 2);
}
| 14.357143 | 82 | 0.402985 | AugustoDipNiloy |
dab2f11e80c12cdc3d524a37a4dd56f887843884 | 4,032 | hpp | C++ | src/interval_map.hpp | keijak/hikidashi-cpp | 63d01dfa1587fa56fd7f4e50712f7c10d8168520 | [
"Apache-2.0"
] | null | null | null | src/interval_map.hpp | keijak/hikidashi-cpp | 63d01dfa1587fa56fd7f4e50712f7c10d8168520 | [
"Apache-2.0"
] | null | null | null | src/interval_map.hpp | keijak/hikidashi-cpp | 63d01dfa1587fa56fd7f4e50712f7c10d8168520 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using Int = long long;
// Disjoint closed intervals [l, r] (mapping l to r).
class ClosedIntervalMap : public std::map<Int, Int> {
private:
// If true, automatically merges [l, c] and [c+1, r].
bool merge_adjacent;
public:
ClosedIntervalMap(bool merge_adjacent = true)
: merge_adjacent(merge_adjacent) {}
// Returns the interval [l, r] which contains p if available.
// Otherwise returns this->end().
std::map<Int, Int>::iterator find_interval(Int p) {
auto it = upper_bound(p);
if (it == begin() || (--it)->second < p) return end();
return it;
}
// Inserts interval [l, r]
void add_interval(Int l, Int r) {
auto itl = upper_bound(l), itr = upper_bound(r + merge_adjacent);
if (itl != begin()) {
if ((--itl)->second < l - merge_adjacent) ++itl;
}
if (itl != itr) {
l = std::min(l, itl->first);
r = std::max(r, std::prev(itr)->second);
for (auto it = itl; it != itr;) {
it = erase(it);
}
}
(*this)[l] = r;
}
// Removes interval [l, r]
void remove_interval(Int l, Int r) {
auto itl = upper_bound(l), itr = upper_bound(r);
if (itl != begin()) {
if ((--itl)->second < l) ++itl;
}
if (itl == itr) return;
Int tl = std::min(l, itl->first);
Int tr = std::max(r, std::prev(itr)->second);
for (auto it = itl; it != itr;) {
it = erase(it);
}
if (tl < l) {
(*this)[tl] = l - 1;
}
if (r < tr) {
(*this)[r + 1] = tr;
}
}
// Are p and q in the same interval?
bool same(Int p, Int q) {
const auto it = find_interval(p);
return it != end() and it->first <= q and q <= it->second;
}
// Minimum excluded value greater than or equal to X.
Int mex(int bottom = 0) {
const auto it = find_interval(bottom);
if (it == end()) return bottom;
return it->second + 1;
}
};
// Disjoint half-open intervals [l, r) (mapping l to r).
class IntervalMap : public std::map<Int, Int> {
private:
// If true, automatically merges [l, c) and [c, r).
bool merge_adjacent;
Int length_sum_;
public:
IntervalMap(bool merge_adjacent = true)
: merge_adjacent(merge_adjacent), length_sum_(0) {}
Int length_sum() const { return length_sum_; }
// Returns the interval [l, r) which contains p if available.
// Otherwise returns this->end().
std::map<Int, Int>::iterator find_interval(Int p) {
auto it = upper_bound(p);
if (it != begin()) {
--it;
if (it->second > p) return it;
}
return end();
}
// Inserts interval [l, r)
void add_interval(Int l, Int r) {
auto itl = upper_bound(l), itr = lower_bound(r + merge_adjacent);
if (itl != begin()) {
--itl;
if (itl->second <= l - merge_adjacent) ++itl;
}
if (itl != itr) {
l = std::min(l, itl->first);
r = std::max(r, std::prev(itr)->second);
for (auto it = itl; it != itr;) {
length_sum_ -= it->second - it->first;
it = erase(it);
}
}
(*this)[l] = r;
length_sum_ += r - l;
}
// Removes interval [l, r)
void remove_interval(Int l, Int r) {
auto itl = upper_bound(l), itr = lower_bound(r);
if (itl != begin()) {
--itl;
if (itl->second <= l) ++itl;
}
if (itl == itr) return;
Int tl = std::min(l, itl->first);
Int tr = std::max(r, std::prev(itr)->second);
for (auto it = itl; it != itr;) {
length_sum_ -= it->second - it->first;
it = erase(it);
}
if (tl < l) {
(*this)[tl] = l;
length_sum_ += l - tl;
}
if (r < tr) {
(*this)[r] = tr;
length_sum_ += tr - r;
}
}
// Are p and q in the same interval?
bool same(Int p, Int q) {
const auto it = find_interval(p);
return it != end() and it->first <= q and q < it->second;
}
// Minimum excluded value greater than or equal to X.
Int mex(int bottom = 0) {
const auto it = find_interval(bottom);
if (it == end()) return bottom;
return it->second;
}
};
| 26.352941 | 69 | 0.550843 | keijak |
dab9d5ff2f9ca6546d8201c8d97727d213f3169c | 825 | hpp | C++ | include/Factory/Factory.hpp | BourgeoisBenjamin/Epitech-ThePlazza | 493eb3227a200d39311956f46c9d8cecb3f5fc6e | [
"MIT"
] | null | null | null | include/Factory/Factory.hpp | BourgeoisBenjamin/Epitech-ThePlazza | 493eb3227a200d39311956f46c9d8cecb3f5fc6e | [
"MIT"
] | null | null | null | include/Factory/Factory.hpp | BourgeoisBenjamin/Epitech-ThePlazza | 493eb3227a200d39311956f46c9d8cecb3f5fc6e | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** CCP_plazza_2019
** File description:
** Factory
*/
#ifndef FACTORY_HPP_
#define FACTORY_HPP_
#include "Reception/Reception.hpp"
namespace Plazza
{
class Factory {
public:
// For socket
Factory(int arg1, int arg2, IIPC::IPCType type);
~Factory();
Factory(const Factory &factory) = default;
Factory &operator=(const Factory &factory) = default;
[[nodiscard]] std::shared_ptr<IIPC> createIPC() const;
private:
[[nodiscard]] std::shared_ptr<IIPC> createSocket() const;
[[nodiscard]] std::shared_ptr<IIPC> createPipe() const;
private:
IIPC::IPCType _type;
int _arg1;
int _arg2;
};
} // namespace Plazza
#endif /* !FACTORY_HPP_ */
| 23.571429 | 69 | 0.581818 | BourgeoisBenjamin |
dabbfd119933482d06cdc40add14499fb5f7796f | 2,365 | cpp | C++ | Client/pulseVehicles.cpp | WuskieFTW1113/IV-MP-T4 | ec4f193c90d23e07e6200dcb061ec8773be6bedc | [
"MIT"
] | 2 | 2021-07-18T17:37:32.000Z | 2021-08-04T12:33:51.000Z | Client/pulseVehicles.cpp | VittorioC97/IV-MP-T4 | ec4f193c90d23e07e6200dcb061ec8773be6bedc | [
"MIT"
] | 1 | 2022-02-22T03:26:50.000Z | 2022-02-22T03:26:50.000Z | Client/pulseVehicles.cpp | WuskieFTW1113/IV-MP-T4 | ec4f193c90d23e07e6200dcb061ec8773be6bedc | [
"MIT"
] | 5 | 2021-06-17T06:41:00.000Z | 2022-02-17T09:37:40.000Z | #include "NetworkManager.h"
#include "CustomFiberThread.h"
#include "vehicles.h"
#include "easylogging++.h"
#include "vehicleSync.h"
#include "../SharedDefines/packetsIds.h"
#include "dummyVehicles.h"
#include "removeVehicle.h"
void pulseVehicles(float x, float y, float z)
{
try
{
std::map<size_t, vehicles::netVehicle>::iterator i = vehicles::getVehiclesBegin();
int loopCount = 0;
long elap = clock();
subTask = 799;
dummyVehicles::pulse();
subTask = 700;
while(i != vehicles::getVehiclesEnd())
{
loopCount++;
if(loopCount > 120)
{
LINFO << "!Error: Pulse vehicles was stuck in a loop";
break;
}
subTask = 701;
vehicles::netVehicle& v = vehicles::getVehicle(i->first);
if(v.threadLock)
{
++i;
continue;
}
v.threadLock = true;
if(v.spawned && !Scripting::DoesVehicleExist(v.vehicle))
{
LINFO << "!Error: Vehicle " << i->first << " was spawned yet vehicle doesnt exist";
v.spawned = false;
v.threadLock = false;
++i;
continue;
}
subTask = 702;
if(v.spawned && v.toBeDeleted != 0)
{
//LINFO << "Deleting vehicle " << i->first;
Scripting::DeleteCar(&v.vehicle);
emptyVehicleOccupants(i->first, false);
if(v.toBeDeleted == 1)
{
RakNet::BitStream bsOut;
bsOut.Write((MessageID)IVMP);
bsOut.Write(CLIENT_DELETED_VEHICLE);
bsOut.Write(i->first);
networkManager::connection* con = networkManager::getConnection();
con->peer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, con->serverIp, false);
vehicles::removeVehicleByIterator(i++);
}
else
{
v.spawned = false;
v.canBeSpawned = true;
v.toBeDeleted = 0;
}
//LINFO << "Vehicle deleted";
}
else if(!v.spawned && v.canBeSpawned)
{
//LINFO << "Spawning vehicle: " << i->first;
if(SpawnCar(v))
{
RakNet::BitStream bsOut;
bsOut.Write((MessageID)IVMP);
bsOut.Write(CLIENT_SPAWNED_VEHICLE);
bsOut.Write(i->first);
networkManager::connection* con = networkManager::getConnection();
con->peer->Send(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, con->serverIp, false);
//LINFO << "Vehicle spawned";
}
}
v.threadLock = false;
v.spawnTime += 30;
subTask = 705;
++i;
}
}
catch(std::exception& e)
{
LINFO << "!Error (pulseVehicles): " << e.what();
}
} | 23.65 | 87 | 0.621564 | WuskieFTW1113 |
dac1564d6a65ffddfd7c0e273b9b5111d1afdae0 | 458 | cpp | C++ | test/test_json_parse.cpp | MMX-World/vnx-base | c806599e630e17928e8c2d9271e896797a069ba2 | [
"Apache-2.0"
] | null | null | null | test/test_json_parse.cpp | MMX-World/vnx-base | c806599e630e17928e8c2d9271e896797a069ba2 | [
"Apache-2.0"
] | 2 | 2022-02-07T05:19:09.000Z | 2022-03-24T18:44:37.000Z | test/test_json_parse.cpp | MMX-World/vnx-base | c806599e630e17928e8c2d9271e896797a069ba2 | [
"Apache-2.0"
] | 1 | 2022-01-22T21:30:26.000Z | 2022-01-22T21:30:26.000Z | /*
* test_json_parse.cpp
*
* Created on: May 26, 2021
* Author: mad
*/
#include <vnx/vnx.h>
int main(int argc, char** argv)
{
vnx::init("test_json_parse", argc, argv);
while(vnx::do_run())
{
vnx::Variant var;
try {
var = vnx::read(std::cin);
vnx::write(std::cout, var);
} catch(std::underflow_error& ex) {
break;
} catch(std::exception& ex) {
std::cerr << ex.what();
}
std::cout << std::endl;
}
vnx::close();
}
| 13.878788 | 42 | 0.565502 | MMX-World |
dac5106dd4cb46a1682096527138ec9c84a573b9 | 42,540 | cpp | C++ | WaveletTL/interval/pq_evaluate.cpp | kedingagnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 3 | 2018-05-20T15:25:58.000Z | 2021-01-19T18:46:48.000Z | WaveletTL/interval/pq_evaluate.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | null | null | null | WaveletTL/interval/pq_evaluate.cpp | agnumerikunimarburg/Marburg_Software_Library | fe53c3ae9db23fc3cb260a735b13a1c6d2329c17 | [
"MIT"
] | 2 | 2019-04-24T18:23:26.000Z | 2020-09-17T10:00:27.000Z | // implementation for pq_evaluate.h
#include <iostream>
#include <Rd/r_index.h>
#include <Rd/cdf_utils.h>
#include <utils/array1d.h>
#include <utils/tiny_tools.h>
#include <numerics/schoenberg_splines.h>
#include <interval/pq_frame.h>
namespace WaveletTL
{
template <int d, int dT>
SampledMapping<1>
evaluate(const PQFrame<d,dT>& basis,
const typename PQFrame<d,dT>::Index& lambda,
const bool primal,
const int resolution,
const int derivative)
{
if (lambda.e() == 0) { // generator
if (primal) {
Grid<1> grid(0, 1, 1<<resolution);
MathTL::Array1D<double> values((1<<resolution)+1);
for (unsigned int i(0); i < values.size(); i++)
values[i] = evaluate(basis, derivative, lambda, i*ldexp(1.0,-resolution));
return SampledMapping<1>(grid, values);
} else {
// dual
int s0 = basis.get_s0();
int s1 = basis.get_s1();
const Matrix<double>& CLAT = basis.get_CLAT();
// left boundary generator
if (lambda.k() < basis.DeltaLTmin()+(int)CLAT.column_dimension()) {
if (s0 >= d-2) {
InfiniteVector<double, RIndex> coeffs;
for (unsigned int i(0); i < CLAT.row_dimension(); i++) {
double v(CLAT(i, lambda.k()-basis.DeltaLTmin()));
if (v != 0)
coeffs.set_coefficient(RIndex(lambda.j(), 0, 1-ell2T<d,dT>()+i), v);
}
return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
}
else {
InfiniteVector<double, RIndex> coeffs;
for (unsigned int i(0); i < CLAT.row_dimension(); i++) {
double v(CLAT(i, lambda.k()-basis.DeltaLTmin()));
if (v != 0)
coeffs.set_coefficient(RIndex(lambda.j()+1, 0, 1-ell2T<d,dT>()+i), v);
}
return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
}
}
// no left boundary generator
else {
const Matrix<double>& CRAT = basis.get_CRAT();
if (lambda.k() > basis.DeltaRTmax(lambda.j())-(int)CRAT.column_dimension()) {
if (s1 >= d-2) {
// right boundary generator
InfiniteVector<double, RIndex> coeffs;
for (unsigned int i(0); i < CRAT.row_dimension(); i++) {
double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k()));
if (v != 0)
coeffs.set_coefficient(RIndex(lambda.j(), 0, (1<<lambda.j())-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v);
}
return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
}
else {
InfiniteVector<double, RIndex> coeffs;
for (unsigned int i(0); i < CRAT.row_dimension(); i++) {
double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k()));
if (v != 0)
coeffs.set_coefficient(RIndex(lambda.j()+1, 0, (1<<(lambda.j()+1))-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v);
}
return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
}
}
// inner generator
else {
return basis.get_CDF_basis().evaluate(0, RIndex(lambda.j(), 0, lambda.k()),
primal, 0, 1, resolution);
}
}
}
}
else { // wavelet
InfiniteVector<double, typename PQFrame<d,dT>::Index> gcoeffs;
if (primal)
basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
else
basis.reconstruct_t_1(lambda, lambda.j()+1, gcoeffs);
return evaluate(basis, gcoeffs, primal, resolution);
}
return SampledMapping<1>(); // dummy return for the compiler
}
template <int d, int dT>
SampledMapping<1>
evaluate(const PQFrame<d,dT>& basis,
const InfiniteVector<double, typename PQFrame<d,dT>::Index>& coeffs,
const bool primal,
const int resolution,
const int derivative)
{
SampledMapping<1> result(Grid<1>(0, 1, 1<<resolution)); // zero
if (coeffs.size() > 0) {
// determine maximal level and maximal polynomial degree
int jmax(0);
int pmax(0);
typedef typename PQFrame<d,dT>::Index Index;
for (typename InfiniteVector<double,Index>::const_iterator it(coeffs.begin()),
itend(coeffs.end()); it != itend; ++it){
jmax = std::max(it.index().j()+it.index().e(), jmax);
pmax = std::max(it.index().p(), pmax);
}
// cout << "jmax: " << jmax << endl;
// cout << "pmax: " << pmax << endl;
InfiniteVector<double,Index> gcoeffs;
if(false){
// switch to generator representation
if (primal)
basis.reconstruct(coeffs,jmax,gcoeffs);
else
basis.reconstruct_t(coeffs,jmax,gcoeffs);
}
else
/*generator representation does not work for quarks, so we keep the indices and
* apply the generator representation only for the quarklets in the
* Sampled Mapping evaluate routine for single indices.*/
gcoeffs=coeffs;
// cout << "Generator coeffs: " << endl << gcoeffs << endl;
for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()),
itend(gcoeffs.end()); it != itend; ++it)
result.add(*it, evaluate(basis, it.index(), primal, resolution, derivative));
}
return result;
}
#include <iostream>
#include "pq_frame.h"
template <int d, int dT>
double evaluate(const PQFrame<d,dT>& basis, const unsigned int derivative,
const typename PQFrame<d,dT>::Index& lambda,
const double x)
{
assert(derivative <= 1); // we only support derivatives up to the second order
double r = 0;
// basis.DeltaLmin();
const double pfkt = d/2.;
// const double pfkt = d/2.;
// const int dhalfsmall = d/2;
const double pfktrez = 1./pfkt;
const double y = (1<<lambda.j())*x-lambda.k()-((d % 2 == 0)? 0 : 0.5);
// double y;
// if(d%2==0)
// y = (1<<lambda.j())*x-lambda.k();
// else
// y = (1<<lambda.j())*x-0.5-lambda.k();
// const int lefthelper = lambda.k()+pfkt-1;
// const int righthelper = (1<<lambda.j())+dhalfsmall -lambda.k();
// basis.DeltaLmin();//Den braucht man hier
// const double leftside = (lambda.k()-basis.DeltaLmin()+1)/2.;//corresponds to (k+m)/2 in Diss Keding P.73
const double leftside = 1./(lambda.k()-basis.DeltaLmin()+1);//corresponds to (k+m) in Diss Keding P.73
// const double leftside = 1./(pfkt+lambda.k());
const double rightside = 1./(basis.DeltaRmax(lambda.j())-lambda.k()+1);
// const double rightside = 1./righthelper;
//cout << boundsupplength;
if (lambda.e() == 0) {
// generator
if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) {//right boundary quarks
switch (derivative){
case 0: r=(lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x)
: MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), (1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-x)
* mypow((1<<lambda.j())*(1-x)*rightside, lambda.p()));
break;
case 1: r=(lambda.p()==0 ? -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1-x)
: -MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1-x)
* lambda.p()*(1<<lambda.j())*rightside*mypow((1<<lambda.j())*(1-x)*rightside, lambda.p()-1)
- MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1-x)
* mypow((1<<lambda.j())*(1-x)*rightside,lambda.p()));
break;
// case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
// (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
// 1-x);
// break;
}
}
else if (lambda.k() < -ell1<d>()){//left boundary quarks
switch (derivative){
case 0: r=(lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), x)
: MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), x)
* mypow((1<<lambda.j())*x*leftside, lambda.p()));
// *mypow(((1<<lambda.j())*x-leftside)/leftside, lambda.p()));
break;
case 1: r=(lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d> (lambda.j(), lambda.k(), x)
: MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), x)
* lambda.p()*(1<<lambda.j())*leftside *mypow((1<<lambda.j())*x*leftside,lambda.p()-1)
+ MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),lambda.k(),x)*mypow((1<<lambda.j())*x*leftside,lambda.p()));
break;
// case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), x);
// break;
}
}
else{//inner quarks
switch (derivative){
case 0: r=(lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), x)
: MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), x)
* mypow(y*pfktrez,lambda.p()));
break;
case 1: r=(lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), x)
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), x)
* mypow(y*pfktrez ,lambda.p())
+ MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), lambda.k(), x)
* lambda.p()*mypow(y*pfktrez ,lambda.p()-1)*(1<<lambda.j())*pfktrez);
break;
// case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), x);
// break;
}
}
}
//
else {
// wavelet
InfiniteVector<double,int> gcoeffs;
basis.reconstruct_1(lambda.p(), lambda.j(), lambda.e(), lambda.k(), lambda.j()+1, gcoeffs);
const int Lmin(basis.DeltaLmin());
for (typename InfiniteVector<double,int>::const_iterator it(gcoeffs.begin());
it != gcoeffs.end(); ++it)
{
// gcoeffs contains only coeffs related to generators on level j+1
// j_ = j+1; e_ = 0; k_ = DeltaLmin() + num
r += *it * evaluate(basis, derivative, lambda.p(), lambda.j()+1,0,Lmin+it.index(), x);
//cout << "Stelle: " << it.index() << " Wert: " << evaluate(basis, derivative, lambda.p(), lambda.j()+1,0,Lmin+it.index(), x) << endl;
}
}
return r;
}
template <int d, int dT>
double evaluate(const PQFrame<d,dT>& basis, const unsigned int derivative,
const int p, const int j, const int e, const int k,
const double x)
{
assert(derivative <= 1); // we only support derivatives up to the first order
double r = 0;
if (e == 0) {
// generator
const double pfkt = d/2.;
// const double pfkt = d/2.;
// const int dhalfsmall = d/2;
const double pfktrez = 1./pfkt;
const double y = (1<<j)*x-k-((d % 2 == 0)? 0 : 0.5);
// double y;
// if(d%2==0)
// y = (1<<j)*x-k;
// else
// y = (1<<j)*x-0.5-k;
// const int lefthelper = k+pfkt-1;
// const int righthelper = (1<<j)+dhalfsmall -k;
// const double leftside = 1./(pfkt+k);
const double leftside = 1./(k-basis.DeltaLmin()+1);
const double rightside = 1./(basis.DeltaRmax(j)-k+1);
if (k > (1<<j)-ell1<d>()-d) { //right boundary quarks
switch (derivative){
case 0: r=(p==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(j,(1<<j)-d-k-2*ell1<d>(),1-x)
: MathTL::EvaluateSchoenbergBSpline_td<d>(j,(1<<j)-d-k-2*ell1<d>(),1-x)*mypow((1<<j)*(1-x)*rightside, p));
//cout << "Fall 1" << endl;
break;
case 1: r=(p==0 ? -MathTL::EvaluateSchoenbergBSpline_td_x<d>(j,(1<<j)-d-k-2*ell1<d>(),1-x)
: -MathTL::EvaluateSchoenbergBSpline_td_x<d>(j,(1<<j)-d-k-2*ell1<d>(),1-x)*mypow((1<<j)*(1-x)*rightside, p)
-MathTL::EvaluateSchoenbergBSpline_td<d>(j,(1<<j)-d-k-2*ell1<d>(),1-x)*p*mypow((1<<j)*(1-x)*rightside, p-1)*(1<<j)*rightside);
break;
// case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(j,(1<<j)-d-k-2*ell1<d>(),1-x);
// break;
}
}
else if (k < -ell1<d>()){ //left boundary quarks
switch (derivative){
case 0: r=(p==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(j, k, x)
: MathTL::EvaluateSchoenbergBSpline_td<d>(j, k, x)*mypow(((1<<j)*x)*leftside, p));
//cout << "Fall 2" << endl;
break;
case 1: r=(p==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(j, k, x)
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(j, k, x)*mypow((1<<j)*x*leftside, p)
+ MathTL::EvaluateSchoenbergBSpline_td<d>(j, k, x)*p*mypow((1<<j)*x*leftside, p-1)*(1<<j)*leftside);
break;
// case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(j, k, x);
// break;
}
}
else {//inner quarks
switch (derivative){
case 0: r=(p==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(j, k, x)
: MathTL::EvaluateSchoenbergBSpline_td<d>(j, k, x)*mypow(y*pfktrez ,p));
//cout << "Fall 3" << endl;
break;
case 1: r=(p==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(j, k, x)
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(j, k, x)*mypow(y*pfktrez ,p)
+ MathTL::EvaluateSchoenbergBSpline_td<d>(j, k, x)*p*mypow(y*pfktrez ,p-1)*(1<<j)*pfktrez);
break;
//case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(j, k, x);
//break;
}
}
} else {
// wavelet
InfiniteVector<double,int> gcoeffs;
basis.reconstruct_1(p,j,e,k, j+1, gcoeffs);
const int Lmin(basis.DeltaLmin());
for (typename InfiniteVector<double,int>::const_iterator it(gcoeffs.begin());
it != gcoeffs.end(); ++it)
{
// gcoeffs contains only coeffs related to generators on level j+1
// j_ = j+1; e_ = 0; k_ = DeltaLmin() + num
r += *it * evaluate(basis, derivative, p,j+1,0,Lmin+it.index(), x);
}
}
//r += *it * evaluate(basis, derivative, it.index(), x);
return r;
}
template <int d, int dT>
Piecewise<double> expandAsPP(const PQFrame<d,dT>& basis, const typename PQFrame<d,dT>::Index& lambda)
{
assert(d <= 4); // we only support orders less then 4
Piecewise<double> r;
Polynomial<double> q;
if (lambda.e() == 0) {
// generator
if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) {
Polynomial<double> p; // p(x) = 1-x
p.set_coefficient(0, 1.0);
p.set_coefficient(1, -1.0);
r= MathTL::ExpandSchoenbergBspline<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1);
}
else {
r=MathTL::ExpandSchoenbergBspline<d> (lambda.j(), lambda.k(),0);
}
}
else {
// wavelet
typedef typename PQFrame<d,dT>::Index Index;
InfiniteVector<double,Index> gcoeffs;
basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin());
it != gcoeffs.end(); ++it)
r += *it * expandAsPP(basis, it.index());
}
return r;
}
template <int d, int dT>
void
evaluate(const PQFrame<d,dT>& basis, const unsigned int derivative,
const typename PQFrame<d,dT>::Index& lambda,
const Array1D<double>& points, Array1D<double>& values)
{
assert(derivative <= 1); // we only support derivatives up to the first order
values.resize(points.size());
for (unsigned int i(0); i < values.size(); i++)
values[i] = 0;
if (lambda.e() == 0)
{
// generator
const double pfkt = d/2.;
// const double pfkt = d/2.;
// const int dhalfsmall = d/2;
const double pfktrez = 1./pfkt;
// const int righthelper = (1<<lambda.j())+dhalfsmall -lambda.k();
// const double leftside = 1./(pfkt+lambda.k());
const double leftside = 1./(lambda.k()-basis.DeltaLmin()+1);
const double rightside = 1./(basis.DeltaRmax(lambda.j())-lambda.k()+1);
// double trans(0);
// if(d%2==1)
// trans=0.5;
if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) //right boundary quarks, only implemented for case 0
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++)
values[m] =(lambda.p()==0 ?MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m])
:MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m])
* mypow((1<<lambda.j())*(1-points[m])*rightside, lambda.p()));
break;
case 1:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (lambda.p()==0 ?-MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1-points[m])
:-MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1-points[m])
* mypow((1<<lambda.j())*(1-points[m])*rightside, lambda.p())
- MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m])
* lambda.p()*mypow((1<<lambda.j())*(1-points[m])*rightside, lambda.p()-1)*(1<<lambda.j())*rightside);
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++)
// values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
// (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
// 1-points[m]);
// break;
}
else if(lambda.k() < -ell1<d>()) //left boundary quarks,
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (lambda.p()==0 ?MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), lambda.k(), points[m])
:MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), lambda.k(), points[m])
*mypow(((1<<lambda.j())*points[m])*leftside, lambda.p()));
break;
case 1:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m])
* mypow((1<<lambda.j())*points[m]*leftside, lambda.p())
+ MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(), lambda.k(), points[m])
* lambda.p()*mypow((1<<lambda.j())*points[m]*leftside, lambda.p()-1)*(1<<lambda.j())*leftside);
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++)
// values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
// lambda.k(),
// points[m]);
}
else //inner quarks
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++)
values[m] =(lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),lambda.k(), points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),lambda.k(), points[m])
* mypow(((1<<lambda.j())*points[m]-lambda.k()-((d % 2 == 0)? 0 : 0.5))*pfktrez,lambda.p()));
break;
case 1:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), points[m])
* mypow(((1<<lambda.j())*points[m]-lambda.k()-((d % 2 == 0)? 0 : 0.5))*pfktrez,lambda.p())
+ MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),lambda.k(), points[m])
* lambda.p()*mypow(((1<<lambda.j())*points[m]-lambda.k()-((d % 2 == 0)? 0 : 0.5))*pfktrez,lambda.p()-1)*(1<<lambda.j())*pfktrez);
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++)
// values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
// lambda.k(), points[m]);
// break;
}
}
else // wavelet
{
if(basis.get_evaluate_with_pre_computation()){ // with pre compuatation
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++){
values[m] = basis.wavelets[lambda.j()][lambda.k()](points[m]);
}
break;
case 1:
for (unsigned int m(0); m < points.size(); m++){
values[m] = basis.wavelets[lambda.j()][lambda.k()].derivative(points[m]);
}
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++){
// values[m] = basis.wavelets[lambda.j()][lambda.k()].secondDerivative(points[m]);
// }
// break;
}
}
else // not with pre computation
{
InfiniteVector<double,int> gcoeffs;
basis.reconstruct_1(lambda.p(), lambda.j(),lambda.e(), lambda.k(), lambda.j()+1, gcoeffs);
const int Lmin(basis.DeltaLmin());
Array1D<double> help(points.size());
for (typename InfiniteVector<double,int>::const_iterator it(gcoeffs.begin());
it != gcoeffs.end(); ++it)
{
evaluate(basis, derivative, lambda.p(), lambda.j()+1, 0, Lmin+it.index(), points, help);
for (unsigned int i = 0; i < points.size(); i++)
values[i] += *it * help[i];
}
}
}
}
template <int d, int dT>
void evaluate(const PQFrame<d,dT>& basis, const unsigned int derivative,
const int p_, const int j_, const int e_, const int k_,
const Array1D<double>& points, Array1D<double>& values)
{
assert(derivative <= 1); // we only support derivatives up to the first order
values.resize(points.size());
for (unsigned int i(0); i < values.size(); i++)
values[i] = 0;
if (e_ == 0)
{
// generator
const double pfkt = d/2.;
// const double pfkt = d/2.;
// const int dhalfsmall = d/2;
const double pfktrez = 1./pfkt;
// const int lefthelper = k_+pfkt-1;
// const int righthelper = (1<<j_)+dhalfsmall -k_;
// const double leftside = 1./(pfkt+k_);
const double leftside = 1./(k_-basis.DeltaLmin()+1);
const double rightside = 1./(basis.DeltaRmax(j_)-k_+1);;
// double trans(0);
// if(d%2==1)
// trans=0.5;
if (k_ > (1<<j_)-ell1<d>()-d)//right boundary quarks
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(j_,(1<<j_)-d-k_-2*ell1<d>(),1-points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d>(j_,(1<<j_)-d-k_-2*ell1<d>(),1-points[m])*mypow((1<<j_)*(1-points[m])*rightside, p_));
break;
case 1:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (p_==0 ?-MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,(1<<j_)-d-k_-2*ell1<d>(),1-points[m])
:-MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,(1<<j_)-d-k_-2*ell1<d>(),1-points[m])*mypow((1<<j_)*(1-points[m])*rightside, p_)
- MathTL::EvaluateSchoenbergBSpline_td<d>(j_,(1<<j_)-d-k_-2*ell1<d>(),1-points[m])
* p_*mypow((1<<j_)*(1-points[m])*rightside, p_-1)*(1<<j_)*rightside);
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++)
// values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(j_,
// (1<<j_)-d-k_-2*ell1<d>(),
// 1-points[m]);
// break;
}
else if(k_ < -ell1<d>())//left boundary quarks
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++){
values[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(j_, k_, points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d>(j_, k_, points[m])*mypow(((1<<j_)*points[m])*leftside, p_));
}
break;
case 1:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_, k_, points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_, k_, points[m])
* mypow((1<<j_)*points[m]*leftside, p_)
+ MathTL::EvaluateSchoenbergBSpline_td<d>(j_, k_, points[m])
* p_*mypow((1<<j_)*points[m]*leftside, p_-1)*(1<<j_)*leftside);
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++)
// values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(j_,
// k_,
// points[m]);
// break;
}
else //inner quarks
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(j_, k_, points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d>(j_, k_, points[m])*mypow(((1<<j_)*points[m]-k_-((d % 2 == 0)? 0 : 0.5))*pfktrez,p_));
break;
case 1:
for (unsigned int m(0); m < points.size(); m++)
values[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_, k_, points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_, k_, points[m])
* mypow(((1<<j_)*points[m]-k_-((d % 2 == 0)? 0 : 0.5))*pfktrez,p_)
+ MathTL::EvaluateSchoenbergBSpline_td<d>(j_, k_, points[m])
* p_*mypow(((1<<j_)*points[m]-k_-((d % 2 == 0)? 0 : 0.5))*pfktrez,p_-1)*(1<<j_)*pfktrez);
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++)
// values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(j_,
// k_,
// points[m]);
// break;
}
}
else // wavelet
{
if(basis.get_evaluate_with_pre_computation()){ // with pre compuatation
switch (derivative) {
case 0:
for (unsigned int m(0); m < points.size(); m++){
values[m] = basis.wavelets[j_][k_](points[m]);
}
break;
case 1:
for (unsigned int m(0); m < points.size(); m++){
values[m] = basis.wavelets[j_][k_].derivative(points[m]);
}
break;
// case 2:
// for (unsigned int m(0); m < points.size(); m++){
// values[m] = basis.wavelets[j_][k_].secondDerivative(points[m]);
// }
// break;
}
}
else // not with pre computation
{
InfiniteVector<double,int> gcoeffs;
basis.reconstruct_1(p_, j_,e_,k_, j_+1, gcoeffs);
const int Lmin(basis.DeltaLmin());
Array1D<double> help;
for (typename InfiniteVector<double,int>::const_iterator it(gcoeffs.begin());
it != gcoeffs.end(); ++it)
{
evaluate(basis, derivative, p_, j_+1,0,Lmin+it.index(), points, help);
for (unsigned int i = 0; i < points.size(); i++)
values[i] += *it * help[i];
}
}
}
}
template <int d, int dT>
void evaluate(const PQFrame<d,dT>& basis,
const typename PQFrame<d,dT>::Index& lambda,
const Array1D<double>& points, Array1D<double>& funcvalues, Array1D<double>& dervalues)
{
const unsigned int npoints(points.size());
funcvalues.resize(npoints);
dervalues.resize(npoints);
//basis.setWavelets();
if (lambda.e() == 0) {
// generator
const double pfkt = d/2.;
// const double pfkt = d/2.;
// const int dhalfsmall = d/2;
const double pfktrez = 1./pfkt;
// const int lefthelper = lambda.k()+pfkt-1;
// const int righthelper = (1<<lambda.j())+dhalfsmall -lambda.k();
const double leftside = 1./(lambda.k()-basis.DeltaLmin()+1);
// const double leftside = 1./(pfkt+lambda.k());
const double rightside = 1./(basis.DeltaRmax(lambda.j())-lambda.k()+1);
// double trans(0);
// if(d%2==1)
// trans=0.5;
if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) {//right boundary quarks
for (unsigned int m(0); m < npoints; m++) {
funcvalues[m] = (lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m])
*mypow((1<<lambda.j())*(1-points[m])*rightside, lambda.p()));
dervalues[m] = (lambda.p()==0 ? -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1-points[m])
: -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),1-points[m])
* mypow((1<<lambda.j())*(1-points[m])*rightside, lambda.p())
- MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(),(1<<lambda.j())-d-lambda.k()-2*ell1<d>(), 1-points[m])
* lambda.p()*mypow((1<<lambda.j())*(1-points[m])*rightside, lambda.p()-1)*(1<<lambda.j())*rightside);
}
}
else if(lambda.k() < -ell1<d>()){//left boundary quarks
for (unsigned int m(0); m < npoints; m++) {
funcvalues[m] = (lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), points[m])
:MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), points[m])
*mypow(((1<<lambda.j())*points[m])*leftside, lambda.p()));
dervalues[m] = (lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),lambda.k(),points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),lambda.k(),points[m])
* mypow((1<<lambda.j())*points[m]*leftside, lambda.p())
+ MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), points[m])
* lambda.p()*mypow((1<<lambda.j())*points[m]*leftside, lambda.p()-1)*(1<<lambda.j())*leftside);
}
}
else {//inner quarks
for (unsigned int m(0); m < npoints; m++) {
funcvalues[m] = (lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(), lambda.k(), points[m])
*mypow(((1<<lambda.j())*points[m]-lambda.k()-((d % 2 == 0)? 0 : 0.5))*pfktrez,lambda.p()));
dervalues[m] = (lambda.p()==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),lambda.k(),points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),lambda.k(),points[m])
* mypow(((1<<lambda.j())*points[m]-lambda.k()-((d % 2 == 0)? 0 : 0.5))*pfktrez,lambda.p())
+ MathTL::EvaluateSchoenbergBSpline_td<d> (lambda.j(),lambda.k(), points[m])
* lambda.p()*mypow(((1<<lambda.j())*points[m]-lambda.k()-((d % 2 == 0)? 0 : 0.5))*pfktrez,lambda.p()-1)*(1<<lambda.j())*pfktrez);
}
}
}
else {
// wavelet
if(basis.get_evaluate_with_pre_computation()) { // with pre compuatation
for (unsigned int m(0); m < npoints; m++){
funcvalues[m] = basis.wavelets[lambda.j()][lambda.k()](points[m]);
dervalues[m] = basis.wavelets[lambda.j()][lambda.k()].derivative(points[m]);
}
}
else { //without pre computation
for (unsigned int i(0); i < npoints; i++) {
funcvalues[i] = 0;
dervalues[i] = 0;
}
// wavelet
InfiniteVector<double,int> gcoeffs;
basis.reconstruct_1(lambda.p(), lambda.j(), lambda.e(), lambda.k(), lambda.j()+1, gcoeffs);
const int Lmin(basis.DeltaLmin());
Array1D<double> help1, help2;
for (typename InfiniteVector<double,int>::const_iterator it(gcoeffs.begin());
it != gcoeffs.end(); ++it)
{
evaluate(basis, lambda.p(), lambda.j()+1,0,Lmin+it.index(), points, help1, help2);
for (unsigned int i = 0; i < points.size(); i++) {
funcvalues[i] += *it * help1[i];
dervalues[i] += *it * help2[i];
}
}
}
}
}
template <int d, int dT>
void evaluate(const PQFrame<d,dT>& basis,
const int p_, const int j_, const int e_, const int k_,
const Array1D<double>& points, Array1D<double>& funcvalues, Array1D<double>& dervalues)
{
const unsigned int npoints(points.size());
funcvalues.resize(npoints);
dervalues.resize(npoints);
//basis.setWavelets();
if (e_ == 0) {
// generator
const double pfkt = d/2.;
// const double pfkt = d/2.;
// const int dhalfsmall = d/2;
const double pfktrez = 1./pfkt;
// const int lefthelper = k_+pfkt-1;
// const int righthelper = (1<<j_)+dhalfsmall -k_;
// const double leftside = 1./(pfkt+k_);
const double leftside = 1./(k_-basis.DeltaLmin()+1);
const double rightside = 1./(basis.DeltaRmax(j_)-k_+1);
// double trans(0);
// if(d%2==1)
// trans=0.5;
if (k_ > (1<<j_)-ell1<d>()-d) {//right boundary quarks, not implemented for dervalues
for (unsigned int m(0); m < npoints; m++) {
funcvalues[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td<d> (j_,(1<<j_)-d-k_-2*ell1<d>(), 1-points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d> (j_,(1<<j_)-d-k_-2*ell1<d>(), 1-points[m])
* mypow((1<<j_)*(1-points[m])*rightside, p_));
dervalues[m] = (p_==0 ?-MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,(1<<j_)-d-k_-2*ell1<d>(), 1-points[m])
:-MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,(1<<j_)-d-k_-2*ell1<d>(), 1-points[m])
* mypow((1<<j_)*(1-points[m])*rightside, p_)
- MathTL::EvaluateSchoenbergBSpline_td<d> (j_,(1<<j_)-d-k_-2*ell1<d>(), 1-points[m])
* p_*mypow((1<<j_)*(1-points[m])*rightside, p_-1)*(1<<j_)*rightside);
}
}
else if(k_ < -ell1<d>()){//left boundary quarks
for (unsigned int m(0); m < npoints; m++) {
funcvalues[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td<d> (j_,k_, points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d> (j_,k_, points[m]) *mypow(((1<<j_)*points[m])*leftside, p_));
dervalues[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,k_,points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,k_,points[m])*mypow((1<<j_)*points[m]*leftside, p_)
+ MathTL::EvaluateSchoenbergBSpline_td<d> (j_,k_, points[m])
* p_*mypow((1<<j_)*points[m]*leftside, p_-1)*(1<<j_)*leftside);
}
}
else {//inner quarks
for (unsigned int m(0); m < npoints; m++) {
funcvalues[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td<d>(j_,k_,points[m])
: MathTL::EvaluateSchoenbergBSpline_td<d>(j_,k_,points[m])*mypow(((1<<j_)*points[m]-k_-((d % 2 == 0)? 0 : 0.5))*pfktrez,p_));
dervalues[m] = (p_==0 ? MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,k_,points[m])
: MathTL::EvaluateSchoenbergBSpline_td_x<d>(j_,k_,points[m])
* mypow(((1<<j_)*points[m]-k_-((d % 2 == 0)? 0 : 0.5))*pfktrez,p_)
+ MathTL::EvaluateSchoenbergBSpline_td<d>(j_,k_,points[m])
* p_*mypow(((1<<j_)*points[m]-k_-((d % 2 == 0)? 0 : 0.5))*pfktrez,p_-1)*(1<<j_)*pfktrez);
}
}
}
else {
// wavelet
if(basis.get_evaluate_with_pre_computation()) { // with pre compuatation
for (unsigned int m(0); m < npoints; m++){
funcvalues[m] = basis.wavelets[j_][k_](points[m]);
dervalues[m] = basis.wavelets[j_][k_].derivative(points[m]);
}
}
else { //without pre computation
for (unsigned int i(0); i < npoints; i++) {
funcvalues[i] = 0;
dervalues[i] = 0;
}
InfiniteVector<double,int> gcoeffs;
basis.reconstruct_1(p_, j_, e_, k_, j_+1, gcoeffs);
const int Lmin(basis.DeltaLmin());
Array1D<double> help1, help2;
for (typename InfiniteVector<double,int>::const_iterator it(gcoeffs.begin());
it != gcoeffs.end(); ++it)
{
evaluate(basis, p_, j_+1,0,Lmin+it.index(), points, help1, help2);
for (unsigned int i = 0; i < points.size(); i++) {
funcvalues[i] += *it * help1[i];
dervalues[i] += *it * help2[i];
}
}
}
}
}
}
| 50.763723 | 185 | 0.473249 | kedingagnumerikunimarburg |
dacbacc07dbccf978febc29d4f58d1d0538ec96b | 1,051 | cc | C++ | src/v8capi.cc | mraleph/node-llvm | 4cf3a16ca5d228bce3627f9631ae39bd79948eff | [
"Apache-2.0"
] | 2 | 2015-04-02T02:07:41.000Z | 2015-05-02T17:41:17.000Z | src/v8capi.cc | mraleph/node-llvm | 4cf3a16ca5d228bce3627f9631ae39bd79948eff | [
"Apache-2.0"
] | null | null | null | src/v8capi.cc | mraleph/node-llvm | 4cf3a16ca5d228bce3627f9631ae39bd79948eff | [
"Apache-2.0"
] | null | null | null | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node.h>
#define V8CAPI extern "C"
#define ARGS(v) reinterpret_cast<v8::Arguments*>(v)
V8CAPI int v8capi_argc(void* p) {
return ARGS(p)->Length();
}
V8CAPI void* v8capi_arg(void* p, uint32_t idx) {
v8::Handle<v8::Value> arg = (*ARGS(p))[idx];
return reinterpret_cast<void*>(*arg);
}
V8CAPI void* v8capi_new_number(double val) {
v8::Handle<v8::Value> arg = v8::Number::New(val);
return reinterpret_cast<void*>(*arg);
}
| 31.848485 | 75 | 0.718363 | mraleph |
dacc543d24cfe7f8ce327e5ffa1812e89c4c24e8 | 2,877 | cpp | C++ | src/objects/world/island.cpp | gersrobert/ppgso-project | 92748d3536acc635ad49cbdbdc38dc373ece7273 | [
"MIT"
] | null | null | null | src/objects/world/island.cpp | gersrobert/ppgso-project | 92748d3536acc635ad49cbdbdc38dc373ece7273 | [
"MIT"
] | null | null | null | src/objects/world/island.cpp | gersrobert/ppgso-project | 92748d3536acc635ad49cbdbdc38dc373ece7273 | [
"MIT"
] | null | null | null | #include <src/util/bezier.h>
#include <cmake-build-debug/shaders/texture_vert_glsl.h>
#include <cmake-build-debug/shaders/texture_frag_glsl.h>
#include <cmake-build-debug/shaders/diffuse_vert_glsl.h>
#include <cmake-build-debug/shaders/diffuse_frag_glsl.h>
#include <cmake-build-debug/shaders/volumetric_cloud_frag_glsl.h>
#include <src/scene/scenes/game_scene.h>
#include "island.h"
#include "src/scene/scene.h"
#include "tree.h"
#include "lighthouse.h"
std::unique_ptr<ppgso::Mesh> Island::mesh;
std::unique_ptr<ppgso::Texture> Island::texture;
std::unique_ptr<ppgso::Shader> Island::shader;
Island::Island(Scene &scene, Chunk &chunk) : chunk(chunk) {
if (!shader) {
ppgso::ShaderConfig shaderConfig;
shaderConfig.vs = diffuse_vert_glsl;
shaderConfig.fs = diffuse_frag_glsl;
shader = std::make_unique<ppgso::Shader>(shaderConfig);
}
if (!texture) texture = std::make_unique<ppgso::Texture>(ppgso::image::loadBMP("island_1.bmp"));
if (!mesh) mesh = std::make_unique<ppgso::Mesh>("island_1.obj");
meshIndex = glm::linearRand((uint32_t) 0, (uint32_t) 2);
textureIndex = glm::linearRand((uint32_t) 0, (uint32_t) 2);
position = {
glm::linearRand(
-chunk.size + chunk.size * chunk.position.x * 1.8f,
chunk.size + chunk.size * chunk.position.x * 1.8f),
-1.0f,
glm::linearRand(
-chunk.size + chunk.size * chunk.position.y * 1.8f,
chunk.size + chunk.size * chunk.position.y * 1.8f)
};
scale *= 100;
rotation.z = glm::linearRand(0.0f, ppgso::PI * 2);
auto treeCount = static_cast<uint32_t>(glm::linearRand(0, 4));
if (treeCount == 0) {
treeCount = 0;
} else if (treeCount == 4) {
treeCount = 2;
} else {
treeCount = 1;
}
for (size_t i = 0; i < treeCount; ++i) {
auto tree = std::make_unique<Tree>(scene, chunk, *this);
scene.objects.push_back(move(tree));
}
}
bool Island::update(Scene &scene, float dt) {
generateModelMatrix();
return chunk.isActive;
}
void Island::render(Scene &scene) {
shader->use();
auto gameScene = dynamic_cast<GameScene*>(&scene);
// Set up light
shader->setUniform("LightDirection", gameScene->lightDirection);
shader->setUniform("lightColor", gameScene->lightColor);
// use camera
shader->setUniform("ProjectionMatrix", gameScene->camera->projectionMatrix);
shader->setUniform("ViewMatrix", gameScene->camera->viewMatrix);
// render mesh
shader->setUniform("ModelMatrix", modelMatrix);
shader->setUniform("Texture", *texture);
shader->setUniform("Transparency", 1.0f);
shader->setUniform("CameraPosition", gameScene->camera->getTotalPosition());
shader->setUniform("viewDistance", gameScene->VISIBILITY);
mesh->render();
} | 35.085366 | 100 | 0.649983 | gersrobert |
dad31754de4131db6ce68f4a25a1c292277812ce | 2,946 | cpp | C++ | tests/catch_timer_manager.cpp | cracked-machine/embedded_utils | 1c82938f66397d709cfbfc8c5b5da3b580b544aa | [
"MIT"
] | null | null | null | tests/catch_timer_manager.cpp | cracked-machine/embedded_utils | 1c82938f66397d709cfbfc8c5b5da3b580b544aa | [
"MIT"
] | 6 | 2022-01-08T13:08:57.000Z | 2022-03-12T15:50:02.000Z | tests/catch_timer_manager.cpp | cracked-machine/embedded_utils | 1c82938f66397d709cfbfc8c5b5da3b580b544aa | [
"MIT"
] | null | null | null | #include <catch2/catch_all.hpp>
#include <timer_manager.hpp>
#include <mock.hpp>
TEST_CASE("Timer Manager - microsecond timer: Null Input", "[timer_manager]")
{
std::cout << "timer_manager - microsecond timer: Null Input" << std::endl;
SECTION("Null Input")
{
TIM_TypeDef *null_timer = nullptr;
REQUIRE_FALSE(stm32::TimerManager::initialise(null_timer));
REQUIRE_FALSE(stm32::TimerManager::delay_microsecond(10));
}
}
/// @brief Non-threaded tests
TEST_CASE("Timer Manager - Init and Reset", "[timer_manager]")
{
std::cout << "timer_manager - init and reset" << std::endl;
// 1. Invalid input check
TIM_TypeDef *null_ptr = nullptr;
REQUIRE_FALSE(stm32::TimerManager::initialise(null_ptr));
// 2. Initialise once
TIM_TypeDef *timer1 = new TIM_TypeDef;
REQUIRE(stm32::TimerManager::initialise(timer1));
// 3. Re-initialise
TIM_TypeDef *timer2 = new TIM_TypeDef;
REQUIRE(stm32::TimerManager::initialise(timer2));
// 4. Register value check
// Timer should be set for 1 microsecond resolution and reset
REQUIRE(timer2->PSC == 64);
REQUIRE(timer2->ARR == 65534);
REQUIRE(timer2->CNT == 0);
// Timer was enabled
REQUIRE(timer2->CR1 == 1);
}
/// @brief Thread-based tests for delay_microsecond()
TEST_CASE("Timer Manager - microsecond timer", "[timer_manager]")
{
std::cout << "timer_manager - microsecond timer" << std::endl;
SECTION("Instantiated Input")
{
// start the testfixture that simulates HW timer counter
stm32::mock::Timer mt;
std::future<bool> tim_res;
TIM_TypeDef *timer = nullptr;
timer = mt.init_timer(tim_res);
// run the SUT; loops until 10ms is reached by timer counter
REQUIRE(stm32::TimerManager::delay_microsecond(10));
// SUT has returned so simulate disabling of the HW Timer
timer->CR1 = 0;
// TIM->CNT should match the time elapsed
REQUIRE(stm32::TimerManager::get_count() == 10);
// This will cause the testfixture to also return. Make sure it exited as expected.
REQUIRE(tim_res.get());
}
}
/// @brief Thread-based tests for delay_millisecond()
TEST_CASE("Timer Manager - Systick Delay", "[timer_manager]")
{
std::cout << "timer_manager - systick milisecond delay" << std::endl;
// enable the mocked SysTick counter. Systick instance is already declared globally in tests/mocks/stm32g0xx.h
stm32::mock::Timer mt;
std::future<bool> tim_res;
mt.init_timer(tim_res, stm32::mock::TimerType::SYSTICK_TYPE);
// call the SUT function
SECTION("Zero delay")
{
stm32::delay_millisecond(0);
}
SECTION("Normal delay")
{
stm32::delay_millisecond(10);
}
// disable the mocked SysTick counter
SysTick->CTRL = SysTick->CTRL & ~(1UL << 0UL);
REQUIRE(tim_res.get());
} | 30.371134 | 114 | 0.6463 | cracked-machine |
dad43acc43b3f918559354c66009677dfbdbe0c8 | 3,058 | cpp | C++ | leetcode/biweekly/49.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/biweekly/49.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/biweekly/49.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: March 20th, 2021
Successful submissions : 2
Time expiration : 1 (solved after looking at the discussion)
Not Solved : 1
Wrong Answer/ Partial result : 0
link: https://leetcode.com/contest/biweekly-contest-49
****************************************************/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <limits.h>
#include <string_view>
using namespace std;
/*
Q: 1812. Determine Color of a Chessboard Square
*/
class Solution1_t
{
public:
bool squareIsWhite(string coordinates)
{
vector< vector<bool> > cb(8, vector<bool>(8, false));
bool color = false;
for(int i = 0; i < 8; ++i)
{
for(int j = 0; j < 8; ++j)
{
cb[i][j] = color;
color = !color;
}
color = !color;
}
return cb[coordinates[0]-'a'][coordinates[1]-'0'-1];
}
};
/*
Q: 1813. Sentence Similarity III
*/
class Solution
{
private:
void getWords(string& str, vector<string>& words)
{
size_t p = 0;
while(p != std::string::npos)
{
size_t temp = str.find_first_of(' ', p);
words.push_back(str.substr(p, temp-p));
if(temp == std::string::npos)
{
break;
}
p = temp+1;
}
}
bool similar(vector<string>& s1, vector<string>& s2)
{
int ans = 0;
auto it1 = s1.begin();
auto it2 = s2.begin();
while(it1 != s1.end() && it2 != s2.end())
{
if(*it1 != *it2)
{
ans++;
string temp = "" + *it2;
while(it1 != s1.end() && *it1 != temp)
{
it2 = s2.insert(it2, *it1);
it1++;
it2++;
}
if(ans >= 2)
{
return false;
}
}
else
{
it1++;
it2++;
}
}
return (it2 == s2.end() && ans == 0 && it1 != s1.end()) || (it1 == s1.end() && it2 == s2.end());
}
public:
bool areSentencesSimilar(string sentence1, string sentence2)
{
vector<string> s1;
getWords(sentence1, s1);
vector<string> s2;
getWords(sentence2, s2);
return (s1.size() >= s2.size()) ? similar(s1, s2) : similar(s2, s1);
}
};
/*
Q: 1814. Count Nice Pairs in an Array - solved after looking at the solution
*/
class Solution3_t
{
public:
int countNicePairs(vector<int>& nums)
{
unordered_map<int, int> freq;
int ans = 0;
static const int MOD = 1e9 + 7;
for(int n : nums)
{
int r = 0;
int t = n;
while(n > 0 )
{
r = (r * 10) + (n%10);
n /= 10;
}
ans = (ans + (freq[t-r]++) % MOD) % MOD;
freq[t-r] = freq[t-r] % MOD;
}
return ans;
}
};
/*
Q: 1815. Maximum Number of Groups Getting Fresh Donuts
*/
class Solution
{
public:
int maxHappyGroups(int batchSize, vector<int>& groups)
{
}
}; | 18.760736 | 100 | 0.503597 | bvbasavaraju |
dad63ec0f34a0ba95a11de28102bc7ed274985e8 | 553 | cpp | C++ | cppcheck/data/c_files/202.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | 2 | 2022-03-23T12:16:20.000Z | 2022-03-31T06:19:40.000Z | cppcheck/data/c_files/202.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | cppcheck/data/c_files/202.cpp | awsm-research/LineVul | 246baf18c1932094564a10c9b81efb21914b2978 | [
"MIT"
] | null | null | null | check_1_6_dummy(kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr)
{
int i;
char *password = *passptr;
/* Old-style randkey operations disallowed tickets to start. */
if (!(mask & KADM5_ATTRIBUTES) ||
!(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX))
return;
/* The 1.6 dummy password was the octets 1..255. */
for (i = 0; (unsigned char) password[i] == i + 1; i++);
if (password[i] != '\0' || i != 255)
return;
/* This will make the caller use a random password instead. */
*passptr = NULL;
}
| 27.65 | 63 | 0.690778 | awsm-research |
dade220ffff7fad38d1466bbcc9a13c6ec0cd33b | 4,695 | cpp | C++ | Source/VSDKInputPlugin/Character/VSDKCharacter.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | 3 | 2021-05-26T14:12:01.000Z | 2022-01-09T01:15:12.000Z | Source/VSDKInputPlugin/Character/VSDKCharacter.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | null | null | null | Source/VSDKInputPlugin/Character/VSDKCharacter.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | null | null | null | // Charles River Analytics Inc. -- Arthur Wollocko (awollocko@cra.com), 2020
#include "VSDKCharacter.h"
#include <Camera/CameraComponent.h>
#include <Components/StaticMeshComponent.h>
#include <Engine/EngineTypes.h>
#include "TimerManager.h"
#include <GameFramework/PlayerController.h>
#include <GameFramework/Actor.h>
#include <Components/CapsuleComponent.h>
#include <Engine/World.h>
#include "NavigationSystem.h"
#include "MotionControllerComponent.h"
#include "DrawDebugHelpers.h"
#include <PhysicsEngine/PhysicsConstraintComponent.h>
#include <Kismet/GameplayStatics.h>
#include <Components/SplineComponent.h>
#include <Components/SplineMeshComponent.h>
#include "../HandPresence/Hand.h"
#include "../Locomotion/LocomotionBase.h"
AVSDKCharacter::AVSDKCharacter()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Set up a ROOT vr object. Important since we'll have to account for the offset that Unreal automatically puts on the Camera when in VR.
VRRoot = CreateDefaultSubobject<USceneComponent>(TEXT("VR Root"));
VRRoot->SetupAttachment(GetRootComponent());
CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
CameraComponent->SetupAttachment(VRRoot);
// Controllers are specified as Actors, and therefore instantiated within BeginPlay
}
void AVSDKCharacter::BeginPlay()
{
Super::BeginPlay();
// Get the offset from camera to the actor
FVector NewCameraOffset = CameraComponent->GetComponentLocation() - GetActorLocation();
AddActorWorldOffset(NewCameraOffset);
// Zero out the Z, so no differential up/down on the camera
NewCameraOffset.Z = 0.f;
// Reset the VR root back a bit, so the user doesn't see the movement of the pawn
VRRoot->AddWorldOffset(NewCameraOffset);
// Spawn the VSDK Hands
LeftHand = GetWorld()->SpawnActor<AHand>(HandLeftControllerBlueprint);
if (LeftHand)
{
LeftHand->AttachToComponent(VRRoot, FAttachmentTransformRules::KeepRelativeTransform);
LeftHand->SetHand(EControllerHand::Left);
LeftHand->SetVSDKCharacter(this);
LeftHand->SetOwner(this);
}
RightHand = GetWorld()->SpawnActor<AHand>(HandRightControllerBlueprint);
if (RightHand)
{
RightHand->AttachToComponent(VRRoot, FAttachmentTransformRules::KeepRelativeTransform);
RightHand->SetHand(EControllerHand::Right);
RightHand->SetVSDKCharacter(this);
RightHand->SetOwner(this);
// For now, locomotion is on the right hand. TODO: Enum and move this around
if (LocomotionClassBlueprint)
{
Locomotion = GetWorld()->SpawnActor<ALocomotionBase>(LocomotionClassBlueprint);
Locomotion->AttachToComponent(RightHand->GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
Locomotion->SetOwner(RightHand);
}
}
}
// Called to bind functionality to input. Allows binding to VSDK inputs (T1)
void AVSDKCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis(TEXT("Forward"), this, &AVSDKCharacter::MoveForward);
PlayerInputComponent->BindAxis(TEXT("Right"), this, &AVSDKCharacter::MoveRight);
PlayerInputComponent->BindAction(TEXT("VirtuosoGrabL"), IE_Pressed, this, &AVSDKCharacter::GrabL);
PlayerInputComponent->BindAction(TEXT("VirtuosoGrabL"), IE_Released, this, &AVSDKCharacter::UnGrabL);
PlayerInputComponent->BindAction(TEXT("VirtuosoGrabR"), IE_Pressed, this, &AVSDKCharacter::GrabR);
PlayerInputComponent->BindAction(TEXT("VirtuosoGrabR"), IE_Released, this, &AVSDKCharacter::UnGrabR);
PlayerInputComponent->BindAction(TEXT("VirtuosoUseL"), IE_Pressed, this, &AVSDKCharacter::UseL);
PlayerInputComponent->BindAction(TEXT("VirtuosoUseL"), IE_Released, this, &AVSDKCharacter::StopUseL);
PlayerInputComponent->BindAction(TEXT("VirtuosoUseR"), IE_Pressed, this, &AVSDKCharacter::UseR);
PlayerInputComponent->BindAction(TEXT("VirtuosoUseR"), IE_Released, this, &AVSDKCharacter::StopUseR);
}
void AVSDKCharacter::MoveForward(float Value)
{
AddMovementInput(CameraComponent->GetForwardVector() * Value);
}
void AVSDKCharacter::MoveRight(float Value)
{
AddMovementInput(CameraComponent->GetRightVector() * Value);
}
void AVSDKCharacter::GrabL()
{
LeftHand->Grab();
}
void AVSDKCharacter::GrabR()
{
RightHand->Grab();
}
void AVSDKCharacter::UnGrabL()
{
LeftHand->DropCurrent();
}
void AVSDKCharacter::UnGrabR()
{
RightHand->DropCurrent();
}
void AVSDKCharacter::UseL()
{
LeftHand->Use();
}
void AVSDKCharacter::UseR()
{
RightHand->Use();
}
void AVSDKCharacter::StopUseL()
{
LeftHand->StopUse();
}
void AVSDKCharacter::StopUseR()
{
RightHand->StopUse();
}
| 31.510067 | 138 | 0.776997 | charles-river-analytics |
dae7c348c1105dac9b1457aaaef00931b3f76b92 | 1,094 | cpp | C++ | codeforces/easy_100/1395B.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | 2 | 2018-06-26T09:52:14.000Z | 2018-07-12T15:02:01.000Z | codeforces/easy_100/1395B.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | null | null | null | codeforces/easy_100/1395B.cpp | sidgairo18/Programming-Practice | 348ad38452fa9fa7b7302161455d3b3f697734da | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
t = 1;
while(t--){
int n,m,sx,sy;
cin>>n>>m>>sx>>sy;
int visited[n][m];
for(int i = 0; i<n; i++)
for(int j =0; j<n; j++)
visited[i][j] = -1;
visited[sx-1][sy-1] = 1;
queue<pair<int, int> > qu;
qu.push(make_pair(sx-1, sy-1));
while(!qu.empty()){
int x,y;
x = qu.front().first;
y = qu.front().second;
qu.pop();
cout<<x+1<<" "<<y+1<<endl;
for(int i =0; i<n; i++){
int flag = 0;
for(int j = 0; j<m; j++)
{
if(visited[i][j] == -1 && ((i==x && j!=y) || (i!=x && j==y))){
qu.push(make_pair(i,j));
visited[i][j] = 1;
flag = 1;
break;
}
}
if(flag == 1)
break;
}
}
}
return 0;
}
| 18.862069 | 83 | 0.304388 | sidgairo18 |
dae96366ca73f596cacfc3c3db688548d1a6b4d4 | 43,029 | cpp | C++ | src/AdditiveVibration.cpp | pixelrust/LifeFormModular | c823c86c74a2c94d88327cf37bdcde5d80bb5645 | [
"BSD-3-Clause"
] | 8 | 2019-09-24T15:22:03.000Z | 2022-03-02T22:58:51.000Z | src/AdditiveVibration.cpp | pixelrust/LifeFormModular | c823c86c74a2c94d88327cf37bdcde5d80bb5645 | [
"BSD-3-Clause"
] | 3 | 2019-10-01T16:54:45.000Z | 2019-11-30T15:51:33.000Z | src/AdditiveVibration.cpp | pixelrust/LifeFormModular | c823c86c74a2c94d88327cf37bdcde5d80bb5645 | [
"BSD-3-Clause"
] | 2 | 2020-09-18T02:40:09.000Z | 2021-10-01T00:30:47.000Z | #include "plugin.hpp"
#include "dsp/math.hpp"
//Based on 21Khz PalmLoop sine fm engine
//https://github.com/21kHz/21kHz-rack-plugins
//Env taken from Rampage
//https://github.com/VCVRack/Befaco
static float shapeDelta(float delta, float tau, float shape) {
float lin = sgn(delta) * 10.f / tau;
if (shape < 0.f) {
float log = sgn(delta) * 40.f / tau / (std::fabs(delta) + 1.f);
return crossfade(lin, log, -shape * 0.95f);
}
else {
float exp = M_E * delta / tau;
return crossfade(lin, exp, shape * 0.90f);
}
}
struct AdditiveVibration : Module {
enum ParamIds {
OCT_PARAM,
D_PARAM,
V_PARAM,
HARM1LVL_PARAM,
HARM2LVL_PARAM,
HARM3LVL_PARAM,
DMOD_PARAM,
VMOD_PARAM,
HARM1MOD_PARAM,
HARM2MOD_PARAM,
HARM3MOD_PARAM,
TZ_PARAM,
HARMMIX_PARAM,
TZENVMOD_PARAM,
TZMOD_PARAM,
TZMOD2_PARAM,
RANGE_A_PARAM,
SHAPE_A_PARAM,
TRIGG_A_PARAM,
RISE_A_PARAM,
FALL_A_PARAM,
CYCLE_A_PARAM,
CV_A_DEST_PARAM,
CV_A_MOD_PARAM,
NUM_PARAMS
};
enum InputIds {
V_OCT_INPUT,
V_OCT2_INPUT,
V_OCT3_INPUT,
D_INPUT,
V_INPUT,
HARM1_INPUT,
HARM2_INPUT,
HARM3_INPUT,
TZMOD_INPUT,
TZMOD2_INPUT,
CV_A_INPUT,
TRIGG_A_INPUT,
NUM_INPUTS
};
enum OutputIds {
SIN_OUTPUT,
OUT_A_OUTPUT,
AUDIO_OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
NUM_LIGHTS
};
float phase = 0.0f;
float oldPhase = 0.0f;
float square = 1.0f;
int discont = 0;
int oldDiscont = 0;
float phaseA = 0.0f;
float oldPhaseA = 0.0f;
float squareA = 1.0f;
int discontA = 0;
int oldDiscontA = 0;
float phaseB = 0.0f;
float oldPhaseB = 0.0f;
float squareB = 1.0f;
int discontB = 0;
int oldDiscontB = 0;
float phase2 = 0.0f;
float oldPhase2 = 0.0f;
float square2 = 1.0f;
int discont2 = 0;
int oldDiscont2 = 0;
float phase2A = 0.0f;
float oldPhase2A = 0.0f;
float square2A = 1.0f;
int discont2A = 0;
int oldDiscont2A = 0;
float phase2B = 0.0f;
float oldPhase2B = 0.0f;
float square2B = 1.0f;
int discont2B = 0;
int oldDiscont2B = 0;
float phase3 = 0.0f;
float oldPhase3 = 0.0f;
float square3 = 1.0f;
int discont3 = 0;
int oldDiscont3 = 0;
float phase3A = 0.0f;
float oldPhase3A = 0.0f;
float square3A = 1.0f;
int discont3A = 0;
int oldDiscont3A = 0;
float phase3B = 0.0f;
float oldPhase3B = 0.0f;
float square3B = 1.0f;
int discont3B = 0;
int oldDiscont3B = 0;
float phase4 = 0.0f;
float oldPhase4 = 0.0f;
float square4 = 1.0f;
int discont4 = 0;
int oldDiscont4 = 0;
float phase4A = 0.0f;
float oldPhase4A = 0.0f;
float square4A = 1.0f;
int discont4A = 0;
int oldDiscont4A = 0;
float phase4B = 0.0f;
float oldPhase4B = 0.0f;
float square4B = 1.0f;
int discont4B = 0;
int oldDiscont4B = 0;
float phase5 = 0.0f;
float oldPhase5 = 0.0f;
float square5 = 1.0f;
int discont5 = 0;
int oldDiscont5 = 0;
float phase5A = 0.0f;
float oldPhase5A = 0.0f;
float square5A = 1.0f;
int discont5A = 0;
int oldDiscont5A = 0;
float phase5B = 0.0f;
float oldPhase5B = 0.0f;
float square5B = 1.0f;
int discont5B = 0;
int oldDiscont5B = 0;
float phase6 = 0.0f;
float oldPhase6 = 0.0f;
float square6 = 1.0f;
int discont6 = 0;
int oldDiscont6 = 0;
float phase6A = 0.0f;
float oldPhase6A = 0.0f;
float square6A = 1.0f;
int discont6A = 0;
int oldDiscont6A = 0;
float phase6B = 0.0f;
float oldPhase6B = 0.0f;
float square6B = 1.0f;
int discont6B = 0;
int oldDiscont6B = 0;
float log2sampleFreq = 15.4284f;
float tzharmmix = 0.0f;
float tzharmmixA = 0.0f;
float tzharmmixB = 0.0f;
dsp::SchmittTrigger resetTrigger;
float out = {};
bool gate = {};
dsp::SchmittTrigger trigger;
dsp::PulseGenerator endOfCyclePulse;
AdditiveVibration(){
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
configParam(OCT_PARAM, 4.0, 12.0, 8.0,"Octave");
configParam(D_PARAM, 0.1, 0.9, 0.5,"Sine Width");
configParam(V_PARAM, 0.0, 0.9, 0.5,"Sine Curve");
configParam(HARM1LVL_PARAM, 0.0, 1.0, 1.0,"1st Harmonic level");
configParam(HARM2LVL_PARAM, 0.0, 1.0, 1.0,"2nd Harmonic level");
configParam(HARM3LVL_PARAM, 0.0, 1.0, 1.0,"3rd Harmonic level");
configParam(DMOD_PARAM, -1.0, 1.0, 0.0,"Sine Width modulation");
configParam(VMOD_PARAM, -1.0, 1.0, 0.0,"Sine Curve modulation");
configParam(HARM1MOD_PARAM, -1.0, 1.0, 0.0,"1st Harmonic level mod");
configParam(HARM2MOD_PARAM, -1.0, 1.0, 0.0,"2nd Harmonic level mod");
configParam(HARM3MOD_PARAM, -1.0, 1.0, 0.0,"3rd Harmonic level mod");
configParam(TZ_PARAM, 0.0, 7.0, 0.0,"FM Depth");
configParam(HARMMIX_PARAM, 0.0, 7.0, 0.0, "Harmonics set");
configParam(TZMOD_PARAM, -1.0, 1.0, 0.0, "FM Depth mod");
configParam(TZMOD2_PARAM, -1.0, 1.0, 0.0,"FM Depth mod2");
configParam(RANGE_A_PARAM, 0.0, 2.0, 0.0, "Env time");
configParam(SHAPE_A_PARAM, 0.0, 1.0, 0.0, "Env shape");
configParam(TRIGG_A_PARAM, 0.0, 1.0, 0.0, "Env trigger");
configParam(RISE_A_PARAM, 0.0, 1.0, 0.0, "Env rise time");
configParam(FALL_A_PARAM, 0.0, 1.0, 0.5, "Env fall time");
configParam(CYCLE_A_PARAM, 0.0, 1.0, 0.0, "Lfo mode");
configParam(CV_A_DEST_PARAM, 0.0, 2.0, 0.0, "Env mod destination");
configParam(CV_A_MOD_PARAM, -0.5, 0.5, 0.0, "Env mod amount");
configParam(TZENVMOD_PARAM, -1.0, 1.0, 0.0,"FM Depth env mod");
}
void onSampleRateChange() override {
log2sampleFreq = log2f(1.0f / APP->engine->getSampleTime()) - 0.00009f;
}
void process(const ProcessArgs &args) override{
float freq = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT_INPUT].getVoltage();
if (freq >= log2sampleFreq) {
freq = log2sampleFreq;
}
freq = powf(2.0f, freq);
float incr = 0.0f;
freq += clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * tzharmmix;
incr = args.sampleTime * freq;
incr = args.sampleTime * freq;
if (incr > 1.0f) {
incr = 1.0f;
}
else if (incr < -1.0f) {
incr = -1.0f;
}
phase += incr;
if (phase >= 0.0f && phase < 1.0f) {
discont = 0;
}
else if (phase >= 1.0f) {
discont = 1;
--phase;
square *= -1.0f;
}
else {
discont = -1;
++phase;
square *= -1.0f;
}
float d = clamp((params[D_PARAM].getValue() + ((inputs[D_INPUT].getVoltage() / 10.0f) * params[DMOD_PARAM].getValue())),0.1,0.9);
float v = clamp((params[V_PARAM].getValue() + ((inputs[V_INPUT].getVoltage() / 10.0f) * params[VMOD_PARAM].getValue())),0.0,0.9);
float saw = (1.0-v)*((phase-d)/(1.0-d)) + v ;
if (phase < d) {
saw = (v * (phase)) / d;
}
oldPhase = phase;
oldDiscont = discont;
float freqA = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT2_INPUT].getVoltage();
if (freqA >= log2sampleFreq) {
freqA = log2sampleFreq;
}
freqA = powf(2.0f, freqA);
float incrA = 0.0f;
freqA += clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * tzharmmixA;
incrA = args.sampleTime * freqA;
incrA = args.sampleTime * freqA;
if (incrA > 1.0f) {
incrA = 1.0f;
}
else if (incrA < -1.0f) {
incrA = -1.0f;
}
phaseA += incrA;
if (phaseA >= 0.0f && phaseA < 1.0f) {
discontA = 0;
}
else if (phaseA >= 1.0f) {
discontA = 1;
--phaseA;
squareA *= -1.0f;
}
else {
discontA = -1;
++phaseA;
squareA *= -1.0f;
}
float sawA = (1.0-v)*((phaseA-d)/(1.0-d)) + v ;
if (phaseA < d) {
sawA = (v * (phaseA)) / d;
}
oldPhaseA = phaseA;
oldDiscontA = discontA;
float freqB = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT3_INPUT].getVoltage();
if (freqB >= log2sampleFreq) {
freqB = log2sampleFreq;
}
freqB = powf(2.0f, freqB);
float incrB = 0.0f;
freqB += clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * clamp(((params[TZENVMOD_PARAM].getValue() * out) + params[TZ_PARAM].getValue() + (inputs[TZMOD_INPUT].getVoltage() * params[TZMOD_PARAM].getValue()) + (inputs[TZMOD2_INPUT].getVoltage() * params[TZMOD2_PARAM].getValue())), 0.0f, 10.0f) * tzharmmixB;
incrB = args.sampleTime * freqB;
incrB = args.sampleTime * freqB;
if (incrB > 1.0f) {
incrB = 1.0f;
}
else if (incrB < -1.0f) {
incrB = -1.0f;
}
phaseB += incrB;
if (phaseB >= 0.0f && phaseB < 1.0f) {
discontB = 0;
}
else if (phaseB >= 1.0f) {
discontB = 1;
--phaseB;
squareB *= -1.0f;
}
else {
discontB = -1;
++phaseB;
squareB *= -1.0f;
}
float sawB = (1.0-v)*((phaseB-d)/(1.0-d)) + v ;
if (phaseB < d) {
sawB = (v * (phaseB)) / d;
}
oldPhaseB = phaseB;
oldDiscontB = discontB;
float freq2 = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT_INPUT].getVoltage() + 1.0;
if (freq2 >= log2sampleFreq) {
freq2 = log2sampleFreq;
}
freq2 = powf(2.0f, freq2);
float incr2 = 0.0f;
incr2 = args.sampleTime * freq2;
phase2 += incr2;
if (phase2 >= 0.0f && phase2 < 1.0f) {
discont2 = 0;
}
else if (phase2 >= 1.0f) {
discont2 = 1;
--phase2;
square2 *= -1.0f;
}
else {
discont2 = -1;
++phase2;
square2 *= -1.0f;
}
oldPhase2 = phase2;
oldDiscont2 = discont2;
float freq3 = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT_INPUT].getVoltage() + 1.0 + ((1.0/12.0) * 7.0) + + ((1.0/12.0) * 0.02);
if (freq3 >= log2sampleFreq) {
freq3 = log2sampleFreq;
}
freq3 = powf(2.0f, freq3);
float incr3 = 0.0f;
incr3 = args.sampleTime * freq3;
phase3 += incr3;
if (phase3 >= 0.0f && phase3 < 1.0f) {
discont3 = 0;
}
else if (phase3 >= 1.0f) {
discont3 = 1;
--phase3;
square3 *= -1.0f;
}
else {
discont3 = -1;
++phase3;
square3 *= -1.0f;
}
oldPhase3 = phase3;
oldDiscont3 = discont3;
float freq4 = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT_INPUT].getVoltage() + 2.0 ;
if (freq4 >= log2sampleFreq) {
freq4 = log2sampleFreq;
}
freq4 = powf(2.0f, freq4);
float incr4 = 0.0f;
incr4 = args.sampleTime * freq4;
phase4 += incr4;
if (phase4 >= 0.0f && phase4 < 1.0f) {
discont4 = 0;
}
else if (phase4 >= 1.0f) {
discont4 = 1;
--phase4;
square4 *= -1.0f;
}
else {
discont4 = -1;
++phase4;
square4 *= -1.0f;
}
oldPhase4 = phase4;
oldDiscont4 = discont4;
float freq5 = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT_INPUT].getVoltage() + 2.0 + ((1.0 / 12.0) * 4.0) - ((1.0/12.0) * 0.14);
if (freq5 >= log2sampleFreq) {
freq5 = log2sampleFreq;
}
freq5 = powf(2.0f, freq5);
float incr5 = 0.0f;
incr5 = args.sampleTime * freq5;
phase5 += incr5;
if (phase5 >= 0.0f && phase5 < 1.0f) {
discont5 = 0;
}
else if (phase5 >= 1.0f) {
discont5 = 1;
--phase5;
square5 *= -1.0f;
}
else {
discont5 = -1;
++phase5;
square5 *= -1.0f;
}
oldPhase5 = phase5;
oldDiscont5 = discont5;
float freq6 = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT_INPUT].getVoltage() + 2.0 + ((1.0 / 12.0) * 7.0) + ((1.0/12.0) * 0.02) ;
if (freq6 >= log2sampleFreq) {
freq6 = log2sampleFreq;
}
freq6 = powf(2.0f, freq6);
float incr6 = 0.0f;
incr6 = args.sampleTime * freq6;
phase6 += incr6;
if (phase6 >= 0.0f && phase6 < 1.0f) {
discont6 = 0;
}
else if (phase6 >= 1.0f) {
discont6 = 1;
--phase6;
square6 *= -1.0f;
}
else {
discont6 = -1;
++phase6;
square6 *= -1.0f;
}
oldPhase6 = phase6;
oldDiscont6 = discont6;
if (inputs[V_OCT2_INPUT].isConnected()){
float freq2A = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT2_INPUT].getVoltage() + 1.0;
if (freq2A >= log2sampleFreq) {
freq2A = log2sampleFreq;
}
freq2A = powf(2.0f, freq2A);
float incr2A = 0.0f;
incr2A = args.sampleTime * freq2A;
phase2A += incr2A;
if (phase2A >= 0.0f && phase2A < 1.0f) {
discont2A = 0;
}
else if (phase2A >= 1.0f) {
discont2A = 1;
--phase2A;
square2A *= -1.0f;
}
else {
discont2A = -1;
++phase2A;
square2A *= -1.0f;
}
oldPhase2A = phase2A;
oldDiscont2A = discont2A;
float freq3A = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT2_INPUT].getVoltage() + 1.0 + ((1.0/12.0) * 7.0) + + ((1.0/12.0) * 0.02);
if (freq3A >= log2sampleFreq) {
freq3A = log2sampleFreq;
}
freq3A = powf(2.0f, freq3A);
float incr3A = 0.0f;
incr3A = args.sampleTime * freq3A;
phase3A += incr3A;
if (phase3A >= 0.0f && phase3A < 1.0f) {
discont3A = 0;
}
else if (phase3A >= 1.0f) {
discont3A = 1;
--phase3A;
square3A *= -1.0f;
}
else {
discont3A = -1;
++phase3A;
square3A *= -1.0f;
}
oldPhase3A = phase3A;
oldDiscont3A = discont3A;
float freq4A = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT2_INPUT].getVoltage() + 2.0 ;
if (freq4A >= log2sampleFreq) {
freq4A = log2sampleFreq;
}
freq4A = powf(2.0f, freq4A);
float incr4A = 0.0f;
incr4A = args.sampleTime * freq4A;
phase4A += incr4A;
if (phase4A >= 0.0f && phase4A < 1.0f) {
discont4A = 0;
}
else if (phase4A >= 1.0f) {
discont4A = 1;
--phase4A;
square4A *= -1.0f;
}
else {
discont4A = -1;
++phase4A;
square4A *= -1.0f;
}
oldPhase4A = phase4A;
oldDiscont4A = discont4A;
float freq5A = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT2_INPUT].getVoltage() + 2.0 + ((1.0 / 12.0) * 4.0) - ((1.0/12.0) * 0.14);
if (freq5A >= log2sampleFreq) {
freq5A = log2sampleFreq;
}
freq5A = powf(2.0f, freq5A);
float incr5A = 0.0f;
incr5A = args.sampleTime * freq5A;
phase5A += incr5A;
if (phase5A >= 0.0f && phase5A < 1.0f) {
discont5A = 0;
}
else if (phase5A >= 1.0f) {
discont5A = 1;
--phase5A;
square5A *= -1.0f;
}
else {
discont5A = -1;
++phase5A;
square5A *= -1.0f;
}
oldPhase5A = phase5A;
oldDiscont5A = discont5A;
float freq6A = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT2_INPUT].getVoltage() + 2.0 + ((1.0 / 12.0) * 7.0) + ((1.0/12.0) * 0.02) ;
if (freq6A >= log2sampleFreq) {
freq6A = log2sampleFreq;
}
freq6A = powf(2.0f, freq6A);
float incr6A = 0.0f;
incr6A = args.sampleTime * freq6A;
phase6A += incr6A;
if (phase6A >= 0.0f && phase6A < 1.0f) {
discont6A = 0;
}
else if (phase6A >= 1.0f) {
discont6A = 1;
--phase6A;
square6A *= -1.0f;
}
else {
discont6A = -1;
++phase6A;
square6A *= -1.0f;
}
oldPhase6A = phase6A;
oldDiscont6A = discont6A;
}
if (inputs[V_OCT3_INPUT].isConnected()) {
float freq2B = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT3_INPUT].getVoltage() + 1.0;
if (freq2B >= log2sampleFreq) {
freq2B = log2sampleFreq;
}
freq2B = powf(2.0f, freq2B);
float incr2B = 0.0f;
incr2B = args.sampleTime * freq2B;
phase2B += incr2B;
if (phase2B >= 0.0f && phase2B < 1.0f) {
discont2B = 0;
}
else if (phase2B >= 1.0f) {
discont2B = 1;
--phase2B;
square2B *= -1.0f;
}
else {
discont2B = -1;
++phase2B;
square2B *= -1.0f;
}
oldPhase2B = phase2B;
oldDiscont2B = discont2B;
float freq3B = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT3_INPUT].getVoltage() + 1.0 + ((1.0/12.0) * 7.0) + + ((1.0/12.0) * 0.02);
if (freq3B >= log2sampleFreq) {
freq3B = log2sampleFreq;
}
freq3B = powf(2.0f, freq3B);
float incr3B = 0.0f;
incr3B = args.sampleTime * freq3B;
phase3B += incr3B;
if (phase3B >= 0.0f && phase3B < 1.0f) {
discont3B = 0;
}
else if (phase3B >= 1.0f) {
discont3B = 1;
--phase3B;
square3B *= -1.0f;
}
else {
discont3B = -1;
++phase3B;
square3B *= -1.0f;
}
oldPhase3B = phase3B;
oldDiscont3B = discont3B;
float freq4B = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT3_INPUT].getVoltage() + 2.0 ;
if (freq4B >= log2sampleFreq) {
freq4B = log2sampleFreq;
}
freq4B = powf(2.0f, freq4B);
float incr4B = 0.0f;
incr4B = args.sampleTime * freq4B;
phase4B += incr4B;
if (phase4B >= 0.0f && phase4B < 1.0f) {
discont4B = 0;
}
else if (phase4B >= 1.0f) {
discont4B = 1;
--phase4B;
square4B *= -1.0f;
}
else {
discont4B = -1;
++phase4B;
square4B *= -1.0f;
}
oldPhase4B = phase4B;
oldDiscont4B = discont4B;
float freq5B = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT3_INPUT].getVoltage() + 2.0 + ((1.0 / 12.0) * 4.0) - ((1.0/12.0) * 0.14);
if (freq5B >= log2sampleFreq) {
freq5B = log2sampleFreq;
}
freq5B = powf(2.0f, freq5B);
float incr5B = 0.0f;
incr5B = args.sampleTime * freq5B;
phase5B += incr5B;
if (phase5B >= 0.0f && phase5B < 1.0f) {
discont5B = 0;
}
else if (phase5B >= 1.0f) {
discont5B = 1;
--phase5B;
square5B *= -1.0f;
}
else {
discont5B = -1;
++phase5B;
square5B *= -1.0f;
}
oldPhase5B = phase5B;
oldDiscont5B = discont5B;
float freq6B = params[OCT_PARAM].getValue() + 0.031360 + inputs[V_OCT2_INPUT].getVoltage() + 2.0 + ((1.0 / 12.0) * 7.0) + ((1.0/12.0) * 0.02) ;
if (freq6B >= log2sampleFreq) {
freq6B = log2sampleFreq;
}
freq6B = powf(2.0f, freq6B);
float incr6B = 0.0f;
incr6B = args.sampleTime * freq6B;
phase6B += incr6B;
if (phase6B >= 0.0f && phase6B < 1.0f) {
discont6B = 0;
}
else if (phase6B >= 1.0f) {
discont6B = 1;
--phase6B;
square6B *= -1.0f;
}
else {
discont6B = -1;
++phase6B;
square6B *= -1.0f;
}
oldPhase6B = phase6B;
oldDiscont6B = discont6B;
}
float osc1 = 5.0f * sin_01(saw);
float osc2 = 5.0f * sin_01(sawA);
float osc3 = 5.0f * sin_01(sawB);
outputs[SIN_OUTPUT].setVoltage(osc1);
outputs[AUDIO_OUTPUT].setVoltage(osc1 * (out/10.0));
if (inputs[V_OCT2_INPUT].isConnected()){
outputs[SIN_OUTPUT].setVoltage((osc1 + osc2)/2.0);
outputs[AUDIO_OUTPUT].setVoltage(((osc1 + osc2)/2.0) * (out/10.0));
}
if (inputs[V_OCT3_INPUT].isConnected()){
outputs[SIN_OUTPUT].setVoltage((osc1 + osc3)/2.0);
outputs[AUDIO_OUTPUT].setVoltage(((osc1 + osc3)/2.0) * (out/10.0));
}
if (inputs[V_OCT2_INPUT].isConnected() && inputs[V_OCT3_INPUT].isConnected()){
outputs[SIN_OUTPUT].setVoltage((osc1 + osc2 + osc3) / 3.0);
outputs[AUDIO_OUTPUT].setVoltage(((osc1 + osc2 + osc3) / 3.0) * (out/10.0));
}
tzharmmix = ((5.0f * sin_01(phase2) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
if (params[HARMMIX_PARAM].getValue() == 1.0) {
tzharmmix = ((5.0f * sin_01(phase2) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase3) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 2.0) {
tzharmmix = ((5.0f * sin_01(phase4) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 3.0) {
tzharmmix = ((5.0f * sin_01(phase3) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 4.0) {
tzharmmix = ((5.0f * sin_01(phase2) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 5.0) {
tzharmmix = ((5.0f * sin_01(phase3) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 6.0) {
tzharmmix = ((5.0f * sin_01(phase4) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 7.0) {
tzharmmix = ((5.0f * sin_01(phase3) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
tzharmmixA = ((5.0f * sin_01(phase2A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
if (params[HARMMIX_PARAM].getValue() == 1.0 && inputs[V_OCT2_INPUT].isConnected()) {
tzharmmixA = ((5.0f * sin_01(phase2A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase3A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 2.0 && inputs[V_OCT2_INPUT].isConnected()) {
tzharmmixA = ((5.0f * sin_01(phase4A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 3.0 && inputs[V_OCT2_INPUT].isConnected()) {
tzharmmixA = ((5.0f * sin_01(phase3A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 4.0 && inputs[V_OCT2_INPUT].isConnected()) {
tzharmmixA = ((5.0f * sin_01(phase2A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 5.0 && inputs[V_OCT2_INPUT].isConnected()) {
tzharmmixA = ((5.0f * sin_01(phase3A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 6.0 && inputs[V_OCT2_INPUT].isConnected()) {
tzharmmixA = ((5.0f * sin_01(phase4A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 7.0 && inputs[V_OCT2_INPUT].isConnected()) {
tzharmmixA = ((5.0f * sin_01(phase3A) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4A) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6A) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
tzharmmixB = ((5.0f * sin_01(phase2B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
if (params[HARMMIX_PARAM].getValue() == 1.0 && inputs[V_OCT3_INPUT].isConnected()) {
tzharmmixB = ((5.0f * sin_01(phase2B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase3B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 2.0 && inputs[V_OCT3_INPUT].isConnected()) {
tzharmmixB = ((5.0f * sin_01(phase4B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 3.0 && inputs[V_OCT3_INPUT].isConnected()) {
tzharmmixB = ((5.0f * sin_01(phase3B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 4.0 && inputs[V_OCT3_INPUT].isConnected()) {
tzharmmixB = ((5.0f * sin_01(phase2B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 5.0 && inputs[V_OCT3_INPUT].isConnected()) {
tzharmmixB = ((5.0f * sin_01(phase3B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 6.0 && inputs[V_OCT3_INPUT].isConnected()) {
tzharmmixB = ((5.0f * sin_01(phase4B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase5B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
if (params[HARMMIX_PARAM].getValue() == 7.0 && inputs[V_OCT3_INPUT].isConnected()){
tzharmmixB = ((5.0f * sin_01(phase3B) * clamp((params[HARM1LVL_PARAM].getValue() + clamp(((inputs[HARM1_INPUT].getVoltage() / 10.0f) * params[HARM1MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase4B) * clamp((params[HARM2LVL_PARAM].getValue()+ clamp(((inputs[HARM2_INPUT].getVoltage() / 10.0f) * params[HARM2MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) + (5.0f * sin_01(phase6B) * clamp((params[HARM3LVL_PARAM].getValue()+ clamp(((inputs[HARM3_INPUT].getVoltage() / 10.0f) * params[HARM3MOD_PARAM].getValue()),-1.0,1.0)),0.0,1.0)) / 3.0) ;
}
float in = 0.0;
if (trigger.process(inputs[TRIGG_A_INPUT].getVoltage())) {
gate = true;
}
if (gate) {
in = 10.0;
}
float shape = params[SHAPE_A_PARAM].getValue();
float delta = in - out;
float minTime;
switch ((int) params[RANGE_A_PARAM].getValue()) {
case 0: minTime = 1e-2; break;
case 1: minTime = 1e-3; break;
default: minTime = 1e-1; break;
}
bool rising = false;
bool falling = false;
if (delta > 0) {
float riseCv = params[RISE_A_PARAM].getValue();
if (params[CV_A_DEST_PARAM].getValue() == 2.0) {
riseCv = params[RISE_A_PARAM].getValue()+ (inputs[CV_A_INPUT].getVoltage() * params[CV_A_MOD_PARAM].getValue()) / 10.0 ;
}
if (params[CV_A_DEST_PARAM].getValue() == 0.0) {
riseCv = params[RISE_A_PARAM].getValue()+ (inputs[CV_A_INPUT].getVoltage() * params[CV_A_MOD_PARAM].getValue()) / 10.0 ;
}
riseCv = clamp(riseCv, 0.0f, 1.0f);
float rise = minTime * std::pow(2.0, riseCv * 10.0);
out += shapeDelta(delta, rise, shape) * args.sampleTime;
rising = (in - out > 1e-3);
if (!rising) {
gate = false;
}
}
else if (delta < 0) {
float fallCv = params[FALL_A_PARAM].getValue();
if (params[CV_A_DEST_PARAM].getValue() == 2.0) {
fallCv = params[FALL_A_PARAM].getValue() + (inputs[CV_A_INPUT].getVoltage() * params[CV_A_MOD_PARAM].getValue()) / 10.0;
}
if (params[CV_A_DEST_PARAM].getValue() == 1.0) {
fallCv = params[FALL_A_PARAM].getValue() + (inputs[CV_A_INPUT].getVoltage() * params[CV_A_MOD_PARAM].getValue())/ 10.0;
}
fallCv = clamp(fallCv, 0.0f, 1.0f);
float fall = minTime * std::pow(2.0, fallCv * 10.0);
out += shapeDelta(delta, fall, shape) * args.sampleTime;
falling = (in - out < -1e-3);
if (!falling) {
endOfCyclePulse.trigger(1e-3);
if (params[CYCLE_A_PARAM].getValue()) {
gate = true;
}
}
}
else {
gate = false;
}
if (!rising && !falling) {
out = in;
}
outputs[OUT_A_OUTPUT].setVoltage(out);
}
};
struct AdditiveVibrationWidget : ModuleWidget {
AdditiveVibrationWidget(AdditiveVibration *module) {
setModule(module);
setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/AdditiveVibration.svg")));
addParam(createParam<LFMSnapKnob>(Vec(10, 40), module, AdditiveVibration::OCT_PARAM));
addParam(createParam<LFMKnob>(Vec(10, 110), module, AdditiveVibration::D_PARAM));
addParam(createParam<LFMKnob>(Vec(130, 110), module, AdditiveVibration::V_PARAM));
addParam(createParam<LFMKnob>(Vec(250, 40), module, AdditiveVibration::TZ_PARAM));
addParam(createParam<LFMKnob>(Vec(250, 110), module, AdditiveVibration::TZENVMOD_PARAM));
addParam(createParam<LFMSliderWhite>(Vec(25.5, 190), module, AdditiveVibration::HARM1LVL_PARAM));
addParam(createParam<LFMSliderWhite>(Vec(85.5, 190), module, AdditiveVibration::HARM2LVL_PARAM));
addParam(createParam<LFMSliderWhite>(Vec(145.5, 190), module, AdditiveVibration::HARM3LVL_PARAM));
addParam(createParam<LFMTinyKnob>(Vec(83, 127), module, AdditiveVibration::DMOD_PARAM));
addParam(createParam<LFMTinyKnob>(Vec(203, 127), module, AdditiveVibration::VMOD_PARAM));
addParam(createParam<LFMTinyKnob>(Vec(28, 317), module, AdditiveVibration::HARM1MOD_PARAM));
addParam(createParam<LFMTinyKnob>(Vec(88, 317), module, AdditiveVibration::HARM2MOD_PARAM));
addParam(createParam<LFMTinyKnob>(Vec(148, 317), module, AdditiveVibration::HARM3MOD_PARAM));
addParam(createParam<LFMSnapKnob>(Vec(190, 230), module, AdditiveVibration::HARMMIX_PARAM));
addParam(createParam<LFMTinyKnob>(Vec(263, 197), module, AdditiveVibration::TZMOD_PARAM));
addParam(createParam<LFMTinyKnob>(Vec(263, 267), module, AdditiveVibration::TZMOD2_PARAM));
addInput(createInput<MiniJackPort>(Vec(68, 110), module, AdditiveVibration::D_INPUT));
addInput(createInput<MiniJackPort>(Vec(188, 110), module, AdditiveVibration::V_INPUT));
addInput(createInput<MiniJackPort>(Vec(8, 300), module, AdditiveVibration::HARM1_INPUT));
addInput(createInput<MiniJackPort>(Vec(68, 300), module, AdditiveVibration::HARM2_INPUT));
addInput(createInput<MiniJackPort>(Vec(128, 300), module, AdditiveVibration::HARM3_INPUT));
addInput(createInput<MiniJackPort>(Vec(248, 180), module, AdditiveVibration::TZMOD_INPUT));
addInput(createInput<MiniJackPort>(Vec(248, 250), module, AdditiveVibration::TZMOD2_INPUT));
addInput(createInput<JackPort>(Vec(78, 50), module, AdditiveVibration::V_OCT_INPUT));
addInput(createInput<JackPort>(Vec(138, 50), module, AdditiveVibration::V_OCT2_INPUT));
addInput(createInput<JackPort>(Vec(198, 50), module, AdditiveVibration::V_OCT3_INPUT));
addOutput(createOutput<OutJackPort>(Vec(258, 318), module, AdditiveVibration::SIN_OUTPUT));
addOutput(createOutput<OutJackPort>(Vec(318, 318), module, AdditiveVibration::AUDIO_OUTPUT));
addParam(createParam<LFMKnob>(Vec(310, 40), module, AdditiveVibration::RISE_A_PARAM));
addParam(createParam<LFMKnob>(Vec(310, 110), module, AdditiveVibration::FALL_A_PARAM));
addInput(createInput<MiniJackPort>(Vec(308, 180), module, AdditiveVibration::CV_A_INPUT));
addParam(createParam<LFMTinyKnob>(Vec(323, 197), module, AdditiveVibration::CV_A_MOD_PARAM));
addParam(createParam<LFMSwitch>(Vec(370, 48), module, AdditiveVibration::RANGE_A_PARAM));
addParam(createParam<MS>(Vec(368, 130), module, AdditiveVibration::SHAPE_A_PARAM));
addParam(createParam<MS>(Vec(398, 130), module, AdditiveVibration::CYCLE_A_PARAM));
addParam(createParam<LFMSwitch>(Vec(370, 188), module, AdditiveVibration::CV_A_DEST_PARAM));
addInput(createInput<JackPort>(Vec(318, 260), module, AdditiveVibration::TRIGG_A_INPUT));
addOutput(createOutput<OutJackPort>(Vec(378, 260), module, AdditiveVibration::OUT_A_OUTPUT));
}
};
Model *modelAdditiveVibration = createModel<AdditiveVibration, AdditiveVibrationWidget>("AdditiveVibration"); | 43.158475 | 737 | 0.613772 | pixelrust |
daedfb6d4c815714adf69f4fcab58bf42c2f968c | 3,941 | cpp | C++ | kernel/arch/x86_64/interrupt/interrupt.cpp | andr3h3nriqu3s11/thornhill | ec31eb06dd914bcb7fd22ff31386b40996656d94 | [
"MIT"
] | 6 | 2021-11-06T08:42:41.000Z | 2022-01-06T11:42:18.000Z | kernel/arch/x86_64/interrupt/interrupt.cpp | andr3h3nriqu3s11/thornhill | ec31eb06dd914bcb7fd22ff31386b40996656d94 | [
"MIT"
] | 1 | 2022-01-09T18:09:57.000Z | 2022-01-09T18:09:57.000Z | kernel/arch/x86_64/interrupt/interrupt.cpp | andr3h3nriqu3s11/thornhill | ec31eb06dd914bcb7fd22ff31386b40996656d94 | [
"MIT"
] | 1 | 2022-01-09T18:07:42.000Z | 2022-01-09T18:07:42.000Z | #include "interrupt.hpp"
uint8_t ThornhillInterrupt::generateIdtDescriptorType(CpuIdtGateType gateType,
CpuPrivilegeLevel privilegeLevel,
bool storageSegment, bool interruptPresent) {
return (interruptPresent << 7) | (privilegeLevel << 5) | (storageSegment << 4) | gateType;
};
void ThornhillInterrupt::setAllowInterrupts(bool allowInterrupts) {
if (allowInterrupts)
__asm__ __volatile__("sti");
else
__asm__ __volatile__("cli");
}
void ThornhillInterrupt::setupInterrupts() {
// Setup IDT gates.
setIdtGate(0, (uint64_t)isr0);
setIdtGate(1, (uint64_t)isr1);
setIdtGate(2, (uint64_t)isr2);
setIdtGate(3, (uint64_t)isr3);
setIdtGate(4, (uint64_t)isr4);
setIdtGate(5, (uint64_t)isr5);
setIdtGate(6, (uint64_t)isr6);
setIdtGate(7, (uint64_t)isr7);
setIdtGate(8, (uint64_t)isr8);
setIdtGate(9, (uint64_t)isr9);
setIdtGate(10, (uint64_t)isr10);
setIdtGate(11, (uint64_t)isr11);
setIdtGate(12, (uint64_t)isr12);
setIdtGate(13, (uint64_t)isr13);
setIdtGate(14, (uint64_t)isr14);
setIdtGate(15, (uint64_t)isr15);
setIdtGate(16, (uint64_t)isr16);
setIdtGate(17, (uint64_t)isr17);
setIdtGate(18, (uint64_t)isr18);
setIdtGate(19, (uint64_t)isr19);
setIdtGate(20, (uint64_t)isr20);
setIdtGate(21, (uint64_t)isr21);
setIdtGate(22, (uint64_t)isr22);
setIdtGate(23, (uint64_t)isr23);
setIdtGate(24, (uint64_t)isr24);
setIdtGate(25, (uint64_t)isr25);
setIdtGate(26, (uint64_t)isr26);
setIdtGate(27, (uint64_t)isr27);
setIdtGate(28, (uint64_t)isr28);
setIdtGate(29, (uint64_t)isr29);
setIdtGate(30, (uint64_t)isr30);
setIdtGate(31, (uint64_t)isr31);
// Remap the PIC.
ThornhillIO::writeByteToPort(0x20, 0x11);
ThornhillIO::writeByteToPort(0xA0, 0x11);
ThornhillIO::writeByteToPort(0x21, 0x20);
ThornhillIO::writeByteToPort(0xA1, 0x28);
ThornhillIO::writeByteToPort(0x21, 0x04);
ThornhillIO::writeByteToPort(0xA1, 0x02);
ThornhillIO::writeByteToPort(0x21, 0x01);
ThornhillIO::writeByteToPort(0xA1, 0x01);
ThornhillIO::writeByteToPort(0x21, 0x00);
ThornhillIO::writeByteToPort(0xA1, 0x00);
// Install the IRQs.
setIdtGate(32, (uint64_t)irq0);
setIdtGate(33, (uint64_t)irq1);
setIdtGate(34, (uint64_t)irq2);
setIdtGate(35, (uint64_t)irq3);
setIdtGate(36, (uint64_t)irq4);
setIdtGate(37, (uint64_t)irq5);
setIdtGate(38, (uint64_t)irq6);
setIdtGate(39, (uint64_t)irq7);
setIdtGate(40, (uint64_t)irq8);
setIdtGate(41, (uint64_t)irq9);
setIdtGate(42, (uint64_t)irq10);
setIdtGate(43, (uint64_t)irq11);
setIdtGate(44, (uint64_t)irq12);
setIdtGate(45, (uint64_t)irq13);
setIdtGate(46, (uint64_t)irq14);
setIdtGate(47, (uint64_t)irq15);
// Setup IDT.
idt_register.base = (uint64_t)&idt;
idt_register.limit = IDT_ENTRIES * sizeof(idt_descriptor_t) - 1;
__asm__ __volatile__("lidt (%0)" : : "r"(&idt_register));
}
void ThornhillInterrupt::setIdtGate(int gateNumber, uint64_t handler) {
idt[gateNumber].offset15_0 = offset15_0(handler);
idt[gateNumber].selector = TH_KERNEL_CODE_SEGMENT;
idt[gateNumber].null_descriptor = 0;
idt[gateNumber].type = generateIdtDescriptorType(IDT_GATE_32BIT_INT);
idt[gateNumber].offset31_16 = offset31_16(handler);
idt[gateNumber].offset63_32 = offset63_32(handler);
idt[gateNumber].null_descriptor_2 = 0;
}
void ThornhillInterrupt::registerInterruptHandler(uint8_t interrupt, interrupt_handler_t handler) {
interruptHandlers[interrupt] = handler;
}
bool ThornhillInterrupt::hasHandlerFor(uint8_t interrupt) {
return interruptHandlers[interrupt] != 0;
}
interrupt_handler_t ThornhillInterrupt::getHandlerFor(uint8_t interrupt) {
return interruptHandlers[interrupt];
}
interrupt_handler_t ThornhillInterrupt::interruptHandlers[256]; | 35.827273 | 99 | 0.70033 | andr3h3nriqu3s11 |
daef3df0ebc8b08bd9ef0312656b9b3c9be50397 | 31,833 | hpp | C++ | clipper-parm/src/libclipper/include/clipper/task_executor.hpp | mukkachaitanya/parity-models | 9f336a67798934d29592aca471dff6ad047473f6 | [
"Apache-2.0"
] | 32 | 2019-09-11T16:49:58.000Z | 2022-01-26T15:40:40.000Z | clipper-parm/src/libclipper/include/clipper/task_executor.hpp | mukkachaitanya/parity-models | 9f336a67798934d29592aca471dff6ad047473f6 | [
"Apache-2.0"
] | 5 | 2019-11-10T16:13:40.000Z | 2022-01-13T01:31:51.000Z | clipper-parm/src/libclipper/include/clipper/task_executor.hpp | mukkachaitanya/parity-models | 9f336a67798934d29592aca471dff6ad047473f6 | [
"Apache-2.0"
] | 9 | 2019-09-03T14:05:26.000Z | 2021-12-22T07:17:27.000Z | #ifndef CLIPPER_LIB_TASK_EXECUTOR_H
#define CLIPPER_LIB_TASK_EXECUTOR_H
#include <chrono>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <boost/optional.hpp>
#include <redox.hpp>
#include <folly/futures/Future.h>
#include <clipper/config.hpp>
#include <clipper/containers.hpp>
#include <clipper/decoder.hpp>
#include <clipper/datatypes.hpp>
#include <clipper/logging.hpp>
#include <clipper/metrics.hpp>
#include <clipper/model_queue.hpp>
#include <clipper/redis.hpp>
#include <clipper/rpc_service.hpp>
#include <clipper/threadpool.hpp>
#include <clipper/util.hpp>
namespace clipper {
const std::string LOGGING_TAG_TASK_EXECUTOR = "TASKEXECUTOR";
class ModelMetrics {
public:
explicit ModelMetrics(VersionedModelId model)
: model_(model),
latency_(metrics::MetricsRegistry::get_metrics().create_histogram(
"model:" + model.serialize() + ":prediction_latency",
"microseconds", 4096)),
throughput_(metrics::MetricsRegistry::get_metrics().create_meter(
"model:" + model.serialize() + ":prediction_throughput")),
num_predictions_(metrics::MetricsRegistry::get_metrics().create_counter(
"model:" + model.serialize() + ":num_predictions")),
cache_hit_ratio_(
metrics::MetricsRegistry::get_metrics().create_ratio_counter(
"model:" + model.serialize() + ":cache_hit_ratio")),
batch_size_(metrics::MetricsRegistry::get_metrics().create_histogram(
"model:" + model.serialize() + ":batch_size", "queries", 4096)) {}
~ModelMetrics() = default;
ModelMetrics(const ModelMetrics &) = default;
ModelMetrics &operator=(const ModelMetrics &) = default;
ModelMetrics(ModelMetrics &&) = default;
ModelMetrics &operator=(ModelMetrics &&) = default;
VersionedModelId model_;
std::shared_ptr<metrics::Histogram> latency_;
std::shared_ptr<metrics::Meter> throughput_;
std::shared_ptr<metrics::Counter> num_predictions_;
std::shared_ptr<metrics::RatioCounter> cache_hit_ratio_;
std::shared_ptr<metrics::Histogram> batch_size_;
};
class CacheEntry {
public:
CacheEntry();
~CacheEntry() = default;
CacheEntry(const CacheEntry &) = delete;
CacheEntry &operator=(const CacheEntry &) = delete;
CacheEntry(CacheEntry &&) = default;
CacheEntry &operator=(CacheEntry &&) = default;
bool completed_ = false;
bool backup_completed_ = false;
bool used_ = true;
Output value_;
Output backup_value_;
std::vector<folly::Promise<Output>> value_promises_;
std::vector<folly::Promise<Output>> backup_value_promises_;
};
// A cache page is a pair of <hash, entry_size>
using CachePage = std::pair<long, long>;
class PredictionCache {
public:
PredictionCache(size_t size_bytes);
std::pair<folly::Future<Output>, folly::Future<Output>> fetch(PredictTask& t);
void put(size_t cache_id, const Output &output, bool redundant);
private:
size_t hash(const VersionedModelId &model, size_t input_hash) const;
void insert_entry(PredictTask&, CacheEntry &value);
void evict_entries(long space_needed_bytes);
std::mutex m_;
const size_t max_size_bytes_;
size_t size_bytes_ = 0;
size_t cur_id_ = 0;
size_t max_entries_ = 1000;
std::queue<size_t> to_evict_list_;
std::unordered_map<size_t, CacheEntry> entries_;
std::vector<long> page_buffer_;
size_t page_buffer_index_ = 0;
std::shared_ptr<metrics::Counter> lookups_counter_;
std::shared_ptr<metrics::RatioCounter> hit_ratio_;
};
struct DeadlineCompare {
bool operator()(const std::pair<Deadline, PredictTask> &lhs,
const std::pair<Deadline, PredictTask> &rhs) {
return lhs.first > rhs.first;
}
};
class InflightMessage {
public:
InflightMessage(
const std::chrono::time_point<std::chrono::system_clock> queue_time,
const VersionedModelId model,
const std::shared_ptr<PredictionData> input,
const bool discard_result,
const size_t cache_id)
: queue_time_(std::move(queue_time)),
sent_(false),
model_(std::move(model)),
input_(std::move(input)),
discard_result_(discard_result),
cache_id_(cache_id) {}
void add_dispatch_info(
const std::chrono::time_point<std::chrono::system_clock> send_time,
const int container_id, const int replica_id) {
send_time_ = std::move(send_time);
sent_ = true;
container_id_ = container_id;
replica_id_ = replica_id;
}
// Default copy and move constructors
InflightMessage(const InflightMessage &) = default;
InflightMessage(InflightMessage &&) = default;
// Default assignment operators
InflightMessage &operator=(const InflightMessage &) = default;
InflightMessage &operator=(InflightMessage &&) = default;
std::chrono::time_point<std::chrono::system_clock> parity_time_;
std::chrono::time_point<std::chrono::system_clock> queue_time_;
std::chrono::time_point<std::chrono::system_clock> send_time_;
bool sent_;
int container_id_;
VersionedModelId model_;
int replica_id_;
std::shared_ptr<PredictionData> input_;
bool discard_result_;
size_t cache_id_;
};
// Class for encompassing a batch of InflightMessages
class InflightMessageBatch {
public:
InflightMessageBatch() : redundant_(false) {}
InflightMessageBatch(bool redundant, unsigned int batch_id) :
redundant_(redundant),
batch_id_(batch_id) {}
std::vector<InflightMessage> messages_;
bool redundant_;
unsigned int batch_id_;
};
class TaskExecutor {
public:
~TaskExecutor() { active_->store(false); };
explicit TaskExecutor(RedundancyType redundancy_mode, QueueType queue_mode,
unsigned int num_models, unsigned int num_redundant_models,
unsigned int batch_size)
: active_(std::make_shared<std::atomic_bool>(true)),
active_containers_(std::make_shared<ActiveContainers>()),
rpc_(std::make_unique<rpc::RPCService>()),
cache_(std::make_unique<PredictionCache>(
get_config().get_prediction_cache_size())),
model_queues_({}),
model_metrics_({}),
redundancy_mode_(redundancy_mode),
queue_mode_(queue_mode),
num_models_(num_models),
num_redundant_models_(num_redundant_models),
batch_size_(batch_size) {
log_debug(LOGGING_TAG_TASK_EXECUTOR, "TaskExecutor started");
if (redundancy_mode_ == RedundancyType::NO_RED) {
group_size_ = 1;
} else if (redundancy_mode_ == RedundancyType::CHEAP) {
group_size_ = 2;
} else {
size_t ec_k_val = num_models_ / num_redundant_models_;
group_size_ = ec_k_val + 1;
}
decoder_.reset(
new SubtractionDecoder(num_models, num_redundant_models_,
group_size_-1, &model_queues_, queue_mode_));
rpc_->start(
"*", RPC_SERVICE_PORT, [ this, task_executor_valid = active_ ](
VersionedModelId model, int replica_id) {
if (*task_executor_valid) {
on_container_ready(model, replica_id);
} else {
log_debug(LOGGING_TAG_TASK_EXECUTOR,
"Not running on_container_ready callback because "
"TaskExecutor has been destroyed.");
}
},
[ this, task_executor_valid = active_ ](rpc::RPCResponse & response) {
if (*task_executor_valid) {
on_response_recv(std::move(response));
} else {
log_debug(LOGGING_TAG_TASK_EXECUTOR,
"Not running on_response_recv callback because "
"TaskExecutor has been destroyed.");
}
},
[ this, task_executor_valid = active_ ](VersionedModelId model,
int replica_id) {
if (*task_executor_valid) {
on_remove_container(model, replica_id);
} else {
log_debug(LOGGING_TAG_TASK_EXECUTOR,
"Not running on_remove_container callback because "
"TaskExecutor has been destroyed.");
}
});
Config &conf = get_config();
while (!redis_connection_.connect(conf.get_redis_address(),
conf.get_redis_port())) {
log_error(LOGGING_TAG_TASK_EXECUTOR,
"TaskExecutor failed to connect to redis",
"Retrying in 1 second...");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
while (!redis_subscriber_.connect(conf.get_redis_address(),
conf.get_redis_port())) {
log_error(LOGGING_TAG_TASK_EXECUTOR,
"TaskExecutor subscriber failed to connect to redis",
"Retrying in 1 second...");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
redis::send_cmd_no_reply<std::string>(
redis_connection_, {"CONFIG", "SET", "notify-keyspace-events", "AKE"});
redis::subscribe_to_model_changes(redis_subscriber_, [
this, task_executor_valid = active_
](const std::string &key, const std::string &event_type) {
if (event_type == "hset" && *task_executor_valid) {
auto model_info =
clipper::redis::get_model_by_key(redis_connection_, key);
VersionedModelId model_id = VersionedModelId(
model_info["model_name"], model_info["model_version"]);
int batch_size = DEFAULT_BATCH_SIZE;
auto batch_size_search = model_info.find("batch_size");
if (batch_size_search != model_info.end()) {
batch_size = std::stoi(model_info["batch_size"]);
}
log_debug_formatted(LOGGING_TAG_TASK_EXECUTOR,
"Registered batch size of {} for model {}:{}",
batch_size, model_id.get_name(), model_id.get_id());
active_containers_->register_batch_size(model_id, batch_size);
}
});
redis::subscribe_to_container_changes(
redis_subscriber_,
// event_type corresponds to one of the Redis event types
// documented in https://redis.io/topics/notifications.
[ this, task_executor_valid = active_ ](const std::string &key,
const std::string &event_type) {
log_debug(LOGGING_TAG_TASK_EXECUTOR, "got subscribe_to_changes callback");
if (event_type == "hset" && *task_executor_valid) {
auto container_info =
redis::get_container_by_key(redis_connection_, key);
VersionedModelId vm = VersionedModelId(
container_info["model_name"], container_info["model_version"]);
unsigned int replica_id = std::stoi(container_info["model_replica_id"]);
bool redundant = replica_id >= num_models_;
active_containers_->add_container(
vm, std::stoi(container_info["zmq_connection_id"]), replica_id,
redundant, parse_input_type(container_info["input_type"]));
auto model_info = redis::get_model(redis_connection_, vm);
int batch_size = DEFAULT_BATCH_SIZE;
auto batch_size_search = model_info.find("batch_size");
if (batch_size_search != model_info.end()) {
batch_size = std::stoi(batch_size_search->second);
}
active_containers_->register_batch_size(vm, batch_size);
//EstimatorFittingThreadPool::create_queue(vm, replica_id);
TaskExecutionThreadPool::create_queue(vm, replica_id);
TaskExecutionThreadPool::submit_job(
vm, replica_id, [this, vm, replica_id]() {
on_container_ready(vm, replica_id);
});
bool created_queue = create_model_queue_if_necessary(vm);
if (created_queue) {
log_debug_formatted(LOGGING_TAG_TASK_EXECUTOR,
"Created queue for new model: {} : {}",
vm.get_name(), vm.get_id());
}
} else if (!*task_executor_valid) {
log_debug(LOGGING_TAG_TASK_EXECUTOR,
"Not running TaskExecutor's "
"subscribe_to_container_changes callback because "
"TaskExecutor has been destroyed.");
}
});
throughput_meter_ = metrics::MetricsRegistry::get_metrics().create_meter(
"internal:aggregate_model_throughput");
predictions_counter_ =
metrics::MetricsRegistry::get_metrics().create_counter(
"internal:aggregate_num_predictions");
}
// Disallow copy
TaskExecutor(const TaskExecutor &other) = delete;
TaskExecutor &operator=(const TaskExecutor &other) = delete;
TaskExecutor(TaskExecutor &&other) = default;
TaskExecutor &operator=(TaskExecutor &&other) = default;
typedef vector<folly::Future<Output>> OutputFutures;
std::tuple<OutputFutures, OutputFutures> schedule_predictions(
std::vector<PredictTask> tasks) {
predictions_counter_->increment(tasks.size());
std::vector<folly::Future<Output>> output_futures;
std::vector<folly::Future<Output>> backup_output_futures;
for (PredictTask& t : tasks) {
// add each task to the queue corresponding to its associated model
boost::shared_lock<boost::shared_mutex> lock(model_queues_mutex_);
auto model_queue_entry = model_queues_.find(t.model_);
if (model_queue_entry != model_queues_.end()) {
auto cache_results = cache_->fetch(t);
auto cache_result = std::move(cache_results.first);
auto backup_cache_result = std::move(cache_results.second);
if (cache_result.isReady()) {
output_futures.push_back(std::move(cache_result));
boost::shared_lock<boost::shared_mutex> model_metrics_lock(
model_metrics_mutex_);
auto cur_model_metric_entry = model_metrics_.find(t.model_);
if (cur_model_metric_entry != model_metrics_.end()) {
auto cur_model_metric = cur_model_metric_entry->second;
cur_model_metric.cache_hit_ratio_->increment(1, 1);
}
}
else if (active_containers_->get_replicas_for_model(t.model_).size() ==
0) {
log_error_formatted(LOGGING_TAG_TASK_EXECUTOR,
"No active model containers for model: {} : {}",
t.model_.get_name(), t.model_.get_id());
} else {
output_futures.push_back(std::move(cache_result));
t.recv_time_ = std::chrono::system_clock::now();
log_debug_formatted(LOGGING_TAG_TASK_EXECUTOR,
"Adding task to queue. QueryID: {}, model: {}",
t.query_id_, t.model_.serialize());
model_queue_entry->second->add_task(t, [this](Batch& batch) {
auto queue_time = std::chrono::system_clock::now();
InflightMessageBatch cur_batch(batch.redundant_, batch.batch_id_);
for (auto b : batch.tasks_) {
cur_batch.messages_.emplace_back(b.recv_time_, b.model_, b.input_, b.artificial_, b.cache_id_);
}
if (batch.tasks_[0].is_parity_) {
for (size_t i = 0; i < cur_batch.messages_.size(); i++) {
cur_batch.messages_[i].parity_time_ = batch.tasks_[i].parity_time_;
}
}
inflight_messages_mutex_.lock();
inflight_messages_.emplace(batch.batch_id_, cur_batch);
inflight_messages_mutex_.unlock();
});
boost::shared_lock<boost::shared_mutex> model_metrics_lock(
model_metrics_mutex_);
auto cur_model_metric_entry = model_metrics_.find(t.model_);
if (cur_model_metric_entry != model_metrics_.end()) {
auto cur_model_metric = cur_model_metric_entry->second;
cur_model_metric.cache_hit_ratio_->increment(0, 1);
}
}
// We don't explicitly add a backup task here, but rather let
// the underlying queue manage it.
backup_output_futures.push_back(std::move(backup_cache_result));
} else {
log_debug_formatted(LOGGING_TAG_TASK_EXECUTOR,
"model_queues_.size() = {}",
model_queues_.size());
for (auto kv : model_queues_)
log_error_formatted(LOGGING_TAG_TASK_EXECUTOR,
"modle_queue contains key {} : {}",
kv.first.get_name(), kv.first.get_id());
log_error_formatted(LOGGING_TAG_TASK_EXECUTOR,
"Received task for unknown model: {} : {}",
t.model_.get_name(), t.model_.get_id());
}
}
return std::make_tuple(std::move(output_futures),
std::move(backup_output_futures));
}
std::vector<folly::Future<FeedbackAck>> schedule_feedback(
const std::vector<FeedbackTask> tasks) {
UNUSED(tasks);
// TODO Implement
return {};
}
private:
// active_containers_ is shared with the RPC service so it can add new
// containers to the collection when they connect
std::shared_ptr<std::atomic_bool> active_;
std::shared_ptr<ActiveContainers> active_containers_;
std::unique_ptr<rpc::RPCService> rpc_;
std::unique_ptr<PredictionCache> cache_;
redox::Redox redis_connection_;
redox::Subscriber redis_subscriber_;
std::mutex inflight_messages_mutex_;
std::unordered_map<unsigned int, InflightMessageBatch> inflight_messages_;
std::unordered_map<int, unsigned int> rpc_id_to_batch_id_;
std::shared_ptr<metrics::Counter> predictions_counter_;
std::shared_ptr<metrics::Meter> throughput_meter_;
boost::shared_mutex model_queues_mutex_;
std::unordered_map<VersionedModelId, std::shared_ptr<ModelQueue>>
model_queues_;
boost::shared_mutex model_metrics_mutex_;
std::unordered_map<VersionedModelId, ModelMetrics> model_metrics_;
// Type of redundancy that should be used.
const RedundancyType redundancy_mode_;
// Load-balancing strategy that should be used.
const QueueType queue_mode_;
// Number of non-redundant models
const unsigned int num_models_;
// Number of batches in a group. Should be as follows:
// NO_RED: 1
// CHEAP: 2
// CODED: ec_k_ + 1
// This should really be const, but my assignment pattern does not lend well
// to the requirements of const variables.
size_t group_size_;
// Number of redundant models
const unsigned int num_redundant_models_;
// Batch size to be enforced
const unsigned int batch_size_;
std::unique_ptr<Decoder> decoder_;
static constexpr int INITIAL_MODEL_QUEUES_MAP_SIZE = 100;
bool create_model_queue_if_necessary(const VersionedModelId &model_id) {
log_debug_formatted(LOGGING_TAG_PARM,
"create_model_queue_if_necessary for {}:{}",
model_id.get_name(), model_id.get_id());
// Adds a new <model_id, task_queue> entry to the queues map, if one
// does not already exist
boost::unique_lock<boost::shared_mutex> l(model_queues_mutex_);
bool queue_added = (model_queues_.find(model_id) == model_queues_.end());
if (queue_added) {
auto queue_emplace = model_queues_.emplace(
std::make_pair(model_id, std::make_shared<ModelQueue>(
redundancy_mode_, queue_mode_, num_models_,
num_redundant_models_, batch_size_)));
assert(queue_emplace.second);
boost::unique_lock<boost::shared_mutex> l(model_metrics_mutex_);
model_metrics_.insert(std::make_pair(model_id, ModelMetrics(model_id)));
}
return queue_added;
}
void on_container_ready(VersionedModelId model_id, int replica_id) {
std::shared_ptr<ModelContainer> container =
active_containers_->get_model_replica(model_id, replica_id);
if (!container) {
throw std::runtime_error(
"TaskExecutor failed to find previously registered active "
"container!");
}
boost::shared_lock<boost::shared_mutex> l(model_queues_mutex_);
auto model_queue_entry = model_queues_.find(container->model_);
if (model_queue_entry == model_queues_.end()) {
throw std::runtime_error(
"Failed to find model queue associated with a previously registered "
"container!");
}
std::shared_ptr<ModelQueue> current_model_queue = model_queue_entry->second;
// NOTE: It is safe to unlock here because we copy the shared_ptr to
// the ModelQueue object so even if that entry in the map gets deleted,
// the ModelQueue object won't be destroyed until our copy of the pointer
// goes out of scope.
l.unlock();
Batch batch = current_model_queue->get_batch(container);
if (batch.tasks_.size() > 0) {
// move the lock up here, so that nothing can pull from the
// inflight_messages_
// map between the time a message is sent and when it gets inserted
// into the map
std::unique_lock<std::mutex> l(inflight_messages_mutex_);
rpc::PredictionRequest prediction_request(container->input_type_);
std::stringstream query_ids_in_batch;
std::chrono::time_point<std::chrono::system_clock> current_time =
std::chrono::system_clock::now();
InflightMessageBatch& cur_batch = inflight_messages_[batch.batch_id_];
for (size_t i = 0; i < cur_batch.messages_.size(); i++) {
prediction_request.add_input(cur_batch.messages_[i].input_);
cur_batch.messages_[i].add_dispatch_info(current_time, container->container_id_, container->replica_id_);
query_ids_in_batch << batch.tasks_[i].query_id_ << " ";
}
int message_id = rpc_->send_message(prediction_request.serialize(),
container->container_id_);
log_debug_formatted(LOGGING_TAG_TASK_EXECUTOR,
"Sending batch to model: {} replica {}."
"Batch size: {}. Query IDs: {}",
model_id.serialize(), std::to_string(replica_id),
std::to_string(batch.tasks_.size()),
query_ids_in_batch.str());
rpc_id_to_batch_id_.emplace(message_id, batch.batch_id_);
} else {
log_error_formatted(
LOGGING_TAG_TASK_EXECUTOR,
"ModelQueue returned empty batch for model {}, replica {}",
model_id.serialize(), std::to_string(replica_id));
}
}
void process_received(InflightMessageBatch& batch,
std::vector<std::shared_ptr<PredictionData>>& parsed_response_outputs,
bool is_reconstruction) {
log_debug_formatted(LOGGING_TAG_PARM, "TaskExecutor::process_received batch_id={}, is_recon={}",
batch.batch_id_, is_reconstruction);
size_t batch_size = batch.messages_.size();
throughput_meter_->mark(batch_size);
std::chrono::time_point<std::chrono::system_clock> current_time =
std::chrono::system_clock::now();
InflightMessage &first_message = batch.messages_[0];
const VersionedModelId &cur_model = first_message.model_;
boost::optional<ModelMetrics> cur_model_metric;
auto cur_model_metric_entry = model_metrics_.find(cur_model);
if (cur_model_metric_entry != model_metrics_.end()) {
cur_model_metric = cur_model_metric_entry->second;
}
// Only do the following if not a reconstruction because we currently don't
// have a good way of tracking model replicas in our redundancy implementation.
if (!is_reconstruction) {
const int cur_replica_id = first_message.replica_id_;
auto batch_latency = current_time - first_message.send_time_;
long long batch_latency_micros =
std::chrono::duration_cast<std::chrono::microseconds>(batch_latency)
.count();
// Because an RPCResponse is guaranteed to contain data received from
// a single model container, the processing container for the first
// InflightMessage in the batch is the same processing container
// for all InflightMessage objects in the batch
std::shared_ptr<ModelContainer> processing_container =
active_containers_->get_model_replica(cur_model, cur_replica_id);
processing_container->add_processing_datapoint(batch_size,
batch_latency_micros);
if (cur_model_metric) {
(*cur_model_metric).throughput_->mark(batch_size);
(*cur_model_metric).num_predictions_->increment(batch_size);
(*cur_model_metric).batch_size_->insert(batch_size);
}
}
for (size_t batch_num = 0; batch_num < batch_size; ++batch_num) {
InflightMessage completed_msg = batch.messages_[batch_num];
if (!completed_msg.discard_result_) {
cache_->put(completed_msg.cache_id_,
Output{parsed_response_outputs[batch_num],
{completed_msg.model_}}, is_reconstruction);
}
auto task_latency = current_time - completed_msg.queue_time_;
long task_latency_micros =
std::chrono::duration_cast<std::chrono::microseconds>(task_latency)
.count();
if (!is_reconstruction && cur_model_metric) {
(*cur_model_metric)
.latency_->insert(static_cast<int64_t>(task_latency_micros));
}
if (completed_msg.sent_) {
auto queue_latency = completed_msg.send_time_ - completed_msg.queue_time_;
long latency_micros =
std::chrono::duration_cast<std::chrono::microseconds>(queue_latency).count();
log_info_formatted(LOGGING_TAG_EC_METRICS,
"QUEUE_LATENCY:group_id={},batch_id={},query_id={},batch_size={},is_reconstruction={},latency_micros={}",
(batch.batch_id_ / group_size_), batch.batch_id_, batch_num,
batch_size, is_reconstruction, latency_micros);
auto model_latency = current_time - completed_msg.send_time_;
latency_micros =
std::chrono::duration_cast<std::chrono::microseconds>(model_latency).count();
log_debug_formatted(LOGGING_TAG_EC_METRICS,
"MODEL_LATENCY:group_id={},batch_id={},query_id={},batch_size={},is_reconstruction={},latency_micros={}",
(batch.batch_id_ / group_size_), batch.batch_id_, batch_num,
batch_size, is_reconstruction, latency_micros);
}
log_info_formatted(LOGGING_TAG_EC_METRICS,
"E2E_LATENCY:group_id={},batch_id={},query_id={},batch_size={},is_reconstruction={},latency_micros={}",
(batch.batch_id_ / group_size_), batch.batch_id_, batch_num,
batch_size, is_reconstruction, task_latency_micros);
}
}
void on_response_recv(rpc::RPCResponse response) {
std::unique_lock<std::mutex> l(inflight_messages_mutex_);
log_debug_formatted(LOGGING_TAG_PARM, "Entered on_response_recv {}", response.first);
auto if_id = rpc_id_to_batch_id_[response.first];
auto batch = inflight_messages_[if_id];
auto model_id = batch.messages_[0].model_;
inflight_messages_.erase(if_id);
rpc_id_to_batch_id_.erase(response.first);
rpc::PredictionResponse parsed_response =
rpc::PredictionResponse::deserialize_prediction_response(
std::move(response.second));
assert(parsed_response.outputs_.size() == batch.messages_.size());
std::vector<std::shared_ptr<PredictionData>> copy_parsed_response_outputs;
for (size_t i = 0; i < parsed_response.outputs_.size(); i++) {
size_t size_bytes = parsed_response.outputs_[i]->byte_size();
void* new_data = malloc(size_bytes);
memcpy(new_data, (void*)get_data<uint8_t>(parsed_response.outputs_[i]).get(), size_bytes);
UniquePoolPtr<void> data(new_data, free);
copy_parsed_response_outputs.push_back(std::make_shared<ByteVector>(std::move(data), size_bytes));
}
// TODO: Probably can refactor to only hold this lock during process_received.
// It currently will be held over both potential calls (this one and the potential
// call from decoding).
boost::shared_lock<boost::shared_mutex> metrics_lock(model_metrics_mutex_);
if (!batch.redundant_ && batch.messages_.size() > 0) {
process_received(batch, parsed_response.outputs_, false);
if (redundancy_mode_ == RedundancyType::CHEAP) {
// If the redundant batch has not yet been dequeued, remove it. The
// redundant batch will have id batch_id_ + 1.
model_queues_.at(model_id)->remove_tasks_with_batch_id_lte(batch.batch_id_ + 1);
}
}
if (redundancy_mode_ == RedundancyType::CODED) {
auto decode_or_none = decoder_->add_prediction(batch.batch_id_,
batch.messages_[0].model_,
std::move(copy_parsed_response_outputs));
if (std::get<0>(decode_or_none) == true) {
auto decoded_batch = inflight_messages_[std::get<1>(decode_or_none)];
process_received(decoded_batch, std::get<2>(decode_or_none), true);
// We do not delete the inflight message
}
} else if (redundancy_mode_ == RedundancyType::CHEAP) {
if (batch.redundant_) {
// If the "main" batch has not yet been dequeued, remove it. The
// redundant batch will have id batch_id_ - 1.
model_queues_.at(model_id)->remove_tasks_with_batch_id_lte(batch.batch_id_ - 1);
// Decrement batch_id_ because this redundant batch is a response to
// the queried batch with id batch_id_ - 1.
batch.batch_id_--;
process_received(batch, parsed_response.outputs_, true);
}
}
if (batch.redundant_) {
std::chrono::time_point<std::chrono::system_clock> current_time = std::chrono::system_clock::now();
size_t batch_size = batch.messages_.size();
for (size_t batch_num = 0; batch_num < batch_size; ++batch_num) {
InflightMessage completed_msg = batch.messages_[batch_num];
auto queue_latency = completed_msg.send_time_ - completed_msg.queue_time_;
long latency_micros =
std::chrono::duration_cast<std::chrono::microseconds>(queue_latency).count();
log_info_formatted(LOGGING_TAG_EC_METRICS,
"QUEUE_LATENCY_PARITY:group_id={},batch_id={},query_id={},batch_size={},latency_micros={}",
(batch.batch_id_ / group_size_), batch.batch_id_, batch_num,
batch_size, latency_micros);
auto model_latency = current_time - completed_msg.send_time_;
latency_micros =
std::chrono::duration_cast<std::chrono::microseconds>(model_latency).count();
log_debug_formatted(LOGGING_TAG_EC_METRICS,
"MODEL_LATENCY_PARITY:group_id={},batch_id={},query_id={},batch_size={},latency_micros={}",
(batch.batch_id_ / group_size_), batch.batch_id_, batch_num,
batch_size, latency_micros);
auto task_latency = current_time - completed_msg.parity_time_;
long task_latency_micros =
std::chrono::duration_cast<std::chrono::microseconds>(task_latency)
.count();
log_info_formatted(LOGGING_TAG_EC_METRICS,
"E2E_LATENCY_PARITY:group_id={},batch_id={},query_id={},batch_size={},latency_micros={}",
(batch.batch_id_ / group_size_), batch.batch_id_, batch_num,
batch_size, task_latency_micros);
}
}
}
void on_remove_container(VersionedModelId model_id, int replica_id) {
// remove the given model_id from active_containers_
active_containers_->remove_container(model_id, replica_id);
}
};
} // namespace clipper
#endif // CLIPPER_LIB_TASK_EXECUTOR_H
| 42.728859 | 131 | 0.660667 | mukkachaitanya |
daf14555849e1909177fc404eb9a1937df729096 | 783 | cpp | C++ | MultiThreading/Signal.cpp | d3m37r4/VoiceTranscoder | a9ae70b436e26f6589ac7841749ce281c227bb2c | [
"Unlicense"
] | 19 | 2019-11-26T13:49:34.000Z | 2021-12-21T03:27:33.000Z | MultiThreading/Signal.cpp | d3m37r4/VoiceTranscoder | a9ae70b436e26f6589ac7841749ce281c227bb2c | [
"Unlicense"
] | 17 | 2019-11-27T11:16:26.000Z | 2021-02-04T07:21:01.000Z | MultiThreading/Signal.cpp | andrewlindberg/VoiceTranscoder | a9ae70b436e26f6589ac7841749ce281c227bb2c | [
"Unlicense"
] | 7 | 2019-11-26T13:09:34.000Z | 2020-12-13T05:48:27.000Z | #include "Signal.h"
#ifdef _WIN32
#include <Windows.h>
#elif defined __linux__
#include <pthread.h>
#endif
#ifdef _WIN32
Signal::Signal() {
m_hEvent = CreateEvent(nullptr, FALSE/*TODO: or TRUE?*/, FALSE, nullptr);
}
Signal::~Signal() {
CloseHandle(m_hEvent);
}
void Signal::Raise() {
SetEvent(m_hEvent);
}
void Signal::Wait(Mutex *pMutex) {
ResetEvent(m_hEvent);
pMutex->Unlock();
WaitForSingleObject(m_hEvent, INFINITE);
pMutex->Lock();
}
#elif defined __linux__
Signal::Signal() {
pthread_cond_init(&m_cond, nullptr);
}
Signal::~Signal() {
pthread_cond_destroy(&m_cond);
}
void Signal::Raise() {
pthread_cond_signal(&m_cond);
}
void Signal::Wait(Mutex *pMutex) {
pthread_cond_wait(&m_cond, &pMutex->m_mutex);
}
#endif | 17.795455 | 75 | 0.669221 | d3m37r4 |
daf170dd7178d8aa213b14eeb05b9e35dc0f3352 | 6,720 | cxx | C++ | MITK/Plugins/uk.ac.ucl.cmic.breastsegmentation/src/internal/BreastSegmentationView.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 13 | 2018-07-28T13:36:38.000Z | 2021-11-01T19:17:39.000Z | MITK/Plugins/uk.ac.ucl.cmic.breastsegmentation/src/internal/BreastSegmentationView.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | null | null | null | MITK/Plugins/uk.ac.ucl.cmic.breastsegmentation/src/internal/BreastSegmentationView.cxx | NifTK/NifTK | 2358b333c89ff1bba1c232eecbbcdc8003305dfe | [
"BSD-3-Clause"
] | 10 | 2018-08-20T07:06:00.000Z | 2021-07-07T07:55:27.000Z | /*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Qmitk
#include "BreastSegmentationView.h"
// Qt
#include <QMessageBox>
#include <mitkDataStorageUtils.h>
#include <mitkNodePredicateDataType.h>
#include <_seg_EM.h>
const std::string BreastSegmentationView::VIEW_ID = "uk.ac.ucl.cmic.views.breastsegmentation";
// ---------------------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------------------
BreastSegmentationView::BreastSegmentationView()
{
m_Modified = false;
m_NumberOfGaussianComponents = 3;
m_NumberOfMultiSpectralComponents = 1;
m_NumberOfTimePoints = 1;
m_MaximumNumberOfIterations = 30;
m_BiasFieldCorrectionOrder = 4;
m_BiasFieldRatioThreshold = 0;
m_AdiposeGlandularAdjacencyCost = 0.15;
m_BackgroundGlandularAdjacencyCost = 6.;
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
BreastSegmentationView::~BreastSegmentationView()
{
}
// ---------------------------------------------------------------------------
// SetFocus()
// ---------------------------------------------------------------------------
void BreastSegmentationView::SetFocus()
{
m_Controls.m_InputImageComboBox->setFocus();
}
// ---------------------------------------------------------------------------
// GetNodes()
// ---------------------------------------------------------------------------
mitk::DataStorage::SetOfObjects::ConstPointer BreastSegmentationView::GetNodes()
{
mitk::DataStorage::Pointer dataStorage = this->GetDataStorage();
mitk::TNodePredicateDataType<mitk::Image>::Pointer isImage;
isImage = mitk::TNodePredicateDataType<mitk::Image>::New();
return dataStorage->GetSubset(isImage);
}
// ---------------------------------------------------------------------------
// CreateQtPartControl()
// ---------------------------------------------------------------------------
void BreastSegmentationView::CreateQtPartControl( QWidget *parent )
{
std::string name;
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi( parent );
// Initialise the input image combo box
mitk::DataStorage::SetOfObjects::ConstPointer nodes = GetNodes();
if ( nodes )
{
if (nodes->size() > 0)
{
for (unsigned int i=0; i<nodes->size(); i++)
{
(*nodes)[i]->GetStringProperty("name", name);
m_Controls.m_InputImageComboBox->insertItem(i, QString(name.c_str()));
}
}
}
this->CreateConnections();
}
// ---------------------------------------------------------------------------
// CreateConnections()
// ---------------------------------------------------------------------------
void BreastSegmentationView::CreateConnections()
{
connect(m_Controls.m_CancelButton, SIGNAL(pressed()), this,
SLOT(OnCancelButtonPressed()) );
connect(m_Controls.m_ExecuteButton, SIGNAL(pressed()), this,
SLOT(OnExecuteButtonPressed()) );
// Register data storage listeners
this->GetDataStorage()->AddNodeEvent
.AddListener( mitk::MessageDelegate1<BreastSegmentationView, const mitk::DataNode*>
( this, &BreastSegmentationView::OnNodeAdded ) );
this->GetDataStorage()->ChangedNodeEvent
.AddListener( mitk::MessageDelegate1<BreastSegmentationView, const mitk::DataNode*>
( this, &BreastSegmentationView::OnNodeChanged ) );
this->GetDataStorage()->RemoveNodeEvent
.AddListener( mitk::MessageDelegate1<BreastSegmentationView, const mitk::DataNode*>
( this, &BreastSegmentationView::OnNodeRemoved ) );
}
// ---------------------------------------------------------------------------
// OnCancelButtonPressed()
// ---------------------------------------------------------------------------
void BreastSegmentationView::OnCancelButtonPressed()
{
std::cout << "CancelButtonPressed" << std::endl;
}
// ---------------------------------------------------------------------------
// OnExecuteButtonPressed()
// ---------------------------------------------------------------------------
void BreastSegmentationView::OnExecuteButtonPressed()
{
std::cout << "ExecuteButtonPressed" << std::endl;
if ( ! m_Modified )
{
return;
}
seg_EM segmentation( m_NumberOfGaussianComponents,
m_NumberOfMultiSpectralComponents,
m_NumberOfTimePoints );
segmentation.SetMaximalIterationNumber( m_MaximumNumberOfIterations );
segmentation.Turn_BiasField_ON( m_BiasFieldCorrectionOrder, m_BiasFieldRatioThreshold);
}
// ---------------------------------------------------------------------------
// OnNodeAdded()
// ---------------------------------------------------------------------------
void BreastSegmentationView::OnNodeAdded(const mitk::DataNode* node)
{
int index;
std::string name;
node->GetStringProperty("name", name);
index = m_Controls.m_InputImageComboBox->findText( QString(name.c_str()) );
m_Controls.m_InputImageComboBox->addItem( QString(name.c_str()) );
}
// ---------------------------------------------------------------------------
// OnNodeRemoved()
// ---------------------------------------------------------------------------
void BreastSegmentationView::OnNodeRemoved(const mitk::DataNode* node)
{
int index;
std::string name;
node->GetStringProperty("name", name);
index = m_Controls.m_InputImageComboBox->findText( QString(name.c_str()) );
// If found, remove item
if ( index >= 0 )
{
m_Controls.m_InputImageComboBox->removeItem( index );
}
}
// ---------------------------------------------------------------------------
// OnNodeChanged()
// ---------------------------------------------------------------------------
void BreastSegmentationView::OnNodeChanged(const mitk::DataNode* node)
{
int index;
std::string name;
node->GetStringProperty("name", name);
index = m_Controls.m_InputImageComboBox->findText( QString(name.c_str()) );
// If this is the current item then the segmentation is out of date
if ( (index != -1) && (index == m_Controls.m_InputImageComboBox->currentIndex()) )
{
m_Modified = true;
}
}
| 27.883817 | 94 | 0.525893 | NifTK |
daf3ca43955a9ce0bc51721ec6b3c0661f33a7c6 | 1,020 | ipp | C++ | include/boost/net/impl/ssl_verify_callback.ipp | vinniefalco/ssl_verify | 9554e5534be7c9a95785c04e8635a58558090604 | [
"BSL-1.0"
] | 2 | 2019-02-01T10:44:39.000Z | 2019-02-26T18:17:44.000Z | include/boost/net/impl/ssl_verify_callback.ipp | vinniefalco/ssl_verify | 9554e5534be7c9a95785c04e8635a58558090604 | [
"BSL-1.0"
] | null | null | null | include/boost/net/impl/ssl_verify_callback.ipp | vinniefalco/ssl_verify | 9554e5534be7c9a95785c04e8635a58558090604 | [
"BSL-1.0"
] | 2 | 2021-05-06T16:50:56.000Z | 2022-01-16T23:04:40.000Z | //
// Copyright (c) 2017 Vinnie Falco (vinnie dot falco 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)
//
// Official repository: https://github.com/boostorg/ssl_verify
//
#ifndef BOOST_NET_SSL_VERIFY_CALLBACK_IPP
#define BOOST_NET_SSL_VERIFY_CALLBACK_IPP
#include <boost/utility/string_view.hpp>
namespace boost {
namespace net {
#if BOOST_NET_SSL_VERIFY_NO_HEADER_ONLY
namespace {
#endif
namespace detail {
namespace ssl_verify {
} // ssl_verify
} // detail
#if BOOST_NET_SSL_VERIFY_NO_HEADER_ONLY
} // anonymous
#endif
#if BOOST_NET_SSL_VERIFY_NO_HEADER_ONLY
static
#else
inline
#endif
bool
ssl_verify_callback::
operator()(
bool pre_verified,
boost::asio::ssl::verify_context& ctx) const
{
// Don't bother looking at certificates
// that have failed pre-verification.
if(! pre_verified)
return false;
return false;
}
} // net
} // boost
#endif
| 17.894737 | 79 | 0.742157 | vinniefalco |
daf4c18e3b9f4cb9dfa6d34e58018a6ef00c8711 | 1,041 | cc | C++ | cpp/mock/test2/test.cc | hackin-zhao/interesting_code | 25fecb716f5c8f9143ec2824bbf8996b347ce8a9 | [
"MIT"
] | 1 | 2021-09-22T10:56:13.000Z | 2021-09-22T10:56:13.000Z | cpp/mock/test2/test.cc | hackin-zhao/interesting_code | 25fecb716f5c8f9143ec2824bbf8996b347ce8a9 | [
"MIT"
] | 1 | 2022-02-15T03:53:47.000Z | 2022-02-15T03:53:47.000Z | cpp/mock/test2/test.cc | hackin-zhao/interesting_code | 25fecb716f5c8f9143ec2824bbf8996b347ce8a9 | [
"MIT"
] | null | null | null | #include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <stdio.h>
using namespace testing;
class Test {
public:
int getInterValue(void);
int getOneInterValue(int a);
};
class MockTest {
public:
MOCK_METHOD0(getInterValue, int());
MOCK_METHOD1(getOneInterValue, int(int a));
};
TEST(GtestMocktest, getInterValue)
{
MockTest test;
int value = 10;
EXPECT_CALL(test, getInterValue()).WillOnce(Return(value));
EXPECT_EQ(10, test.getInterValue());
}
TEST(GtestMockTest, getOneInterValue)
{
MockTest test;
int value = 10;
EXPECT_CALL(test, getOneInterValue(10)).WillOnce(Return(value));
EXPECT_EQ(10, test.getOneInterValue(10));
}
// Run all the tests that were declared with TEST()
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
/*
*********************************************************************
*
* 1. 对于测试 C 语言相关的函数,只需要把要测试的函数做一个class的封装即可。
*
*********************************************************************
*/
| 21.244898 | 70 | 0.596542 | hackin-zhao |
daf78f7d59eab72dcce1fe84543dba1db50576d1 | 18,686 | cpp | C++ | src/translator.cpp | saeenyoda/Gomm_Compiler | 64e238c8476663eb1b6fe76630b7bb6f8f919882 | [
"Unlicense",
"MIT"
] | null | null | null | src/translator.cpp | saeenyoda/Gomm_Compiler | 64e238c8476663eb1b6fe76630b7bb6f8f919882 | [
"Unlicense",
"MIT"
] | 1 | 2021-06-26T08:00:40.000Z | 2021-06-26T08:00:40.000Z | src/translator.cpp | saeenyoda/Gomm_Compiler | 64e238c8476663eb1b6fe76630b7bb6f8f919882 | [
"Unlicense",
"MIT"
] | null | null | null | /* GENERATES BOTH TAC AND MACHINE CODE*/
#include "translator.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "error_handler.h"
Translator *Translator::m_Instance;
Translator::Translator(const std::string &wListPath, const std::string &stPath)
{
run(wListPath, stPath);
}
std::vector<Translator::Token> Translator::loadTokens(const std::string &wListPath)
{
std::ifstream in(wListPath);
ASSERT(!in.is_open(), ERRORS::TOK_FILE_OPEN_ERROR);
std::string line;
std::vector<Translator::Token> toks;
while (std::getline(in, line))
{
std::string tok, id;
if (line[line.length() - 2] == '^')
{
tok = line.substr(1, line.find(',') - 1);
id = "^";
std::for_each(tok.begin(), tok.end(), [](char &c)
{ c = std::tolower(c); });
}
else
{
int s_idx = line.find(',') + 2;
tok = line.substr(s_idx, line.length() - s_idx - 1);
id = line.substr(1, line.find(',') - 1);
}
toks.push_back(Token(id, tok));
}
return toks;
}
std::vector<std::string> Translator::splitStr(const std::string &line, const char &delim)
{
size_t start;
size_t end = 0;
std::vector<std::string> out;
while ((start = line.find_first_not_of(delim, end)) != std::string::npos)
{
end = line.find(delim, start);
out.push_back(line.substr(start, end - start));
trim(out[out.size() - 1]);
}
return out;
}
void Translator::loadST(const std::string &stPath)
{
std::ifstream in(stPath);
ASSERT(!in.is_open(), ERRORS::TOK_FILE_OPEN_ERROR);
std::string line;
char delim = '|';
std::getline(in, line);
while (std::getline(in, line))
{
auto vals = splitStr(line, delim);
symbols[vals[0]] = {vals[0], vals[1], 0, 0};
}
in.close();
}
void Translator::writeST()
{
std::ofstream symTable("translator-symboltable.txt");
symTable << "ID | DT | S | IV" << std::endl;
std::vector<STData> vec;
for (std::map<std::string, STData>::iterator itr = symbols.begin(); itr != symbols.end(); itr++)
vec.push_back(itr->second);
std::sort(vec.begin(), vec.end(), less_than_key());
for (int i = 0; i < vec.size(); i++)
{
if (!vec[i].lex.empty()) {
symTable << vec[i].lex
<< " | "
<< vec[i].dt
<< " | "
<< vec[i].addr
<< " | "
<< vec[i].initVal
<< '\n';
}
}
symTable.close();
}
void Translator::writeTAC()
{
std::ofstream out("tac.txt");
ASSERT(!out.is_open(), ERRORS::TAC_FILE_OPEN_ERROR);
for (int line = 0; line < tacLines.size(); line++)
out << tacLines[line];
}
void Translator::writeMC()
{
std::ofstream out("machine-code.txt");
ASSERT(!out.is_open(), ERRORS::MC_FILE_OPEN_ERROR);
for (int line = 0; line < tacLines.size(); line++)
out << std::get<0>(quadTuples[line])
<< " "
<< std::get<1>(quadTuples[line])
<< " "
<< std::get<2>(quadTuples[line])
<< " "
<< std::get<3>(quadTuples[line])
<< "\n";
}
void Translator::emit(int num, ...)
{
va_list valist;
va_start(valist, num);
std::string temp = "";
for (int i = 0; i < num; i++)
{
temp += (va_arg(valist, char *));
if (i < num - 1)
temp += " ";
}
trim(temp);
temp += "\n";
tacLines.push_back(temp);
va_end(valist);
n++;
}
void Translator::quad(int a, int b, int c, int d)
{
quadTuples.push_back({a, b, c, d});
}
std::string Translator::handleNumericConstant(const std::string &str)
{
if (isNumber(str))
{
int val = atoi(str.c_str());
std::string temp = "t" + std::to_string(tempValIdx++);
symbols[temp] = {temp, "Integer", 0, val};
addToST(4, temp);
return temp;
}
return str;
}
void Translator::backpatch(int lineNo, int value)
{
tacLines[lineNo - 1].pop_back();
tacLines[lineNo - 1].append(" " + std::to_string(value));
tacLines[lineNo - 1].push_back('\n');
}
void Translator::addToST(int size, std::string &lex)
{
trim(lex);
auto vec = splitStr(lex, ' ');
if (!vec.empty())
{
for (const std::string &id : vec)
{
symbols[id].addr = addr;
addr += size;
}
}
else
{
symbols[lex].addr = addr;
addr += size;
}
}
Translator::Token Translator::peekToken()
{
Translator::Token next_tok = *(++look);
look--;
return next_tok;
}
void Translator::match(const std::string &token)
{
if (look->lexeme == token)
look++;
else
TR_LOG(ERRORS::BAD_TOK, token, look->lexeme);
}
std::pair<std::string, int> Translator::datatype()
{
if (look->lexeme == "char" || look->lexeme == "Integer")
{
std::pair<std::string, int> ret = {look->lexeme, (look->lexeme == "char") ? 1 : 4};
look++;
return ret;
}
else
TR_LOG(ERRORS::BAD_TOK, "char or Integer", look->lexeme);
}
std::string Translator::identifier()
{
std::string lex = look->lexeme;
if (look->type == "ID")
{
look++;
return lex;
}
else
TR_LOG(ERRORS::BAD_TOK, "of type Identifier", look->lexeme);
}
void Translator::variable()
{
std::pair<std::string, int> dt = datatype();
match(":");
std::string lex = identifier();
addToST(dt.second, lex);
}
std::string Translator::variableDeclerationB()
{
if (look->lexeme == ",")
{
match(",");
return variableDeclerationA();
}
else
return "";
}
std::string Translator::variableDeclerationA()
{
std::string lex = identifier() + " ";
lex += variableDeclerationB();
return lex;
}
void Translator::variableDecleration()
{
std::pair<std::string, int> dt = datatype();
match(":");
std::string lex = variableDeclerationA();
match(";");
addToST(dt.second, lex);
}
std::string Translator::literalConstant()
{
if (look->type == "LC")
{
std::string lex = look->lexeme;
look++;
return lex;
}
else
TR_LOG(ERRORS::BAD_TOK, "of type Literal Constant", look->lexeme);
}
std::string Translator::numConstant()
{
if (look->type == "NUMC")
{
std::string lex = look->lexeme;
look++;
return lex;
}
else
TR_LOG(ERRORS::BAD_TOK, "of type Number Constant/Number", look->lexeme);
}
std::string Translator::F()
{
if (look->type == "ID")
return identifier();
else if (look->type == "NUMC")
return numConstant();
else if (look->lexeme == "(")
{
match("(");
std::string lex = expression();
match(")");
return lex;
}
else
throw std::runtime_error("Invalid Expression found!");
}
std::string Translator::termPrime(std::string &prevLex)
{
if (look->lexeme == "*")
{
match("*");
auto fVal = F();
std::string termLex = "* " + fVal + " ";
std::string temp = "t" + std::to_string(tempValIdx++);
symbols[temp] = {temp, "Integer", 0, 0};
addToST(4, temp);
emit(4, temp.c_str(), "=", prevLex.c_str(), termLex.c_str());
quad(opcodes["*"], symbols[handleNumericConstant(prevLex)].addr, symbols[handleNumericConstant(fVal)].addr, symbols[temp].addr);
return termPrime(temp);
}
else if (look->lexeme == "/")
{
match("/");
auto fVal = F();
std::string termLex = "/ " + fVal + " ";
std::string temp = "t" + std::to_string(tempValIdx++);
symbols[temp] = {temp, "Integer", 0, 0};
addToST(4, temp);
emit(4, temp.c_str(), "=", prevLex.c_str(), termLex.c_str());
quad(opcodes["/"], symbols[handleNumericConstant(prevLex)].addr, symbols[handleNumericConstant(fVal)].addr, symbols[temp].addr);
return termPrime(temp);
}
else
return prevLex;
}
std::string Translator::term()
{
std::string lex = F();
return termPrime(lex);
}
std::string Translator::expressionPrime(std::string &prevLex)
{
if (look->lexeme == "+")
{
match("+");
auto tVal = term();
std::string termLex = "+ " + tVal + " ";
std::string temp = "t" + std::to_string(tempValIdx++);
symbols[temp] = {temp, "Integer", 0, 0};
addToST(4, temp);
emit(4, temp.c_str(), "=", prevLex.c_str(), termLex.c_str());
quad(opcodes["+"], symbols[handleNumericConstant(prevLex)].addr, symbols[handleNumericConstant(tVal)].addr, symbols[temp].addr);
return expressionPrime(temp);
}
else if (look->lexeme == "-")
{
match("-");
auto tVal = term();
std::string termLex = "- " + tVal + " ";
std::string temp = "t" + std::to_string(tempValIdx++);
symbols[temp] = {temp, "Integer", 0, 0};
addToST(4, temp);
emit(4, temp.c_str(), "=", prevLex.c_str(), termLex.c_str());
quad(opcodes["-"], symbols[handleNumericConstant(prevLex)].addr, symbols[handleNumericConstant(tVal)].addr, symbols[temp].addr);
return expressionPrime(temp);
}
else
return prevLex;
}
std::string Translator::expression()
{
std::string termLex = term();
std::string ePLex = expressionPrime(termLex);
return ePLex;
}
std::string Translator::value()
{
if (look->type == "LC")
{
return literalConstant();
}
else if (look->type == "ID" && peekToken().lexeme == "(")
{
functionCall();
return "";
}
else
{
return expression();
}
}
void Translator::functionCallArgPrime()
{
if (look->lexeme == ",")
{
match(",");
value();
functionCallArgPrime();
}
else
;
}
void Translator::functionCallArg()
{
if (look->lexeme == ")")
{
}
else
{
value();
functionCallArgPrime();
}
}
void Translator::functionCall()
{
identifier();
match("(");
functionCallArg();
match(")");
match(";");
}
void Translator::variableAssignment()
{
std::string idLex = identifier();
match(":=");
std::string valLex = value();
match(";");
emit(3, idLex.c_str(), "=", valLex.c_str());
quad(opcodes["="], symbols[handleNumericConstant(valLex)].addr, symbols[idLex].addr, 0);
}
std::string Translator::relationalOperator()
{
if (look->type == "RO")
{
std::string lex = look->lexeme;
look++;
return lex;
}
else
TR_LOG(ERRORS::BAD_TOK, "of type RO", look->lexeme);
}
std::string Translator::with()
{
if (look->type == "ID")
return identifier();
else if (look->type == "NUMC")
return numConstant();
else
TR_LOG(ERRORS::BAD_TOK, "of type Identifier or Number", look->lexeme);
}
std::pair<int, int> Translator::comparison()
{
// assuming first is supposed to be identifier, not any other thing
// to maintain consistency and order
std::string idLex = identifier();
std::string reLex = relationalOperator();
std::string wLex = with();
std::pair<int, int> ret;
ret.first = n;
emit(5, "if", idLex.c_str(), reLex.c_str(), wLex.c_str(), "goto");
std::string val = handleNumericConstant(wLex);
quad(opcodes[reLex == "=" ? "==" : reLex], symbols[idLex].addr, symbols[val].addr, 0);
ret.second = n;
emit(1, "goto");
quad(opcodes["goto"], 0, 0, 0);
return ret;
}
void Translator::whileLoop()
{
match("while");
int start = n;
std::pair<int, int> cmpRet = comparison();
backpatch(cmpRet.first, n);
std::get<3>(quadTuples[cmpRet.first - 1]) = n;
match(":");
match("{");
codeBlock();
match("}");
emit(2, "goto", std::to_string(start).c_str());
quad(opcodes["goto"], start, 0, 0);
backpatch(cmpRet.second, n);
std::get<1>(quadTuples[cmpRet.second - 1]) = n;
}
std::string Translator::stringLiteral()
{
std::string lex;
if (look->type == "STR")
{
lex = look->lexeme;
look++;
return lex;
}
else
TR_LOG(ERRORS::BAD_TOK, "String", look->lexeme);
}
std::string Translator::output()
{
if (look->type == "STR")
return stringLiteral();
else if (look->type == "ID")
return identifier();
else
TR_LOG(ERRORS::BAD_TOK, "of type String or Identifier", look->lexeme);
}
void Translator::printStatement()
{
if (look->lexeme == "print")
{
match("print");
match("(");
std::string lex = output();
match(")");
match(";");
emit(2, "out", lex.c_str());
quad(opcodes["out"], symbols[lex].addr, 0, 0);
}
else if (look->lexeme == "println")
{
match("println");
match("(");
std::string lex = output();
match(")");
match(";");
emit(2, "outln", lex.c_str());
quad(opcodes["outln"], symbols[lex].addr, 0, 0);
}
else
TR_LOG(ERRORS::BAD_TOK, "of type print or pritln", look->lexeme);
}
void Translator::inputStatement()
{
match("In");
match(">>");
std::string idLex = identifier();
match(";");
emit(2, "in", idLex.c_str());
quad(opcodes["in"], symbols[idLex].addr, 0, 0);
}
void Translator::returnStatement()
{
match("ret");
std::string lex = identifier();
match(";");
emit(2, "ret", lex.c_str());
quad(opcodes["ret"], symbols[lex].addr, 0, 0);
}
int Translator::ifStatement()
{
match("if");
std::pair<int, int> cmpRet = comparison();
backpatch(cmpRet.first, n);
std::get<3>(quadTuples[cmpRet.first - 1]) = n;
match(":");
match("{");
codeBlock();
match("}");
return cmpRet.second;
}
int Translator::elifStatement()
{
match("elif");
std::pair<int, int> cmpRet = comparison();
backpatch(cmpRet.first, n);
std::get<3>(quadTuples[cmpRet.first - 1]) = n;
match(":");
match("{");
codeBlock();
match("}");
return cmpRet.second;
}
void Translator::elseStatement()
{
match("else");
match("{");
codeBlock();
match("}");
}
void Translator::conditionalStatementPrime()
{
if (look->lexeme == "if")
{
int cmpF = ifStatement();
int next = n;
emit(1, "goto");
quad(opcodes["goto"], 0, 0, 0);
backpatch(cmpF, n);
std::get<1>(quadTuples[cmpF - 1]) = n;
conditionalStatementPrime();
backpatch(next, n);
std::get<1>(quadTuples[next - 1]) = n;
}
else if (look->lexeme == "elif")
{
int cmpF = elifStatement();
int next = n;
emit(1, "goto");
quad(opcodes["goto"], 0, 0, 0);
backpatch(cmpF, n);
std::get<1>(quadTuples[cmpF - 1]) = n;
conditionalStatementPrime();
backpatch(next, n);
std::get<1>(quadTuples[next - 1]) = n;
}
else if (look->lexeme == "else")
{
elseStatement();
conditionalStatementPrime();
}
else
;
}
// Handles nested ifs
void Translator::conditionalStatement()
{
int cmpF = ifStatement();
int next = n;
emit(1, "goto");
quad(opcodes["goto"], 0, 0, 0);
backpatch(cmpF, n);
std::get<1>(quadTuples[cmpF - 1]) = n;
conditionalStatementPrime();
backpatch(next, n);
std::get<1>(quadTuples[next - 1]) = n;
}
void Translator::statement()
{
Token curr_tok = *look;
if (curr_tok.type == "DT")
{
variableDecleration();
}
else if (curr_tok.type == "ID" && peekToken().lexeme == "(")
{
functionCall();
}
else if (curr_tok.type == "ID")
{
variableAssignment();
}
else if (curr_tok.lexeme == "while")
{
whileLoop();
}
else if (curr_tok.lexeme == "print" || curr_tok.lexeme == "println")
{
printStatement();
}
else if (curr_tok.lexeme == "In")
{
inputStatement();
}
else if (curr_tok.lexeme == "if")
{
conditionalStatement();
}
else if (curr_tok.lexeme == "ret")
{
returnStatement();
}
else
throw std::runtime_error("Unkown Statement found!");
}
void Translator::codeBlock()
{
Token curr_tok = *look;
if (curr_tok.type == "DT" || curr_tok.type == "ID" || curr_tok.lexeme == "print" || curr_tok.lexeme == "println" || curr_tok.lexeme == "while" || curr_tok.lexeme == "In" || curr_tok.lexeme == "if" || curr_tok.lexeme == "ret")
{
statement();
codeBlock();
}
else
;
}
void Translator::functionArgument()
{
if (look->type == "PUNC")
{
match(",");
variable();
functionArgument();
}
else if (look->type == "DT")
{
variable();
functionArgument();
}
else
;
}
void Translator::functionDecleration()
{
match("func");
datatype();
match(":");
identifier();
match("(");
functionArgument();
match(")");
match("{");
codeBlock();
match("}");
}
void Translator::source()
{
if (look != end)
{
// This assumes that everything in this language is
// contained within a function, and there is no "stray" code
functionDecleration();
source();
}
}
void Translator::run(const std::string &wListPath, const std::string &stPath)
{
auto wList = loadTokens(wListPath);
loadST(stPath);
look = wList.begin();
end = wList.end();
source();
writeST();
writeTAC();
writeMC();
}
Translator::~Translator()
{
delete m_Instance;
} | 21.677494 | 230 | 0.511988 | saeenyoda |
dafcdc05ec4fba55d331c891e2416959ad3db796 | 551 | cpp | C++ | PushMeasurementOnDeepSleep/TempHumBehavior.cpp | vknabel/arduino-push-measurements-on-deep-sleep | 47e9193d5e4e6ab314d7214dd781bde7dd30903d | [
"MIT"
] | null | null | null | PushMeasurementOnDeepSleep/TempHumBehavior.cpp | vknabel/arduino-push-measurements-on-deep-sleep | 47e9193d5e4e6ab314d7214dd781bde7dd30903d | [
"MIT"
] | null | null | null | PushMeasurementOnDeepSleep/TempHumBehavior.cpp | vknabel/arduino-push-measurements-on-deep-sleep | 47e9193d5e4e6ab314d7214dd781bde7dd30903d | [
"MIT"
] | null | null | null | #include "TempHumBehavior.h"
#include "StringHelpers.h"
TempHumBehavior::TempHumBehavior(TempHumSensor tempHumSensor)
: Behavior(),
_sensor(tempHumSensor) {
}
void TempHumBehavior::setup() {
_sensor.setup();
}
String TempHumBehavior::characteristics() {
float temperature = 0.0;
float humidity = 0.0;
if (_sensor.read(&temperature, &humidity)) {
return "\"temperature\":" + quote(String(temperature))
+ ",\"humidity\":" + quote(String(humidity));
} else {
return "\"error\":\"Reading from TempHumSensor failed\"";
}
}
| 23.956522 | 61 | 0.682396 | vknabel |
dafd00a356b1c08940cefd482878bd30dc3cb5a6 | 17,771 | cpp | C++ | Source.cpp | kenjinote/DownloadTumblrVideo | d6c989cd7b8b0833f4ba9c73f0b38908302bc7c1 | [
"MIT"
] | 2 | 2017-09-29T13:22:31.000Z | 2021-12-15T02:56:03.000Z | Source.cpp | kenjinote/DownloadTumblrVideo | d6c989cd7b8b0833f4ba9c73f0b38908302bc7c1 | [
"MIT"
] | null | null | null | Source.cpp | kenjinote/DownloadTumblrVideo | d6c989cd7b8b0833f4ba9c73f0b38908302bc7c1 | [
"MIT"
] | 1 | 2022-03-05T04:28:15.000Z | 2022-03-05T04:28:15.000Z | #pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "rpcrt4")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "wininet")
#pragma comment(lib, "comctl32")
#include <windows.h>
#include <commctrl.h>
#include <shlwapi.h>
#include <wininet.h>
#include <vector>
#include <string>
#define IDC_EDIT 1000
#define IDC_PROGRESS 1001
HWND hMainWnd;
BOOL bAbort;
void DropData(HWND hWnd, IDataObject *pDataObject)
{
FORMATETC fmtetc = { CF_UNICODETEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
STGMEDIUM stgmed;
if (pDataObject->QueryGetData(&fmtetc) == S_OK) {
if (pDataObject->GetData(&fmtetc, &stgmed) == S_OK) {
PVOID data = GlobalLock(stgmed.hGlobal);
SetDlgItemTextW(hWnd, IDC_EDIT, (LPWSTR)data);
SendDlgItemMessage(hWnd, IDC_EDIT, EM_SETSEL, 0, -1);
GlobalUnlock(stgmed.hGlobal);
ReleaseStgMedium(&stgmed);
}
}
}
class CDropTarget : public IDropTarget
{
public:
HRESULT __stdcall QueryInterface(REFIID iid, void ** ppvObject) {
if (iid == IID_IDropTarget || iid == IID_IUnknown) {
AddRef();
*ppvObject = this;
return S_OK;
}
else {
*ppvObject = 0;
return E_NOINTERFACE;
}
}
ULONG __stdcall AddRef(void) {
return InterlockedIncrement(&m_lRefCount);
}
ULONG __stdcall Release(void) {
LONG count = InterlockedDecrement(&m_lRefCount);
if (count == 0) {
delete this;
return 0;
}
else {
return count;
}
}
HRESULT __stdcall DragEnter(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect) {
m_fAllowDrop = QueryDataObject(pDataObject);
if (m_fAllowDrop) {
*pdwEffect = DropEffect(grfKeyState, pt, *pdwEffect);
SetFocus(m_hWnd);
}
else {
*pdwEffect = DROPEFFECT_NONE;
}
return S_OK;
}
HRESULT __stdcall DragOver(DWORD grfKeyState, POINTL pt, DWORD * pdwEffect) {
if (m_fAllowDrop) {
*pdwEffect = DropEffect(grfKeyState, pt, *pdwEffect);
}
else {
*pdwEffect = DROPEFFECT_NONE;
}
return S_OK;
}
HRESULT __stdcall DragLeave(void) {
return S_OK;
}
HRESULT __stdcall Drop(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect) {
if (m_fAllowDrop) {
DropData(m_hWnd, pDataObject);
*pdwEffect = DropEffect(grfKeyState, pt, *pdwEffect);
}
else {
*pdwEffect = DROPEFFECT_NONE;
}
return S_OK;
}
CDropTarget(HWND hwnd) {
m_lRefCount = 1;
m_hWnd = hwnd;
m_fAllowDrop = false;
}
~CDropTarget() {}
private:
DWORD DropEffect(DWORD grfKeyState, POINTL pt, DWORD dwAllowed) {
DWORD dwEffect = 0;
if (grfKeyState & MK_CONTROL) {
dwEffect = dwAllowed & DROPEFFECT_COPY;
}
else if (grfKeyState & MK_SHIFT) {
dwEffect = dwAllowed & DROPEFFECT_MOVE;
}
if (dwEffect == 0) {
if (dwAllowed & DROPEFFECT_COPY) dwEffect = DROPEFFECT_COPY;
if (dwAllowed & DROPEFFECT_MOVE) dwEffect = DROPEFFECT_MOVE;
}
return dwEffect;
}
BOOL QueryDataObject(IDataObject *pDataObject) {
FORMATETC fmtetc = { CF_UNICODETEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
return pDataObject->QueryGetData(&fmtetc) == S_OK;
}
LONG m_lRefCount;
HWND m_hWnd;
BOOL m_fAllowDrop;
IDataObject *m_pDataObject;
};
LPBYTE DownloadToMemory(IN LPCWSTR lpszURL)
{
LPBYTE lpszReturn = 0;
DWORD dwSize = 0;
const HINTERNET hSession = InternetOpenW(L"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_NO_COOKIES);
if (hSession)
{
URL_COMPONENTSW uc = { 0 };
WCHAR HostName[MAX_PATH];
WCHAR UrlPath[MAX_PATH];
uc.dwStructSize = sizeof(uc);
uc.lpszHostName = HostName;
uc.lpszUrlPath = UrlPath;
uc.dwHostNameLength = MAX_PATH;
uc.dwUrlPathLength = MAX_PATH;
InternetCrackUrlW(lpszURL, 0, 0, &uc);
const HINTERNET hConnection = InternetConnectW(hSession, HostName, INTERNET_DEFAULT_HTTP_PORT, 0, 0, INTERNET_SERVICE_HTTP, 0, 0);
if (hConnection)
{
const HINTERNET hRequest = HttpOpenRequestW(hConnection, L"GET", UrlPath, 0, 0, 0, 0, 0);
if (hRequest)
{
ZeroMemory(&uc, sizeof(URL_COMPONENTS));
WCHAR Scheme[16];
uc.dwStructSize = sizeof(uc);
uc.lpszScheme = Scheme;
uc.lpszHostName = HostName;
uc.dwSchemeLength = 16;
uc.dwHostNameLength = MAX_PATH;
InternetCrackUrlW(lpszURL, 0, 0, &uc);
WCHAR szReferer[1024];
lstrcpyW(szReferer, L"Referer: ");
lstrcatW(szReferer, Scheme);
lstrcatW(szReferer, L"://");
lstrcatW(szReferer, HostName);
HttpAddRequestHeadersW(hRequest, szReferer, lstrlenW(szReferer), HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
HttpSendRequestW(hRequest, 0, 0, 0, 0);
lpszReturn = (LPBYTE)GlobalAlloc(GMEM_FIXED, 1);
DWORD dwRead;
BYTE szBuf[1024 * 16];
LPBYTE lpTmp;
for (;;)
{
if (!InternetReadFile(hRequest, szBuf, (DWORD)sizeof(szBuf), &dwRead) || !dwRead) break;
lpTmp = (LPBYTE)GlobalReAlloc(lpszReturn, (SIZE_T)(dwSize + dwRead), GMEM_MOVEABLE);
if (lpTmp == NULL) break;
lpszReturn = lpTmp;
CopyMemory(lpszReturn + dwSize, szBuf, dwRead);
dwSize += dwRead;
}
InternetCloseHandle(hRequest);
}
InternetCloseHandle(hConnection);
}
InternetCloseHandle(hSession);
}
return lpszReturn;
}
BOOL DownloadToFile(IN LPCWSTR lpszURL, IN LPCWSTR lpszFilePath)
{
BOOL bReturn = FALSE;
LPBYTE lpByte = DownloadToMemory(lpszURL);
if (lpByte) {
const DWORD nSize = (DWORD)GlobalSize(lpByte);
const HANDLE hFile = CreateFileW(lpszFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD dwWritten;
WriteFile(hFile, lpByte, nSize, &dwWritten, NULL);
CloseHandle(hFile);
bReturn = TRUE;
}
GlobalFree(lpByte);
}
return bReturn;
}
BOOL CreateTempDirectory(LPWSTR pszDir)
{
DWORD dwSize = GetTempPath(0, 0);
if (dwSize == 0 || dwSize > MAX_PATH - 14) { goto END0; }
LPWSTR pTmpPath = (LPWSTR)GlobalAlloc(GPTR, sizeof(WCHAR)*(dwSize + 1));
GetTempPathW(dwSize + 1, pTmpPath);
dwSize = GetTempFileNameW(pTmpPath, L"", 0, pszDir);
GlobalFree(pTmpPath);
if (dwSize == 0) { goto END0; }
DeleteFileW(pszDir);
if (CreateDirectoryW(pszDir, 0) == 0) { goto END0; }
return TRUE;
END0:
return FALSE;
}
VOID MyCreateFileFromResource(WCHAR *szResourceName, WCHAR *szResourceType, WCHAR *szResFileName)
{
DWORD dwWritten;
HRSRC hRs = FindResourceW(0, szResourceName, szResourceType);
DWORD dwResSize = SizeofResource(0, hRs);
HGLOBAL hMem = LoadResource(0, hRs);
LPBYTE lpByte = (BYTE *)LockResource(hMem);
HANDLE hFile = CreateFileW(szResFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(hFile, lpByte, dwResSize, &dwWritten, NULL);
CloseHandle(hFile);
}
std::wstring Replace(std::wstring String1, std::wstring String2, std::wstring String3)
{
std::wstring::size_type Pos(String1.find(String2));
while (Pos != std::wstring::npos) {
String1.replace(Pos, String2.length(), String3);
Pos = String1.find(String2, Pos + String3.length());
}
return String1;
}
LPWSTR Download2WChar(LPCWSTR lpszURL)
{
LPWSTR lpszReturn = 0;
LPBYTE lpByte = DownloadToMemory(lpszURL);
if (lpByte) {
const DWORD len = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)lpByte, -1, 0, 0);
lpszReturn = (LPWSTR)GlobalAlloc(0, (len + 1) * sizeof(WCHAR));
if (lpszReturn) {
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)lpByte, -1, lpszReturn, len);
}
GlobalFree(lpByte);
}
return lpszReturn;
}
BOOL DownloadTumblrVideo(LPCWSTR lpszURL)
{
// 入力される URL 例1: https://www.tumblr.com/video/kenjinote/165813628414/700/
// 例2: http://kenjinote.tumblr.com/post/165813628414/
// URL から UserName, TweetID を取得し、ダウンロードファイル名を決定する
WCHAR szUserName[256] = { 0 };
WCHAR szTweetID[256] = { 0 };
WCHAR szTargetFilePath[MAX_PATH] = { 0 };
std::wstring url(lpszURL);
{
if (url.find(L"/post/") != std::wstring::npos)
{
size_t posStart = url.find(L"://");
if (posStart == std::wstring::npos) return FALSE;
posStart += 3;
size_t posEnd = url.find(L"/post/", posStart);
if (posEnd == std::wstring::npos) return FALSE;
std::wstring strUserName(url, posStart, posEnd - posStart);
lstrcpyW(szUserName, strUserName.c_str());
posStart = posEnd + 6;
lstrcpyW(szTweetID, std::to_wstring(std::stoull(std::wstring(url, posStart))).c_str());
} else if (url.find(L"://www.tumblr.com/video/")) {
size_t posStart = url.find(L"/video/");
if (posStart == std::wstring::npos) return FALSE;
posStart += 7;
size_t posEnd = url.find(L"/", posStart);
if (posEnd == std::wstring::npos) return FALSE;
std::wstring strUserName(url, posStart, posEnd - posStart);
lstrcpyW(szUserName, strUserName.c_str());
posStart = posEnd + 1;
lstrcpyW(szTweetID, std::to_wstring(std::stoull(std::wstring(url, posStart))).c_str());
}
if (szUserName[0] == 0 || szTweetID[0] == 0) {
return FALSE;
}
lstrcatW(szTargetFilePath, szUserName);
lstrcatW(szTargetFilePath, L"_");
lstrcatW(szTargetFilePath, szTweetID);
lstrcatW(szTargetFilePath, L".mp4");
}
// 既にダウンロード済なら抜ける
if (PathFileExistsW(szTargetFilePath))
{
return FALSE;
}
// HTML から動画ファイルを取得
LPWSTR lpszWeb;
std::wstring srcW;
size_t posStart, posEnd;
if (url.find(L"://www.tumblr.com/video/") == std::wstring::npos)
{
lpszWeb = Download2WChar(lpszURL);
if (!lpszWeb)
{
return 0;
}
srcW = std::wstring(lpszWeb);
GlobalFree(lpszWeb);
posStart = srcW.find(L"<iframe src='https://www.tumblr.com/video/");
if (posStart == std::wstring::npos)
{
return FALSE;
}
posStart += 13;
posEnd = srcW.find(L'\'', posStart);
url = std::wstring(srcW, posStart, posEnd - posStart);
}
if (url.find(L"://www.tumblr.com/video/") == std::wstring::npos)
{
return FALSE;
}
lpszWeb = Download2WChar(url.c_str());
if (!lpszWeb) return 0;
srcW = std::wstring(lpszWeb);
GlobalFree(lpszWeb);
//<source src="https://kenjinote.tumblr.com/video_file/t:xxxxxxx-xx_xxxxxxxxxxx/000000000000/tumblr_nsnva7Qh5b1swsrod" type="video/mp4"> を探す
posStart = srcW.find(L"<source src=\"");
if (posStart == std::wstring::npos)
{
return FALSE;
}
posStart += 13;
posEnd = srcW.find(L'\"', posStart);
if (posEnd == std::wstring::npos)
{
return FALSE;
}
return DownloadToFile(std::wstring(srcW, posStart, posEnd - posStart).c_str(), szTargetFilePath);
}
BOOL GetVideoUrlListFromHtmlSource(std::vector<std::wstring> * urllist, LPCWSTR lpszWeb)
{
if (!lpszWeb) return 0;
std::wstring srcW(lpszWeb);
size_t posStart = 0, posEnd = 0;
for (;;) {
posStart = srcW.find(L"<iframe src='https://www.tumblr.com/video/", posStart);
if (posStart == std::wstring::npos) break;
posStart += 13;
posEnd = srcW.find(L'\'', posStart);
if (posEnd == std::wstring::npos) break;
urllist->push_back(std::wstring(srcW, posStart, posEnd - posStart).c_str());
posStart = posEnd;
}
return TRUE;
}
BOOL GetVideoUrlListFromFile(std::vector<std::wstring> * urllist, LPCWSTR lpszFilePath)
{
if (!lpszFilePath) return 0;
const HANDLE hFile = CreateFileW(lpszFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) return 0;
DWORD nSize = GetFileSize(hFile, 0);
if (!nSize) {
CloseHandle(hFile);
return 0;
}
LPBYTE lpByte = (LPBYTE)GlobalAlloc(0, nSize + 1);
if (!lpByte) {
CloseHandle(hFile);
return 0;
}
DWORD dwRead = 0;
ReadFile(hFile, lpByte, nSize, &dwRead, NULL);
CloseHandle(hFile);
lpByte[nSize] = 0;
const DWORD len = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)lpByte, -1, 0, 0);
LPWSTR lpszWeb = (LPWSTR)GlobalAlloc(0, (len + 1) * sizeof(WCHAR));
if (!lpszWeb) {
GlobalFree(lpByte);
return 0;
}
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)lpByte, -1, lpszWeb, len);
GlobalFree(lpByte);
BOOL bRet = GetVideoUrlListFromHtmlSource(urllist, lpszWeb);
GlobalFree(lpszWeb);
return bRet;
}
BOOL GetVideoUrlListFromID(std::vector<std::wstring> * urllist, LPCWSTR lpszUserID)
{
WCHAR szUrl[1024] = { 0 };
if (StrStrW(lpszUserID, L".tumblr.com") == NULL) {
lstrcatW(szUrl, L"https://");
lstrcatW(szUrl, lpszUserID);
{
LPWSTR lpszWeb = Download2WChar(szUrl);
if (!lpszWeb) return 0;
BOOL bRet = GetVideoUrlListFromHtmlSource(urllist, lpszWeb);
GlobalFree(lpszWeb);
}
lstrcatW(szUrl, L".tumblr.com/");
{
LPWSTR lpszWeb = Download2WChar(szUrl);
if (!lpszWeb) return 0;
BOOL bRet = GetVideoUrlListFromHtmlSource(urllist, lpszWeb);
GlobalFree(lpszWeb);
}
}
return TRUE;
}
VOID GetVideoUrlList(std::vector<std::wstring> * urllist, LPCWSTR lpszInput)
{
if (PathFileExistsW(lpszInput)) {
GetVideoUrlListFromFile(urllist, lpszInput);
}
else if (StrStrW(lpszInput, L"/post/")) {
urllist->push_back(lpszInput);
}
else {
GetVideoUrlListFromID(urllist, lpszInput);
}
}
DWORD WINAPI ThreadFunc(LPVOID lpV)
{
std::vector<std::wstring> * urllist = (std::vector<std::wstring> *)lpV;
HWND hProgress = GetDlgItem(hMainWnd, IDC_PROGRESS);
const int nSize = (int)urllist->size();
SendMessage(hProgress, PBM_SETRANGE, 0, MAKELPARAM(0, nSize));
SendMessage(hProgress, PBM_SETSTEP, 1, 0);
SendMessage(hProgress, PBM_SETPOS, 0, 0);
for (int i = 0; i < nSize && bAbort == FALSE; ++i) {
DownloadTumblrVideo(urllist->at(i).c_str());
SendMessage(hProgress, PBM_STEPIT, 0, 0);
}
PostMessage(hMainWnd, WM_APP, 0, 0);
return 0;
}
void RegisterDropWindow(HWND hwnd, IDropTarget **ppDropTarget)
{
CDropTarget *pDropTarget = new CDropTarget(hwnd);
CoLockObjectExternal(pDropTarget, TRUE, FALSE);
RegisterDragDrop(hwnd, pDropTarget);
*ppDropTarget = pDropTarget;
}
void UnregisterDropWindow(HWND hwnd, IDropTarget *pDropTarget)
{
RevokeDragDrop(hwnd);
CoLockObjectExternal(pDropTarget, FALSE, TRUE);
pDropTarget->Release();
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static IDropTarget *pDropTarget;
static HWND hEdit, hButton1, hButton2, hProgress;
static HANDLE hThread;
static std::vector<std::wstring> urllist;
switch (msg) {
case WM_CREATE:
InitCommonControls();
hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), 0, WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, (HMENU)IDC_EDIT, ((LPCREATESTRUCT)lParam)->hInstance, 0);
SendMessage(hEdit, EM_SETCUEBANNER, TRUE, (LPARAM)TEXT("http://kenjinote.tumblr.com/post/165816695691"));
hButton1 = CreateWindow(TEXT("BUTTON"), TEXT("ダウンロード開始"), WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_DEFPUSHBUTTON, 0, 0, 0, 0, hWnd, (HMENU)IDOK, ((LPCREATESTRUCT)lParam)->hInstance, 0);
hButton2 = CreateWindow(TEXT("BUTTON"), TEXT("停止"), WS_VISIBLE | WS_CHILD | WS_TABSTOP | WS_DISABLED, 0, 0, 0, 0, hWnd, (HMENU)IDCANCEL, ((LPCREATESTRUCT)lParam)->hInstance, 0);
hProgress = CreateWindow(TEXT("msctls_progress32"), 0, WS_VISIBLE | WS_CHILD | PBS_SMOOTH, 0, 0, 0, 0, hWnd, (HMENU)IDC_PROGRESS, ((LPCREATESTRUCT)lParam)->hInstance, 0);
RegisterDropWindow(hWnd, &pDropTarget);
DragAcceptFiles(hWnd, TRUE);
break;
case WM_SIZE:
MoveWindow(hEdit, 10, 10, LOWORD(lParam) - 20, 32, TRUE);
MoveWindow(hButton1, 10, 50, 256, 32, TRUE);
MoveWindow(hButton2, 276, 50, 256, 32, TRUE);
MoveWindow(hProgress, 10, 90, LOWORD(lParam) - 20, 32, TRUE);
break;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK) {
if (GetWindowTextLength(hEdit) == 0) return 0;
EnableWindow(hEdit, FALSE);
EnableWindow(hButton1, FALSE);
urllist.clear();
WCHAR szInput[MAX_PATH];
GetWindowTextW(hEdit, szInput, _countof(szInput));
PathUnquoteSpacesW(szInput);
GetVideoUrlList(&urllist, szInput);
bAbort = FALSE;
hThread = CreateThread(0, 0, ThreadFunc, (LPVOID)&urllist, 0, 0);
EnableWindow(hButton2, TRUE);
SetFocus(hButton2);
}
else if (LOWORD(wParam) == IDCANCEL) {
EnableWindow(hButton2, FALSE);
bAbort = TRUE;
}
break;
case WM_APP:
EnableWindow(hButton2, FALSE);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
hThread = 0;
urllist.clear();
SendMessage(hProgress, PBM_SETPOS, 0, 0);
EnableWindow(hEdit, TRUE);
EnableWindow(hButton1, TRUE);
SetFocus(hEdit);
break;
case WM_DROPFILES:
{
UINT uFileNum = DragQueryFileW((HDROP)wParam, -1, NULL, 0);
if (uFileNum == 1)
{
WCHAR szFilePath[MAX_PATH];
DragQueryFileW((HDROP)wParam, 0, szFilePath, MAX_PATH);
SetWindowText(hEdit, szFilePath);
}
DragFinish((HDROP)wParam);
}
break;
case WM_CLOSE:
UnregisterDropWindow(hWnd, pDropTarget);
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefDlgProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreInst, LPSTR pCmdLine, int nCmdShow)
{
int n;
LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &n);
if (n == 1) {
OleInitialize(0);
TCHAR szClassName[] = TEXT("Window");
MSG msg;
WNDCLASS wndclass = {
CS_HREDRAW | CS_VREDRAW,
WndProc,
0,
DLGWINDOWEXTRA,
hInstance,
0,
LoadCursor(0,IDC_ARROW),
0,
0,
szClassName
};
RegisterClass(&wndclass);
hMainWnd = CreateWindow(
szClassName,
TEXT("Tumblrのツイートに含まれる動画をMP4形式でダウンロードする"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
0,
CW_USEDEFAULT,
0,
0,
0,
hInstance,
0
);
ShowWindow(hMainWnd, SW_SHOWDEFAULT);
UpdateWindow(hMainWnd);
while (GetMessage(&msg, 0, 0, 0)) {
if (!IsDialogMessage(hMainWnd, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
OleUninitialize();
}
else if (n == 2) {
std::vector<std::wstring> urllist;
GetVideoUrlList(&urllist, argv[1]);
HANDLE hThread = CreateThread(0, 0, ThreadFunc, (LPVOID)&urllist, 0, 0);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
hThread = 0;
}
LocalFree(argv);
return 0;
}
| 29.717391 | 218 | 0.69861 | kenjinote |
970572e01e99fd246b9b4ac5c673f5ba133b29c3 | 2,579 | hpp | C++ | src/backend/opencl/kernel/laswp.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-06-14T23:49:18.000Z | 2018-06-14T23:49:18.000Z | src/backend/opencl/kernel/laswp.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2015-07-02T15:53:02.000Z | 2015-07-02T15:53:02.000Z | src/backend/opencl/kernel/laswp.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-02-26T17:11:03.000Z | 2018-02-26T17:11:03.000Z | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <kernel_headers/laswp.hpp>
#include <program.hpp>
#include <traits.hpp>
#include <string>
#include <mutex>
#include <map>
#include <dispatch.hpp>
#include <Param.hpp>
#include <debug_opencl.hpp>
#include <types.hpp>
using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::make_kernel;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;
namespace opencl
{
namespace kernel
{
static const int NTHREADS = 256;
static const int MAX_PIVOTS = 32;
typedef struct {
int npivots;
int ipiv[MAX_PIVOTS];
} zlaswp_params_t;
template<typename T>
void laswp(int n, cl_mem in, size_t offset, int ldda,
int k1, int k2, const int *ipiv, int inci)
{
static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
static std::map<int, Program*> swpProgs;
static std::map<int, Kernel*> swpKernels;
int device = getActiveDeviceId();
std::call_once(compileFlags[device], [device] () {
std::ostringstream options;
options << " -D T=" << dtype_traits<T>::getName()
<< " -D MAX_PIVOTS=" << MAX_PIVOTS;
if (std::is_same<T, double>::value ||
std::is_same<T, cdouble>::value) {
options << " -D USE_DOUBLE";
}
cl::Program prog;
buildProgram(prog, laswp_cl, laswp_cl_len, options.str());
swpProgs[device] = new Program(prog);
swpKernels[device] = new Kernel(*swpProgs[device], "laswp");
});
int groups = divup(n, NTHREADS);
NDRange local(NTHREADS);
NDRange global(groups * local[0]);
zlaswp_params_t params;
auto laswpOp = make_kernel<int, cl_mem, unsigned long long,
int, zlaswp_params_t>(*swpKernels[device]);
for( int k = k1-1; k < k2; k += MAX_PIVOTS ) {
int pivots_left = k2-k;
params.npivots = pivots_left > MAX_PIVOTS ? MAX_PIVOTS : pivots_left;
for( int j = 0; j < params.npivots; ++j ) {
params.ipiv[j] = ipiv[(k+j)*inci] - k - 1;
}
unsigned long long k_offset = offset + k*ldda;
laswpOp(EnqueueArgs(getQueue(), global, local),
n, in, k_offset, ldda, params);
}
}
}
}
| 25.038835 | 77 | 0.586661 | JuliaComputing |
9707a75797344671face8866fc32b9a89391c535 | 422 | cpp | C++ | data-structure/Desorden.cpp | ejpcr/libs-c | e544e4338ea9f2fe8c57de83045944f38ae06a07 | [
"MIT"
] | null | null | null | data-structure/Desorden.cpp | ejpcr/libs-c | e544e4338ea9f2fe8c57de83045944f38ae06a07 | [
"MIT"
] | null | null | null | data-structure/Desorden.cpp | ejpcr/libs-c | e544e4338ea9f2fe8c57de83045944f38ae06a07 | [
"MIT"
] | null | null | null | //Programa de insersion, eliminacion, busqueda, etc.
//en un arreglo unidimensional desordenado.
//Castillo Gardea Mariano
//01070097
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
void captura(int);
int k;
int n=100;
void main()
{int datos[100]; clrscr(); captura(datos[100]); getchar();
}
void captura(int datos[])
{cout<<"Cuantos datos deseas capturar: "; cin>>k;
for(int i=0; i<k; i++) cin>>datos[i];
} | 22.210526 | 58 | 0.694313 | ejpcr |
8ccce31936abca36fa81aeef5a6d2d2221fe7d97 | 5,063 | hxx | C++ | arm9/source/emucore/M6502.hxx | wavemotion-dave/StellaDS | 8aa9954c9294c3d567b156619472a31ff6863da0 | [
"MIT"
] | 13 | 2020-11-25T20:58:44.000Z | 2022-02-01T19:10:27.000Z | arm9/source/emucore/M6502.hxx | wavemotion-dave/StellaDS | 8aa9954c9294c3d567b156619472a31ff6863da0 | [
"MIT"
] | null | null | null | arm9/source/emucore/M6502.hxx | wavemotion-dave/StellaDS | 8aa9954c9294c3d567b156619472a31ff6863da0 | [
"MIT"
] | 3 | 2021-07-29T10:05:51.000Z | 2022-01-10T02:14:58.000Z | //============================================================================
//
// MM MM 6666 555555 0000 2222
// MMMM MMMM 66 66 55 00 00 22 22
// MM MMM MM 66 55 00 00 22
// MM M MM 66666 55555 00 00 22222 -- "A 6502 Microprocessor Emulator"
// MM MM 66 66 55 00 00 22
// MM MM 66 66 55 55 00 00 22
// MM MM 6666 5555 0000 222222
//
// Copyright (c) 1995-1998 by Bradford W. Mott
//
// See the file "license" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: M6502.hxx,v 1.2 2002/05/13 19:10:25 stephena Exp $
//============================================================================
#ifndef M6502_HXX
#define M6502_HXX
class D6502;
class M6502;
#include "bspf.hxx"
#include "System.hxx"
extern uInt8 A;
extern uInt8 X;
extern uInt8 Y;
extern uInt8 SP;
extern uInt16 PC;
extern uInt8 N;
extern uInt8 V;
extern uInt8 B;
extern uInt8 D;
extern uInt8 I;
extern uInt8 notZ;
extern uInt8 C;
/**
This is an abstract base class for classes that emulate the
6502 microprocessor. The 6502 is an 8-bit microprocessor that
has a 64K addressing space.
@author Bradford W. Mott
@version $Id: M6502.hxx,v 1.2 2002/05/13 19:10:25 stephena Exp $
*/
class M6502
{
public:
/**
The 6502 debugger class is a friend who needs special access
*/
friend class D6502;
public:
/**
Enumeration of the 6502 addressing modes
*/
enum AddressingMode
{
Absolute, AbsoluteX, AbsoluteY, Immediate, Implied,
Indirect, IndirectX, IndirectY, Invalid, Relative,
Zero, ZeroX, ZeroY
};
public:
/**
Create a new 6502 microprocessor with the specified cycle
multiplier. The cycle multiplier is the number of system cycles
per processor cycle.
@param systemCyclesPerProcessorCycle The cycle multiplier
*/
M6502(uInt32 systemCyclesPerProcessorCycle);
/**
Destructor
*/
virtual ~M6502();
public:
/**
Install the processor in the specified system. Invoked by the
system when the processor is attached to it.
@param system The system the processor should install itself in
*/
virtual void install(System& system);
public:
/**
Reset the processor to its power-on state. This method should not
be invoked until the entire 6502 system is constructed and installed
since it involves reading the reset vector from memory.
*/
virtual void reset();
/**
Request a maskable interrupt
*/
virtual void irq();
/**
Request a non-maskable interrupt
*/
virtual void nmi();
/**
Get a null terminated string which is the processor's name (i.e. "M6532")
@return The name of the device
*/
virtual const char* name() const = 0;
public:
/**
Execute instructions until the specified number of instructions
is executed, someone stops execution, or an error occurs. Answers
true iff execution stops normally.
@param number Indicates the number of instructions to execute
@return true iff execution stops normally
*/
virtual bool execute(uInt16 number) = 0;
/**
Tell the processor to stop executing instructions. Invoking this
method while the processor is executing instructions will stop
execution as soon as possible.
*/
void stop();
/**
Answer true iff a fatal error has occured from which the processor
cannot recover (i.e. illegal instruction, etc.)
@return true iff a fatal error has occured
*/
bool fatalError() const
{
return myExecutionStatus & FatalErrorBit;
}
public:
/**
Overload the ostream output operator for addressing modes.
@param out The stream to output the addressing mode to
@param mode The addressing mode to output
*/
friend ostream& operator<<(ostream& out, const AddressingMode& mode);
protected:
/**
Get the 8-bit value of the Processor Status register.
@return The processor status register
*/
uInt8 PS() const;
/**
Change the Processor Status register to correspond to the given value.
@param ps The value to set the processor status register to
*/
void PS(uInt8 ps);
protected:
/**
Bit fields used to indicate that certain conditions need to be
handled such as stopping execution, fatal errors, maskable interrupts
and non-maskable interrupts
*/
uInt8 myExecutionStatus;
/**
Constants used for setting bits in myExecutionStatus
*/
enum
{
StopExecutionBit = 0x01,
FatalErrorBit = 0x02,
MaskableInterruptBit = 0x04,
NonmaskableInterruptBit = 0x08
};
/// Pointer to the system the processor is installed in or the null pointer
System* mySystem;
protected:
/// Lookup table used for binary-code-decimal math
static uInt8 ourBCDTable[2][256];
};
#endif
| 25.315 | 79 | 0.634802 | wavemotion-dave |
8ccda9f8961cfad017b3667e6fcd0367dca439bc | 48 | cpp | C++ | base/src/GameSparks/GSTypedResponse.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 7 | 2019-07-11T02:05:32.000Z | 2020-11-01T18:57:51.000Z | base/src/GameSparks/GSTypedResponse.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 3 | 2019-02-26T15:59:03.000Z | 2019-06-04T10:46:07.000Z | base/src/GameSparks/GSTypedResponse.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 6 | 2020-05-18T08:44:47.000Z | 2022-02-26T12:18:17.000Z | /* empty file to avoid breaking project files */ | 48 | 48 | 0.75 | djdron |
8cd68c562c2f066bb4487fcca286be583e8b2d57 | 304 | hpp | C++ | src/mapping.hpp | StanislavPavlic/countmap | 1c6ea352dc2cffb4db079aeba797bdb0c0a6726f | [
"MIT"
] | null | null | null | src/mapping.hpp | StanislavPavlic/countmap | 1c6ea352dc2cffb4db079aeba797bdb0c0a6726f | [
"MIT"
] | null | null | null | src/mapping.hpp | StanislavPavlic/countmap | 1c6ea352dc2cffb4db079aeba797bdb0c0a6726f | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <string>
struct mapping_t {
std::string qname;
int flag;
std::string rname;
uint32_t pos;
uint32_t mapq;
std::string cigar;
std::string rnext;
uint32_t pnext;
int32_t tlen;
std::string seq;
std::string qual;
uint32_t nm;
int32_t as;
}; | 15.2 | 20 | 0.677632 | StanislavPavlic |
8cdd3f86def43518f1bc231e47ad04088bb7de24 | 2,775 | cc | C++ | src/envoy/http/service_control/filter_stats.cc | CorrelatedLabs/esp-v2 | 9fa93040d70f98087b3586a88a0764b9f5ec544c | [
"Apache-2.0"
] | 163 | 2019-12-18T18:40:50.000Z | 2022-03-17T03:34:22.000Z | src/envoy/http/service_control/filter_stats.cc | CorrelatedLabs/esp-v2 | 9fa93040d70f98087b3586a88a0764b9f5ec544c | [
"Apache-2.0"
] | 669 | 2019-12-19T00:36:12.000Z | 2022-03-30T20:27:52.000Z | src/envoy/http/service_control/filter_stats.cc | CorrelatedLabs/esp-v2 | 9fa93040d70f98087b3586a88a0764b9f5ec544c | [
"Apache-2.0"
] | 177 | 2019-12-19T00:35:51.000Z | 2022-03-24T10:22:23.000Z | // Copyright 2019 Google LLC
//
// 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 "src/envoy/http/service_control/filter_stats.h"
#include "google/protobuf/stubs/status.h"
using ::google::protobuf::util::Status;
using ::google::protobuf::util::StatusCode;
namespace espv2 {
namespace envoy {
namespace http_filters {
namespace service_control {
void ServiceControlFilterStats::collectCallStatus(CallStatusStats& stats,
const StatusCode& code) {
// The status error code cases must match the error codes defined by
// https://github.com/protocolbuffers/protobuf/blob/4b4e66743503bf927cfb0f27a267ecd077250667/src/google/protobuf/stubs/status.h#L45
switch (code) {
case StatusCode::kOk:
stats.OK_.inc();
return;
case StatusCode::kCancelled:
stats.CANCELLED_.inc();
return;
case StatusCode::kUnknown:
stats.UNKNOWN_.inc();
return;
case StatusCode::kInvalidArgument:
stats.INVALID_ARGUMENT_.inc();
return;
case StatusCode::kDeadlineExceeded:
stats.DEADLINE_EXCEEDED_.inc();
return;
case StatusCode::kNotFound:
stats.NOT_FOUND_.inc();
return;
case StatusCode::kAlreadyExists:
stats.ALREADY_EXISTS_.inc();
return;
case StatusCode::kPermissionDenied:
stats.PERMISSION_DENIED_.inc();
return;
case StatusCode::kResourceExhausted:
stats.RESOURCE_EXHAUSTED_.inc();
return;
case StatusCode::kFailedPrecondition:
stats.FAILED_PRECONDITION_.inc();
return;
case StatusCode::kAborted:
stats.ABORTED_.inc();
return;
case StatusCode::kOutOfRange:
stats.OUT_OF_RANGE_.inc();
return;
case StatusCode::kUnimplemented:
stats.UNIMPLEMENTED_.inc();
return;
case StatusCode::kInternal:
stats.INTERNAL_.inc();
return;
case StatusCode::kUnavailable:
stats.UNAVAILABLE_.inc();
return;
case StatusCode::kDataLoss:
stats.DATA_LOSS_.inc();
return;
case StatusCode::kUnauthenticated:
stats.UNAUTHENTICATED_.inc();
return;
default:
return;
}
}
} // namespace service_control
} // namespace http_filters
} // namespace envoy
} // namespace espv2
| 30.163043 | 133 | 0.687207 | CorrelatedLabs |
8ce181e8a1569aba3217505aafd9f4c234959a66 | 625 | hpp | C++ | include/experimental/meta/v1/type.hpp | mwoehlke/viboes-std-make | 5d65a40289301ae35a8f32349c13c365a553dc51 | [
"BSL-1.0"
] | 105 | 2015-01-24T13:26:41.000Z | 2022-02-18T15:36:53.000Z | include/experimental/meta/v1/type.hpp | mwoehlke/viboes-std-make | 5d65a40289301ae35a8f32349c13c365a553dc51 | [
"BSL-1.0"
] | 37 | 2015-09-04T06:57:10.000Z | 2021-09-09T18:01:44.000Z | include/experimental/meta/v1/type.hpp | mwoehlke/viboes-std-make | 5d65a40289301ae35a8f32349c13c365a553dc51 | [
"BSL-1.0"
] | 23 | 2015-01-27T11:09:18.000Z | 2021-10-04T02:23:30.000Z | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Vicente J. Botet Escriba 2014.
// 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)
//
//////////////////////////////////////////////////////////////////////////////
#ifndef JASEL_META_V1_TYPE_HPP
#define JASEL_META_V1_TYPE_HPP
namespace std
{
namespace experimental
{
namespace meta
{
inline namespace v1
{
template < class T >
struct type
{
using underlying_type = T;
};
}
}
}
}
#endif // header
| 20.16129 | 93 | 0.5232 | mwoehlke |
8ce3b36b1dc0f9cdf066be87d0d4f0c2c5cc3bac | 3,586 | cpp | C++ | ToolKit/Controls/Splitter/XTPSplitterWndTheme.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 2 | 2018-03-30T06:40:08.000Z | 2022-02-23T12:40:13.000Z | ToolKit/Controls/Splitter/XTPSplitterWndTheme.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | null | null | null | ToolKit/Controls/Splitter/XTPSplitterWndTheme.cpp | 11Zero/DemoBCG | 8f41d5243899cf1c82990ca9863fb1cb9f76491c | [
"MIT"
] | 1 | 2020-08-11T05:48:02.000Z | 2020-08-11T05:48:02.000Z | // XTPSplitterWndTheme.cpp: implementation of the XTPSplitterWndTheme class.
//
// This file is a part of the XTREME CONTROLS MFC class library.
// (c)1998-2011 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Common/XTPWinThemeWrapper.h"
#include "Common/XTPColorManager.h"
#include "Common/XTPDrawHelpers.h"
#include "Common/XTPResourceImage.h"
#include "Controls/Util/XTPControlTheme.h"
#include "Controls/Splitter/XTPSplitterWnd.h"
#include "Controls/Splitter/XTPSplitterWndTheme.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CXTPSplitterWndTheme
CXTPSplitterWndTheme::CXTPSplitterWndTheme()
{
}
void CXTPSplitterWndTheme::RefreshMetrics(CXTPSplitterWnd* /*pSplitter*/)
{
m_clrSplitterFace.SetStandardValue(GetSysColor(COLOR_3DFACE));
m_clrSplitterBorders.SetStandardValue(GetSysColor(COLOR_3DSHADOW));
}
/////////////////////////////////////////////////////////////////////////////
// CXTPSplitterWndThemeOfficeXP
CXTPSplitterWndThemeOfficeXP::CXTPSplitterWndThemeOfficeXP()
{
m_nTheme = xtpControlThemeOfficeXP;
}
void CXTPSplitterWndThemeOfficeXP::RefreshMetrics(CXTPSplitterWnd* pSplitter)
{
CXTPSplitterWndTheme::RefreshMetrics(pSplitter);
}
/////////////////////////////////////////////////////////////////////////////
// CXTPSplitterWndThemeOffice2003
CXTPSplitterWndThemeOffice2003::CXTPSplitterWndThemeOffice2003()
{
m_nTheme = xtpControlThemeOffice2003;
}
void CXTPSplitterWndThemeOffice2003::RefreshMetrics(CXTPSplitterWnd* pSplitter)
{
CXTPSplitterWndThemeOfficeXP::RefreshMetrics(pSplitter);
if (!XTPColorManager()->IsLunaColorsDisabled())
{
XTPCurrentSystemTheme systemTheme = XTPColorManager()->GetCurrentSystemTheme();
switch (systemTheme)
{
case xtpSystemThemeBlue:
case xtpSystemThemeRoyale:
case xtpSystemThemeAero:
m_clrSplitterFace.SetStandardValue(RGB(216, 231, 252));
m_clrSplitterBorders.SetStandardValue(RGB(158, 190, 245));
break;
case xtpSystemThemeOlive:
m_clrSplitterFace.SetStandardValue(RGB(226, 231, 191));
m_clrSplitterBorders.SetStandardValue(RGB(171, 192, 138));
break;
case xtpSystemThemeSilver:
m_clrSplitterFace.SetStandardValue(RGB(223, 223, 234));
m_clrSplitterBorders.SetStandardValue(RGB(177, 176, 195));
break;
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CXTPSplitterWndThemeResource
CXTPSplitterWndThemeResource::CXTPSplitterWndThemeResource()
{
m_nTheme = xtpControlThemeResource;
}
void CXTPSplitterWndThemeResource::RefreshMetrics(CXTPSplitterWnd* pSplitter)
{
CXTPSplitterWndThemeOffice2003::RefreshMetrics(pSplitter);
CXTPResourceImages* pImages = XTPResourceImages();
m_clrSplitterFace.SetStandardValue(pImages->GetImageColor(_T("Window"), _T("ButtonFace")));
m_clrSplitterBorders.SetStandardValue(pImages->GetImageColor(_T("Window"), _T("WindowFrame")));
}
| 29.636364 | 96 | 0.709147 | 11Zero |
8ceb329e848263ff88ee9386ad30b397f7b0f33a | 907 | cpp | C++ | Whakman/ImageManager.cpp | dingjun/Whakman | ee70583481d942a98210744f0e56e747c157549d | [
"MIT"
] | null | null | null | Whakman/ImageManager.cpp | dingjun/Whakman | ee70583481d942a98210744f0e56e747c157549d | [
"MIT"
] | null | null | null | Whakman/ImageManager.cpp | dingjun/Whakman | ee70583481d942a98210744f0e56e747c157549d | [
"MIT"
] | null | null | null | #include "ImageManager.h"
std::vector<IImage*> ImageManager::_images;
void ImageManager::init(ISBZLibrary* lib) {
_images.push_back(lib->load_image("images/wall_cross.png"));
_images.push_back(lib->load_image("images/wall_end.png"));
_images.push_back(lib->load_image("images/wall_straight.png"));
_images.push_back(lib->load_image("images/wall_t.png"));
_images.push_back(lib->load_image("images/wall_turn.png"));
_images.push_back(lib->load_image("images/whakman_01.png"));
_images.push_back(lib->load_image("images/whakman_02.png"));
_images.push_back(lib->load_image("images/ghost_01.png"));
_images.push_back(lib->load_image("images/ghost_02.png"));
_images.push_back(lib->load_image("images/coin.png"));
_images.push_back(lib->load_image("images/osd_whakman.png"));
}
void ImageManager::deinit() {
for (auto image : _images) {
image->destroy();
}
_images.clear();
}
| 36.28 | 65 | 0.736494 | dingjun |
8ceda98027b8496b244f038002cc2e3b6a452829 | 1,872 | cpp | C++ | Chapter_4_Graph/Graph_Traversal/kattis_gold.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | 2 | 2021-12-29T04:12:59.000Z | 2022-03-30T09:32:19.000Z | Chapter_4_Graph/Graph_Traversal/kattis_gold.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | null | null | null | Chapter_4_Graph/Graph_Traversal/kattis_gold.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | 1 | 2022-03-01T06:12:46.000Z | 2022-03-01T06:12:46.000Z | /**Kattis - gold
* BFS floodfill, but with the modification that we don't go to any adjancent cells if there exist
* a draft, ie there exist a trap that we could potentially go to.
*
* Time: O(hw), Space: O(hw)
*/
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int h, w, s_r, s_c;
vector<vector<char>> grid;
vector<vector<int>> dist;
string row;
int dc[] = {0, 1, 0, -1};
int dr[] = {1, 0, -1, 0};
queue<pair<int,int>> q;
int main(){
cin >> w >> h;
grid.assign(h, vector<char>(w));
dist.assign(h, vector<int>(w, -1));
for (int r=0; r<h; r++){
cin >> row;
for (int c=0; c<w; c++){
grid[r][c] = row[c];
if (row[c] == 'P'){
s_r = r;
s_c = c;
}
}
}
dist[s_r][s_c] = 0;
q.push({s_r, s_c});
int gold = 0;
while (!q.empty()){
auto &[r, c] = q.front();
q.pop();
gold += (grid[r][c] == 'G');
bool draft = false;
for (int i=0; i<4; i++){
int nr = r + dr[i];
int nc = c + dc[i];
if (grid[nr][nc] == '#') continue;
if (grid[nr][nc] == 'T'){
draft = true;
break;
}
}
if (draft) continue;
for (int i=0; i<4; i++){
int nr = r + dr[i];
int nc = c + dc[i];
if (grid[nr][nc] == '#') continue;
if (dist[nr][nc] == -1){
dist[nr][nc] = dist[r][c] + 1;
q.push({nr, nc});
}
}
}
cout << gold << endl;
return 0;
} | 24.96 | 98 | 0.459936 | BrandonTang89 |
8cf66d901dedcd6eceffaa0f696b3e2212403ccb | 586 | cpp | C++ | src/Random.cpp | darklam/CppNeuralNetwork | 8edd53f0c9917cd4d217287d3fb711f2fccc43c1 | [
"MIT"
] | null | null | null | src/Random.cpp | darklam/CppNeuralNetwork | 8edd53f0c9917cd4d217287d3fb711f2fccc43c1 | [
"MIT"
] | null | null | null | src/Random.cpp | darklam/CppNeuralNetwork | 8edd53f0c9917cd4d217287d3fb711f2fccc43c1 | [
"MIT"
] | null | null | null | #include <random>
#include "Random.h"
double Random::randomDouble(double min, double max){
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<double> dist(min, max);
return dist(gen);
}
double Random::randomDouble(double max){
return Random::randomDouble(0, max);
}
double Random::randomDouble(){
return Random::randomDouble(0, 1);
}
int Random::randomInt(int min, int max){
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dist(min, max);
return dist(gen);
} | 24.416667 | 59 | 0.658703 | darklam |
8cf7587ce6fb25b5f8732ca0b3b998eb088e6568 | 6,728 | cpp | C++ | src/visitor/test/FoldConstantExprVisitorTest.cpp | yixinglu/nebula-graph | faf9cd44d818b953da98b5c922999560c89867bd | [
"Apache-2.0"
] | 1 | 2021-08-23T05:55:55.000Z | 2021-08-23T05:55:55.000Z | src/visitor/test/FoldConstantExprVisitorTest.cpp | yixinglu/nebula-graph | faf9cd44d818b953da98b5c922999560c89867bd | [
"Apache-2.0"
] | null | null | null | src/visitor/test/FoldConstantExprVisitorTest.cpp | yixinglu/nebula-graph | faf9cd44d818b953da98b5c922999560c89867bd | [
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "visitor/FoldConstantExprVisitor.h"
#include <gtest/gtest.h>
#include "util/ObjectPool.h"
using Type = nebula::Value::Type;
namespace nebula {
namespace graph {
class FoldConstantExprVisitorTest : public ::testing::Test {
public:
void TearDown() override {
pool.clear();
}
static ConstantExpression *constant(Value value) {
return new ConstantExpression(std::move(value));
}
static ArithmeticExpression *add(Expression *lhs, Expression *rhs) {
return new ArithmeticExpression(Expression::Kind::kAdd, lhs, rhs);
}
static ArithmeticExpression *minus(Expression *lhs, Expression *rhs) {
return new ArithmeticExpression(Expression::Kind::kMinus, lhs, rhs);
}
static RelationalExpression *gt(Expression *lhs, Expression *rhs) {
return new RelationalExpression(Expression::Kind::kRelGT, lhs, rhs);
}
static RelationalExpression *eq(Expression *lhs, Expression *rhs) {
return new RelationalExpression(Expression::Kind::kRelEQ, lhs, rhs);
}
static TypeCastingExpression *cast(Type type, Expression *expr) {
return new TypeCastingExpression(type, expr);
}
static UnaryExpression *not_(Expression *expr) {
return new UnaryExpression(Expression::Kind::kUnaryNot, expr);
}
static LogicalExpression *and_(Expression *lhs, Expression *rhs) {
return new LogicalExpression(Expression::Kind::kLogicalAnd, lhs, rhs);
}
static LogicalExpression *or_(Expression *lhs, Expression *rhs) {
return new LogicalExpression(Expression::Kind::kLogicalOr, lhs, rhs);
}
static ListExpression *list_(std::initializer_list<Expression *> exprs) {
auto exprList = new ExpressionList;
for (auto expr : exprs) {
exprList->add(expr);
}
return new ListExpression(exprList);
}
static SubscriptExpression *sub(Expression *lhs, Expression *rhs) {
return new SubscriptExpression(lhs, rhs);
}
static FunctionCallExpression *fn(std::string fn, std::initializer_list<Expression *> args) {
auto argsList = new ArgumentList;
for (auto arg : args) {
argsList->addArgument(std::unique_ptr<Expression>(arg));
}
return new FunctionCallExpression(new std::string(std::move(fn)), argsList);
}
static VariableExpression *var(const std::string &name) {
return new VariableExpression(new std::string(name));
}
protected:
ObjectPool pool;
};
TEST_F(FoldConstantExprVisitorTest, TestArithmeticExpr) {
// (5 - 1) + 2 => 4 + 2
auto expr = pool.add(add(minus(constant(5), constant(1)), constant(2)));
FoldConstantExprVisitor visitor;
expr->accept(&visitor);
auto expected = pool.add(add(constant(4), constant(2)));
ASSERT_EQ(*expr, *expected) << expr->toString() << " vs. " << expected->toString();
ASSERT(visitor.canBeFolded());
// 4+2 => 6
auto root = pool.add(visitor.fold(expr));
auto rootExpected = pool.add(constant(6));
ASSERT_EQ(*root, *rootExpected) << root->toString() << " vs. " << rootExpected->toString();
}
TEST_F(FoldConstantExprVisitorTest, TestRelationExpr) {
// false == !(3 > (1+1)) => false == false
auto expr = pool.add(eq(constant(false), not_(gt(constant(3), add(constant(1), constant(1))))));
auto expected = pool.add(eq(constant(false), constant(false)));
FoldConstantExprVisitor visitor;
expr->accept(&visitor);
ASSERT_EQ(*expr, *expected) << expr->toString() << " vs. " << expected->toString();
ASSERT(visitor.canBeFolded());
// false==false => true
auto root = pool.add(visitor.fold(expr));
auto rootExpected = pool.add(constant(true));
ASSERT_EQ(*root, *rootExpected) << root->toString() << " vs. " << rootExpected->toString();
}
TEST_F(FoldConstantExprVisitorTest, TestLogicalExpr) {
// false && (false || (3 > (1 + 1))) => false && true
auto expr = pool.add(and_(
constant(false), or_(constant(false), gt(constant(3), add(constant(1), constant(1))))));
auto expected = pool.add(and_(constant(false), constant(true)));
FoldConstantExprVisitor visitor;
expr->accept(&visitor);
ASSERT_EQ(*expr, *expected) << expr->toString() << " vs. " << expected->toString();
ASSERT(visitor.canBeFolded());
// false && true => false
auto root = pool.add(visitor.fold(expr));
auto rootExpected = pool.add(constant(false));
ASSERT_EQ(*root, *rootExpected) << root->toString() << " vs. " << rootExpected->toString();
}
TEST_F(FoldConstantExprVisitorTest, TestSubscriptExpr) {
// 1 + [1, pow(2, 2+1), 2][2-1] => 1 + 8
auto expr = pool.add(add(constant(1),
sub(list_({constant(1),
fn("pow", {constant(2), add(constant(2), constant(1))}),
constant(2)}),
minus(constant(2), constant(1)))));
auto expected = pool.add(add(constant(1), constant(8)));
FoldConstantExprVisitor visitor;
expr->accept(&visitor);
ASSERT_EQ(*expr, *expected) << expr->toString() << " vs. " << expected->toString();
ASSERT(visitor.canBeFolded());
// 1+8 => 9
auto root = pool.add(visitor.fold(expr));
auto rootExpected = pool.add(constant(9));
ASSERT_EQ(*root, *rootExpected) << root->toString() << " vs. " << rootExpected->toString();
}
TEST_F(FoldConstantExprVisitorTest, TestFoldFailed) {
// function call
{
// pow($v, (1+2)) => pow($v, 3)
auto expr = pool.add(fn("pow", {var("v"), add(constant(1), constant(2))}));
auto expected = pool.add(fn("pow", {var("v"), constant(3)}));
FoldConstantExprVisitor visitor;
expr->accept(&visitor);
ASSERT_EQ(*expr, *expected) << expr->toString() << " vs. " << expected->toString();
ASSERT_FALSE(visitor.canBeFolded());
}
// list
{
// [$v, pow(1, 2), 1+2][2-1] => [$v, 1, 3][0]
auto expr = pool.add(sub(
list_({var("v"), fn("pow", {constant(1), constant(2)}), add(constant(1), constant(2))}),
minus(constant(1), constant(1))));
auto expected = pool.add(sub(list_({var("v"), constant(1), constant(3)}), constant(0)));
FoldConstantExprVisitor visitor;
expr->accept(&visitor);
ASSERT_EQ(*expr, *expected) << expr->toString() << " vs. " << expected->toString();
ASSERT_FALSE(visitor.canBeFolded());
}
}
} // namespace graph
} // namespace nebula
| 37.171271 | 100 | 0.625149 | yixinglu |
8cfdfb1762e52d384b218580e1a4114d7937deaf | 182 | hh | C++ | TrkBase/TrkHitListIter.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | TrkBase/TrkHitListIter.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | TrkBase/TrkHitListIter.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | #ifndef TRKHITLISTITER_HH
#define TRKHITLISTITER_HH
#include "TrkBase/TrkHitOnTrkIter.hh"
#include "TrkBase/TrkHitList.hh"
typedef TrkHitList::hot_iterator TrkHitListIter;
#endif
| 18.2 | 48 | 0.82967 | brownd1978 |
8cff2e7f7a69347fb018276c81594de5be419c8e | 1,123 | cpp | C++ | src/base/CloudProcessor.cpp | mcserep/railroad | 17666e6db3b1847e81c76bdf25b83343439df169 | [
"BSD-3-Clause"
] | 14 | 2018-12-28T06:36:29.000Z | 2022-03-08T02:29:37.000Z | src/base/CloudProcessor.cpp | enginBozkurt/railroad | 0b9fcc463d88c1bc625008cabb81891cd164a8a5 | [
"BSD-3-Clause"
] | 2 | 2021-03-11T02:59:57.000Z | 2021-12-14T22:31:16.000Z | src/base/CloudProcessor.cpp | enginBozkurt/railroad | 0b9fcc463d88c1bc625008cabb81891cd164a8a5 | [
"BSD-3-Clause"
] | 13 | 2018-07-14T04:53:11.000Z | 2022-02-22T02:44:57.000Z | /*
* BSD 3-Clause License
* Copyright (c) 2018-2020, Máté Cserép & Péter Hudoba
* All rights reserved.
*
* You may obtain a copy of the License at
* https://opensource.org/licenses/BSD-3-Clause
*/
#include <pcl/common/io.h>
#include "CloudProcessor.h"
#include "../helpers/LogHelper.h"
namespace railroad
{
pcl::PointCloud<pcl::PointXYZ>::Ptr CloudProcessor::execute()
{
LOG(debug) << "[" << _name << "] Started filter";
// check seeding
if (_seedRequired && !_seedCloud) {
LOG(error) << _name << " requires seed cloud, skipping algorithm.";
pcl::PointCloud<pcl::PointXYZ>::Ptr result(new pcl::PointCloud<pcl::PointXYZ>);
pcl::copyPointCloud(*_cloud, *result);
return result;
}
startTimeMeasure();
PointCloudPtr result = process();
stopTimeMeasure();
_numberOfFilteredPoints = _cloud->points.size() - result->points.size();
LOG(info) << "[" << _name << "] "
<< "Filtered points: " << (_cloud->size() - result->size())
<< " (" << _cloud->size() << " -> " << result->size() << ")";
return result;
}
} // railroad | 28.794872 | 87 | 0.60463 | mcserep |
ea008823030fc2e0a50d0141929428dae103364b | 212 | cpp | C++ | C++/Esercizi/es.13_pag.377_.cpp | Daniele-Tentoni/esercizi_ripetizioni | a8b59b4ead3d6a7459103b91c53017a7495d9e82 | [
"MIT"
] | null | null | null | C++/Esercizi/es.13_pag.377_.cpp | Daniele-Tentoni/esercizi_ripetizioni | a8b59b4ead3d6a7459103b91c53017a7495d9e82 | [
"MIT"
] | null | null | null | C++/Esercizi/es.13_pag.377_.cpp | Daniele-Tentoni/esercizi_ripetizioni | a8b59b4ead3d6a7459103b91c53017a7495d9e82 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main (){
float t =20;
float g =9.81;
float h = g*t*t/2;
cout << "il corpo e' caduto da una altezza di: " ;
cout << h;
cout << " metri\n";
}
| 10.6 | 52 | 0.533019 | Daniele-Tentoni |
ea01a2fc4457bf6e2fb96a29daf11992a9e5e837 | 3,116 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/IfcTimePeriod.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | 1 | 2018-10-23T09:43:07.000Z | 2018-10-23T09:43:07.000Z | IfcPlusPlus/src/ifcpp/IFC4/IfcTimePeriod.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/IfcTimePeriod.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcTime.h"
#include "include/IfcTimePeriod.h"
// ENTITY IfcTimePeriod
IfcTimePeriod::IfcTimePeriod() { m_entity_enum = IFCTIMEPERIOD; }
IfcTimePeriod::IfcTimePeriod( int id ) { m_id = id; m_entity_enum = IFCTIMEPERIOD; }
IfcTimePeriod::~IfcTimePeriod() {}
shared_ptr<IfcPPObject> IfcTimePeriod::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcTimePeriod> copy_self( new IfcTimePeriod() );
if( m_StartTime ) { copy_self->m_StartTime = dynamic_pointer_cast<IfcTime>( m_StartTime->getDeepCopy(options) ); }
if( m_EndTime ) { copy_self->m_EndTime = dynamic_pointer_cast<IfcTime>( m_EndTime->getDeepCopy(options) ); }
return copy_self;
}
void IfcTimePeriod::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCTIMEPERIOD" << "(";
if( m_StartTime ) { m_StartTime->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_EndTime ) { m_EndTime->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcTimePeriod::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcTimePeriod::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 2 ){ std::stringstream err; err << "Wrong parameter count for entity IfcTimePeriod, expecting 2, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
m_StartTime = IfcTime::createObjectFromSTEP( args[0] );
m_EndTime = IfcTime::createObjectFromSTEP( args[1] );
}
void IfcTimePeriod::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
vec_attributes.push_back( std::make_pair( "StartTime", m_StartTime ) );
vec_attributes.push_back( std::make_pair( "EndTime", m_EndTime ) );
}
void IfcTimePeriod::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
}
void IfcTimePeriod::setInverseCounterparts( shared_ptr<IfcPPEntity> )
{
}
void IfcTimePeriod::unlinkFromInverseCounterparts()
{
}
| 47.212121 | 221 | 0.723363 | linsipese |
ea06d30177ece38b4129d391a84e1422624ad922 | 1,774 | hpp | C++ | libgramtools/include/genotype/infer/types.hpp | bricoletc/gramtools | 1ce06178b7b26f42d72e47d3d7b8a7a606e6f256 | [
"MIT"
] | null | null | null | libgramtools/include/genotype/infer/types.hpp | bricoletc/gramtools | 1ce06178b7b26f42d72e47d3d7b8a7a606e6f256 | [
"MIT"
] | null | null | null | libgramtools/include/genotype/infer/types.hpp | bricoletc/gramtools | 1ce06178b7b26f42d72e47d3d7b8a7a606e6f256 | [
"MIT"
] | null | null | null | #ifndef GT_INFER_TYPES
#define GT_INFER_TYPES
#include <memory>
#include "genotype/quasimap/coverage/types.hpp"
namespace gram::genotype::infer {
class Genotyper;
using gtyper_ptr = std::shared_ptr<Genotyper>;
class GenotypedSite;
using gt_site = GenotypedSite;
using gt_site_ptr = std::shared_ptr<GenotypedSite>;
using gt_sites = std::vector<gt_site_ptr>;
using GtypedIndex =
int32_t; /**< The index of an allele in an allele vector or -1 for null*/
using GtypedIndices = std::vector<GtypedIndex>;
using allele_coverages = std::vector<double>;
struct Allele {
std::string sequence;
PerBaseCoverage pbCov;
AlleleId
haplogroup; /**< Which ID in its site this allele is associated with */
Allele() : sequence(""), haplogroup(0) {}
Allele(std::string seq, PerBaseCoverage pb)
: sequence(seq), pbCov(pb), haplogroup(0) {}
Allele(std::string seq, PerBaseCoverage pb, AlleleId haplo)
: sequence(seq), pbCov(pb), haplogroup(haplo) {}
/**
* Allele combination overload
* The left-hand side (= this object) argument's haplogroup is used,
* regardless of `other`'s haplogroup.
*/
Allele operator+(Allele const& other) const {
PerBaseCoverage new_pbCov;
new_pbCov.reserve(pbCov.size() + other.pbCov.size());
new_pbCov.insert(new_pbCov.end(), pbCov.begin(), pbCov.end());
new_pbCov.insert(new_pbCov.end(), other.pbCov.begin(), other.pbCov.end());
return Allele{sequence + other.sequence, new_pbCov, haplogroup};
}
bool operator<(Allele const& other) const {
return sequence < other.sequence;
}
bool operator==(Allele const& other) const {
return sequence == other.sequence;
}
};
using allele_vector = std::vector<Allele>;
} // namespace gram::genotype::infer
#endif // GT_INFER_TYPES
| 29.566667 | 78 | 0.709132 | bricoletc |
ea0b203195062a973edd40d2fc9f18d6fbf66f09 | 1,267 | hpp | C++ | src/lib/logical_query_plan/sort_node.hpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | 1 | 2021-04-14T11:16:52.000Z | 2021-04-14T11:16:52.000Z | src/lib/logical_query_plan/sort_node.hpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | null | null | null | src/lib/logical_query_plan/sort_node.hpp | IanJamesMcKay/InMemoryDB | a267d9522926eca9add2ad4512f8ce352daac879 | [
"MIT"
] | 1 | 2020-11-30T13:11:04.000Z | 2020-11-30T13:11:04.000Z | #pragma once
#include <string>
#include <vector>
#include "abstract_lqp_node.hpp"
#include "lqp_column_reference.hpp"
#include "types.hpp"
namespace opossum {
/**
* Struct to specify Order By items.
* Order By items are defined by the column they operate on and their sort order.
*/
struct OrderByDefinition {
OrderByDefinition(const LQPColumnReference& column_reference, const OrderByMode order_by_mode);
LQPColumnReference column_reference;
OrderByMode order_by_mode;
};
using OrderByDefinitions = std::vector<OrderByDefinition>;
/**
* This node type represents sorting operations as defined in ORDER BY clauses.
*/
class SortNode : public EnableMakeForLQPNode<SortNode>, public AbstractLQPNode {
public:
explicit SortNode(const OrderByDefinitions& order_by_definitions);
std::string description() const override;
const OrderByDefinitions& order_by_definitions() const;
bool shallow_equals(const AbstractLQPNode& rhs) const override;
protected:
std::shared_ptr<AbstractLQPNode> _deep_copy_impl(
const std::shared_ptr<AbstractLQPNode>& copied_left_input,
const std::shared_ptr<AbstractLQPNode>& copied_right_input) const override;
private:
const OrderByDefinitions _order_by_definitions;
};
} // namespace opossum
| 26.395833 | 97 | 0.78453 | IanJamesMcKay |
ea111f8dd2e1f4f2b5114570bae53f2ab171a89d | 3,772 | cpp | C++ | OverlordEditor/GeneratedFiles/Release/moc_NewProjectWindow.cpp | Ruvah/Overlord-Editor | 3193b4986b10edb0fa8fdbc493ee3b05fdea217d | [
"Apache-2.0"
] | 1 | 2018-11-28T12:30:13.000Z | 2018-11-28T12:30:13.000Z | OverlordEditor/GeneratedFiles/Debug/moc_NewProjectWindow.cpp | Ruvah/Overlord-Editor | 3193b4986b10edb0fa8fdbc493ee3b05fdea217d | [
"Apache-2.0"
] | null | null | null | OverlordEditor/GeneratedFiles/Debug/moc_NewProjectWindow.cpp | Ruvah/Overlord-Editor | 3193b4986b10edb0fa8fdbc493ee3b05fdea217d | [
"Apache-2.0"
] | 2 | 2019-12-28T12:34:51.000Z | 2021-03-08T08:37:33.000Z | /****************************************************************************
** Meta object code from reading C++ file 'NewProjectWindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "stdafx.h"
#include "../../NewProjectWindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'NewProjectWindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.11.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_NewProjectWindow_t {
QByteArrayData data[4];
char stringdata0[46];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_NewProjectWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_NewProjectWindow_t qt_meta_stringdata_NewProjectWindow = {
{
QT_MOC_LITERAL(0, 0, 16), // "NewProjectWindow"
QT_MOC_LITERAL(1, 17, 13), // "BrowseFolders"
QT_MOC_LITERAL(2, 31, 0), // ""
QT_MOC_LITERAL(3, 32, 13) // "CreateProject"
},
"NewProjectWindow\0BrowseFolders\0\0"
"CreateProject"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_NewProjectWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 24, 2, 0x0a /* Public */,
3, 0, 25, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void NewProjectWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
NewProjectWindow *_t = static_cast<NewProjectWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->BrowseFolders(); break;
case 1: _t->CreateProject(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject NewProjectWindow::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_NewProjectWindow.data,
qt_meta_data_NewProjectWindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *NewProjectWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *NewProjectWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_NewProjectWindow.stringdata0))
return static_cast<void*>(this);
if (!strcmp(_clname, "Subject"))
return static_cast< Subject*>(this);
return QWidget::qt_metacast(_clname);
}
int NewProjectWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 30.666667 | 96 | 0.632291 | Ruvah |
ea18c3b4711930b2c38703929f2c338ae1aa4d4e | 2,225 | hpp | C++ | c++/en/dropbox/remove_sentences_effectively/remove_sentences_effectively/Config.hpp | aimldl/coding | 70ddbfaa454ab92fd072ee8dc614ecc330b34a70 | [
"MIT"
] | null | null | null | c++/en/dropbox/remove_sentences_effectively/remove_sentences_effectively/Config.hpp | aimldl/coding | 70ddbfaa454ab92fd072ee8dc614ecc330b34a70 | [
"MIT"
] | null | null | null | c++/en/dropbox/remove_sentences_effectively/remove_sentences_effectively/Config.hpp | aimldl/coding | 70ddbfaa454ab92fd072ee8dc614ecc330b34a70 | [
"MIT"
] | null | null | null | #pragma once // config.hpp
#include <string>
using namespace std;
//==================================================================
// Class Declaration //
//==================================================================
class Config
{
public:
Config();
~Config();
string get_file_default_cfg();
string get_file_keywords2remove();
string get_file_uniq_words();
string get_file_similar_sentences();
string get_file_filtered_sentences();
string get_file_uniq_sentences();
string get_file_uniq_sentences_filtered_wt_keywords();
string get_file_sorted_transcript_en();
private:
void init();
string file_default_cfg;
string file_keywords2remove;
string file_uniq_words;
string file_similar_sentences;
string file_filtered_sentences;
string file_uniq_sentences;
string file_uniq_sentences_filtered_wt_keywords;
string file_sorted_transcript_en;
};
#define SHOW_INDEX 0 //
#define VERBOSE 0 // Verbose output
#define DEBUG 0 // Use this flag for the part for debugging now.
#define DEBUG_VERBOSE 0 // Shows all function calls & stuff
#define DEBUG_STOP 0 // Use getchar to stop the program
#define DEBUG_PT1 0 // Debug point 1: print all the sentences
#define DEBUG_PT2 0 // Debug point 2: print all the words
#define DEBUG_PT3 0 // Debug point 3: print all the sentences in save()
#define DEBUG_PT4 0 // Debug point 4: print all the words in save()
#define DEBUG_PT5 0 // Debug point 5: print kw << ": " << word
#define DEBUG_PT6 0 // Debug point 6: print all the lines with the keyword in it.
#define DEBUG_PT7 0 // Debug point 7: idx2remove in TextProc::filterout()
#define DEBUG_PT8 0 // Debug point 8: Normalize text
#define DEBUG_PT9 0 // matched_index
/*
string filename_normalized_uniq_sentences("../output/normalized_uniq_sentences.txt");
string filename_normalized_uniq_words("../output/normalized_uniq_words.txt");
string filename_removed_sentences("../output/normalized_uniq_seantences.txt");
string filename_proprocessed_sentences("../outputproprocessed_sentences.txt");
*/ | 36.47541 | 87 | 0.660225 | aimldl |
ea19c954d672732183127b1dbfb3c86302cfbde7 | 244 | hpp | C++ | Include/FishEngine/Physics/RaycastHit.hpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-12-20T02:38:44.000Z | 2018-12-20T02:38:44.000Z | Include/FishEngine/Physics/RaycastHit.hpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | null | null | null | Include/FishEngine/Physics/RaycastHit.hpp | yushroom/FishEngine_-Experiment | 81e4c06f20f6b94dc561b358f8a11a092678aeeb | [
"MIT"
] | 1 | 2018-10-25T19:40:22.000Z | 2018-10-25T19:40:22.000Z | #pragma once
#include "../Math/Vector3.hpp"
#include "../Math/Vector2.hpp"
namespace FishEngine
{
class Collider;
struct RaycastHit
{
Vector3 m_Point;
float m_Distance;
Vector3 m_Normal;
Collider* m_Collider;
Vector2 m_UV;
};
} | 13.555556 | 30 | 0.709016 | yushroom |
ea1dc87cbfb4389461e41c0f4d872db1ee69e362 | 922 | cpp | C++ | cl_dll/hud_nextmap.cpp | rtxa/OpenAG | fad63ee16e956353b54bc497cc4067102d3d1e33 | [
"MIT"
] | 108 | 2016-06-19T15:24:42.000Z | 2022-01-21T16:51:13.000Z | cl_dll/hud_nextmap.cpp | rtxa/OpenAG | fad63ee16e956353b54bc497cc4067102d3d1e33 | [
"MIT"
] | 147 | 2016-06-19T18:15:35.000Z | 2022-03-19T05:48:26.000Z | cl_dll/hud_nextmap.cpp | rtxa/OpenAG | fad63ee16e956353b54bc497cc4067102d3d1e33 | [
"MIT"
] | 54 | 2016-12-05T15:49:48.000Z | 2022-03-21T23:07:09.000Z | #include "hud.h"
#include "cl_util.h"
#include "parsemsg.h"
DECLARE_MESSAGE(m_NextMap, Nextmap);
int CHudNextMap::Init()
{
HOOK_MESSAGE(Nextmap);
m_iFlags = 0;
next_map[ARRAYSIZE(next_map) - 1] = '\0';
gHUD.AddHudElem(this);
return 0;
}
int CHudNextMap::VidInit()
{
m_iFlags &= ~HUD_ACTIVE;
return 1;
}
int CHudNextMap::Draw(float time)
{
if (gHUD.m_flTime >= draw_until) {
m_iFlags &= ~HUD_ACTIVE;
return 0;
}
int r, g, b;
UnpackRGB(r, g, b, gHUD.m_iDefaultHUDColor);
char str[ARRAYSIZE(next_map) + 32];
sprintf(str, "The next map is %s.", next_map);
gHUD.DrawHudStringCentered(ScreenWidth / 2, gHUD.m_scrinfo.iCharHeight * 5, str, r, g, b);
return 0;
}
int CHudNextMap::MsgFunc_Nextmap(const char* name, int size, void* buf)
{
BEGIN_READ(buf, size);
strncpy(next_map, READ_STRING(), ARRAYSIZE(next_map) - 1);
draw_until = gHUD.m_flTime + 10.0f;
m_iFlags |= HUD_ACTIVE;
return 1;
}
| 17.074074 | 91 | 0.686551 | rtxa |
ea258e164bf869fa7bf4ed7e9398308bcb7eed82 | 606 | cpp | C++ | src/sys/animate.cpp | wtfsystems/wtengine | 0fb56d6eb2ac6359509e7a52876c8656da6b3ce0 | [
"MIT"
] | 7 | 2020-06-16T18:47:35.000Z | 2021-08-25T13:41:13.000Z | src/sys/animate.cpp | wtfsystems/wtengine | 0fb56d6eb2ac6359509e7a52876c8656da6b3ce0 | [
"MIT"
] | 15 | 2020-07-23T14:03:39.000Z | 2022-01-28T02:32:07.000Z | src/sys/animate.cpp | wtfsystems/wtengine | 0fb56d6eb2ac6359509e7a52876c8656da6b3ce0 | [
"MIT"
] | null | null | null | /*!
* WTEngine | File: animate.cpp
*
* \author Matthew Evans
* \version 0.7
* \copyright See LICENSE.md for copyright information.
* \date 2019-2021
*/
#include "wtengine/sys/animate.hpp"
namespace wte::sys {
/*
*
*/
animate::animate() : system("animate", true) {}
/*
*
*/
void animate::run(void) {
component_container<cmp::gfx> animation_components =
mgr::world::set_components<cmp::gfx>();
for(auto& it: animation_components)
try {
if(it.second->visible) it.second->animate(it.first);
} catch(...) { throw; }
}
} // end namespace wte::sys
| 18.363636 | 64 | 0.608911 | wtfsystems |
ea2ad5b7727759ae9a55d500f4248afc5a407d81 | 242 | cpp | C++ | Sem1/WDI/laborka/Zadanie1/main.cpp | YuunOoO/Code | 5e01c53ab54b4cd8e1694e5f343b012797805688 | [
"MIT"
] | 1 | 2021-06-03T14:54:30.000Z | 2021-06-03T14:54:30.000Z | Sem1/WDI/laborka/Zadanie1/main.cpp | YuunOoO/Code | 5e01c53ab54b4cd8e1694e5f343b012797805688 | [
"MIT"
] | null | null | null | Sem1/WDI/laborka/Zadanie1/main.cpp | YuunOoO/Code | 5e01c53ab54b4cd8e1694e5f343b012797805688 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
cout << "Program do obliczania kwadratow liczb od -100 do 100!" << endl;
int n=100;
for(int i=-n; i<=n; i++)
{
cout<<i<<"^2 ="<<i*i<<endl;
}
return 0;
}
| 15.125 | 76 | 0.524793 | YuunOoO |
ea2b5172dc14fcb9abad32d623f73bfbe2364b14 | 5,213 | cpp | C++ | src/board.cpp | szdytom/five-a-row | a88e8c3229d0f32ea5f39ec0102e373db6012cf6 | [
"MIT"
] | null | null | null | src/board.cpp | szdytom/five-a-row | a88e8c3229d0f32ea5f39ec0102e373db6012cf6 | [
"MIT"
] | null | null | null | src/board.cpp | szdytom/five-a-row | a88e8c3229d0f32ea5f39ec0102e373db6012cf6 | [
"MIT"
] | null | null | null | /**
* board.cpp
*
* Define of functions and classes in board.h
*/
#include "../include/board.h"
#include <algorithm>
#include <cstdio>
const int ltzero::Board::size = 15;
void ltzero::Board::clear_state() {
this->status = 0;
this->state.clear();
this->state.resize(ltzero::Board::size);
for (int i = 0; i < ltzero::Board::size; ++i)
state[i].resize(ltzero::Board::size);
for (int i = 0; i < ltzero::Board::size; ++i) {
for (int j = 0; j < ltzero::Board::size; ++j) {
state[i][j] = ltzero::Color::Empty;
}
}
}
bool ltzero::Board::check_end_about(ltzero::Move lst) {
int cnt = 0;
/**
* like this kind:
* x
* x
* x
* x
* x
*/
for (int i = std::max(lst.x - 4, 0); i < std::min(lst.x + 5, ltzero::Board::size); ++i) {
if (this->state[i][lst.y] == lst.c) {
++cnt;
if (cnt == 5 && (i + 1 >= ltzero::Board::size
|| state[i + 1][lst.y] != lst.c)) {
return true;
}
} else {
cnt = 0;
continue;
}
}
/**
* like this kind:
* xxxxx
*/
cnt = 0;
for (int i = std::max(lst.y - 4, 0); i < std::min(lst.y + 5, ltzero::Board::size); ++i) {
if (this->state[lst.x][i] == lst.c) {
++cnt;
if (cnt == 5 && (i + 1 >= ltzero::Board::size
|| this->state[lst.x][i + 1] != lst.c)) {
return true;
}
} else {
cnt = 0;
continue;
}
}
/**
* like this kind:
* x
* x
* x
* x
* x
*/
cnt = 0;
for (int i = -4; i <= 4; ++i) {
int xx = lst.x + i;
int yy = lst.y + i;
if (xx < 0 || xx >= ltzero::Board::size || yy < 0 || yy >= ltzero::Board::size) continue;
if (this->state[xx][yy] == lst.c) {
++cnt;
if (cnt == 5 && (xx + 1 >= ltzero::Board::size || yy + 1 >= ltzero::Board::size
|| this->state[xx + 1][yy + 1] != lst.c)) {
return true;
}
}
}
/**
* like this kind:
* x
* x
* x
* x
* x
*/
cnt = 0;
for (int i = -4; i <= 4; ++i) {
int xx = lst.x + i;
int yy = lst.y - i;
if (xx < 0 || xx >= ltzero::Board::size || yy < 0 || yy >= ltzero::Board::size) continue;
if (this->state[xx][yy] == lst.c) {
++cnt;
if (cnt == 5 && (xx + 1 >= ltzero::Board::size
|| yy - 1 < 0 || this->state[xx + 1][yy - 1] != lst.c)) {
return true;
}
}
}
return false;
}
void ltzero::Board::upd_status() {
ltzero::Move lst = this->moves[this->moves.size() - 1];
if (this->check_end_about(lst)) {
this->status = (lst.c == ltzero::Color::Black ? 1 : -1);
}
}
bool ltzero::Board::make_move(ltzero::Move m) {
if (this->is_end()) {
return false;
}
if (this->state[m.x][m.y] != ltzero::Color::Empty) {
return false;
}
this->moves.push_back(m);
this->state[m.x][m.y] = m.c;
this->upd_status();
now_ts += 1;
return true;
}
ltzero::Board::Board() {
this->clear();
}
bool ltzero::Board::move(int x, int y) {
return this->make_move(ltzero::Move(x, y, this->get_next_player()));
}
bool ltzero::Board::undo() {
if (this->is_end()) return false;
if (this->moves.size() == 0) return false;
ltzero::Move lst = this->moves[this->moves.size() - 1];
this->moves.pop_back();
this->state[lst.x][lst.y] = ltzero::Color::Empty;
this->now_ts += 1;
return true;
}
bool ltzero::Board::is_end() {
return this->status != 0;
}
/**
* Check the state.
* -1 for white wins.
* 0 for still running.
* 1 for black wins.
*/
int ltzero::Board::check() {
return this->status;
}
void ltzero::Board::clear() {
this->clear_state();
this->moves.clear();
this->now_ts = 0;
this->ok_move_ts = -1;
}
ltzero::Color ltzero::Board::get_next_player() {
if (this->moves.size() == 0) // Black moves the first
return ltzero::Color::Black;
if (this->moves[this->moves.size() - 1].c == ltzero::Color::White)
return ltzero::Color::Black;
return ltzero::Color::White;
}
// Get available move list
void ltzero::Board::get_moves(std::vector<ltzero::Move> &m) {
if (this->is_end()) {
m.clear();
return;
}
if (this->ok_move_ts == this->now_ts) {
m = this->ok_move;
return;
}
ltzero::Color c = this->get_next_player();
this->ok_move.clear();
for (int i = 0; i < ltzero::Board::size; ++i) {
for (int j = 0; j < ltzero::Board::size; ++j) {
if (state[i][j] == ltzero::Color::Empty)
this->ok_move.push_back(ltzero::Move(i, j, c));
}
}
this->ok_move_ts = this->now_ts;
m = this->ok_move;
}
void ltzero::Board::print_board() {
for (int i = 0; i < ltzero::Board::size; ++i) {
for (int j = 0; j < ltzero::Board::size; ++j) {
switch (this->state[i][j]) {
case ltzero::Color::Empty:
std::printf(".");
break;
case ltzero::Color::Black:
std::printf("X");
break;
case ltzero::Color::White:
std::printf("O");
break;
default:
break;
}
}
std::printf("\n");
}
}
// Get the board
std::vector<std::vector<ltzero::Color> > ltzero::Board::get_board() {
return this->state;
}
// Get move history
std::vector<ltzero::Move> ltzero::Board::get_history() {
return this->moves;
}
ltzero::Move::Move() {
this->x = -1;
this->y = -1;
this->c = ltzero::Color::Empty;
}
ltzero::Move::Move(int x, int y) {
this->x = x;
this->y = y;
this->c = ltzero::Color::Empty;
}
ltzero::Move::Move(int x, int y, ltzero::Color c) {
this->x = x;
this->y = y;
this->c = c;
} | 19.236162 | 91 | 0.547286 | szdytom |
ea2f24144e07a6575b0d3044c3a09534394c8327 | 2,871 | hpp | C++ | src/manager.hpp | AmbrSb/LServer | 97fde72db060bcc4a5ea4e6fd6d9fff603a23fcf | [
"BSD-2-Clause"
] | 1 | 2021-09-01T08:57:10.000Z | 2021-09-01T08:57:10.000Z | src/manager.hpp | AmbrSb/LServer | 97fde72db060bcc4a5ea4e6fd6d9fff603a23fcf | [
"BSD-2-Clause"
] | null | null | null | src/manager.hpp | AmbrSb/LServer | 97fde72db060bcc4a5ea4e6fd6d9fff603a23fcf | [
"BSD-2-Clause"
] | null | null | null | /*
* BSD 2-Clause License
*
* Copyright (c) 2021, Amin Saba
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "common.hpp"
#include "server.hpp"
#ifdef ENABLE_STATISTICS
#include "stats.hpp"
#endif
namespace lserver {
/*
* This class is responsible for creating servers and managing their
* lifetime. It also provides a single point of contact for various
* other operatios/queries on servers, like get_stats(), etc.
*/
class ServerManager {
public:
using ServerHandle = int;
class ServerCreationFailed : public std::exception { };
ServerManager() = default;
~ServerManager();
/*
* Create a managed server using P as the Session (CRTP-base) derived
* protocol.
*/
template <class P>
ServerHandle create_server(auto config);
AbstractServer* get_server(ServerHandle sh);
std::vector<ServerInfo> get_servers_info();
bool validate_server_handle(ServerHandle sh);
void wait();
void stop();
void stop(ServerHandle sh);
#ifdef ENABLE_STATISTICS
std::vector<LSStats> get_stats() const;
#endif
private:
std::map<ServerHandle, AbstractServer*> servers_;
ServerHandle handle_id_ = 0;
};
template <class P>
inline ServerManager::ServerHandle
ServerManager::create_server(auto config)
{
auto srv = new Server<P>(config);
auto [iter, inserted] = servers_.insert(std::make_pair(handle_id_++, srv));
if (!inserted) {
delete srv;
throw ServerCreationFailed{};
}
srv->dispatch();
return iter->first;
}
} // namespace lserver | 33.383721 | 79 | 0.723093 | AmbrSb |
ea32df2408f04df4e0b388293744f483005b0d31 | 5,650 | hh | C++ | Xtide/xtide-2.14/libxtide/config.hh | lobrien/TideMonkey | 296d8d24f25f5ef5aeafa1bab4a82246843fe9a7 | [
"MIT"
] | 1 | 2019-05-01T19:56:38.000Z | 2019-05-01T19:56:38.000Z | Xtide/xtide-2.14/libxtide/config.hh | lobrien/TideMonkey | 296d8d24f25f5ef5aeafa1bab4a82246843fe9a7 | [
"MIT"
] | null | null | null | Xtide/xtide-2.14/libxtide/config.hh | lobrien/TideMonkey | 296d8d24f25f5ef5aeafa1bab4a82246843fe9a7 | [
"MIT"
] | null | null | null | // $Id: config.hh 5748 2014-10-11 19:38:53Z flaterco $
// Compiled-in defaults for settings.
// These are XTide's internal configurables ("settings") which can be
// overridden at run time. If you were looking for the GNU standard config.h
// that is generated by autoconf and contains immutable installation choices
// about such things as what libraries were linked, see autoconf-defines.h.
/* Copyright (C) 2007 David Flater.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Normally, the values of configurables should be obtained via
// Global::settings, and there is no reason for any module other than
// Settings.cc to include this file. However, xxX.cc uses defmonofont as a
// fallback so that xtide can still start when the setting is screwed.
// The order of precedence, from least significant to most
// significant, is:
// 1. config.hh
// 2. Xdefaults (X resources)
// 3. ~/.xtide.xml (Control Panel)
// 4. Command line
// Note that only xtide (not xttpd or tide) reads Xdefaults.
namespace libxtide {
// Default monospace font.
static constString defmonofont =
#ifdef HAVE_XAW3DXFT
"LiberationMono-12";
#else
"-misc-fixed-medium-r-normal--13-100-100-100-c-70-iso8859-1";
#endif
// Default graph font. "embedded" means use the font that is compiled into
// Global.cc.
static constString defgraphfont = "embedded";
// There is no define for the default *default* font that is used for button
// labels and verbiage in text window; that is as incoming from X11 or
// libXaw3dXft.
// Default colors.
static constString bgdefcolor = "white";
static constString fgdefcolor = "black";
static constString markdefcolor = "red";
static constString buttondefcolor = "gray80";
static constString daydefcolor = "SkyBlue";
static constString nightdefcolor = "DeepSkyBlue";
static constString flooddefcolor = "Blue";
static constString ebbdefcolor = "SeaGreen";
static constString datumdefcolor = "white";
static constString msldefcolor = "yellow";
static constString tidedotdefcolor = "red";
static constString currentdotdefcolor = "rgb:00/A0/00";
// Default opacity of the fill in graph style s (semitransparent).
static const double deftideopacity = 0.65;
// Default style of graphs and clocks.
static const char defgraphstyle = 'd';
// Default graph width and height (pixels), and aspect.
static const unsigned defgwidth = 960U;
static const unsigned defgheight = 312U;
static const double defgaspect = 1.0;
// Default clock width and height (pixels).
static const unsigned defcwidth = 84U;
static const unsigned defcheight = 312U;
// Default width of ASCII graphs and banners (characters).
static const unsigned defttywidth = 79U;
// Default height of ASCII graphs (characters).
static const unsigned defttyheight = 24U;
// Default length and width of paper in LaTeX output (mm). This need
// not match your actual paper; use "Shrink oversized pages" in print
// options.
static const double defpageheight = 420.0;
static const double defpagewidth = 297.0;
static const double defpagemargin = 10.0;
// Label tenths of units in tide graphs?
static const char graphtenths = 'n';
// Draw datum and middle-level lines?
static const char extralines = 'n';
// Prefer flat map to round globe location chooser?
static const char flatearth = 'n';
// Create tide clocks with buttons?
static const char cbuttons = 'n';
// Draw depth lines on top of graph?
static const char toplines = 'n';
// Draw tide graph as a line graph?
static const char nofill = 'n';
// Pagebreak and header before every month of a calendar?
static const char pagebreak = 'y';
// Linebreak before prediction value in calendars?
static const char linebreak = 'n';
// Print numbers with no ft/m/kt? Usually a very bad idea.
static const char omitunits = 'n';
// Events to suppress (p = phase of moon, S = sunrise, s = sunset, M =
// moonrise, m = moonset), or x to suppress none.
static constString eventmask = "x";
// Infer constituents? (Expert use only)
static const char infer = 'n';
// Default width of lines in line graphs
static const double deflwidth = 2.5;
// Default preferred units: ft, m, or x (no preference).
static constString prefunits = "x";
// Force UTC?
static const char forceZuluTime = 'n';
// Date, time, hour formats.
static constString datefmt = "%Y-%m-%d";
static constString caldayfmt = "%a %d";
// For US-style AM/PM
#ifdef HAVE_GOOD_STRFTIME
static constString hourfmt = "%l";
static constString timefmt = "%l:%M %p %Z";
#else
static constString hourfmt = "%I";
static constString timefmt = "%I:%M %p %Z";
#endif
// For 24-hour time with no AM/PM, use
// hourfmt "%H"
// timefmt "%H:%M %Z"
// See the man page for strftime to learn how to alter the formats
// to do other things.
// Default center longitude for location chooser.
// Valid values: -180 -150 -120 -90 -60 -30 0 30 60 90 120 150 360
// 360 will pick the longitude with the most tide stations.
static const double defgl = 360.0;
}
| 33.832335 | 77 | 0.72177 | lobrien |
ea342c66e8b83ea52d6a16d41b837cd1f9ab2941 | 976 | cpp | C++ | DataOrientedDesign/BoatsTestCase/dod_boat.cpp | SpowNzz/HellocplusplusBlog | 492dee9dcce85e3a85fbe3d7fe23fb4d83b4f37b | [
"MIT"
] | null | null | null | DataOrientedDesign/BoatsTestCase/dod_boat.cpp | SpowNzz/HellocplusplusBlog | 492dee9dcce85e3a85fbe3d7fe23fb4d83b4f37b | [
"MIT"
] | null | null | null | DataOrientedDesign/BoatsTestCase/dod_boat.cpp | SpowNzz/HellocplusplusBlog | 492dee9dcce85e3a85fbe3d7fe23fb4d83b4f37b | [
"MIT"
] | null | null | null | #include "dod_boat.h"
#include <cassert>
void BoatRentalDataStore::CreateBoatMonthlyRentalInfo(const string& inName,
unsigned int inNrOfRents,
float inMaintenanceCostPerRent,
float inEarningsPerRent)
{
m_BoatNames.push_back(inName);
m_MaintenanceCostData.push_back({ inNrOfRents, inMaintenanceCostPerRent });
m_EarningsData.push_back({ inNrOfRents, inEarningsPerRent });
}
float BoatRentalDataStore::CalculateAverageReturnOnInvestent() const
{
float combined_costs = 0.0f;
for (auto &data : m_MaintenanceCostData)
combined_costs += data.m_NrOfRents * data.m_MaintenanceCostPerRent;
float combined_earnings = 0.0f;
for (auto &data : m_EarningsData)
combined_earnings += data.m_NrOfRents * data.m_EarningsPerRent;
return (combined_earnings / combined_costs) * 100.0f - 100.0f;
}
void BoatRentalDataStore::SetEstimatedAverageReturnOnInvestment(const float inValue)
{
m_EstimatedAverageReturnOnInvestment = inValue;
} | 32.533333 | 84 | 0.773566 | SpowNzz |
ea361b97cca06a318a30d699eefb1be5dc682013 | 5,878 | cpp | C++ | libs/cephes/cephes.cpp | pvavercak/randomness-testing-toolkit | 8a29349edee0dc44bc8e765708555dda57b9e339 | [
"MIT"
] | 16 | 2016-11-09T15:45:52.000Z | 2021-03-05T13:52:24.000Z | libs/cephes/cephes.cpp | pvavercak/randomness-testing-toolkit | 8a29349edee0dc44bc8e765708555dda57b9e339 | [
"MIT"
] | 36 | 2015-10-13T19:22:57.000Z | 2020-05-12T16:23:55.000Z | libs/cephes/cephes.cpp | pvavercak/randomness-testing-toolkit | 8a29349edee0dc44bc8e765708555dda57b9e339 | [
"MIT"
] | 4 | 2016-08-21T00:37:01.000Z | 2022-02-10T16:06:41.000Z | #include <stdio.h>
#include <math.h>
#include "cephes.h"
static const double rel_error = 1E-12;
double MACHEP = 1.11022302462515654042E-16; // 2**-53
double MAXLOG = 7.09782712893383996732224E2; // log(MAXNUM)
double MAXNUM = 1.7976931348623158E308; // 2**1024*(1-MACHEP)
double PI = 3.14159265358979323846; // pi, duh!
static double big = 4.503599627370496e15;
static double biginv = 2.22044604925031308085e-16;
int sgngam = 0;
double Cephes::cephes_igamc(double a, double x) {
double ans, ax, c, yc, r, t, y, z;
double pk, pkm1, pkm2, qk, qkm1, qkm2;
if ( (x <= 0) || ( a <= 0) )
return( 1.0 );
if ( (x < 1.0) || (x < a) )
return( 1.e0 - cephes_igam(a,x) );
ax = a * log(x) - x - cephes_lgam(a);
if ( ax < -MAXLOG ) {
printf("igamc: UNDERFLOW\n");
return 0.0;
}
ax = exp(ax);
/* continued fraction */
y = 1.0 - a;
z = x + y + 1.0;
c = 0.0;
pkm2 = 1.0;
qkm2 = x;
pkm1 = x + 1.0;
qkm1 = z * x;
ans = pkm1/qkm1;
do {
c += 1.0;
y += 1.0;
z += 2.0;
yc = y * c;
pk = pkm1 * z - pkm2 * yc;
qk = qkm1 * z - qkm2 * yc;
if ( qk != 0 ) {
r = pk/qk;
t = fabs( (ans - r)/r );
ans = r;
}
else
t = 1.0;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if ( fabs(pk) > big ) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
} while ( t > MACHEP );
return ans*ax;
}
double Cephes::cephes_igam(double a, double x)
{
double ans, ax, c, r;
if ( (x <= 0) || ( a <= 0) )
return 0.0;
if ( (x > 1.0) && (x > a ) )
return 1.e0 - cephes_igamc(a,x);
/* Compute x**a * exp(-x) / gamma(a) */
ax = a * log(x) - x - cephes_lgam(a);
if ( ax < -MAXLOG ) {
printf("igam: UNDERFLOW\n");
return 0.0;
}
ax = exp(ax);
/* power series */
r = a;
c = 1.0;
ans = 1.0;
do {
r += 1.0;
c *= x/r;
ans += c;
} while ( c/ans > MACHEP );
return ans * ax/a;
}
/* A[]: Stirling's formula expansion of log gamma
* B[], C[]: log gamma function between 2 and 3
*/
static unsigned short A[] = {
0x6661,0x2733,0x9850,0x3f4a,
0xe943,0xb580,0x7fbd,0xbf43,
0x5ebb,0x20dc,0x019f,0x3f4a,
0xa5a1,0x16b0,0xc16c,0xbf66,
0x554b,0x5555,0x5555,0x3fb5
};
static unsigned short B[] = {
0x6761,0x8ff3,0x8901,0xc095,
0xb93e,0x355b,0xf234,0xc0e2,
0x89e5,0xf890,0x3d73,0xc114,
0xdb51,0xf994,0xbc82,0xc131,
0xf20b,0x0219,0x4589,0xc13a,
0x055e,0x5418,0x0c67,0xc12a
};
static unsigned short C[] = {
/*0x0000,0x0000,0x0000,0x3ff0,*/
0x12b2,0x1cf3,0xfd0d,0xc075,
0xd757,0x7b89,0xaa0d,0xc0d0,
0x4c9b,0xb974,0xeb84,0xc10a,
0x0043,0x7195,0x6286,0xc131,
0xf34c,0x892f,0x5255,0xc143,
0xe14a,0x6a11,0xce4b,0xc13e
};
#define MAXLGM 2.556348e305
/* Logarithm of gamma function */
double Cephes::cephes_lgam(double x)
{
double p, q, u, w, z;
int i;
sgngam = 1;
if ( x < -34.0 ) {
q = -x;
w = cephes_lgam(q); /* note this modifies sgngam! */
p = floor(q);
if ( p == q ) {
lgsing:
goto loverf;
}
i = (int)p;
if ( (i & 1) == 0 )
sgngam = -1;
else
sgngam = 1;
z = q - p;
if ( z > 0.5 ) {
p += 1.0;
z = p - q;
}
z = q * sin( PI * z );
if ( z == 0.0 )
goto lgsing;
/* z = log(PI) - log( z ) - w;*/
z = log(PI) - log( z ) - w;
return z;
}
if ( x < 13.0 ) {
z = 1.0;
p = 0.0;
u = x;
while ( u >= 3.0 ) {
p -= 1.0;
u = x + p;
z *= u;
}
while ( u < 2.0 ) {
if ( u == 0.0 )
goto lgsing;
z /= u;
p += 1.0;
u = x + p;
}
if ( z < 0.0 ) {
sgngam = -1;
z = -z;
}
else
sgngam = 1;
if ( u == 2.0 )
return( log(z) );
p -= 2.0;
x = x + p;
p = x * cephes_polevl( x, (double *)B, 5 ) / cephes_p1evl( x, (double *)C, 6);
return log(z) + p;
}
if ( x > MAXLGM ) {
loverf:
printf("lgam: OVERFLOW\n");
return sgngam * MAXNUM;
}
q = ( x - 0.5 ) * log(x) - x + log( sqrt( 2*PI ) );
if ( x > 1.0e8 )
return q;
p = 1.0/(x*x);
if ( x >= 1000.0 )
q += (( 7.9365079365079365079365e-4 * p
- 2.7777777777777777777778e-3) *p
+ 0.0833333333333333333333) / x;
else
q += cephes_polevl( p, (double *)A, 4 ) / x;
return q;
}
double Cephes::cephes_polevl(double x, double *coef, int N)
{
double ans;
int i;
double *p;
p = coef;
ans = *p++;
i = N;
do
ans = ans * x + *p++;
while ( --i );
return ans;
}
double Cephes::cephes_p1evl(double x, double *coef, int N)
{
double ans;
double *p;
int i;
p = coef;
ans = x + *p++;
i = N-1;
do
ans = ans * x + *p++;
while ( --i );
return ans;
}
double Cephes::cephes_erf(double x)
{
static const double two_sqrtpi = 1.128379167095512574;
double sum = x, term = x, xsqr = x * x;
int j = 1;
if ( fabs(x) > 2.2 )
return 1.0 - cephes_erfc(x);
do {
term *= xsqr/j;
sum -= term/(2*j+1);
j++;
term *= xsqr/j;
sum += term/(2*j+1);
j++;
} while ( fabs(term)/sum > rel_error );
return two_sqrtpi*sum;
}
double Cephes::cephes_erfc(double x)
{
static const double one_sqrtpi = 0.564189583547756287;
double a = 1, b = x, c = x, d = x*x + 0.5;
double q1, q2 = b/d, n = 1.0, t;
if ( fabs(x) < 2.2 )
return 1.0 - cephes_erf(x);
if ( x < 0 )
return 2.0 - cephes_erfc(-x);
do {
t = a*n + b*x;
a = b;
b = t;
t = c*n + d*x;
c = d;
d = t;
n += 0.5;
q1 = q2;
q2 = b/d;
} while ( fabs(q1-q2)/q2 > rel_error );
return one_sqrtpi*exp(-x*x)*q2;
}
double Cephes::cephes_normal(double x)
{
double arg, result, sqrt2=1.414213562373095048801688724209698078569672;
if (x > 0) {
arg = x/sqrt2;
result = 0.5 * ( 1 + erf(arg) );
}
else {
arg = -x/sqrt2;
result = 0.5 * ( 1 - erf(arg) );
}
return( result);
}
| 18.254658 | 81 | 0.511058 | pvavercak |
ea3a761d00b86c8e52afada1c16a001475086bb6 | 1,890 | cpp | C++ | simplelinearregression.cpp | JUNZ1/Godot_MachineLearning | d596b695056839f7a610375bfc81dfdf0c654210 | [
"MIT"
] | 16 | 2020-08-11T19:53:34.000Z | 2022-02-15T15:05:07.000Z | simplelinearregression.cpp | JUNZ1/Godot_MachineLearning | d596b695056839f7a610375bfc81dfdf0c654210 | [
"MIT"
] | 1 | 2020-08-11T17:23:29.000Z | 2020-08-11T17:23:29.000Z | simplelinearregression.cpp | JUNZ1/Godot_MachineLearning | d596b695056839f7a610375bfc81dfdf0c654210 | [
"MIT"
] | null | null | null | #include "simplelinearregression.h"
SimpleLinearRegression::SimpleLinearRegression()
{
_simpleLR.TrainingFinish = std::bind(&SimpleLinearRegression::BinderForFinished,this,std::placeholders::_1);
ADD_SIGNAL(MethodInfo("TrainingFinished", PropertyInfo(Variant::BOOL, "TEST TEXT")));
}
SimpleLinearRegression::SimpleLinearRegression(const SimpleLinearRegression& copyFromthis)
{
this->_simpleLR = copyFromthis._simpleLR;
}
SimpleLinearRegression::SimpleLinearRegression(SimpleLinearRegression&& moveFromthis)
{
this->_simpleLR = moveFromthis._simpleLR;
}
void SimpleLinearRegression::_bind_methods()
{
ClassDB::bind_method(D_METHOD("TestFunc"), &SimpleLinearRegression::TestFunc);
ClassDB::bind_method(D_METHOD("SetInputs","InputArray"), &SimpleLinearRegression::SetInputs);
ClassDB::bind_method(D_METHOD("SetOutputs","OutputArray"), &SimpleLinearRegression::SetOutputs);
ClassDB::bind_method(D_METHOD("StartTraining"), &SimpleLinearRegression::StartTraining);
ClassDB::bind_method(D_METHOD("CalculateOutput","InputValue"), &SimpleLinearRegression::CalculateOutput);
}
String SimpleLinearRegression::TestFunc()
{
//Just a simple "is this Working ?" lines..
std::string testReturn{"Simple Linear Regression Test Ok"};
String tryThis(testReturn.c_str());
return tryThis;
}
void SimpleLinearRegression::BinderForFinished(bool input)
{
std::cout<<"Training Finished"<<std::endl;
emit_signal("TrainingFinished", true);
}
void SimpleLinearRegression::StartTraining(void)
{
std::cout<<"Training Start Command Received"<<std::endl;
_simpleLR.SetInputs(GetInputVector());
_simpleLR.SetOutputs(GetOutputVector());
_simpleLR.Train();
}
real_t SimpleLinearRegression::CalculateOutput(real_t calculateThis)
{
std::cout<<"Calculate Output CMD received Value: "<<calculateThis<<std::endl;
std::vector<double> output = _simpleLR.Predict({calculateThis});
return output[0];
}
| 32.033898 | 109 | 0.790476 | JUNZ1 |
ea3d8a4b4bb50a105e1c1edb306cb86dab38d31e | 843 | hpp | C++ | FileLoad/f_load.hpp | Rintarooo/DTAM_Mapping | 4da777b9b50c01c44307b583733726e471c56b98 | [
"MIT"
] | null | null | null | FileLoad/f_load.hpp | Rintarooo/DTAM_Mapping | 4da777b9b50c01c44307b583733726e471c56b98 | [
"MIT"
] | null | null | null | FileLoad/f_load.hpp | Rintarooo/DTAM_Mapping | 4da777b9b50c01c44307b583733726e471c56b98 | [
"MIT"
] | null | null | null | #ifndef FILELOADER_H
#define FILELOADER_H
#include <iostream>
#include <string> // string
#include <fstream> // ifstream, ofstream
#include <sstream> // stringstream
#include <vector>
#include <opencv2/opencv.hpp>
#include <iomanip> // https://stackoverflow.com/questions/225362/convert-a-number-to-a-string-with-specified-length-in-c
void file_loader_fou (const std::string&,
std::vector<std::string>&,
std::vector<cv::Mat>&,
std::vector<cv::Mat>&);
void file_loader_tum (const std::string&,
std::vector<std::string>&,
std::vector<cv::Mat>&,
std::vector<cv::Mat>&);
void file_loader_icl (const std::string&,
std::vector<std::string>&,
std::vector<cv::Mat>&,
std::vector<cv::Mat>&);
void file_loader_aha (const std::string&,
std::vector<std::string>&,
std::vector<cv::Mat>&,
std::vector<cv::Mat>&);
#endif | 26.34375 | 120 | 0.685647 | Rintarooo |
ea3e3d8ee026aa880443e59e5ece0579daaf87ec | 4,552 | cpp | C++ | build/main/Player.cpp | walthill/final-crusade | 4533651b6a4cf55665ea864cb1cb2d40beaf4ee3 | [
"Apache-2.0"
] | null | null | null | build/main/Player.cpp | walthill/final-crusade | 4533651b6a4cf55665ea864cb1cb2d40beaf4ee3 | [
"Apache-2.0"
] | null | null | null | build/main/Player.cpp | walthill/final-crusade | 4533651b6a4cf55665ea864cb1cb2d40beaf4ee3 | [
"Apache-2.0"
] | null | null | null | #include "Player.h"
#include "Game.h"
Player::Player()
{
mPlayerFrameSpeed = 16;
mVelocity = 4;
mXBound = 0;
mYBound = 0; //map size
lastLife = false;
dtTime = 0;
invulnerableTime = 3000;
}
Player::~Player()
{
}
void Player::init(int xBounds, int yBounds, string hitAudioId)
{
playerHit = hitAudioId;
mXBound = xBounds;
mYBound = yBounds;
}
void Player::update(double timeElapsed, vector<Collider*> colliderList, int mouseX, int mouseY, int camX, int camY)
{
if (mIsVisible)
{
Entity::update(timeElapsed);
if (timeElapsed > mPlayerFrameSpeed)
{
if (!mControllerConnected)
rotate(mouseX, mouseY, camX, camY);
else
{
angle = (atan2(mouseX, -mouseY)*DEGREE_CONVERSION_VAL) / PI;
setRotation(angle+ ANGLE_OFFSET);
}
checkBounds();
checkForEnemyCollision(colliderList, timeElapsed);
//checkForFragmentCollision(colliderList);
move(mouseX, mouseY, camX, camY);
}
}
}
void Player::checkBounds()
{
if (mXLoc < 0)
mXLoc = 1;
if (mXLoc > mXBound)
mXLoc = mXBound-5.0f;
if (mYLoc < 0)
mYLoc = 1;
if (mYLoc > mYBound)
mYLoc = mYBound-5.0f;
}
void Player::checkForEnemyCollision(vector<Collider*> colliderList, double timeElapsed)
{
for (unsigned int i = 0; i < colliderList.size(); i++)
{
b = *colliderList[i];
if (checkCollision(&mThisCollider, &b) && !collisionDetected)
{
if (b.getTag() == "ronin" || b.getTag() == "mountain" ||
b.getTag() == "enemyBullet" || b.getTag() == "hive")
{
//b.getEntity()->setVisible(false);
if (!lastLife) //first hit - send to near death
{
Game::getInstance()->_Scene->playSfx(playerHit);
collisionDetected = true;
mShouldAnimate = true;
mAnim.setLooping(true); //death should go to lose screen //cout << "ENEMY COLLISION" << endl; //TODO(high): player death
lastLife = true;
Game::getInstance()->endCombo();
}
else if (hasRecovered)
{
mIsVisible = false; //lose screen
lastLife = false;
}
}
/* else if (b.getTag() == "fragment")
{
cout << "COLLISION" << endl;
}*/
}
else
{
mHasCollided = false;
}
}
if (lastLife && dtTime < invulnerableTime)
{
dtTime += timeElapsed;
if (dtTime > invulnerableTime)
{
hasRecovered = true;
collisionDetected = false;
mAnim.setSpriteIndex(1);
mAnim.setLooping(false);
dtTime = 0;
}
}
}
/*
void Player::checkForFragmentCollision(vector<Collider*> colliderList)
{
for (unsigned int i = 0; i < colliderList.size(); i++)
{
Collider b = *colliderList[i];
if (checkCollision(mThisCollider, b))
{
if (b.getTag() == "ronin" || b.getTag() == "mountain")
{
}
}
}
}*/
/*bool Player::checkCollision(Collider a, Collider b)
{
}*/
void Player::move(int mouseX, int mouseY, int camX, int camY)
{
//Help from WAKS on the c++ forums @ https://bit.ly/2KHZL8T
if (mLeft)
{
mXLoc += -mVelocity;
}
if (mRight)
{
mXLoc += mVelocity;
}
if (mUp)
{
mYLoc += -mVelocity;
}
if (mDown)
{
mYLoc += mVelocity;
}
if(!mControllerConnected)
rotate(mouseX, mouseY, camX, camY);
}
void Player::rotate(int mouseX, int mouseY, int camX, int camY)
{
//Math salvation from jordsti on StackOverflow @ https://bit.ly/2KrJx7Y
if (mouseX != 0)
{
//subtract camera position to accurately rotate outside of screen space coordinates
dX = (mXLoc - camX) - mouseX;
dY = (mYLoc + ROT_ALIGNMENT - camY) - mouseY;
angle = (atan2(dY, dX)*DEGREE_CONVERSION_VAL) / PI;
setRotation(angle);
}
}
void Player::setLeft(bool isMovingLeft)
{
mLeft = isMovingLeft;
}
void Player::setRight(bool isMovingRight)
{
mRight = isMovingRight;
}
void Player::setDown(bool isMovingDown)
{
mDown = isMovingDown;
}
void Player::setUp(bool isMovingUp)
{
mUp= isMovingUp;
}
int Player::getWidth()
{
return mAnim.getCurrentSprite().getSpriteWidth();
}
int Player::getHeight()
{
return mAnim.getCurrentSprite().getSpriteHeight();
}
bool Player::isLastLife()
{
return lastLife;
}
void Player::setLastLife(bool isLastLife)
{
lastLife = isLastLife;
}
void Player::setCollisionDetected(bool colDetected)
{
collisionDetected = colDetected;
}
bool Player::isCollisionDetected()
{
return collisionDetected;
}
void Player::setControllerConnected(bool controllerConnected)
{
mControllerConnected = controllerConnected;
} | 19.046025 | 129 | 0.623682 | walthill |
ea40e6193b9dd77573d66db31a16c63e87541c04 | 165 | cpp | C++ | atcoder/abc099/A.cpp | SashiRin/protrode | c03d0a6e9a5ac87d0f3d3af5d39b05a10f58527c | [
"MIT"
] | 1 | 2019-08-03T13:42:16.000Z | 2019-08-03T13:42:16.000Z | atcoder/abc099/A.cpp | SashiRin/protrode | c03d0a6e9a5ac87d0f3d3af5d39b05a10f58527c | [
"MIT"
] | null | null | null | atcoder/abc099/A.cpp | SashiRin/protrode | c03d0a6e9a5ac87d0f3d3af5d39b05a10f58527c | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
cout << ((n < 1000) ? "ABC" : "ABD") << endl;
return 0;
}
| 12.692308 | 49 | 0.521212 | SashiRin |
ea4544e8f8fdd2ee21f84537eb8b7aa7dbecc39c | 13,717 | cpp | C++ | GeneratedFiles/Debug/moc_std.toolbar.cpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | GeneratedFiles/Debug/moc_std.toolbar.cpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | GeneratedFiles/Debug/moc_std.toolbar.cpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'std.toolbar.hpp'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../include/std.toolbar.hpp"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'std.toolbar.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_std__ToolBar_t {
QByteArrayData data[24];
char stringdata0[318];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_std__ToolBar_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_std__ToolBar_t qt_meta_stringdata_std__ToolBar = {
{
QT_MOC_LITERAL(0, 0, 12), // "std::ToolBar"
QT_MOC_LITERAL(1, 13, 9), // "OnCommand"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 7), // "Action*"
QT_MOC_LITERAL(4, 32, 7), // "pAction"
QT_MOC_LITERAL(5, 40, 8), // "ToolBar*"
QT_MOC_LITERAL(6, 49, 7), // "pSender"
QT_MOC_LITERAL(7, 57, 21), // "OnAllowedAreasChanged"
QT_MOC_LITERAL(8, 79, 16), // "Qt::ToolBarAreas"
QT_MOC_LITERAL(9, 96, 7), // "tbAreas"
QT_MOC_LITERAL(10, 104, 17), // "OnIconSizeChanged"
QT_MOC_LITERAL(11, 122, 9), // "sIconsize"
QT_MOC_LITERAL(12, 132, 16), // "OnMovableChanged"
QT_MOC_LITERAL(13, 149, 8), // "bMovable"
QT_MOC_LITERAL(14, 158, 20), // "OnOrientationChanged"
QT_MOC_LITERAL(15, 179, 15), // "Qt::Orientation"
QT_MOC_LITERAL(16, 195, 12), // "oOrientation"
QT_MOC_LITERAL(17, 208, 24), // "OnToolButtonStyleChanged"
QT_MOC_LITERAL(18, 233, 19), // "Qt::ToolButtonStyle"
QT_MOC_LITERAL(19, 253, 7), // "tbStyle"
QT_MOC_LITERAL(20, 261, 17), // "OnTopLevelChanged"
QT_MOC_LITERAL(21, 279, 9), // "bTopLevel"
QT_MOC_LITERAL(22, 289, 19), // "OnVisibilityChanged"
QT_MOC_LITERAL(23, 309, 8) // "bVisible"
},
"std::ToolBar\0OnCommand\0\0Action*\0pAction\0"
"ToolBar*\0pSender\0OnAllowedAreasChanged\0"
"Qt::ToolBarAreas\0tbAreas\0OnIconSizeChanged\0"
"sIconsize\0OnMovableChanged\0bMovable\0"
"OnOrientationChanged\0Qt::Orientation\0"
"oOrientation\0OnToolButtonStyleChanged\0"
"Qt::ToolButtonStyle\0tbStyle\0"
"OnTopLevelChanged\0bTopLevel\0"
"OnVisibilityChanged\0bVisible"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_std__ToolBar[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
8, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
8, // signalCount
// signals: name, argc, parameters, tag, flags
1, 2, 54, 2, 0x06 /* Public */,
7, 2, 59, 2, 0x06 /* Public */,
10, 2, 64, 2, 0x06 /* Public */,
12, 2, 69, 2, 0x06 /* Public */,
14, 2, 74, 2, 0x06 /* Public */,
17, 2, 79, 2, 0x06 /* Public */,
20, 2, 84, 2, 0x06 /* Public */,
22, 2, 89, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void, 0x80000000 | 3, 0x80000000 | 5, 4, 6,
QMetaType::Void, 0x80000000 | 8, 0x80000000 | 5, 9, 6,
QMetaType::Void, QMetaType::QSize, 0x80000000 | 5, 11, 6,
QMetaType::Void, QMetaType::Bool, 0x80000000 | 5, 13, 6,
QMetaType::Void, 0x80000000 | 15, 0x80000000 | 5, 16, 6,
QMetaType::Void, 0x80000000 | 18, 0x80000000 | 5, 19, 6,
QMetaType::Void, QMetaType::Bool, 0x80000000 | 5, 21, 6,
QMetaType::Void, QMetaType::Bool, 0x80000000 | 5, 23, 6,
0 // eod
};
void std::ToolBar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
ToolBar *_t = static_cast<ToolBar *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->OnCommand((*reinterpret_cast< Action*(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
case 1: _t->OnAllowedAreasChanged((*reinterpret_cast< Qt::ToolBarAreas(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
case 2: _t->OnIconSizeChanged((*reinterpret_cast< const QSize(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
case 3: _t->OnMovableChanged((*reinterpret_cast< const bool(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
case 4: _t->OnOrientationChanged((*reinterpret_cast< Qt::Orientation(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
case 5: _t->OnToolButtonStyleChanged((*reinterpret_cast< Qt::ToolButtonStyle(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
case 6: _t->OnTopLevelChanged((*reinterpret_cast< const bool(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
case 7: _t->OnVisibilityChanged((*reinterpret_cast< const bool(*)>(_a[1])),(*reinterpret_cast< ToolBar*(*)>(_a[2]))); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< Action* >(); break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
case 1:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
case 2:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
case 3:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
case 4:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
case 5:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
case 6:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
case 7:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< ToolBar* >(); break;
}
break;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (ToolBar::*_t)(Action * , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnCommand)) {
*result = 0;
}
}
{
typedef void (ToolBar::*_t)(Qt::ToolBarAreas , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnAllowedAreasChanged)) {
*result = 1;
}
}
{
typedef void (ToolBar::*_t)(const QSize & , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnIconSizeChanged)) {
*result = 2;
}
}
{
typedef void (ToolBar::*_t)(bool const & , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnMovableChanged)) {
*result = 3;
}
}
{
typedef void (ToolBar::*_t)(Qt::Orientation , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnOrientationChanged)) {
*result = 4;
}
}
{
typedef void (ToolBar::*_t)(Qt::ToolButtonStyle , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnToolButtonStyleChanged)) {
*result = 5;
}
}
{
typedef void (ToolBar::*_t)(bool const & , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnTopLevelChanged)) {
*result = 6;
}
}
{
typedef void (ToolBar::*_t)(bool const & , ToolBar * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ToolBar::OnVisibilityChanged)) {
*result = 7;
}
}
}
}
const QMetaObject std::ToolBar::staticMetaObject = {
{ &QToolBar::staticMetaObject, qt_meta_stringdata_std__ToolBar.data,
qt_meta_data_std__ToolBar, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *std::ToolBar::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *std::ToolBar::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_std__ToolBar.stringdata0))
return static_cast<void*>(const_cast< ToolBar*>(this));
return QToolBar::qt_metacast(_clname);
}
int std::ToolBar::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QToolBar::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 8)
qt_static_metacall(this, _c, _id, _a);
_id -= 8;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 8)
qt_static_metacall(this, _c, _id, _a);
_id -= 8;
}
return _id;
}
// SIGNAL 0
void std::ToolBar::OnCommand(Action * _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void std::ToolBar::OnAllowedAreasChanged(Qt::ToolBarAreas _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void std::ToolBar::OnIconSizeChanged(const QSize & _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
// SIGNAL 3
void std::ToolBar::OnMovableChanged(bool const & _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
// SIGNAL 4
void std::ToolBar::OnOrientationChanged(Qt::Orientation _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 4, _a);
}
// SIGNAL 5
void std::ToolBar::OnToolButtonStyleChanged(Qt::ToolButtonStyle _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 5, _a);
}
// SIGNAL 6
void std::ToolBar::OnTopLevelChanged(bool const & _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 6, _a);
}
// SIGNAL 7
void std::ToolBar::OnVisibilityChanged(bool const & _t1, ToolBar * _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 7, _a);
}
QT_END_MOC_NAMESPACE
| 41.566667 | 147 | 0.573303 | wilsonsouza |
357ccc3d7794bc38c683b0d83e93df2ddc1eae5e | 3,879 | cpp | C++ | corelib/src/Monitor.cpp | supersaiyajinggod/VISFS | 6567df9b064437a32dc96d6f03ef6cd4ea1b24ce | [
"BSD-3-Clause"
] | 3 | 2021-06-09T13:20:59.000Z | 2022-01-14T13:31:11.000Z | corelib/src/Monitor.cpp | supersaiyajinggod/VISFS | 6567df9b064437a32dc96d6f03ef6cd4ea1b24ce | [
"BSD-3-Clause"
] | null | null | null | corelib/src/Monitor.cpp | supersaiyajinggod/VISFS | 6567df9b064437a32dc96d6f03ef6cd4ea1b24ce | [
"BSD-3-Clause"
] | null | null | null | #include <opencv2/highgui/highgui_c.h>
#include "Monitor.h"
#include "Stl.h"
namespace VISFS {
Monitor::Monitor(const ParametersMap & _parameters) :
sensorStrategy_(Parameters::defaultSystemSensorStrategy()) {
Parameters::parse(_parameters, Parameters::kSystemSensorStrategy(), sensorStrategy_);
}
void Monitor::addSignature(const Signature & _signature) {
std::lock_guard<std::mutex> lock(mutexDataRW_);
signatureBuf_.emplace(_signature);
}
void Monitor::threadProcess() {
while (1) {
Signature signature;
if (!signatureBuf_.empty()) {
{
std::lock_guard<std::mutex> lock(mutexDataRW_);
signature = signatureBuf_.front();
signatureBuf_.pop();
}
process(signature);
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
void Monitor::process(Signature & _signature) {
if (sensorStrategy_ == 0 || sensorStrategy_ >= 2) { // Stereo && Stereo + wheel
cv::Mat imageLeft = _signature.getImageLeft();
cv::Mat imageRight = _signature.getImageRight();
std::vector<cv::KeyPoint> kptsMatchesFormer = uValues(_signature.getKeyPointsMatchesFormer());
std::vector<cv::KeyPoint> kptsNewExtract = uValues(_signature.getKeyPointsNewExtract());
std::map<std::size_t, cv::KeyPoint> kptsMatchesLeftToRight = _signature.getKeyPointsMatchesImageRight();
std::map<std::size_t, cv::Point3f> words3d = _signature.getWords3d();
std::map<std::size_t, cv::KeyPoint> blockedWords = _signature.getBlockedWords();
if (sensorStrategy_ <= 3) {
cv::Mat stitch;
cv::hconcat(imageLeft, imageRight, stitch);
const float cols = static_cast<float>(imageLeft.cols);
for (auto kpt : kptsMatchesFormer) {
cv::circle(stitch, kpt.pt, 2, cv::Scalar(0, 0, 255), 1);
}
for (auto kpt : kptsNewExtract) {
cv::circle(stitch, kpt.pt, 2, cv::Scalar(255, 0, 0), 1);
}
for (auto blockedWord : blockedWords) {
// cv::Rect rect((blockedWord.second.pt.x - 10) < 0 ? 0 : (blockedWord.second.pt.x - 10), (blockedWord.second.pt.y - 10) < 0 ? 0 : (blockedWord.second.pt.y - 10), 20, 20);
// cv::rectangle(stitch, blockedWord.second.pt, blockedWord.second.pt, cv::Scalar(255, 0, 0));
cv::circle(stitch, blockedWord.second.pt, 10, cv::Scalar(255, 0, 0), 1);
}
assert(kptsMatchesLeftToRight.size() == words3d.size());
for (auto iter = kptsMatchesLeftToRight.begin(); iter != kptsMatchesLeftToRight.end(); ++iter) {
auto id = iter->first;
iter->second.pt.x += cols;
cv::circle(stitch, iter->second.pt, 2, cv::Scalar(176, 48, 96), 1);
auto jter = words3d.find(id);
if (jter != words3d.end()) {
if (std::isfinite(jter->second.z)) {
std::stringstream ss;
ss.precision(4);
std::string text;
ss << jter->second.x;
ss >> text;
cv::putText(stitch, text, iter->second.pt, cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(0, 255, 0), 2);
}
}
}
cv::namedWindow("Monitor", CV_WINDOW_NORMAL);
cv::imshow("Monitor", stitch);
cv::waitKey(5);
}
auto submap = _signature.getSubmap();
if (sensorStrategy_ >= 3 && !submap.empty()) {
cv::namedWindow("Submap");
cv::imshow("Submap", submap);
cv::waitKey(5);
}
} else if (sensorStrategy_ == 1) { // RGBD
}
}
} // namespace | 39.581633 | 187 | 0.55272 | supersaiyajinggod |
357dc2c2141c89de0b9d552cd46b1076521c22df | 2,273 | cpp | C++ | benchmark/src/benchmark_number.cpp | ivangalkin/spotify-json | 68cfafc488ffae851cca3f556b90129cffb26be1 | [
"Apache-2.0"
] | 192 | 2016-09-29T17:10:07.000Z | 2022-03-22T15:22:48.000Z | benchmark/src/benchmark_number.cpp | ivangalkin/spotify-json | 68cfafc488ffae851cca3f556b90129cffb26be1 | [
"Apache-2.0"
] | 35 | 2016-10-03T16:57:12.000Z | 2021-09-28T13:11:15.000Z | benchmark/src/benchmark_number.cpp | ivangalkin/spotify-json | 68cfafc488ffae851cca3f556b90129cffb26be1 | [
"Apache-2.0"
] | 47 | 2016-09-29T08:21:32.000Z | 2022-03-19T10:05:43.000Z | /*
* Copyright (c) 2016 Spotify AB
*
* 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 <string>
#include <boost/test/unit_test.hpp>
#include <spotify/json/codec/number.hpp>
#include <spotify/json/decode.hpp>
#include <spotify/json/encode.hpp>
#include <spotify/json/encode_context.hpp>
#include <spotify/json/benchmark/benchmark.hpp>
BOOST_AUTO_TEST_SUITE(spotify)
BOOST_AUTO_TEST_SUITE(json)
BOOST_AUTO_TEST_SUITE(codec)
BOOST_AUTO_TEST_CASE(benchmark_json_codec_number_encode_positive_int32_t) {
const auto codec = number<int32_t>();
JSON_BENCHMARK(1e6, [=]{
auto context = encode_context();
for (int32_t i = 0; i < 10000000; i += 48071) {
codec.encode(context, i);
context.clear();
}
});
}
BOOST_AUTO_TEST_CASE(benchmark_json_codec_number_encode_positive_uint32_t) {
const auto codec = number<uint32_t>();
JSON_BENCHMARK(1e6, [=]{
auto context = encode_context();
for (uint32_t i = 0; i < 10000000; i += 48071) {
codec.encode(context, i);
context.clear();
}
});
}
BOOST_AUTO_TEST_CASE(benchmark_json_codec_number_encode_positive_int64_t) {
const auto codec = number<int64_t>();
JSON_BENCHMARK(1e6, [=]{
auto context = encode_context();
for (int64_t i = 0; i < 10000000; i += 48071) {
codec.encode(context, i);
context.clear();
}
});
}
BOOST_AUTO_TEST_CASE(benchmark_json_codec_number_encode_positive_uint64_t) {
const auto codec = number<uint64_t>();
JSON_BENCHMARK(1e6, [=]{
auto context = encode_context();
for (uint64_t i = 0; i < 10000000; i += 48071) {
codec.encode(context, i);
context.clear();
}
});
}
BOOST_AUTO_TEST_SUITE_END() // codec
BOOST_AUTO_TEST_SUITE_END() // json
BOOST_AUTO_TEST_SUITE_END() // spotify
| 28.772152 | 80 | 0.707435 | ivangalkin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.