hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
260f13fa0e1490d084a85a11714f4c4f9fa2d3ca | 3,216 | hpp | C++ | hpx/runtime/parcelset/policies/mpi/allocator.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | hpx/runtime/parcelset/policies/mpi/allocator.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | hpx/runtime/parcelset/policies/mpi/allocator.hpp | Titzi90/hpx | 150fb0de1cfe40c26a722918097199147957b45c | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2012 Hartmut Kaiser
// Copyright (c) 2013 Thomas Heller
// Copyright (c) 2006 Douglas Gregor
//
// 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)
// This file is an adaption of boost/mpi/allocator.hpp.
// We don't want to depend on Boost.Mpi because it might not be available on all
// supported platforms.
#ifndef HPX_PARCELSET_MPI_ALLOCATOR_HPP
#define HPX_PARCELSET_MPI_ALLOCATOR_HPP
#include <hpx/config.hpp>
#include <cstddef>
#include <memory>
#include <boost/limits.hpp>
namespace hpx { namespace parcelset { namespace mpi {
template <typename T> class allocator;
template <>
class allocator<void>
{
public:
typedef void* pointer;
typedef const void* const_pointer;
typedef void value_type;
template <typename U>
struct rebind
{
typedef allocator<U> other;
};
};
template <typename T>
class allocator
{
public:
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <typename U>
struct rebind
{
typedef allocator<U> other;
};
allocator() throw() {}
allocator(allocator const &) throw() {}
template <typename U>
allocator(allocator<U> const &) throw() {}
pointer address(reference x) const
{
return &x;
}
const_pointer address(const_reference x) const
{
return &x;
}
pointer allocate(size_type n, allocator<void>::const_pointer /*hint*/ = 0)
{
pointer result;
MPI_Alloc_mem(static_cast<MPI_Aint>(n * sizeof(T)), MPI_INFO_NULL, &result);
return result;
}
void deallocate(pointer p, size_type /*n*/)
{
MPI_Free_mem(p);
}
size_type max_size() const throw()
{
return (std::numeric_limits<std::size_t>::max)() / sizeof(T);
}
void construct(pointer p)
{
new ((void *)p) T();
}
void construct(pointer p, const T& val)
{
new ((void *)p) T(val);
}
/** Destroy the object referenced by @c p. */
void destroy(pointer p)
{
((T*)p)->~T();
}
};
template<typename T1, typename T2>
inline bool operator==(const allocator<T1>&, const allocator<T2>&) throw()
{
return true;
}
template<typename T1, typename T2>
inline bool operator!=(const allocator<T1>&, const allocator<T2>&) throw()
{
return false;
}
}}}
#endif
| 26.578512 | 92 | 0.522699 | [
"object"
] |
2616704fec0bd2dbb5de2c90c1581126eabc2665 | 223 | hpp | C++ | src/data/dict_loader_i.hpp | icorbrey/word-search-solver | d5b4738acf32bfb3cb99810f4dab56ae1aa6cee3 | [
"MIT"
] | null | null | null | src/data/dict_loader_i.hpp | icorbrey/word-search-solver | d5b4738acf32bfb3cb99810f4dab56ae1aa6cee3 | [
"MIT"
] | null | null | null | src/data/dict_loader_i.hpp | icorbrey/word-search-solver | d5b4738acf32bfb3cb99810f4dab56ae1aa6cee3 | [
"MIT"
] | null | null | null | #ifndef DICT_LOADER_I_HPP
#define DICT_LOADER_I_HPP
#include <string>
#include <vector>
class dict_loader_i
{
public:
virtual std::vector<std::string> load_dict(std::string path) = 0;
};
#endif // !DICT_LOADER_I_HPP
| 15.928571 | 69 | 0.744395 | [
"vector"
] |
262aa9859142d572db12cfafaf4817fcfb4f5a5e | 1,416 | cpp | C++ | cpp01/ex03/HumanA.cpp | pgomez-a/42_CPP_Piscine | c350f5f3c2e4d332b13bfa632b36f9a4b7bc6ce1 | [
"MIT"
] | null | null | null | cpp01/ex03/HumanA.cpp | pgomez-a/42_CPP_Piscine | c350f5f3c2e4d332b13bfa632b36f9a4b7bc6ce1 | [
"MIT"
] | null | null | null | cpp01/ex03/HumanA.cpp | pgomez-a/42_CPP_Piscine | c350f5f3c2e4d332b13bfa632b36f9a4b7bc6ce1 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* HumanA.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pgomez-a <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/04 15:29:28 by pgomez-a #+# #+# */
/* Updated: 2021/10/04 15:29:29 by pgomez-a ### ########.fr */
/* */
/* ************************************************************************** */
#include "HumanA.hpp"
/**
** Constructor of HumanA object
** Always take a name and a reference to a weapon
**/
HumanA::HumanA(std::string name, Weapon& weapon) : _weapon(weapon)
{
this->_name = name;
return ;
}
/**
** Destructor of a HumanA object
**/
HumanA::~HumanA(void)
{
return ;
}
/**
** Print an attack message
**/
void HumanA::attack(void) const
{
const std::string& weapon_type = this->_weapon.getType();
std::cout << this->_name << " attacks with his " << weapon_type << std::endl;
return ;
}
| 30.782609 | 80 | 0.300847 | [
"object"
] |
1c84e0b2482f813e9b9692c22f11bb69987c8062 | 3,684 | cpp | C++ | assignments/handofros_odroid/src/motion_node_service.cpp | robertsatya/ros-bot | 12ef876beee36ebb1d9af90c6e9d8b1b0a4a76d2 | [
"MIT"
] | null | null | null | assignments/handofros_odroid/src/motion_node_service.cpp | robertsatya/ros-bot | 12ef876beee36ebb1d9af90c6e9d8b1b0a4a76d2 | [
"MIT"
] | null | null | null | assignments/handofros_odroid/src/motion_node_service.cpp | robertsatya/ros-bot | 12ef876beee36ebb1d9af90c6e9d8b1b0a4a76d2 | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include "handofros_odroid/motion_node.h"
#include <geometry_msgs/PoseStamped.h>
#include <visualization_msgs/Marker.h>
// adadad
using namespace std;
ros::Publisher marker_pub;
ros::Publisher location_pub;
visualization_msgs::Marker marker;
geometry_msgs::Pose p;
bool select_mode(handofros_odroid::motion_node::Request &req, handofros_odroid::motion_node::Response &res);
int main(int argc, char **argv){
ros::init(argc, argv, "h_odroid_node");
ros::NodeHandle n,n1,n2;
ros::Rate r(1);
p.position.x = 0;
p.position.y = 0;
p.position.z = 0;
p.orientation.x = 0.0;
p.orientation.y = 0.0;
p.orientation.z = 0.0;
p.orientation.w = 1.0;
ros::ServiceServer service = n.advertiseService("motion_node_service",select_mode);
location_pub = n1.advertise<geometry_msgs::PoseStamped>("loc", 100);
marker_pub = n2.advertise<visualization_msgs::Marker>("visualization_marker", 1);
// Set our initial shape type to be a cube
uint32_t shape = visualization_msgs::Marker::CUBE;
marker.header.frame_id = "/my_frame";
marker.header.stamp = ros::Time::now();
// Set the namespace and id for this marker. This serves to create a unique ID
// Any marker sent with the same namespace and id will overwrite the old one
marker.ns = "motion_node";
marker.id = 0;
marker.action = visualization_msgs::Marker::ADD;
// Set the pose of the marker. This is a full 6DOF pose relative to the frame/time specified in the header
marker.pose.position = p.position;
marker.pose.orientation = p.orientation;
// Set the scale of the marker -- 1x1x1 here means 1m on a side
marker.scale.x = 1.0;
marker.scale.y = 1.0;
marker.scale.z = 1.0;
// Set the color -- be sure to set alpha to something non-zero!
marker.color.r = 0.0f;
marker.color.g = 1.0f;
marker.color.b = 0.0f;
marker.color.a = 1.0;
marker.lifetime = ros::Duration();
// Publish the marker
while (marker_pub.getNumSubscribers() < 1)
{
if (!ros::ok())
{
return 0;
}
ROS_WARN_ONCE("Please create a subscriber to the marker");
sleep(1);
}
// Set the marker type. Initially this is CUBE, and cycles between that and SPHERE, ARROW, and CYLINDER
marker.type = shape;
marker_pub.publish(marker);
r.sleep();
ros::spin();
return 0;
}
bool select_mode(handofros_odroid::motion_node::Request &req, handofros_odroid::motion_node::Response &res)
{
ros::NodeHandle n,n1;
res.mode = req.mode;
int dir = res.mode;
ROS_INFO("\n Selected mode is %d", dir);
ros::Rate r(1);
marker_pub = n.advertise<visualization_msgs::Marker>("visualization_marker", 1);
location_pub = n1.advertise<geometry_msgs::PoseStamped>("loc", 100);
// Set the frame ID and timestamp. See the TF tutorials for information on these.
marker.header.stamp = ros::Time::now();
marker.action = visualization_msgs::Marker::ADD;
// Set the pose of the marker. This is a full 6DOF pose relative to the frame/time specified in the header
float fb=0,lr=0;
if(dir==1)
fb = 0.5;
else if(dir==2)
fb = -0.5;
else if(dir==3)
lr = 0.5;
else if(dir==4)
lr = -0.5;
else return 0;
p.position.x += fb;
p.position.y += lr;
marker.pose.position = p.position;
marker.pose.orientation = p.orientation;
ROS_INFO(" %lf %lf \n",marker.pose.position.x,marker.pose.position.y);
// Publish the marker
marker_pub.publish(marker);
geometry_msgs::PoseStamped ps;
ps.header.stamp = ros::Time::now();
ps.header.frame_id = "/my_frame";
ps.pose = p;
location_pub.publish(ps);
if (res.mode == 0) {
exit(0);
}
return true;
}
| 27.288889 | 111 | 0.672367 | [
"shape"
] |
1c85549291b3cc5c49efb5cec13a19d344289b1f | 997 | cpp | C++ | src/StackTrace.cpp | jrialland/cpplogging | ba9e189dfe8a72959bc0abc87793be28ec2014a1 | [
"Unlicense"
] | null | null | null | src/StackTrace.cpp | jrialland/cpplogging | ba9e189dfe8a72959bc0abc87793be28ec2014a1 | [
"Unlicense"
] | null | null | null | src/StackTrace.cpp | jrialland/cpplogging | ba9e189dfe8a72959bc0abc87793be28ec2014a1 | [
"Unlicense"
] | null | null | null |
#include "StackTrace.hpp"
#include "execinfo.h"
#include <dlfcn.h>
#include <cxxabi.h>
std::string demangle(const char* name) {
int status;
char *demangled = abi::__cxa_demangle(name, NULL, 0, &status);
if(status == 0) {
string sdemangled(demangled);
if(demangled != NULL) {
free(demangled);
}
return sdemangled;
} else {
return name;
}
}
namespace logging {
vector<string> getStackTrace(int maxSize) {
vector<string> vec;
void** buffer = new void*[maxSize];
int items = backtrace(buffer, maxSize);
if(items > 0) {
char **symbols = backtrace_symbols (buffer, items);
for(int i=0; i< items; i++) {
Dl_info info;
if(dladdr(buffer[i], &info) && info.dli_sname != nullptr) {
vec.push_back(demangle(info.dli_sname));
} else {
vec.push_back(symbols[i]);
}
}
if(symbols != NULL) {
free(symbols);
}
if(items == maxSize) {
vec.push_back("[...]");
}
}
if(vec.size() > 0) {
vec.erase(vec.begin());
}
return vec;
}
};
| 16.898305 | 63 | 0.614845 | [
"vector"
] |
1c8b2414e319894d2b81c555f64d347c7686dc65 | 2,150 | hh | C++ | src/SimpleAllocator.hh | fuzziqersoftware/sharedstructures | 23471fc24484b472e4b2399d7c64c1071d12c641 | [
"MIT"
] | 21 | 2016-11-30T06:40:04.000Z | 2022-03-23T13:16:53.000Z | src/SimpleAllocator.hh | fuzziqersoftware/sharedstructures | 23471fc24484b472e4b2399d7c64c1071d12c641 | [
"MIT"
] | null | null | null | src/SimpleAllocator.hh | fuzziqersoftware/sharedstructures | 23471fc24484b472e4b2399d7c64c1071d12c641 | [
"MIT"
] | 3 | 2018-02-21T12:25:08.000Z | 2021-12-16T06:14:05.000Z | #pragma once
#include "Allocator.hh"
namespace sharedstructures {
class SimpleAllocator : public Allocator {
public:
SimpleAllocator() = delete;
SimpleAllocator(const SimpleAllocator&) = delete;
SimpleAllocator(SimpleAllocator&&) = delete;
explicit SimpleAllocator(std::shared_ptr<Pool> pool);
~SimpleAllocator() = default;
// allocator functions.
// there are three sets of these.
// - allocate/free behave like malloc/free but deal with raw offsets instead
// of pointers.
// - allocate_object/free_object behave like the new/delete operators (they
// call object constructors/destructors) but also deal with offsets instead
// of pointers.
// - allocate_object_ptr and free_object_ptr deal with PoolPointer instances,
// but otherwise behave like allocate_object/free_object.
virtual uint64_t allocate(size_t size);
virtual void free(uint64_t x);
virtual size_t block_size(uint64_t offset) const;
virtual void set_base_object_offset(uint64_t offset);
virtual uint64_t base_object_offset() const;
virtual size_t bytes_allocated() const;
virtual size_t bytes_free() const;
// locks the entire pool
virtual ProcessReadWriteLockGuard lock(bool writing) const;
virtual bool is_locked(bool writing) const;
virtual void verify() const;
private:
// pool structure
struct Data {
std::atomic<uint64_t> size; // this is part of the Pool structure
std::atomic<uint8_t> initialized;
ProcessReadWriteLock data_lock;
std::atomic<uint64_t> base_object_offset;
std::atomic<uint64_t> bytes_allocated; // sum of allocated block sizes
std::atomic<uint64_t> bytes_committed; // same as above, + the block structs
std::atomic<uint64_t> head;
std::atomic<uint64_t> tail;
uint8_t arena[0];
};
Data* data();
const Data* data() const;
// struct that describes an allocated block. inside the pool, these form a
// doubly-linked list with variable-size elements.
struct AllocatedBlock {
uint64_t prev;
uint64_t next;
uint64_t size;
uint64_t effective_size();
};
virtual void repair();
};
} // namespace sharedstructures
| 26.219512 | 80 | 0.731163 | [
"object"
] |
1c8f09a535bb408ac62a013e8a2e2ed49d52fa6c | 99,754 | cpp | C++ | src/Conversion.cpp | eProsima/FastDDS-SH | 58367aa629612559bba5f89276950b4afc702173 | [
"Apache-2.0"
] | 3 | 2021-06-17T09:57:27.000Z | 2021-12-08T02:09:46.000Z | src/Conversion.cpp | eProsima/FastDDS-SH | 58367aa629612559bba5f89276950b4afc702173 | [
"Apache-2.0"
] | 2 | 2021-04-07T14:06:06.000Z | 2021-07-16T09:32:41.000Z | src/Conversion.cpp | eProsima/FastDDS-SH | 58367aa629612559bba5f89276950b4afc702173 | [
"Apache-2.0"
] | 1 | 2021-11-28T02:46:47.000Z | 2021-11-28T02:46:47.000Z | /*
* Copyright 2019 - present Proyectos y Sistemas de Mantenimiento SL (eProsima).
*
* 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 "Conversion.hpp"
#include <fastrtps/types/TypeDescriptor.h>
#include <fastrtps/types/DynamicDataFactory.h>
#include <fastrtps/types/DynamicTypeBuilderFactory.h>
#include <fastrtps/types/MemberDescriptor.h>
#include <sstream>
#include <stack>
using eprosima::fastrtps::types::MemberId;
// TODO(@jamoralp): Add more debug traces here.
namespace eprosima {
namespace is {
namespace sh {
namespace fastdds {
namespace xtypes = eprosima::xtypes;
using namespace eprosima::fastrtps;
using namespace eprosima::fastrtps::types;
std::map<std::string, ::xtypes::DynamicType::Ptr> Conversion::types_;
std::map<std::string, DynamicPubSubType*> Conversion::registered_types_;
std::map<std::string, DynamicTypeBuilder_ptr> Conversion::builders_;
// Static member initialization
utils::Logger NavigationNode::logger_("is::sh::FastDDS::Conversion::NavigationNode");
std::string NavigationNode::get_path()
{
using wt = std::weak_ptr<NavigationNode>;
if (!parent_node.owner_before(wt{}) && !wt{}
.owner_before(parent_node)) // parent_node == nullptr
{
return type_name;
}
return parent_node.lock()->get_path() + "." + member_name;
}
std::string NavigationNode::get_type(
std::map<std::string, std::shared_ptr<NavigationNode> > map_nodes,
const std::string& full_path)
{
if (full_path.find(".") == std::string::npos)
{
if (map_nodes.count(full_path) > 0)
{
return map_nodes[full_path]->type_name;
}
return full_path;
}
std::string root = full_path.substr(0, full_path.find("."));
if (map_nodes.count(root) > 0)
{
return get_type(map_nodes[root], full_path.substr(full_path.find(".") + 1));
}
return "";
}
std::string NavigationNode::get_type(
std::shared_ptr<NavigationNode> root,
const std::string& full_path)
{
if (full_path.empty() || full_path.find(".") == std::string::npos)
{
return root->type_name;
}
std::string member = full_path.substr(0, full_path.find("."));
if (root->member_node.count(member) > 0)
{
std::string path = full_path.substr(full_path.find(".") + 1);
if (path.find(".") == std::string::npos)
{
return root->member_node[member]->type_name;
}
else
{
return get_type(root->member_node[member], path);
}
}
return "";
}
std::shared_ptr<NavigationNode> NavigationNode::fill_root_node(
std::shared_ptr<NavigationNode> root,
const ::xtypes::DynamicType& type,
const std::string& full_path)
{
std::string type_name;
std::string path;
if (full_path.find(".") == std::string::npos)
{
type_name = full_path;
path = "";
}
else
{
type_name = full_path.substr(0, full_path.find("."));
path = full_path.substr(full_path.find(".") + 1);
}
if (type_name != type.name())
{
logger_ << utils::Logger::Level::ERROR
<< "Attempting to create a root navigation node from a type with different name."
<< std::endl;
return root;
}
if (!path.empty())
{
std::string member;
if (path.find(".") == std::string::npos)
{
member = path;
path = "";
}
else
{
member = path.substr(0, path.find("."));
path = path.substr(path.find(".") + 1);
}
if (!type.is_aggregation_type())
{
logger_ << utils::Logger::Level::ERROR
<< "Attempting to create a root navigation node from a non-aggregated type."
<< std::endl;
return root;
}
const ::xtypes::AggregationType& aggr_type = static_cast<const ::xtypes::AggregationType&>(type);
if (!aggr_type.has_member(member))
{
logger_ << utils::Logger::Level::ERROR
<< "Type \"" << type_name << "\" doesn't have a member named \""
<< member << "\"." << std::endl;
return root;
}
std::shared_ptr<NavigationNode> member_node;
const ::xtypes::Member& type_member = aggr_type.member(member);
if (root->member_node.count(member) > 0)
{
member_node = root->member_node[member];
}
else
{
member_node = std::make_shared<NavigationNode>();
member_node->member_name = member;
member_node->type_name = type_member.type().name();
member_node->parent_node = root;
root->member_node[member] = member_node;
}
if (!path.empty())
{
fill_member_node(member_node, type_member.type(), path);
}
}
root->type_name = type.name();
return root;
}
void NavigationNode::fill_member_node(
std::shared_ptr<NavigationNode> node,
const ::xtypes::DynamicType& type,
const std::string& full_path)
{
std::string member;
std::string path;
if (!type.is_aggregation_type())
{
logger_ << utils::Logger::Level::ERROR
<< "Member " << node->member_name << " isn't an aggregated type." << std::endl;
return;
}
const ::xtypes::AggregationType& aggr_type = static_cast<const ::xtypes::AggregationType&>(type);
if (full_path.find(".") == std::string::npos)
{
member = full_path;
path = "";
}
else
{
member = full_path.substr(0, full_path.find("."));
path = full_path.substr(full_path.find(".") + 1);
}
if (!aggr_type.has_member(member))
{
logger_ << utils::Logger::Level::ERROR
<< "Member \"" << node->member_name << "\" of type \"" << node->type_name
<< "\" doesn't have a member named \"" << member << "\"." << std::endl;
return;
}
std::shared_ptr<NavigationNode> member_node;
const ::xtypes::Member& type_member = aggr_type.member(member);
if (node->member_node.count(member) > 0)
{
member_node = node->member_node[member];
}
else
{
member_node = std::make_shared<NavigationNode>();
member_node->member_name = member;
member_node->type_name = type_member.type().name();
member_node->parent_node = node;
node->member_node[member] = member_node;
}
if (!path.empty())
{
fill_member_node(member_node, type_member.type(), path);
}
}
std::shared_ptr<NavigationNode> NavigationNode::get_discriminator(
const std::map<std::string, std::shared_ptr<NavigationNode> >& member_map,
const ::xtypes::DynamicData& data,
const std::vector<std::string>& member_types)
{
const std::string& type_name = data.type().name();
if (member_map.count(type_name) == 0)
{
auto result = std::make_shared<NavigationNode>();
result->type_name = type_name;
return result;
}
if (std::find(member_types.begin(), member_types.end(), type_name) != member_types.end())
{
return member_map.at(type_name);
}
return get_discriminator(member_map.at(type_name), data.ref(), member_types);
}
std::shared_ptr<NavigationNode> NavigationNode::get_discriminator(
std::shared_ptr<NavigationNode> node,
::xtypes::ReadableDynamicDataRef data,
const std::vector<std::string>& member_types)
{
const std::string& type_name = data.type().name();
if (std::find(member_types.begin(), member_types.end(), type_name) != member_types.end())
{
return node;
}
if (data.type().is_aggregation_type())
{
const ::xtypes::AggregationType& aggr = static_cast<const ::xtypes::AggregationType&>(data.type());
std::shared_ptr<NavigationNode> result;
if (aggr.kind() == ::xtypes::TypeKind::UNION_TYPE)
{
std::string member = data.current_case().name();
if (node->member_node.count(member) > 0)
{
result =
get_discriminator(node->member_node[member], data[member], member_types);
}
}
else
{
for (auto& n : node->member_node)
{
if (aggr.has_member(n.first))
{
result = get_discriminator(n.second, data[n.first], member_types);
if (result)
{
break;
}
}
}
}
return result;
}
return nullptr;
}
// Static member initialization
utils::Logger Conversion::logger_("is::sh::FastDDS::Conversion");
// This function patches the problem of dynamic types, which do not admit '/' in their type name.
std::string Conversion::convert_type_name(
const std::string& message_type)
{
std::string type = message_type;
//TODO(Ricardo) Remove when old dyntypes support namespaces.
size_t npos = type.rfind(":");
if (std::string::npos != npos)
{
type = type.substr(npos + 1);
}
for (size_t i = type.find('/'); i != std::string::npos; i = type.find('/', i))
{
type.replace(i, 1, "__");
}
return type;
}
const xtypes::DynamicType& Conversion::resolve_type(
const xtypes::DynamicType& type)
{
if (type.kind() == ::xtypes::TypeKind::ALIAS_TYPE)
{
return static_cast<const ::xtypes::AliasType&>(type).rget();
}
return type;
}
void Conversion::set_primitive_data(
::xtypes::ReadableDynamicDataRef from,
DynamicData* to,
MemberId id)
{
switch (resolve_type(from.type()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
to->set_bool_value(from.value<bool>() ? true : false, id);
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
to->set_char8_value(from.value<char>(), id);
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
to->set_char16_value(from.value<wchar_t>(), id);
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
to->set_uint8_value(from.value<uint8_t>(), id);
break;
case ::xtypes::TypeKind::INT_8_TYPE:
to->set_int8_value(from.value<int8_t>(), id);
break;
case ::xtypes::TypeKind::INT_16_TYPE:
to->set_int16_value(from.value<int16_t>(), id);
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
to->set_uint16_value(from.value<uint16_t>(), id);
break;
case ::xtypes::TypeKind::INT_32_TYPE:
to->set_int32_value(from.value<int32_t>(), id);
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
to->set_uint32_value(from.value<uint32_t>(), id);
break;
case ::xtypes::TypeKind::INT_64_TYPE:
to->set_int64_value(from.value<int64_t>(), id);
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
to->set_uint64_value(from.value<uint64_t>(), id);
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
to->set_float32_value(from.value<float>(), id);
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
to->set_float64_value(from.value<double>(), id);
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
to->set_float128_value(from.value<long double>(), id);
break;
case ::xtypes::TypeKind::STRING_TYPE:
to->set_string_value(from.value<std::string>(), id);
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
to->set_wstring_value(from.value<std::wstring>(), id);
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
to->set_enum_value(from.value<uint32_t>(), id);
break;
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Expected primitive data, but found '"
<< from.type().name() << "'" << std::endl;
}
}
}
void Conversion::set_array_data(
xtypes::ReadableDynamicDataRef from,
DynamicData* to,
const std::vector<uint32_t>& indexes)
{
const ::xtypes::ArrayType& type = static_cast<const ::xtypes::ArrayType&>(from.type());
const ::xtypes::DynamicType& inner_type = resolve_type(type.content_type());
DynamicDataFactory* factory = DynamicDataFactory::get_instance();
MemberId id;
for (uint32_t idx = 0; idx < from.size(); ++idx)
{
std::vector<uint32_t> new_indexes = indexes;
new_indexes.push_back(idx);
switch (inner_type.kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
id = to->get_array_index(new_indexes);
to->set_bool_value(from[idx].value<bool>(), id);
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
id = to->get_array_index(new_indexes);
to->set_char8_value(from[idx].value<char>(), id);
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
id = to->get_array_index(new_indexes);
to->set_char16_value(static_cast<wchar_t>(from[idx].value<char32_t>()), id);
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
id = to->get_array_index(new_indexes);
to->set_uint8_value(from[idx].value<uint8_t>(), id);
break;
case ::xtypes::TypeKind::INT_8_TYPE:
id = to->get_array_index(new_indexes);
to->set_int8_value(from[idx].value<int8_t>(), id);
break;
case ::xtypes::TypeKind::INT_16_TYPE:
id = to->get_array_index(new_indexes);
to->set_int16_value(from[idx].value<int16_t>(), id);
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
id = to->get_array_index(new_indexes);
to->set_uint16_value(from[idx].value<uint16_t>(), id);
break;
case ::xtypes::TypeKind::INT_32_TYPE:
id = to->get_array_index(new_indexes);
to->set_int32_value(from[idx].value<int32_t>(), id);
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
id = to->get_array_index(new_indexes);
to->set_uint32_value(from[idx].value<uint32_t>(), id);
break;
case ::xtypes::TypeKind::INT_64_TYPE:
id = to->get_array_index(new_indexes);
to->set_int64_value(from[idx].value<int64_t>(), id);
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
id = to->get_array_index(new_indexes);
to->set_uint64_value(from[idx].value<uint64_t>(), id);
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
id = to->get_array_index(new_indexes);
to->set_float32_value(from[idx].value<float>(), id);
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
id = to->get_array_index(new_indexes);
to->set_float64_value(from[idx].value<double>(), id);
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
id = to->get_array_index(new_indexes);
to->set_float128_value(from[idx].value<long double>(), id);
break;
case ::xtypes::TypeKind::STRING_TYPE:
id = to->get_array_index(new_indexes);
to->set_string_value(from[idx].value<std::string>(), id);
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
id = to->get_array_index(new_indexes);
to->set_wstring_value(from[idx].value<std::wstring>(), id);
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
id = to->get_array_index(new_indexes);
to->set_enum_value(from[idx].value<uint32_t>(), id);
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
set_array_data(from[idx], to, new_indexes);
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
id = to->get_array_index(new_indexes);
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner sequence builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* seq_data = factory->create_data(builder_ptr->build());
set_sequence_data(from[idx], seq_data);
to->set_complex_value(seq_data, id);
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
id = to->get_array_index(new_indexes);
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner map builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* seq_data = factory->create_data(builder_ptr->build());
set_map_data(from[idx], seq_data);
to->set_complex_value(seq_data, id);
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
id = to->get_array_index(new_indexes);
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner struct builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* st_data = factory->create_data(builder_ptr->build());
set_struct_data(from[idx], st_data);
to->set_complex_value(st_data, id);
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
id = to->get_array_index(new_indexes);
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner struct builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* st_data = factory->create_data(builder_ptr->build());
set_union_data(from[idx], st_data);
to->set_complex_value(st_data, id);
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << from.type().name() << "'" << std::endl;
}
}
}
}
void Conversion::set_sequence_data(
::xtypes::ReadableDynamicDataRef from,
DynamicData* to)
{
const ::xtypes::SequenceType& type = static_cast<const ::xtypes::SequenceType&>(from.type());
MemberId id;
DynamicDataFactory* factory = DynamicDataFactory::get_instance();
to->clear_all_values();
for (uint32_t idx = 0; idx < from.size(); ++idx)
{
to->insert_sequence_data(id);
switch (resolve_type(type.content_type()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
to->set_bool_value(from[idx].value<bool>(), id);
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
to->set_char8_value(from[idx].value<char>(), id);
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
to->set_char16_value(static_cast<wchar_t>(from[idx].value<char32_t>()), id);
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
//to->set_uint8_value(from[idx].value<uint8_t>(), id);
to->set_byte_value(from[idx].value<uint8_t>(), id);
break;
case ::xtypes::TypeKind::INT_8_TYPE:
//to->set_int8_value(from[idx].value<int8_t>(), id);
to->set_byte_value(static_cast<rtps::octet>(from[idx].value<int8_t>()), id);
break;
case ::xtypes::TypeKind::INT_16_TYPE:
to->set_int16_value(from[idx].value<int16_t>(), id);
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
to->set_uint16_value(from[idx].value<uint16_t>(), id);
break;
case ::xtypes::TypeKind::INT_32_TYPE:
to->set_int32_value(from[idx].value<int32_t>(), id);
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
to->set_uint32_value(from[idx].value<uint32_t>(), id);
break;
case ::xtypes::TypeKind::INT_64_TYPE:
to->set_int64_value(from[idx].value<int64_t>(), id);
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
to->set_uint64_value(from[idx].value<uint64_t>(), id);
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
to->set_float32_value(from[idx].value<float>(), id);
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
to->set_float64_value(from[idx].value<double>(), id);
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
to->set_float128_value(from[idx].value<long double>(), id);
break;
case ::xtypes::TypeKind::STRING_TYPE:
to->set_string_value(from[idx].value<std::string>(), id);
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
to->set_wstring_value(from[idx].value<std::wstring>(), id);
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
to->set_enum_value(from[idx].value<uint32_t>(), id);
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner array builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* array_data = factory->create_data(builder_ptr->build());
set_array_data(from[idx], array_data, std::vector<uint32_t>());
to->set_complex_value(array_data, id);
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner sequence builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* seq_data = factory->create_data(builder_ptr->build());
set_sequence_data(from[idx], seq_data);
to->set_complex_value(seq_data, id);
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner map builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* seq_data = factory->create_data(builder_ptr->build());
set_map_data(from[idx], seq_data);
to->set_complex_value(seq_data, id);
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner struct builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* st_data = factory->create_data(builder_ptr->build());
set_struct_data(from[idx], st_data);
to->set_complex_value(st_data, id);
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(from[idx].type()); // The inner union builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* st_data = factory->create_data(builder_ptr->build());
set_union_data(from[idx], st_data);
to->set_complex_value(st_data, id);
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << from.type().name() << "'" << std::endl;
}
}
}
}
void Conversion::set_map_data(
::xtypes::ReadableDynamicDataRef from,
DynamicData* to)
{
const ::xtypes::MapType& type = static_cast<const ::xtypes::MapType&>(from.type());
const ::xtypes::PairType& pair_type = static_cast<const ::xtypes::PairType&>(type.content_type());
MemberId id_key;
MemberId id_value;
DynamicDataFactory* factory = DynamicDataFactory::get_instance();
to->clear_all_values();
DynamicTypeBuilder_ptr key_builder = get_builder(pair_type.first());
DynamicTypeBuilder_ptr value_builder = get_builder(pair_type.second());
for (::xtypes::ReadableDynamicDataRef pair : from)
{
// Convert key
DynamicData* key_data = factory->create_data(key_builder->build());
::xtypes::ReadableDynamicDataRef key = pair[0];
MemberId id = MEMBER_ID_INVALID;
switch (resolve_type(pair_type.first()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
key_data->set_bool_value(key, id);
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
key_data->set_char8_value(key, id);
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
key_data->set_char16_value(key, id);
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
//key_data->set_uint8_value(from[key].value<uint8_t>(), id);
key_data->set_byte_value(key, id);
break;
case ::xtypes::TypeKind::INT_8_TYPE:
//key_data->set_int8_value(from[key].value<int8_t>(), id);
key_data->set_byte_value(key, id);
break;
case ::xtypes::TypeKind::INT_16_TYPE:
key_data->set_int16_value(key, id);
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
key_data->set_uint16_value(key, id);
break;
case ::xtypes::TypeKind::INT_32_TYPE:
key_data->set_int32_value(key, id);
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
key_data->set_uint32_value(key, id);
break;
case ::xtypes::TypeKind::INT_64_TYPE:
key_data->set_int64_value(key, id);
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
key_data->set_uint64_value(key, id);
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
key_data->set_float32_value(key, id);
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
key_data->set_float64_value(key, id);
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
key_data->set_float128_value(key, id);
break;
case ::xtypes::TypeKind::STRING_TYPE:
key_data->set_string_value(key, id);
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
key_data->set_wstring_value(key, id);
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
key_data->set_enum_value(key.value<uint32_t>(), id);
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(key.type()); // The inner array builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* array_data = factory->create_data(builder_ptr->build());
set_array_data(key, array_data, std::vector<uint32_t>());
key_data->set_complex_value(array_data, id);
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(key.type()); // The inner map builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* seq_data = factory->create_data(builder_ptr->build());
set_map_data(key, seq_data);
key_data->set_complex_value(seq_data, id);
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(key.type()); // The inner sequence builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* seq_data = factory->create_data(builder_ptr->build());
set_sequence_data(key, seq_data);
key_data->set_complex_value(seq_data, id);
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(key.type()); // The inner struct builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* st_data = factory->create_data(builder_ptr->build());
set_struct_data(key, st_data);
key_data->set_complex_value(st_data, id);
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
DynamicTypeBuilder_ptr builder = get_builder(key.type()); // The inner struct builder
DynamicTypeBuilder* builder_ptr = static_cast<DynamicTypeBuilder*>(builder.get());
DynamicData* st_data = factory->create_data(builder_ptr->build());
set_union_data(key, st_data);
key_data->set_complex_value(st_data, id);
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << from.type().name() << "'" << std::endl;
}
}
// Convert data
id = MEMBER_ID_INVALID;
DynamicData* value_data = factory->create_data(value_builder->build());
::xtypes::ReadableDynamicDataRef value = pair[1];
switch (resolve_type(pair_type.second()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
value_data->set_bool_value(value, id);
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
value_data->set_char8_value(value, id);
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
value_data->set_char16_value(value, id);
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
//value_data->set_uint8_value(value, id);
value_data->set_byte_value(value, id);
break;
case ::xtypes::TypeKind::INT_8_TYPE:
//value_data->set_int8_value(value, id);
value_data->set_byte_value(value, id);
break;
case ::xtypes::TypeKind::INT_16_TYPE:
value_data->set_int16_value(value, id);
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
value_data->set_uint16_value(value, id);
break;
case ::xtypes::TypeKind::INT_32_TYPE:
value_data->set_int32_value(value, id);
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
value_data->set_uint32_value(value, id);
break;
case ::xtypes::TypeKind::INT_64_TYPE:
value_data->set_int64_value(value, id);
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
value_data->set_uint64_value(value, id);
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
value_data->set_float32_value(value, id);
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
value_data->set_float64_value(value, id);
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
value_data->set_float128_value(value, id);
break;
case ::xtypes::TypeKind::STRING_TYPE:
value_data->set_string_value(value, id);
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
value_data->set_wstring_value(value, id);
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
value_data->set_enum_value(value.value<uint32_t>(), id);
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
set_array_data(value, value_data, std::vector<uint32_t>());
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
set_map_data(value, value_data);
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
set_sequence_data(value, value_data);
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
set_struct_data(value, value_data);
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
set_union_data(value, value_data);
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << from.type().name() << "'" << std::endl;
}
}
// Add key value
to->insert_map_data(key_data, value_data, id_key, id_value);
}
}
bool Conversion::xtypes_to_fastdds(
const ::xtypes::DynamicData& input,
DynamicData* output)
{
if (input.type().kind() == ::xtypes::TypeKind::STRUCTURE_TYPE)
{
return set_struct_data(input, output);
}
else if (input.type().kind() == ::xtypes::TypeKind::UNION_TYPE)
{
return set_union_data(input, output);
}
logger_ << utils::Logger::Level::ERROR
<< "Unsupported data to convert (expected Structure or Union)." << std::endl;
return false;
}
bool Conversion::set_struct_data(
::xtypes::ReadableDynamicDataRef input,
DynamicData* output)
{
std::stringstream ss;
const ::xtypes::StructType& type = static_cast<const ::xtypes::StructType&>(input.type());
for (const ::xtypes::Member& member : type.members())
{
MemberId id = output->get_member_id_by_name(member.name());
switch (resolve_type(member.type()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
case ::xtypes::TypeKind::CHAR_8_TYPE:
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
case ::xtypes::TypeKind::UINT_8_TYPE:
case ::xtypes::TypeKind::INT_8_TYPE:
case ::xtypes::TypeKind::INT_16_TYPE:
case ::xtypes::TypeKind::UINT_16_TYPE:
case ::xtypes::TypeKind::INT_32_TYPE:
case ::xtypes::TypeKind::UINT_32_TYPE:
case ::xtypes::TypeKind::INT_64_TYPE:
case ::xtypes::TypeKind::UINT_64_TYPE:
case ::xtypes::TypeKind::FLOAT_32_TYPE:
case ::xtypes::TypeKind::FLOAT_64_TYPE:
case ::xtypes::TypeKind::FLOAT_128_TYPE:
case ::xtypes::TypeKind::STRING_TYPE:
case ::xtypes::TypeKind::WSTRING_TYPE:
case ::xtypes::TypeKind::ENUMERATION_TYPE:
{
set_primitive_data(input[member.name()], output, id);
break;
}
case ::xtypes::TypeKind::ARRAY_TYPE:
{
DynamicData* array_data = output->loan_value(id);
set_array_data(input[member.name()], array_data, std::vector<uint32_t>());
output->return_loaned_value(array_data);
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
DynamicData* seq_data = output->loan_value(id);
set_sequence_data(input[member.name()], seq_data);
output->return_loaned_value(seq_data);
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
DynamicData* seq_data = output->loan_value(id);
set_map_data(input[member.name()], seq_data);
output->return_loaned_value(seq_data);
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicData* st_data = output->loan_value(id);
set_struct_data(input[member.name()], st_data);
output->return_loaned_value(st_data);
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
DynamicData* st_data = output->loan_value(id);
set_union_data(input[member.name()], st_data);
output->return_loaned_value(st_data);
break;
}
default:
logger_ << utils::Logger::Level::ERROR
<< "Unsupported type: '" << member.type().name() << "'" << std::endl;
}
}
return true;
}
bool Conversion::set_union_data(
::xtypes::ReadableDynamicDataRef input,
DynamicData* output)
{
std::stringstream ss;
// Discriminator
switch (resolve_type(input.d().type()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
output->set_discriminator_value(input.d().value<bool>());
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
output->set_discriminator_value(static_cast<uint64_t>(input.d().value<char>()));
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
output->set_discriminator_value(static_cast<uint64_t>(input.d().value<char16_t>()));
break;
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
output->set_discriminator_value(static_cast<uint64_t>(input.d().value<wchar_t>()));
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
output->set_discriminator_value(input.d().value<uint8_t>());
break;
case ::xtypes::TypeKind::INT_8_TYPE:
output->set_discriminator_value(static_cast<uint64_t>(input.d().value<int8_t>()));
break;
case ::xtypes::TypeKind::INT_16_TYPE:
output->set_discriminator_value(static_cast<uint64_t>(input.d().value<int16_t>()));
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
output->set_discriminator_value(input.d().value<uint16_t>());
break;
case ::xtypes::TypeKind::INT_32_TYPE:
output->set_discriminator_value(static_cast<uint64_t>(input.d().value<int32_t>()));
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
output->set_discriminator_value(input.d().value<uint32_t>());
break;
case ::xtypes::TypeKind::INT_64_TYPE:
output->set_discriminator_value(static_cast<uint64_t>(input.d().value<int64_t>()));
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
output->set_discriminator_value(input.d().value<uint64_t>());
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
output->set_discriminator_value(input.d().value<uint32_t>());
break;
default:
break;
}
// Active member
const ::xtypes::Member& member = input.current_case();
MemberId id = output->get_member_id_by_name(member.name());
switch (resolve_type(member.type()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
case ::xtypes::TypeKind::CHAR_8_TYPE:
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
case ::xtypes::TypeKind::UINT_8_TYPE:
case ::xtypes::TypeKind::INT_8_TYPE:
case ::xtypes::TypeKind::INT_16_TYPE:
case ::xtypes::TypeKind::UINT_16_TYPE:
case ::xtypes::TypeKind::INT_32_TYPE:
case ::xtypes::TypeKind::UINT_32_TYPE:
case ::xtypes::TypeKind::INT_64_TYPE:
case ::xtypes::TypeKind::UINT_64_TYPE:
case ::xtypes::TypeKind::FLOAT_32_TYPE:
case ::xtypes::TypeKind::FLOAT_64_TYPE:
case ::xtypes::TypeKind::FLOAT_128_TYPE:
case ::xtypes::TypeKind::STRING_TYPE:
case ::xtypes::TypeKind::WSTRING_TYPE:
case ::xtypes::TypeKind::ENUMERATION_TYPE:
{
set_primitive_data(input[member.name()], output, id);
break;
}
case ::xtypes::TypeKind::ARRAY_TYPE:
{
DynamicData* array_data = output->loan_value(id);
set_array_data(input[member.name()], array_data, std::vector<uint32_t>());
output->return_loaned_value(array_data);
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
DynamicData* seq_data = output->loan_value(id);
set_sequence_data(input[member.name()], seq_data);
output->return_loaned_value(seq_data);
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicData* st_data = output->loan_value(id);
set_struct_data(input[member.name()], st_data);
output->return_loaned_value(st_data);
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
DynamicData* st_data = output->loan_value(id);
set_map_data(input[member.name()], st_data);
output->return_loaned_value(st_data);
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
DynamicData* st_data = output->loan_value(id);
set_union_data(input[member.name()], st_data);
output->return_loaned_value(st_data);
break;
}
default:
logger_ << utils::Logger::Level::ERROR
<< "Unsupported type: '" << member.type().name() << "'" << std::endl;
}
return true;
}
void Conversion::set_sequence_data(
const DynamicData* c_from,
::xtypes::WritableDynamicDataRef to)
{
const ::xtypes::SequenceType& type = static_cast<const ::xtypes::SequenceType&>(to.type());
DynamicData* from = const_cast<DynamicData*>(c_from);
for (uint32_t idx = 0; idx < c_from->get_item_count(); ++idx)
{
MemberId id = idx;
ResponseCode ret = ResponseCode::RETCODE_ERROR;
switch (resolve_type(type.content_type()).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
{
bool value;
ret = from->get_bool_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
{
char value;
ret = from->get_char8_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
{
wchar_t value;
ret = from->get_char16_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
{
uint8_t value;
ret = from->get_uint8_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::INT_8_TYPE:
{
int8_t value;
ret = from->get_int8_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::INT_16_TYPE:
{
int16_t value;
ret = from->get_int16_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
{
uint16_t value;
ret = from->get_uint16_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::INT_32_TYPE:
{
int32_t value;
ret = from->get_int32_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
{
uint32_t value;
ret = from->get_uint32_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::INT_64_TYPE:
{
int64_t value;
ret = from->get_int64_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
{
uint64_t value;
ret = from->get_uint64_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
{
float value;
ret = from->get_float32_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
{
double value;
ret = from->get_float64_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
{
long double value;
ret = from->get_float128_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::STRING_TYPE:
{
std::string value;
ret = from->get_string_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
{
std::wstring value;
ret = from->get_wstring_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
{
uint32_t value;
ret = from->get_enum_value(value, id);
to.push(value);
}
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
DynamicData* array = from->loan_value(id);
::xtypes::DynamicData xtypes_array(type.content_type());
set_array_data(array, xtypes_array.ref(), std::vector<uint32_t>());
from->return_loaned_value(array);
to.push(xtypes_array);
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
DynamicData* seq = from->loan_value(id);
::xtypes::DynamicData xtypes_seq(type.content_type());
set_sequence_data(seq, xtypes_seq.ref());
from->return_loaned_value(seq);
to.push(xtypes_seq);
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
DynamicData* seq = from->loan_value(id);
::xtypes::DynamicData xtypes_map(type.content_type());
set_map_data(seq, xtypes_map.ref());
from->return_loaned_value(seq);
to.push(xtypes_map);
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicData* st = from->loan_value(id);
::xtypes::DynamicData xtypes_st(type.content_type());
set_struct_data(st, xtypes_st.ref());
from->return_loaned_value(st);
to.push(xtypes_st);
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
DynamicData* st = from->loan_value(id);
::xtypes::DynamicData xtypes_union(type.content_type());
set_union_data(st, xtypes_union.ref());
from->return_loaned_value(st);
to.push(xtypes_union);
ret = ResponseCode::RETCODE_OK;
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << to.type().name() << "'" << std::endl;
}
}
if (ret != ResponseCode::RETCODE_OK)
{
logger_ << utils::Logger::Level::ERROR
<< "Error parsing from dynamic type '" << to.type().name() << "'" << std::endl;
}
}
}
void Conversion::set_map_data(
const DynamicData* c_from,
::xtypes::WritableDynamicDataRef to)
{
const ::xtypes::MapType& map_type = static_cast<const ::xtypes::MapType&>(to.type());
const ::xtypes::PairType& pair_type = static_cast<const ::xtypes::PairType&>(map_type.content_type());
const ::xtypes::DynamicType& key_type = pair_type.first();
const ::xtypes::DynamicType& value_type = pair_type.second();
DynamicData* from = const_cast<DynamicData*>(c_from);
for (uint32_t idx = 0; idx < c_from->get_item_count(); ++idx)
{
MemberId key_id = idx * 2;
MemberId value_id = key_id + 1;
ResponseCode ret = ResponseCode::RETCODE_ERROR;
::xtypes::DynamicData key_data(key_type);
::xtypes::DynamicData value_data(value_type);
// Key
switch (resolve_type(key_type).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
{
bool value;
ret = from->get_bool_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
{
char value;
ret = from->get_char8_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
{
wchar_t value;
ret = from->get_char16_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
{
uint8_t value;
ret = from->get_uint8_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::INT_8_TYPE:
{
int8_t value;
ret = from->get_int8_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::INT_16_TYPE:
{
int16_t value;
ret = from->get_int16_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
{
uint16_t value;
ret = from->get_uint16_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::INT_32_TYPE:
{
int32_t value;
ret = from->get_int32_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
{
uint32_t value;
ret = from->get_uint32_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::INT_64_TYPE:
{
int64_t value;
ret = from->get_int64_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
{
uint64_t value;
ret = from->get_uint64_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
{
float value;
ret = from->get_float32_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
{
double value;
ret = from->get_float64_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
{
long double value;
ret = from->get_float128_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::STRING_TYPE:
{
std::string value;
ret = from->get_string_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
{
std::wstring value;
ret = from->get_wstring_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
{
uint32_t value;
ret = from->get_enum_value(value, key_id);
key_data = value;
}
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
DynamicData* array = from->loan_value(key_id);
::xtypes::DynamicData xtypes_array(key_type);
set_array_data(array, xtypes_array.ref(), std::vector<uint32_t>());
from->return_loaned_value(array);
key_data = xtypes_array;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
DynamicData* seq = from->loan_value(key_id);
::xtypes::DynamicData xtypes_seq(key_type);
set_sequence_data(seq, xtypes_seq.ref());
from->return_loaned_value(seq);
key_data = xtypes_seq;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
DynamicData* seq = from->loan_value(key_id);
::xtypes::DynamicData xtypes_map(key_type);
set_map_data(seq, xtypes_map.ref());
from->return_loaned_value(seq);
key_data = xtypes_map;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicData* st = from->loan_value(key_id);
::xtypes::DynamicData xtypes_st(key_type);
set_struct_data(st, xtypes_st.ref());
from->return_loaned_value(st);
key_data = xtypes_st;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
DynamicData* st = from->loan_value(key_id);
::xtypes::DynamicData xtypes_union(key_type);
set_union_data(st, xtypes_union.ref());
from->return_loaned_value(st);
key_data = xtypes_union;
ret = ResponseCode::RETCODE_OK;
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << key_type.name() << "'" << std::endl;
}
}
// Value
switch (resolve_type(value_type).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
{
bool value;
ret = from->get_bool_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
{
char value;
ret = from->get_char8_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
{
wchar_t value;
ret = from->get_char16_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
{
uint8_t value;
ret = from->get_uint8_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::INT_8_TYPE:
{
int8_t value;
ret = from->get_int8_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::INT_16_TYPE:
{
int16_t value;
ret = from->get_int16_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
{
uint16_t value;
ret = from->get_uint16_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::INT_32_TYPE:
{
int32_t value;
ret = from->get_int32_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
{
uint32_t value;
ret = from->get_uint32_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::INT_64_TYPE:
{
int64_t value;
ret = from->get_int64_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
{
uint64_t value;
ret = from->get_uint64_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
{
float value;
ret = from->get_float32_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
{
double value;
ret = from->get_float64_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
{
long double value;
ret = from->get_float128_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::STRING_TYPE:
{
std::string value;
ret = from->get_string_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
{
std::wstring value;
ret = from->get_wstring_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
{
uint32_t value;
ret = from->get_enum_value(value, value_id);
value_data = value;
}
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
DynamicData* array = from->loan_value(value_id);
::xtypes::DynamicData xtypes_array(value_type);
set_array_data(array, xtypes_array.ref(), std::vector<uint32_t>());
from->return_loaned_value(array);
value_data = xtypes_array;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
DynamicData* seq = from->loan_value(value_id);
::xtypes::DynamicData xtypes_seq(value_type);
set_sequence_data(seq, xtypes_seq.ref());
from->return_loaned_value(seq);
value_data = xtypes_seq;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
DynamicData* seq = from->loan_value(value_id);
::xtypes::DynamicData xtypes_map(value_type);
set_map_data(seq, xtypes_map.ref());
from->return_loaned_value(seq);
value_data = xtypes_map;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicData* st = from->loan_value(value_id);
::xtypes::DynamicData xtypes_st(value_type);
set_struct_data(st, xtypes_st.ref());
from->return_loaned_value(st);
value_data = xtypes_st;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
DynamicData* st = from->loan_value(value_id);
::xtypes::DynamicData xtypes_union(value_type);
set_union_data(st, xtypes_union.ref());
from->return_loaned_value(st);
value_data = xtypes_union;
ret = ResponseCode::RETCODE_OK;
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << value_type.name() << "'" << std::endl;
}
}
if (ret != ResponseCode::RETCODE_OK)
{
logger_ << utils::Logger::Level::ERROR
<< "Error parsing from dynamic type '" << to.type().name() << "'" << std::endl;
}
// Add entry
to[key_data] = value_data;
}
}
void Conversion::set_array_data(
const DynamicData* c_from,
::xtypes::WritableDynamicDataRef to,
const std::vector<uint32_t>& indexes)
{
const ::xtypes::ArrayType& type = static_cast<const ::xtypes::ArrayType&>(to.type());
const ::xtypes::DynamicType& inner_type = type.content_type();
DynamicData* from = const_cast<DynamicData*>(c_from);
MemberId id;
for (uint32_t idx = 0; idx < type.dimension(); ++idx)
{
std::vector<uint32_t> new_indexes = indexes;
new_indexes.push_back(idx);
ResponseCode ret = ResponseCode::RETCODE_ERROR;
switch (resolve_type(inner_type).kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
{
id = from->get_array_index(new_indexes);
bool value;
ret = from->get_bool_value(value, id);
to[idx].value<bool>(value);
}
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
{
id = from->get_array_index(new_indexes);
char value;
ret = from->get_char8_value(value, id);
to[idx].value<char>(value);
}
break;
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
{
id = from->get_array_index(new_indexes);
wchar_t value;
ret = from->get_char16_value(value, id);
to[idx].value<wchar_t>(value);
}
break;
case ::xtypes::TypeKind::UINT_8_TYPE:
{
id = from->get_array_index(new_indexes);
uint8_t value;
ret = from->get_uint8_value(value, id);
to[idx].value<uint8_t>(value);
}
break;
case ::xtypes::TypeKind::INT_8_TYPE:
{
id = from->get_array_index(new_indexes);
int8_t value;
ret = from->get_int8_value(value, id);
to[idx].value<int8_t>(value);
}
break;
case ::xtypes::TypeKind::INT_16_TYPE:
{
id = from->get_array_index(new_indexes);
int16_t value;
ret = from->get_int16_value(value, id);
to[idx].value<int16_t>(value);
}
break;
case ::xtypes::TypeKind::UINT_16_TYPE:
{
id = from->get_array_index(new_indexes);
uint16_t value;
ret = from->get_uint16_value(value, id);
to[idx].value<uint16_t>(value);
}
break;
case ::xtypes::TypeKind::INT_32_TYPE:
{
id = from->get_array_index(new_indexes);
int32_t value;
ret = from->get_int32_value(value, id);
to[idx].value<int32_t>(value);
}
break;
case ::xtypes::TypeKind::UINT_32_TYPE:
{
id = from->get_array_index(new_indexes);
uint32_t value;
ret = from->get_uint32_value(value, id);
to[idx].value<uint32_t>(value);
}
break;
case ::xtypes::TypeKind::INT_64_TYPE:
{
id = from->get_array_index(new_indexes);
int64_t value;
ret = from->get_int64_value(value, id);
to[idx].value<int64_t>(value);
}
break;
case ::xtypes::TypeKind::UINT_64_TYPE:
{
id = from->get_array_index(new_indexes);
uint64_t value;
ret = from->get_uint64_value(value, id);
to[idx].value<uint64_t>(value);
}
break;
case ::xtypes::TypeKind::FLOAT_32_TYPE:
{
id = from->get_array_index(new_indexes);
float value;
ret = from->get_float32_value(value, id);
to[idx].value<float>(value);
}
break;
case ::xtypes::TypeKind::FLOAT_64_TYPE:
{
id = from->get_array_index(new_indexes);
double value;
ret = from->get_float64_value(value, id);
to[idx].value<double>(value);
}
break;
case ::xtypes::TypeKind::FLOAT_128_TYPE:
{
id = from->get_array_index(new_indexes);
long double value;
ret = from->get_float128_value(value, id);
to[idx].value<long double>(value);
}
break;
case ::xtypes::TypeKind::STRING_TYPE:
{
id = from->get_array_index(new_indexes);
std::string value;
ret = from->get_string_value(value, id);
to[idx].value<std::string>(value);
}
break;
case ::xtypes::TypeKind::WSTRING_TYPE:
{
id = from->get_array_index(new_indexes);
std::wstring value;
ret = from->get_wstring_value(value, id);
to[idx].value<std::wstring>(value);
}
break;
case ::xtypes::TypeKind::ENUMERATION_TYPE:
{
id = from->get_array_index(new_indexes);
uint32_t value;
ret = from->get_enum_value(value, id);
to[idx].value<uint32_t>(value);
}
break;
case ::xtypes::TypeKind::ARRAY_TYPE:
{
::xtypes::DynamicData xtypes_array(type.content_type());
set_array_data(from, xtypes_array.ref(), new_indexes);
to[idx] = xtypes_array;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
id = from->get_array_index(new_indexes);
DynamicData* seq = from->loan_value(id);
::xtypes::DynamicData xtypes_seq(type.content_type());
set_sequence_data(seq, xtypes_seq.ref());
from->return_loaned_value(seq);
to[idx] = xtypes_seq;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::MAP_TYPE:
{
id = from->get_array_index(new_indexes);
DynamicData* seq = from->loan_value(id);
::xtypes::DynamicData xtypes_map(type.content_type());
set_map_data(seq, xtypes_map.ref());
from->return_loaned_value(seq);
to[idx] = xtypes_map;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
id = from->get_array_index(new_indexes);
DynamicData* st = from->loan_value(id);
::xtypes::DynamicData xtypes_st(type.content_type());
set_struct_data(st, xtypes_st.ref());
from->return_loaned_value(st);
to[idx] = xtypes_st;
ret = ResponseCode::RETCODE_OK;
break;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
id = from->get_array_index(new_indexes);
DynamicData* st = from->loan_value(id);
::xtypes::DynamicData xtypes_union(type.content_type());
set_union_data(st, xtypes_union.ref());
from->return_loaned_value(st);
to[idx] = xtypes_union;
ret = ResponseCode::RETCODE_OK;
break;
}
default:
{
logger_ << utils::Logger::Level::ERROR
<< "Unexpected data type: '" << to.type().name() << "'" << std::endl;
}
}
if (ret != ResponseCode::RETCODE_OK)
{
logger_ << utils::Logger::Level::ERROR
<< "Error parsing from dynamic type '" << to.type().name() << "'" << std::endl;
}
}
}
// TODO: Can we receive a type without members as root?
bool Conversion::fastdds_to_xtypes(
const DynamicData* c_input,
::xtypes::DynamicData& output)
{
if (output.type().kind() == ::xtypes::TypeKind::STRUCTURE_TYPE)
{
return set_struct_data(c_input, output.ref());
}
else if (output.type().kind() == ::xtypes::TypeKind::UNION_TYPE)
{
return set_union_data(c_input, output.ref());
}
logger_ << utils::Logger::Level::ERROR
<< "Unsupported data to convert (expected Structure or Union)." << std::endl;
return false;
}
TypeKind Conversion::resolve_type(
const DynamicType_ptr type)
{
TypeDescriptor* desc_type = type->get_descriptor();
while (desc_type->get_kind() == types::TK_ALIAS)
{
desc_type = desc_type->get_base_type()->get_descriptor();
}
return desc_type->get_kind();
}
bool Conversion::set_struct_data(
const DynamicData* c_input,
::xtypes::WritableDynamicDataRef output)
{
std::stringstream ss;
uint32_t id = 0;
uint32_t i = 0;
MemberDescriptor descriptor;
// We promise to not modify it, but we need it non-const, so we can call loan_value freely.
DynamicData* input = const_cast<DynamicData*>(c_input);
while (id != MEMBER_ID_INVALID)
{
id = input->get_member_id_at_index(i);
ResponseCode ret = ResponseCode::RETCODE_ERROR;
if (id != MEMBER_ID_INVALID)
{
ret = input->get_descriptor(descriptor, id);
if (ret == ResponseCode::RETCODE_OK)
{
switch (resolve_type(descriptor.get_type()))
{
case types::TK_BOOLEAN:
{
bool value;
ret = input->get_bool_value(value, id);
output[descriptor.get_name()].value<bool>(value ? true : false);
break;
}
case types::TK_BYTE:
{
uint8_t value;
ret = input->get_byte_value(value, id);
switch (output[descriptor.get_name()].type().kind())
{
case ::xtypes::TypeKind::UINT_8_TYPE:
output[descriptor.get_name()].value<uint8_t>(value);
break;
case ::xtypes::TypeKind::CHAR_8_TYPE:
output[descriptor.get_name()].value<char>(static_cast<char>(value));
break;
case ::xtypes::TypeKind::INT_8_TYPE:
output[descriptor.get_name()].value<int8_t>(static_cast<int8_t>(value));
break;
default:
logger_ << utils::Logger::Level::ERROR
<< "Error parsing from dynamic type '"
<< input->get_name() << "'" << std::endl;
}
break;
}
case types::TK_INT16:
{
int16_t value;
ret = input->get_int16_value(value, id);
output[descriptor.get_name()].value<int16_t>(value);
break;
}
case types::TK_INT32:
{
int32_t value;
ret = input->get_int32_value(value, id);
output[descriptor.get_name()].value<int32_t>(value);
break;
}
case types::TK_INT64:
{
int64_t value;
ret = input->get_int64_value(value, id);
output[descriptor.get_name()].value<int64_t>(value);
break;
}
case types::TK_UINT16:
{
uint16_t value;
ret = input->get_uint16_value(value, id);
output[descriptor.get_name()].value<uint16_t>(value);
break;
}
case types::TK_UINT32:
{
uint32_t value;
ret = input->get_uint32_value(value, id);
output[descriptor.get_name()].value<uint32_t>(value);
break;
}
case types::TK_UINT64:
{
uint64_t value;
ret = input->get_uint64_value(value, id);
output[descriptor.get_name()].value<uint64_t>(value);
break;
}
case types::TK_FLOAT32:
{
float value;
ret = input->get_float32_value(value, id);
output[descriptor.get_name()].value<float>(value);
break;
}
case types::TK_FLOAT64:
{
double value;
ret = input->get_float64_value(value, id);
output[descriptor.get_name()].value<double>(value);
break;
}
case types::TK_FLOAT128:
{
long double value;
ret = input->get_float128_value(value, id);
output[descriptor.get_name()].value<long double>(value);
break;
}
case types::TK_CHAR8:
{
char value;
ret = input->get_char8_value(value, id);
output[descriptor.get_name()].value<char>(value);
break;
}
case types::TK_CHAR16:
{
wchar_t value;
ret = input->get_char16_value(value, id);
output[descriptor.get_name()].value<wchar_t>(value);
break;
}
case types::TK_STRING8:
{
std::string value;
ret = input->get_string_value(value, id);
output[descriptor.get_name()].value<std::string>(value);
break;
}
case types::TK_STRING16:
{
std::wstring value;
ret = input->get_wstring_value(value, id);
output[descriptor.get_name()].value<std::wstring>(value);
break;
}
case types::TK_ENUM:
{
uint32_t value;
ret = input->get_enum_value(value, id);
output[descriptor.get_name()].value<uint32_t>(value);
break;
}
case types::TK_ARRAY:
{
DynamicData* array = input->loan_value(id);
set_array_data(array, output[descriptor.get_name()], std::vector<uint32_t>());
input->return_loaned_value(array);
break;
}
case types::TK_SEQUENCE:
{
DynamicData* seq = input->loan_value(id);
set_sequence_data(seq, output[descriptor.get_name()]);
input->return_loaned_value(seq);
break;
}
case types::TK_MAP:
{
DynamicData* seq = input->loan_value(id);
set_map_data(seq, output[descriptor.get_name()]);
input->return_loaned_value(seq);
break;
}
case types::TK_STRUCTURE:
{
DynamicData* nested_msg_dds = input->loan_value(id);
if (nested_msg_dds != nullptr)
{
if (set_struct_data(nested_msg_dds, output[descriptor.get_name()]))
{
ret = ResponseCode::RETCODE_OK;
}
input->return_loaned_value(nested_msg_dds);
}
break;
}
case types::TK_UNION:
{
DynamicData* nested_msg_dds = input->loan_value(id);
if (nested_msg_dds != nullptr)
{
if (set_union_data(nested_msg_dds, output[descriptor.get_name()]))
{
ret = ResponseCode::RETCODE_OK;
}
input->return_loaned_value(nested_msg_dds);
}
break;
}
default:
{
ret = ResponseCode::RETCODE_ERROR;
break;
}
}
i++;
}
if (ret != ResponseCode::RETCODE_OK)
{
logger_ << utils::Logger::Level::ERROR
<< "Error parsing from dynamic type '"
<< input->get_name() << "'" << std::endl;
}
}
}
return true;
}
bool Conversion::set_union_data(
const DynamicData* c_input,
::xtypes::WritableDynamicDataRef output)
{
std::stringstream ss;
MemberDescriptor descriptor;
// We promise to not modify it, but we need it non-const, so we can call loan_value freely.
DynamicData* input = const_cast<DynamicData*>(c_input);
// Discriminator is set automatically when the operator[] is used.
// Active member
UnionDynamicData* u_input = static_cast<UnionDynamicData*>(input);
MemberId id = u_input->get_union_id();
ResponseCode ret = ResponseCode::RETCODE_ERROR;
ret = input->get_descriptor(descriptor, id);
if (ret == ResponseCode::RETCODE_OK)
{
switch (resolve_type(descriptor.get_type()))
{
case types::TK_BOOLEAN:
{
bool value;
ret = input->get_bool_value(value, id);
output[descriptor.get_name()].value<bool>(value);
break;
}
case types::TK_BYTE:
{
uint8_t value;
ret = input->get_byte_value(value, id);
output[descriptor.get_name()].value<uint8_t>(value);
break;
}
case types::TK_INT16:
{
int16_t value;
ret = input->get_int16_value(value, id);
output[descriptor.get_name()].value<int16_t>(value);
break;
}
case types::TK_INT32:
{
int32_t value;
ret = input->get_int32_value(value, id);
output[descriptor.get_name()].value<int32_t>(value);
break;
}
case types::TK_INT64:
{
int64_t value;
ret = input->get_int64_value(value, id);
output[descriptor.get_name()].value<int64_t>(value);
break;
}
case types::TK_UINT16:
{
uint16_t value;
ret = input->get_uint16_value(value, id);
output[descriptor.get_name()].value<uint16_t>(value);
break;
}
case types::TK_UINT32:
{
uint32_t value;
ret = input->get_uint32_value(value, id);
output[descriptor.get_name()].value<uint32_t>(value);
break;
}
case types::TK_UINT64:
{
uint64_t value;
ret = input->get_uint64_value(value, id);
output[descriptor.get_name()].value<uint64_t>(value);
break;
}
case types::TK_FLOAT32:
{
float value;
ret = input->get_float32_value(value, id);
output[descriptor.get_name()].value<float>(value);
break;
}
case types::TK_FLOAT64:
{
double value;
ret = input->get_float64_value(value, id);
output[descriptor.get_name()].value<double>(value);
break;
}
case types::TK_FLOAT128:
{
long double value;
ret = input->get_float128_value(value, id);
output[descriptor.get_name()].value<long double>(value);
break;
}
case types::TK_CHAR8:
{
char value;
ret = input->get_char8_value(value, id);
output[descriptor.get_name()].value<char>(value);
break;
}
case types::TK_CHAR16:
{
wchar_t value;
ret = input->get_char16_value(value, id);
output[descriptor.get_name()].value<wchar_t>(value);
break;
}
case types::TK_STRING8:
{
std::string value;
ret = input->get_string_value(value, id);
output[descriptor.get_name()].value<std::string>(value);
break;
}
case types::TK_STRING16:
{
std::wstring value;
ret = input->get_wstring_value(value, id);
output[descriptor.get_name()].value<std::wstring>(value);
break;
}
case types::TK_ENUM:
{
uint32_t value;
ret = input->get_enum_value(value, id);
output[descriptor.get_name()].value<uint32_t>(value);
break;
}
case types::TK_ARRAY:
{
DynamicData* array = input->loan_value(id);
set_array_data(array, output[descriptor.get_name()], std::vector<uint32_t>());
input->return_loaned_value(array);
break;
}
case types::TK_SEQUENCE:
{
DynamicData* seq = input->loan_value(id);
set_sequence_data(seq, output[descriptor.get_name()]);
input->return_loaned_value(seq);
break;
}
case types::TK_MAP:
{
DynamicData* seq = input->loan_value(id);
set_map_data(seq, output[descriptor.get_name()]);
input->return_loaned_value(seq);
break;
}
case types::TK_STRUCTURE:
{
DynamicData* nested_msg_dds = input->loan_value(id);
if (nested_msg_dds != nullptr)
{
if (set_struct_data(nested_msg_dds, output[descriptor.get_name()]))
{
ret = ResponseCode::RETCODE_OK;
}
input->return_loaned_value(nested_msg_dds);
}
break;
}
case types::TK_UNION:
{
DynamicData* nested_msg_dds = input->loan_value(id);
if (nested_msg_dds != nullptr)
{
if (set_union_data(nested_msg_dds, output[descriptor.get_name()]))
{
ret = ResponseCode::RETCODE_OK;
}
input->return_loaned_value(nested_msg_dds);
}
break;
}
default:
{
ret = ResponseCode::RETCODE_ERROR;
break;
}
}
}
if (ret != ResponseCode::RETCODE_OK)
{
logger_ << utils::Logger::Level::ERROR
<< "Error parsing from dynamic type '" << input->get_name() << "'" << std::endl;
}
return true;
}
::xtypes::DynamicData Conversion::dynamic_data(
const std::string& type_name)
{
auto it = types_.find(type_name);
if (it == types_.end())
{
logger_ << utils::Logger::Level::ERROR
<< "Error getting data from dynamic type '"
<< type_name << "' (not registered)" << std::endl;
}
return ::xtypes::DynamicData(*it->second.get());
}
DynamicTypeBuilder* Conversion::create_builder(
const ::xtypes::DynamicType& type)
{
if (builders_.count(type.name()) > 0)
{
return static_cast<DynamicTypeBuilder*>(builders_[type.name()].get());
}
DynamicTypeBuilder_ptr builder = get_builder(type);
if (builder == nullptr)
{
return nullptr;
}
DynamicTypeBuilder* result = static_cast<DynamicTypeBuilder*>(builder.get());
result->set_name(convert_type_name(type.name()));
builders_.emplace(type.name(), std::move(builder));
return result;
}
DynamicTypeBuilder_ptr Conversion::get_builder(
const ::xtypes::DynamicType& type)
{
DynamicTypeBuilderFactory* factory = DynamicTypeBuilderFactory::get_instance();
switch (type.kind())
{
case ::xtypes::TypeKind::BOOLEAN_TYPE:
{
return factory->create_bool_builder();
}
case ::xtypes::TypeKind::INT_8_TYPE:
case ::xtypes::TypeKind::UINT_8_TYPE:
{
return factory->create_byte_builder();
}
case ::xtypes::TypeKind::INT_16_TYPE:
{
return factory->create_int16_builder();
}
case ::xtypes::TypeKind::UINT_16_TYPE:
{
return factory->create_uint16_builder();
}
case ::xtypes::TypeKind::INT_32_TYPE:
{
return factory->create_int32_builder();
}
case ::xtypes::TypeKind::UINT_32_TYPE:
{
return factory->create_uint32_builder();
}
case ::xtypes::TypeKind::INT_64_TYPE:
{
return factory->create_int64_builder();
}
case ::xtypes::TypeKind::UINT_64_TYPE:
{
return factory->create_uint64_builder();
}
case ::xtypes::TypeKind::FLOAT_32_TYPE:
{
return factory->create_float32_builder();
}
case ::xtypes::TypeKind::FLOAT_64_TYPE:
{
return factory->create_float64_builder();
}
case ::xtypes::TypeKind::FLOAT_128_TYPE:
{
return factory->create_float128_builder();
}
case ::xtypes::TypeKind::CHAR_8_TYPE:
{
return factory->create_char8_builder();
}
case ::xtypes::TypeKind::CHAR_16_TYPE:
case ::xtypes::TypeKind::WIDE_CHAR_TYPE:
{
return factory->create_char16_builder();
}
case ::xtypes::TypeKind::ENUMERATION_TYPE:
{
DynamicTypeBuilder* builder = factory->create_enum_builder();
builder->set_name(convert_type_name(type.name()));
const ::xtypes::EnumerationType<uint32_t>& enum_type =
static_cast<const ::xtypes::EnumerationType<uint32_t>&>(type);
const std::map<std::string, uint32_t>& enumerators = enum_type.enumerators();
for (auto pair : enumerators)
{
builder->add_empty_member(pair.second, pair.first);
}
return builder;
}
case ::xtypes::TypeKind::BITSET_TYPE:
{
// TODO
break;
}
case ::xtypes::TypeKind::ALIAS_TYPE:
{
/* Real alias... doesn't returns a builder, but a type
DynamicTypeBuilder_ptr content = get_builder(static_cast<const ::xtypes::AliasType&>(type).get());
DynamicTypeBuilder* ptr = content.get();
return factory->create_alias_type(ptr, type.name());
*/
return get_builder(static_cast<const ::xtypes::AliasType&>(type).rget()); // Resolve alias
}
/*
case ::xtypes::TypeKind::BITMASK_TYPE:
{
// TODO
}
*/
case ::xtypes::TypeKind::ARRAY_TYPE:
{
const ::xtypes::ArrayType& c_type = static_cast<const ::xtypes::ArrayType&>(type);
std::pair<std::vector<uint32_t>, DynamicTypeBuilder_ptr> pair;
get_array_specs(c_type, pair);
DynamicTypeBuilder* builder = static_cast<DynamicTypeBuilder*>(pair.second.get());
DynamicTypeBuilder_ptr result = factory->create_array_builder(builder, pair.first);
return result;
}
case ::xtypes::TypeKind::SEQUENCE_TYPE:
{
const ::xtypes::SequenceType& c_type = static_cast<const ::xtypes::SequenceType&>(type);
DynamicTypeBuilder_ptr content = get_builder(c_type.content_type());
DynamicTypeBuilder* builder = static_cast<DynamicTypeBuilder*>(content.get());
DynamicTypeBuilder_ptr result = factory->create_sequence_builder(builder, c_type.bounds());
return result;
}
case ::xtypes::TypeKind::STRING_TYPE:
{
const ::xtypes::StringType& c_type = static_cast<const ::xtypes::StringType&>(type);
return factory->create_string_builder(c_type.bounds());
}
case ::xtypes::TypeKind::WSTRING_TYPE:
{
const ::xtypes::WStringType& c_type = static_cast<const ::xtypes::WStringType&>(type);
return factory->create_wstring_builder(c_type.bounds());
}
case ::xtypes::TypeKind::MAP_TYPE:
{
const ::xtypes::MapType& c_type = static_cast<const ::xtypes::MapType&>(type);
const ::xtypes::PairType& content_type = static_cast<const ::xtypes::PairType&>(c_type.content_type());
DynamicTypeBuilder_ptr key = get_builder(content_type.first());
DynamicTypeBuilder_ptr value = get_builder(content_type.second());
DynamicTypeBuilder_ptr result = factory->create_map_builder(key.get(), value.get(), c_type.bounds());
return result;
}
case ::xtypes::TypeKind::UNION_TYPE:
{
const ::xtypes::UnionType& c_type = static_cast<const ::xtypes::UnionType&>(type);
DynamicTypeBuilder_ptr disc_type = get_builder(c_type.discriminator());
DynamicTypeBuilder_ptr result = factory->create_union_builder(disc_type.get());
MemberId idx = 0;
for (const std::string& member_name : c_type.get_case_members())
{
bool is_default = c_type.is_default(member_name);
const ::xtypes::Member& member = c_type.member(member_name);
std::vector<int64_t> labels_original = c_type.get_labels(member_name);
std::vector<uint64_t> labels;
for (int64_t label : labels_original)
{
labels.push_back(static_cast<uint64_t>(label));
}
DynamicTypeBuilder_ptr member_builder = get_builder(member.type());
result->add_member(idx++, member_name, member_builder.get(), "", labels, is_default);
}
return result;
}
case ::xtypes::TypeKind::STRUCTURE_TYPE:
{
DynamicTypeBuilder_ptr result = factory->create_struct_builder();
const ::xtypes::StructType& from = static_cast<const ::xtypes::StructType&>(type);
for (size_t idx = 0; idx < from.members().size(); ++idx)
{
const ::xtypes::Member& member = from.member(idx);
DynamicTypeBuilder_ptr member_builder = get_builder(member.type());
DynamicTypeBuilder* builder = static_cast<DynamicTypeBuilder*>(member_builder.get());
DynamicTypeBuilder* result_ptr = static_cast<DynamicTypeBuilder*>(result.get());
result_ptr->add_member(static_cast<MemberId>(idx), member.name(), builder);
}
return result;
}
default:
break;
}
return nullptr;
}
void Conversion::get_array_specs(
const ::xtypes::ArrayType& array,
std::pair<std::vector<uint32_t>, DynamicTypeBuilder_ptr>& result)
{
result.first.push_back(array.dimension());
if (array.content_type().kind() == ::xtypes::TypeKind::ARRAY_TYPE)
{
get_array_specs(static_cast<const ::xtypes::ArrayType&>(array.content_type()), result);
}
else
{
result.second = get_builder(array.content_type());
}
}
const xtypes::DynamicType& Conversion::resolve_discriminator_type(
const ::xtypes::DynamicType& service_type,
const std::string& discriminator)
{
if (discriminator.find(".") == std::string::npos)
{
return service_type;
}
std::string path = discriminator;
const xtypes::DynamicType* type_ptr;
std::string type = path.substr(0, path.find("."));
std::string member;
type_ptr = &service_type;
while (path.find(".") != std::string::npos)
{
path = path.substr(path.find(".") + 1);
member = path.substr(0, path.find("."));
if (type_ptr->is_aggregation_type())
{
const xtypes::AggregationType& aggregation = static_cast<const xtypes::AggregationType&>(*type_ptr);
type_ptr = &aggregation.member(member).type();
}
}
return *type_ptr;
}
::xtypes::WritableDynamicDataRef Conversion::access_member_data(
::xtypes::WritableDynamicDataRef membered_data,
const std::string& path)
{
std::vector<std::string> nodes;
std::string token;
std::istringstream iss(path);
// Split the path
while (std::getline(iss, token, '.'))
{
nodes.push_back(token);
}
// Navigate
return access_member_data(membered_data, nodes, 1);
}
::xtypes::WritableDynamicDataRef Conversion::access_member_data(
::xtypes::WritableDynamicDataRef membered_data,
const std::vector<std::string>& tokens,
size_t index)
{
if (tokens.empty() || index == tokens.size())
{
return membered_data;
}
else
{
return access_member_data(membered_data[tokens[index]], tokens, index + 1);
}
}
} // namespace fastdds
} // namespace sh
} // namespace is
} // namespace eprosima
| 37.207758 | 115 | 0.512451 | [
"vector"
] |
1c97790bf6875fe368a340e84e2534b87eb5e59d | 323 | hpp | C++ | simcore/simulation/library/cell_list_int.hpp | lamsoa729/simcore | daf7056cb0c17563ed0f6bdee343fa1f6cd59729 | [
"MIT"
] | null | null | null | simcore/simulation/library/cell_list_int.hpp | lamsoa729/simcore | daf7056cb0c17563ed0f6bdee343fa1f6cd59729 | [
"MIT"
] | null | null | null | simcore/simulation/library/cell_list_int.hpp | lamsoa729/simcore | daf7056cb0c17563ed0f6bdee343fa1f6cd59729 | [
"MIT"
] | null | null | null | #include <mutex>
#include <tuple>
#include <vector>
typedef std::pair<int, int> ix_pair;
class Cell {
private:
std::mutex cell_mtx;
void PairSelf(std::vector<ix_pair>& nl);
public:
std::vector<int> objs_;
Cell();
void AddObj(int oid);
void PopBack();
void PairObjs(Cell* c, std::vector<ix_pair>* nl);
};
| 17 | 51 | 0.665635 | [
"vector"
] |
1c98adb6cce9b8cd3e3645db45dbe913220a9394 | 4,451 | cpp | C++ | hardware/src/ADS1015.cpp | elchtzeasar/balcony-watering-system | 2fb20dc8bdf79cff4b7ba93cb362489562b62732 | [
"MIT"
] | null | null | null | hardware/src/ADS1015.cpp | elchtzeasar/balcony-watering-system | 2fb20dc8bdf79cff4b7ba93cb362489562b62732 | [
"MIT"
] | null | null | null | hardware/src/ADS1015.cpp | elchtzeasar/balcony-watering-system | 2fb20dc8bdf79cff4b7ba93cb362489562b62732 | [
"MIT"
] | null | null | null | #include "ADS1015.h"
#include "Master.h"
#include <cassert>
#include <sstream>
#include <unistd.h>
#include <iostream>
namespace balcony_watering_system {
namespace hardware {
using std::string;
enum RegisterAddrss {
CONVERSION_REGISTER = 0x0,
CONFIG_REGISTER = 0x1,
LOW_THRESH_REGISTER = 0x2,
HIGH_THRESH_REGISTER = 0x3,
};
enum OperationStatusRegister {
START_SINGLE_CONVERSION = 0x1 << 15,
};
enum InputMultiplexRegister {
INPUT0_VS_INPUT1 = 0x0 << 12,
INPUT0_VS_INPUT3 = 0x1 << 12,
INPUT1_VS_INPUT3 = 0x2 << 12,
INPUT2_VS_INPUT3 = 0x3 << 12,
INPUT0_VS_GROUND = 0x4 << 12,
INPUT1_VS_GROUND = 0x5 << 12,
INPUT2_VS_GROUND = 0x6 << 12,
INPUT3_VS_GROUND = 0x7 << 12,
};
enum AmplifierRegister {
AMPLIFIER_6_144V = 0x0 << 9,
AMPLIFIER_4_096V = 0x1 << 9,
AMPLIFIER_2_048V = 0x2 << 9,
AMPLIFIER_1_024V = 0x3 << 9,
AMPLIFIER_0_512V = 0x4 << 9,
AMPLIFIER_0_256V = 0x5 << 9,
};
enum ModeRegister {
CONTINUOUS_CONVERSION_MODE = 0x0 << 8,
SINGLE_SHOT_CONVERSION_MODE = 0x1 << 8,
};
enum DataRateRegister {
DATA_RATE_128SPS = 0x0 << 5,
DATA_RATE_250SPS = 0x1 << 5,
DATA_RATE_490SPS = 0x2 << 5,
DATA_RATE_920SPS = 0x3 << 5,
DATA_RATE_1600SPS = 0x4 << 5,
DATA_RATE_2400SPS = 0x5 << 5,
DATA_RATE_3300SPS = 0x6 << 5,
};
enum ComparatorModeRegister {
TRADITIONAL_COMPARATOR = 0x0 << 4,
WINDOW_COMPARATOR = 0x1 << 4,
};
enum ComparatorPolarityRegister {
COMPARATOR_POLARITY_ACTIVE_LOW = 0x0 << 3,
COMPARATOR_POLARITY_ACTIVE_HIGH = 0x1 << 3,
};
enum ComparatorLatchRegister {
NON_LATCHING_COMPARATOR = 0x0 << 2,
LATCHING_COMPARATOR = 0x1 << 2,
};
enum ComparatorQueRegister {
COMPARATOR_DISABLE = 0x3 << 0,
COMPARATOR_ASSERT_AFTER_4_CONVERSIONS = 0x2 << 0,
COMPARATOR_ASSERT_AFTER_2_CONVERSIONS = 0x1 << 0,
COMPARATOR_ASSERT_AFTER_1_CONVERSIONS = 0x0 << 0,
};
const uint16_t DEFAULT_COMMAND =
START_SINGLE_CONVERSION | AMPLIFIER_6_144V | SINGLE_SHOT_CONVERSION_MODE | DATA_RATE_3300SPS;
ADS1015::ADS1015(const string& namePrefix, Master& master) :
master(master),
analogInputs(),
logger("hardware.ads1015", namePrefix) {
master.registerReadNode(*this);
for (int i = 0; i < 4; i++) {
std::ostringstream stream;
stream << namePrefix << "." << i;
analogInputs.push_back(AnalogInput(stream.str(), -6.144, 6.144));
}
}
ADS1015::~ADS1015() {
}
void ADS1015::doSample() {
LOG_TRACE(logger, "doSample");
for (int i = 0; i < 4; i++) {
master.setNodeAddress(0x48);
uint16_t input;
switch (i) {
case 0: input = INPUT0_VS_GROUND; break;
case 1: input = INPUT1_VS_GROUND; break;
case 2: input = INPUT2_VS_GROUND; break;
case 3: input = INPUT3_VS_GROUND; break;
default: assert(false && "bad index");
}
const uint16_t command = DEFAULT_COMMAND | input;
const uint8_t commandMsb = static_cast<uint8_t>((command >> 8) & 0xff);
const uint8_t commandLsb = static_cast<uint8_t>((command >> 0) & 0xff);
const uint8_t writeData[3] = { CONFIG_REGISTER, commandMsb, commandLsb };
master.writeData(writeData, 3);
bool dataReady;
do {
constexpr size_t expectedResponseSize = 2;
master.setNodeAddress(0x48);
uint8_t status[expectedResponseSize];
const size_t actualResponseSize = master.readData(status, 2);
assert(actualResponseSize == expectedResponseSize);
dataReady = (status[0] & 0x80) == 0x80;
usleep(100);
} while (!dataReady);
master.setNodeAddress(0x48);
master.writeByte(uint8_t{CONVERSION_REGISTER});
usleep(10000);
constexpr size_t expectedDataSize = 2;
uint8_t data[expectedDataSize] = {0};
master.setNodeAddress(0x48);
const size_t actualDataSize = master.readData(data, expectedDataSize);
assert(actualDataSize == expectedDataSize);
const int16_t msb = data[0];
const int16_t lsb = data[1];
const int16_t voltageWord = ((msb << 8) & 0xff00) | (lsb & 0x00ff);
const int VDD = 6.144;
const float voltage = voltageWord / float(0x7ff0) * VDD;
analogInputs.at(i).setCurrentVoltage(voltage);
LOG_TRACE(logger, "doSample[" << i << "] "
<< std::hex
<< "msb=0x" << msb
<< ", lsb=0x" << lsb
<< " => voltageWord=0x" << voltageWord
<< std::dec
<< " => voltage=" << voltage);
}
}
const std::vector<AnalogInput>& ADS1015::getAnalogInputs() const {
return analogInputs;
}
} /* namespace hardware */
} /* namespace balcony_watering_system */
| 27.645963 | 97 | 0.677825 | [
"vector"
] |
1c9bf1fd144dc4a53b3fa3c761e7d281b773ef0f | 2,028 | cpp | C++ | dataset/test/modification/1491_rename/10/transformation_1.cpp | Karina5005/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | 3 | 2022-02-15T00:29:39.000Z | 2022-03-15T08:36:44.000Z | dataset/test/modification/1491_rename/10/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | dataset/test/modification/1491_rename/10/transformation_1.cpp | Kira5005-code/Plagiarism | ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <random>
#include <set>
#include <queue>
#ifdef HOME
#define debug(x) cerr << #x << " = " << x << endl;
#define debug_v(v) \
{ \
cerr << #v << " = "; \
for (auto x : v) \
cerr << x << " "; \
cerr << endl; \
}
#define debug_vp(v) \
{ \
cerr << #v << " = "; \
for (auto [x, y] : v) \
cerr << x << "," << y << " "; \
cerr << endl; \
}
#else
#define debug(x) 0;
#define debug_v(x) 0;
#define debug_vp(x) 0;
#endif // HOME
using namespace std;
// mt19937 rng(5);
// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define fo(i, n) for (int i = 0; i < n; ++i)
#define foback(i, n) for (int i = n - 1; i >= 0; --i)
#define fo1(i, n) for (ll i = 1; i <= n; ++i)
typedef long long ll;
void ai()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
void ddk();
int main()
{
ai();
int j = 1;
cin >> j;
fo(i, t)
{
ddk();
}
return 0;
}
void one()
{
int sdd_oyq, tj_ccb;
cin >> sdd_oyq >> tj_ccb;
bool y = true;
if (tj_ccb < sdd_oyq)
{
cout << "NO\n";
return;
}
int pub_be = 0;
fo(i, 31)
{
int dx = (1 << i);
if (sdd_oyq & dx)
{
pub_be++;
}
if (tj_ccb & dx)
{
if (pub_be <= 0)
{
cout << "NO\n";
return;
}
else
{
pub_be--;
}
}
}
cout << (y ? "YES" : "NO") << "\n";
}
// 1 = 001 6 = 110
// 3 = 011
// 6 = 110 | 18.27027 | 72 | 0.365385 | [
"vector"
] |
1c9e4fdfc8cb2dd6a7db25c9def3c1491622f796 | 3,816 | cpp | C++ | graph-source-code/27-D/3383775.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/27-D/3383775.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/27-D/3383775.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: MS C++
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll __int64
#define ls rt<<1
#define rs ls|1
#define lson l,mid,ls
#define rson mid+1,r,rs
#define middle (l+r)>>1
#define clr_all(x,c) memset(x,c,sizeof(x))
#define clr(x,c,n) memset(x,c,sizeof(x[0])*(n+1))
#define eps (1e-8)
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#pragma comment(linker, "/STACK:102400000,102400000")
template <class T> T _max(T x,T y){return x>y? x:y;}
template <class T> T _min(T x,T y){return x<y? x:y;}
template <class T> T _abs(T x){return (x < 0)? -x:x;}
template <class T> T _mod(T x,T y){return (x > 0)? x%y:((x%y)+y)%y;}
template <class T> void _swap(T &x,T &y){T t=x;x=y;y=t;}
template <class T> void getmax(T& x,T y){x=(y > x)? y:x;}
template <class T> void getmin(T& x,T y){x=(x<0 || y<x)? y:x;}
int TS,cas=1;
const int M=100+5;
int n,m;
struct edge{
int u,v;
void read(){
scanf("%d%d",&u,&v);
if(u>v) _swap(u,v);
}
}p[M];
bool isIntersect(int l1,int r1,int l2,int r2){
if(l1<l2 && l2<r1 && r1<r2) return true;
if(l2<l1 && l1<r2 && r2<r1) return true;
return false;
}
vector<int>init[M<<1],now[M<<1];
int pre[M<<1],low[M<<1],idx[M<<1];
int ss[M<<1],top,index,nn;
int deg[M<<1],op[M<<1];
void dfs(int u){
ss[++top]=u;
pre[u]=low[u]=++index;
for(int i=0;i<init[u].size();i++){
int v=init[u][i];
if(pre[v]==-1){
dfs(v);
getmin(low[u],low[v]);
}else if(idx[v]==-1){
getmin(low[u],pre[v]);
}
}
if(pre[u]==low[u]){
now[++nn].clear();
int v=-1;
while(u!=v){
idx[v=ss[top--]]=nn;
}
}
}
void Tarjan(int n){
ss[top=index=nn=0]=-1;
clr(pre,-1,n+1),clr(idx,-1,n+1);
for(int i=1;i<=n;i++){
if(pre[i]==-1) dfs(i);
}
}
void shrink(int n){
clr(deg,0,n+1);
for(int u=1;u<=n;u++){
for(int i=0;i<init[u].size();i++){
int v=init[u][i];
if(idx[v]!=idx[u]){
now[idx[u]].push_back(idx[v]);
deg[idx[v]]++;
}
}
}
}
void run(){
int i,j;
for(i=1;i<=m;i++) p[i].read();
for(i=1;i<=m*2;i++) init[i].clear();
bool flag=true;
for(i=1;i<=m;i++){
for(j=i+1;j<=m;j++){
if(isIntersect(p[i].u,p[i].v,p[j].u,p[j].v)){
init[i].push_back(j+m);
init[j+m].push_back(i);
init[j].push_back(i+m);
init[i+m].push_back(j);
}
}
}
Tarjan(m<<1);
for(i=1;i<=m;i++){
if(idx[i]==idx[i+m]){
puts("Impossible");
return;
}
}
shrink(nn);
for(i=1;i<=m;i++){
op[idx[i]]=idx[i+m];
op[idx[i+m]]=idx[i];
}
ss[top=0]=-1;
for(i=1;i<=nn;i++) if(!deg[i]){
ss[++top]=idx[i];
deg[idx[i]]=-1,deg[op[idx[i]]]=-2;
}
while(top){
int u=ss[top--];
for(i=0;i<now[u].size();i++){
int v=now[u][i];
if(--deg[v]==0) ss[++top]=v,deg[v]=-1,deg[op[v]]=-2;
}
}
for(i=1;i<=m;i++){
if(deg[idx[i]]==-1) putchar('o');
else putchar('i');
}puts("");
}
void preSof(){
}
int main(){
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
preSof();
//run();
while((~scanf("%d%d",&n,&m))) run();
//for(scanf("%d",&TS);cas<=TS;cas++) run();
return 0;
} | 24.779221 | 69 | 0.460168 | [
"vector"
] |
1ca9bf3f35c570d1e66f358683ab470c4c0a264c | 19,873 | cpp | C++ | src/south/sonic-interface/main.cpp | falcacicd/goldstone-mgmt | e7348011180e3c2dcd0558636ddc5c21779c7a3f | [
"Apache-2.0"
] | null | null | null | src/south/sonic-interface/main.cpp | falcacicd/goldstone-mgmt | e7348011180e3c2dcd0558636ddc5c21779c7a3f | [
"Apache-2.0"
] | null | null | null | src/south/sonic-interface/main.cpp | falcacicd/goldstone-mgmt | e7348011180e3c2dcd0558636ddc5c21779c7a3f | [
"Apache-2.0"
] | null | null | null | /***************************************************************
* File name : main.cpp *
* Description : This file is the south bound application used*
* to register yang files for sonic submodules. *
***************************************************************/
#include <chrono>
#include <thread>
#include <csignal>
#include <queue>
#include "controller.hpp"
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <fstream>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <curl/curl.h>
#include <getopt.h>
volatile int exit_application = 0;
static const std::string SONIC_PORT_MODULE_NAME = "sonic-port";
static const std::string SONIC_INTERFACE_MODULE_NAME = "sonic-interface";
/* holder for curl fetch */
struct
curl_fetch_st
{
char *payload;
size_t size;
};
/*****************************************************************************
* Function Name : sigint_handler *
* Description : To handle the signal interrupt *
* Input : int signum *
* Output : void *
*****************************************************************************/
static void
sigint_handler (int signum)
{
(void) signum;
exit_application = 1;
}
/*****************************************************************************
* Function Name : _populate_oper_data *
* Description : To populate the operational datastore *
* Input : libyang::S_Context& ctx *
* libyang::S_Data_Node& parent *
* const std::string& name *
* const std::string& path *
* const std::string& value *
* Output : static int *
*****************************************************************************/
static int
_populate_oper_data (libyang::S_Context& ctx,
libyang::S_Data_Node& parent,
const std::string& name,
const std::string& path,
const std::string& value)
{
std::stringstream xpath;
xpath << name << "/" << path;
parent->new_path (ctx, xpath.str().c_str(),
value.c_str(),
LYD_ANYDATA_CONSTSTRING, 0);
return SR_ERR_OK;
}
/*****************************************************************************
* Function Name : get_index_of_yang *
* Description : To get the primary key of yang data *
* Input : libyang::S_Data_Node &parent *
* Output : char *
*****************************************************************************/
char
*get_index_of_yang (libyang::S_Data_Node &parent)
{
lyd_node *lyd = parent->C_lyd_node();
lys_node *lys = lyd->schema;
while (lys->nodetype != LYS_LEAF)
{
lys = lys->child;
}
return (char *)lys->name;
}
/*****************************************************************************
* Function Name : json_decode *
* Description : To decode the received json data *
* Input : json j *
* libyang::S_Context& ly_ctx *
* libyang::S_Data_Node &parent *
* const char *request_xpath *
* Output : void *
*****************************************************************************/
void
json_decode (json j, libyang::S_Context& ly_ctx,
libyang::S_Data_Node &parent,
const char *request_xpath)
{
std::stringstream val;
std::stringstream xpath;
switch (j.type())
{
case nlohmann::basic_json<>::value_t::object:
for (auto& x : j.items())
{
if (x.value().is_primitive())
{
char *primKey = get_index_of_yang(parent);
std::string index = j[primKey];
xpath.str("");
xpath << request_xpath << "[" << primKey << "='" << index << "']";
if (strcmp(x.key().c_str(), primKey))
{
if (x.value().is_string())
{
_populate_oper_data (ly_ctx, parent,
xpath.str().c_str(),
x.key(),
x.value());
}
else if (x.value().is_number())
{
val.str("");
val << x.value();
_populate_oper_data (ly_ctx, parent,
xpath.str().c_str(),
x.key(),
val.str().c_str());
}
}
}
else
{
json_decode (x.value(), ly_ctx, parent, request_xpath);
}
}
break;
case nlohmann::basic_json<>::value_t::array:
for (json::iterator it = j.begin(); it != j.end(); ++it)
{
json_decode (*it, ly_ctx, parent, request_xpath);
}
break;
}
}
/*****************************************************************************
* Function Name : curl_callback *
* Description : Callback for curl fetch *
* Input : void *contents *
* size_t size *
* size_t nmemb *
* void *userp *
* Output : size_t *
*****************************************************************************/
size_t
curl_callback (void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct curl_fetch_st *p = (struct curl_fetch_st *) userp;
p->payload = (char *) realloc (p->payload, p->size + realsize + 1);
/* check buffer */
if (p->payload == NULL)
{
fprintf (stderr, "ERROR: Failed to expand buffer in curl_callback");
/* free buffer */
free (p->payload);
/* return */
return size;
}
/* copy contents to buffer */
memcpy (&(p->payload[p->size]), contents, realsize);
/* set new buffer size */
p->size += realsize;
/* ensure null termination */
p->payload[p->size] = 0;
/* return size */
return realsize;
}
/*****************************************************************************
* Function Name : set_sonic_parameters *
* Description : Sonic Parameters *
* Input : std::string mgmt_ip *
* std::string port_no *
* Output : *
*****************************************************************************/
void
SonicController::set_sonic_parameters (std::string mgmt_ip, std::string port_no)
{
mgmt_server = mgmt_ip;
port = port_no;
}
/*****************************************************************************
* Function Name : oper_get_items *
* Description : To get the Operational data *
* Input : sysrepo::S_Session session *
* const char *module_name *
* const char *path *
* const char *request_xpath *
* uint32_t request_id *
* libyang::S_Data_Node &parent *
* void *private_data *
* Output : int *
*****************************************************************************/
int
SonicController::oper_get_items (sysrepo::S_Session session,
const char *module_name,
const char *path,
const char *request_xpath,
uint32_t request_id,
libyang::S_Data_Node &parent,
void *private_data)
{
std::stringstream url;
libyang::S_Context ly_ctx = session->get_context();
CURL *curl;
CURLcode res;
curl_fetch_st curl_fetch;
curl_fetch_st *fetch = &curl_fetch;
fetch->payload = (char *) calloc (1, sizeof(fetch->payload));
/* check payload */
if (fetch->payload == NULL)
{
/* log error */
fprintf (stderr, "ERROR: Failed to allocate payload in curl_fetch_url");
/* return error */
return 0;
}
fetch->size = 0;
url << port << "://" << mgmt_server << "/restconf/data";
curl = curl_easy_init ();
if (curl)
{
url << request_xpath;
curl_easy_setopt (curl, CURLOPT_URL, url.str().c_str());
curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, curl_callback);
curl_easy_setopt (curl, CURLOPT_WRITEDATA, (void *) fetch);
/* Perform the request, res will get the return code */
res = curl_easy_perform (curl);
/* Check for errors */
if (res != CURLE_OK)
{
fprintf (stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
/* always cleanup */
curl_easy_cleanup (curl);
}
if (fetch->payload != NULL)
{
printf ("CURL Returned: \n%s\n", fetch->payload);
}
json j = json::parse (fetch->payload);
json_decode (j, ly_ctx, parent, request_xpath);
session->apply_changes ();
return SR_ERR_OK;
}
/*****************************************************************************
* Function Name : print_current_config *
* Description : To print the configured data *
* Input : sysrepo::S_Session session *
* const char *module_name *
* Output : static void *
*****************************************************************************/
static void
print_current_config (sysrepo::S_Session session, const char *module_name)
{
char select_xpath[100];
try
{
snprintf (select_xpath, 100, "/%s:*//.", module_name);
auto values = session->get_items (&select_xpath[0]);
if (values == nullptr)
{
return;
}
for (unsigned int i = 0; i < values->val_cnt(); i++)
{
std::cout << values->val(i)->to_string();
}
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
/*****************************************************************************
* Function Name : module_change *
* Description : Callback for set function *
* Input : sysrepo::S_Session session *
* const char *module_name *
* const char *xpath *
* sr_event_t event *
* uint32_t request_id *
* void *private_data *
* Output : int *
*****************************************************************************/
int
SonicController::module_change (sysrepo::S_Session session,
const char *module_name,
const char *xpath,
sr_event_t event,
uint32_t request_id,
void *private_data)
{
CURL *curl;
CURLcode res;
struct curl_slist *headers = NULL;
libyang::S_Data_Node tree;
std::string json_data;
std::stringstream url;
tree = std::make_shared<libyang::Data_Node>(nullptr);
/* To get the subtree of a particular node */
tree = session->get_subtree (xpath, 0);
/* To store the yang tree in json format */
json_data = tree->print_mem (LYD_JSON, 0);
headers = curl_slist_append (headers, "accept: application/yang-data+json");
headers = curl_slist_append (headers, "Content-Type: application/yang-data+json");
url << port << "://" << mgmt_server << "/restconf/data";
curl = curl_easy_init ();
if (curl)
{
url << xpath;
curl_easy_setopt (curl, CURLOPT_URL, url.str().c_str());
curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0);
/* To execute the CURL PUT operation*/
curl_easy_setopt (curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt (curl, CURLOPT_FAILONERROR, true);
curl_easy_setopt (curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt (curl, CURLOPT_POSTFIELDS, json_data.c_str());
/* Perform the request, res will get the return code */
res = curl_easy_perform (curl);
/* Check for errors */
if (res != CURLE_OK)
{
fprintf (stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
/* always cleanup */
curl_easy_cleanup (curl);
}
std::cout << "\n\n ========== EVENT CHANGES: ==========\n\n" << std::endl;
print_current_config (session, module_name);
return SR_ERR_OK;
}
/*****************************************************************************
* Function Name : SonicController *
* Description : To subscribe for yang module *
* Input : sysrepo::S_Session& sess) : m_sess(sess) *
* m_subscribe(new sysrepo::Subscribe(sess) *
* Output : *
*****************************************************************************/
SonicController::SonicController (sysrepo::S_Session& sess) : m_sess(sess),
m_subscribe(new sysrepo::Subscribe(sess))
{
auto mod_name_port = SONIC_PORT_MODULE_NAME.c_str();
auto mod_name_interface = SONIC_INTERFACE_MODULE_NAME.c_str();
auto callback = sysrepo::S_Callback (this);
/* To subscribe callback for sysrepo write functionality*/
m_subscribe->module_change_subscribe (mod_name_port,
callback,
"/sonic-port:sonic-port/PORT");
m_subscribe->module_change_subscribe (mod_name_interface,
callback,
"/sonic-interface:sonic-interface/INTERFACE");
/* read running config */
std::cout << "\n\n ========== READING RUNNING CONFIG: ==========\n" << std::endl;
print_current_config (sess, mod_name_port);
/* To subscribe callback for sysrepo get functionality */
m_subscribe->oper_get_items_subscribe (mod_name_port,
"/sonic-port:sonic-port/PORT",
callback);
m_subscribe->oper_get_items_subscribe (mod_name_interface,
"/sonic-interface:sonic-interface/INTERFACE",
callback);
}
/*****************************************************************************
* Function Name : SonicController *
* Description : Destructor *
*****************************************************************************/
SonicController::~SonicController()
{}
/*****************************************************************************
* Function Name : loop *
* Description : Used for looping main *
* Input : *
* Output : void *
*****************************************************************************/
void
SonicController::loop()
{
/* loop until ctrl-c is pressed / SIGINT is received */
signal (SIGINT, sigint_handler);
signal (SIGPIPE, SIG_IGN);
while (!exit_application)
{
std::this_thread::sleep_for (std::chrono::seconds(1000));
}
}
/*****************************************************************************
* Function Name : main *
* Description : Driver function *
* Input : void *
* Output : int *
*****************************************************************************/
int
main (int argc,char **argv)
{
int c;
int verbose = 0;
std::string mgmt_ip, port_no;
int option_index = 0;
static struct option long_options[] =
{
{ "verbose", no_argument, 0, 'v' },
{ "mgmt_ip", required_argument, 0, 's' },
{ "port_no", required_argument, 0, 'p' }
};
while ((c = getopt_long (argc, argv, "v:s:p:", long_options, &option_index)) != -1 )
{
switch (c)
{
case 'v':
verbose = 1;
break;
case 's':
mgmt_ip = std::string (optarg);
break;
case 'p':
port_no = std::string (optarg);
break;
default:
std::cout << "usage: " << argv[0]
<< " -s <mgmt-server-ip> -p <port:https/http>" << std::endl;
return -1;
}
}
if (argc < 5)
{
std::cout << "mgmt_server-ip and port is mandatory" << std::endl;
std::cout << "usage: " << argv[0]
<< " -s <mgmt-server-ip> -p <port:https/http>" << std::endl;
exit (1);
}
if (verbose)
{
sysrepo::Logs().set_stderr (SR_LL_DBG);
}
sysrepo::S_Connection conn (new sysrepo::Connection);
sysrepo::S_Session sess (new sysrepo::Session(conn));
sysrepo::S_Subscribe subscribe (new sysrepo::Subscribe(sess));
auto controller = SonicController (sess);
controller.set_sonic_parameters(mgmt_ip, port_no);
controller.loop ();
std::cout << "Application exit requested, exiting." << std::endl;
return 0;
}
| 39.043222 | 86 | 0.404972 | [
"object"
] |
1cb2b4b67ae01ffa24e3532e7c7fbfb92118f8ba | 2,078 | cc | C++ | Question/最长公共子序列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | Question/最长公共子序列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | Question/最长公共子序列.cc | lkimprove/Study_C | ee1153536f28e160d5daad4ddebaa547c3941ee7 | [
"MIT"
] | null | null | null | // write your code here cpp
//子串:顺序取出,且连续
//子序列:顺序取出,可不连续
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string s1, s2;
while(cin >> s1 >> s2){
int n = s1.size(), m = s2.size();
//dp[i][j]:
// 1.dp[i - 1][j - 1] + 1; s1[i - 1] == s2[j - 1]
// 2.max(dp[i - 1][j], dp[i][j - 1]); otherwise
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s1[i - 1] == s2[j - 1]){
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else{
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
cout << dp[n][m] << endl;
}
return 0;
}
//需要输出最长子序列
class Solution {
public:
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
string LCS(string s1, string s2) {
// write code here
int n = s1.size(), m = s2.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s1[i - 1] == s2[j - 1]){
dp[i][j] = dp[i -1][j - 1] + 1;
}
else{
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
int maxlen = dp[n][m];
if(maxlen == 0){
return "-1";
}
string ret;
int i = 1, j = 1;
while(maxlen > 0 && i <= n && j <= m){
if(dp[i - 1][j] == dp[i][j]){
i++;
}
else if(dp[i][j - 1] == dp[i][j]){
j++;
}
else{
ret.push_back(s1[i - 1]);
i++;
j++;
maxlen--;
}
}
return ret;
}
};
| 23.613636 | 63 | 0.333975 | [
"vector"
] |
1cb357d7937ffd6e7f2f6d076557598bf97aa16d | 782 | hpp | C++ | Reflection/FunctionContainers.hpp | jodavis42/SimpleMeta | 1d42ef6b9a1138789c48f988c22eaaec3519f381 | [
"MIT"
] | null | null | null | Reflection/FunctionContainers.hpp | jodavis42/SimpleMeta | 1d42ef6b9a1138789c48f988c22eaaec3519f381 | [
"MIT"
] | 37 | 2020-02-06T16:10:59.000Z | 2020-03-11T00:29:26.000Z | Reflection/FunctionContainers.hpp | jodavis42/SimpleMeta | 1d42ef6b9a1138789c48f988c22eaaec3519f381 | [
"MIT"
] | 1 | 2020-02-13T17:05:25.000Z | 2020-02-13T17:05:25.000Z | #pragma once
#include <vector>
#include <string>
#include <unordered_map>
namespace SimpleReflection
{
struct Function;
struct FunctionType;
struct BoundType;
struct FunctionList : public std::vector<Function*>
{
Function* FindFunction(const FunctionType& functionType) const;
void DeleteAll();
};
struct FunctionMultiMap : public std::unordered_map<std::string, FunctionList>
{
Function* FindFunction(const std::string& fnName, const FunctionType& functionType) const;
void DeleteAll();
};
struct ExtensionFunctionMultiMap : public std::unordered_map<const BoundType*, FunctionMultiMap>
{
Function* FindFunction(const BoundType* boundType, const std::string& fnName, const FunctionType& functionType) const;
void DeleteAll();
};
}//namespace SimpleReflection
| 21.722222 | 120 | 0.774936 | [
"vector"
] |
1cba771d1bfb02591da71dca2aa5cf60c62db650 | 1,432 | cpp | C++ | main.cpp | GoldFeniks/delaunay | a96621d28a57bd6c73fbecf0ae5347714a3ed07e | [
"MIT"
] | null | null | null | main.cpp | GoldFeniks/delaunay | a96621d28a57bd6c73fbecf0ae5347714a3ed07e | [
"MIT"
] | 1 | 2021-01-31T11:20:44.000Z | 2021-02-01T00:16:53.000Z | main.cpp | GoldFeniks/delaunay | a96621d28a57bd6c73fbecf0ae5347714a3ed07e | [
"MIT"
] | null | null | null | #include <chrono>
#include <vector>
#include <random>
#include <fstream>
#include <iostream>
#include <functional>
#include "delaunay.hpp"
template<typename T>
void output_vector(std::ofstream& out, const std::vector<T>& values) {
for (const auto& it : values)
out << it << ' ';
out << std::endl;
}
int main() {
constexpr auto n = 50;
std::vector<double> x(n), y(n);
std::default_random_engine eng(static_cast<unsigned long>(time(nullptr)));
std::uniform_real_distribution<double> dist(-10000, 10000);
auto random = std::bind(dist, eng);
for (size_t i = 0; i < n; ++i) {
x[i] = random();
y[i] = random();
}
std::ofstream out("test.txt");
output_vector(out, x);
output_vector(out, y);
const auto t1 = std::chrono::system_clock::now();
delaunay_triangulation<double> tri(x, y);
const auto t2 = std::chrono::system_clock::now();
std::cout << "Evaluation time(ms): " << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << std::endl;
std::cout << "Number of points : " << tri.points().size() << std::endl;
std::cout << "Number of edges : " << tri.edges().size() << std::endl;
std::cout << "Number of triangles: " << tri.triangles().size() << std::endl;
for (const auto& it : tri.edges())
out << it.a.get().x << ' ' << it.a.get().y << ' '<< it.b.get().x << ' ' << it.b.get().y << std::endl;
} | 33.302326 | 128 | 0.585894 | [
"vector"
] |
1cc0581f5bf2c2d78c7d0d5d9081efb1ada7dac0 | 1,380 | cpp | C++ | renderer/objects/Triangle.cpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | null | null | null | renderer/objects/Triangle.cpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | null | null | null | renderer/objects/Triangle.cpp | AdrienVannson/3D-Renderer | 78148e88b9ab91ccaea0f883a746ee93cac5d767 | [
"MIT"
] | 1 | 2021-03-18T08:05:35.000Z | 2021-03-18T08:05:35.000Z | #include "Triangle.hpp"
#include "renderer/Stats.hpp"
Triangle::Triangle (const Vect &A, const Vect &B, const Vect &C, const Material &material) :
SolidObject(material),
m_A(A),
m_B(B),
m_C(C)
{}
Triangle::~Triangle ()
{}
double Triangle::collisionDate (const Ray &ray) const
{
Stats::addRayTriangleTest();
const Vect n = (m_B - m_A) ^ (m_C - m_A);
const double lambda = (n * (m_A - ray.pos())) / (n * ray.dir());
if (lambda <= 0) {
return INFINITY;
}
const Vect M = ray.pos() + lambda * ray.dir();
// Check if M is in ABC
if ( ((m_B-m_A) ^ (M-m_A)) * ((M-m_A) ^ (m_C-m_A)) >= 0
&& ((m_A-m_B) ^ (M-m_B)) * ((M-m_B) ^ (m_C-m_B)) >= 0
&& ((m_A-m_C) ^ (M-m_C)) * ((M-m_C) ^ (m_B-m_C)) >= 0) {
Stats::addRayTriangleIntersection();
return lambda;
}
return INFINITY;
}
Vect Triangle::normal (const Vect &pos) const
{
(void)pos;
Vect normal = (m_B - m_A) ^ (m_C - m_A);
normal.normalize();
return normal;
}
Object::Collision Triangle::collision (const Ray &ray) const
{
Collision col;
col.date = collisionDate(ray);
col.normal = normal(ray.pos() + col.date*ray.dir());
col.material = m_material;
return col;
}
Box Triangle::boundingBox () const
{
Box res;
res.addPoint(m_A);
res.addPoint(m_B);
res.addPoint(m_C);
return res;
}
| 21.5625 | 92 | 0.57029 | [
"object"
] |
1cc83b4ccd5ff5a16eb4049f5959a52738d6dbab | 5,870 | cc | C++ | code/application/physicsfeature/properties/staticphysicsproperty.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/application/physicsfeature/properties/staticphysicsproperty.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/application/physicsfeature/properties/staticphysicsproperty.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z |
// physicsfeature/properties/staticphysicsproperty.cc
// (C) 2005 Radon Labs GmbH
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "physicsfeature/properties/staticphysicsproperty.h"
#include "game/entity.h"
#include "physics/physicsserver.h"
#include "physics/scene.h"
#include "physics/physicsbody.h"
#include "physicsfeature/physicsattr/physicsattributes.h"
#include "core/factory.h"
#include "basegamefeature/basegameprotocol.h"
#include "physicsfeature/physicsprotocol.h"
#include "graphicsfeature/graphicsfeatureprotocol.h"
#include "io/ioserver.h"
#include "io/xmlreader.h"
#include "resources/resourcemanager.h"
#include "graphicsfeature/graphicsattr/graphicsattributes.h"
#include "physics/resource/managedphysicsmodel.h"
#include "multiplayer/multiplayerfeatureunit.h"
namespace PhysicsFeature
{
using namespace Game;
using namespace Math;
using namespace BaseGameFeature;
using namespace Physics;
using namespace Util;
__ImplementClass(PhysicsFeature::StaticPhysicsProperty, 'SPPR', TransformableProperty);
//------------------------------------------------------------------------------
/**
*/
StaticPhysicsProperty::StaticPhysicsProperty()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
StaticPhysicsProperty::~StaticPhysicsProperty()
{
n_assert(!this->physicsEntity.isvalid());
}
//------------------------------------------------------------------------------
/**
Called when property is attached to a game entity. This will create and setup
the required physics entities.
*/
void
StaticPhysicsProperty::OnActivate()
{
TransformableProperty::OnActivate();
// activate physics by default
this->EnablePhysics();
}
//------------------------------------------------------------------------------
/**
Called when property is going to be removed from its game entity.
This will release the physics entity owned by the game entity.
*/
void
StaticPhysicsProperty::OnDeactivate()
{
if (this->IsEnabled())
{
this->DisablePhysics();
}
this->physicsEntity = 0;
TransformableProperty::OnDeactivate();
}
//------------------------------------------------------------------------------
/**
*/
void
StaticPhysicsProperty::SetupAcceptedMessages()
{
this->RegisterMessage(SetTransform::Id);
this->RegisterMessage(EnableCollisionCallback::Id);
this->RegisterMessage(SetCollideCategory::Id);
this->RegisterMessage(SetCollideCategoryMask::Id);
this->RegisterMessage(Collision::Id);
TransformableProperty::SetupAcceptedMessages();
}
//------------------------------------------------------------------------------
/**
*/
void
StaticPhysicsProperty::HandleMessage(const Ptr<Messaging::Message>& msg)
{
n_assert(0 != msg);
if (this->IsEnabled())
{
if (msg->CheckId(SetTransform::Id))
{
// set transform of physics entity
SetTransform* transformMsg = (SetTransform*) msg.get();
this->physicsEntity->SetTransform(transformMsg->GetMatrix());
}
else if (msg->CheckId(EnableCollisionCallback::Id))
{
Ptr<PhysicsFeature::EnableCollisionCallback> velMsg = msg.downcast<PhysicsFeature::EnableCollisionCallback>();
this->physicsEntity->SetEnableCollisionCallback(velMsg->GetEnableCallback());
}
else if (msg->CheckId(SetCollideCategory::Id))
{
Ptr<PhysicsFeature::SetCollideCategory> velMsg = msg.downcast<PhysicsFeature::SetCollideCategory>();
this->physicsEntity->SetCollideCategory(velMsg->GetCategory());
}
else if (msg->CheckId(SetCollideCategoryMask::Id))
{
Ptr<PhysicsFeature::SetCollideCategoryMask> velMsg = msg.downcast<PhysicsFeature::SetCollideCategoryMask>();
this->physicsEntity->SetCollideFilter(velMsg->GetCategoryMask());
}
}
// need to forward to parent
TransformableProperty::HandleMessage(msg);
}
//------------------------------------------------------------------------------
/**
*/
void
StaticPhysicsProperty::EnablePhysics()
{
n_assert(!this->IsEnabled());
if (this->entity->HasAttr(Attr::Graphics)
&& this->entity->GetString(Attr::Graphics).IsValid())
{
Util::String path;
path.Format("physics:%s.np3",this->entity->GetString(Attr::Graphics).AsCharPtr());
Ptr<ManagedPhysicsModel> model = Resources::ResourceManager::Instance()->CreateManagedResource(PhysicsModel::RTTI,path).cast<ManagedPhysicsModel>();
Ptr<PhysicsObject> object;
object = model->GetModel()->CreateStaticInstance(this->entity->GetMatrix44(Attr::Transform))[0];
PhysicsServer::Instance()->GetScene()->Attach(object);
Physics::MaterialType mat = Physics::MaterialTable::StringToMaterialType(this->entity->GetString(Attr::PhysicMaterial));
object->SetMaterialType(mat);
this->physicsEntity = object.cast<StaticObject>();
this->physicsEntity->SetUserData(this->entity.cast<Core::RefCounted>());
if(this->entity->HasAttr(Attr::CollisionFeedback))
{
this->physicsEntity->SetEnableCollisionCallback(this->entity->GetBool(Attr::CollisionFeedback));
}
}
}
//------------------------------------------------------------------------------
/**
*/
void
StaticPhysicsProperty::DisablePhysics()
{
n_assert(this->IsEnabled());
if (this->physicsEntity.isvalid())
{
PhysicsServer::Instance()->GetScene()->Detach(this->physicsEntity.cast<PhysicsObject>());
this->physicsEntity = 0;
}
}
//------------------------------------------------------------------------------
/**
*/
void
StaticPhysicsProperty::SetEnabled(bool setEnabled)
{
if (this->IsEnabled() != setEnabled)
{
if (setEnabled)
{
this->EnablePhysics();
}
else
{
this->DisablePhysics();
}
}
}
}; // namespace Properties
| 29.497487 | 150 | 0.623509 | [
"object",
"model",
"transform"
] |
1cdfa709a1e1f284aea97eab70821df4ab16557c | 3,698 | cpp | C++ | main.cpp | cazzwastaken/external-aimbot | 035a3dbd114f7e1fba6b78681957b72d15b746e5 | [
"MIT"
] | 11 | 2021-11-27T04:45:59.000Z | 2022-03-08T19:34:29.000Z | main.cpp | cazzwastaken/external-aimbot | 035a3dbd114f7e1fba6b78681957b72d15b746e5 | [
"MIT"
] | null | null | null | main.cpp | cazzwastaken/external-aimbot | 035a3dbd114f7e1fba6b78681957b72d15b746e5 | [
"MIT"
] | 10 | 2021-12-28T22:20:31.000Z | 2022-03-18T17:52:22.000Z | #include "memory.h"
#include "vector.h"
#include <thread>
namespace offset
{
// client
constexpr ::std::ptrdiff_t dwLocalPlayer = 0xDB25DC;
constexpr ::std::ptrdiff_t dwEntityList = 0x4DCDE7C;
// engine
constexpr ::std::ptrdiff_t dwClientState = 0x58CFC4;
constexpr ::std::ptrdiff_t dwClientState_ViewAngles = 0x4D90;
constexpr ::std::ptrdiff_t dwClientState_GetLocalPlayer = 0x180;
// entity
constexpr ::std::ptrdiff_t m_dwBoneMatrix = 0x26A8;
constexpr ::std::ptrdiff_t m_bDormant = 0xED;
constexpr ::std::ptrdiff_t m_iTeamNum = 0xF4;
constexpr ::std::ptrdiff_t m_lifeState = 0x25F;
constexpr ::std::ptrdiff_t m_vecOrigin = 0x138;
constexpr ::std::ptrdiff_t m_vecViewOffset = 0x108;
constexpr ::std::ptrdiff_t m_aimPunchAngle = 0x303C;
constexpr ::std::ptrdiff_t m_bSpottedByMask = 0x980;
}
constexpr Vector3 CalculateAngle(
const Vector3& localPosition,
const Vector3& enemyPosition,
const Vector3& viewAngles) noexcept
{
return ((enemyPosition - localPosition).ToAngle() - viewAngles);
}
int main()
{
// initialize memory class
const auto memory = Memory{ "csgo.exe" };
// module addresses
const auto client = memory.GetModuleAddress("client.dll");
const auto engine = memory.GetModuleAddress("engine.dll");
// infinite hack loop
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// aimbot key
if (!GetAsyncKeyState(VK_RBUTTON))
continue;
// get local player
const auto localPlayer = memory.Read<std::uintptr_t>(client + offset::dwLocalPlayer);
const auto localTeam = memory.Read<std::int32_t>(localPlayer + offset::m_iTeamNum);
// eye position = origin + viewOffset
const auto localEyePosition = memory.Read<Vector3>(localPlayer + offset::m_vecOrigin) +
memory.Read<Vector3>(localPlayer + offset::m_vecViewOffset);
const auto clientState = memory.Read<std::uintptr_t>(engine + offset::dwClientState);
const auto localPlayerId =
memory.Read<std::int32_t>(clientState + offset::dwClientState_GetLocalPlayer);
const auto viewAngles = memory.Read<Vector3>(clientState + offset::dwClientState_ViewAngles);
const auto aimPunch = memory.Read<Vector3>(localPlayer + offset::m_aimPunchAngle) * 2;
// aimbot fov
auto bestFov = 5.f;
auto bestAngle = Vector3{ };
for (auto i = 1; i <= 32; ++i)
{
const auto player = memory.Read<std::uintptr_t>(client + offset::dwEntityList + i * 0x10);
if (memory.Read<std::int32_t>(player + offset::m_iTeamNum) == localTeam)
continue;
if (memory.Read<bool>(player + offset::m_bDormant))
continue;
if (memory.Read<std::int32_t>(player + offset::m_lifeState))
continue;
if (memory.Read<std::int32_t>(player + offset::m_bSpottedByMask) & (1 << localPlayerId))
{
const auto boneMatrix = memory.Read<std::uintptr_t>(player + offset::m_dwBoneMatrix);
// pos of player head in 3d space
// 8 is the head bone index :)
const auto playerHeadPosition = Vector3{
memory.Read<float>(boneMatrix + 0x30 * 8 + 0x0C),
memory.Read<float>(boneMatrix + 0x30 * 8 + 0x1C),
memory.Read<float>(boneMatrix + 0x30 * 8 + 0x2C)
};
const auto angle = CalculateAngle(
localEyePosition,
playerHeadPosition,
viewAngles + aimPunch
);
const auto fov = std::hypot(angle.x, angle.y);
if (fov < bestFov)
{
bestFov = fov;
bestAngle = angle;
}
}
}
// if we have a best angle, do aimbot
if (!bestAngle.IsZero())
memory.Write<Vector3>(clientState + offset::dwClientState_ViewAngles, viewAngles + bestAngle / 3.f); // smoothing
}
return 0;
}
| 30.311475 | 117 | 0.681449 | [
"vector",
"3d"
] |
1ce6b19688a2b67cf56f696f0a0f1855dc7f8a04 | 8,654 | cpp | C++ | src/integrator/surface_integrator.cpp | Twinklebear/tray | eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b | [
"MIT"
] | 61 | 2015-01-01T10:58:21.000Z | 2022-01-05T14:22:15.000Z | src/integrator/surface_integrator.cpp | Twinklebear/tray | eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b | [
"MIT"
] | null | null | null | src/integrator/surface_integrator.cpp | Twinklebear/tray | eeb6dc930a3f81bb2abd74a41a4fb409a0e0865b | [
"MIT"
] | 3 | 2016-04-11T19:07:47.000Z | 2018-05-31T12:40:50.000Z | #include <cassert>
#include <algorithm>
#include <cmath>
#include "scene.h"
#include "monte_carlo/util.h"
#include "monte_carlo/distribution1d.h"
#include "integrator/surface_integrator.h"
void SurfaceIntegrator::preprocess(const Scene&){}
Colorf SurfaceIntegrator::spec_reflect(const RayDifferential &ray, const BSDF &bsdf, const Renderer &renderer,
const Scene &scene, Sampler &sampler, MemoryPool &pool)
{
const Normal &n = bsdf.dg.normal;
const Point &p = bsdf.dg.point;
Vector w_o = -ray.d;
Vector w_i;
float pdf_val = 0;
std::array<float, 2> u_sample;
float c_sample = 0;
sampler.get_samples(&u_sample, 1);
sampler.get_samples(&c_sample, 1);
//Compute the color reflected off the BSDF
Colorf reflected{0};
Colorf f = bsdf.sample(w_o, w_i, u_sample, c_sample, pdf_val,
BxDFTYPE(BxDFTYPE::REFLECTION | BxDFTYPE::SPECULAR));
if (pdf_val > 0 && !f.is_black() && std::abs(w_i.dot(n)) != 0){
RayDifferential refl{p, w_i, ray, 0.001};
if (ray.has_differentials()){
refl.rx = Ray{p + bsdf.dg.dp_dx, w_i, ray, 0.001};
refl.ry = Ray{p + bsdf.dg.dp_dy, w_i, ray, 0.001};
//We compute dn_dx and dn_dy as described in PBR since we're following their differential
//geometry method, the rest of the computation is directly from Igehy's paper
auto dn_dx = Vector{bsdf.dg.dn_du * bsdf.dg.du_dx + bsdf.dg.dn_dv * bsdf.dg.dv_dx};
auto dn_dy = Vector{bsdf.dg.dn_du * bsdf.dg.du_dy + bsdf.dg.dn_dv * bsdf.dg.dv_dy};
auto dd_dx = -ray.rx.d - w_o;
auto dd_dy = -ray.ry.d - w_o;
float ddn_dx = dd_dx.dot(n) + w_o.dot(dn_dx);
float ddn_dy = dd_dy.dot(n) + w_o.dot(dn_dy);
refl.rx.d = w_i - dd_dx + 2 * Vector{w_o.dot(n) * dn_dx + Vector{ddn_dx * n}};
refl.ry.d = w_i - dd_dy + 2 * Vector{w_o.dot(n) * dn_dy + Vector{ddn_dy * n}};
}
Colorf li = renderer.illumination(refl, scene, sampler, pool);
reflected = f * li * std::abs(w_i.dot(n)) / pdf_val;
}
return reflected;
}
Colorf SurfaceIntegrator::spec_transmit(const RayDifferential &ray, const BSDF &bsdf, const Renderer &renderer,
const Scene &scene, Sampler &sampler, MemoryPool &pool)
{
const Normal &n = bsdf.dg.normal;
const Point &p = bsdf.dg.point;
Vector w_o = -ray.d;
Vector w_i;
float pdf_val = 0;
std::array<float, 2> u_sample;
float c_sample;
sampler.get_samples(&u_sample, 1);
sampler.get_samples(&c_sample, 1);
Colorf f = bsdf.sample(w_o, w_i, u_sample, c_sample, pdf_val,
BxDFTYPE(BxDFTYPE::TRANSMISSION | BxDFTYPE::SPECULAR));
//Compute the color transmitted through the BSDF
Colorf transmitted{0};
if (pdf_val > 0 && !f.is_black() && std::abs(w_i.dot(n)) != 0){
RayDifferential refr_ray{p, w_i, ray, 0.001};
if (ray.has_differentials()){
refr_ray.rx = Ray{p + bsdf.dg.dp_dx, w_i, ray, 0.001};
refr_ray.ry = Ray{p + bsdf.dg.dp_dy, w_i, ray, 0.001};
float eta = w_o.dot(n) < 0 ? 1 / bsdf.eta : bsdf.eta;
//We compute dn_dx and dn_dy as described in PBR since we're following their differential
//geometry method, the rest of the computation is directly from Igehy's paper
auto dn_dx = Vector{bsdf.dg.dn_du * bsdf.dg.du_dx + bsdf.dg.dn_dv * bsdf.dg.dv_dx};
auto dn_dy = Vector{bsdf.dg.dn_du * bsdf.dg.du_dy + bsdf.dg.dn_dv * bsdf.dg.dv_dy};
auto dd_dx = -ray.rx.d - w_o;
auto dd_dy = -ray.ry.d - w_o;
float ddn_dx = dd_dx.dot(n) + w_o.dot(dn_dx);
float ddn_dy = dd_dy.dot(n) + w_o.dot(dn_dy);
float mu = eta * ray.d.dot(n) - w_i.dot(n);
float dmu_dx = (eta - eta * eta * ray.d.dot(n) / w_i.dot(n)) * ddn_dx;
float dmu_dy = (eta - eta * eta * ray.d.dot(n) / w_i.dot(n)) * ddn_dy;
refr_ray.rx.d = w_i + eta * dd_dx - Vector{mu * dn_dx + Vector{dmu_dx * n}};
refr_ray.ry.d = w_i + eta * dd_dy - Vector{mu * dn_dy + Vector{dmu_dy * n}};
}
Colorf li = renderer.illumination(refr_ray, scene, sampler, pool);
transmitted = f * li * std::abs(w_i.dot(n)) / pdf_val;
}
return transmitted;
}
Colorf SurfaceIntegrator::uniform_sample_all_lights(const Scene &scene, const Renderer &renderer, const Point &p,
const Normal &n, const Vector &w_o, const BSDF &bsdf, Sampler &sampler, MemoryPool &pool)
{
Colorf illum;
for (const auto &lit : scene.get_light_cache()){
const auto &light = *lit.second;
auto *l_samples_u = pool.alloc_array<std::array<float, 2>>(light.n_samples);
auto *l_samples_comp = pool.alloc_array<float>(light.n_samples);
auto *bsdf_samples_u = pool.alloc_array<std::array<float, 2>>(light.n_samples);
auto *bsdf_samples_comp = pool.alloc_array<float>(light.n_samples);
sampler.get_samples(l_samples_u, light.n_samples);
sampler.get_samples(l_samples_comp, light.n_samples);
sampler.get_samples(bsdf_samples_u, light.n_samples);
sampler.get_samples(bsdf_samples_comp, light.n_samples);
Colorf light_illum;
for (int i = 0; i < light.n_samples; ++i){
BSDFSample bsdf_sample{bsdf_samples_u[i], bsdf_samples_comp[i]};
LightSample l_sample{l_samples_u[i], l_samples_comp[i]};
light_illum += estimate_direct(scene, renderer, p, n, w_o, bsdf, light, l_sample,
bsdf_sample, BxDFTYPE(BxDFTYPE::ALL & ~BxDFTYPE::SPECULAR), sampler, pool);
}
illum += light_illum / light.n_samples;
}
return illum;
}
Colorf SurfaceIntegrator::uniform_sample_one_light(const Scene &scene, const Renderer &renderer, const Point &p,
const Normal &n, const Vector &w_o, const BSDF &bsdf, const LightSample &l_sample, const BSDFSample &bsdf_sample,
Sampler &sampler, MemoryPool &pool)
{
int n_lights = scene.get_light_cache().size();
if (n_lights == 0){
return Colorf{0};
}
int light_num = static_cast<int>(l_sample.light * n_lights);
light_num = std::min(light_num, n_lights - 1);
//The unordered map isn't a random access container, so 'find' the light_num light
auto lit = std::find_if(scene.get_light_cache().begin(), scene.get_light_cache().end(),
[&light_num](const auto&){
return light_num-- == 0;
});
assert(lit != scene.get_light_cache().end());
return n_lights * estimate_direct(scene, renderer, p, n, w_o, bsdf, *lit->second, l_sample,
bsdf_sample, BxDFTYPE(BxDFTYPE::ALL & ~BxDFTYPE::SPECULAR), sampler, pool);
}
Colorf SurfaceIntegrator::estimate_direct(const Scene &scene, const Renderer &renderer, const Point &p,
const Normal &n, const Vector &w_o, const BSDF &bsdf, const Light &light, const LightSample &l_sample,
const BSDFSample &bsdf_sample, BxDFTYPE flags, Sampler &sampler, MemoryPool &pool)
{
//We sample both the light source and the BSDF and weight them accordingly to sample both well
Colorf direct_light;
Vector w_i;
float pdf_light = 0, pdf_bsdf = 0;
OcclusionTester occlusion;
//Sample the light
Colorf li = light.sample(p, l_sample, w_i, pdf_light, occlusion);
if (pdf_light > 0 && !li.is_black()){
Colorf f = bsdf(w_o, w_i, flags);
if (!f.is_black() && !occlusion.occluded(scene)){
li *= occlusion.transmittance(scene, renderer, sampler, pool);
//If we have a delta distribution in the light we don't do MIS as it'd be incorrect
//Otherwise we do MIS using the power heuristic
if (light.delta_light()){
direct_light += f * li * std::abs(w_i.dot(n)) / pdf_light;
}
else {
pdf_bsdf = bsdf.pdf(w_o, w_i, flags);
float w = power_heuristic(1, pdf_light, 1, pdf_bsdf);
direct_light += f * li * std::abs(w_i.dot(n)) * w / pdf_light;
}
}
}
//Sample the BSDF in the same manner as the light
if (!light.delta_light()){
BxDFTYPE sampled_bxdf;
Colorf f = bsdf.sample(w_o, w_i, bsdf_sample.u, bsdf_sample.comp, pdf_bsdf, flags, &sampled_bxdf);
if (pdf_bsdf > 0 && !f.is_black()){
//Handle delta distributions in the BSDF the same way we did for the light
float weight = 1;
if (!(sampled_bxdf & BxDFTYPE::SPECULAR)){
pdf_light = light.pdf(p, w_i);
if (pdf_light == 0){
return direct_light;
}
weight = power_heuristic(1, pdf_bsdf, 1, pdf_light);
}
//Find out if the ray along w_i actually hits the light source
DifferentialGeometry dg;
Colorf li;
RayDifferential ray{p, w_i, 0.001};
if (scene.get_root().intersect(ray, dg)){
if (dg.node->get_area_light() == &light){
li = dg.node->get_area_light()->radiance(dg.point, dg.normal, -w_i);
}
}
if (!li.is_black()){
li *= renderer.transmittance(scene, ray, sampler, pool);
direct_light += f * li * std::abs(w_i.dot(n)) * weight / pdf_bsdf;
}
}
}
return direct_light;
}
Distribution1D SurfaceIntegrator::light_sampling_cdf(const Scene &scene){
std::vector<float> light_power(scene.get_light_cache().size());
std::transform(scene.get_light_cache().begin(), scene.get_light_cache().end(), light_power.begin(),
[&](const auto &l){
return l.second->power(scene).luminance();
});
return Distribution1D{light_power};
}
| 43.054726 | 114 | 0.694708 | [
"geometry",
"vector",
"transform"
] |
1ced85502419bbeedf0bc86f0cf0690d451b6f4f | 4,157 | hpp | C++ | ros2_full_sensor_suite/include/ros2_full_sensor_suite/gazebo_ros_gps.hpp | nikostsagk/botanbot_sim | 7b0c7a0336f04a04ac9c4c963f374a15064077b4 | [
"Apache-2.0"
] | null | null | null | ros2_full_sensor_suite/include/ros2_full_sensor_suite/gazebo_ros_gps.hpp | nikostsagk/botanbot_sim | 7b0c7a0336f04a04ac9c4c963f374a15064077b4 | [
"Apache-2.0"
] | 1 | 2022-03-26T18:21:11.000Z | 2022-03-28T09:31:00.000Z | ros2_full_sensor_suite/include/ros2_full_sensor_suite/gazebo_ros_gps.hpp | nikostsagk/botanbot_sim | 7b0c7a0336f04a04ac9c4c963f374a15064077b4 | [
"Apache-2.0"
] | 1 | 2022-03-25T13:35:02.000Z | 2022-03-25T13:35:02.000Z | //=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// Modification Copyright (c) 2020, Fetullah Atas, Norwegian University of Life Sciences
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Flight Systems and Automatic Control group,
// TU Darmstadt, 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 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.
//=================================================================================================
#ifndef ROS2_FULL_SENSOR_SUITE__GAZEBO_ROS_GPS_HPP_
#define ROS2_FULL_SENSOR_SUITE__GAZEBO_ROS_GPS_HPP_
#include <string>
#include "gazebo/common/Plugin.hh"
#include "gazebo/physics/World.hh"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp/publisher.hpp"
#include "sensor_msgs/msg/nav_sat_fix.hpp"
#include "geometry_msgs/msg/vector3_stamped.hpp"
#include "sensor_model.hpp"
/**
* @brief
*
*/
namespace gazebo
{
/**
* @brief
*
*/
class GazeboRosGps : public ModelPlugin
{
public:
struct GNSSConfig
{
bool STATUS_FIX = true;
bool STATUS_SBAS_FIX = false;
bool STATUS_GBAS_FIX = false;
bool SERVICE_GPS = true;
bool SERVICE_GLONASS = true;
bool SERVICE_COMPASS = true;
bool SERVICE_GALILEO = true;
};
/**
* @brief Construct a new Gazebo Ros Gps object
*
*/
GazeboRosGps();
/**
* @brief Destroy the Gazebo Ros Gps object
*
*/
virtual ~GazeboRosGps();
protected:
virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf);
virtual void Reset();
virtual void OnUpdate();
/*void dynamicReconfigureCallback(GazeboRosGps::GNSSConfig & config, uint32_t level);*/
private:
gazebo::physics::WorldPtr world_;
gazebo::physics::LinkPtr link_;
gazebo::SensorModel3 position_error_model_;
gazebo::SensorModel3 velocity_error_model_;
rclcpp::Node::SharedPtr node_;
rclcpp::Publisher<sensor_msgs::msg::NavSatFix>::SharedPtr fix_publisher_;
rclcpp::Publisher<geometry_msgs::msg::Vector3Stamped>::SharedPtr velocity_publisher_;
sensor_msgs::msg::NavSatFix fix_;
geometry_msgs::msg::Vector3Stamped velocity_;
std::string namespace_;
std::string link_name_;
std::string frame_id_;
std::string fix_topic_;
std::string velocity_topic_;
double reference_latitude_;
double reference_longitude_;
double reference_heading_;
double reference_altitude_;
double radius_north_;
double radius_east_;
// UpdateTimer updateTimer;
gazebo::event::ConnectionPtr updateConnection_;
// Last update time.
gazebo::common::Time last_update_time_;
};
} // namespace gazebo
#endif // ROS2_FULL_SENSOR_SUITE__GAZEBO_ROS_GPS_HPP_
| 34.355372 | 99 | 0.696416 | [
"object"
] |
1cee589aafc5ff0874b1d4839690754c8a80b18d | 38,187 | cc | C++ | db/version_set.cc | hidva/rocksdb | 9dca27383742ce6634c2ab42f945ad0ab9982849 | [
"BSD-3-Clause"
] | 2 | 2018-12-06T06:39:09.000Z | 2020-11-24T02:23:57.000Z | db/version_set.cc | hidva/rocksdb | 9dca27383742ce6634c2ab42f945ad0ab9982849 | [
"BSD-3-Clause"
] | null | null | null | db/version_set.cc | hidva/rocksdb | 9dca27383742ce6634c2ab42f945ad0ab9982849 | [
"BSD-3-Clause"
] | 1 | 2022-02-22T02:51:43.000Z | 2022-02-22T02:51:43.000Z | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/version_set.h"
#include <algorithm>
#include <stdio.h>
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/table_cache.h"
#include "include/env.h"
#include "include/table_builder.h"
#include "table/merger.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
#include "util/logging.h"
namespace leveldb {
// 为啥不用查表法, 省得每次计算了.
static double MaxBytesForLevel(int level) {
if (level == 0) {
return 4 * 1048576.0;
} else {
double result = 10 * 1048576.0;
while (level > 1) {
result *= 10;
level--;
}
return result;
}
}
// 返回 level 层 table file 的最大长度, 默认是固定的 2MB.
static uint64_t MaxFileSizeForLevel(int level) {
return 2 << 20; // We could vary per level to reduce number of files?
// 我也觉得 level 越大是不是这个值也可以适当调大点?
}
namespace {
std::string IntSetToString(const std::set<uint64_t>& s) {
std::string result = "{";
for (std::set<uint64_t>::const_iterator it = s.begin();
it != s.end();
++it) {
result += (result.size() > 1) ? "," : "";
result += NumberToString(*it);
}
result += "}";
return result;
}
}
Version::~Version() {
assert(refs_ == 0);
for (int level = 0; level < config::kNumLevels; level++) {
for (int i = 0; i < files_[level].size(); i++) {
FileMetaData* f = files_[level][i];
assert(f->refs >= 0);
f->refs--;
if (f->refs <= 0) {
delete f;
}
}
}
delete cleanup_mem_;
}
// An internal iterator. For a given version/level pair, yields
// information about the files in the level. For a given entry, key()
// is the largest key that occurs in the file, and value() is an
// 8-byte value containing the file number of the file, encoding using
// EncodeFixed64.
/*
* LevelFileNumIterator, 在了解 LevelFileNumIterator 之前首先了解一下 flist_ 是啥, flist_ 是某一 level 下
* 若干 table 文件的集合, 如 flist_ 可能是 version->files_[level], flist_ 中的文件按照 largest key 从小到大
* 排序. 所以 flist_ 像极了 table file 的 index block. LevelFileNumIterator 就是对 flist_ 的迭代,
* iter->Key() 是 largest key, iter->Value() 是 file number of the file.
*/
class Version::LevelFileNumIterator : public Iterator {
public:
LevelFileNumIterator(const Version* version,
const std::vector<FileMetaData*>* flist)
: icmp_(version->vset_->icmp_.user_comparator()), // 为啥不写成 icmp_(version->vset_->icmp) 呢?
flist_(flist),
index_(flist->size()) { // Marks as invalid
}
virtual bool Valid() const {
return index_ < flist_->size();
}
virtual void Seek(const Slice& target) {
uint32_t left = 0;
uint32_t right = flist_->size() - 1;
while (left < right) {
uint32_t mid = (left + right) / 2;
int cmp = icmp_.Compare((*flist_)[mid]->largest.Encode(), target);
if (cmp < 0) {
// Key at "mid.largest" is < than "target". Therefore all
// files at or before "mid" are uninteresting.
left = mid + 1;
} else {
// Key at "mid.largest" is >= "target". Therefore all files
// after "mid" are uninteresting.
right = mid;
}
}
index_ = left;
}
virtual void SeekToFirst() { index_ = 0; }
virtual void SeekToLast() {
index_ = flist_->empty() ? 0 : flist_->size() - 1;
}
virtual void Next() {
assert(Valid());
index_++;
}
virtual void Prev() {
assert(Valid());
if (index_ == 0) {
index_ = flist_->size(); // Marks as invalid
} else {
index_--;
}
}
Slice key() const {
assert(Valid());
return (*flist_)[index_]->largest.Encode();
}
Slice value() const {
assert(Valid());
EncodeFixed64(value_buf_, (*flist_)[index_]->number);
return Slice(value_buf_, sizeof(value_buf_));
}
virtual Status status() const { return Status::OK(); }
private:
const InternalKeyComparator icmp_;
const std::vector<FileMetaData*>* const flist_;
int index_; // 当前在 flist_ 中的位置.
mutable char value_buf_[8]; // Used for encoding the file number for value()
};
// 参见该函数的使用场景 NewConcatenatingIterator().
static Iterator* GetFileIterator(void* arg,
const ReadOptions& options,
const Slice& file_value) {
TableCache* cache = reinterpret_cast<TableCache*>(arg);
if (file_value.size() != 8) {
return NewErrorIterator(
Status::Corruption("FileReader invoked with unexpected value"));
} else {
return cache->NewIterator(options, DecodeFixed64(file_value.data()));
}
}
Iterator* Version::NewConcatenatingIterator(const ReadOptions& options,
int level) const {
return NewTwoLevelIterator(
new LevelFileNumIterator(this, &files_[level]),
&GetFileIterator, vset_->table_cache_, options);
}
void Version::AddIterators(const ReadOptions& options,
std::vector<Iterator*>* iters) {
// Merge all level zero files together since they may overlap
for (int i = 0; i < files_[0].size(); i++) {
iters->push_back(
vset_->table_cache_->NewIterator(options, files_[0][i]->number));
}
// For levels > 0, we can use a concatenating iterator that sequentially
// walks through the non-overlapping files in the level, opening them
// lazily.
for (int level = 1; level < config::kNumLevels; level++) {
if (!files_[level].empty()) {
iters->push_back(NewConcatenatingIterator(options, level));
}
}
}
void Version::Ref() {
++refs_;
}
void Version::Unref() {
assert(refs_ >= 1);
--refs_;
if (refs_ == 0) {
vset_->MaybeDeleteOldVersions();
// TODO: try to delete obsolete files
}
}
std::string Version::DebugString() const {
std::string r;
for (int level = 0; level < config::kNumLevels; level++) {
// E.g., level 1: 17:123['a' .. 'd'] 20:43['e' .. 'g']
r.append("level ");
AppendNumberTo(&r, level);
r.push_back(':');
const std::vector<FileMetaData*>& files = files_[level];
for (int i = 0; i < files.size(); i++) {
r.push_back(' ');
AppendNumberTo(&r, files[i]->number);
r.push_back(':');
AppendNumberTo(&r, files[i]->file_size);
r.append("['");
AppendEscapedStringTo(&r, files[i]->smallest.Encode());
r.append("' .. '");
AppendEscapedStringTo(&r, files[i]->largest.Encode());
r.append("']");
}
r.push_back('\n');
}
return r;
}
// A helper class so we can efficiently apply a whole sequence
// of edits to a particular state without creating intermediate
// Versions that contain full copies of the intermediate state.
/* 按我理解, 如果没有 Builder, 那么 apply a whole sequence of edits 的过程:
* version0 经过 apply edit 0 变成 version1 经过 apply edit 1 变成 version2 ...
* 在使用 Builder 之后:
* Builder(version0) apply edit 0, apply edit 1, ... , Builder.SaveTo(versionN);
* 即省了中间 Version 的创建.
*/
class VersionSet::Builder {
private:
// <<file number, FileMetaData>>; 这里之所以不使用 std::vector<FileMetaData*> 原因参见 Apply(),
// 在 apply delete file 更改时, 使用 std::map 更有效率.
typedef std::map<uint64_t, FileMetaData*> FileMap;
VersionSet* vset_;
FileMap files_[config::kNumLevels];
public:
// Initialize a builder with the files from *base and other info from *vset
Builder(VersionSet* vset, Version* base)
: vset_(vset) {
for (int level = 0; level < config::kNumLevels; level++) {
const std::vector<FileMetaData*>& files = base->files_[level];
for (int i = 0; i < files.size(); i++) {
FileMetaData* f = files[i];
f->refs++;
files_[level].insert(std::make_pair(f->number, f));
}
}
}
~Builder() {
for (int level = 0; level < config::kNumLevels; level++) {
const FileMap& fmap = files_[level];
for (FileMap::const_iterator iter = fmap.begin();
iter != fmap.end();
++iter) {
FileMetaData* f = iter->second;
f->refs--;
if (f->refs <= 0) {
delete f;
}
}
}
}
// Apply all of the edits in *edit to the current state.
// all of the edits in *edit 是指 edit 这个 VersionEdit 对象中所存放着的所有更改操作, 但根据实现可以看出
// 这里并没有 apply all of the edits in *edit.
// 这里 edit 应该是经过 normalize 之后的, 即如果原生 edit 包含了: 新增 file number 为 5, 7 的文件, 删除
// file number 为 5, 6 的文件; 那么 normalize 之后 edit 包含了: 新增 file number 为 7 的文件, 删除 file
// numberi 为 6 的文件.
void Apply(VersionEdit* edit) {
// Update compaction pointers
for (int i = 0; i < edit->compact_pointers_.size(); i++) {
const int level = edit->compact_pointers_[i].first;
vset_->compact_pointer_[level] =
edit->compact_pointers_[i].second.Encode().ToString();
}
// Delete files
const VersionEdit::DeletedFileSet& del = edit->deleted_files_;
for (VersionEdit::DeletedFileSet::const_iterator iter = del.begin();
iter != del.end();
++iter) {
const int level = iter->first;
const uint64_t number = iter->second;
FileMap::iterator fiter = files_[level].find(number);
// 既然此时 edit 中包含了对 file number 为 N 的删除操作, 那么很显然表明当前存活着的 files 中肯定有
// file number 为 N 的文件.
assert(fiter != files_[level].end()); // Sanity check for debug mode
if (fiter != files_[level].end()) {
FileMetaData* f = fiter->second;
f->refs--;
if (f->refs <= 0) {
delete f;
}
files_[level].erase(fiter);
}
}
// Add new files
for (int i = 0; i < edit->new_files_.size(); i++) {
const int level = edit->new_files_[i].first;
FileMetaData* f = new FileMetaData(edit->new_files_[i].second);
f->refs = 1;
assert(files_[level].count(f->number) == 0);
files_[level].insert(std::make_pair(f->number, f));
}
// Add large value refs
for (int i = 0; i < edit->large_refs_added_.size(); i++) {
const VersionEdit::Large& l = edit->large_refs_added_[i];
vset_->RegisterLargeValueRef(l.large_ref, l.fnum, l.internal_key);
}
}
// Save the current state in *v.
void SaveTo(Version* v) {
for (int level = 0; level < config::kNumLevels; level++) {
const FileMap& fmap = files_[level];
for (FileMap::const_iterator iter = fmap.begin();
iter != fmap.end();
++iter) {
FileMetaData* f = iter->second;
f->refs++;
v->files_[level].push_back(f);
}
}
}
};
VersionSet::VersionSet(const std::string& dbname,
const Options* options,
TableCache* table_cache,
const InternalKeyComparator* cmp)
: env_(options->env),
dbname_(dbname),
options_(options),
table_cache_(table_cache),
icmp_(*cmp),
next_file_number_(2), // Filled by Recover()
manifest_file_number_(0), // Filled by Recover()
descriptor_file_(NULL),
descriptor_log_(NULL),
current_(new Version(this)),
oldest_(current_) {
}
VersionSet::~VersionSet() {
for (Version* v = oldest_; v != NULL; ) {
Version* next = v->next_;
assert(v->refs_ == 0);
delete v;
v = next;
}
delete descriptor_log_;
delete descriptor_file_;
}
Status VersionSet::LogAndApply(VersionEdit* edit, MemTable* cleanup_mem) {
/*
// 我脑补的 LogAndApply() 实现.
std::string new_manifest_file;
edit->SetNextFile(next_file_number_);
// 1. 首先将更改持久化到持久性存储中.
// Initialize new descriptor log file if necessary by creating
// a temporary file that contains a snapshot of the current version.
if (s.ok()) {
if (descriptor_log_ == NULL) {
assert(descriptor_file_ == NULL);
new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
if (s.ok()) {
descriptor_log_ = new log::Writer(descriptor_file_);
s = WriteSnapshot(descriptor_log_);
}
}
}
// Write new record to log file
if (s.ok()) {
std::string record;
edit->EncodeTo(&record);
s = descriptor_log_->AddRecord(record);
if (s.ok()) {
s = descriptor_file_->Sync();
}
}
// If we just created a new descriptor file, install it by writing a
// new CURRENT file that points to it.
if (s.ok() && !new_manifest_file.empty()) {
s = SetCurrentFile(env_, dbname_, manifest_file_number_);
}
// 2. 再将更改应用到内存中.
Version* v = new Version(this);
{
Builder builder(this, current_);
builder.Apply(edit);
builder.SaveTo(v);
}
Status s = Finalize(v);
// Install the new version
if (s.ok()) {
assert(current_->next_ == NULL);
assert(current_->cleanup_mem_ == NULL);
current_->cleanup_mem_ = cleanup_mem;
v->next_ = NULL;
current_->next_ = v;
current_ = v;
} else {
delete v;
if (!new_manifest_file.empty()) {
delete descriptor_log_;
delete descriptor_file_;
descriptor_log_ = NULL;
descriptor_file_ = NULL;
env_->DeleteFile(new_manifest_file);
}
}
//Log(env_, options_->info_log, "State\n%s", current_->DebugString().c_str());
return s;
*/
edit->SetNextFile(next_file_number_);
Version* v = new Version(this);
{
Builder builder(this, current_);
builder.Apply(edit);
builder.SaveTo(v);
}
std::string new_manifest_file;
Status s = Finalize(v);
// Initialize new descriptor log file if necessary by creating
// a temporary file that contains a snapshot of the current version.
if (s.ok()) {
if (descriptor_log_ == NULL) {
assert(descriptor_file_ == NULL);
new_manifest_file = DescriptorFileName(dbname_, manifest_file_number_);
edit->SetNextFile(next_file_number_);
s = env_->NewWritableFile(new_manifest_file, &descriptor_file_);
if (s.ok()) {
descriptor_log_ = new log::Writer(descriptor_file_);
s = WriteSnapshot(descriptor_log_);
}
}
}
// Write new record to log file
if (s.ok()) {
std::string record;
edit->EncodeTo(&record);
s = descriptor_log_->AddRecord(record);
if (s.ok()) {
s = descriptor_file_->Sync();
}
}
// If we just created a new descriptor file, install it by writing a
// new CURRENT file that points to it.
if (s.ok() && !new_manifest_file.empty()) {
s = SetCurrentFile(env_, dbname_, manifest_file_number_);
}
// Install the new version
if (s.ok()) {
assert(current_->next_ == NULL);
assert(current_->cleanup_mem_ == NULL);
current_->cleanup_mem_ = cleanup_mem;
v->next_ = NULL;
current_->next_ = v;
current_ = v;
} else {
delete v;
if (!new_manifest_file.empty()) {
delete descriptor_log_;
delete descriptor_file_;
descriptor_log_ = NULL;
descriptor_file_ = NULL;
env_->DeleteFile(new_manifest_file);
}
}
//Log(env_, options_->info_log, "State\n%s", current_->DebugString().c_str());
return s;
}
Status VersionSet::Recover(uint64_t* log_number,
SequenceNumber* last_sequence) {
struct LogReporter : public log::Reader::Reporter {
Status* status;
virtual void Corruption(size_t bytes, const Status& s) {
if (this->status->ok()) *this->status = s;
}
};
// Read "CURRENT" file, which contains a pointer to the current manifest file
std::string current;
Status s = ReadFileToString(env_, CurrentFileName(dbname_), ¤t);
if (!s.ok()) {
return s;
}
if (current.empty() || current[current.size()-1] != '\n') {
// 这么严格==
return Status::Corruption("CURRENT file does not end with newline");
}
current.resize(current.size() - 1);
std::string dscname = dbname_ + "/" + current;
SequentialFile* file;
s = env_->NewSequentialFile(dscname, &file);
if (!s.ok()) {
return s;
}
bool have_log_number = false;
bool have_next_file = false;
bool have_last_sequence = false;
uint64_t next_file = 0;
Builder builder(this, current_);
{
LogReporter reporter;
reporter.status = &s;
// checksum 为 true 为啥不根据 option 计算出来?
log::Reader reader(file, &reporter, true/*checksum*/);
Slice record;
std::string scratch;
while (reader.ReadRecord(&record, &scratch) && s.ok()) {
VersionEdit edit;
s = edit.DecodeFrom(record);
if (s.ok()) {
if (edit.has_comparator_ &&
edit.comparator_ != icmp_.user_comparator()->Name()) {
s = Status::InvalidArgument(
edit.comparator_ + "does not match existing comparator ",
icmp_.user_comparator()->Name());
}
}
if (s.ok()) {
builder.Apply(&edit);
}
if (edit.has_log_number_) {
*log_number = edit.log_number_;
have_log_number = true;
}
if (edit.has_next_file_number_) {
next_file = edit.next_file_number_;
have_next_file = true;
}
if (edit.has_last_sequence_) {
*last_sequence = edit.last_sequence_;
have_last_sequence = true;
}
}
}
delete file;
file = NULL;
if (s.ok()) {
if (!have_next_file) {
s = Status::Corruption("no meta-nextfile entry in descriptor");
} else if (!have_log_number) {
s = Status::Corruption("no meta-lognumber entry in descriptor");
} else if (!have_last_sequence) {
s = Status::Corruption("no last-sequence-number entry in descriptor");
}
}
if (s.ok()) {
Version* v = new Version(this);
builder.SaveTo(v);
s = Finalize(v);
if (!s.ok()) {
delete v;
} else {
// Install recovered version
v->next_ = NULL;
current_->next_ = v;
current_ = v;
manifest_file_number_ = next_file;
next_file_number_ = next_file + 1; // 不加 1 也可以的吧?
}
}
return s;
}
Status VersionSet::Finalize(Version* v) {
// Precomputed best level for next compaction
int best_level = -1;
double best_score = -1;
Status s;
for (int level = 0; s.ok() && level < config::kNumLevels; level++) {
s = SortLevel(v, level);
// Compute the ratio of current size to size limit.
uint64_t level_bytes = 0;
for (int i = 0; i < v->files_[level].size(); i++) {
level_bytes += v->files_[level][i]->file_size;
}
double score = static_cast<double>(level_bytes) / MaxBytesForLevel(level);
if (level == 0) {
// Level-0 file sizes are going to be often much smaller than
// MaxBytesForLevel(0) since we do not account for compression
// when producing a level-0 file; and too many level-0 files
// increase merging costs. So use a file-count limit for
// level-0 in addition to the byte-count limit.
//
// 当 leveldb 检测到内存中的 memtable 在未压缩的情况下达到 1mb 时, 就会将 memtable 压缩序列化到
// 某个 level0 文件中, 所以此时该 level0 文件大小要比 1mb 要少. 所以说 Level-0 file sizes are going
// to be often much smaller than ...
//
// too many level-0 files increase merging costs. 按我理解, 根据程序局部性原理, 大多数读取操作将落在
// 内存中的 memtable 或者 level 0 中, 如果 level 0 文件数目过多, 那么很显然将导致这些读取操作延迟增加.
// 毕竟当读取操作落在 level 0 文件中时, 会不得不遍历相当多 level 0 文件来查找结果.
double count_score = v->files_[level].size() / 4.0;
if (count_score > score) {
score = count_score;
}
// 本来我想的是当 level 0 文件数目达到或者超过 4 之后, 就将 score 置为无穷大, 即此时首先 compact level
// 0. 原文实现的较为温和.
}
if (score > best_score) {
best_level = level;
best_score = score;
}
}
v->compaction_level_ = best_level;
v->compaction_score_ = best_score;
return s;
}
Status VersionSet::WriteSnapshot(log::Writer* log) {
// TODO: Break up into multiple records to reduce memory usage on recovery?
// Save metadata
VersionEdit edit;
edit.SetComparatorName(icmp_.user_comparator()->Name());
// Save compaction pointers
for (int level = 0; level < config::kNumLevels; level++) {
if (!compact_pointer_[level].empty()) {
InternalKey key;
key.DecodeFrom(compact_pointer_[level]);
edit.SetCompactPointer(level, key);
}
}
// Save files
for (int level = 0; level < config::kNumLevels; level++) {
const std::vector<FileMetaData*>& files = current_->files_[level];
for (int i = 0; i < files.size(); i++) {
const FileMetaData* f = files[i];
edit.AddFile(level, f->number, f->file_size, f->smallest, f->largest);
}
}
// Save large value refs
for (LargeValueMap::const_iterator it = large_value_refs_.begin();
it != large_value_refs_.end();
++it) {
const LargeValueRef& ref = it->first;
const LargeReferencesSet& pointers = it->second;
for (LargeReferencesSet::const_iterator j = pointers.begin();
j != pointers.end();
++j) {
edit.AddLargeValueRef(ref, j->first, j->second);
}
}
std::string record;
edit.EncodeTo(&record);
return log->AddRecord(record);
}
// Helper to sort by tables_[file_number].smallest
struct VersionSet::BySmallestKey {
const InternalKeyComparator* internal_comparator;
bool operator()(FileMetaData* f1, FileMetaData* f2) const {
return internal_comparator->Compare(f1->smallest, f2->smallest) < 0;
}
};
Status VersionSet::SortLevel(Version* v, uint64_t level) {
Status result;
BySmallestKey cmp;
cmp.internal_comparator = &icmp_;
std::sort(v->files_[level].begin(), v->files_[level].end(), cmp);
// 把这段对 level 合法性检查操作放在一个 CheckLevelValid() 之类的函数是不是更为合适.
if (result.ok() && level > 0) {
// There should be no overlap
for (int i = 1; i < v->files_[level].size(); i++) {
const InternalKey& prev_end = v->files_[level][i-1]->largest;
const InternalKey& this_begin = v->files_[level][i]->smallest;
if (icmp_.Compare(prev_end, this_begin) >= 0) {
result = Status::Corruption(
"overlapping ranges in same level",
(EscapeString(prev_end.Encode()) + " vs. " +
EscapeString(this_begin.Encode())));
break;
}
}
}
return result;
}
int VersionSet::NumLevelFiles(int level) const {
assert(level >= 0);
assert(level < config::kNumLevels);
return current_->files_[level].size();
}
uint64_t VersionSet::ApproximateOffsetOf(Version* v, const InternalKey& ikey) {
uint64_t result = 0;
for (int level = 0; level < config::kNumLevels; level++) {
const std::vector<FileMetaData*>& files = v->files_[level];
for (int i = 0; i < files.size(); i++) {
if (icmp_.Compare(files[i]->largest, ikey) <= 0) {
// Entire file is before "ikey", so just add the file size
result += files[i]->file_size;
} else if (icmp_.Compare(files[i]->smallest, ikey) > 0) {
// Entire file is after "ikey", so ignore
// 可以证明, 当 level == 0 时, 这里也可以 break. 不过或许是此时 v level 0 并未使用 SortLevel() 排序.
if (level > 0) {
// Files other than level 0 are sorted by meta->smallest, so
// no further files in this level will contain data for
// "ikey".
break;
}
} else {
// "ikey" falls in the range for this table. Add the
// approximate offset of "ikey" within the table.
Table* tableptr;
Iterator* iter = table_cache_->NewIterator(
ReadOptions(), files[i]->number, &tableptr);
if (tableptr != NULL) {
result += tableptr->ApproximateOffsetOf(ikey.Encode());
} // 话说不应该有 tableptr == NULL 的情况吧.
delete iter;
}
}
}
// 明明都是 Approximate 了, 为啥还这么精细. 不过话说回来了我一开始还真没有想到还要加上 large value size.
// Add in large value files which are references from internal keys
// stored in the table files
//
// TODO(opt): this is O(# large values in db). If this becomes too slow,
// we could store an auxiliary data structure indexed by internal key.
// 所以这个 data structure 是 map<internal key, large value ref> 么?
for (LargeValueMap::const_iterator it = large_value_refs_.begin();
it != large_value_refs_.end();
++it) {
const LargeValueRef& lref = it->first;
for (LargeReferencesSet::const_iterator it2 = it->second.begin();
it2 != it->second.end();
++it2) {
if (icmp_.Compare(it2->second, ikey.Encode()) <= 0) {
// Internal key for large value is before our key of interest
result += lref.ValueSize();
}
}
}
return result;
}
bool VersionSet::RegisterLargeValueRef(const LargeValueRef& large_ref,
uint64_t fnum,
const InternalKey& internal_key) {
LargeReferencesSet* refs = &large_value_refs_[large_ref];
bool is_first = refs->empty();
refs->insert(make_pair(fnum, internal_key.Encode().ToString()));
return is_first;
}
void VersionSet::CleanupLargeValueRefs(const std::set<uint64_t>& live_tables,
uint64_t log_file_num) {
for (LargeValueMap::iterator it = large_value_refs_.begin();
it != large_value_refs_.end();
) {
LargeReferencesSet* refs = &it->second;
for (LargeReferencesSet::iterator ref_it = refs->begin();
ref_it != refs->end();
) {
if (ref_it->first != log_file_num && // Not in log file
live_tables.count(ref_it->first) == 0) { // Not in a live table
// No longer live: erase
LargeReferencesSet::iterator to_erase = ref_it;
++ref_it;
refs->erase(to_erase);
} else {
// Still live: leave this reference alone
++ref_it;
}
}
if (refs->empty()) {
// No longer any live references to this large value: remove from
// large_value_refs
Log(env_, options_->info_log, "large value is dead: '%s'",
LargeValueRefToFilenameString(it->first).c_str());
LargeValueMap::iterator to_erase = it;
++it;
large_value_refs_.erase(to_erase);
} else {
++it;
}
}
}
bool VersionSet::LargeValueIsLive(const LargeValueRef& large_ref) {
LargeValueMap::iterator it = large_value_refs_.find(large_ref);
if (it == large_value_refs_.end()) {
return false;
} else {
assert(!it->second.empty());
return true;
}
}
void VersionSet::MaybeDeleteOldVersions() {
// Note: it is important to delete versions in order since a newer
// version with zero refs may be holding a pointer to a memtable
// that is used by somebody who has a ref on an older version.
// QA: 不理解为啥会有这样的局面?
// A: 参见 dbimpl versions_ 的文档说明, 一个读线程在读取的时候会持有 current version 的引用, 同时还会读取
// dbimpl 中的 memtable; 此时另外一个写线程可能会执行 CompactMemTable() 操作, 生成一个新 version, 并将
// dbimpl 中的 memtable 作为新 version 的 cleanup mem.
while (oldest_ != current_ && oldest_->refs_ == 0) {
Version* next = oldest_->next_;
delete oldest_;
oldest_ = next;
}
}
void VersionSet::AddLiveFiles(std::set<uint64_t>* live) {
// any live version? 我本来以为会首先 MaybeDeleteOldVersions() 一次呢
for (Version* v = oldest_; v != NULL; v = v->next_) {
for (int level = 0; level < config::kNumLevels; level++) {
const std::vector<FileMetaData*>& files = v->files_[level];
for (int i = 0; i < files.size(); i++) {
live->insert(files[i]->number);
}
}
}
}
// Store in "*inputs" all files in "level" that overlap [begin,end]
void VersionSet::GetOverlappingInputs(
int level,
const InternalKey& begin,
const InternalKey& end,
std::vector<FileMetaData*>* inputs) {
inputs->clear();
/*
* QA: 忽然想到此时没有考虑 sequence number, 所以在 compact 时, 相同 key 之下只会保留最新的 key, 那么如果
* 使用老的 shapshot 是不是就读取不到 key 的存在了? 若 key#2, key#1 经过 compact 之后只剩下 key#2, 那么
* 使用 sequence=1 的 shapshot 读取的时候是不是就读取不到 key 了.
* 难道是从 old version 中读取? 老 snapshot 依赖着 old version, 所以 snapshot alive, old version 就
* alive.
* A: 参见 DoCompactionWork 中的 smallest_snapshot.
*/
Slice user_begin = begin.user_key();
Slice user_end = end.user_key();
const Comparator* user_cmp = icmp_.user_comparator();
for (int i = 0; i < current_->files_[level].size(); i++) {
FileMetaData* f = current_->files_[level][i];
if (user_cmp->Compare(f->largest.user_key(), user_begin) < 0 ||
user_cmp->Compare(f->smallest.user_key(), user_end) > 0) {
// Either completely before or after range; skip it
} else {
inputs->push_back(f);
}
}
}
// Stores the minimal range that covers all entries in inputs in
// *smallest, *largest. 被 minimal range 唬住了, 直接说 range 不就得了.
// REQUIRES: inputs is not empty
void VersionSet::GetRange(const std::vector<FileMetaData*>& inputs,
InternalKey* smallest,
InternalKey* largest) {
assert(!inputs.empty());
smallest->Clear();
largest->Clear();
for (int i = 0; i < inputs.size(); i++) {
FileMetaData* f = inputs[i];
if (i == 0) { // 放到外面岂不是可以避免每次循环体内执行 if 语句.
*smallest = f->smallest;
*largest = f->largest;
} else {
if (icmp_.Compare(f->smallest, *smallest) < 0) {
*smallest = f->smallest;
}
if (icmp_.Compare(f->largest, *largest) > 0) {
*largest = f->largest;
}
}
}
}
Iterator* VersionSet::MakeInputIterator(Compaction* c) {
ReadOptions options;
// 本来按照我的理解, paranoid_checks 为 true 时意味着 verify_checksums 总是为 true.
// 但有的地方 paranoid_checks 的值就不影响 verify_checksums, 有的地方则是影响.
options.verify_checksums = options_->paranoid_checks;
options.fill_cache = false;
// Level-0 files have to be merged together. For other levels,
// we will make a concatenating iterator per level.
// TODO(opt): use concatenating iterator for level-0 if there is no overlap
// 和我想的一样, 仅当 c->level() == 0 && which == 0 时才可能会 overlap, 其他情况下绝不会 overlap, 即可以
// 使用 LevelFileNumIterator, NewTwoLevelIterator.
const int space = (c->level() == 0 ? c->inputs_[0].size() + 1 : 2);
Iterator** list = new Iterator*[space]; // 为啥不使用 vector.
int num = 0;
for (int which = 0; which < 2; which++) {
if (!c->inputs_[which].empty()) {
if (c->level() + which == 0) {
const std::vector<FileMetaData*>& files = c->inputs_[which];
for (int i = 0; i < files.size(); i++) {
list[num++] = table_cache_->NewIterator(options, files[i]->number);
}
} else {
// Create concatenating iterator for the files from this level
list[num++] = NewTwoLevelIterator(
new Version::LevelFileNumIterator(
c->input_version_, &c->inputs_[which]),
&GetFileIterator, table_cache_, options);
}
}
}
assert(num <= space);
Iterator* result = NewMergingIterator(&icmp_, list, num);
delete[] list;
return result;
}
Compaction* VersionSet::PickCompaction() {
if (!NeedsCompaction()) {
return NULL;
}
const int level = current_->compaction_level_;
assert(level >= 0);
Compaction* c = new Compaction(level);
c->input_version_ = current_;
c->input_version_->Ref();
// Pick the first file that comes after compact_pointer_[level]
for (int i = 0; i < current_->files_[level].size(); i++) {
FileMetaData* f = current_->files_[level][i];
if (compact_pointer_[level].empty() ||
// QA: compact_pointer_ 是如何更新的? 为啥选择 f->largest 来比较, 而不是 smallest?
// A: compact_pointer_ 如何更新, 见下. 按我理解这里也可以使用 f->smallest 来更新, 因为可以根据
// 下面的代码流程结合反证法证明出:
// 不会存在 f, 使得 compact_pointer_[level] 落在 f.smallest, f.largest 之间.
// 所以可以得出当 f.largest > compact_pointer[level] 时, f.smallest 也大于 compact ponter level.
icmp_.Compare(f->largest.Encode(), compact_pointer_[level]) > 0) {
c->inputs_[0].push_back(f);
break;
}
}
if (c->inputs_[0].empty()) {
// Wrap-around to the beginning of the key space
c->inputs_[0].push_back(current_->files_[level][0]);
}
// Find the range we are compacting
InternalKey smallest, largest;
GetRange(c->inputs_[0], &smallest, &largest);
// Files in level 0 may overlap each other, so pick up all overlapping ones
if (level == 0) {
// Note that the next call will discard the file we placed in
// c->inputs_[0] earlier and replace it with an overlapping set
// which will include the picked file.
GetOverlappingInputs(0, smallest, largest, &c->inputs_[0]);
assert(!c->inputs_[0].empty());
GetRange(c->inputs_[0], &smallest, &largest);
// 本来我以为 level 0 直接把 level 0 的所有文件都作为 inputs_[0] 内.
}
GetOverlappingInputs(level+1, smallest, largest, &c->inputs_[1]);
// See if we can grow the number of inputs in "level" without
// changing the number of "level+1" files we pick up.
// 就是在 inputs_[1] 大小不变的基础上, 尽可能多地往 inputs_[0] 中塞入数据, 大概是想提高 compact 效果吧.
// 这里是不是可以作为一个无限循环? 在 expanded0 == inputs[0] 或者 expanded1.size() > inputs[1].size()
// 时才退出. 让效果最大化嘛.
if (!c->inputs_[1].empty()) {
// Get entire range covered by compaction
// 按我理解 GetRange(c->inputs_[1]) 包括了 [smallest, largest], 所以这里:
// [all_start, all_limit] 等于 GetRange(c->inputs_[1]).
std::vector<FileMetaData*> all = c->inputs_[0];
all.insert(all.end(), c->inputs_[1].begin(), c->inputs_[1].end());
InternalKey all_start, all_limit;
GetRange(all, &all_start, &all_limit);
std::vector<FileMetaData*> expanded0;
GetOverlappingInputs(level, all_start, all_limit, &expanded0);
// 此时 expanded0.size() >= inputs[0].size(), 并且当 expanded0.size() == inputs[0].size() 时,
// expanded0 == inputs[0]. 这是因为 [allstart, alllimit] 包括了 [smallest, largest], 所以
// inputs[0] 是 expanded0 的子集.
if (expanded0.size() > c->inputs_[0].size()) {
InternalKey new_start, new_limit;
GetRange(expanded0, &new_start, &new_limit);
std::vector<FileMetaData*> expanded1;
GetOverlappingInputs(level+1, new_start, new_limit, &expanded1);
// 同样此时 inputs[1] 是 expanded1 的子集.
if (expanded1.size() == c->inputs_[1].size()) {
Log(env_, options_->info_log,
"Expanding@%d %d+%d to %d+%d\n",
level,
int(c->inputs_[0].size()),
int(c->inputs_[1].size()),
int(expanded0.size()),
int(expanded1.size()));
smallest = new_start;
largest = new_limit;
c->inputs_[0] = expanded0;
c->inputs_[1] = expanded1;
}
}
}
// 此时 smallest, largest 始终等于 GetRange(inputs[0]).
if (false) {
Log(env_, options_->info_log, "Compacting %d '%s' .. '%s'",
level,
EscapeString(smallest.Encode()).c_str(),
EscapeString(largest.Encode()).c_str());
}
// Update the place where we will do the next compaction for this level.
// We update this immediately instead of waiting for the VersionEdit
// to be applied so that if the compaction fails, we will try a different
// key range next time. QA: 由于对 compaction 的整体流程不理解, 所以这句话不是很懂.
// A: 如果 c 标识着的 compaction 失败, 那么 c->edit_ 中的内容会被废弃, 相当于持久化设备中的 compact pointer
// 保持不变. 但是内存中的 compact_pointer_ 已经更新了, 所以如果程序未重启的话, 下一次的 compact 将会
// try a different key range.
compact_pointer_[level] = largest.Encode().ToString();
// 我们都知道不能把 compact_pointer[level] 设置为 smallest 对吧.
c->edit_.SetCompactPointer(level, largest);
return c;
}
Compaction* VersionSet::CompactRange(
int level,
const InternalKey& begin,
const InternalKey& end) {
std::vector<FileMetaData*> inputs;
GetOverlappingInputs(level, begin, end, &inputs);
if (inputs.empty()) {
return NULL;
}
Compaction* c = new Compaction(level);
c->input_version_ = current_;
c->input_version_->Ref();
c->inputs_[0] = inputs;
// Find the range we are compacting
InternalKey smallest, largest;
GetRange(c->inputs_[0], &smallest, &largest);
GetOverlappingInputs(level+1, smallest, largest, &c->inputs_[1]);
if (false) {
Log(env_, options_->info_log, "Compacting %d '%s' .. '%s'",
level,
EscapeString(smallest.Encode()).c_str(),
EscapeString(largest.Encode()).c_str());
}
return c;
}
Compaction::Compaction(int level)
: level_(level),
// 我觉得 max_output_file_size_ 应该初始化 MaxFileSizeForLevel(level + 1) 吧, 毕竟输出的是
// level + 1 层的文件.
max_output_file_size_(MaxFileSizeForLevel(level)),
input_version_(NULL) {
for (int i = 0; i < config::kNumLevels; i++) {
level_ptrs_[i] = 0; // QA: 由于不知道 level_ptrs_ 干啥的, 所以也不知道这里为啥这样.
// A: 现在我终于知道了哈哈
}
}
Compaction::~Compaction() {
if (input_version_ != NULL) {
input_version_->Unref();
}
}
void Compaction::AddInputDeletions(VersionEdit* edit) {
for (int which = 0; which < 2; which++) {
for (int i = 0; i < inputs_[which].size(); i++) {
edit->DeleteFile(level_ + which, inputs_[which][i]->number);
}
}
}
bool Compaction::IsBaseLevelForKey(const Slice& user_key) {
// Maybe use binary search to find right entry instead of linear search?
const Comparator* user_cmp = input_version_->vset_->icmp_.user_comparator();
for (int lvl = level_ + 2; lvl < config::kNumLevels; lvl++) {
const std::vector<FileMetaData*>& files = input_version_->files_[lvl];
for (; level_ptrs_[lvl] < files.size(); ) {
FileMetaData* f = files[level_ptrs_[lvl]];
if (user_cmp->Compare(user_key, f->largest.user_key()) <= 0) {
// We've advanced far enough
if (user_cmp->Compare(user_key, f->smallest.user_key()) >= 0) {
// Key falls in this file's range, so definitely not base level
// 本来按照我的想法, 此时会进一步执行如下代码:
// iter = TableCache::NewIterator(ReadOptions(), f->number);
// iter->Seek(user_key); // 实际上这里不能使用 user_key, 这里 Seek 只接受 InternalKey.
// 来判断 f 中是否真的存在 user_key, 但是原文很显然并没有这么做.
return false;
} /* else {
user_key < f->smallest.user_key(); 此时不需要继续往下遍历了, 而且也不需要更新 level_ptrs_[lvl].
所以 break.
} */
break;
} /* else {
f->largest < user_key, 所以应该更新 level_ptrs_[lvl] 的值, 就像下面一样.
}*/
level_ptrs_[lvl]++;
}
}
// 这时候我们可以确认 user_key 不再高层存在, 而且我们还更新 level_ptrs_.
return true;
}
void Compaction::ReleaseInputs() {
if (input_version_ != NULL) {
input_version_->Unref();
input_version_ = NULL;
}
}
}
| 32.83491 | 95 | 0.62262 | [
"vector"
] |
1cee61409471da7aed5e075642fe7ae890f19774 | 3,788 | cpp | C++ | third/parallel/example.cpp | aceisnotmycard/Parallel-programming-course | 83a751d90de9ecfe3ced3c78d5de0ad0800f5530 | [
"MIT"
] | null | null | null | third/parallel/example.cpp | aceisnotmycard/Parallel-programming-course | 83a751d90de9ecfe3ced3c78d5de0ad0800f5530 | [
"MIT"
] | null | null | null | third/parallel/example.cpp | aceisnotmycard/Parallel-programming-course | 83a751d90de9ecfe3ced3c78d5de0ad0800f5530 | [
"MIT"
] | 1 | 2020-02-20T12:51:18.000Z | 2020-02-20T12:51:18.000Z | #include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
// Input variables
/* Количество ячеек вдоль координат x, y, z */
#define in 20
#define jn 20
#define kn 20
int a = 1;
double X = 2.0, Y = 2.0, Z = 2.0;
double e = 0.00001;
// MPI
int rank, size;
/* Allocating memory for current and previous iterations */
double F[2][in+1][jn+1][kn+1];
double hx, hy, hz;
/* Функция определения точного решения */
double Fresh(double,double,double);
/* Функция задания правой части уравнения */
double Ro(double,double,double);
/* Подпрограмма инициализации границ 3D пространства */
void Init();
// Get number of rows in current layer
int get_chunk_size(int given_rank);
// Get number of rows below current layer
int calculate_shift(int given_rank);
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// calculating rank of neighbours
int neighbour_below_rank = (rank == size - 1) ? -1 : rank - 1;
int neighbour_above_rank = (rank == 0) ? -1 : rank + 1;
// allocating space for receiving data
double neighbour_above[in+1][jn+1];
double neighbour_below[in+1][jn+1];
//calculating starting point of local array's part
int localZ = calculate_shift(rank);
double N, t1, t2;
double owx, owy, owz, c;
double Fi, Fj, Fk;
int i, j, k;
int R, fl, fcur_it, fl2;
int it,f, prev_it, cur_it;
// time calculation variables
long int osdt;
struct timeval tv1,tv2;
// iterations init
it = 0;
prev_it = 1;
cur_it = 0;
/* Step size */
hx = X/in;
hy = Y/jn;
hz = Z/kn;
owx = pow(hx,2);
owy = pow(hy,2);
owz = pow(hz,2);
c = 2/owx + 2/owy + 2/owz + a;
gettimeofday(&tv1, (struct timezone*)0);
/* Initialization of borders */
Init();
/* Main cycle */
do {
f = 1;
prev_it = 1 - prev_it;
cur_it = 1 - cur_it;
for(i = 1; i < in; i++)
for(j = 1; j < jn; j++) {
for(k = 1; k < kn; k++) {
Fi = (F[prev_it][i+1][j][k] + F[prev_it][i-1][j][k]) / owx;
Fj = (F[prev_it][i][j+1][k] + F[prev_it][i][j-1][k]) / owy;
Fk = (F[prev_it][i][j][k+1] + F[prev_it][i][j][k-1]) / owz;
F[cur_it][i][j][k] = (Fi + Fj + Fk - Ro(i*hx,j*hy,k*hz)) / c;
if (fabs(F[cur_it][i][j][k] - F[prev_it][i][j][k]) > e)
f = 0;
}
}
it++;
} while (f == 0);
gettimeofday(&tv2,(struct timezone*)0);
osdt = (tv2.tv_sec - tv1.tv_sec)*1000000 + tv2.tv_usec-tv1.tv_usec;
printf("\n in = %d iter = %d E = %f T = %ld\n",in,it,e,osdt);
double max, F1;
int mk, mj, mi;
/* Нахождение максимального расхождения полученного приближенного решения * и точного решения */
max = 0.0;
for(i = 1; i < in; i++) {
for(j = 1; j < jn; j++) {
for(k = 1; k < kn; k++) {
if((F1 = fabs(F[cur_it][i][j][k] - Fresh(i*hx,j*hy,k*hz))) > max) {
max = F1;
mi = i;
mj = j;
mk = k;
}
}
}
}
printf("Max differ = %f\n in point(%d,%d,%d)\n",max,mi,mj,mk);
MPI_Finalize();
return 0;
}
int get_chunk_size(int given_rank) {
int basic_chunk = kn / size;
int rest = kn % size;
return basic_chunk + (given_rank < rest ? 1 : 0);
}
int calculate_shift(int given_rank) {
int result = 0;
for (int i = 0; i < given_rank; i++) {
result += get_chunk_size(i);
}
return result;
}
double Fresh(double x,double y,double z) {
return x + y + z;
}
void Init() {
int i, j, k;
for(i = 0; i <= in; i++) {
for(j = 0; j <= jn; j++) {
for(k = 0; k <= kn; k++) {
if (i != 0 && j != 0 && k != 0 && i != in && j != jn && k != kn) {
F[0][i][j][k] = 0;
F[1][i][j][k] = 0;
} else {
F[0][i][j][k] = Fresh(i*hx,j*hy,k*hz);
F[1][i][j][k] = Fresh(i*hx,j*hy,k*hz);
}
}
}
}
}
double Ro(double x, double y, double z) {
return -a*(x+y+z);
} | 22.819277 | 97 | 0.57075 | [
"3d"
] |
1cf0edda395ffc48362d882c2a3d4a6046b974e3 | 1,731 | cpp | C++ | SPOJ/Random/PPBRJB/red_john.cpp | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | SPOJ/Random/PPBRJB/red_john.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | SPOJ/Random/PPBRJB/red_john.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<cstring>
using namespace std;
int l;
bool is_prime (const int& n, int (&primes)[20000]){
double root = sqrt (n);
for(int i = 0; i < l and i <= root; i++){
if(n % primes[i] == 0)
return 0;
}
return 1;
}
long long fill_dp(long long (&dp)[41], int empty){
if(empty < 4)
return 1;
else if(dp[empty] != 0)
return dp[empty];
else
dp[empty] = fill_dp(dp, empty - 4) + fill_dp(dp, empty - 1);
return dp[empty];
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t, n;
long long dp[41];
int ans[41];
ans[0] = 0;
ans[1] = 0;
ans[2] = 0;
ans[3] = 0;
ans[4] = 1;
int primes[20000];
l = 1;
primes[0] = 2;
//vector<int> primes;
//primes.push_back(2);
dp[0] = 0;
dp[1] = 1;
dp[2] = 1;
dp[3] = 1;
dp[4] = 2;
for(int i = 5; i < 41; i++)
dp[i] = 0;
fill_dp(dp, 40);
int flag;
double root;
for (int i=3; i<=217286; i+=2){
if(is_prime(i,&primes[20000])){
primes[l] = i;
l++;
}
}
ans[40] = l;
int j = 5, count=0;
int k = 0;
//vector<int>::iterator it = primes.begin();
while ( k < l){
if (primes[k] > dp[j]){
ans[j] = count;
j++;
}
else if(primes[k] == dp[j]){
count++;
ans[j] = count;
j++;
k++;
}
else{
k++;
count++;
}
}
scanf("%d",&t);
while(t--){
scanf("%d",&n);
cout<<ans[n]<<endl;
}
return 0;
}
| 18.815217 | 80 | 0.444252 | [
"vector"
] |
7f3235ba8de77227c906099a985e63bdb1577a9f | 530 | cpp | C++ | solutions/174.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/174.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | solutions/174.cpp | tdakhran/leetcode | ed680059661faae32857eaa791ca29c1d9c16120 | [
"MIT"
] | null | null | null | #include <limits>
#include <vector>
class Solution {
public:
int calculateMinimumHP(std::vector<std::vector<int>>& dungeon) {
auto dp =
std::vector<int>(dungeon.size() + 1, std::numeric_limits<int>::max());
dp[dungeon.size() - 1] = 1;
for (size_t col = dungeon.front().size(); col > 0; --col) {
for (size_t row = dungeon.size(); row > 0; --row) {
dp[row - 1] = std::max(
1, std::min(dp[row - 1], dp[row]) - dungeon[row - 1][col - 1]);
}
}
return dp.front();
}
};
| 26.5 | 78 | 0.537736 | [
"vector"
] |
7f32b6583b9a2f613562358c5983e004356aef55 | 917 | hpp | C++ | include/depthai/pipeline/datatype/SystemInformation.hpp | jdavidberger/depthai-core | daf3577f67318fddd4530090adf86a4be5d9e970 | [
"MIT"
] | 112 | 2020-09-05T01:56:31.000Z | 2022-03-27T15:20:07.000Z | include/depthai/pipeline/datatype/SystemInformation.hpp | jdavidberger/depthai-core | daf3577f67318fddd4530090adf86a4be5d9e970 | [
"MIT"
] | 226 | 2020-06-12T11:14:17.000Z | 2022-03-31T13:32:36.000Z | include/depthai/pipeline/datatype/SystemInformation.hpp | jdavidberger/depthai-core | daf3577f67318fddd4530090adf86a4be5d9e970 | [
"MIT"
] | 66 | 2020-09-06T03:22:27.000Z | 2022-03-30T09:01:29.000Z | #pragma once
#include <chrono>
#include <unordered_map>
#include <vector>
#include "depthai-shared/datatype/RawSystemInformation.hpp"
#include "depthai/pipeline/datatype/Buffer.hpp"
namespace dai {
/**
* SystemInformation message. Carries memory usage, cpu usage and chip temperatures.
*/
class SystemInformation : public Buffer {
std::shared_ptr<RawBuffer> serialize() const override;
RawSystemInformation& systemInformation;
public:
/**
* Construct SystemInformation message.
*/
SystemInformation();
explicit SystemInformation(std::shared_ptr<RawSystemInformation> ptr);
virtual ~SystemInformation() = default;
MemoryInfo& ddrMemoryUsage;
MemoryInfo& cmxMemoryUsage;
MemoryInfo& leonCssMemoryUsage;
MemoryInfo& leonMssMemoryUsage;
CpuUsage& leonCssCpuUsage;
CpuUsage& leonMssCpuUsage;
ChipTemperature& chipTemperature;
};
} // namespace dai
| 25.472222 | 84 | 0.74373 | [
"vector"
] |
7f3372c1a398856907f6491ab273cc17a5f5e316 | 3,264 | hpp | C++ | cyberdog_interaction/cyberdog_audio/audio_base/include/audio_base/audio_player.hpp | gitter-badger/cyberdog_ros2 | f995b3cbf5773a47cd2d7293b0622d91fb409cdc | [
"Apache-2.0"
] | 284 | 2021-09-15T12:31:22.000Z | 2022-03-31T01:16:13.000Z | cyberdog_interaction/cyberdog_audio/audio_base/include/audio_base/audio_player.hpp | gitter-badger/cyberdog_ros2 | f995b3cbf5773a47cd2d7293b0622d91fb409cdc | [
"Apache-2.0"
] | 85 | 2021-09-18T03:44:26.000Z | 2022-03-23T12:32:55.000Z | cyberdog_interaction/cyberdog_audio/audio_base/include/audio_base/audio_player.hpp | gitter-badger/cyberdog_ros2 | f995b3cbf5773a47cd2d7293b0622d91fb409cdc | [
"Apache-2.0"
] | 94 | 2021-09-15T14:40:14.000Z | 2022-03-30T06:50:11.000Z | // Copyright (c) 2021 Beijing Xiaomi Mobile Software Co., Ltd. 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.
#ifndef AUDIO_BASE__AUDIO_PLAYER_HPP_
#define AUDIO_BASE__AUDIO_PLAYER_HPP_
// C++ headers
#include <map>
#include <queue>
#include <thread>
#include <vector>
#include <memory>
#include <iostream>
#include <functional>
// SDL2 headers
#include "SDL2/SDL.h"
#include "SDL2/SDL_mixer.h"
namespace cyberdog_audio
{
#define ERROR_CHANNEL -2
#define DELAY_CHECK_TIME 1000
#define DEFAULT_PLAY_CHANNEL_NUM 4
#define DEFAULT_VOLUME MIX_MAX_VOLUME
#define AUDIO_FREQUENCY 16000
#define AUDIO_FORMAT MIX_DEFAULT_FORMAT
#define AUDIO_CHANNELS 1
#define AUDIO_CHUCKSIZE 2048
#define INDE_VOLUME_GROUP -1
#define MAX_QUEUE_BUFF_NUM 100
using chuck_ptr = std::shared_ptr<Mix_Chunk>;
using callback = std::function<void (void)>;
class AudioPlayer
{
public:
explicit AudioPlayer(
int channel,
callback finish_callback = nullptr,
int volume_group = INDE_VOLUME_GROUP,
int volume = DEFAULT_VOLUME);
~AudioPlayer();
static int GetFreeChannel();
static bool InitSuccess();
static bool OpenReference(int buffsize);
static void CloseReference();
static bool GetReferenceData(char * buff);
static bool HaveReferenceData();
static void ClearReferenceData();
void SetFinishCallBack(callback finish_callback);
void SetChuckVolume(int volume);
int SetVolume(int volume);
void SetVolumeGroup(int volume_gp, int default_volume);
int GetVolume();
void AddPlay(Uint8 * buff, int len);
void AddPlay(const char * file);
void StopPlay();
bool IsPlaying();
bool InitReady();
private:
inline static bool init_success_;
inline static int channelNum_;
inline static int activeNum_;
inline static std::vector<int> thread_num_;
inline static std::vector<int> chuck_volume_;
inline static std::vector<int> volume_group_;
inline static std::map<int, std::queue<chuck_ptr>> chucks_;
inline static std::map<int, std::queue<Uint8 *>> databuff_;
inline static std::map<int, callback> finish_callbacks_;
inline static std::queue<Uint8 *> reference_data_;
inline static SDL_AudioDeviceID reference_id_;
inline static SDL_AudioSpec obtained_spec_;
inline static int ref_buffsize_;
int self_channel_;
int init_ready_;
bool Init();
void Close();
int SetSingleVolume(int channel, int volume);
int GetGroupVolume(int volume_group, int default_volume);
static bool PopEmpty(int channel);
static void PlayThreadFunc(int channel, int thread_num);
static void chuckFinish_callback(int channel);
static void audioRecording_callback(void *, Uint8 * stream, int len);
}; // class AudioPlayer
} // namespace cyberdog_audio
#endif // AUDIO_BASE__AUDIO_PLAYER_HPP_
| 29.672727 | 83 | 0.762561 | [
"vector"
] |
7f596283f761fc600e9a9f5c3da7bbb39241bbeb | 621 | hpp | C++ | proxy/cert/rsa_maker.hpp | plater-inc/proxy | f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda | [
"MIT"
] | null | null | null | proxy/cert/rsa_maker.hpp | plater-inc/proxy | f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda | [
"MIT"
] | null | null | null | proxy/cert/rsa_maker.hpp | plater-inc/proxy | f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda | [
"MIT"
] | null | null | null | #ifndef PROXY_CERT_RSA_MAKER_HPP
#define PROXY_CERT_RSA_MAKER_HPP
#include "rsa.hpp"
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <vector>
namespace proxy {
namespace cert {
class rsa_maker : private boost::noncopyable {
static const size_t SOFT_LIMIT = 128;
static const size_t HARD_LIMIT = 156;
std::vector<RSA_ptr> storage;
size_t count = 0;
public:
rsa_maker();
typedef boost::function<void()> reschedule;
void generate_callback(reschedule reschedule);
RSA_ptr get(reschedule reschedule);
};
} // namespace cert
} // namespace proxy
#endif // PROXY_CERT_RSA_MAKER_HPP
| 21.413793 | 48 | 0.756844 | [
"vector"
] |
7f5fb341ab3f09394b0f2e27fe28bd0dbb1fd6ee | 88,847 | cpp | C++ | ASNativeActivity/phoenixas/src/main/cpp/wiiu/controller_patcher/ControllerPatcher.cpp | playbar/android-ndk | 34e79bc1de9caa27faa72f5f1fb4ad3202debdc6 | [
"Apache-2.0"
] | 1 | 2017-06-01T01:20:57.000Z | 2017-06-01T01:20:57.000Z | ASNativeActivity/phoenixas/src/main/cpp/wiiu/controller_patcher/ControllerPatcher.cpp | playbar/android-ndk | 34e79bc1de9caa27faa72f5f1fb4ad3202debdc6 | [
"Apache-2.0"
] | 1 | 2018-07-17T07:09:17.000Z | 2018-07-17T07:09:17.000Z | ASNativeActivity/phoenixas/src/main/cpp/wiiu/controller_patcher/ControllerPatcher.cpp | playbar/android-ndk | 34e79bc1de9caa27faa72f5f1fb4ad3202debdc6 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* Copyright (C) 2016,2017 Maschell
*
* 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/>.
****************************************************************************/
#include "ControllerPatcher.hpp"
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <vector>
#include "wiiu/sysapp.h"
#include "wiiu/syshid.h"
#include "sys/socket.h"
#include "wiiu/kpad.h"
#include "utils/CPRetainVars.hpp"
// This stores the holded buttons for the gamepad after the button remapping.
static u32 buttonRemapping_lastButtonsHold = 0;
/* To set the controls of an Pro Controler, we first get the result for an Gamepad and convert them later. This way both can share the same functions.*/
// This arrays stores the last hold buttons of the Pro Controllers. One u32 for each channel of the controllers
static u32 last_button_hold[4] = {0,0,0,0};
// This arrays stores the VPADStatus that will be used to get the HID Data for the Pro Controllers. One for each channel.
static VPADStatus myVPADBuffer[4];
void ControllerPatcher::InitButtonMapping(){
if(HID_DEBUG){ printf("ControllerPatcher::InitButtonMapping(line %d): Init called \n",__LINE__); }
if(!gButtonRemappingConfigDone){
if(HID_DEBUG){ printf("ControllerPatcher::InitButtonMapping(line %d): Remapping is running! \n",__LINE__); }
gButtonRemappingConfigDone = 1;
memset(gGamePadValues,0,sizeof(gGamePadValues)); // Init / Invalid everything
gGamePadValues[CONTRPS_VPAD_BUTTON_A] = VPAD_BUTTON_A;
gGamePadValues[CONTRPS_VPAD_BUTTON_B] = VPAD_BUTTON_B;
gGamePadValues[CONTRPS_VPAD_BUTTON_X] = VPAD_BUTTON_X;
gGamePadValues[CONTRPS_VPAD_BUTTON_Y] = VPAD_BUTTON_Y;
gGamePadValues[CONTRPS_VPAD_BUTTON_LEFT] = VPAD_BUTTON_LEFT;
gGamePadValues[CONTRPS_VPAD_BUTTON_RIGHT] = VPAD_BUTTON_RIGHT;
gGamePadValues[CONTRPS_VPAD_BUTTON_UP] = VPAD_BUTTON_UP;
gGamePadValues[CONTRPS_VPAD_BUTTON_DOWN] = VPAD_BUTTON_DOWN;
gGamePadValues[CONTRPS_VPAD_BUTTON_ZL] = VPAD_BUTTON_ZL;
gGamePadValues[CONTRPS_VPAD_BUTTON_ZR] = VPAD_BUTTON_ZR;
gGamePadValues[CONTRPS_VPAD_BUTTON_L] = VPAD_BUTTON_L;
gGamePadValues[CONTRPS_VPAD_BUTTON_R] = VPAD_BUTTON_R;
gGamePadValues[CONTRPS_VPAD_BUTTON_PLUS] = VPAD_BUTTON_PLUS;
gGamePadValues[CONTRPS_VPAD_BUTTON_MINUS] = VPAD_BUTTON_MINUS;
gGamePadValues[CONTRPS_VPAD_BUTTON_HOME] = VPAD_BUTTON_HOME;
gGamePadValues[CONTRPS_VPAD_BUTTON_SYNC] = VPAD_BUTTON_SYNC;
gGamePadValues[CONTRPS_VPAD_BUTTON_STICK_R] = VPAD_BUTTON_STICK_R;
gGamePadValues[CONTRPS_VPAD_BUTTON_STICK_L] = VPAD_BUTTON_STICK_L;
gGamePadValues[CONTRPS_VPAD_BUTTON_TV] = VPAD_BUTTON_TV;
gGamePadValues[CONTRPS_VPAD_STICK_R_EMULATION_LEFT] = VPAD_STICK_R_EMULATION_LEFT;
gGamePadValues[CONTRPS_VPAD_STICK_R_EMULATION_RIGHT] = VPAD_STICK_R_EMULATION_RIGHT;
gGamePadValues[CONTRPS_VPAD_STICK_R_EMULATION_UP] = VPAD_STICK_R_EMULATION_UP;
gGamePadValues[CONTRPS_VPAD_STICK_R_EMULATION_DOWN] = VPAD_STICK_R_EMULATION_DOWN;
gGamePadValues[CONTRPS_VPAD_STICK_L_EMULATION_LEFT] = VPAD_STICK_L_EMULATION_LEFT;
gGamePadValues[CONTRPS_VPAD_STICK_L_EMULATION_RIGHT] = VPAD_STICK_L_EMULATION_RIGHT;
gGamePadValues[CONTRPS_VPAD_STICK_L_EMULATION_UP] = VPAD_STICK_L_EMULATION_UP;
gGamePadValues[CONTRPS_VPAD_STICK_L_EMULATION_DOWN] = VPAD_STICK_L_EMULATION_DOWN;
}
}
void ControllerPatcher::ResetConfig(){
memset(connectionOrderHelper,0,sizeof(connectionOrderHelper));
memset(&gControllerMapping,0,sizeof(gControllerMapping)); // Init / Invalid everything
memset(config_controller,CONTROLLER_PATCHER_INVALIDVALUE,sizeof(config_controller)); // Init / Invalid everything
memset(config_controller_hidmask,0,sizeof(config_controller_hidmask)); // Init / Invalid everything
memset(gNetworkController,0,sizeof(gNetworkController)); // Init / Invalid everything
memset(gHID_Devices,0,sizeof(gHID_Devices)); // Init / Invalid everything
memset(gWPADConnectCallback,0,sizeof(gWPADConnectCallback));
memset(gKPADConnectCallback,0,sizeof(gKPADConnectCallback));
memset(gExtensionCallback,0,sizeof(gExtensionCallback));
gCallbackCooldown = 0;
gHID_Mouse_Mode = HID_MOUSE_MODE_AIM;
gHID_LIST_GC = 0;
gHID_LIST_DS3 = 0;
gHID_LIST_DS4 = 0;
gHID_LIST_KEYBOARD = 0;
gHID_LIST_MOUSE = 0;
gGamePadSlot = 0;
gHID_SLOT_GC = 0;
gHID_SLOT_KEYBOARD = 0;
gMouseSlot = 0;
HIDSlotData slotdata;
gHIDRegisteredDevices = 0;
ControllerPatcherUtils::getNextSlotData(&slotdata);
gGamePadSlot = slotdata.deviceslot;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register Gamepad-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(slotdata.hidmask),gGamePadSlot); }
ControllerPatcherUtils::getNextSlotData(&slotdata);
gMouseSlot = slotdata.deviceslot;
gHID_LIST_MOUSE = slotdata.hidmask;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register Mouse-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(gHID_LIST_MOUSE),gMouseSlot); }
ControllerPatcherUtils::getNextSlotData(&slotdata);
u32 keyboard_slot = slotdata.deviceslot;
u32 keyboard_hid = slotdata.hidmask;
gHID_LIST_KEYBOARD = keyboard_hid;
gHID_SLOT_KEYBOARD = keyboard_slot;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register Keyboard-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(gHID_LIST_KEYBOARD),gHID_SLOT_KEYBOARD); }
ControllerPatcherUtils::getNextSlotData(&slotdata);
u32 gc_slot = slotdata.deviceslot;
u32 gc_hid = slotdata.hidmask;
gHID_LIST_GC = gc_hid;
gHID_SLOT_GC = gc_slot;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register GC-Adapter-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(gHID_LIST_GC),gHID_SLOT_GC); }
ControllerPatcherUtils::getNextSlotData(&slotdata);
u32 ds3_slot = slotdata.deviceslot;
u32 ds3_hid = slotdata.hidmask;
gHID_LIST_DS3 = ds3_hid;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register DS3-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(gHID_LIST_DS3),ds3_slot); }
ControllerPatcherUtils::getNextSlotData(&slotdata);
u32 ds4_slot = slotdata.deviceslot;
u32 ds4_hid = slotdata.hidmask;
gHID_LIST_DS4 = ds4_hid;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register DS4-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(ds4_hid),ds4_slot); }
ControllerPatcherUtils::getNextSlotData(&slotdata);
u32 xinput_slot = slotdata.deviceslot;
u32 xinput_hid = slotdata.hidmask;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register XInput-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(xinput_hid),xinput_slot); }
ControllerPatcherUtils::getNextSlotData(&slotdata);
u32 switch_pro_slot = slotdata.deviceslot;
gHID_LIST_SWITCH_PRO = slotdata.hidmask;
if(HID_DEBUG){ printf("ControllerPatcher::ResetConfig(line %d): Register Switch-Pro-Config. HID-Mask %s Device-Slot: %d\n",__LINE__,CPStringTools::byte_to_binary(gHID_LIST_SWITCH_PRO),switch_pro_slot); }
config_controller_hidmask[gc_slot] = gHID_LIST_GC;
config_controller_hidmask[ds3_slot] = gHID_LIST_DS3;
config_controller_hidmask[keyboard_slot] = gHID_LIST_KEYBOARD;
config_controller_hidmask[gMouseSlot] = gHID_LIST_MOUSE;
config_controller_hidmask[ds4_slot] = gHID_LIST_DS4;
config_controller_hidmask[xinput_slot] = xinput_hid;
config_controller_hidmask[switch_pro_slot] = gHID_LIST_SWITCH_PRO;
/* We need to give the GamePad, Mouse and Keyboard a unique VID/PID to find the right slots.*/
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! GamePad
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gGamePadSlot][CONTRPS_VID], 0xAF,0xFE);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gGamePadSlot][CONTRPS_PID], 0xAA,0xAA);
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! Switch Pro Controller
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VID], (HID_SWITCH_PRO_VID>>8)&0xFF, HID_SWITCH_PRO_VID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_PID], (HID_SWITCH_PRO_PID>>8)&0xFF, HID_SWITCH_PRO_PID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_A], HID_SWITCH_PRO_BT_BUTTON_A[0], HID_SWITCH_PRO_BT_BUTTON_A[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_B], HID_SWITCH_PRO_BT_BUTTON_B[0], HID_SWITCH_PRO_BT_BUTTON_B[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_X], HID_SWITCH_PRO_BT_BUTTON_X[0], HID_SWITCH_PRO_BT_BUTTON_X[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_Y], HID_SWITCH_PRO_BT_BUTTON_Y[0], HID_SWITCH_PRO_BT_BUTTON_Y[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_DPAD_MODE], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_BUTTON_DPAD_TYPE[CONTRDPAD_MODE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_DPAD_MASK], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_BUTTON_DPAD_TYPE[CONTRDPAD_MASK]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_N], HID_SWITCH_PRO_BT_BUTTON_DPAD_N[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_N[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_NE], HID_SWITCH_PRO_BT_BUTTON_DPAD_NE[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_NE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_E], HID_SWITCH_PRO_BT_BUTTON_DPAD_E[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_E[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_SE], HID_SWITCH_PRO_BT_BUTTON_DPAD_SE[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_SE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_S], HID_SWITCH_PRO_BT_BUTTON_DPAD_S[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_S[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_SW], HID_SWITCH_PRO_BT_BUTTON_DPAD_SW[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_SW[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_W], HID_SWITCH_PRO_BT_BUTTON_DPAD_W[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_W[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_NW], HID_SWITCH_PRO_BT_BUTTON_DPAD_NW[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_NW[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_DPAD_NEUTRAL], HID_SWITCH_PRO_BT_BUTTON_DPAD_NEUTRAL[0], HID_SWITCH_PRO_BT_BUTTON_DPAD_NEUTRAL[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_PLUS], HID_SWITCH_PRO_BT_BUTTON_PLUS[0], HID_SWITCH_PRO_BT_BUTTON_PLUS[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_MINUS], HID_SWITCH_PRO_BT_BUTTON_MINUS[0], HID_SWITCH_PRO_BT_BUTTON_MINUS[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L], HID_SWITCH_PRO_BT_BUTTON_L[0], HID_SWITCH_PRO_BT_BUTTON_L[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R], HID_SWITCH_PRO_BT_BUTTON_R[0], HID_SWITCH_PRO_BT_BUTTON_R[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_ZL], HID_SWITCH_PRO_BT_BUTTON_ZL[0], HID_SWITCH_PRO_BT_BUTTON_ZL[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_ZR], HID_SWITCH_PRO_BT_BUTTON_ZR[0], HID_SWITCH_PRO_BT_BUTTON_ZR[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_STICK_L], HID_SWITCH_PRO_BT_BUTTON_STICK_L[0], HID_SWITCH_PRO_BT_BUTTON_STICK_L[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_STICK_R], HID_SWITCH_PRO_BT_BUTTON_STICK_R[0], HID_SWITCH_PRO_BT_BUTTON_STICK_R[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_HOME], HID_SWITCH_PRO_BT_BUTTON_HOME[0], HID_SWITCH_PRO_BT_BUTTON_HOME[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_PAD_COUNT], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_PAD_COUNT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_X], HID_SWITCH_PRO_BT_STICK_L_X[STICK_CONF_BYTE], HID_SWITCH_PRO_BT_STICK_L_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_L_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_MINMAX], HID_SWITCH_PRO_BT_STICK_L_X[STICK_CONF_MIN], HID_SWITCH_PRO_BT_STICK_L_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_L_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y], HID_SWITCH_PRO_BT_STICK_L_Y[STICK_CONF_BYTE], HID_SWITCH_PRO_BT_STICK_L_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_L_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_MINMAX], HID_SWITCH_PRO_BT_STICK_L_Y[STICK_CONF_MIN], HID_SWITCH_PRO_BT_STICK_L_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_L_Y[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_X], HID_SWITCH_PRO_BT_STICK_R_X[STICK_CONF_BYTE], HID_SWITCH_PRO_BT_STICK_R_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_R_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_MINMAX], HID_SWITCH_PRO_BT_STICK_R_X[STICK_CONF_MIN], HID_SWITCH_PRO_BT_STICK_R_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_R_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y], HID_SWITCH_PRO_BT_STICK_R_Y[STICK_CONF_BYTE], HID_SWITCH_PRO_BT_STICK_R_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_R_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_MINMAX], HID_SWITCH_PRO_BT_STICK_R_Y[STICK_CONF_MIN], HID_SWITCH_PRO_BT_STICK_R_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[switch_pro_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_SWITCH_PRO_BT_STICK_R_Y[STICK_CONF_INVERT]);
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! Mouse
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gMouseSlot][CONTRPS_VID], (HID_MOUSE_VID>>8)&0xFF, HID_MOUSE_VID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gMouseSlot][CONTRPS_PID], (HID_MOUSE_PID>>8)&0xFF, HID_MOUSE_PID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gMouseSlot][CONTRPS_VPAD_BUTTON_LEFT], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_ZR);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gMouseSlot][CONTRPS_VPAD_BUTTON_RIGHT], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_R);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gMouseSlot][CONTRPS_PAD_COUNT], CONTROLLER_PATCHER_VALUE_SET, HID_MOUSE_PAD_COUNT);
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! Keyboard
//!---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VID], (HID_KEYBOARD_VID>>8)&0xFF, HID_KEYBOARD_VID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_PID], (HID_KEYBOARD_PID>>8)&0xFF, HID_KEYBOARD_PID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_A], 0x00, HID_KEYBOARD_BUTTON_E);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_B], 0x00, HID_KEYBOARD_BUTTON_Q);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_X], 0x00, HID_KEYBOARD_BUTTON_SPACEBAR);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_Y], 0x00, HID_KEYBOARD_BUTTON_R);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_DPAD_MODE], CONTROLLER_PATCHER_VALUE_SET,CONTRPDM_Normal);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_LEFT], 0x00, HID_KEYBOARD_BUTTON_LEFT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_RIGHT], 0x00, HID_KEYBOARD_BUTTON_RIGHT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_DOWN], 0x00, HID_KEYBOARD_BUTTON_DOWN);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_UP], 0x00, HID_KEYBOARD_BUTTON_UP);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_PLUS], 0x00, HID_KEYBOARD_BUTTON_RETURN);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_MINUS], 0x00, HID_KEYBOARD_KEYPAD_BUTTON_MINUS);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_L], 0x00, HID_KEYBOARD_BUTTON_V);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_R], 0x00, HID_KEYBOARD_BUTTON_B);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_ZL], 0x00, HID_KEYBOARD_BUTTON_SHIFT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_ZR], 0x00, HID_KEYBOARD_BUTTON_N);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_STICK_L], 0x00, HID_KEYBOARD_BUTTON_F);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_STICK_R], 0x00, HID_KEYBOARD_BUTTON_TAB);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_L_STICK_UP], 0x00, HID_KEYBOARD_BUTTON_W);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_L_STICK_DOWN], 0x00, HID_KEYBOARD_BUTTON_S);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_L_STICK_LEFT], 0x00, HID_KEYBOARD_BUTTON_A);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_L_STICK_RIGHT], 0x00, HID_KEYBOARD_BUTTON_D);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_R_STICK_UP], 0x00, HID_KEYBOARD_KEYPAD_BUTTON_8);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_R_STICK_DOWN], 0x00, HID_KEYBOARD_KEYPAD_BUTTON_2);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_R_STICK_LEFT], 0x00, HID_KEYBOARD_KEYPAD_BUTTON_4);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_VPAD_BUTTON_R_STICK_RIGHT], 0x00, HID_KEYBOARD_KEYPAD_BUTTON_6);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_KEYBOARD][CONTRPS_PAD_COUNT], CONTROLLER_PATCHER_VALUE_SET,HID_KEYBOARD_PAD_COUNT);
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! GC-Adapter
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VID], (HID_GC_VID>>8)&0xFF, HID_GC_VID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_PID], (HID_GC_PID>>8)&0xFF, HID_GC_PID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_A], HID_GC_BUTTON_A[0], HID_GC_BUTTON_A[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_B], HID_GC_BUTTON_B[0], HID_GC_BUTTON_B[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_X], HID_GC_BUTTON_X[0], HID_GC_BUTTON_X[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_Y], HID_GC_BUTTON_Y[0], HID_GC_BUTTON_Y[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DPAD_MODE], CONTROLLER_PATCHER_VALUE_SET, HID_GC_BUTTON_DPAD_TYPE[CONTRDPAD_MODE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DPAD_MASK], CONTROLLER_PATCHER_VALUE_SET, HID_GC_BUTTON_DPAD_TYPE[CONTRDPAD_MASK]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_LEFT], HID_GC_BUTTON_LEFT[0], HID_GC_BUTTON_LEFT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_RIGHT], HID_GC_BUTTON_RIGHT[0], HID_GC_BUTTON_RIGHT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_DOWN], HID_GC_BUTTON_DOWN[0], HID_GC_BUTTON_DOWN[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_UP], HID_GC_BUTTON_UP[0], HID_GC_BUTTON_UP[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_MINUS], HID_GC_BUTTON_START[0], HID_GC_BUTTON_START[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L], HID_GC_BUTTON_L[0], HID_GC_BUTTON_L[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R], HID_GC_BUTTON_R[0], HID_GC_BUTTON_R[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_PLUS], HID_GC_BUTTON_START[0], HID_GC_BUTTON_START[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_ZL], HID_GC_BUTTON_L[0], HID_GC_BUTTON_L[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_ZR], HID_GC_BUTTON_R[0], HID_GC_BUTTON_R[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_STICK_L], HID_GC_BUTTON_A[0], HID_GC_BUTTON_A[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_STICK_R], HID_GC_BUTTON_B[0], HID_GC_BUTTON_B[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE], CONTROLLER_PATCHER_VALUE_SET, CONTROLLER_PATCHER_GC_DOUBLE_USE);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_ACTIVATOR], HID_GC_BUTTON_Z[0], HID_GC_BUTTON_Z[1]);
//Buttons that will be ignored when the CONTRPS_DOUBLE_USE_BUTTON_ACTIVATOR is pressed
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_1_PRESSED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_MINUS);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_2_PRESSED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_L);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_3_PRESSED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_R);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_4_PRESSED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_STICK_L);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_5_PRESSED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_STICK_R);
//Buttons that will be ignored when the CONTRPS_DOUBLE_USE_BUTTON_ACTIVATOR is released
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_1_RELEASED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_PLUS);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_2_RELEASED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_ZL);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_3_RELEASED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_ZR);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_4_RELEASED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_A);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_DOUBLE_USE_BUTTON_5_RELEASED], CONTROLLER_PATCHER_VALUE_SET, CONTRPS_VPAD_BUTTON_B);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_PAD_COUNT], CONTROLLER_PATCHER_VALUE_SET, HID_GC_PAD_COUNT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_X], HID_GC_STICK_L_X[STICK_CONF_BYTE],HID_GC_STICK_L_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_L_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_X_MINMAX], HID_GC_STICK_L_X[STICK_CONF_MIN], HID_GC_STICK_L_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_L_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_Y], HID_GC_STICK_L_Y[STICK_CONF_BYTE],HID_GC_STICK_L_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_L_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_Y_MINMAX], HID_GC_STICK_L_Y[STICK_CONF_MIN], HID_GC_STICK_L_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_L_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_L_Y[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_X], HID_GC_STICK_R_X[STICK_CONF_BYTE],HID_GC_STICK_R_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_R_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_X_MINMAX], HID_GC_STICK_R_X[STICK_CONF_MIN], HID_GC_STICK_R_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_R_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_Y], HID_GC_STICK_R_Y[STICK_CONF_BYTE],HID_GC_STICK_R_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_R_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_Y_MINMAX], HID_GC_STICK_R_Y[STICK_CONF_MIN], HID_GC_STICK_R_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[gHID_SLOT_GC][CONTRPS_VPAD_BUTTON_R_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_GC_STICK_R_Y[STICK_CONF_INVERT]);
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! DS3
//!---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VID], (HID_DS3_VID>>8)&0xFF, HID_DS3_VID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_PID], (HID_DS3_PID>>8)&0xFF, HID_DS3_PID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_BUF_SIZE], CONTROLLER_PATCHER_VALUE_SET, 128);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_A], HID_DS3_BUTTON_CIRCLE[0], HID_DS3_BUTTON_CIRCLE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_B], HID_DS3_BUTTON_CROSS[0], HID_DS3_BUTTON_CROSS[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_X], HID_DS3_BUTTON_TRIANGLE[0], HID_DS3_BUTTON_TRIANGLE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_Y], HID_DS3_BUTTON_SQUARE[0], HID_DS3_BUTTON_SQUARE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_DPAD_MODE], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_BUTTON_DPAD_TYPE[CONTRDPAD_MODE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_DPAD_MASK], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_BUTTON_DPAD_TYPE[CONTRDPAD_MASK]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_LEFT], HID_DS3_BUTTON_LEFT[0], HID_DS3_BUTTON_LEFT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_RIGHT], HID_DS3_BUTTON_RIGHT[0], HID_DS3_BUTTON_RIGHT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_DOWN], HID_DS3_BUTTON_DOWN[0], HID_DS3_BUTTON_DOWN[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_UP], HID_DS3_BUTTON_UP[0], HID_DS3_BUTTON_UP[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_PLUS], HID_DS3_BUTTON_START[0], HID_DS3_BUTTON_START[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_MINUS], HID_DS3_BUTTON_SELECT[0], HID_DS3_BUTTON_SELECT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L], HID_DS3_BUTTON_L1[0], HID_DS3_BUTTON_L1[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R], HID_DS3_BUTTON_R1[0], HID_DS3_BUTTON_R1[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_ZL], HID_DS3_BUTTON_L2[0], HID_DS3_BUTTON_L2[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_ZR], HID_DS3_BUTTON_R2[0], HID_DS3_BUTTON_R2[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_STICK_L], HID_DS3_BUTTON_L3[0], HID_DS3_BUTTON_L3[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_STICK_R], HID_DS3_BUTTON_R3[0], HID_DS3_BUTTON_R3[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_HOME], HID_DS3_BUTTON_GUIDE[0], HID_DS3_BUTTON_GUIDE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_PAD_COUNT], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_PAD_COUNT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_X], HID_DS3_STICK_L_X[STICK_CONF_BYTE], HID_DS3_STICK_L_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_L_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_MINMAX], HID_DS3_STICK_L_X[STICK_CONF_MIN], HID_DS3_STICK_L_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_L_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y], HID_DS3_STICK_L_Y[STICK_CONF_BYTE], HID_DS3_STICK_L_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_L_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_MINMAX], HID_DS3_STICK_L_Y[STICK_CONF_MIN], HID_DS3_STICK_L_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_L_Y[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_X], HID_DS3_STICK_R_X[STICK_CONF_BYTE], HID_DS3_STICK_R_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_R_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_MINMAX], HID_DS3_STICK_R_X[STICK_CONF_MIN], HID_DS3_STICK_R_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_R_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y], HID_DS3_STICK_R_Y[STICK_CONF_BYTE], HID_DS3_STICK_R_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_R_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_MINMAX], HID_DS3_STICK_R_Y[STICK_CONF_MIN], HID_DS3_STICK_R_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds3_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS3_STICK_R_Y[STICK_CONF_INVERT]);
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! DS4
//!---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VID], (HID_DS4_VID>>8)&0xFF, HID_DS4_VID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_PID], (HID_DS4_PID>>8)&0xFF, HID_DS4_PID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_BUF_SIZE], CONTROLLER_PATCHER_VALUE_SET, 128);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_A], HID_DS4_BUTTON_CIRCLE[0], HID_DS4_BUTTON_CIRCLE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_B], HID_DS4_BUTTON_CROSS[0], HID_DS4_BUTTON_CROSS[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_X], HID_DS4_BUTTON_TRIANGLE[0], HID_DS4_BUTTON_TRIANGLE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_Y], HID_DS4_BUTTON_SQUARE[0], HID_DS4_BUTTON_SQUARE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_DPAD_MODE], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_BUTTON_DPAD_TYPE[CONTRDPAD_MODE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_DPAD_MASK], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_BUTTON_DPAD_TYPE[CONTRDPAD_MASK]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_N], HID_DS4_BUTTON_DPAD_N[0], HID_DS4_BUTTON_DPAD_N[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_NE], HID_DS4_BUTTON_DPAD_NE[0], HID_DS4_BUTTON_DPAD_NE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_E], HID_DS4_BUTTON_DPAD_E[0], HID_DS4_BUTTON_DPAD_E[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_SE], HID_DS4_BUTTON_DPAD_SE[0], HID_DS4_BUTTON_DPAD_SE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_S], HID_DS4_BUTTON_DPAD_S[0], HID_DS4_BUTTON_DPAD_S[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_SW], HID_DS4_BUTTON_DPAD_SW[0], HID_DS4_BUTTON_DPAD_SW[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_W], HID_DS4_BUTTON_DPAD_W[0], HID_DS4_BUTTON_DPAD_W[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_NW], HID_DS4_BUTTON_DPAD_NW[0], HID_DS4_BUTTON_DPAD_NW[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_DPAD_NEUTRAL], HID_DS4_BUTTON_DPAD_NEUTRAL[0], HID_DS4_BUTTON_DPAD_NEUTRAL[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_PLUS], HID_DS4_BUTTON_OPTIONS[0], HID_DS4_BUTTON_OPTIONS[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_MINUS], HID_DS4_BUTTON_SHARE[0], HID_DS4_BUTTON_SHARE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L], HID_DS4_BUTTON_L1[0], HID_DS4_BUTTON_L1[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R], HID_DS4_BUTTON_R1[0], HID_DS4_BUTTON_R1[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_ZL], HID_DS4_BUTTON_L2[0], HID_DS4_BUTTON_L2[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_ZR], HID_DS4_BUTTON_R2[0], HID_DS4_BUTTON_R2[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_STICK_L], HID_DS4_BUTTON_L3[0], HID_DS4_BUTTON_L3[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_STICK_R], HID_DS4_BUTTON_R3[0], HID_DS4_BUTTON_R3[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_HOME], HID_DS4_BUTTON_GUIDE[0], HID_DS4_BUTTON_GUIDE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_PAD_COUNT], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_PAD_COUNT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_X], HID_DS4_STICK_L_X[STICK_CONF_BYTE], HID_DS4_STICK_L_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_L_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_MINMAX], HID_DS4_STICK_L_X[STICK_CONF_MIN], HID_DS4_STICK_L_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_L_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y], HID_DS4_STICK_L_Y[STICK_CONF_BYTE], HID_DS4_STICK_L_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_L_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_MINMAX], HID_DS4_STICK_L_Y[STICK_CONF_MIN], HID_DS4_STICK_L_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_L_Y[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_X], HID_DS4_STICK_R_X[STICK_CONF_BYTE], HID_DS4_STICK_R_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_R_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_MINMAX], HID_DS4_STICK_R_X[STICK_CONF_MIN], HID_DS4_STICK_R_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_R_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y], HID_DS4_STICK_R_Y[STICK_CONF_BYTE], HID_DS4_STICK_R_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_R_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_MINMAX], HID_DS4_STICK_R_Y[STICK_CONF_MIN], HID_DS4_STICK_R_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[ds4_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_DS4_STICK_R_Y[STICK_CONF_INVERT]);
//!----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//! XInput
//!---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VID], (HID_XINPUT_VID>>8)&0xFF, HID_XINPUT_VID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_PID], (HID_XINPUT_PID>>8)&0xFF, HID_XINPUT_PID&0xFF);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_BUF_SIZE], CONTROLLER_PATCHER_VALUE_SET, 128);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_A], HID_XINPUT_BUTTON_B[0], HID_XINPUT_BUTTON_B[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_B], HID_XINPUT_BUTTON_A[0], HID_XINPUT_BUTTON_A[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_X], HID_XINPUT_BUTTON_Y[0], HID_XINPUT_BUTTON_Y[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_Y], HID_XINPUT_BUTTON_X[0], HID_XINPUT_BUTTON_X[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_DPAD_MODE], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_BUTTON_DPAD_TYPE[CONTRDPAD_MODE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_DPAD_MASK], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_BUTTON_DPAD_TYPE[CONTRDPAD_MASK]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_UP], HID_XINPUT_BUTTON_UP[0], HID_XINPUT_BUTTON_UP[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_DOWN], HID_XINPUT_BUTTON_DOWN[0], HID_XINPUT_BUTTON_DOWN[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_LEFT], HID_XINPUT_BUTTON_LEFT[0], HID_XINPUT_BUTTON_LEFT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_RIGHT], HID_XINPUT_BUTTON_RIGHT[0], HID_XINPUT_BUTTON_RIGHT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_PLUS], HID_XINPUT_BUTTON_START[0], HID_XINPUT_BUTTON_START[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_MINUS], HID_XINPUT_BUTTON_BACK[0], HID_XINPUT_BUTTON_BACK[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L], HID_XINPUT_BUTTON_LB[0], HID_XINPUT_BUTTON_LB[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R], HID_XINPUT_BUTTON_RB[0], HID_XINPUT_BUTTON_RB[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_ZL], HID_XINPUT_BUTTON_LT[0], HID_XINPUT_BUTTON_LT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_ZR], HID_XINPUT_BUTTON_RT[0], HID_XINPUT_BUTTON_RT[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_STICK_L], HID_XINPUT_BUTTON_L3[0], HID_XINPUT_BUTTON_L3[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_STICK_R], HID_XINPUT_BUTTON_R3[0], HID_XINPUT_BUTTON_R3[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_HOME], HID_XINPUT_BUTTON_GUIDE[0], HID_XINPUT_BUTTON_GUIDE[1]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_PAD_COUNT], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_PAD_COUNT);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_X], HID_XINPUT_STICK_L_X[STICK_CONF_BYTE], HID_XINPUT_STICK_L_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_L_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_MINMAX], HID_XINPUT_STICK_L_X[STICK_CONF_MIN], HID_XINPUT_STICK_L_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_L_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y], HID_XINPUT_STICK_L_Y[STICK_CONF_BYTE], HID_XINPUT_STICK_L_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_L_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_MINMAX], HID_XINPUT_STICK_L_Y[STICK_CONF_MIN], HID_XINPUT_STICK_L_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_L_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_L_Y[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_X], HID_XINPUT_STICK_R_X[STICK_CONF_BYTE], HID_XINPUT_STICK_R_X[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_R_X[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_MINMAX], HID_XINPUT_STICK_R_X[STICK_CONF_MIN], HID_XINPUT_STICK_R_X[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_X_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_R_X[STICK_CONF_INVERT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y], HID_XINPUT_STICK_R_Y[STICK_CONF_BYTE], HID_XINPUT_STICK_R_Y[STICK_CONF_DEFAULT]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_DEADZONE], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_R_Y[STICK_CONF_DEADZONE]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_MINMAX], HID_XINPUT_STICK_R_Y[STICK_CONF_MIN], HID_XINPUT_STICK_R_Y[STICK_CONF_MAX]);
ControllerPatcherUtils::setConfigValue((u8*)&config_controller[xinput_slot][CONTRPS_VPAD_BUTTON_R_STICK_Y_INVERT], CONTROLLER_PATCHER_VALUE_SET, HID_XINPUT_STICK_R_Y[STICK_CONF_INVERT]);
}
bool ControllerPatcher::Init(){
/*
InitOSFunctionPointers();
InitSocketFunctionPointers();
InitSysHIDFunctionPointers();
InitVPadFunctionPointers();
InitPadScoreFunctionPointers();*/
OSDynLoadModule padscore_handle = 0;
OSDynLoad_Acquire("padscore.rpl", &padscore_handle);
void(*KPADRead_test)();
OSDynLoad_FindExport(padscore_handle, 0, "KPADRead", (void**)&KPADRead_test);
printf("ControllerPatcher::Init(line %d): Found the KPADRead at %08X \n",__LINE__,KPADRead_test);
gSamplingCallback = (wpad_sampling_callback_t)((u32)KPADRead_test + 0x1F0);
if(*(u32*)gSamplingCallback != FIRST_INSTRUCTION_IN_SAMPLING_CALLBACK){
gSamplingCallback = NULL;
//In Firmware <= 5.1.2 the offset changes
gSamplingCallback = (wpad_sampling_callback_t)((u32)KPADRead_test + 0x1F8);
if(*(u32*)gSamplingCallback != FIRST_INSTRUCTION_IN_SAMPLING_CALLBACK){
//Should never happen. I looked into the padscore.rpl of ALL firmwares.
gSamplingCallback = NULL;
}
}
printf("ControllerPatcher::Init(line %d): Found the gSamplingCallback at %08X \n",__LINE__,gSamplingCallback);
if(HID_DEBUG){ printf("ControllerPatcher::Init(line %d): Init called! \n",__LINE__); }
/* if(syshid_handle == 0){
printf("ControllerPatcher::Init(line %d): Failed to load the HID API \n",__LINE__);
return false;
}*/
if(gConfig_done == HID_INIT_NOT_DONE){
if(HID_DEBUG){ printf("ControllerPatcher::Init(line %d): First time calling the Init\n",__LINE__); }
gConfig_done = HID_INIT_DONE;
ControllerPatcher::ResetConfig();
}else{
if(HID_DEBUG){ printf("ControllerPatcher::Init(line %d): ControllerPatcher::Init(): Config already done!\n",__LINE__); }
}
//Broken
if(gConfig_done != HID_SDCARD_READ){
printf("ControllerPatcher::Init(line %d): Reading config files from SD Card\n",__LINE__);
ConfigReader* reader = ConfigReader::getInstance();
s32 status = 0;
if((status = reader->InitSDCard()) == 0){
if(HID_DEBUG){ printf("ControllerPatcher::Init(line %d): SD Card mounted for controller config!\n",__LINE__); }
reader->ReadAllConfigs();
printf("ControllerPatcher::Init(line %d): Done with reading config files from SD Card\n",__LINE__);
gConfig_done = HID_SDCARD_READ;
}else{
printf("ControllerPatcher::Init(line %d): SD mounting failed! %d\n",__LINE__,status);
}
ConfigReader::destroyInstance();
}
printf("ControllerPatcher::Init(line %d): Initializing the data for button remapping\n",__LINE__);
InitButtonMapping();
if(!gHIDAttached){
HIDAddClient(&gHIDClient, ControllerPatcherHID::myAttachDetachCallback);
}
return true;
}
void ControllerPatcher::startNetworkServer(){
UDPServer::getInstance();
TCPServer::getInstance();
}
void ControllerPatcher::stopNetworkServer(){
UDPServer::destroyInstance();
UDPClient::destroyInstance();
TCPServer::destroyInstance();
}
void ControllerPatcher::DeInit(){
if(HID_DEBUG){ printf("ControllerPatcher::DeInit(line %d) called! \n",__LINE__); }
if(gHIDAttached) HIDDelClient(&gHIDClient);
//Resetting the state of the last pressed data.
buttonRemapping_lastButtonsHold = 0;
memset(last_button_hold,0,sizeof(last_button_hold));
memset(myVPADBuffer,0,sizeof(myVPADBuffer));
memset(&gControllerMapping,0,sizeof(gControllerMapping));
memset(&gHIDClient,0,sizeof(gHIDClient));
memset(gHID_Devices,0,sizeof(gHID_Devices));
memset(gGamePadValues,0,sizeof(gGamePadValues));
memset(config_controller,0,sizeof(config_controller));
memset(config_controller_hidmask,0,sizeof(config_controller_hidmask));
memset(gNetworkController,0,sizeof(gNetworkController));
memset(connectionOrderHelper,0,sizeof(connectionOrderHelper));
memset(gWPADConnectCallback,0,sizeof(gWPADConnectCallback));
memset(gKPADConnectCallback,0,sizeof(gKPADConnectCallback));
memset(gExtensionCallback,0,sizeof(gExtensionCallback));
gCallbackCooldown = 0;
gConfig_done = HID_INIT_NOT_DONE;
gButtonRemappingConfigDone = 0;
gHIDAttached = 0;
gHIDCurrentDevice = 0;
gHIDRegisteredDevices = 0;
gHID_Mouse_Mode = HID_MOUSE_MODE_TOUCH;
gHID_LIST_GC = 0;
gHID_LIST_DS3 = 0;
gHID_LIST_DS4 = 0;
gHID_LIST_KEYBOARD = 0;
gHID_LIST_MOUSE = 0;
gHID_LIST_SWITCH_PRO = 0;
gGamePadSlot = 0;
gHID_SLOT_GC = 0;
gHID_SLOT_KEYBOARD = 0;
gMouseSlot = 0;
gOriginalDimState = 0;
gOriginalAPDState = 0;
gHIDNetworkClientID = 0;
destroyConfigHelper();
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::enableControllerMapping(){
gControllerMapping.gamepad.useAll = 0;
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::disableControllerMapping(){
gControllerMapping.gamepad.useAll = 1;
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::disableWiiUEnergySetting(){
s32 res;
if(IMIsDimEnabled(&res) == 0){
if(res == 1){
if(HID_DEBUG){ printf("ControllerPatcher::disableWiiUEnergySetting(): Dim was orignally enabled!\n"); }
gOriginalDimState = 1;
}
}
if(IMIsAPDEnabled(&res) == 0){
if(res == 1){
if(HID_DEBUG){ printf("ControllerPatcher::disableWiiUEnergySetting(): Auto power down was orignally enabled!\n"); }
gOriginalAPDState = 1;
}
}
IMDisableDim();
IMDisableAPD();
printf("ControllerPatcher::disableWiiUEnergySetting(): Disable Energy savers\n");
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::restoreWiiUEnergySetting(){
//Check if we need to enable Auto Power down again on exiting
if(gOriginalAPDState == 1){
printf("ControllerPatcher::restoreWiiUEnergySetting(): Auto shutdown was on before using HID to VPAD. Setting it to on again.\n");
IMEnableAPD();
}
if(gOriginalDimState == 1){
printf("ControllerPatcher::restoreWiiUEnergySetting(): Burn-in reduction was on before using HID to VPAD. Setting it to on again.\n");
IMEnableDim();
}
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::resetControllerMapping(UController_Type type){
ControllerMappingPAD * cm_map_pad = ControllerPatcherUtils::getControllerMappingByType(type);
if(cm_map_pad == NULL){return CONTROLLER_PATCHER_ERROR_NULL_POINTER;}
memset(cm_map_pad,0,sizeof(*cm_map_pad));
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::addControllerMapping(UController_Type type,ControllerMappingPADInfo config){
ControllerMappingPAD * cm_map_pad = ControllerPatcherUtils::getControllerMappingByType(type);
s32 result = 0;
for(s32 i=0;i<HID_MAX_DEVICES_PER_SLOT;i++){
ControllerMappingPADInfo * info = &(cm_map_pad->pad_infos[i]);
if(info != NULL && !info->active){
info->active = 1;
info->pad = config.pad;
info->type = config.type;
info->vidpid.vid = config.vidpid.vid;
info->vidpid.pid = config.vidpid.pid;
result = 1;
break;
}
}
if(result == 0){
//No free slot.
return -1;
}
return CONTROLLER_PATCHER_ERROR_NONE;
}
s32 ControllerPatcher::getActiveMappingSlot(UController_Type type){
ControllerMappingPAD * cm_map_pad = ControllerPatcherUtils::getControllerMappingByType(type);
if(cm_map_pad == NULL){return -1;}
s32 connected = -1;
for(s32 i =0;i<HID_MAX_DEVICES_PER_SLOT;i++){
if(cm_map_pad->pad_infos[i].active || cm_map_pad->pad_infos[i].type == CM_Type_RealController){
connected = i;
break;
}
}
return connected;
}
bool ControllerPatcher::isControllerConnectedAndActive(UController_Type type,s32 mapping_slot){
ControllerMappingPADInfo * padinfo = getControllerMappingInfo(type,mapping_slot);
if(!padinfo){
return false;
}
if(padinfo->active){
DeviceInfo device_info;
memset(&device_info,0,sizeof(device_info));
device_info.vidpid = padinfo->vidpid;
s32 res;
if((res = ControllerPatcherUtils::getDeviceInfoFromVidPid(&device_info)) < 0){
return false;
}
u32 hidmask = device_info.slotdata.hidmask;
u32 pad = padinfo->pad;
HID_Data * data_cur;
if((res = ControllerPatcherHID::getHIDData(hidmask,pad,&data_cur)) < 0) {
return false;
}
return true;
}
return false;
}
ControllerMappingPADInfo * ControllerPatcher::getControllerMappingInfo(UController_Type type,s32 mapping_slot){
ControllerMappingPAD * cm_map_pad = ControllerPatcherUtils::getControllerMappingByType(type);
if(cm_map_pad == NULL){return NULL;}
if(mapping_slot < 0 || mapping_slot > HID_MAX_DEVICES_PER_SLOT-1){ return NULL;}
return &(cm_map_pad->pad_infos[mapping_slot]);
}
HID_Mouse_Data * ControllerPatcher::getMouseData(){
ControllerMappingPAD * CMPAD = ControllerPatcherUtils::getControllerMappingByType(UController_Type_Gamepad);
if(CMPAD == NULL){
return NULL;
}
HID_Mouse_Data * result = NULL;
for(s32 i;i<HID_MAX_DEVICES_PER_SLOT;i++){
ControllerMappingPADInfo * padinfo = &(CMPAD->pad_infos[i]);
if(!padinfo->active){
break;
}
if(padinfo->type == CM_Type_Mouse){
result = &(gHID_Devices[gMouseSlot].pad_data[padinfo->pad].data_union.mouse.cur_mouse_data);
}
}
return result;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::setRumble(UController_Type type,u32 status){
ControllerMappingPAD * cm_map_pad = ControllerPatcherUtils::getControllerMappingByType(type);
if(cm_map_pad == NULL){return -1;}
cm_map_pad->rumble = !!status; //to make sure it's only 0 or 1.
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::gettingInputAllDevices(InputData * output,s32 array_size){
HID_Data * data_cur;
VPADStatus pad_buffer;
VPADStatus * buffer = &pad_buffer;
s32 result = CONTROLLER_PATCHER_ERROR_NONE;
std::map<my_cb_user *,s32> pad_count;
//printf("fill in data\n");
for(s32 i = 0;i < gHIDMaxDevices;i++){
u8 * status = &output[result].status;
*status = 0;
if(connectionOrderHelper[i] != NULL){
*status = 1;
my_cb_user * usr = connectionOrderHelper[i];
pad_count[usr] = pad_count[usr] +1;
s32 hid = usr->slotdata.hidmask;
//printf("result[%d] usr: %08X\n",result,usr);
s32 realpad = pad_count[usr] - 1;
output[result].device_info.pad_count = usr->pads_per_device;
output[result].device_info.slotdata = usr->slotdata;
output[result].device_info.vidpid = usr->vidpid;
InputButtonData * buttondata = &output[result].button_data;
InputStickData * stickdata = &output[result].stick_data;
s32 buttons_hold = 0;
buttondata->hold = 0;
buttondata->trigger = 0;
buttondata->release = 0;
s32 res;
if((res = ControllerPatcherHID::getHIDData(hid,realpad,&data_cur)) == 0){
res = ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_A);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_B);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_X);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_Y);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_LEFT);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_RIGHT);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_DOWN);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_UP);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_MINUS);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_L);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_R);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_PLUS);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_ZL);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_ZR);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_HOME);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_STICK_L);
ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_STICK_R);
buttondata->hold |= buttons_hold;
buttondata->trigger |= (buttons_hold & (~(data_cur->last_buttons)));
buttondata->release |= ((data_cur->last_buttons) & (~buttons_hold));
buffer->leftStick.x = 0.0f;
buffer->leftStick.y = 0.0f;
buffer->rightStick.x = 0.0f;
buffer->rightStick.y = 0.0f;
ControllerPatcherUtils::convertAnalogSticks(data_cur,buffer);
ControllerPatcherUtils::normalizeStickValues(&(buffer->leftStick));
ControllerPatcherUtils::normalizeStickValues(&(buffer->rightStick));
stickdata->leftStickX = buffer->leftStick.x;
stickdata->leftStickY = buffer->leftStick.y;
stickdata->rightStickX = buffer->rightStick.x;
stickdata->rightStickY = buffer->rightStick.y;
//printf("result[%d] buttons %08X\n",result,buttons_hold);
data_cur->last_buttons = buttons_hold;
}
}
result++;
if(result >= array_size){
break;
}
}
return result;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::setProControllerDataFromHID(void * data,s32 chan, s32 mode){
if(data == NULL) return CONTROLLER_PATCHER_ERROR_NULL_POINTER;
if(chan < 0 || chan > 3) return CONTROLLER_PATCHER_ERROR_INVALID_CHAN;
//if(gControllerMapping.proController[chan].enabled == 0) return CONTROLLER_PATCHER_ERROR_MAPPING_DISABLED;
VPADStatus * vpad_buffer = &myVPADBuffer[chan];
memset(vpad_buffer,0,sizeof(*vpad_buffer));
std::vector<HID_Data *> data_list;
for(s32 i = 0;i<HID_MAX_DEVICES_PER_SLOT;i++){
ControllerMappingPADInfo cm_map_pad_info = gControllerMapping.proController[chan].pad_infos[i];
if(!cm_map_pad_info.active){
continue;
}
DeviceInfo device_info;
memset(&device_info,0,sizeof(device_info));
device_info.vidpid = cm_map_pad_info.vidpid;
s32 res;
if((res = ControllerPatcherUtils::getDeviceInfoFromVidPid(&device_info)) < 0){
printf("ControllerPatcherUtils::getDeviceInfoFromVidPid(&device_info) = %d\n",res);
continue;
}
s32 hidmask = device_info.slotdata.hidmask;
s32 pad = cm_map_pad_info.pad;
HID_Data * data_cur;
if((res = ControllerPatcherHID::getHIDData(hidmask,pad,&data_cur)) < 0) {
//printf("ControllerPatcherHID::getHIDData(hidmask,pad,&data_cur)) = %d\n",res);
continue;
}
data_list.push_back(data_cur);
}
if(data_list.empty()){
return CONTROLLER_PATCHER_ERROR_FAILED_TO_GET_HIDDATA;
}
s32 res = 0;
if((res = ControllerPatcherHID::setVPADControllerData(vpad_buffer,data_list)) < 0) return res;
//make it configurable?
//ControllerPatcher::printVPADButtons(vpad_buffer); //Leads to random crashes on transitions.
//a bit hacky?
if(mode == PRO_CONTROLLER_MODE_KPADDATA){
KPADData * pro_buffer = (KPADData *) data;
if((res = ControllerPatcherUtils::translateToPro(vpad_buffer,pro_buffer,&last_button_hold[chan])) < 0 ) return res;
}else if(mode == PRO_CONTROLLER_MODE_WPADReadData){
WPADReadData * pro_buffer = (WPADReadData *) data;
if((res = ControllerPatcherUtils::translateToProWPADRead(vpad_buffer,pro_buffer)) < 0 ) return res;
}
for(std::vector<HID_Data *>::iterator it = data_list.begin(); it != data_list.end(); ++it) {
HID_Data * cur_ptr = *it;
cur_ptr->rumbleActive = !!gControllerMapping.proController[chan].rumble;
}
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::setControllerDataFromHID(VPADStatus * buffer){
if(buffer == NULL) return CONTROLLER_PATCHER_ERROR_NULL_POINTER;
//if(gControllerMapping.gamepad.enabled == 0) return CONTROLLER_PATCHER_ERROR_MAPPING_DISABLED;
s32 hidmask = 0;
s32 pad = 0;
ControllerMappingPAD cm_map_pad = gControllerMapping.gamepad;
std::vector<HID_Data *> data_list;
if (cm_map_pad.useAll == 1) {
data_list = ControllerPatcherHID::getHIDDataAll();
}else{
for(s32 i = 0;i<HID_MAX_DEVICES_PER_SLOT;i++){
ControllerMappingPADInfo cm_map_pad_info = cm_map_pad.pad_infos[i];
if(cm_map_pad_info.active){
DeviceInfo device_info;
memset(&device_info,0,sizeof(device_info));
device_info.vidpid = cm_map_pad_info.vidpid;
if(ControllerPatcherUtils::getDeviceInfoFromVidPid(&device_info) < 0){
continue;
//return CONTROLLER_PATCHER_ERROR_UNKNOWN_VID_PID;
}
hidmask = device_info.slotdata.hidmask;
HID_Data * data;
pad = cm_map_pad_info.pad;
s32 res = ControllerPatcherHID::getHIDData(hidmask,pad,&data);
if(res < 0){
continue;
//return CONTROLLER_PATCHER_ERROR_FAILED_TO_GET_HIDDATA;
}
if(data != NULL) data_list.push_back(data);
}
}
}
if(data_list.empty()){
return CONTROLLER_PATCHER_ERROR_FAILED_TO_GET_HIDDATA;
}
ControllerPatcherHID::setVPADControllerData(buffer,data_list);
for(u32 i = 0; i < data_list.size();i++){
data_list[i]->rumbleActive = !!gControllerMapping.gamepad.rumble;
}
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::printVPADButtons(VPADStatus * buffer){
return CONTROLLER_PATCHER_ERROR_NONE;
/* BROKEN on transitions.*/
if(buffer == NULL) return CONTROLLER_PATCHER_ERROR_NULL_POINTER;
if(buffer->trigger != 0x00000000){
char output[250];
output[0] = 0; //null terminate it. just in case.
if((buffer->trigger & VPAD_BUTTON_A) == VPAD_BUTTON_A) strcat(output,"A ");
if((buffer->trigger & VPAD_BUTTON_B) == VPAD_BUTTON_B) strcat(output,"B ");
if((buffer->trigger & VPAD_BUTTON_X) == VPAD_BUTTON_X) strcat(output,"X ");
if((buffer->trigger & VPAD_BUTTON_Y) == VPAD_BUTTON_Y) strcat(output,"Y ");
if((buffer->trigger & VPAD_BUTTON_L) == VPAD_BUTTON_L) strcat(output,"L ");
if((buffer->trigger & VPAD_BUTTON_R) == VPAD_BUTTON_R) strcat(output,"R ");
if((buffer->trigger & VPAD_BUTTON_ZR) == VPAD_BUTTON_ZR) strcat(output,"ZR ");
if((buffer->trigger & VPAD_BUTTON_ZL) == VPAD_BUTTON_ZL) strcat(output,"ZL ");
if((buffer->trigger & VPAD_BUTTON_LEFT) == VPAD_BUTTON_LEFT) strcat(output,"Left ");
if((buffer->trigger & VPAD_BUTTON_RIGHT) == VPAD_BUTTON_RIGHT) strcat(output,"Right ");
if((buffer->trigger & VPAD_BUTTON_UP) == VPAD_BUTTON_UP) strcat(output,"Up ");
if((buffer->trigger & VPAD_BUTTON_DOWN) == VPAD_BUTTON_DOWN) strcat(output,"Down ");
if((buffer->trigger & VPAD_BUTTON_PLUS) == VPAD_BUTTON_PLUS) strcat(output,"+ ");
if((buffer->trigger & VPAD_BUTTON_MINUS) == VPAD_BUTTON_MINUS) strcat(output,"- ");
if((buffer->trigger & VPAD_BUTTON_TV) == VPAD_BUTTON_TV) strcat(output,"TV ");
if((buffer->trigger & VPAD_BUTTON_HOME) == VPAD_BUTTON_HOME) strcat(output,"HOME ");
if((buffer->trigger & VPAD_BUTTON_STICK_L) == VPAD_BUTTON_STICK_L) strcat(output,"SL ");
if((buffer->trigger & VPAD_BUTTON_STICK_R) == VPAD_BUTTON_STICK_R) strcat(output,"SR ");
if((buffer->trigger & VPAD_STICK_R_EMULATION_LEFT) == VPAD_STICK_R_EMULATION_LEFT) strcat(output,"RE_Left ");
if((buffer->trigger & VPAD_STICK_R_EMULATION_RIGHT) == VPAD_STICK_R_EMULATION_RIGHT) strcat(output,"RE_Right ");
if((buffer->trigger & VPAD_STICK_R_EMULATION_UP) == VPAD_STICK_R_EMULATION_UP) strcat(output,"RE_Up ");
if((buffer->trigger & VPAD_STICK_R_EMULATION_DOWN) == VPAD_STICK_R_EMULATION_DOWN) strcat(output,"RE_Down ");
if((buffer->trigger & VPAD_STICK_L_EMULATION_LEFT) == VPAD_STICK_L_EMULATION_LEFT) strcat(output,"LE_Left ");
if((buffer->trigger & VPAD_STICK_L_EMULATION_RIGHT) == VPAD_STICK_L_EMULATION_RIGHT) strcat(output,"LE_Right ");
if((buffer->trigger & VPAD_STICK_L_EMULATION_UP) == VPAD_STICK_L_EMULATION_UP) strcat(output,"LE_Up ");
if((buffer->trigger & VPAD_STICK_L_EMULATION_DOWN) == VPAD_STICK_L_EMULATION_DOWN) strcat(output,"LE_Down ");
printf("%spressed Sticks: LX %f LY %f RX %f RY %f\n",output,buffer->leftStick.x,buffer->leftStick.y,buffer->rightStick.x,buffer->rightStick.y);
}
return CONTROLLER_PATCHER_ERROR_NONE;
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::buttonRemapping(VPADStatus * buffer,s32 buffer_count){
if(!gButtonRemappingConfigDone) return CONTROLLER_PATCHER_ERROR_CONFIG_NOT_DONE;
if(buffer == NULL) return CONTROLLER_PATCHER_ERROR_NULL_POINTER;
for(s32 i = 0;i < buffer_count;i++){
VPADStatus new_data;
memset(&new_data,0,sizeof(new_data));
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_A, CONTRPS_VPAD_BUTTON_A);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_B, CONTRPS_VPAD_BUTTON_B);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_X, CONTRPS_VPAD_BUTTON_X);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_Y, CONTRPS_VPAD_BUTTON_Y);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_LEFT, CONTRPS_VPAD_BUTTON_LEFT);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_RIGHT, CONTRPS_VPAD_BUTTON_RIGHT);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_UP, CONTRPS_VPAD_BUTTON_UP);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_DOWN, CONTRPS_VPAD_BUTTON_DOWN);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_ZL, CONTRPS_VPAD_BUTTON_ZL);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_ZR, CONTRPS_VPAD_BUTTON_ZR);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_L, CONTRPS_VPAD_BUTTON_L);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_R, CONTRPS_VPAD_BUTTON_R);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_PLUS, CONTRPS_VPAD_BUTTON_PLUS);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_MINUS, CONTRPS_VPAD_BUTTON_MINUS);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_HOME, CONTRPS_VPAD_BUTTON_HOME);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_SYNC, CONTRPS_VPAD_BUTTON_SYNC);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_STICK_R, CONTRPS_VPAD_BUTTON_STICK_R);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_STICK_L, CONTRPS_VPAD_BUTTON_STICK_L);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_BUTTON_TV, CONTRPS_VPAD_BUTTON_TV);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_LEFT, CONTRPS_VPAD_STICK_R_EMULATION_LEFT);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_RIGHT, CONTRPS_VPAD_STICK_R_EMULATION_RIGHT);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_UP, CONTRPS_VPAD_STICK_R_EMULATION_UP);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_DOWN, CONTRPS_VPAD_STICK_R_EMULATION_DOWN);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_LEFT, CONTRPS_VPAD_STICK_L_EMULATION_LEFT);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_RIGHT, CONTRPS_VPAD_STICK_L_EMULATION_RIGHT);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_UP, CONTRPS_VPAD_STICK_L_EMULATION_UP);
ControllerPatcherUtils::setButtonRemappingData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_DOWN, CONTRPS_VPAD_STICK_L_EMULATION_DOWN);
//Even when you remap any Stick Emulation to a button, we still want to keep the emulated stick data. Some games like New Super Mario Bros. only work with the emulated stick data.
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_LEFT, VPAD_STICK_L_EMULATION_LEFT);
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_RIGHT, VPAD_STICK_L_EMULATION_RIGHT);
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_UP, VPAD_STICK_L_EMULATION_UP);
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_L_EMULATION_DOWN, VPAD_STICK_L_EMULATION_DOWN);
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_LEFT, VPAD_STICK_R_EMULATION_LEFT);
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_RIGHT, VPAD_STICK_R_EMULATION_RIGHT);
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_UP, VPAD_STICK_R_EMULATION_UP);
ControllerPatcherUtils::setButtonData(&buffer[i],&new_data,VPAD_STICK_R_EMULATION_DOWN, VPAD_STICK_R_EMULATION_DOWN);
buffer[i].hold = new_data.hold;
buffer[i].trigger = new_data.trigger;
buffer[i].release = new_data.release;
}
return CONTROLLER_PATCHER_ERROR_NONE;
}
std::string ControllerPatcher::getIdentifierByVIDPID(u16 vid,u16 pid){
return ConfigValues::getStringByVIDPID(vid,pid);
}
void ControllerPatcher::destroyConfigHelper(){
ConfigReader::destroyInstance();
ConfigValues::destroyInstance();
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::doSamplingForDeviceSlot(u16 device_slot){
return ControllerPatcherUtils::doSampling(device_slot,0,true);
}
CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcher::setRumbleActivated(bool value){
gGlobalRumbleActivated = value;
return CONTROLLER_PATCHER_ERROR_NONE;
}
bool ControllerPatcher::isRumbleActivated(){
return gGlobalRumbleActivated;
}
| 81.735971 | 224 | 0.699675 | [
"vector"
] |
7f7aab6ddd70bd86464b7a84b18836c3aa33bca2 | 461 | cpp | C++ | HouseRobber.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | 3 | 2017-11-27T03:01:50.000Z | 2021-03-13T08:14:00.000Z | HouseRobber.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | null | null | null | HouseRobber.cpp | yplusplus/LeetCode | 122bd31b291af1e97ee4e9349a8e65bba6e04c96 | [
"MIT"
] | null | null | null | class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
vector<int> dp(n, 0);
for (int i = 0; i < n; i++) {
if (i - 2 >= 0)
dp[i] = max(dp[i], dp[i - 2]);
if (i - 3 >= 0)
dp[i] = max(dp[i], dp[i - 3]);
dp[i] += nums[i];
}
return max(dp[n - 2], dp[n - 1]);
}
}; | 27.117647 | 46 | 0.349241 | [
"vector"
] |
7f7e3cfe66b6f11c0c770e31b0d3f7c913d10bfc | 1,584 | cpp | C++ | src/MockSerialPort.cpp | oddguid/visualstatus | 0ac831dfb5ce65e5885e06f041b2fd2162a0287a | [
"MIT"
] | null | null | null | src/MockSerialPort.cpp | oddguid/visualstatus | 0ac831dfb5ce65e5885e06f041b2fd2162a0287a | [
"MIT"
] | null | null | null | src/MockSerialPort.cpp | oddguid/visualstatus | 0ac831dfb5ce65e5885e06f041b2fd2162a0287a | [
"MIT"
] | null | null | null | #include "MockSerialPort.h"
MockSerialPort::MockSerialPort(QObject *parent)
: BaseSerialPort(parent)
, m_isOpen(false)
{
}
MockSerialPort::~MockSerialPort()
{
}
bool MockSerialPort::open(const QString &deviceName, unsigned int baudrate,
unsigned short timeoutSecs)
{
Q_UNUSED(deviceName);
Q_UNUSED(baudrate);
Q_UNUSED(timeoutSecs);
m_error.clear();
m_isOpen = true;
return m_isOpen;
}
bool MockSerialPort::isOpen()
{
return m_isOpen;
}
bool MockSerialPort::close()
{
m_error.clear();
m_isOpen = false;
return true;
}
bool MockSerialPort::setTimeout(unsigned short timeoutSecs)
{
Q_UNUSED(timeoutSecs);
m_error.clear();
return true;
}
bool MockSerialPort::write(const QString &data)
{
m_error.clear();
if (m_isOpen)
{
// emit the data
emit writtenData(data);
return true;
}
// port not open
m_error = tr("Cannot write data, serial port is closed.");
return false;
}
bool MockSerialPort::writeRaw(const QByteArray &data)
{
m_error.clear();
if (m_isOpen)
{
// emit the data
emit writtenRawData(data);
return true;
}
// port not open
m_error = tr("Cannot write data, serial port is closed.");
return false;
}
QScriptValue mockSerialPortConstructor(QScriptContext *context,
QScriptEngine *engine)
{
// parent of new object is in context
QObject *parent = context->argument(0).toQObject();
// create new MockSerialPort object
QObject *object = new MockSerialPort(parent);
// pass object to script
return engine->newQObject(object, QScriptEngine::ScriptOwnership);
}
| 16.163265 | 75 | 0.70202 | [
"object"
] |
7fa16e88a43ccb4d903ed8d6f875dd26974719f9 | 19,251 | cpp | C++ | Fields/ParticleFieldMaster.cpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | Fields/ParticleFieldMaster.cpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | Fields/ParticleFieldMaster.cpp | danielfrascarelli/esys-particle | e56638000fd9c4af77e21c75aa35a4f8922fd9f0 | [
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////
// //
// Copyright (c) 2003-2017 by The University of Queensland //
// Centre for Geoscience Computing //
// http://earth.uq.edu.au/centre-geoscience-computing //
// //
// Primary Business: Brisbane, Queensland, Australia //
// Licensed under the Open Software License version 3.0 //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
/////////////////////////////////////////////////////////////
// --- TML includes ---
#include "tml/comm/comm.h"
// --- Project includes ---
#include "ParticleFieldMaster.h"
#include "field_const.h"
//--- IO includes ---
#include <iostream>
#include <fstream>
//--- STL inculdes ---
#include <string>
#include <map>
using std::cout;
using std::endl;
using std::ofstream;
using std::string;
using std::multimap;
//==== SCALAR PFM ===
/*!
Constructor. Set up the Master and broadcast parameters to the slaves.
\param comm the communicator
\param fieldname the name of the field to be saved
\param filename the name of the file to be saved into or the base for the generation of the filenames if the saving format requires multiple files
\param savetype the way to save data, currently supported are DX,SUM
\param t0 the first timestep to be saved
\param tend the last timestep to be saved
\param dt the interval between timesteps to be saving
*/
ScalarParticleFieldMaster::ScalarParticleFieldMaster(TML_Comm* comm,const string& fieldname,const string& filename,const string& savetype,int t0,int tend,int dt)
:AFieldMaster(comm,fieldname,filename,savetype,t0,tend,dt)
{
m_comm->broadcast_cont(fieldname);
m_comm->broadcast(m_id);
int is_tagged=0;
m_comm->broadcast(is_tagged);
}
/*!
Constructor. Set up the Master and broadcast parameters to the slaves.
\param comm the communicator
\param fieldname the name of the field to be saved
\param filename the name of the file to be saved into or the base for the generation of the filenames if the saving format requires multiple files
\param savetype the way to save data, currently supported are DX,SUM
\param t0 the first timestep to be saved
\param tend the last timestep to be saved
\param dt the interval between timesteps to be saving
\param tag the tag of the particles to be saved
\param mask the mask to be applied to the tag
*/
ScalarParticleFieldMaster::ScalarParticleFieldMaster(TML_Comm* comm,const string& fieldname,const string& filename,const string& savetype,int t0,int tend,int dt,int tag,int mask):AFieldMaster(comm,fieldname,filename,savetype,t0,tend,dt)
{
m_comm->broadcast_cont(fieldname);
m_comm->broadcast(m_id);
int is_tagged=1;
m_comm->broadcast(is_tagged);
m_comm->broadcast(tag);
m_comm->broadcast(mask);
}
void ScalarParticleFieldMaster::collect()
{
// send field id to slave
m_comm->broadcast(m_id);
if((m_write_type==WRITE_TYPE_SUM)||(m_write_type==WRITE_TYPE_MAX)) {
collectSum();
} else {
collectFull();
}
}
/*!
collect the full set of data, i.e. value, and posn,size of particles
*/
void ScalarParticleFieldMaster::collectFull()
{
multimap<int,pair<int,double> > temp_mm;
multimap<int,pair<int,Vec3> > temp_pos_mm;
multimap<int,pair<int,double> > temp_rad_mm;
// send type of collect to slaves
int coll_type=1;
m_comm->broadcast(coll_type);
// get data from slaves
m_comm->gather(temp_mm);
m_comm->gather(temp_pos_mm);
m_comm->gather(temp_rad_mm);
// collate receive data from multimap into single map
for(multimap<int,pair<int,double> >::iterator iter=temp_mm.begin();
iter!=temp_mm.end();
iter++){
m_save_map.insert(iter->second);
}
for(multimap<int,pair<int,Vec3> >::iterator iter=temp_pos_mm.begin();
iter!=temp_pos_mm.end();
iter++){
m_pos_map.insert(iter->second);
}
for(multimap<int,pair<int,double> >::iterator iter=temp_rad_mm.begin();
iter!=temp_rad_mm.end();
iter++){
m_rad_map.insert(iter->second);
}
}
/*!
collect sum of values only
*/
void ScalarParticleFieldMaster::collectSum()
{
multimap<int,double> temp_mm;
// send type of collect to slaves
m_comm->broadcast(m_write_type);
// get data from slaves
m_comm->gather(temp_mm);
// collate receive data from multimap into single map
for(multimap<int,double>::iterator iter=temp_mm.begin();
iter!=temp_mm.end();
iter++){
m_save_map.insert(*iter);
}
}
/*!
write data out as OpenDX compatible file
\todo desciption
*/
void ScalarParticleFieldMaster::writeAsDX()
{
//generate filename
string fn=makeFilename();
// write header
ofstream out_file(fn.c_str());
out_file << "points = " << m_save_map.size() << endl;
out_file << "format = ascii" << endl;
out_file << "dependency = positions, positions" << endl;
out_file << "interleaving = field" << endl;
out_file << "field = locations, " << m_field_name << endl;
out_file << "structure = 3-vector, scalar" << endl;
out_file << "type = float, float " << endl;
out_file << "header = marker \"Start\\n\"" << endl;
out_file << endl << "end" << endl;
out_file << "Start" << endl;
// write data
for(map<int,double>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << m_pos_map[iter->first] << " " << iter->second << endl;
}
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
m_rad_map.erase(m_rad_map.begin(),m_rad_map.end());
}
/*!
write data out as Povray(>=3.0) compatible file
\warning not fully impl.
*/
void ScalarParticleFieldMaster::writeAsPOV()
{
//generate filename
string fn=makeFilename();
// open file
ofstream out_file(fn.c_str());
// work out object size
Vec3 vmin,vmax;
for(map<int,Vec3>::iterator iter=m_pos_map.begin();
iter!=m_pos_map.end();
iter++){
vmin=cmin(vmin,iter->second);
vmax=cmax(vmax,iter->second);
}
// fit camera position
//Vec3 lookat=0.5*(vmin+vmax);
// write camera etc.
out_file << "#include \"colors.inc\"" << endl;
out_file << "background { color Black }" << endl;
out_file << " camera {" << endl;
out_file << "location <0, 2, -3>" << endl;
out_file << "look_at <0, 1, 2>" << endl;
out_file << "}" << endl<< endl;
out_file << "light_source { <2, 4, -3> color White}" << endl;
// write particles
for(map<int,double>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << "sphere { <" << m_pos_map[iter->first].X() << " , "
<< m_pos_map[iter->first].Y() << " , "
<< m_pos_map[iter->first].Z() << " > , "
<< m_rad_map[iter->first] << endl;
out_file << " texture { rgb < 1.0,0.5,0.5 > } }" << endl; //<< iter->second << endl;
}
// close file
out_file.close();
}
/*!
write data out as SILO file (if supported)
*/
void ScalarParticleFieldMaster::writeAsSILO()
{
#if HAVE_SILO
bool append;
DBfile* dbfile = openSiloFile(append);
if (!dbfile) {
console.Error() << "writeAsSILO not supported";
return;
}
// prepare data
std::vector<float> x, y, z, radius, data;
x.clear(); y.clear(); z.clear(); radius.clear(); data.clear();
for (map<int,double>::iterator iter=m_save_map.begin();
iter != m_save_map.end();
iter++) {
// the mesh is only needed if we are not appending
if (!append) {
const Vec3& v = m_pos_map[iter->first];
x.push_back(v.X());
y.push_back(v.Y());
z.push_back(v.Z());
}
radius.push_back(m_rad_map[iter->first]);
data.push_back(iter->second);
}
// write mesh first if needed
if (!append) {
float* coords[] = { &x[0], &y[0], &z[0] };
DBPutPointmesh(dbfile, "mesh", 3, coords, m_save_map.size(),
DB_FLOAT, NULL);
}
// and now the fields
DBPutPointvar1(dbfile, "radius", "mesh", &radius[0], radius.size(),
DB_FLOAT, NULL);
DBPutPointvar1(dbfile, m_field_name.c_str(), "mesh", &data[0],
data.size(), DB_FLOAT, NULL);
// close file
DBClose(dbfile);
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
m_rad_map.erase(m_rad_map.begin(),m_rad_map.end());
#else
console.Error() << "writeAsSILO not supported\n";
#endif
}
/*!
sum data and write them out into a single continuous file
\warning n
*/
void ScalarParticleFieldMaster::writeAsSUM()
{
// sum data
double sum_data=0.0;
for(map<int,double>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
sum_data+=iter->second;
}
// open file for appending
ofstream out_file(m_file_name.c_str(),ios::app);
// write data
out_file << sum_data << endl;
// close file
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
m_rad_map.erase(m_rad_map.begin(),m_rad_map.end());
}
/*!
find max datum and write it out into a single continuous file
*/
void ScalarParticleFieldMaster::writeAsMAX()
{
// get max data
double max_data=(m_save_map.begin())->second;
for(map<int,double>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
max_data=(iter->second > max_data) ? iter->second : max_data;
}
// open file for appending
ofstream out_file(m_file_name.c_str(),ios::app);
// write data
out_file << max_data << endl;
// close file
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
m_rad_map.erase(m_rad_map.begin(),m_rad_map.end());
}
/*!
write data as a raw series of values, one row of values per time step,
all timesteps into the same file
*/
void ScalarParticleFieldMaster::writeAsRAW_SERIES()
{
// open file
ofstream out_file(m_file_name.c_str(),ios::app);
// write data
for(map<int,double>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << iter->second << " ";
}
out_file << endl;
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
m_rad_map.erase(m_rad_map.begin(),m_rad_map.end());
}
/*!
write data as raw id, position, radius, value, one time step per file
*/
void ScalarParticleFieldMaster::writeAsRawWithPosID()
{
//generate filename
string fn=makeFilename();
// open file
ofstream out_file(fn.c_str());
// write data
for(map<int,double>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << iter->first << " " << m_pos_map[iter->first] << " " << m_rad_map[iter->first] << " "<< iter->second << endl;
}
// close file
out_file.close();
// clean up
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
m_rad_map.erase(m_rad_map.begin(),m_rad_map.end());
}
// === VECTOR PFM ===
/*!
Constructor. Set up the Master and broadcast parameters to the slaves.
\param comm the communicator
\param fieldname the name of the field to be saved
\param filename the name of the file to be saved into or the base for the generation of the filenames if the saving format requires multiple files
\param savetype the way to save data, currently supported are DX,SUM
\param t0 the first timestep to be saved
\param tend the last timestep to be saved
\param dt the interval between timesteps to be saving
*/
VectorParticleFieldMaster::VectorParticleFieldMaster(TML_Comm* comm,const string& fieldname,const string& filename,const string& savetype,int t0,int tend,int dt)
:AFieldMaster(comm,fieldname,filename,savetype,t0,tend,dt)
{
m_comm->broadcast_cont(fieldname);
m_comm->broadcast(m_id);
int is_tagged=0;
m_comm->broadcast(is_tagged);
}
/*!
Constructor. Set up the Master and broadcast parameters to the slaves.
\param comm the communicator
\param fieldname the name of the field to be saved
\param filename the name of the file to be saved into or the base for the generation of the filenames if the saving format requires multiple files
\param savetype the way to save data, currently supported are DX,SUM
\param t0 the first timestep to be saved
\param tend the last timestep to be saved
\param dt the interval between timesteps to be saving
\param tag the tag of the particles to be saved
\param mask the mask to be applied to the tag
*/
VectorParticleFieldMaster::VectorParticleFieldMaster(TML_Comm* comm,const string& fieldname,const string& filename,const string& savetype,int t0,int tend,int dt,int tag,int mask)
:AFieldMaster(comm,fieldname,filename,savetype,t0,tend,dt)
{
m_comm->broadcast_cont(fieldname);
m_comm->broadcast(m_id);
int is_tagged=1;
m_comm->broadcast(is_tagged);
m_comm->broadcast(tag);
m_comm->broadcast(mask);
}
void VectorParticleFieldMaster::collect()
{
multimap<int,pair<int,Vec3> > temp_mm;
multimap<int,pair<int,Vec3> > temp_pos_mm;
// send field id to slaves
m_comm->broadcast(m_id);
//receive data from fields
m_comm->gather(temp_mm);
m_comm->gather(temp_pos_mm);
// collate receive data from multimap into single map
for(multimap<int,pair<int,Vec3> >::iterator iter=temp_mm.begin();
iter!=temp_mm.end();
iter++){
m_save_map.insert(iter->second);
}
for(multimap<int,pair<int,Vec3> >::iterator iter=temp_pos_mm.begin();
iter!=temp_pos_mm.end();
iter++){
m_pos_map.insert(iter->second);
}
}
/*!
write data out as OpenDX compatible file
\todo desciption
*/
void VectorParticleFieldMaster::writeAsDX()
{
//generate filename
string fn=makeFilename();
// write header
ofstream out_file(fn.c_str());
out_file << "points = " << m_save_map.size() << endl;
out_file << "format = ascii" << endl;
out_file << "dependency = positions, positions" << endl;
out_file << "interleaving = field" << endl;
out_file << "field = locations, " << m_field_name << endl;
out_file << "structure = 3-vector, 3-vector" << endl;
out_file << "type = float, float " << endl;
out_file << "header = marker \"Start\\n\"" << endl;
out_file << endl << "end" << endl;
out_file << "Start" << endl;
// write data
for(map<int,Vec3>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << m_pos_map[iter->first] << " " << iter->second << endl;
}
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
}
/*!
write data out as Povray(>=3.0) compatible file
\warning not impl.
*/
void VectorParticleFieldMaster::writeAsPOV()
{
}
/*!
write data out as SILO file (if supported)
*/
void VectorParticleFieldMaster::writeAsSILO()
{
#if HAVE_SILO
bool append;
DBfile* dbfile = openSiloFile(append);
if (!dbfile) {
console.Error() << "writeAsSILO not supported";
return;
}
// prepare data
std::vector<float> x, y, z;
std::vector<float> vx, vy, vz;
x.clear(); y.clear(); z.clear();
vx.clear(); vy.clear(); vz.clear();
for (map<int,Vec3>::iterator iter=m_save_map.begin();
iter != m_save_map.end();
iter++) {
if (!append) {
const Vec3& m = m_pos_map[iter->first];
x.push_back(m.X());
y.push_back(m.Y());
z.push_back(m.Z());
}
const Vec3& v = iter->second;
vx.push_back(v.X());
vy.push_back(v.Y());
vz.push_back(v.Z());
}
// write mesh first if needed
if (!append) {
float* coords[] = { &x[0], &y[0], &z[0] };
DBPutPointmesh(dbfile, "mesh", 3, coords, m_save_map.size(),
DB_FLOAT, NULL);
}
float* vdata[] = { &vx[0], &vy[0], &vz[0] };
DBPutPointvar(dbfile, m_field_name.c_str(), "mesh", 3, vdata,
m_save_map.size(), DB_FLOAT, NULL);
// close file
DBClose(dbfile);
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
#else
console.Error() << "writeAsSILO not supported\n";
#endif
}
/*!
sum data and write them out into a single continuous file
\warning untested
*/
void VectorParticleFieldMaster::writeAsSUM()
{
Vec3 sum_data=Vec3(0.0,0.0,0.0);
for(map<int,Vec3>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
sum_data+=iter->second;
}
// open file for appending
ofstream out_file(m_file_name.c_str(),ios::app);
// write data
out_file << sum_data << endl;
// close file
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
}
/*!
get max datum and write it out into a single continuous file
\warning untested
*/
void VectorParticleFieldMaster::writeAsMAX()
{
Vec3 max_data=(m_save_map.begin())->second;
for(map<int,Vec3>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
max_data=(iter->second.norm2() > max_data.norm2()) ? iter->second : max_data;
}
// open file for appending
ofstream out_file(m_file_name.c_str(),ios::app);
// write data
out_file << max_data << endl;
// close file
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
}
/*!
write data as a raw series of values, one row of values per time step,
all timesteps into the same file
*/
void VectorParticleFieldMaster::writeAsRAW_SERIES()
{
// open file
ofstream out_file(m_file_name.c_str(),ios::app);
// write data
for(map<int,Vec3>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << iter->second << " ";
}
out_file << endl;
out_file.close();
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
}
/*!
write data as raw position, value pairs, one time step per file
*/
void VectorParticleFieldMaster::writeAsRAW2()
{
//generate filename
string fn=makeFilename();
// open file
ofstream out_file(fn.c_str());
// write data
for(map<int,Vec3>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << m_pos_map[iter->first] << " " << iter->second << endl;
}
// close file
out_file.close();
// clean up
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
}
/*!
write data as raw id, position, value triples, one time step per file
*/
void VectorParticleFieldMaster::writeAsRawWithID()
{
//generate filename
string fn=makeFilename();
// open file
ofstream out_file(fn.c_str());
// write data
for(map<int,Vec3>::iterator iter=m_save_map.begin();
iter!=m_save_map.end();
iter++){
out_file << iter->first << " " << m_pos_map[iter->first] << " " << iter->second << endl;
}
// close file
out_file.close();
// clean up
m_save_map.erase(m_save_map.begin(),m_save_map.end());
m_pos_map.erase(m_pos_map.begin(),m_pos_map.end());
}
| 28.52 | 236 | 0.656745 | [
"mesh",
"object",
"vector"
] |
7facb814a191f355130eaf73a9d6474b4a7e8341 | 8,884 | cc | C++ | src/artm_tests/scores_test.cc | MelLain/bigartm | 79126b68500bd5b378d6d6168f1b68eb03971bcb | [
"BSD-3-Clause"
] | 638 | 2015-02-03T22:17:00.000Z | 2022-03-23T18:47:50.000Z | src/artm_tests/scores_test.cc | MelLain/bigartm | 79126b68500bd5b378d6d6168f1b68eb03971bcb | [
"BSD-3-Clause"
] | 566 | 2015-01-01T21:49:00.000Z | 2022-02-14T09:14:35.000Z | src/artm_tests/scores_test.cc | bt2901/bigartm | 92c9d5746c122d0124bab700469d8a2a7f58ff40 | [
"BSD-3-Clause"
] | 148 | 2015-01-06T15:30:07.000Z | 2022-02-12T18:40:17.000Z | // Copyright 2017, Additive Regularization of Topic Models.
#include <memory>
#include "boost/filesystem.hpp"
#include "gtest/gtest.h"
#include "artm/cpp_interface.h"
#include "artm/core/common.h"
#include "artm/core/instance.h"
#include "artm_tests/test_mother.h"
#include "artm_tests/api.h"
// artm_tests.exe --gtest_filter=Scores.Perplexity
TEST(Scores, Perplexity) {
int nTokens = 60, nDocs = 10, nTopics = 10;
::artm::MasterModelConfig master_config_0 = ::artm::test::TestMother::GenerateMasterModelConfig(nTopics);
::artm::test::Helpers::ConfigurePerplexityScore("perplexity_1", &master_config_0, { },
{ artm::core::DefaultTransactionTypeName });
::artm::test::Helpers::ConfigurePerplexityScore("perplexity_2", &master_config_0, { });
master_config_0.add_transaction_typename(artm::core::DefaultTransactionTypeName);
::artm::MasterModel master_0(master_config_0);
::artm::test::Api api_0(master_0);
::artm::MasterModelConfig master_config_1 = ::artm::test::TestMother::GenerateMasterModelConfig(nTopics);
::artm::test::Helpers::ConfigurePerplexityScore("perplexity", &master_config_1, { "@error_class" });
::artm::MasterModel master_1(master_config_1);
::artm::test::Api api_1(master_1);
::artm::MasterModelConfig master_config_2 = ::artm::test::TestMother::GenerateMasterModelConfig(nTopics);
master_config_2.add_class_id("@default_class"); master_config_2.add_class_weight(1.0f);
master_config_2.add_class_id("@some_class"); master_config_2.add_class_weight(2.0f);
::artm::test::Helpers::ConfigurePerplexityScore("perplexity_1", &master_config_2, { });
::artm::test::Helpers::ConfigurePerplexityScore("perplexity_2", &master_config_2,
{ "@default_class", "@some_class" });
::artm::test::Helpers::ConfigurePerplexityScore("perplexity_3", &master_config_2, { "@default_class" });
::artm::test::Helpers::ConfigurePerplexityScore("perplexity_4", &master_config_2,
{ "@error_class", "@some_class" });
::artm::MasterModel master_2(master_config_2);
::artm::test::Api api_2(master_2);
::artm::MasterModelConfig master_config_3 = ::artm::test::TestMother::GenerateMasterModelConfig(nTopics);
::artm::test::Helpers::ConfigurePerplexityScore("perplexity", &master_config_3, { });
::artm::MasterModel master_3(master_config_3);
::artm::test::Api api_3(master_3);
// Generate doc-token matrix
artm::Batch batch = ::artm::test::Helpers::GenerateBatch(nTokens, nDocs, "@default_class", "@some_class");
artm::DictionaryData dict = ::artm::test::Helpers::GenerateDictionary(nTokens, "@default_class", "@some_class");
std::vector<std::shared_ptr< ::artm::Batch>> batches;
batches.push_back(std::make_shared< ::artm::Batch>(batch));
auto offline_args_0 = api_0.Initialize(batches, nullptr, nullptr, &dict);
auto offline_args_1 = api_1.Initialize(batches, nullptr, nullptr, &dict);
auto offline_args_2 = api_2.Initialize(batches, nullptr, nullptr, &dict);
auto offline_args_3 = api_3.Initialize(batches, nullptr, nullptr, &dict);
master_0.FitOfflineModel(offline_args_0);
::artm::GetScoreValueArgs gs;
gs.set_score_name("perplexity_1");
auto score = master_0.GetScoreAs< ::artm::PerplexityScore>(gs);
ASSERT_EQ(score.transaction_typename_info_size(), 1);
ASSERT_DOUBLE_EQ(score.normalizer(), 0.0);
ASSERT_DOUBLE_EQ(score.raw(), 0.0);
ASSERT_EQ(score.zero_words(), 0);
ASSERT_GT(score.value(), 0.0);
float value_1 = score.value();
gs.set_score_name("perplexity_2");
score = master_0.GetScoreAs< ::artm::PerplexityScore>(gs);
ASSERT_EQ(score.transaction_typename_info_size(), 1);
ASSERT_DOUBLE_EQ(score.normalizer(), 0.0);
ASSERT_DOUBLE_EQ(score.raw(), 0.0);
ASSERT_EQ(score.zero_words(), 0);
ASSERT_GT(score.value(), 0.0);
float value_2 = score.value();
ASSERT_DOUBLE_EQ(value_1, value_2);
master_1.FitOfflineModel(offline_args_1);
gs.set_score_name("perplexity");
score = master_1.GetScoreAs< ::artm::PerplexityScore>(gs);
// score calculation should be skipped if class ids sets of model and score have empty intersection
ASSERT_EQ(score.transaction_typename_info_size(), 0);
ASSERT_DOUBLE_EQ(score.normalizer(), 0.0);
ASSERT_DOUBLE_EQ(score.raw(), 0.0);
ASSERT_DOUBLE_EQ(score.value(), 0.0);
ASSERT_EQ(score.zero_words(), 0);
for (int iter = 0; iter < 5; ++iter) {
master_2.FitOfflineModel(offline_args_2);
master_3.FitOfflineModel(offline_args_3);
}
gs.set_score_name("perplexity_1");
score = master_2.GetScoreAs< ::artm::PerplexityScore>(gs);
ASSERT_GT(score.value(), 0.0);
ASSERT_LT(score.raw(), 0.0);
ASSERT_GT(score.normalizer(), 0);
ASSERT_EQ(score.zero_words(), 0);
ASSERT_EQ(score.transaction_typename_info_size(), 0);
value_1 = score.value();
gs.set_score_name("perplexity_2");
score = master_2.GetScoreAs< ::artm::PerplexityScore>(gs);
ASSERT_GT(score.value(), 0.0);
ASSERT_LT(score.raw(), 0.0);
ASSERT_GT(score.normalizer(), 0);
ASSERT_EQ(score.zero_words(), 0);
ASSERT_EQ(score.transaction_typename_info_size(), 0);
value_2 = score.value();
ASSERT_DOUBLE_EQ(value_1, value_2);
gs.set_score_name("perplexity_3");
score = master_2.GetScoreAs< ::artm::PerplexityScore>(gs);
ASSERT_GT(score.value(), 0.0);
ASSERT_LT(score.raw(), 0.0);
ASSERT_GT(score.normalizer(), 0);
ASSERT_EQ(score.zero_words(), 0);
ASSERT_EQ(score.transaction_typename_info_size(), 0);
gs.set_score_name("perplexity_4");
score = master_2.GetScoreAs< ::artm::PerplexityScore>(gs);
ASSERT_GT(score.value(), 0.0);
ASSERT_LT(score.raw(), 0.0);
ASSERT_GT(score.normalizer(), 0);
ASSERT_EQ(score.zero_words(), 0);
ASSERT_EQ(score.transaction_typename_info_size(), 0);
gs.set_score_name("perplexity");
score = master_3.GetScoreAs< ::artm::PerplexityScore>(gs);
ASSERT_GT(score.value(), 0.0);
ASSERT_LT(score.raw(), 0.0);
ASSERT_GT(score.normalizer(), 0.0);
ASSERT_EQ(score.transaction_typename_info_size(), 0);
}
// artm_tests.exe --gtest_filter=Scores.ScoreTrackerExportImport
TEST(Scores, ScoreTrackerExportImport) {
int nTokens = 60, nDocs = 10, nTopics = 10, nPasses = 5;
::artm::ScoreConfig score_config;
::artm::TopTokensScore top_tokens_config;
score_config.set_config(top_tokens_config.SerializeAsString());
score_config.set_type(::artm::ScoreType_TopTokens);
score_config.set_name("top_tokens");
::artm::MasterModelConfig master_config_1 = ::artm::test::TestMother::GenerateMasterModelConfig(nTopics);
::artm::test::Helpers::ConfigurePerplexityScore("perplexity", &master_config_1);
master_config_1.add_score_config()->CopyFrom(score_config);
::artm::MasterModel master_1(master_config_1);
::artm::test::Api api_1(master_1);
::artm::MasterModelConfig master_config_2 = ::artm::test::TestMother::GenerateMasterModelConfig(nTopics);
::artm::MasterModel master_2(master_config_2);
::artm::test::Api api_2(master_2);
// Generate doc-token matrix
artm::Batch batch = ::artm::test::Helpers::GenerateBatch(nTokens, nDocs, "@default_class", "@default_class");
artm::DictionaryData dict = ::artm::test::Helpers::GenerateDictionary(nTokens, "@default_class", "@default_class");
std::vector<std::shared_ptr< ::artm::Batch>> batches;
batches.push_back(std::make_shared< ::artm::Batch>(batch));
auto offline_args = api_1.Initialize(batches, nullptr, nullptr, &dict);
offline_args.set_num_collection_passes(nPasses);
master_1.FitOfflineModel(offline_args);
::artm::GetScoreArrayArgs args;
args.set_score_name("perplexity");
auto score_array_1_perp = master_1.GetScoreArray(args);
ASSERT_EQ(score_array_1_perp.score_size(), nPasses);
args.set_score_name("top_tokens");
auto score_array_1_top = master_1.GetScoreArray(args);
ASSERT_EQ(score_array_1_top.score_size(), nPasses);
std::string target_name = artm::test::Helpers::getUniqueString();
::artm::ExportScoreTrackerArgs export_args;
export_args.set_file_name(target_name);
master_1.ExportScoreTracker(export_args);
::artm::ImportScoreTrackerArgs import_args;
import_args.set_file_name(target_name);
master_2.ImportScoreTracker(import_args);
// assert that source and loaded data has same size and content
args.set_score_name("perplexity");
auto score_array_2 = master_2.GetScoreArray(args);
ASSERT_EQ(score_array_2.score_size(), nPasses);
for (size_t i = 0; i < nPasses; ++i) {
ASSERT_EQ(score_array_1_perp.score(i).data(), score_array_2.score(i).data());
}
args.set_score_name("top_tokens");
score_array_2 = master_2.GetScoreArray(args);
ASSERT_EQ(score_array_2.score_size(), nPasses);
for (size_t i = 0; i < nPasses; ++i) {
ASSERT_EQ(score_array_1_top.score(i).data(), score_array_2.score(i).data());
}
try { boost::filesystem::remove(target_name); }
catch (...) { }
}
| 42.104265 | 117 | 0.72805 | [
"vector",
"model"
] |
7fadd0eab62cb274c2cc1d18bd173579cbd28e2e | 9,999 | cpp | C++ | cluster-genes/dominant.cpp | luispedro/Coelho2021_GMGCv1_analysis | 5f1a62844631121cc11f8ac5a776d25baca56ff7 | [
"MIT"
] | 6 | 2021-12-16T09:20:28.000Z | 2022-03-29T03:21:48.000Z | cluster-genes/dominant.cpp | luispedro/Coelho2021_GMGCv1_analysis | 5f1a62844631121cc11f8ac5a776d25baca56ff7 | [
"MIT"
] | 1 | 2022-02-18T01:56:56.000Z | 2022-02-22T14:39:48.000Z | cluster-genes/dominant.cpp | luispedro/Coelho2021_GMGCv1_analysis | 5f1a62844631121cc11f8ac5a776d25baca56ff7 | [
"MIT"
] | 8 | 2021-12-17T02:14:50.000Z | 2022-03-21T06:40:59.000Z | #include <algorithm>
#include <queue>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <assert.h>
typedef std::vector<int> renumber_t;
typedef std::vector<int>::size_type index_t;
struct Int1dSlice {
typedef std::vector<int>::const_iterator base_iterator;
Int1dSlice(base_iterator start, base_iterator end)
:first_(start)
,past_(end)
{ }
base_iterator begin() const { return first_; }
base_iterator end() const { return past_; }
base_iterator first_;
base_iterator past_;
};
struct Int2d {
Int2d() { }
Int2d(Int2d&& other) {
indices_.swap(other.indices_);
data_.swap(other.data_);
}
static Int2d make_int2d(std::vector<index_t>& indices, std::vector<int>& data) {
Int2d r;
r.indices_.swap(indices);
r.data_.swap(data);
return r;
}
std::vector<int>::const_iterator start_of(index_t ix) const { return data_.begin() + (ix > 0 ? indices_[ix - 1] : 0); }
std::vector<int>::const_iterator end_of(index_t ix) const { return start_of(ix + 1); }
Int1dSlice neighbors(index_t ix) const { return Int1dSlice(start_of(ix), end_of(ix)); }
index_t size() const { return data_.size(); }
std::vector<index_t> indices_;
std::vector<int> data_;
};
inline
int lazy_vertex_add(std::vector<int>& vertex_renumber, std::vector<int>& cur, int orig) {
//std::cerr << "lazy_vertex_add(" << orig << ")\n";
if (vertex_renumber[orig] != -1) return vertex_renumber[orig];
int n = cur.size();
vertex_renumber[orig] = n;
cur.push_back(orig);
return n;
}
struct DiGraphBuilderRenamer {
DiGraphBuilderRenamer()
: prev_(-1)
{ }
void add_edge(unsigned int v0, unsigned int v1) {
if (int(v0) != prev_) {
assert(int(v0) == (prev_+1));
if (!data_.empty()) {
indices_.push_back(data_.size());
}
prev_ = v0;
}
data_.push_back(v1);
}
Int2d finish(std::vector<int>& renamer, std::vector<int>& rmap) {
indices_.push_back(data_.size());
for (index_t i = 0; i != data_.size(); ++i) {
data_[i] = lazy_vertex_add(renamer, rmap, data_[i]);
}
return Int2d::make_int2d(indices_, data_);
}
void clear() {
prev_ = -1;
indices_.clear();
data_.clear();
}
bool empty() const { return data_.empty(); }
int prev_;
std::vector<index_t> indices_;
std::vector<int> data_;
};
struct DiGraph {
DiGraph(DiGraphBuilderRenamer& builder, std::vector<int>& renamer, std::vector<int>& rmap)
:edges_(builder.finish(renamer, rmap))
{ nv_ = rmap.size(); }
unsigned n_vertices() const { return nv_; }
unsigned n_edges() const { return edges_.data_.size(); }
Int1dSlice neighbors(index_t ix) const {
if (ix < edges_.indices_.size()) return edges_.neighbors(ix);
return Int1dSlice(edges_.data_.begin(), edges_.data_.begin());
}
unsigned nv_;
Int2d edges_;
};
typedef std::vector<int> vertex_set;
typedef int dset_value;
struct VertexWeight {
VertexWeight(unsigned v, int w)
:vertex_(v)
,weight_(w)
{ }
bool operator < (const VertexWeight& other) const {
if (weight_ == other.weight_) return vertex_ > other.vertex_;
return weight_ < other.weight_;
}
unsigned vertex_;
int weight_;
};
index_t weight(const DiGraph& g, const std::vector<bool>& covered, index_t i) {
index_t r = 0;
if (!covered[i]) ++r;
for (auto j : g.neighbors(i)) {
if (!covered[j]) ++r;
}
//std::cerr << "weight(" << i << "): " << r << '\n';
return r;
}
int extract_next(const DiGraph& g, const std::vector<bool>& covered, std::priority_queue<VertexWeight>& max_bound, bool noise) {
if (max_bound.size() == 1) {
while (!max_bound.empty()) {
VertexWeight n = max_bound.top();
max_bound.pop();
if (!covered[n.vertex_]) return n.vertex_;
}
return -1;
}
VertexWeight next = max_bound.top();
max_bound.pop();
const int new_weight = weight(g, covered, next.vertex_);
if (new_weight == next.weight_) {
return next.vertex_;
}
next.weight_ = new_weight;
std::vector<VertexWeight> candidates;
candidates.push_back(next);
VertexWeight best = next;
while (!max_bound.empty() && best < max_bound.top()) {
next = max_bound.top();
max_bound.pop();
next.weight_ = weight(g, covered, next.vertex_);
if (best < next) best = next;
candidates.push_back(next);
}
for (auto first : candidates) {
if (first.vertex_ != best.vertex_ && first.weight_ > 0) {
max_bound.push(first);
}
}
return best.vertex_;
}
vertex_set greedy_find_dset_queue(const DiGraph& g) {
vertex_set r;
std::priority_queue<VertexWeight> max_bound;
index_t uncovered = g.n_vertices();
std::vector<bool> covered(g.n_vertices(), true);
for (index_t i = 0; i < g.n_vertices(); ++i) {
for (auto n : g.neighbors(i)) {
covered.at(n) = false;
}
}
for (index_t i = 0; i < g.n_vertices(); ++i) {
if (covered.at(i)) {
r.push_back(i);
--uncovered;
} else {
max_bound.push(VertexWeight(i, weight(g, covered, i)));
}
}
for (auto vertex : r) {
for (auto n : g.neighbors(vertex)) {
if (!covered.at(n)) {
covered[n] = true;
--uncovered;
}
}
}
while (uncovered) {
index_t vid = extract_next(g, covered, max_bound, true);
assert(vid != index_t(-1));
r.push_back(vid);
if (!covered.at(vid)) {
covered[vid] = true;
--uncovered;
}
for (auto n : g.neighbors(vid)) {
if (!covered.at(n)) {
covered[n] = true;
--uncovered;
}
}
}
return r;
}
vertex_set greedy_find_dset_brute(const DiGraph& g) {
vertex_set r;
std::vector<int> weight(g.n_vertices());
std::vector<int> used(g.n_vertices());
std::vector<bool> covered(g.n_vertices());
index_t uncovered = g.n_vertices();
while (1) {
// #pragma omp parallel for
for (index_t i = 0; i < g.n_vertices(); ++i) {
if (used[i]) continue;
if (!covered[i]) ++weight[i];
for (auto c: g.neighbors(i)) {
if (!covered[c]) ++weight[i];
}
}
auto next = max_element(weight.begin(), weight.end());
index_t vid = next - weight.begin();
r.push_back(vid);
used[vid] = true;
if (!covered[vid]) {
covered[vid] = true;
--uncovered;
}
for (auto n : g.neighbors(vid)) {
if (!covered[n]) {
covered[n] = true;
--uncovered;
}
}
if (!uncovered) return r;
std::fill(weight.begin(), weight.end(), 0);
}
}
vertex_set greedy_find_dset(const DiGraph& g) {
if (g.n_vertices() > 10) return greedy_find_dset_queue(g);
else return greedy_find_dset_brute(g);
}
void dominant(DiGraphBuilderRenamer& gb, renumber_t& vertex_renumber, std::vector<int>& rmap) {
//std::cerr << "Handling graph of size " << gb.nv_ << "/" << gb.edges_.size() << '\n';
if (gb.data_.size() == 1) {
std::cout << rmap.at(0) << '\n';
return;
}
DiGraph g(gb, vertex_renumber, rmap);
if (g.n_vertices() > 10000) {
std::cerr << "Built Graph: " << g.n_vertices() << "/" << g.n_edges() << ".\n";
}
//std::cerr << "Built Graph: " << g.n_vertices() << "/" << g.n_edges() << ".\n";
vertex_set r = greedy_find_dset(g);
for (auto v : r) {
std::cout << rmap.at(v) << '\n';
}
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage : " << argv[0] << " TRIPLETS-FILE" << std::endl;
return 1;
}
int active = -1;
uint32_t buffer[4096 * 3];
DiGraphBuilderRenamer gb;
long long vi = 0;
int next = 100000000;
renumber_t vertex_renumber;
std::vector<int> rmap;
std::ifstream fdata(argv[1]);
while (!fdata.eof()) {
void* bufferp = buffer;
fdata.read((char*)bufferp, sizeof(buffer));
const unsigned nbytes = fdata.gcount();
if (nbytes % (3 * sizeof(buffer[0])) != 0) {
std::cerr << "Bad input file " << argv[1]
<< " size is incorrect (read " << nbytes << " Bytes; not multiple of " << (3*sizeof(buffer[0])) << ")." << std::endl;
return 2;
}
const int n_triplets = nbytes/(3 * sizeof(buffer[0]));
if (!n_triplets) break;
for (int i = 0; i < n_triplets; ++i) {
++vi;
--next;
if (!next) {
std::cerr << "Loaded " << vi/1000000000. << "g entries.\n";
next = 100000000;
}
const int group = buffer[i*3 + 0];
const int v0 = buffer[i*3 + 1];
const int v1 = buffer[i*3 + 2];
//std::cerr << "group: " << group << '\n';
if (group != active) {
if (active != -1) {
dominant(gb, vertex_renumber, rmap);
}
gb.clear();
rmap.clear();
active = group;
}
if (unsigned(v0) >= vertex_renumber.size() || unsigned(v1) >= vertex_renumber.size()) {
unsigned new_size = 1 + (v0 > v1 ? v0 : v1);
vertex_renumber.resize(new_size, -1);
}
const int e0 = lazy_vertex_add(vertex_renumber, rmap, v0);
gb.add_edge(e0, v1);
}
}
if (!rmap.empty()) {
dominant(gb, vertex_renumber, rmap);
}
return 0;
}
| 28.898844 | 141 | 0.536254 | [
"vector"
] |
7fb0f283f15256293807fe55c68fac86280e8ff8 | 2,578 | cc | C++ | live/src/model/AddDRMCertificateRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | live/src/model/AddDRMCertificateRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | live/src/model/AddDRMCertificateRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/live/model/AddDRMCertificateRequest.h>
using AlibabaCloud::Live::Model::AddDRMCertificateRequest;
AddDRMCertificateRequest::AddDRMCertificateRequest() :
RpcServiceRequest("live", "2016-11-01", "AddDRMCertificate")
{
setMethod(HttpRequest::Method::Post);
}
AddDRMCertificateRequest::~AddDRMCertificateRequest()
{}
std::string AddDRMCertificateRequest::getServCert()const
{
return servCert_;
}
void AddDRMCertificateRequest::setServCert(const std::string& servCert)
{
servCert_ = servCert;
setParameter("ServCert", servCert);
}
std::string AddDRMCertificateRequest::getDescription()const
{
return description_;
}
void AddDRMCertificateRequest::setDescription(const std::string& description)
{
description_ = description;
setParameter("Description", description);
}
std::string AddDRMCertificateRequest::getPrivateKey()const
{
return privateKey_;
}
void AddDRMCertificateRequest::setPrivateKey(const std::string& privateKey)
{
privateKey_ = privateKey;
setParameter("PrivateKey", privateKey);
}
std::string AddDRMCertificateRequest::getCertName()const
{
return certName_;
}
void AddDRMCertificateRequest::setCertName(const std::string& certName)
{
certName_ = certName;
setParameter("CertName", certName);
}
long AddDRMCertificateRequest::getOwnerId()const
{
return ownerId_;
}
void AddDRMCertificateRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string AddDRMCertificateRequest::getAsk()const
{
return ask_;
}
void AddDRMCertificateRequest::setAsk(const std::string& ask)
{
ask_ = ask;
setParameter("Ask", ask);
}
std::string AddDRMCertificateRequest::getPassphrase()const
{
return passphrase_;
}
void AddDRMCertificateRequest::setPassphrase(const std::string& passphrase)
{
passphrase_ = passphrase;
setParameter("Passphrase", passphrase);
}
| 24.093458 | 78 | 0.749418 | [
"model"
] |
7fbc31c5fc4952d87d8c140aa45c58583cf41faa | 1,271 | hpp | C++ | cpp/godot-cpp/include/gen/VisualShaderNodeColorOp.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | 1 | 2021-03-16T09:51:00.000Z | 2021-03-16T09:51:00.000Z | cpp/godot-cpp/include/gen/VisualShaderNodeColorOp.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | cpp/godot-cpp/include/gen/VisualShaderNodeColorOp.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | #ifndef GODOT_CPP_VISUALSHADERNODECOLOROP_HPP
#define GODOT_CPP_VISUALSHADERNODECOLOROP_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "VisualShaderNodeColorOp.hpp"
#include "VisualShaderNode.hpp"
namespace godot {
class VisualShaderNodeColorOp : public VisualShaderNode {
struct ___method_bindings {
godot_method_bind *mb_get_operator;
godot_method_bind *mb_set_operator;
};
static ___method_bindings ___mb;
public:
static void ___init_method_bindings();
static inline const char *___get_class_name() { return (const char *) "VisualShaderNodeColorOp"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
enum Operator {
OP_SCREEN = 0,
OP_DIFFERENCE = 1,
OP_DARKEN = 2,
OP_LIGHTEN = 3,
OP_OVERLAY = 4,
OP_DODGE = 5,
OP_BURN = 6,
OP_SOFT_LIGHT = 7,
OP_HARD_LIGHT = 8,
};
// constants
static VisualShaderNodeColorOp *_new();
// methods
VisualShaderNodeColorOp::Operator get_operator() const;
void set_operator(const int64_t op);
};
}
#endif | 23.109091 | 245 | 0.762392 | [
"object"
] |
7fc37e4f587d39bc6c687f87762c1a10d7fa053e | 15,696 | cpp | C++ | src/tools/FuzzyUtils.cpp | saulocbarreto/bgslibrary | e1890b6b05cd40757ad00e1c71e8c1db13a74a2a | [
"MIT"
] | 1,899 | 2015-01-04T01:13:30.000Z | 2022-03-29T21:58:28.000Z | src/tools/FuzzyUtils.cpp | saulocbarreto/bgslibrary | e1890b6b05cd40757ad00e1c71e8c1db13a74a2a | [
"MIT"
] | 175 | 2015-01-25T16:14:03.000Z | 2022-03-17T17:36:53.000Z | src/tools/FuzzyUtils.cpp | saulocbarreto/bgslibrary | e1890b6b05cd40757ad00e1c71e8c1db13a74a2a | [
"MIT"
] | 752 | 2015-01-04T01:34:29.000Z | 2022-03-29T13:53:33.000Z | #include "FuzzyUtils.h"
using namespace bgslibrary::tools;
FuzzyUtils::FuzzyUtils() {}
FuzzyUtils::~FuzzyUtils() {}
void FuzzyUtils::LBP(IplImage* InputImage, IplImage* LBPimage)
{
PixelUtils p;
float* neighberPixel = (float*)malloc(9 * sizeof(float));
float* BinaryValue = (float*)malloc(9 * sizeof(float));
float* CarreExp = (float*)malloc(9 * sizeof(float));
float* valLBP = (float*)malloc(1 * sizeof(float));
*valLBP = 0;
int x = 0, y = 0;
// on implemente les 8 valeurs puissance de 2 qui correspondent aux 8 elem. d'image voisins au elem. d'image central
*(CarreExp + 0) = 1.0;
*(CarreExp + 1) = 2.0;
*(CarreExp + 2) = 4.0;
*(CarreExp + 3) = 8.0;
*(CarreExp + 4) = 0.0;
*(CarreExp + 5) = 16.0;
*(CarreExp + 6) = 32.0;
*(CarreExp + 7) = 64.0;
*(CarreExp + 8) = 128.0;
//le calcule de LBP
//pour les 4 coins
/* 1.*/
if (x == 0 && y == 0)
{
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 4, 0);
*valLBP = *valLBP + ((*(BinaryValue + 1))*(*(CarreExp + 1)) + (*(BinaryValue + 2))*(*(CarreExp + 2)) + (*(BinaryValue + 3))*(*(CarreExp + 3))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
/* 2.*/
if (x == 0 && y == InputImage->width)
{
*valLBP = 0;
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 4, 1);
*valLBP = *valLBP + ((*(BinaryValue))*(*(CarreExp)) + (*(BinaryValue + 2))*(*(CarreExp + 2)) + (*(BinaryValue + 3))*(*(CarreExp + 3))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
/* 3.*/
if (x == InputImage->height && y == 0)
{
*valLBP = 0;
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 4, 2);
*valLBP = *valLBP + ((*(BinaryValue))*(*(CarreExp)) + (*(BinaryValue + 1))*(*(CarreExp + 1)) + (*(BinaryValue + 3))*(*(CarreExp + 3))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
/* 4.*/
if (x == InputImage->height && y == InputImage->width)
{
*valLBP = 0;
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 4, 3);
*valLBP = *valLBP + ((*(BinaryValue))*(*(CarreExp)) + (*(BinaryValue + 1))*(*(CarreExp + 1)) + (*(BinaryValue + 2))*(*(CarreExp + 2))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
//le calcul de LBP pour la première ligne : L(0)
if (x == 0 && (y != 0 && y != InputImage->width))
{
for (int y = 1; y < InputImage->width - 1; y++)
{
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 6, 4);
*valLBP = 0;
*valLBP = *valLBP + ((*(BinaryValue))*(*(CarreExp)) + (*(BinaryValue + 1))*(*(CarreExp + 1)) + (*(BinaryValue + 2))*(*(CarreExp + 2)) + (*(BinaryValue + 3))*(*(CarreExp + 3)) + (*(BinaryValue + 5))*(*(CarreExp + 5))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
}
//le calcul de LBP pour la dernière colonne : C(w)
if ((x != 0 && x != InputImage->height) && y == InputImage->width)
{
for (int x = 1; x < InputImage->height - 1; x++)
{
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 6, 4);
*valLBP = 0;
*valLBP = *valLBP + ((*(BinaryValue))*(*(CarreExp)) + (*(BinaryValue + 1))*(*(CarreExp + 1)) + (*(BinaryValue + 2))*(*(CarreExp + 2)) + (*(BinaryValue + 3))*(*(CarreExp + 3)) + (*(BinaryValue + 5))*(*(CarreExp + 5))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
}
//le calcul de LBP pour la dernière ligne : L(h)
if (x == InputImage->height && (y != 0 && y != InputImage->width))
{
for (int y = 1; y < InputImage->width - 1; y++)
{
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 6, 1);
*valLBP = 0;
*valLBP = *valLBP + ((*(BinaryValue))*(*(CarreExp)) + (*(BinaryValue + 2))*(*(CarreExp + 2)) + (*(BinaryValue + 3))*(*(CarreExp + 3)) + (*(BinaryValue + 4))*(*(CarreExp + 4)) + (*(BinaryValue + 5))*(*(CarreExp + 5))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
}
//le calcul de LBP pour la première colonne : C(0)
if ((x != 0 && x != InputImage->height) && y == 0)
{
for (int x = 1; x < InputImage->height - 1; x++)
{
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 6, 2);
*valLBP = 0;
*valLBP = *valLBP + ((*(BinaryValue))*(*(CarreExp + 5)) + (*(BinaryValue + 1))*(*(CarreExp + 6)) + (*(BinaryValue + 3))*(*(CarreExp + 3)) + (*(BinaryValue + 4))*(*(CarreExp)) + (*(BinaryValue + 5))*(*(CarreExp + 1))) / 255.0;
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
}
//pour le reste des elements d'image
for (int y = 1; y < InputImage->height - 1; y++)
{
for (int x = 1; x < InputImage->width - 1; x++)
{
p.getNeighberhoodGrayPixel(InputImage, x, y, neighberPixel);
getBinValue(neighberPixel, BinaryValue, 9, 4);
//le calcul de la valeur du LBP pour chaque elem. d'im.
*valLBP = 0;
for (int l = 0; l < 9; l++)
*valLBP = *valLBP + ((*(BinaryValue + l)) * (*(CarreExp + l))) / 255.0;
//printf("\nvalLBP(%d,%d)=%f",x,y,*valLBP);
p.PutGrayPixel(LBPimage, x, y, *valLBP);
}
}
free(neighberPixel);
free(BinaryValue);
free(CarreExp);
free(valLBP);
}
void FuzzyUtils::getBinValue(float* neighberGrayPixel, float* BinaryValue, int m, int n)
{
// la comparaison entre la valeur d'elem d'image central et les valeurs des elem. d'im. voisins
// m = le numero des elements (4, 6 ou 9);
// n = la position de l'element central;
int h = 0;
for (int k = 0; k < m; k++)
{
if (*(neighberGrayPixel + k) >= *(neighberGrayPixel + n))
{
*(BinaryValue + h) = 1;
h++;
}
else
{
*(BinaryValue + h) = 0;
h++;
}
}
}
void FuzzyUtils::SimilarityDegreesImage(IplImage* CurrentImage, IplImage* BGImage, IplImage* DeltaImage, int n, int color_space)
{
PixelUtils p;
int i, j;
if (n == 1)
{
float* CurrentGrayPixel = (float*)malloc(1 * (sizeof(float)));
float* BGGrayPixel = (float*)malloc(1 * (sizeof(float)));
float* DeltaGrayPixel = (float*)malloc(1 * (sizeof(float)));
for (i = 0; i < CurrentImage->width; i++)
{
for (j = 0; j < CurrentImage->height; j++)
{
p.GetGrayPixel(CurrentImage, i, j, CurrentGrayPixel);
p.GetGrayPixel(BGImage, i, j, BGGrayPixel);
RatioPixels(CurrentGrayPixel, BGGrayPixel, DeltaGrayPixel, 1);
p.PutGrayPixel(DeltaImage, i, j, *DeltaGrayPixel);
}
}
free(CurrentGrayPixel);
free(BGGrayPixel);
free(DeltaGrayPixel);
}
if (n != 1)
{
IplImage* ConvertedCurrentImage = cvCreateImage(cvSize(CurrentImage->width, CurrentImage->height), IPL_DEPTH_32F, 3);
IplImage* ConvertedBGImage = cvCreateImage(cvSize(CurrentImage->width, CurrentImage->height), IPL_DEPTH_32F, 3);
float* ConvertedCurrentPixel = (float*)malloc(3 * (sizeof(float)));
float* ConvertedBGPixel = (float*)malloc(3 * (sizeof(float)));
float* DeltaConvertedPixel = (float*)malloc(3 * (sizeof(float)));
p.ColorConversion(CurrentImage, ConvertedCurrentImage, color_space);
p.ColorConversion(BGImage, ConvertedBGImage, color_space);
for (i = 0; i < CurrentImage->width; i++)
{
for (j = 0; j < CurrentImage->height; j++)
{
p.GetPixel(ConvertedCurrentImage, i, j, ConvertedCurrentPixel);
p.GetPixel(ConvertedBGImage, i, j, ConvertedBGPixel);
RatioPixels(ConvertedCurrentPixel, ConvertedBGPixel, DeltaConvertedPixel, 3);
p.PutPixel(DeltaImage, i, j, DeltaConvertedPixel);
}
}
free(ConvertedCurrentPixel);
free(ConvertedBGPixel);
free(DeltaConvertedPixel);
cvReleaseImage(&ConvertedCurrentImage);
cvReleaseImage(&ConvertedBGImage);
}
}
void FuzzyUtils::RatioPixels(float* CurrentPixel, float* BGPixel, float* DeltaPixel, int n)
{
if (n == 1)
{
if (*CurrentPixel < *BGPixel)
*DeltaPixel = *CurrentPixel / *BGPixel;
if (*CurrentPixel > *BGPixel)
*DeltaPixel = *BGPixel / *CurrentPixel;
if (*CurrentPixel == *BGPixel)
*DeltaPixel = 1.0;
}
if (n == 3)
for (int i = 0; i < 3; i++)
{
if (*(CurrentPixel + i) < *(BGPixel + i))
*(DeltaPixel + i) = *(CurrentPixel + i) / *(BGPixel + i);
if (*(CurrentPixel + i) > *(BGPixel + i))
*(DeltaPixel + i) = *(BGPixel + i) / *(CurrentPixel + i);
if (*(CurrentPixel + i) == *(BGPixel + i))
*(DeltaPixel + i) = 1.0;
}
}
void FuzzyUtils::getFuzzyIntegralSugeno(IplImage* H, IplImage* Delta, int n, float *MeasureG, IplImage* OutputImage)
{
// MeasureG : est un vecteur contenant 3 mesure g (g1,g2,g3) tel que : g1+g2+g3=1
// n : =2 cad aggreger les 2 images "H" et "Delta"
// =1 cad aggreger uniquement les valeurs des composantes couleurs de l'image "Delta"
PixelUtils p;
float* HTexturePixel = (float*)malloc(1 * sizeof(float));
float* DeltaOhtaPixel = (float*)malloc(3 * (sizeof(float)));
int *Indice = (int*)malloc(3 * (sizeof(int)));
float *HI = (float*)malloc(3 * (sizeof(float)));
float *Integral = (float*)malloc(3 * (sizeof(float)));
float* X = (float*)malloc(1 * sizeof(float));
float* XiXj = (float*)malloc(1 * sizeof(float));
float IntegralFlou;
*Indice = 0;
*(Indice + 1) = 1;
*(Indice + 2) = 2;
*X = 1.0;
for (int i = 0; i < H->width; i++)
{
for (int j = 0; j < H->height; j++)
{
p.GetGrayPixel(H, i, j, HTexturePixel);
p.GetPixel(Delta, i, j, DeltaOhtaPixel);
*(HI + 0) = *(HTexturePixel + 0);
*(HI + 1) = *(DeltaOhtaPixel + 0);
*(HI + 2) = *(DeltaOhtaPixel + 1);
Trier(HI, 3, Indice);
*XiXj = *(MeasureG + (*(Indice + 1))) + (*(MeasureG + (*(Indice + 2))));
*(Integral + 0) = min((HI + (*(Indice + 0))), X);
*(Integral + 1) = min((HI + (*(Indice + 1))), XiXj);
*(Integral + 2) = min((HI + (*(Indice + 2))), ((MeasureG + (*(Indice + 2)))));
IntegralFlou = max(Integral, 3);
p.PutGrayPixel(OutputImage, i, j, IntegralFlou);
}
}
free(HTexturePixel);
free(DeltaOhtaPixel);
free(Indice);
free(HI);
free(X);
free(XiXj);
free(Integral);
}
void FuzzyUtils::getFuzzyIntegralChoquet(IplImage* H, IplImage* Delta, int n, float *MeasureG, IplImage* OutputImage)
{
// MeasureG : est un vecteur contenant 3 mesure g (g1,g2,g3) tel que : g1+g2+g3=1
// n : =2 cad aggreger les 2 images "H" et "Delta"
// =1 cad aggreger uniquement les valeurs des composantes couleurs de l'image "Delta"
PixelUtils p;
float* HTexturePixel = (float*)malloc(1 * sizeof(float));
float* DeltaOhtaPixel = (float*)malloc(3 * (sizeof(float)));
int *Indice = (int*)malloc(3 * (sizeof(int)));
float *HI = (float*)malloc(3 * (sizeof(float)));
float *Integral = (float*)malloc(3 * (sizeof(float)));
float* X = (float*)malloc(1 * sizeof(float));
float* XiXj = (float*)malloc(1 * sizeof(float));
float IntegralFlou;
*Indice = 0;
*(Indice + 1) = 1;
*(Indice + 2) = 2;
*X = 1.0;
for (int i = 0; i < Delta->width; i++)
{
for (int j = 0; j < Delta->height; j++)
{
if (n == 2)
{
p.GetGrayPixel(H, i, j, HTexturePixel);
p.GetPixel(Delta, i, j, DeltaOhtaPixel);
*(HI + 0) = *(HTexturePixel + 0);
*(HI + 1) = *(DeltaOhtaPixel + 0);
*(HI + 2) = *(DeltaOhtaPixel + 1);
}
if (n == 1)
{
//remplir HI par les valeurs des 3 composantes couleurs uniquement
p.GetPixel(Delta, i, j, DeltaOhtaPixel);
*(HI + 0) = *(DeltaOhtaPixel + 0);
//*(HI+0) = *(DeltaOhtaPixel+2);
*(HI + 1) = *(DeltaOhtaPixel + 1);
*(HI + 2) = *(DeltaOhtaPixel + 2);
}
Trier(HI, 3, Indice);
*XiXj = *(MeasureG + (*(Indice + 1))) + (*(MeasureG + (*(Indice + 2))));
*(Integral + 0) = *(HI + (*(Indice + 0)))* (*X - *XiXj);
*(Integral + 1) = *(HI + (*(Indice + 1)))* (*XiXj - *(MeasureG + (*(Indice + 2))));
*(Integral + 2) = *(HI + (*(Indice + 2)))* (*(MeasureG + (*(Indice + 2))));
IntegralFlou = *(Integral + 0) + *(Integral + 1) + *(Integral + 2);
p.PutGrayPixel(OutputImage, i, j, IntegralFlou);
}
}
free(HTexturePixel);
free(DeltaOhtaPixel);
free(Indice);
free(HI);
free(X);
free(XiXj);
free(Integral);
}
void FuzzyUtils::FuzzyMeasureG(float g1, float g2, float g3, float *G)
{
*(G + 0) = g1;
*(G + 1) = g2;
*(G + 2) = g3;
}
void FuzzyUtils::Trier(float* g, int n, int* index)
{
// Cette fonction trie un vecteur g par ordre croissant et
// sort egalement l'indice des elements selon le trie dans le vecteur "index" supposé initialisé par des valeurs de 1 a n
float t;
int r, a, b;
for (a = 1; a <= n; a++)
{
for (b = n - 1; b >= a; b--)
if (*(g + b - 1) < (*(g + b)))
{
// ordre croissant des élements
t = *(g + b - 1);
*(g + b - 1) = *(g + b);
*(g + b) = t;
// ordre des indices des élements du vecteur g
r = *(index + b - 1);
*(index + b - 1) = *(index + b);
*(index + b) = r;
}
}
}
float FuzzyUtils::min(float *a, float *b)
{
float min = 0;
if (*a >= (*b))
min = *b;
else
min = *a;
return min;
}
float FuzzyUtils::max(float* g, int n)
{
float max = 0;
for (int i = 0; i < n; i++)
{
if (*(g + i) >= max)
max = *(g + i);
}
return max;
}
void FuzzyUtils::gDeDeux(float* a, float* b, float* lambda)
{
float* c = (float*)malloc(1 * sizeof(float));
*c = *a + (*b) + (*lambda) * (*a) * (*b);
}
void FuzzyUtils::getLambda(float* g)
{
float a, b;
float* lambda = (float*)malloc(1 * sizeof(float));
a = (*(g + 0) * (*(g + 1)) + (*(g + 1)) * (*(g + 2)) + (*(g + 0)) * (*(g + 2)));
*lambda = -(*(g + 0) * (*(g + 1)) + (*(g + 1)) * (*(g + 2)) + (*(g + 0)) * (*(g + 2))) / (*(g + 0) * (*(g + 1)) * (*(g + 2)));
b = (*(g + 0) * (*(g + 1)) * (*(g + 2)));
//printf("\na:%f",a);
//printf("\nb:%f",b);
//printf("\nlambda:%f", *lambda);
free(lambda);
}
void FuzzyUtils::AdaptativeSelectiveBackgroundModelUpdate(IplImage* CurrentImage, IplImage* BGImage, IplImage* OutputImage, IplImage* Integral, float seuil, float alpha)
{
PixelUtils p;
float beta = 0.0;
float* CurentImagePixel = (float*)malloc(3 * sizeof(float));
float* BGImagePixel = (float*)malloc(3 * sizeof(float));
float* OutputImagePixel = (float*)malloc(3 * sizeof(float));
float* IntegralImagePixel = (float*)malloc(1 * sizeof(float));
float *Maximum = (float*)malloc(1 * sizeof(float));
float *Minimum = (float*)malloc(1 * sizeof(float));
p.ForegroundMaximum(Integral, Maximum, 1);
p.ForegroundMinimum(Integral, Minimum, 1);
for (int i = 0; i < CurrentImage->width; i++)
{
for (int j = 0; j < CurrentImage->height; j++)
{
p.GetPixel(CurrentImage, i, j, CurentImagePixel);
p.GetPixel(BGImage, i, j, BGImagePixel);
p.GetGrayPixel(Integral, i, j, IntegralImagePixel);
beta = 1 - ((*IntegralImagePixel) - ((*Minimum / (*Minimum - *Maximum)) * (*IntegralImagePixel) - (*Minimum * (*Maximum) / (*Minimum - *Maximum))));
for (int k = 0; k < 3; k++)
*(OutputImagePixel + k) = beta * (*(BGImagePixel + k)) + (1 - beta) * (alpha * (*(CurentImagePixel + k)) + (1 - alpha) * (*(BGImagePixel + k)));
p.PutPixel(OutputImage, i, j, OutputImagePixel);
}
}
free(CurentImagePixel);
free(BGImagePixel);
free(OutputImagePixel);
free(IntegralImagePixel);
free(Maximum);
free(Minimum);
}
| 31.45491 | 231 | 0.570528 | [
"cad"
] |
7fc7e8606bfcb85be1bb9beb74c859649489ce9c | 927 | hpp | C++ | framework/composite.hpp | Montag55/Das-raytracer | 356eac6a2ad6fe4f09015a94df9bbafe490f9585 | [
"MIT"
] | null | null | null | framework/composite.hpp | Montag55/Das-raytracer | 356eac6a2ad6fe4f09015a94df9bbafe490f9585 | [
"MIT"
] | null | null | null | framework/composite.hpp | Montag55/Das-raytracer | 356eac6a2ad6fe4f09015a94df9bbafe490f9585 | [
"MIT"
] | null | null | null | #ifndef COMPOSITE_HPP
#define COMPOSITE_HPP
#include "box.hpp"
#include "sphere.hpp"
#include "ray.hpp"
#include "hit.hpp"
#include <memory>
#include <string>
#include <vector>
class Composite : public Shape
{
public:
typedef std::shared_ptr<Shape> shape_pointer;
//KONSTRUTOREN----------------------------------------------------------------------
Composite();
Composite(std::string name);
~Composite();
//FUNKTIONEN-------------------------------------------------------------------------
Hit intersect(Ray const& inray) const override;
/*
void translate(glm::vec3 const& distance) override;
void rotate(double angle, glm::vec3 const& point) override;
void scale(double scale_factor) override;
*/
void add(shape_pointer const& shape);
void set_name(std::string const name);
private:
std::string m_name;
std::vector<shape_pointer> m_shapes;
};
#endif
| 23.769231 | 89 | 0.582524 | [
"shape",
"vector"
] |
7fd500fad413255398b7f65baabb8e5026d3198d | 7,337 | cpp | C++ | thrift/lib/cpp2/protocol/nimble/test/NimbleForwardCompatibilityTest.cpp | tahmidbintaslim/fbthrift | 1492869dbd748295a2262ad76a19623c90e47b95 | [
"Apache-2.0"
] | null | null | null | thrift/lib/cpp2/protocol/nimble/test/NimbleForwardCompatibilityTest.cpp | tahmidbintaslim/fbthrift | 1492869dbd748295a2262ad76a19623c90e47b95 | [
"Apache-2.0"
] | null | null | null | thrift/lib/cpp2/protocol/nimble/test/NimbleForwardCompatibilityTest.cpp | tahmidbintaslim/fbthrift | 1492869dbd748295a2262ad76a19623c90e47b95 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/portability/GTest.h>
#include <thrift/lib/cpp2/protocol/NimbleProtocol.h>
#include <thrift/lib/cpp2/protocol/nimble/test/gen-cpp2/forward_compatibility_types.h>
using namespace apache::thrift::test;
namespace apache {
namespace thrift {
namespace detail {
Primitives defaultPrimitives() {
Primitives result;
result.f1 = 1;
result.f2 = 2;
result.f3 = 3;
result.f4 = 4;
result.f5 = "5";
result.f6 = "6";
result.f7 = "7";
result.f8 = 8.0f;
result.f9 = 9.0;
return result;
}
BigFieldIds defaultBigFieldIds() {
BigFieldIds result;
result.f1 = 1;
result.f100 = 100;
result.f2 = 2;
result.f101 = 101;
result.f102 = 102;
result.f1000 = 1000;
result.f1001 = 1001;
result.f3 = 3;
result.f4 = 4;
return result;
}
NestedStructL2 defaultNestedStructL2() {
NestedStructL2 result;
result.f1 = "1";
result.f2.f1 = 1;
result.f2.f2 = 2;
result.f2.f3.f1 = 1;
result.f2.f3.f2 = 2;
result.f3 = 3;
return result;
}
ListStructElem defaultListStructElem() {
ListStructElem result;
result.f1 = "1";
result.f2 = 2;
return result;
}
ListStruct defaultListStruct() {
ListStruct result;
result.f1 = std::vector<ListStructElem>(10, defaultListStructElem());
result.f2.f1 = "unusual";
result.f2.f2 = 123;
result.f3 = 456;
result.f4 = {1, 2, 3, 4, 5};
result.f5 = 789;
return result;
}
MapStruct defaultMapStruct() {
MapStructValue mapValue;
mapValue.f1 = "1";
mapValue.f2 = 2;
MapStruct result;
result.f1 = {{1, mapValue}, {2, mapValue}, {3, mapValue}};
result.f2.f1 = "abc";
result.f2.f2 = 123;
result.f5 = 5;
return result;
}
template <typename Dst, typename Src>
Dst nimble_cast(Src& src) {
NimbleProtocolWriter writer;
src.write(&writer);
auto buf = writer.finalize();
buf->coalesce();
NimbleProtocolReader reader;
reader.setInput(folly::io::Cursor{buf.get()});
Dst dst;
dst.read(&reader);
return dst;
}
TEST(NimbleForwardCompatibilityTest, PrimitiveSimpleSkip) {
auto primitives = defaultPrimitives();
auto casted = nimble_cast<PrimitivesSimpleSkip>(primitives);
EXPECT_EQ(1, casted.f1);
EXPECT_EQ(2, casted.f2);
// Altered
EXPECT_EQ(0, casted.f3);
EXPECT_EQ(4, casted.f4);
// Altered
EXPECT_EQ("", casted.f5);
EXPECT_EQ("6", casted.f6);
}
TEST(NimbleForwardCompatibilityTest, PrimitiveConsecutiveMissing) {
auto primitives = defaultPrimitives();
auto casted = nimble_cast<PrimitivesConsecutiveMissing>(primitives);
EXPECT_EQ(1, casted.f1);
EXPECT_EQ("6", casted.f6);
}
TEST(NimbleForwardCompatibilityTest, PrimitivesTypesChanged) {
auto primitives = defaultPrimitives();
auto casted = nimble_cast<PrimitivesTypesChanged>(primitives);
// Altered
EXPECT_EQ(0, casted.f1);
EXPECT_EQ(2, casted.f2);
// Altered
EXPECT_EQ(0, casted.f3);
EXPECT_EQ(4, casted.f4);
// Altered
EXPECT_EQ(0.0, casted.f5);
// Altered
EXPECT_TRUE(casted.f6.empty());
EXPECT_EQ("7", casted.f7);
EXPECT_EQ(8.0f, casted.f8);
// Altered
EXPECT_EQ(0.0, casted.f9);
}
TEST(NimbleForwardCompatibilityTest, PrimitivesTypesReordered) {
auto primitives = defaultPrimitives();
auto casted = nimble_cast<PrimitivesTypesReordered>(primitives);
EXPECT_EQ(primitives.f1, casted.f1);
EXPECT_EQ(primitives.f2, casted.f2);
EXPECT_EQ(primitives.f3, casted.f3);
EXPECT_EQ(primitives.f4, casted.f4);
EXPECT_EQ(primitives.f5, casted.f5);
EXPECT_EQ(primitives.f6, casted.f6);
EXPECT_EQ(primitives.f7, casted.f7);
EXPECT_EQ(primitives.f8, casted.f8);
EXPECT_EQ(primitives.f9, casted.f9);
}
TEST(NimbleForwardCompatibilityTest, BigFieldIds) {
BigFieldIds bigFieldIds;
bigFieldIds.f1 = 1;
bigFieldIds.f100 = 100;
bigFieldIds.f2 = 2;
bigFieldIds.f101 = 101;
bigFieldIds.f102 = 102;
bigFieldIds.f1000 = 1000;
bigFieldIds.f1001 = 1001;
bigFieldIds.f3 = 3;
bigFieldIds.f4 = 4;
auto bigFieldIdsMissing = nimble_cast<BigFieldIdsMissing>(bigFieldIds);
EXPECT_EQ(1, bigFieldIdsMissing.f1);
EXPECT_EQ(2, bigFieldIdsMissing.f2);
EXPECT_EQ(4, bigFieldIdsMissing.f4);
}
TEST(NimbleForwardCompatibilityTest, NestedStruct) {
NestedStructL2 nested;
nested.f1 = "1";
nested.f2.f1 = 1;
nested.f2.f2 = 2;
nested.f2.f3.f1 = 1;
nested.f2.f3.f2 = 2;
nested.f3 = 3;
auto casted = nimble_cast<NestedStructMissingSubstruct>(nested);
EXPECT_EQ("1", casted.f1);
EXPECT_EQ(3, casted.f3);
}
TEST(NimbleForwardCompatibilityTest, NestedStructTypeChanged) {
auto nested = defaultNestedStructL2();
auto casted = nimble_cast<NestedStructTypeChanged>(nested);
EXPECT_EQ("1", casted.f1);
EXPECT_EQ(3, casted.f3);
}
TEST(NimbleForwardCompatabilityTest, Lists) {
auto listStruct = defaultListStruct();
auto casted = nimble_cast<ListStructMissingFields>(listStruct);
EXPECT_EQ("unusual", casted.f2.f1);
EXPECT_EQ(123, casted.f2.f2);
EXPECT_EQ(456, casted.f3);
EXPECT_EQ(789, casted.f5);
}
TEST(NimbleForwardCompatibilityTest, ListTypeChanged) {
auto listStruct = defaultListStruct();
auto casted = nimble_cast<ListStructTypeChanged>(listStruct);
EXPECT_EQ("unusual", casted.f2.f1);
EXPECT_EQ(123, casted.f2.f2);
EXPECT_EQ(456, casted.f3);
std::vector<int32_t> expectedList = {1, 2, 3, 4, 5};
EXPECT_EQ(expectedList, casted.f4);
EXPECT_EQ(789, casted.f5);
}
TEST(NimbleForwardCompatibilityTest, ListElemTypeChanged) {
auto listStruct = defaultListStruct();
auto casted = nimble_cast<ListStructListElemTypeChanged>(listStruct);
EXPECT_EQ("unusual", casted.f2.f1);
EXPECT_EQ(123, casted.f2.f2);
EXPECT_EQ(456, casted.f3);
std::vector<int32_t> expectedList = {1, 2, 3, 4, 5};
EXPECT_EQ(expectedList, casted.f4);
EXPECT_EQ(789, casted.f5);
}
TEST(NimbleForwardCompatibilityTest, Maps) {
auto mapStruct = defaultMapStruct();
auto casted = nimble_cast<MapStructMissingFields>(mapStruct);
EXPECT_EQ("abc", casted.f2.f1);
EXPECT_EQ(123, casted.f2.f2);
}
TEST(NimbleForwardCompatibilityTest, MapTypeChanged) {
auto mapStruct = defaultMapStruct();
auto casted = nimble_cast<MapStructTypeChanged>(mapStruct);
EXPECT_EQ("abc", casted.f2.f1);
EXPECT_EQ(123, casted.f2.f2);
EXPECT_EQ(5, casted.f5);
}
TEST(NimbleForwardCompatibilityTest, MapKeyTypeChanged) {
auto mapStruct = defaultMapStruct();
auto casted = nimble_cast<MapStructKeyTypeChanged>(mapStruct);
EXPECT_EQ("abc", casted.f2.f1);
EXPECT_EQ(123, casted.f2.f2);
EXPECT_EQ(5, casted.f5);
}
TEST(NimbleForwardCompatibilityTest, MapValueTypeChanged) {
auto mapStruct = defaultMapStruct();
auto casted = nimble_cast<MapStructValueTypeChanged>(mapStruct);
EXPECT_EQ("abc", casted.f2.f1);
EXPECT_EQ(123, casted.f2.f2);
EXPECT_EQ(5, casted.f5);
}
} // namespace detail
} // namespace thrift
} // namespace apache
| 26.974265 | 86 | 0.719913 | [
"vector"
] |
7fda276a88a5ee992368186483f462fe4b80b497 | 1,134 | cpp | C++ | C++/Gaddis/Ch8_Arrays/Ch8_Program8-3/Ch8_Program8-3.cpp | rlong2/Code | feb6c097159bf822122a73e0131ad928780bcfcd | [
"BSD-3-Clause"
] | null | null | null | C++/Gaddis/Ch8_Arrays/Ch8_Program8-3/Ch8_Program8-3.cpp | rlong2/Code | feb6c097159bf822122a73e0131ad928780bcfcd | [
"BSD-3-Clause"
] | null | null | null | C++/Gaddis/Ch8_Arrays/Ch8_Program8-3/Ch8_Program8-3.cpp | rlong2/Code | feb6c097159bf822122a73e0131ad928780bcfcd | [
"BSD-3-Clause"
] | null | null | null | /* This program reads employee work hours from work.dat
* located in the same folder as this cpp file
* and stores them in an int array. An array is used to
* input the hours and another to display them.
*/
#include <iostream>
#include<fstream>
using namespace std;
int main()
{
const int NUM_EMPLOYEES = 6;
int hours[NUM_EMPLOYEES];
int count = 0;
ifstream inputFile; // input file stream object
// Open the data file
inputFile.open("work.dat");
if (!inputFile)
cout << "Error opening data file" << endl;
else
{ // Read the numbers from the file into the array.
// When the loop is exited, count holds the # of items read in.
while (count < NUM_EMPLOYEES && inputFile >> hours[count] )
count ++;
// Close the file
inputFile.close();
// Display contents of array
cout << "The hours worked by each employee are:" << endl;
for (int employee = 0; employee < count; employee++)
{
cout << "Employee " << employee + 1 << ": ";
cout << hours[employee] << endl;
}
}
return 0;
}
| 24.12766 | 69 | 0.597002 | [
"object"
] |
8f12d1619a8ade37b0ae896919fb94301875780b | 6,984 | cpp | C++ | src/InsertMediaPropertiesAction.cpp | Ultraschall/ultraschall-3 | 7e2479fc0eb877a9b4979bedaf92f95bad627073 | [
"MIT"
] | 11 | 2018-07-08T09:14:22.000Z | 2019-11-08T02:54:42.000Z | src/InsertMediaPropertiesAction.cpp | Ultraschall/ultraschall-3 | 7e2479fc0eb877a9b4979bedaf92f95bad627073 | [
"MIT"
] | 17 | 2018-01-18T23:12:15.000Z | 2019-02-03T07:47:51.000Z | src/InsertMediaPropertiesAction.cpp | Ultraschall/ultraschall-3 | 7e2479fc0eb877a9b4979bedaf92f95bad627073 | [
"MIT"
] | 4 | 2018-03-07T19:38:29.000Z | 2019-01-10T09:04:05.000Z | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) The Ultraschall Project (http://ultraschall.fm)
//
// The MIT License (MIT)
//
// 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 <string>
#include <vector>
#include "CustomActionFactory.h"
#include "FileManager.h"
#include "ITagWriter.h"
#include "InsertMediaPropertiesAction.h"
#include "StringUtilities.h"
#include "SystemProperties.h"
#include "TagWriterFactory.h"
#include "TimeUtilities.h"
#include "UIFileDialog.h"
#include "UIMessageSupervisor.h"
#include "ReaperProjectManager.h"
namespace ultraschall { namespace reaper {
static DeclareCustomAction<InsertMediaPropertiesAction> action;
ServiceStatus InsertMediaPropertiesAction::Execute()
{
PRECONDITION_RETURN(ValidateProject() == true, SERVICE_FAILURE);
PRECONDITION_RETURN(ConfigureTargets() == true, SERVICE_FAILURE);
PRECONDITION_RETURN(ConfigureSources() == true, SERVICE_FAILURE);
// caution! requires ConfigureSources() to be called beforehand
PRECONDITION_RETURN(ValidateChapterMarkers(chapterMarkers_) == true, SERVICE_FAILURE);
ServiceStatus status = SERVICE_FAILURE;
UIMessageSupervisor supervisor;
size_t errorCount = 0;
for(size_t i = 0; i < targets_.size(); i++)
{
ITagWriter* pTagWriter = TagWriterFactory::Create(targets_[i]);
if(pTagWriter != 0)
{
if(pTagWriter->InsertProperties(targets_[i], mediaProperties_) == false)
{
UnicodeStringStream os;
os << "Failed to insert tags into " << targets_[i] << ".";
supervisor.RegisterError(os.str());
errorCount++;
}
if(pTagWriter->InsertCoverImage(targets_[i], coverImage_) == false)
{
UnicodeStringStream os;
os << "Failed to insert cover image into " << targets_[i] << ".";
supervisor.RegisterError(os.str());
errorCount++;
}
if(pTagWriter->ReplaceChapterMarkers(targets_[i], chapterMarkers_) == false)
{
UnicodeStringStream os;
os << "Failed to insert chapter markers into " << targets_[i] << ".";
supervisor.RegisterError(os.str());
errorCount++;
}
SafeRelease(pTagWriter);
}
}
if(0 == errorCount)
{
for(size_t i = 0; i < targets_.size(); i++)
{
UnicodeStringStream os;
os << targets_[i] << " has been updated successfully.";
supervisor.RegisterSuccess(os.str());
}
status = SERVICE_SUCCESS;
}
return status;
}
bool InsertMediaPropertiesAction::ConfigureSources()
{
bool result = false;
UIMessageSupervisor supervisor;
size_t invalidAssetCount = 0;
mediaProperties_.Clear();
coverImage_.clear();
chapterMarkers_.clear();
mediaProperties_ = MediaProperties::ParseProjectNotes();
if(mediaProperties_.Validate() == false)
{
supervisor.RegisterWarning("ID3v2 tags have not been defined yet.");
invalidAssetCount++;
}
coverImage_ = FindCoverImage();
if(coverImage_.empty() == true)
{
supervisor.RegisterWarning("Cover image is missing.");
invalidAssetCount++;
}
chapterMarkers_ = ReaperProjectManager::Instance().CurrentProject().AllMarkers();
if(chapterMarkers_.empty() == true)
{
supervisor.RegisterWarning("No chapters have been set.");
invalidAssetCount++;
}
if(invalidAssetCount >= 3)
{
supervisor.RegisterError("Specify at least one ID3v2 tag, a cover image or a chapter marker.");
result = false;
}
else
{
result = true;
}
return result;
} // namespace reaper
bool InsertMediaPropertiesAction::ConfigureTargets()
{
UIMessageSupervisor supervisor;
targets_.clear();
#ifdef ULTRASCHALL_ENABLE_MP4
static const size_t MAX_FILE_EXTENSIONS = 3;
static const char* fileExtensions[MAX_FILE_EXTENSIONS] = {".mp3", ".mp4", ".m4a"};
#else // #ifdef ULTRASCHALL_ENABLE_MP4
static const size_t MAX_FILE_EXTENSIONS = 1;
static const char* fileExtensions[MAX_FILE_EXTENSIONS] = {".mp3"};
#endif // #ifdef ULTRASCHALL_ENABLE_MP4
for(size_t i = 0; i < MAX_FILE_EXTENSIONS; i++)
{
UnicodeString targetName = CreateProjectPath(fileExtensions[i]);
if(FileManager::FileExists(targetName) != false)
{
targets_.push_back(targetName);
}
}
if(targets_.empty() == true)
{
supervisor.RegisterWarning("Ultraschall can't find a suitable media file. Please select an alternative media "
"file from the file selection dialog after closing this message.");
UIFileDialog fileDialog("Select audio file");
const UnicodeString target = fileDialog.BrowseForAudio();
if(target.empty() == false)
{
targets_.push_back(target);
}
}
return targets_.empty() == false;
}
UnicodeString InsertMediaPropertiesAction::FindCoverImage()
{
UnicodeString coverImage;
UnicodeStringArray files;
const UnicodeStringArray extensions{".jpg", ".jpeg", ".png"};
for(size_t i = 0; i < extensions.size(); i++)
{
files.push_back(FileManager::AppendPath(GetProjectDirectory(), "cover") + extensions[i]);
files.push_back(FileManager::AppendPath(GetProjectDirectory(), GetProjectName()) + extensions[i]);
}
const size_t imageIndex = FileManager::FileExists(files);
if(imageIndex != -1)
{
coverImage = files[imageIndex];
}
return coverImage;
}
}} // namespace ultraschall::reaper
| 32.943396 | 118 | 0.634307 | [
"vector"
] |
8f13b9fcd6b704d7a590318323eb5f0d83d51dd3 | 3,216 | hpp | C++ | code/hologine_platform/hologine/core/memory/heap_allocator.hpp | aaronbolyard/hologine | 6fd07d28c6acfd9cfc49b3efa55b23c95240374e | [
"MIT"
] | 3 | 2015-02-23T21:32:18.000Z | 2017-08-14T10:34:52.000Z | code/hologine_platform/hologine/core/memory/heap_allocator.hpp | aaronbolyard/hologine | 6fd07d28c6acfd9cfc49b3efa55b23c95240374e | [
"MIT"
] | null | null | null | code/hologine_platform/hologine/core/memory/heap_allocator.hpp | aaronbolyard/hologine | 6fd07d28c6acfd9cfc49b3efa55b23c95240374e | [
"MIT"
] | null | null | null | // This file is a part of Hologine.
//
// Hologine is a straight-forward framework for interactive simulations,
// most notably video games.
//
// Copyright 2015 Aaron Bolyard.
//
// For licensing information, review the LICENSE file located at the root
// directory of the source package.
#ifndef HOLOGINE_CORE_MEMORY_HEAP_ALLOCATOR_HPP_
#define HOLOGINE_CORE_MEMORY_HEAP_ALLOCATOR_HPP_
#include <cstddef>
#include "core/memory/allocator.hpp"
#include "core/memory/buffer.hpp"
#include "core/memory/memory_arena_pool.hpp"
#include "core/memory/pool_allocator.hpp"
namespace holo
{
class pool_allocator;
// Provides an interface to a general allocation strategy.
class heap_allocator final : public allocator
{
public:
// Constructs a heap allocator with the provided parameters.
//
// 'arena_size' determines the minimum size of memory arenas
// allocated by the allocator and must be a power of two.
//
// 'arena_count' determines how many memory regions are permitted in
// total.
//
// 'pool_start' determines the minimum size of a pool while 'pool_end'
// determines the maximum size. Small allocations (that is, allocations
// less than 'pool_end') may be stored in a pool, resulting in a faster
// allocation pattern. The behavior is implementation-specific, however.
//
// Therefore, the only guarantee is that a number of pools will be created
// to fit smaller allocations, and that the largest pool will be
// 'pool_end' bytes large, while the smallest will be 'pool_start'.
//
// Note: size parameters are in bytes.
explicit heap_allocator(
std::size_t arena_size = 0x40000u,
std::size_t arena_count = 0x100u,
std::size_t pool_start = 0x20u,
std::size_t pool_end = 0x10000u);
// Frees all memory allocated.
//
// Any memory allocated by this instance is no longer valid.
~heap_allocator();
// Allocates a block of memory from the heap allocator.
//
// If the allocation could not be made, then this method returns NULL and
// an appropriate exception is pushed.
void* allocate(std::size_t size, std::size_t alignment = default_alignment);
// Deallocates a block of memory previously obtained from this allocator.
void deallocate(void* pointer);
private:
// The maximum number of pools allocated by the heap allocator.
//
// Keep in mind each pool is a power of two. The last pool, in this
// pattern, would make 4 gigabyte allocations for one object! 32 max pools
// is more than plenty.
static const std::size_t maximum_pool_count = 32;
// The memory arena pool.
holo::memory_arena_pool memory_arena_pool;
// Static buffer used to generate an array of pool allocators.
holo::buffer<sizeof(holo::pool_allocator) * maximum_pool_count> pool_allocators_buffer;
// Pointer to an array of pool allocators.
//
// This is the value of pool_allocator_buffer::get().
pool_allocator* pool_allocators;
// Minimum size of a pool, represented as the log2 (e.g., 32 would be 5).
std::size_t minimum_pool_size;
// Maximum size of a pool, represented as the log2 (e.g., 8192 would be
// 13).
std::size_t maximum_pool_size;
};
}
#endif
| 34.212766 | 90 | 0.722326 | [
"object"
] |
8f179e15e0762edcd12c26663c6da5428ac12698 | 34,757 | cpp | C++ | src/chainparams.cpp | Ankh-Trust/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 2 | 2019-10-31T11:56:31.000Z | 2019-11-02T08:48:45.000Z | src/chainparams.cpp | Ankh-fdn/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 2 | 2019-11-22T18:49:20.000Z | 2020-10-06T11:44:46.000Z | src/chainparams.cpp | Ankh-fdn/credit-core | fa6fd67bdc9846cc40ee24f9a64e610e634b9356 | [
"MIT"
] | 1 | 2020-06-09T16:15:27.000Z | 2020-06-09T16:15:27.000Z |
// Copyright (c) 2009-2019 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Developers
// Copyright (c) 2014-2019 The Dash Core Developers
// Copyright (c) 2016-2019 Duality Blockchain Solutions Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "arith_uint256.h"
#include "consensus/merkle.h"
#include "hash.h"
#include "streams.h"
#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"
#include "uint256.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
#include "chainparamsseeds.h"
const arith_uint256 maxUint = UintToArith256(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, const uint32_t nTime, const uint32_t nNonce, const uint32_t nBits, const int32_t nVersion, const CAmount& genesisReward)
{
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 1591833600 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = genesisOutputScript;
CBlock genesis;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.nVersion = nVersion;
genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));
genesis.hashPrevBlock.SetNull();
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
static void MineGenesis(CBlockHeader& genesisBlock, const uint256& powLimit, bool noProduction)
{
if (noProduction)
genesisBlock.nTime = std::time(0);
genesisBlock.nNonce = 0;
printf("NOTE: Genesis nTime = %u \n", genesisBlock.nTime);
printf("WARN: Genesis nNonce (BLANK!) = %u \n", genesisBlock.nNonce);
arith_uint256 besthash = maxUint;
arith_uint256 hashTarget = UintToArith256(powLimit);
printf("Target: %s\n", hashTarget.GetHex().c_str());
arith_uint256 newhash = UintToArith256(genesisBlock.GetHash());
while (newhash > hashTarget) {
genesisBlock.nNonce++;
if (genesisBlock.nNonce == 0) {
printf("NONCE WRAPPED, incrementing time\n");
++genesisBlock.nTime;
}
// If nothing found after trying for a while, print status
if ((genesisBlock.nNonce & 0xfff) == 0)
printf("nonce %08X: hash = %s (target = %s)\n",
genesisBlock.nNonce, newhash.ToString().c_str(),
hashTarget.ToString().c_str());
if (newhash < besthash) {
besthash = newhash;
printf("New best: %s\n", newhash.GetHex().c_str());
}
newhash = UintToArith256(genesisBlock.GetHash());
}
printf("Genesis nTime = %u \n", genesisBlock.nTime);
printf("Genesis nNonce = %u \n", genesisBlock.nNonce);
printf("Genesis nBits: %08x\n", genesisBlock.nBits);
printf("Genesis Hash = %s\n", newhash.ToString().c_str());
printf("Genesis Hash Merkle Root = %s\n", genesisBlock.hashMerkleRoot.ToString().c_str());
}
/**
* Build the genesis block. Note that the output of its generation
* transaction cannot be spent since it did not originally exist in the
* database.
*
* CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
* CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
* CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
* CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
* vMerkleTree: e0028e
*/
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char* pszTimestamp = "Put on the full armor of God, so that you can take your stand against the devil's schemes";
const CScript genesisOutputScript = CScript() << ParseHex("") << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
/**
* Main network
*/
class CMainParams : public CChainParams
{
public:
CMainParams()
{
strNetworkID = "main";
consensus.nRewardsStart = 5; // PoW Rewards begin on block 5
consensus.nServiceNodePaymentsStartBlock = 32000; // ServiceNode Payments begin on block 32000
consensus.nMinCountServiceNodesPaymentStart = 1; // ServiceNode Payments begin once 1 ServiceNodes exist or more.
consensus.nInstantSendConfirmationsRequired = 11;
consensus.nInstantSendKeepLock = 24;
consensus.nBudgetPaymentsStartBlock = 10800; // actual historical value
consensus.nBudgetPaymentsCycleBlocks = 87660; //Blocks per month
consensus.nBudgetPaymentsWindowBlocks = 100;
consensus.nBudgetProposalEstablishingTime = 24 * 60 * 60;
consensus.nSuperblockStartBlock = 10800;
consensus.nSuperblockStartHash = uint256S("000007856f7f9cb78b2aebf7535e3c0d8e4ef60036ba00ecc95bdd7ecc72f89a");
consensus.nSuperblockCycle = 87660; // 2880 (Blocks per day) x 365.25 (Days per Year) / 12 = 87660
consensus.nGovernanceMinQuorum = 10;
consensus.nGovernanceFilterElements = 20000;
consensus.nServiceNodeMinimumConfirmations = 15;
consensus.nMajorityEnforceBlockUpgrade = 750;
consensus.nMajorityRejectBlockOutdated = 950;
consensus.nMajorityWindow = 1000;
consensus.powLimit = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 30 * 64; // Credit: 1920 seconds [original aim 12h]
consensus.nPowTargetSpacing = DEFAULT_AVERAGE_POW_BLOCK_TIME; // Credit: 30s [original aim 128s]
consensus.nUpdateDiffAlgoHeight = 10; // Credit: Algorithm fork block
consensus.nPowAveragingWindow = 5;
consensus.nPowMaxAdjustUp = 32;
consensus.nPowMaxAdjustDown = 48;
assert(maxUint / UintToArith256(consensus.powLimit) >= consensus.nPowAveragingWindow);
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 321; // 95% of nMinerConfirmationWindow [original aim 320.625 = 321 blocks]
consensus.nMinerConfirmationWindow = 30; // nPowTargetTimespan / nPowTargetSpacing [original aim 337.5 = 338 blocks]
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1513591800; // Dec 18th 2017 10:10:00
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1545134400; // Dec 18th 2018 12:00:00
// Deployment of BIP147
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 1533945600; // Aug 11th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = 1565481600; // Aug 11th, 2019
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nWindowSize = 4032;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nThreshold = 3226; // 80% of 4032
// Deployment of InstantSend autolocks
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].bit = 4;
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nStartTime = 1533945600; // Aug 11th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nTimeout = 1565481600; // Aug 11th, 2019
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nWindowSize = 4032;
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nThreshold = 3226; // 80% of 4032
// The best chain should have at least this much work.
consensus.nMinimumChainWork = 32000;
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x00000bfa926462511071c77070f8a990db10b2bc4c050aba77111d60fd2c10b2"); // 32000
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 32-bit integer with any alignment.
*/
pchMessageStart[0] = 0x65;
pchMessageStart[1] = 0x67;
pchMessageStart[2] = 0x7a;
pchMessageStart[3] = 0x85;
vAlertPubKey = ParseHex("045d786a68d9da26e8edb3f770639e409d200a9aaab9a051dea55f8ff7886ee91df21d4e3ee96f8bdbe38558bf641995dcecfa37d2343cf112bf15c2c03ee322e1");
nDefaultPort = DEFAULT_P2P_PORT;
nPruneAfterHeight = 87660;
startNewChain = false;
genesis = CreateGenesisBlock(1591830336, 1102454, UintToArith256(consensus.powLimit).GetCompact(), 1, (1 * COIN));
if (startNewChain == true) {
MineGenesis(genesis, consensus.powLimit, true);
}
consensus.hashGenesisBlock = genesis.GetHash();
if (!startNewChain) {
assert(consensus.hashGenesisBlock == uint256S("0x0000049d099254d27f72451dd68377969aaef8b6cb6d673859ee9c9e8ec437a6"));
assert(genesis.hashMerkleRoot == uint256S("0xcf42d6a146359c277a6620e802ff3511ec0877c588fd5e26d996e431befb966c"));
}
vSeeds.push_back(CDNSSeedData("ankh-trust.com", "dnsseed1.ankh-trust.com"));
vSeeds.push_back(CDNSSeedData("ankh-trust.com", "dnsseed2.ankh-trust.com"));
// Credit addresses start with 'C'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 28);
// Credit script addresses start with '5'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 10);
// Credit private keys start with 'y'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 140);
// Credit BIP32 pubkeys start with 'xpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
// Credit BIP32 prvkeys start with 'xprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
// Credit Stealth Address start with 'L'
base58Prefixes[STEALTH_ADDRESS] = {0x0F};
// Credit BIP44 coin type is '5'
nExtCoinType = 5;
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
fMiningRequiresPeers = true;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fRequireRoutableExternalIP = true;
fMineBlocksOnDemand = false;
fAllowMultipleAddressesFromGroup = false;
fAllowMultiplePorts = false;
nPoolMaxTransactions = 3;
nFulfilledRequestExpireTime = 60 * 60; // fulfilled requests expire in 1 hour
vSporkAddresses = {"CJRBs6AwoRqYsfoyMKMCaVziDdHVFrCKE1"};
nMinSporkKeys = 1;
checkpointData = (CCheckpointData){
boost::assign::map_list_of
(0, uint256S("0x0000049d099254d27f72451dd68377969aaef8b6cb6d673859ee9c9e8ec437a6"))
(250, uint256S("0x00000d97524be1a7caa42ac5f658884ba1f26185bced893cf87098d0b19254cd"))
(500, uint256S("0x0000049bbd385b6f55abfce05a45015b4666278d77686074efbf89ea40bc5de4"))
(1000, uint256S("0x000005c596e3447f27b67560a6679b59ad4b59802029daded0eb4ddbaf573511"))
(2500, uint256S("0x00000554a35ac5a29a1249bf363b7d6bdc4f50c91065593d9c52250d668b3ecf"))
(5000, uint256S("0x0000043c8c7a8e388dd63664f6eb8eee41c576ea14d764b481a7cc30a19c41a8"))
(10000, uint256S("0x00000225bdbddc9123fea8e19fa30a6f359ea53a387d707d87b4ef309ce88d6d"))
(25000, uint256S("0x000008562088281c54f2d5e7c3a38a957a42a75501a1b5b386b8644b0bc6e74a"))
(50000, uint256S("0x000007fd129a9cb4b22ed627639e0a9d93426d840daec0c41de1ab8344f09768"))
(100000, uint256S("0x000005a18c659973a15e5c01f4342096bef2e694d2d016b2abcd0349ab6528e4"))
};
chainTxData = ChainTxData{
0, // * UNIX timestamp of last known number of transactions
0, // * total number of transactions between genesis and that timestamp
// (the tx=... number in the SetBestChain debug.log lines)
0.1 // * estimated number of transactions per second after that timestamp
};
}
};
static CMainParams mainParams;
/**
* Testnet (v3)
*/
class CTestNetParams : public CChainParams
{
public:
CTestNetParams()
{
strNetworkID = "test";
consensus.nRewardsStart = 0; // Rewards starts on block 0
consensus.nServiceNodePaymentsStartBlock = 0;
consensus.nMinCountServiceNodesPaymentStart = 1; // ServiceNode Payments begin once 1 ServiceNode exists or more.
consensus.nInstantSendConfirmationsRequired = 11;
consensus.nInstantSendKeepLock = 24;
consensus.nBudgetPaymentsStartBlock = 200;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 10;
consensus.nBudgetProposalEstablishingTime = 60 * 20;
consensus.nSuperblockStartBlock = 0;
consensus.nSuperblockStartHash = uint256(); // do not check this on testnet
consensus.nSuperblockCycle = 24; // Superblocks can be issued hourly on testnet
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 500;
consensus.nServiceNodeMinimumConfirmations = 1;
consensus.nMajorityEnforceBlockUpgrade = 510;
consensus.nMajorityRejectBlockOutdated = 750;
consensus.nMajorityWindow = 1000;
consensus.powLimit = uint256S("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowAveragingWindow = 5;
consensus.nPowMaxAdjustUp = 32;
consensus.nPowMaxAdjustDown = 48;
consensus.nPowTargetTimespan = 30 * 64; // Credit: 1920 seconds
consensus.nPowTargetSpacing = DEFAULT_AVERAGE_POW_BLOCK_TIME;
consensus.nUpdateDiffAlgoHeight = 10; // Credit: Algorithm fork block
assert(maxUint / UintToArith256(consensus.powLimit) >= consensus.nPowAveragingWindow);
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 254; // 75% of nMinerConfirmationWindow
consensus.nMinerConfirmationWindow = 30; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1513591800; // Dec 18th 2017 10:10:00
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1545134400; // Dec 18th 2018 12:00:00
// Deployment of BIP147
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 1517792400; // Feb 5th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = 1549328400; // Feb 5th, 2019
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nThreshold = 50; // 50% of 100
// Deployment of InstantSend autolocks
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].bit = 4;
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nStartTime = 1532476800; // Jul 25th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nTimeout = 1564012800; // Jul 25th, 2019
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nThreshold = 50; // 50% of 100
// The best chain should have at least this much work.
consensus.nMinimumChainWork = 0; // 0
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x"); // 50
pchMessageStart[0] = 0x35;
pchMessageStart[1] = 0x38;
pchMessageStart[2] = 0x1b;
pchMessageStart[3] = 0x45;
vAlertPubKey = ParseHex("04e6a381e79100342992ff72e825962b8dcfee89e7586aa77760f4ec4a1a7c222e40fefbccd33403d7febbfe9c99a5e4553c2615e9cdc29612ed56836f50a7a2f4");
nDefaultPort = DEFAULT_P2P_PORT + 100;
nPruneAfterHeight = 100;
startNewChain = false;
genesis = CreateGenesisBlock(1591831730, 22, UintToArith256(consensus.powLimit).GetCompact(), 1, (1 * COIN));
if (startNewChain == true) {
MineGenesis(genesis, consensus.powLimit, true);
}
consensus.hashGenesisBlock = genesis.GetHash();
if (!startNewChain) {
assert(consensus.hashGenesisBlock == uint256S("0x001e293da952831f70af634c8bfb8c580a1d1e0d0ba1151a74f7e5d727c29262"));
assert(genesis.hashMerkleRoot == uint256S("0xcf42d6a146359c277a6620e802ff3511ec0877c588fd5e26d996e431befb966c"));
}
vFixedSeeds.clear();
vSeeds.clear();
//vSeeds.push_back(CDNSSeedData("", ""));
//vSeeds.push_back(CDNSSeedData("", ""));
// Testnet Credit addresses start with 'c'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 87);
// Testnet Credit script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 10);
// Testnet private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 158);
// Testnet Credit BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
// Testnet Credit BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
// Credit Stealth Address start with 'T'
base58Prefixes[STEALTH_ADDRESS] = {0x15};
// Testnet Credit BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
fMiningRequiresPeers = false;
fDefaultConsistencyChecks = false;
fRequireStandard = false;
fRequireRoutableExternalIP = true;
fMineBlocksOnDemand = false;
fAllowMultipleAddressesFromGroup = false;
fAllowMultiplePorts = false;
nPoolMaxTransactions = 3;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
vSporkAddresses = {"cE9XsKfm3Y9t7jTJ9SzAToiD8CDHZFAd2o"};
nMinSporkKeys = 1;
checkpointData = (CCheckpointData){
boost::assign::map_list_of
(0, uint256S("0x"))
};
chainTxData = ChainTxData{
0, // * UNIX timestamp of last known number of transactions
0, // * total number of transactions between genesis and that timestamp
// (the tx=... number in the SetBestChain debug.log lines)
0.1 // * estimated number of transactions per second after that timestamp
};
}
};
static CTestNetParams testNetParams;
/**
* Regression test
*/
class CRegTestParams : public CChainParams
{
public:
CRegTestParams()
{
strNetworkID = "regtest";
consensus.nRewardsStart = 0; // Rewards starts on block 0
consensus.nServiceNodePaymentsStartBlock = 0;
consensus.nMinCountServiceNodesPaymentStart = 1; // ServiceNode Payments begin once 1 ServiceNode exists or more.
consensus.nInstantSendConfirmationsRequired = 11;
consensus.nInstantSendKeepLock = 24;
consensus.nBudgetPaymentsStartBlock = 1000;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 10;
consensus.nBudgetProposalEstablishingTime = 60 * 20;
consensus.nSuperblockStartBlock = 0;
consensus.nSuperblockStartHash = uint256(); // do not check this on regtest
consensus.nSuperblockCycle = 10;
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 100;
consensus.nServiceNodeMinimumConfirmations = 1;
consensus.nMajorityEnforceBlockUpgrade = 750;
consensus.nMajorityRejectBlockOutdated = 950;
consensus.nMajorityWindow = 1000;
consensus.powLimit = uint256S("000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowAveragingWindow = 5;
consensus.nPowMaxAdjustUp = 32;
consensus.nPowMaxAdjustDown = 48;
consensus.nPowTargetTimespan = 30 * 64; // Credit: 1920 seconds
consensus.nPowTargetSpacing = DEFAULT_AVERAGE_POW_BLOCK_TIME;
consensus.nUpdateDiffAlgoHeight = 10; // Credit: Algorithm fork block
assert(maxUint / UintToArith256(consensus.powLimit) >= consensus.nPowAveragingWindow);
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = true;
consensus.nRuleChangeActivationThreshold = 254; // 75% of nMinerConfirmationWindow
consensus.nMinerConfirmationWindow = 30; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].bit = 4;
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_ISAUTOLOCKS].nTimeout = 999999999999ULL;
// The best chain should have at least this much work.
consensus.nMinimumChainWork = 0;
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x");
pchMessageStart[0] = 0x37;
pchMessageStart[1] = 0x3a;
pchMessageStart[2] = 0x1d;
pchMessageStart[3] = 0x47;
vAlertPubKey = ParseHex("043ec9f8941d64bcb9abe169aad9400ca3bc713d0b89ccd5dd6f54fac98831cec17fc87f4665fc83ace24e7081f5b6f0ee6cf946195174ba1bdf1eda650573c632");
nDefaultPort = DEFAULT_P2P_PORT + 200;
nPruneAfterHeight = 100;
startNewChain = false;
genesis = CreateGenesisBlock(1591831730, 744, UintToArith256(consensus.powLimit).GetCompact(), 1, (1 * COIN));
if (startNewChain == true) {
MineGenesis(genesis, consensus.powLimit, true);
}
consensus.hashGenesisBlock = genesis.GetHash();
if (!startNewChain) {
assert(consensus.hashGenesisBlock == uint256S("0x000dd558f4324c4df1740bcab666ee9f7b61aa863b1de62bc864d780dbab64cd"));
assert(genesis.hashMerkleRoot == uint256S("0xcf42d6a146359c277a6620e802ff3511ec0877c588fd5e26d996e431befb966c"));
}
vFixedSeeds.clear(); //! Regtest mode doesn't have any fixed seeds.
vSeeds.clear(); //! Regtest mode doesn't have any DNS seeds.
fMiningRequiresPeers = false;
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fRequireRoutableExternalIP = true;
fMineBlocksOnDemand = true;
fAllowMultipleAddressesFromGroup = false;
fAllowMultiplePorts = false;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
vSporkAddresses = {"yjDHexSC7vHmf7KYwDaB5ybiARup1Wj88m"}; //private key: cUJ3aeHjikcaixh8k6gjwNESazyMqXfjKXeXzpgUVXe3UBMd2A2A
nMinSporkKeys = 1;
checkpointData = (CCheckpointData){
boost::assign::map_list_of(0, uint256S("0x"))};
chainTxData = ChainTxData{
0, // * UNIX timestamp of last known number of transactions
0, // * total number of transactions between genesis and that timestamp
// (the tx=... number in the SetBestChain debug.log lines)
0.1 // * estimated number of transactions per second after that timestamp
};
// Regtest Credit addresses start with 'y'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 140);
// Regtest Credit script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19);
// Regtest private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239);
// Regtest Credit BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
// Regtest Credit BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
// Credit Stealth Address start with 'R'
base58Prefixes[STEALTH_ADDRESS] = {0x13};
// Regtest Credit BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
}
void UpdateBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
consensus.vDeployments[d].nStartTime = nStartTime;
consensus.vDeployments[d].nTimeout = nTimeout;
}
};
static CRegTestParams regTestParams;
/**
* Privatenet
*/
class CPrivateNetParams : public CChainParams
{
public:
CPrivateNetParams()
{
strNetworkID = "privatenet";
consensus.nRewardsStart = 0; // Rewards starts on block 0
consensus.nServiceNodePaymentsStartBlock = 0;
consensus.nMinCountServiceNodesPaymentStart = 1; // ServiceNode Payments begin once 1 ServiceNode exists or more.
consensus.nInstantSendConfirmationsRequired = 11;
consensus.nInstantSendKeepLock = 24;
consensus.nBudgetPaymentsStartBlock = 200;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 10;
consensus.nBudgetProposalEstablishingTime = 60 * 20;
consensus.nSuperblockStartBlock = 0;
consensus.nSuperblockStartHash = uint256(); // do not check this on testnet
consensus.nSuperblockCycle = 24; // Superblocks can be issued hourly on testnet
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 500;
consensus.nServiceNodeMinimumConfirmations = 1;
consensus.nMajorityEnforceBlockUpgrade = 510;
consensus.nMajorityRejectBlockOutdated = 750;
consensus.nMajorityWindow = 1000;
consensus.powLimit = uint256S("0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowAveragingWindow = 5;
consensus.nPowMaxAdjustUp = 32;
consensus.nPowMaxAdjustDown = 48;
consensus.nPowTargetTimespan = 30 * 64; // Credit: 1920 seconds
consensus.nPowTargetSpacing = DEFAULT_AVERAGE_POW_BLOCK_TIME;
consensus.nUpdateDiffAlgoHeight = 10; // Credit: Algorithm fork block
assert(maxUint / UintToArith256(consensus.powLimit) >= consensus.nPowAveragingWindow);
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 254; // 75% of nMinerConfirmationWindow
consensus.nMinerConfirmationWindow = 30; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1513591800; // Dec 18th 2017 10:10:00
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1545134400; // Dec 18th 2018 12:00:00
// The best chain should have at least this much work.
consensus.nMinimumChainWork = 0; // 0
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x"); //15
pchMessageStart[0] = 0x35;
pchMessageStart[1] = 0x38;
pchMessageStart[2] = 0x1b;
pchMessageStart[3] = 0x45;
// Alert key
vAlertPubKey = ParseHex("04c1d08f17a0eedb3aa465676f39134e39f180fceefb793e85cfbe9066157a52cbfc7cfa63fc51f3a1ef001d60f10e0561dbbe032aa32f13b180039de60527cc86");
nDefaultPort = DEFAULT_P2P_PORT + 300; // 33900
nPruneAfterHeight = 100;
startNewChain = false;
genesis = CreateGenesisBlock(1591831731, 25040, UintToArith256(consensus.powLimit).GetCompact(), 1, (1 * COIN));
if (startNewChain == true) {
MineGenesis(genesis, consensus.powLimit, true);
}
consensus.hashGenesisBlock = genesis.GetHash();
if (!startNewChain) {
assert(consensus.hashGenesisBlock == uint256S("0x00002e435e476837b630c19c93c2e372480c3bc8209f523cd0d0c2d47ab48123"));
assert(genesis.hashMerkleRoot == uint256S("0xcf42d6a146359c277a6620e802ff3511ec0877c588fd5e26d996e431befb966c"));
}
vFixedSeeds.clear();
vSeeds.clear();
//vSeeds.push_back(CDNSSeedData("", ""));
//vSeeds.push_back(CDNSSeedData("", ""));
// Privatenet Credit addresses start with 'z'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 142);
// Privatenet Credit script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 10);
// Privatenet private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 158);
// Privatenet Credit BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
// Privatenet Credit BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
// Privatenet Stealth Address start with 'P'
base58Prefixes[STEALTH_ADDRESS] = {0x12};
// Privatenet Credit BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_privatenet, pnSeed6_privatenet + ARRAYLEN(pnSeed6_privatenet));
fMiningRequiresPeers = false;
fDefaultConsistencyChecks = false;
fRequireStandard = false;
fRequireRoutableExternalIP = true;
fMineBlocksOnDemand = false;
fAllowMultipleAddressesFromGroup = false;
fAllowMultiplePorts = false;
nPoolMaxTransactions = 3;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
// To import spork key (D777Y4eMXrf1NgDSY1Q7kjoZuVso1ed7HL): importprivkey QWtd8MQx5kRgwmu4LGzSR5KRprf7RTCJc24yZ9BingoUMF1sBmcs
vSporkAddresses = {"zHAf5Nt9y6XHCoB79obPLqhm5ioG4vwQPa"};
nMinSporkKeys = 1;
checkpointData = (CCheckpointData){
boost::assign::map_list_of(0, uint256S("0x0000c5300560ed12db551d3dc80dbf12838ad92b260d5a8936f56844e96adb74"))};
chainTxData = ChainTxData{
0, // * UNIX timestamp of last known number of transactions
0, // * total number of transactions between genesis and that timestamp
// (the tx=... number in the SetBestChain debug.log lines)
0.1 // * estimated number of transactions per second after that timestamp
};
}
};
static CPrivateNetParams privateNetParams;
static CChainParams* pCurrentParams = 0;
const CChainParams& Params()
{
assert(pCurrentParams);
return *pCurrentParams;
}
CChainParams& Params(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return mainParams;
else if (chain == CBaseChainParams::TESTNET)
return testNetParams;
else if (chain == CBaseChainParams::REGTEST)
return regTestParams;
else if (chain == CBaseChainParams::PRIVATENET)
return privateNetParams;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectParams(const std::string& network)
{
SelectBaseParams(network);
pCurrentParams = &Params(network);
}
void UpdateRegtestBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
regTestParams.UpdateBIP9Parameters(d, nStartTime, nTimeout);
}
| 48.273611 | 242 | 0.703772 | [
"vector"
] |
8f192ae90eb6e42f6969c415ad911c0295ec111e | 25,010 | cc | C++ | src/suif1/TaskFusion.cc | paulhjkelly/taskgraph-metaprogramming | 54c4e2806a97bec555a90784ab4cf0880660bf89 | [
"BSD-3-Clause"
] | 5 | 2020-04-11T21:30:19.000Z | 2021-12-04T16:16:09.000Z | src/suif1/TaskFusion.cc | paulhjkelly/taskgraph-metaprogramming | 54c4e2806a97bec555a90784ab4cf0880660bf89 | [
"BSD-3-Clause"
] | null | null | null | src/suif1/TaskFusion.cc | paulhjkelly/taskgraph-metaprogramming | 54c4e2806a97bec555a90784ab4cf0880660bf89 | [
"BSD-3-Clause"
] | null | null | null | #include <memory>
#include <vector>
#include <set>
#include <list>
#include <map>
#include <utility>
#include <iterator>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <suif1.h>
#include <useful.h>
#include <dependence.h>
#include <iostream>
//#define VERBOSE_FUSION
#ifdef VERBOSE_FUSION
#define INFO printf
#else
#define INFO if ( false ) printf
#endif
//char *prog_who_string = "fusion";
//char *prog_ver_string = "1";
namespace
{
enum LoopFusionResult
{
FUSED_INTO_FIRST,
FUSED_INTO_SECOND,
FUSION_FAILED
};
void fuseLoopsByUsage(std::list<tree_for*>& loops);
void rename(instruction * ins, var_sym * from, var_sym * to);
void rename(tree_node * tn, var_sym * from, var_sym * to);
void rename(tree_node_list * tnl, var_sym * from, var_sym * to);
void rename(tree_node_list * tnl, var_sym * from, var_sym * to)
{
tree_node_list_iter iter(tnl);
while (!iter.is_empty())
{
tree_node *tn = iter.step();
rename(tn, from, to);
}
}
void rename(tree_node * tn, var_sym * from, var_sym * to)
{
switch (tn->kind())
{
case TREE_FOR:
{
tree_for *const tnf = static_cast < tree_for * >(tn);
rename(tnf->lb_list(), from, to);
rename(tnf->ub_list(), from, to);
rename(tnf->step_list(), from, to);
rename(tnf->landing_pad(), from, to);
rename(tnf->body(), from, to);
break;
}
case TREE_IF:
{
tree_if *const tni = static_cast < tree_if * >(tn);
rename(tni->header(), from, to);
rename(tni->then_part(), from, to);
rename(tni->else_part(), from, to);
break;
}
case TREE_LOOP:
{
tree_loop *const tnl = static_cast < tree_loop * >(tn);
rename(tnl->body(), from, to);
rename(tnl->test(), from, to);
break;
}
case TREE_BLOCK:
{
tree_block *const tnb = static_cast < tree_block * >(tn);
rename(tnb->body(), from, to);
break;
}
case TREE_INSTR:
{
tree_instr *const tnin = static_cast < tree_instr * >(tn);
rename(tnin->instr(), from, to);
break;
}
default:
{
assert(false);
break;
}
}
}
void rename(instruction* const ins, var_sym* const from, var_sym* const to)
{
for (unsigned i = 0; i < ins->num_srcs(); ++i)
{
operand op(ins->src_op(i));
if (op.is_instr())
{
rename(op.instr(), from, to);
}
else if (op.is_symbol() && op.symbol()->is_var() && op.symbol() == from)
{
ins->set_src_op(i, operand(to));
}
}
}
struct compareArray
{
compareArray(in_array* const _array) : array(_array)
{
}
bool operator() (in_array* const rhs) const
{
return get_sym_of_array(array) == get_sym_of_array(rhs);
}
in_array* const array;
};
class VariableAccess
{
public:
VariableAccess():tooComplicated(false)
{
}
void clear()
{
readScalarId.clear();
writeScalarId.clear();
readArray.clear();
writeArray.clear();
tooComplicated = false;
}
void merge(const VariableAccess& access)
{
tooComplicated = tooComplicated || access.tooComplicated;
readScalarId.insert(access.readScalarId.begin(), access.readScalarId.end());
writeScalarId.insert(access.writeScalarId.begin(), access.writeScalarId.end());
readArray.insert(access.readArray.begin(), access.readArray.end());
writeArray.insert(access.writeArray.begin(), access.writeArray.end());
}
void findVariableAccess(instruction* const ins, const bool base, const bool write)
{
unsigned start = 0;
if (ins->opcode() == io_array)
{
in_array* const ia = static_cast<in_array*>(ins);
var_sym* const sym = get_sym_of_array(ia);
if (write)
{
INFO("Write Array:%s\n", sym->name());
writeArray.insert(ia);
}
else
{
INFO("Read Array:%s\n", sym->name());
readArray.insert(ia);
}
}
if (base)
{
operand op(ins->dst_op());
if (op.is_symbol())
{
INFO("Base Write:%s\n", op.symbol()->name());
writeScalarId.insert(op.symbol());
}
if (op.is_instr())
{
assert(false);
}
}
if (ins->opcode() == io_jmp)
{
INFO("Complicated: Jump Statement\n");
tooComplicated = true;
return;
}
if (ins->opcode() == io_str || ins->opcode() == io_memcpy)
{
operand op(ins->src_op(0));
if (op.is_symbol())
{
INFO("Write:%s\n", op.symbol()->name());
writeScalarId.insert(op.symbol());
}
else if (op.is_instr())
{
if (op.instr()->opcode() == io_array)
{
findVariableAccess(op.instr(), false, true);
}
else
{
INFO("Complicated: Expected array\n");
tooComplicated = true;
return;
}
}
else
{
INFO("Complicated: Expected array or symbol\n");
tooComplicated = true;
return;
}
start = 1;
}
for (unsigned i = start; i < ins->num_srcs(); ++i)
{
operand op(ins->src_op(i));
if (op.is_symbol())
{
INFO("Read:%s\n", op.symbol()->name());
readScalarId.insert(op.symbol());
}
if (op.is_instr())
findVariableAccess(op.instr(), false, false);
}
}
void findVariableAccess(tree_node * const tn)
{
switch (tn->kind())
{
case TREE_FOR:
{
tree_for *const tnf = static_cast < tree_for * >(tn);
findVariableAccess(tnf->lb_list());
findVariableAccess(tnf->ub_list());
findVariableAccess(tnf->step_list());
findVariableAccess(tnf->landing_pad());
findVariableAccess(tnf->body());
break;
}
case TREE_IF:
{
tree_if *const tni = static_cast < tree_if * >(tn);
findVariableAccess(tni->header());
findVariableAccess(tni->then_part());
findVariableAccess(tni->else_part());
break;
}
case TREE_LOOP:
{
tree_loop *const tnl = static_cast < tree_loop * >(tn);
findVariableAccess(tnl->body());
findVariableAccess(tnl->test());
break;
}
case TREE_BLOCK:
{
tree_block *const tnb = static_cast < tree_block * >(tn);
findVariableAccess(tnb->body());
break;
}
case TREE_INSTR:
{
tree_instr *const tnin = static_cast < tree_instr * >(tn);
findVariableAccess(tnin->instr(), true, false);
break;
}
default:
{
assert(false);
break;
}
}
}
void findVariableAccess(tree_node_list* const loop)
{
tree_node_list_iter iter(loop);
while (!iter.is_empty())
findVariableAccess(iter.step());
}
void findVariableAccessBetween(tree_for* const first, tree_for* const second)
{
assert(first != second);
assert(first->parent() == second->parent());
tree_node_list* const list = first->parent();
tree_node_list_iter iter(list);
bool passedFirst = false;
bool reachedSecond = false;
while(!iter.is_empty() && !reachedSecond)
{
tree_node* const node = iter.step();
if (node == second)
{
reachedSecond = true;
assert(passedFirst);
}
if (passedFirst && !reachedSecond)
{
findVariableAccess(node);
}
if (node == first)
{
passedFirst = true;
assert(!reachedSecond);
}
}
}
bool checkScalars(const VariableAccess & varAccB) const
{
INFO("\nChecking Scalars\n");
for(std::set<sym_node*>::const_iterator writeIter=writeScalarId.begin(); writeIter!=writeScalarId.end(); ++writeIter)
{
if (varAccB.readScalarId.find(*writeIter) != varAccB.readScalarId.end())
{
INFO("Write/Read Conflict %s\n", (*writeIter)->name());
return false;
}
if (varAccB.writeScalarId.find(*writeIter) != varAccB.writeScalarId.end())
{
INFO("Write/Write Conflict %s\n", (*writeIter)->name());
return false;
}
}
for(std::set<sym_node*>::const_iterator readIter=readScalarId.begin(); readIter!=readScalarId.end(); ++readIter)
{
if(varAccB.writeScalarId.find(*readIter) != varAccB.writeScalarId.end())
{
INFO ( "Read/Write Conflict %s\n", (*readIter)->name ( ) );
return false;
}
}
return true;
}
// Only for inbetween code
bool checkArrays(const VariableAccess & varAccB) const
{
INFO("\nChecking Arrays\n");
for(std::set<in_array*>::const_iterator writeIter=writeArray.begin(); writeIter!=writeArray.end(); ++writeIter)
{
if (std::find_if(varAccB.readArray.begin(), varAccB.readArray.end(), compareArray(*writeIter)) != varAccB.readArray.end())
{
INFO("Read/Write Conflict %s\n", get_sym_of_array(*writeIter)->name());
return false;
}
if (std::find_if(varAccB.writeArray.begin(), varAccB.writeArray.end(), compareArray(*writeIter)) !=
varAccB.writeArray.end())
{
INFO("Write/Write Conflict %s\n", get_sym_of_array(*writeIter)->name());
return false;
}
}
for(std::set<in_array*>::iterator readIter=readArray.begin(); readIter!=readArray.end(); ++readIter)
{
if ( std::find_if(varAccB.writeArray.begin(), varAccB.writeArray.end(), compareArray(*readIter)) != varAccB.writeArray.end())
{
INFO ( "Write/Read Conflict %s\n", get_sym_of_array(*readIter )->name());
return false;
}
}
return true;
}
static var_sym* getArraySymbolFromInstruction(in_array* const instr)
{
return get_sym_of_array(instr);
}
std::set<var_sym*> getReadArrays()
{
std::set<var_sym*> arrays;
std::transform(readArray.begin(), readArray.end(), std::inserter(arrays, arrays.begin()), getArraySymbolFromInstruction);
return arrays;
}
std::set<var_sym*> getWrittenArrays()
{
std::set<var_sym*> arrays;
std::transform(writeArray.begin(), writeArray.end(), std::inserter(arrays, arrays.begin()), getArraySymbolFromInstruction);
return arrays;
}
public:
std::set<sym_node*> readScalarId, writeScalarId;
std::set<in_array*> readArray, writeArray;
bool tooComplicated;
};
bool dependenceTest(in_array* const arrayA, in_array* const arrayB)
{
deptest_result res;
std::auto_ptr<dvlist> dep(DependenceTest(arrayA, arrayB, 0, &res, TRUE));
if (res == dt_none)
{
INFO("None\n");
dep->clear();
return false;
}
else if (res == dt_indep)
{
INFO("Independent\n");
dep->clear();
}
else if (res == dt_no_common_nest)
{
INFO("No Common Nest\n");
dep->clear();
return false;
}
else if (res == dt_too_messy)
{
INFO("Messy\n");
dep->clear();
return false;
}
assert(dep.get() != NULL);
#ifdef VERBOSE_FUSION
dep->print(stdout);
#endif
dvlist_iter depiter(dep.get());
while (!depiter.is_empty())
{
distance_vector* const dv = depiter.step()->dv;
const int level = dv->first_not_eq();
if ( level != 0 )
{
const std::auto_ptr<distance> d(dv->thresh(level));
if (!(d->dir() == d_gt))
{
INFO ( "Illegal fusion\n" );
dep->clear();
return false;
}
}
}
dep->clear();
return true;
}
// Checks the reads and write of the array accesses.
// If array names are same, then do dependence checks.
bool checkArrayAccess(const VariableAccess & varAccA, const VariableAccess & varAccB)
{
INFO("\nChecking Arrays\n");
std::vector<in_array*>::const_iterator writeEnd, writeIter;
for(std::set<in_array*>::const_iterator writeIter=varAccA.writeArray.begin(); writeIter!=varAccA.writeArray.end(); ++writeIter)
{
var_sym* const writeSym = get_sym_of_array(*writeIter);
for(std::set<in_array*>::const_iterator iter=varAccB.readArray.begin(); iter!=varAccB.readArray.end(); ++iter)
{
if (writeSym == get_sym_of_array(*iter))
{
// Check Write Read
INFO("Write/Read Check %s %s\n", writeSym->name(), get_sym_of_array(*iter)->name());
if (!dependenceTest(*writeIter, *iter))
return false;
}
}
for(std::set<in_array*>::const_iterator iter=varAccB.writeArray.begin(); iter!=varAccB.writeArray.end(); ++iter)
{
if (writeSym == get_sym_of_array(*iter))
{
// Check Write Read
INFO("Write/Write Check %s %s\n", writeSym->name(), get_sym_of_array(*iter)->name());
if (!dependenceTest(*writeIter, *iter))
return false;
}
}
}
for(std::set<in_array*>::const_iterator writeIter=varAccB.writeArray.begin(); writeIter!=varAccB.writeArray.end(); ++writeIter)
{
var_sym* const writeSym = get_sym_of_array(*writeIter);
for(std::set<in_array*>::const_iterator iter=varAccA.readArray.begin(); iter!=varAccA.readArray.end(); ++iter)
{
if (writeSym == get_sym_of_array(*iter))
{
// Check Write Read
INFO("Read/Write Check %s %s\n", writeSym->name(), get_sym_of_array(*iter)->name());
if (!dependenceTest(*iter, *writeIter))
return false;
}
}
}
return true;
}
bool isBefore(tree_for* const first, tree_for* const second)
{
assert(first != second);
assert(first->parent() == second->parent());
tree_node_list* const list = first->parent();
tree_node_list_iter iter(list);
while(!iter.is_empty())
{
tree_node* const node = iter.step();
if (node == first)
return true;
if (node == second)
return false;
}
assert(false);
return false;
}
LoopFusionResult attemptLoopFusion(tree_for* const loopA, tree_for* const loopB)
{
assert(loopA != loopB);
assert(isBefore(loopA, loopB));
VariableAccess access;
access.findVariableAccessBetween(loopA, loopB);
bool mergeWithFirstLoop = true;
// Check Bounds
int lb, ub, step, blb, bub, bstep;
if (!(loopA->lb_is_constant(&lb) && loopA->ub_is_constant(&ub) && loopA->step_is_constant(&step)))
{
INFO("Non-constant bounds\n");
return FUSION_FAILED;
}
else if (!(loopB->lb_is_constant(&blb) && loopB->ub_is_constant(&bub) && loopB->step_is_constant(&bstep)))
{
INFO("Non-constant bounds\n");
return FUSION_FAILED;
}
else if (lb != blb || ub != bub || step != bstep)
{
INFO("Bounds do not match\n");
return FUSION_FAILED;
}
else if (loopA->test() != loopB->test())
{
INFO("Loops have different test\n");
return FUSION_FAILED;
}
else if (access.tooComplicated)
{
INFO("No fusion - In betwen code too Complicated\n");
return FUSION_FAILED;
}
// TODO: Check for landing pad
INFO("\nChecking Var Access\n");
VariableAccess varAccA, varAccB;
INFO("\nFirst Loop\n");
varAccA.findVariableAccess(loopA->body());
INFO("\nSecond Loop\n");
varAccB.findVariableAccess(loopB->body());
if (varAccA.tooComplicated)
{
INFO("No fusion - Loop A Complicated\n");
return FUSION_FAILED;
}
else if (varAccB.tooComplicated)
{
INFO("No fusion - Loop B Complicated\n");
return FUSION_FAILED;
}
// Check Scalars
INFO("\nChecking Scalars\n");
if (!varAccA.checkScalars(varAccB) )
return FUSION_FAILED;
// Check inbetween code
if (varAccA.checkScalars(access) && varAccA.checkArrays(access))
{
// If first loop does not interfere with intervening, prepend onto second
mergeWithFirstLoop = false;
INFO("Attempting merge with second loop\n");
}
else if (varAccB.checkScalars(access) && varAccB.checkArrays(access))
{
// If second loop does not interfere with the intervening, append to first
mergeWithFirstLoop = true;
INFO("Attempting merge with first loop\n");
}
else
{
// Both loops have dependencies on intervening, so fusion can't be done
return FUSION_FAILED;
}
bool renamed = false;
if (loopA->index() != loopB->index())
{
INFO("Loops have different index var\n");
if (find(varAccB.writeScalarId.begin(), varAccB.writeScalarId.end(), loopA->index()) != varAccB.writeScalarId.end())
{
INFO("First index variable used in second loop\n");
return FUSION_FAILED;
}
else if (find(varAccB.readScalarId.begin(), varAccB.readScalarId.end(), loopA->index()) != varAccB.readScalarId.end())
{
INFO("First index variable used in second loop\n");
return FUSION_FAILED;
}
// TODO: Set index to max if needed
if (mergeWithFirstLoop)
{
rename(loopB, loopB->index(), loopA->index());
renamed = true;
}
else
{
rename(loopA, loopA->index(), loopB->index());
renamed = true;
}
}
if (mergeWithFirstLoop)
{
tree_node_list_e *const headB = loopB->body()->head();
loopA->body()->append(loopB->body());
if (!checkArrayAccess(varAccA, varAccB))
{
INFO("Merging with first loop failed - putting body back\n");
tree_node_list_e *currentNode = headB;
while (currentNode != NULL)
{
tree_node_list_e *const nextNode = currentNode->next();
loopA->body()->remove(currentNode);
loopB->body()->append(currentNode);
currentNode = nextNode;
}
if (renamed)
rename(loopB, loopA->index(), loopB->index());
return FUSION_FAILED;
}
else
{
kill_node(loopB);
return FUSED_INTO_FIRST;
}
}
else
{
tree_node_list_e *const headA = loopA->body()->head();
tree_node_list_e *const headB = loopB->body()->head();
loopB->body()->push(loopA->body());
if (!checkArrayAccess(varAccA, varAccB))
{
INFO("Merging with second loop failed - putting body back\n");
tree_node_list_e *currentNode = headA;
while (currentNode != headB)
{
tree_node_list_e *const nextNode = currentNode->next();
loopB->body()->remove(currentNode);
loopA->body()->append(currentNode);
currentNode = nextNode;
}
if (renamed)
rename(loopA, loopB->index(), loopA->index());
return FUSION_FAILED;
}
else
{
kill_node(loopA);
return FUSED_INTO_SECOND;
}
}
}
void fuseLoopsByUsage(tree_node_list* const tnl)
{
std::list<tree_for*> loops;
tree_node_list_iter iter(tnl);
// Get list of high level loops
while (!iter.is_empty())
{
tree_node* const tn = iter.step();
if (tn->kind() == TREE_FOR)
{
tree_for* const tnf = static_cast < tree_for * >(tn);
loops.push_back(tnf);
}
}
// try to fuse high level loops
fuseLoopsByUsage(loops);
iter.reset(tnl);
while(!iter.is_empty())
{
tree_node* const tn = iter.step();
switch(tn->kind())
{
case TREE_FOR:
{
tree_for* const tnf = static_cast < tree_for * >(tn);
fuseLoopsByUsage(tnf->body());
break;
}
case TREE_IF:
{
tree_if *const tni = static_cast < tree_if * >(tn);
fuseLoopsByUsage(tni->then_part());
fuseLoopsByUsage(tni->else_part());
break;
}
case TREE_LOOP:
{
tree_loop *const tnl = static_cast < tree_loop * >(tn);
fuseLoopsByUsage(tnl->body());
fuseLoopsByUsage(tnl->test());
break;
}
case TREE_BLOCK:
{
tree_block *const tnb = static_cast < tree_block * >(tn);
fuseLoopsByUsage(tnb->body());
break;
}
case TREE_INSTR:
{
// Nothing to do as no loops to fuse inside instruction
break;
}
default:
{
assert(false);
break;
}
}
}
}
class LoopInfo
{
private:
tree_for* loop;
std::set<var_sym*> arrayAccess;
bool dead;
static const std::set<var_sym*> findArrayAccess(tree_for* const loop)
{
std::set<var_sym*> arrayAccess;
VariableAccess varAccess;
varAccess.findVariableAccess(loop);
const std::set<var_sym*> readAccess(varAccess.getReadArrays()), writeAccess(varAccess.getWrittenArrays());
arrayAccess.insert(readAccess.begin(), readAccess.end());
arrayAccess.insert(writeAccess.begin(), writeAccess.end());
return arrayAccess;
}
public:
LoopInfo(tree_for* const l) : loop(l), arrayAccess(findArrayAccess(l)), dead(false)
{
}
bool isDead() const
{
return dead;
}
bool attemptFusion(LoopInfo& otherLoop, const bool agressive)
{
assert(!dead);
assert(!otherLoop.dead);
// Give up if loops are same
if (loop == otherLoop.loop)
return false;
// If loops are wrong way round, reverse the method call
if (!isBefore(loop, otherLoop.loop))
return otherLoop.attemptFusion(*this, agressive);
// Do not fuse if loops do not access same array
std::set<var_sym*> intersection;
std::insert_iterator< std::set<var_sym*> > intersectionInserter(intersection, intersection.begin());
std::set_intersection(arrayAccess.begin(), arrayAccess.end(),
otherLoop.arrayAccess.begin(), otherLoop.arrayAccess.end(),
intersectionInserter);
// Fused only when they share array accesses or agressive is requested
if (intersection.empty() && !agressive)
return false;
const LoopFusionResult result = attemptLoopFusion(loop, otherLoop.loop);
if (result == FUSED_INTO_FIRST)
{
otherLoop.dead=true;
arrayAccess.insert(otherLoop.arrayAccess.begin(), otherLoop.arrayAccess.end());
return true;
}
else if (result == FUSED_INTO_SECOND)
{
dead = true;
otherLoop.arrayAccess.insert(arrayAccess.begin(), arrayAccess.end());
return true;
}
else if (result == FUSION_FAILED)
{
return false;
}
else
{
assert(false);
return false;
}
}
};
void fuseAll(std::vector<LoopInfo>& usage, const bool agressive)
{
bool changed = true;
while (changed)
{
changed = false;
for(std::vector<LoopInfo>::size_type firstIndex=0; firstIndex<usage.size(); ++firstIndex)
{
for(std::vector<LoopInfo>::size_type secondIndex=firstIndex; secondIndex<usage.size(); ++secondIndex)
{
if (!(usage[firstIndex].isDead() || usage[secondIndex].isDead()))
{
const bool successfulFusion = usage[firstIndex].attemptFusion(usage[secondIndex], agressive);
changed = changed || successfulFusion;
}
}
}
}
}
void fuseLoopsByUsage(std::list<tree_for*>& loops)
{
std::vector<LoopInfo> usage;
for(std::list<tree_for*>::iterator loopIter = loops.begin(); loopIter!=loops.end(); ++loopIter)
{
usage.push_back(LoopInfo(*loopIter));
}
fuseAll(usage, true);
}
}
/***************************************************************************
* create the annotations needed by dependence by calling fill_in_access *
* and start processing.. *
***************************************************************************/
namespace tg
{
void fusionDoProc(tree_proc* const tp, void *)
{
proc_sym* const psym = tp->proc();
INFO("=======%s======= \n", psym->name());
fill_in_access(tp);
fuseLoopsByUsage(tp->body());
}
}
/***************************************************************************
* Initialize and iterate over all the procedures. *
***************************************************************************/
/*main(int argc, char * argv[])
{
start_suif ( argc, argv );
suif_proc_iter ( argc, argv, do_proc, TRUE );
return 0;
}
*/
| 27.0671 | 134 | 0.563575 | [
"vector",
"transform"
] |
8f24d72aff07d4f0772f6849da6efe6e8cb9ac22 | 1,302 | hpp | C++ | include/global_parameters.hpp | jermp/opt_vbyte | e6fc79ef6c329e2b967f484ffba157e156a4c9bf | [
"MIT"
] | 12 | 2018-12-02T15:47:41.000Z | 2021-04-14T07:12:12.000Z | include/global_parameters.hpp | jermp/opt_vbyte | e6fc79ef6c329e2b967f484ffba157e156a4c9bf | [
"MIT"
] | null | null | null | include/global_parameters.hpp | jermp/opt_vbyte | e6fc79ef6c329e2b967f484ffba157e156a4c9bf | [
"MIT"
] | 2 | 2019-08-20T02:35:07.000Z | 2021-01-25T22:21:04.000Z | #pragma once
namespace pvb {
struct global_parameters {
global_parameters()
: ef_log_sampling0(9)
, ef_log_sampling1(8)
, rb_log_rank1_sampling(9)
, rb_log_sampling1(8)
, log_partition_size(7)
, blocks(3, 0)
, dense_avg_gap(0.0)
, sparse_avg_gap(0.0)
{}
template <typename Visitor>
void map(Visitor& visit)
{
visit
(ef_log_sampling0, "ef_log_sampling0")
(ef_log_sampling1, "ef_log_sampling1")
(rb_log_rank1_sampling, "rb_log_rank1_sampling")
(rb_log_sampling1, "rb_log_sampling1")
(log_partition_size, "log_partition_size")
;
}
uint8_t ef_log_sampling0;
uint8_t ef_log_sampling1;
uint8_t rb_log_rank1_sampling;
uint8_t rb_log_sampling1;
uint8_t log_partition_size;
/*
blocks[0] = # accessed blocks of type 0
blocks[1] = # accessed blocks of type 1
blocks[2] = # accessed blocks of type 2
*/
std::vector<uint64_t> blocks;
// avg. gap of dense and sparse blocks
double dense_avg_gap;
double sparse_avg_gap;
};
}
| 26.571429 | 64 | 0.545315 | [
"vector"
] |
8f25648b506a82706ff1b25f30b225c06bc7c31d | 6,302 | cpp | C++ | lib/ObjectDump/ObjectDump.cpp | thfabian/findsymbol | 88d8f1ce520884f67ebebe07eaddd35e8d71888f | [
"MIT"
] | 1 | 2016-03-18T21:37:33.000Z | 2016-03-18T21:37:33.000Z | lib/ObjectDump/ObjectDump.cpp | thfabian/findsymbol | 88d8f1ce520884f67ebebe07eaddd35e8d71888f | [
"MIT"
] | null | null | null | lib/ObjectDump/ObjectDump.cpp | thfabian/findsymbol | 88d8f1ce520884f67ebebe07eaddd35e8d71888f | [
"MIT"
] | null | null | null | /*******************************************************************- C++ -****\
*
* FindSymbol v1.0
* (c) 2015 Fabian Thüring
*
* This file is distributed under the MIT Open Source License. See
* LICENSE.TXT for details.
*
\******************************************************************************/
#include "findsymbol/Demangle/Demangle.h"
#include "findsymbol/ObjectDump/ObjectDump.h"
#include "findsymbol/Support/Error.h"
#include "findsymbol/Support/DebugLog.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Support/MemoryBuffer.h"
#include <cstring>
using namespace findsymbol;
using namespace llvm;
using namespace object;
ObjectDump::ObjectDump(const std::string& symbol,
const std::string& filename,
const Options& options,
Stats& stats)
: symbol_(symbol), filename_(filename), options_(options), stats_(stats)
{
}
/// Get Iterators for dynamic symbol table
#if LLVM_VERSION_MAJOR >= 3 && LLVM_VERSION_MINOR >= 8
static std::pair<basic_symbol_iterator, basic_symbol_iterator>
getDynamicSymbolIterators(SymbolicFile& Obj)
{
// There seems to be a bug in getDynamicSymbolIterators as it crashes on
// some object files (llvm-nm shows the same behaviour)
// e.g llvm-nm-3.8 -D /usr/lib/llvm-3.6/lib/liblldbUtility.a
// results in a seg fault while earlier version and GNU just report no
// symbols (as expected)
if(const ELFObjectFileBase* ELFObject = dyn_cast<ELFObjectFileBase>(&Obj))
{
auto sym = ELFObject->getDynamicSymbolIterators();
return std::pair<basic_symbol_iterator, basic_symbol_iterator>(
sym.begin(), sym.end());
}
else
return std::pair<basic_symbol_iterator, basic_symbol_iterator>(
Obj.symbol_begin(), Obj.symbol_end());
}
#else
static std::pair<symbol_iterator, symbol_iterator>
getDynamicSymbolIterators(SymbolicFile& Obj)
{
return getELFDynamicSymbolIterators(&Obj);
}
#endif
bool ObjectDump::lookForSymbolInObject(SymbolicFile& Obj)
{
basic_symbol_iterator symItBegin = Obj.symbol_begin();
basic_symbol_iterator symItEnd = Obj.symbol_end();
std::string nameBuffer;
raw_string_ostream OS(nameBuffer);
std::size_t symbolCounter = 0;
// Check if we deal with a dynamic symbol table
if((symItBegin == symItEnd))
{
if(!Obj.isELF())
return false;
auto dynamicIterators = ::getDynamicSymbolIterators(Obj);
symItBegin = dynamicIterators.first;
symItEnd = dynamicIterators.second;
}
// Convert all symbols in the object to NMSymbols
for(basic_symbol_iterator it = symItBegin; it != symItEnd;
++it, ++symbolCounter)
{
NMSymbol nmSymbol(Obj, it);
// we only consider global text symbols
if(nmSymbol.isGlobalTextSymbol())
{
it->printName(OS);
OS << '\0';
symbolTable_.push_back(nmSymbol);
}
}
OS.flush();
if(options_.gatherStatistics)
stats_.incrementSymbolCounter(symbolCounter);
// Retrieve symbol name
const char* p = nameBuffer.c_str();
for(std::size_t i = 0; i < symbolTable_.size(); ++i)
{
symbolTable_[i].setSymbolName(p);
p += std::strlen(p) + 1;
}
// Look for the symbol
if(!options_.demangle)
{
for(const auto& symEntry : symbolTable_)
if(symEntry.getSymbolName().equals(symbol_))
{
symbolTable_.clear();
return true;
}
}
else
{
// Try to demangle all C++ symbols
for(const auto& symEntry : symbolTable_)
{
StringRef symbolName = symEntry.getSymbolName();
std::unique_ptr<char> symbolDemangled
= std::move(demangleSymbol(symbolName.data()));
if(symbolDemangled.get() != nullptr)
{
std::string symbolNameDemangled(symbolDemangled.get());
if(symbolNameDemangled == symbol_)
{
symbolTable_.clear();
return true;
}
}
else if(symbolName.equals(symbol_))
{
symbolTable_.clear();
return true;
}
}
}
symbolTable_.clear();
return false;
}
bool ObjectDump::lookForSymbol()
{
if(options_.gatherStatistics)
stats_.incrementFileCounter();
// Open the specified file as a MemoryBuffer
ErrorOr<std::unique_ptr<MemoryBuffer>> bufferOrErr
= MemoryBuffer::getFileOrSTDIN(filename_);
if(bufferOrErr.getError())
{
DEBUG_LOG_ERR(bufferOrErr.getError().message(), ": '", filename_, "'");
return false;
}
// Get the context to handle data of LLVM's core infrastructure
LLVMContext& context = getGlobalContext();
// Create a Binary from Source
ErrorOr<std::unique_ptr<Binary>> binaryOrErr
= createBinary(bufferOrErr.get()->getMemBufferRef(), &context);
if(binaryOrErr.getError())
{
DEBUG_LOG_ERR(binaryOrErr.getError().message(), ": '", filename_, "'");
return false;
}
Binary& bin = *binaryOrErr.get();
// Iterate over objects in the Archive
if(Archive* A = dyn_cast<Archive>(&bin))
{
DEBUG_LOG("dumping archive: '", filename_, "'");
for(Archive::child_iterator I = A->child_begin(), E = A->child_end();
I != E; ++I)
{
ErrorOr<std::unique_ptr<Binary>> childOrErr
= I->getAsBinary(&context);
if(childOrErr.getError())
continue;
if(SymbolicFile* O = dyn_cast<SymbolicFile>(&*childOrErr.get()))
{
if(lookForSymbolInObject(*O))
return true;
}
}
return false;
}
if(SymbolicFile* O = dyn_cast<SymbolicFile>(&bin))
{
DEBUG_LOG("dumping symbolic: '", filename_, "'");
return lookForSymbolInObject(*O);
}
DEBUG_LOG_ERR("unrecognizable file type: '", filename_, "'");
return false;
}
| 29.726415 | 80 | 0.591082 | [
"object"
] |
8f2f991b01792fdecbf6be7a31e8741df9610154 | 3,460 | cpp | C++ | src/camera/camera.cpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | 21 | 2020-05-02T06:32:23.000Z | 2021-07-14T11:22:07.000Z | src/camera/camera.cpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | null | null | null | src/camera/camera.cpp | wchang22/Nova | 3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb | [
"MIT"
] | 1 | 2021-05-24T13:44:56.000Z | 2021-05-24T13:44:56.000Z | #include <glm/gtx/transform.hpp>
#include "camera.hpp"
#include "vector/vector_conversions.hpp"
namespace nova {
Camera::Camera(const glm::vec3& position,
const glm::vec3& target,
const glm::vec3& up,
const std::pair<uint32_t, uint32_t>& dimensions,
float fovy)
: position(position), target(target), up(up), dimensions(dimensions), fovy(fovy) {}
bool Camera::operator==(const Camera& other) const {
// clang-format off
return position == other.position &&
target == other.target &&
up == other.up &&
dimensions == other.dimensions &&
fovy == other.fovy;
// clang-format on
}
void Camera::set_position(const glm::vec3& position) { this->position = position; }
void Camera::set_target(const glm::vec3& target) { this->target = target; }
void Camera::set_up(const glm::vec3& up) { this->up = up; }
void Camera::set_dimensions(const std::pair<uint32_t, uint32_t>& dimensions) {
this->dimensions = dimensions;
}
void Camera::set_fovy(float fovy) { this->fovy = fovy; }
const glm::vec3& Camera::get_position() const { return position; }
const glm::vec3& Camera::get_target() const { return target; }
const glm::vec3& Camera::get_up() const { return up; }
float Camera::get_fovy() const { return fovy; }
void Camera::move(Direction direction, float speed) {
constexpr float rotate_threshold = 0.98f;
constexpr float pan_multiplier = 0.025f;
constexpr float forward_multiplier = 0.5f;
glm::vec3 w = -glm::normalize(target - position);
glm::vec3 u = glm::normalize(glm::cross(up, w));
glm::vec3 v = glm::cross(w, u);
glm::vec3 forward = position - target;
float distance = glm::length(forward);
// Slow down movement as we move close to the target position
constexpr auto dist_mod = [](float x) {
return std::exp(2.0f * std::min(x, 2.334f) - 4.0f) + 0.05f;
};
switch (direction) {
case Direction::FORWARD:
// Prevent camera position from moving past target position
if (distance >= 0.1f || speed < 0.0f) {
position += -w * glm::sign(speed) * dist_mod(distance) * forward_multiplier;
}
break;
case Direction::RIGHT:
position += pan_multiplier * speed * u;
target += pan_multiplier * speed * u;
break;
case Direction::UP:
position += pan_multiplier * speed * v;
target += pan_multiplier * speed * v;
break;
case Direction::ROTATE_RIGHT:
position = glm::mat3(glm::rotate(glm::radians(speed), v)) * forward + target;
break;
case Direction::ROTATE_UP:
// Prevent camera from moving past overhead/underneath position
if (glm::dot(w, glm::normalize(up)) * glm::sign(speed) < rotate_threshold) {
position = glm::mat3(glm::rotate(-glm::radians(speed), u)) * forward + target;
}
break;
}
}
EyeCoords Camera::get_eye_coords() const {
const auto& [width, height] = dimensions;
glm::vec2 half_fov(glm::vec2(fovy * width / height, fovy) * 0.5f);
glm::vec2 coord_dims(glm::vec2(width, height) * 0.5f);
glm::vec2 coord_scale(glm::tan(glm::radians(half_fov)) / coord_dims);
glm::vec3 w = -glm::normalize(target - position);
glm::vec3 u = glm::normalize(glm::cross(up, w));
glm::vec3 v = glm::cross(w, u);
return {
glm_to_float2(coord_scale),
glm_to_float2(coord_dims),
glm_to_float3(position),
{ glm_to_float3(u), glm_to_float3(v), glm_to_float3(w) },
};
}
}
| 32.037037 | 86 | 0.645376 | [
"vector",
"transform"
] |
8f449d0d2d735cfdb2e2346b7313aec879a291d3 | 14,785 | cpp | C++ | tinyember/TinyEmberPlus/glow/util/StreamConverter.cpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 78 | 2015-07-31T14:46:38.000Z | 2022-03-28T09:28:28.000Z | tinyember/TinyEmberPlus/glow/util/StreamConverter.cpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 81 | 2015-08-03T07:58:19.000Z | 2022-02-28T16:21:19.000Z | tinyember/TinyEmberPlus/glow/util/StreamConverter.cpp | purefunsolutions/ember-plus | d022732f2533ad697238c6b5210d7fc3eb231bfc | [
"BSL-1.0"
] | 49 | 2015-08-03T12:53:10.000Z | 2022-03-17T17:25:49.000Z | /*
Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com).
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include "../../gadget/ParameterTypeVisitor.h"
#include "../../gadget/StreamFormat.h"
#include <map>
#include <memory>
#include <vector>
#include <ember/Ember.hpp>
#include "StreamConverter.h"
#include "../../gadget/BooleanParameter.h"
#include "../../gadget/EnumParameter.h"
#include "../../gadget/IntegerParameter.h"
#include "../../gadget/RealParameter.h"
#include "../../gadget/StringParameter.h"
#include "../../gadget/Parameter.h"
#include "../../gadget/StreamManager.h"
/**************************************************************************
* Inline implementation *
**************************************************************************/
template<typename OutputIterator>
inline void glow::util::StreamConverter::encode(long long value, gadget::StreamFormat const& format, OutputIterator first, OutputIterator last)
{
auto const type = format.value();
switch(type)
{
case gadget::StreamFormat::UnsignedInt8:
*first = (value & 0xFF);
break;
case gadget::StreamFormat::UnsignedInt16BigEndian:
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::UnsignedInt16LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
break;
case gadget::StreamFormat::UnsignedInt32BigEndian:
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::UnsignedInt32LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
break;
case gadget::StreamFormat::UnsignedInt64BigEndian:
*first++ = ((value >> 56) & 0xFF);
*first++ = ((value >> 48) & 0xFF);
*first++ = ((value >> 40) & 0xFF);
*first++ = ((value >> 32) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::UnsignedInt64LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 32) & 0xFF);
*first++ = ((value >> 40) & 0xFF);
*first++ = ((value >> 48) & 0xFF);
*first++ = ((value >> 56) & 0xFF);
break;
case gadget::StreamFormat::SignedInt8:
*first = (value & 0xFF);
break;
case gadget::StreamFormat::SignedInt16BigEndian:
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::SignedInt16LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
break;
case gadget::StreamFormat::SignedInt32BigEndian:
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::SignedInt32LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
break;
case gadget::StreamFormat::SignedInt64BigEndian:
*first++ = ((value >> 56) & 0xFF);
*first++ = ((value >> 48) & 0xFF);
*first++ = ((value >> 40) & 0xFF);
*first++ = ((value >> 32) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::SignedInt64LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 32) & 0xFF);
*first++ = ((value >> 40) & 0xFF);
*first++ = ((value >> 48) & 0xFF);
*first++ = ((value >> 56) & 0xFF);
break;
case gadget::StreamFormat::IeeeFloat32BigEndian:
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::IeeeFloat32LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
break;
case gadget::StreamFormat::IeeeFloat64BigEndian:
*first++ = ((value >> 56) & 0xFF);
*first++ = ((value >> 48) & 0xFF);
*first++ = ((value >> 40) & 0xFF);
*first++ = ((value >> 32) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 0) & 0xFF);
break;
case gadget::StreamFormat::IeeeFloat64LittleEndian:
*first++ = ((value >> 0) & 0xFF);
*first++ = ((value >> 8) & 0xFF);
*first++ = ((value >> 16) & 0xFF);
*first++ = ((value >> 24) & 0xFF);
*first++ = ((value >> 32) & 0xFF);
*first++ = ((value >> 40) & 0xFF);
*first++ = ((value >> 48) & 0xFF);
*first++ = ((value >> 56) & 0xFF);
break;
}
}
template<typename OutputIterator>
inline void glow::util::StreamConverter::encode(double value, gadget::StreamFormat const& format, OutputIterator first, OutputIterator last)
{
if (format.value() == gadget::StreamFormat::IeeeFloat64BigEndian
|| format.value() == gadget::StreamFormat::IeeeFloat64LittleEndian)
{
long long transformed = *(reinterpret_cast<long long*>(&value));
encode(transformed, format, first, last);
}
else
{
auto valueAsSingle = static_cast<float>(value);
long long transformed = *(reinterpret_cast<long*>(&valueAsSingle));
encode(transformed, format, first, last);
}
}
template<typename OutputIterator>
inline void glow::util::StreamConverter::encode(gadget::Parameter* parameter, OutputIterator first, OutputIterator last)
{
glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::encode(parameter, first, last);
}
template<typename OutputIterator>
inline void glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::encode(gadget::Parameter* parameter, OutputIterator first, OutputIterator last)
{
auto volatile encoder = OctetStreamEntryEncoder(parameter, first, last);
}
template<typename OutputIterator>
glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::OctetStreamEntryEncoder(gadget::Parameter* parameter, OutputIterator first, OutputIterator last)
: m_first(first)
, m_last(last)
{
parameter->accept(*this);
}
template<typename OutputIterator>
void glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::visit(gadget::BooleanParameter* parameter)
{
/* Booleans are not supported */
}
template<typename OutputIterator>
void glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::visit(gadget::EnumParameter* parameter)
{
if (parameter->hasStreamDescriptor())
{
long long const value = parameter->index();
gadget::StreamFormat const format = parameter->streamDescriptor()->format();
auto const offset = parameter->streamDescriptor()->offset();
glow::util::StreamConverter::encode(value, format, m_first + offset, m_last);
}
}
template<typename OutputIterator>
void glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::visit(gadget::StringParameter* parameter)
{
/* Strings are not supported for octet streams */
}
template<typename OutputIterator>
void glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::visit(gadget::IntegerParameter* parameter)
{
if (parameter->hasStreamDescriptor())
{
long long const value = parameter->value();
auto const format = parameter->streamDescriptor()->format();
auto const offset = parameter->streamDescriptor()->offset();
glow::util::StreamConverter::encode(value, format, m_first + offset, m_last);
}
}
template<typename OutputIterator>
void glow::util::StreamConverter::OctetStreamEntryEncoder<OutputIterator>::visit(gadget::RealParameter* parameter)
{
if (parameter->hasStreamDescriptor())
{
auto const value = parameter->value();
auto const format = parameter->streamDescriptor()->format();
auto const offset = parameter->streamDescriptor()->offset();
glow::util::StreamConverter::encode(value, format, m_first + offset, m_last);
}
}
using namespace ::libember::glow;
namespace glow { namespace util
{
libember::glow::GlowStreamEntry* StreamConverter::SingleStreamEntryFactory::create(gadget::Parameter* parameter)
{
auto converter = SingleStreamEntryFactory(parameter);
return converter.m_entry;
}
void StreamConverter::SingleStreamEntryFactory::visit(gadget::BooleanParameter* parameter)
{
m_entry = new GlowStreamEntry(parameter->streamIdentifier(), !!parameter->value());
}
void StreamConverter::SingleStreamEntryFactory::visit(gadget::EnumParameter* parameter)
{
m_entry = new GlowStreamEntry(parameter->streamIdentifier(), static_cast<int>(parameter->index()));
}
void StreamConverter::SingleStreamEntryFactory::visit(gadget::StringParameter* parameter)
{
m_entry = new GlowStreamEntry(parameter->streamIdentifier(), parameter->value());
}
void StreamConverter::SingleStreamEntryFactory::visit(gadget::IntegerParameter* parameter)
{
m_entry = new GlowStreamEntry((int)parameter->streamIdentifier(), static_cast<int>(parameter->value()));
}
void StreamConverter::SingleStreamEntryFactory::visit(gadget::RealParameter* parameter)
{
m_entry = new GlowStreamEntry((int)parameter->streamIdentifier(), (gadget::RealParameter::value_type)parameter->value());
}
StreamConverter::SingleStreamEntryFactory::SingleStreamEntryFactory(gadget::Parameter* parameter)
: m_entry(nullptr)
{
parameter->accept(*this);
}
libember::glow::GlowStreamCollection* StreamConverter::create(libember::glow::GlowStreamCollection* root, gadget::StreamManager const& manager)
{
typedef std::vector<gadget::Parameter*> ParameterCollection;
std::map<int, std::unique_ptr<ParameterCollection> > dic;
{
auto it = std::begin(manager);
auto const last= std::end(manager);
for (; it != last; ++it)
{
auto& parameter = *it;
auto const identifier = parameter->streamIdentifier();
if (dic.find(identifier) == std::end(dic))
{
dic[identifier] = std::unique_ptr<ParameterCollection>(new ParameterCollection());
}
dic[identifier]->push_back(parameter);
}
}
{
for(auto& pair : dic)
{
auto& streams = *pair.second;
auto const identifier = pair.first;
auto const size = streams.size();
if (size == 1 && streams.front()->hasStreamDescriptor() == false)
{
auto parameter = streams.front();
if (parameter->isSubscribed() && parameter->isDirty())
{
auto entry = SingleStreamEntryFactory::create(parameter);
root->insert(entry);
}
}
else if (size >= 1)
{
auto const first = std::begin(streams);
auto const last = std::end(streams);
auto const result = std::max_element(first, last, [](decltype(*first) max, decltype(*first) cur) -> bool
{
if (max->hasStreamDescriptor() && cur->hasStreamDescriptor())
{
return cur->streamDescriptor()->offset() > max->streamDescriptor()->offset();
}
else if (max->hasStreamDescriptor())
{
return false;
}
else if (cur->hasStreamDescriptor())
{
return true;
}
return false;
});
auto const isSubscribed = std::any_of(first, last, [](decltype(*first) stream) -> bool
{
return stream->isSubscribed() && stream->isDirty();
});
if (result != last && isSubscribed)
{
auto descriptor = (*result)->streamDescriptor();
auto const format = descriptor->format();
auto const offset = descriptor->offset();
auto const size = offset + format.size();
auto buffer = std::vector<unsigned char>(size, 0x00);
for(auto parameter : streams)
{
encode(parameter, std::begin(buffer), std::end(buffer));
parameter->clearDirtyState();
}
root->insert(identifier, std::begin(buffer), std::end(buffer));
}
}
}
}
return root;
}
}
}
| 38.10567 | 166 | 0.532905 | [
"vector"
] |
8f471a3850162edc28100266b5f28c7533b37d4d | 41,221 | cpp | C++ | source/mdsplit/mdsplitter.cpp | alandefreitas/mdsplit | f73f8f9bc5123828be3bb360d3c918c088a11eb2 | [
"MIT"
] | 4 | 2020-10-01T02:57:46.000Z | 2021-05-24T06:31:01.000Z | source/mdsplit/mdsplitter.cpp | alandefreitas/mdsplit | f73f8f9bc5123828be3bb360d3c918c088a11eb2 | [
"MIT"
] | null | null | null | source/mdsplit/mdsplitter.cpp | alandefreitas/mdsplit | f73f8f9bc5123828be3bb360d3c918c088a11eb2 | [
"MIT"
] | 1 | 2020-10-02T20:30:50.000Z | 2020-10-02T20:30:50.000Z | //
// Created by Alan Freitas on 30/09/20.
//
#include <algorithm>
#include <cassert>
#include <map>
#include "mdsplitter.h"
namespace mdsplit {
int mdsplitter::run() {
fs::create_directory(output_dir_);
if (trace_) {
std::cout << "# Find Sections" << std::endl;
}
find_sections();
if (trace_) {
std::cout << "# Put parent sections in subdirectories" << std::endl;
}
move_parents_to_subdirectories();
if (remove_autotoc_) {
if (trace_) {
std::cout << "\n# Remove Auto TOC" << std::endl;
}
remove_auto_toc();
}
if (!clear_html_tags_.empty()) {
if (trace_) {
std::cout << "\n# Remove HTML Tags" << std::endl;
}
remove_html_tags();
}
if (update_links_) {
if (trace_) {
std::cout << "\n# Update Links" << std::endl;
}
run_update_links();
}
if (include_toc_) {
if (trace_) {
std::cout << "\n# Create Subsection links" << std::endl;
}
create_subsection_links();
}
if (jekyll_escape_) {
if (trace_) {
std::cout << "\n# Escape Jekyll" << std::endl;
}
escape_jekyll();
}
if (indent_headers_) {
if (trace_) {
std::cout << "\n# Reindent Headers" << std::endl;
}
reindent_headers();
}
if (add_front_matter_) {
if (trace_) {
std::cout << "\n# Add Front Matter" << std::endl;
}
run_add_front_matter();
}
if (trace_) {
std::cout << "\n# Save Sections" << std::endl;
}
save_sections();
if (trace_) {
std::cout << "\n# Generate navigation files" << std::endl;
}
generate_navigation_files();
list_doc_outsiders();
return 0;
}
std::string mdsplitter::slugify(std::string_view str) {
std::string r;
for (const auto &c : str) {
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') {
r += c;
} else if (c >= 'A' && c <= 'Z') {
r += std::tolower(c);
} else if (c == ' ') {
r += '-';
}
}
return r;
}
void mdsplitter::find_sections() {
// # some text
std::regex header_regex{"(^|\\n)(#+) +(.*)"};
std::regex ignore_begin_regex{R"( *<!-- START mdsplit-ignore --> *)"};
std::regex ignore_end_regex{R"( *<!-- END mdsplit-ignore --> *)"};
/*
* # some text
* std::regex h1_regex{"# +(.*)"};
* // ## some text
* std::regex h2_regex{"## +(.*)"};
* // ### some text
* std::regex h3_regex{"### +(.*)"};
*/
std::ifstream fin(input_);
std::string current_line;
bool inside_codeblock = false;
bool inside_ignoreblock = false;
while (std::getline(fin, current_line)) {
std::smatch sm;
if (is_codeblock(current_line)) {
inside_codeblock = 1 - inside_codeblock;
}
if (!inside_codeblock) {
if (std::regex_match(current_line, ignore_begin_regex)) {
inside_ignoreblock = true;
continue;
} else if (std::regex_match(current_line, ignore_end_regex)) {
inside_ignoreblock = false;
continue;
}
if (inside_ignoreblock) {
continue;
}
bool found_header =
std::regex_search(current_line, sm, header_regex);
if (found_header) {
short level = sm[2].length();
if (level <= max_split_level_) {
// Create new section
mdsection new_section;
new_section.level = level;
new_section.header_name = sm[3].str();
while (!new_section.header_name.empty() &&
new_section.header_name.back() == ' ') {
new_section.header_name.pop_back();
}
// Find its parent headers
// For each level below this section's (ignoring level
// 1)
for (int i = new_section.level - 1; i > 1; --i) {
// Find some section with this lower level
auto it = std::find_if(sections_.rbegin(),
sections_.rend(),
[&i](const mdsection &s) {
return s.level == i;
});
// If we found it
if (it != sections_.rend()) {
// Then this is the parent
new_section.parent_headers.insert(
new_section.parent_headers.begin(),
it->header_name);
}
}
bool first_section = sections_.empty();
if (first_section) {
new_section.filepath = output_dir_ / "index.md";
new_section.header_name = "Home";
} else {
new_section.filepath = output_dir_;
for (const auto &parent_section :
new_section.parent_headers) {
new_section.filepath /= slugify(parent_section);
}
new_section.filepath /=
slugify(new_section.header_name);
new_section.filepath += ".md";
}
fs::create_directory(
new_section.filepath.parent_path());
sections_.push_back(new_section);
}
}
}
// Make sure there's at least one default section
bool found_text_before_any_section = sections_.empty();
if (found_text_before_any_section && !current_line.empty()) {
mdsection new_section;
new_section.level = 0;
new_section.header_name = "";
new_section.filepath = output_dir_ / "index.md";
sections_.push_back(new_section);
}
// Store line
if (!sections_.empty()) {
sections_.back().lines.push_back(std::move(current_line));
}
}
}
bool mdsplitter::is_codeblock(const std::string &str) {
// ```
std::regex codeblock_regex{"(\\s*)```(.*)"};
std::smatch sm;
std::regex_match(str, sm, codeblock_regex);
return !sm.empty();
}
void mdsplitter::save_sections() {
// Try to save each section
for (auto §ion : sections_) {
// Add mdsplit comment to allow later removal
if (section.has_content()) {
section.lines.emplace_back("");
section.lines.emplace_back("");
section.lines.emplace_back(
"<!-- Generated with mdsplit: "
"https://github.com/alandefreitas/mdsplit -->");
} else {
continue;
}
// check if files have the same content
// this allows us to run mdsplit without making
// the mkdocs server refresh for nothing
bool content_is_the_same = true;
std::ifstream fin(section.filepath);
if (!fin) {
content_is_the_same = false;
}
std::string file_current_line;
size_t section_current_line_idx = 0;
while (std::getline(fin, file_current_line)) {
if (section_current_line_idx < section.lines.size()) {
const std::string §ion_current_line =
section.lines[section_current_line_idx];
if (file_current_line != section_current_line) {
content_is_the_same = false;
break;
}
++section_current_line_idx;
} else {
if (!file_current_line.empty()) {
content_is_the_same = false;
break;
}
}
}
const bool this_section_has_extra_information =
section_current_line_idx != section.lines.size();
if (this_section_has_extra_information) {
content_is_the_same = false;
}
if (content_is_the_same) {
std::cout << "File " << section.filepath << " has not changed"
<< std::endl;
continue;
}
// If content is not the same, write section to the file
std::ofstream fout(section.filepath);
if (trace_) {
std::cout << "Saving " << section.filepath
<< "(Section: " << section.header_name << ")"
<< std::endl;
}
for (const auto &line : section.lines) {
fout << line << std::endl;
}
}
}
void mdsplitter::remove_auto_toc() {
std::regex toc_begin_regex{
R"( *<!-- START doctoc generated TOC please keep comment here to allow auto update --> *)"};
std::regex toc_end_regex{
R"( *<!-- END doctoc generated TOC please keep comment here to allow auto update --> *)"};
for (auto §ion : sections_) {
auto line_it = section.lines.begin();
auto line_it_end = section.lines.end();
auto toc_line_it = line_it_end;
auto toc_line_it_end = line_it_end;
bool in_codeblock = false;
for (; line_it != line_it_end; ++line_it) {
if (is_codeblock(*line_it)) {
in_codeblock = 1 - in_codeblock;
}
if (in_codeblock) {
continue;
}
bool found_toc_begin =
std::regex_search(*line_it, toc_begin_regex);
if (found_toc_begin) {
toc_line_it = line_it;
} else {
bool found_toc_end =
std::regex_search(*line_it, toc_end_regex);
if (found_toc_end) {
toc_line_it_end = line_it;
break;
}
}
}
if (toc_line_it != line_it_end && toc_line_it_end != line_it_end) {
if (trace_) {
std::cout << "Found Auto TOC in " << section.header_name
<< std::endl;
}
section.lines.erase(toc_line_it, std::next(toc_line_it_end));
}
}
}
void mdsplitter::remove_html_tags() {
for (const auto &tag : clear_html_tags_) {
std::string complete_html_tag_format = "< *";
complete_html_tag_format += tag;
complete_html_tag_format += "( +[^>]*)?>(.*?)</ *";
complete_html_tag_format += tag;
complete_html_tag_format += " *>";
std::regex complete_html_tag_regex{complete_html_tag_format};
std::string html_tag_format = "< */? *" + tag + "( +[^>]*)?>";
std::regex html_tag_regex{html_tag_format};
for (auto §ion : sections_) {
bool in_codeblock = false;
for (auto &line : section.lines) {
if (is_codeblock(line)) {
in_codeblock = 1 - in_codeblock;
}
if (in_codeblock) {
continue;
}
std::smatch match;
while (std::regex_search(line, match,
complete_html_tag_regex)) {
if (trace_) {
std::cout << match[0] << "->" << match[2]
<< std::endl;
}
line.replace(match.position(0), match[0].length(),
match[2]);
// Removing tags might leave a lot of white space in the
// left which would be interpreted as something
// different by markdown. We have to remove these
line.erase(0, line.find_first_not_of(" \t"));
}
while (std::regex_search(line, match, html_tag_regex)) {
if (trace_) {
std::cout << match[0] << "-> <empty>" << std::endl;
}
line.erase(match.position(0), match[0].length());
}
}
}
}
}
void mdsplitter::run_update_links() {
// [some text](URL) -> std::regex{R"([^!]*\[(.*)\]\((.*)\))"};
//  -> std::regex{R"(!\[(.*)\]\((.*)\))"};
std::regex url_or_img_regex{R"(\[([^\[\]]*)\]\(([^\)]*)\))"};
// [](examples/line_plot/area/area_1.cpp)
std::regex second_order_url_or_img_regex{
R"(\[(!?)\[([^\[\]]*)\]\(([^\)]*)\)\]\(([^\)]*)\))"};
std::vector<std::pair<std::regex, size_t>> url_regexes = {
{url_or_img_regex, 2}, {second_order_url_or_img_regex, 4}};
for (const auto &[url_regex, url_idx] : url_regexes) {
for (auto §ion : sections_) {
bool in_codeblock = false;
for (auto &line : section.lines) {
if (is_codeblock(line)) {
in_codeblock = 1 - in_codeblock;
}
if (in_codeblock) {
continue;
}
std::smatch matches;
auto line_begin = line.cbegin();
auto line_end = line.cend();
size_t replacement_size = 0;
while (std::regex_search(line_begin, line_end, matches,
url_regex)) {
size_t line_begin_pos = line_begin - line.cbegin();
std::string url = matches[url_idx];
if (!is_external(url)) {
bool is_anchor = url.rfind('#', 0) == 0;
if (!is_anchor) {
bool is_single_dot_directory =
url.rfind("./", 0) == 0;
if (is_single_dot_directory) {
url.erase(url.begin(), url.begin() + 2);
}
fs::path relative_url =
relative_path(url, section.filepath);
if (trace_) {
std::cout << section.filepath.c_str()
<< ": " << url << " -> "
<< relative_url.c_str()
<< std::endl;
}
size_t pos =
std::distance(line.cbegin(), line_begin) +
matches.position(url_idx);
line.replace(pos, matches[url_idx].length(),
relative_url.string());
replacement_size = relative_url.string().size();
} else {
// look for section
std::string header_slug = url.substr(1);
auto it = std::find_if(
sections_.begin(), sections_.end(),
[&](const mdsection &s) {
return slugify(s.header_name) ==
header_slug;
});
// if it's a empty section, point to next
// section this is important for empty
// categories for which mkdocs creates no links
if (it != sections_.end()) {
if (!it->has_content()) {
++it;
}
}
// if link to valid section
if (it != sections_.end()) {
fs::path absolute_destination =
fs::current_path() / it->filepath;
fs::path relative_url = relative_path(
absolute_destination, section.filepath);
if (trace_) {
std::cout << url << "->"
<< relative_url.c_str()
<< std::endl;
}
size_t pos = std::distance(line.cbegin(),
line_begin) +
matches.position(url_idx);
line.replace(pos, matches[url_idx].length(),
relative_url.string());
replacement_size =
relative_url.string().size();
} else {
// not link to a valid section
// we hope we didn't get here
if (trace_) {
std::cout
<< "Cannot find file for a header "
<< url << " whose slug is "
<< header_slug << std::endl;
}
replacement_size = url.size();
}
}
} else {
if (trace_) {
std::cout << url << " <- (external)"
<< std::endl;
}
replacement_size = url.size();
}
if (replacement_size == 0) {
replacement_size = matches[url_idx].length();
}
size_t new_begin_pos = line_begin_pos +
matches.position(url_idx) +
replacement_size;
if (new_begin_pos < line.size()) {
line_begin = line.cbegin() + new_begin_pos;
line_end = line.cend();
} else {
break;
}
}
}
}
}
}
void mdsplitter::create_subsection_links() {
for (auto section_it = sections_.begin(); section_it != sections_.end();
++section_it) {
auto §ion = *section_it;
section.lines.emplace_back("");
for (auto subsection_it = std::next(section_it);
subsection_it != sections_.end(); ++subsection_it) {
auto &subsection = *subsection_it;
if (subsection.level <= section.level) {
break;
} else {
int level_difference = subsection.level - section.level;
assert(level_difference > 0);
std::string padding((level_difference - 1) * 2, ' ');
fs::path absolute_destination = fs::current_path() /
input_.parent_path() /
subsection.filepath;
fs::path relative_destination = fs::relative(
absolute_destination, section.filepath.parent_path());
section.lines.emplace_back(
padding + "- [" + subsection.header_name + "](" +
relative_destination.string() + ")");
}
}
}
}
void mdsplitter::escape_jekyll() {
for (auto §ion : sections_) {
for (auto &line : section.lines) {
size_t pos = line.find("{{");
while (pos != std::string::npos) {
if (trace_) {
std::cout << line << "->";
}
line.replace(pos, 2, "{ {");
if (trace_) {
std::cout << line << std::endl;
}
pos = line.find("{{", pos + 3);
}
}
}
}
void mdsplitter::reindent_headers() {
std::regex header_regex{"(#+) +(.*)"};
for (auto §ion : sections_) {
bool inside_codeblock = false;
for (auto &line : section.lines) {
if (is_codeblock(line)) {
inside_codeblock = 1 - inside_codeblock;
}
if (inside_codeblock) {
continue;
}
std::smatch sm;
if (std::regex_match(line, sm, header_regex)) {
auto level = static_cast<short>(sm[1].length());
auto level_diff = level - section.level;
if (level_diff < 0) {
std::cerr
<< section.filepath.c_str()
<< ": level_diff should not be less than zero."
<< std::endl;
level_diff = 0;
}
line = std::string(level_diff + 1, '#') + " " + sm[2].str();
}
}
}
}
void mdsplitter::run_add_front_matter() {
short current_level = 0;
std::vector<int> level_order;
std::vector<std::string> level_parent;
for (auto it = sections_.begin(); it != sections_.end(); ++it) {
auto §ion = *it;
// we consider level 1 and 2 to be the same
short adjusted_level =
section.level == 1
? static_cast<short>(1)
: static_cast<short>(static_cast<short>(section.level) -
static_cast<short>(1));
bool is_new_level = adjusted_level != current_level;
if (is_new_level) {
level_order.resize(adjusted_level, 1);
if (adjusted_level < current_level) {
++level_order.back();
}
level_parent.resize(adjusted_level - 1);
if (adjusted_level > current_level && it != sections_.begin()) {
level_parent.back() = std::prev(it)->header_name;
}
} else {
++level_order.back();
}
current_level = adjusted_level;
auto next_section_it = std::next(it);
bool has_children = next_section_it != sections_.end() &&
next_section_it->level - 1 > current_level;
std::vector<std::string> front_matter;
front_matter.emplace_back("---");
front_matter.emplace_back("layout: default");
if (has_children) {
front_matter.emplace_back("title: Introduction");
} else {
front_matter.emplace_back("title: " + section.header_name);
}
front_matter.emplace_back("nav_order: " +
std::to_string(level_order.back()));
if (has_children) {
front_matter.emplace_back("has_children: true");
} else {
front_matter.emplace_back("has_children: false");
}
if (adjusted_level > 1) {
front_matter.emplace_back("parent: " + level_parent.back());
}
if (adjusted_level > 2) {
if (level_parent.size() >= 2) {
front_matter.emplace_back(
"grand_parent: " +
level_parent[level_parent.size() - 2]);
}
}
front_matter.emplace_back("has_toc: false");
front_matter.emplace_back("---");
if (trace_) {
std::cout << section.filepath.c_str() << std::endl;
}
for (const auto &l : front_matter) {
if (trace_) {
std::cout << l << std::endl;
}
}
section.lines.insert(section.lines.begin(), front_matter.begin(),
front_matter.end());
}
}
const fs::path &mdsplitter::input() const { return input_; }
void mdsplitter::input(const fs::path &input) { input_ = input; }
const fs::path &mdsplitter::output_dir() const { return output_dir_; }
void mdsplitter::output_dir(const fs::path &output_dir) {
output_dir_ = output_dir;
}
const std::vector<std::string> &mdsplitter::clear_html_tags() const {
return clear_html_tags_;
}
void mdsplitter::clear_html_tags(
const std::vector<std::string> &clear_html_tags) {
clear_html_tags_ = clear_html_tags;
}
const std::string &mdsplitter::repository() const { return repository_; }
void mdsplitter::repository(const std::string &repository) {
repository_ = repository;
}
short mdsplitter::max_split_level() const { return max_split_level_; }
void mdsplitter::max_split_level(short max_split_level) {
max_split_level_ = max_split_level;
}
bool mdsplitter::include_toc() const { return include_toc_; }
void mdsplitter::include_toc(bool include_toc) {
include_toc_ = include_toc;
}
bool mdsplitter::jekyll_escape() const { return jekyll_escape_; }
void mdsplitter::jekyll_escape(bool jekyll_escape) {
jekyll_escape_ = jekyll_escape;
}
bool mdsplitter::indent_headers() const { return indent_headers_; }
void mdsplitter::indent_headers(bool indent_headers) {
indent_headers_ = indent_headers;
}
void mdsplitter::add_front_matter(bool add_front_matter) {
add_front_matter_ = add_front_matter;
}
void mdsplitter::update_links(bool update_links) {
update_links_ = update_links;
}
bool mdsplitter::remove_autotoc() const { return remove_autotoc_; }
void mdsplitter::remove_autotoc(bool remove_autotoc) {
remove_autotoc_ = remove_autotoc;
}
const fs::path &mdsplitter::current_output_file() const {
return current_output_file_;
}
void mdsplitter::current_output_file(const fs::path ¤t_output_file) {
current_output_file_ = current_output_file;
}
const std::vector<mdsection> &mdsplitter::sections() const {
return sections_;
}
void mdsplitter::sections(const std::vector<mdsection> §ions) {
sections_ = sections;
}
bool mdsplitter::add_front_matter() const { return add_front_matter_; }
bool mdsplitter::update_links() const { return update_links_; }
bool mdsplitter::trace() const { return trace_; }
void mdsplitter::trace(bool trace) { trace_ = trace; }
/// Returns path is inside base
bool mdsplitter::is_subdirectory(const fs::path &path,
const fs::path &base) {
fs::path p = path;
if (p.is_relative()) {
p = fs::current_path() / input_.parent_path() / p;
}
fs::path b = base;
if (b.is_relative()) {
b = fs::current_path() / b;
}
if (!fs::is_directory(b)) {
b = b.parent_path();
}
while (b != p && p.parent_path() != p) {
p = p.parent_path();
}
return b == p;
}
fs::path mdsplitter::relative_path(const fs::path &path,
const fs::path &base) {
fs::path base_dir = fs::is_directory(base) ? base : base.parent_path();
bool is_in_docs_dir = is_subdirectory(path, output_dir_);
bool is_docs_dir = path == this->output_dir_;
if (is_in_docs_dir && !is_docs_dir) {
fs::path r = fs::relative(path, base_dir);
std::string ext = r.extension().string();
// GitHub does not convert ".md#anchor" links automatically
/*
bool is_anchor_inside_docs = ext.rfind(".md#", 0) == 0;
if (is_anchor_inside_docs) {
ext.replace(0, 4, ".html#");
r = r.parent_path() / r.stem();
r += ext;
}
*/
return r;
} else {
bool is_in_project_dir = is_subdirectory(path, fs::current_path());
if (is_in_project_dir) {
if (!repository_.empty()) {
fs::path url;
if (!is_external(repository_)) {
url /= "https://github.com";
}
url /= repository_;
url /= "blob/master";
url /= fs::relative(path, fs::current_path());
return url;
} else {
std::cerr << fs::relative(path, fs::current_path())
<< " is outside the output directory but you "
"have not provided a repository to mdsplit. "
"This will generate a broken link."
<< std::endl;
return fs::relative(path, fs::current_path());
}
} else {
std::cerr
<< fs::relative(path, fs::current_path())
<< " is outside the project directory. There's no way to "
"generate a relative link that will work elsewhere. "
"This will generate a broken link in your documentation."
<< std::endl;
return fs::relative(path, fs::current_path());
}
}
}
bool mdsplitter::is_external(const std::string &url) {
bool is_http = url.rfind("http://", 0) == 0;
bool is_https = url.rfind("https://", 0) == 0;
bool is_www = url.rfind("www.", 0) == 0;
return is_http || is_https || is_www;
}
void mdsplitter::list_doc_outsiders() {
bool first = true;
std::vector<fs::path> outsiders;
for (auto &p : fs::recursive_directory_iterator(output_dir_)) {
if (p.path().extension() == ".md") {
fs::path outsider = fs::relative(p.path(), fs::current_path());
auto it = std::find_if(
sections_.begin(), sections_.end(),
[&](const mdsection &s) { return s.filepath == outsider; });
bool section_exists = it != sections_.end();
if (!section_exists || !it->has_content()) {
if (first) {
if (trace_) {
std::cout << "\n# The following .md files were not "
"generated by mdsplit in this run"
<< std::endl;
std::cout
<< "# Please make sure that is on purpose:"
<< std::endl;
}
first = false;
}
if (trace_) {
std::cout << "Outsider doc file: " << outsider.c_str()
<< '\n';
}
outsiders.emplace_back(outsider);
}
}
}
// Remove outsiders generated by mdsplit
std::regex gen_with_mdsplit_regex{
R"( *<!-- Generated with mdsplit: https://github.com/alandefreitas/mdsplit --> *)"};
std::regex ignore_begin_regex{R"( *<!-- START mdsplit-ignore --> *)"};
std::regex ignore_end_regex{R"( *<!-- END mdsplit-ignore --> *)"};
for (const auto &outsider : outsiders) {
std::ifstream fin(outsider.string());
std::string current_line;
bool inside_codeblock = false;
bool inside_ignoreblock = false;
while (std::getline(fin, current_line)) {
std::smatch sm;
if (is_codeblock(current_line)) {
inside_codeblock = 1 - inside_codeblock;
}
if (!inside_codeblock) {
if (std::regex_match(current_line, ignore_begin_regex)) {
inside_ignoreblock = true;
continue;
} else if (std::regex_match(current_line,
ignore_end_regex)) {
inside_ignoreblock = false;
continue;
}
if (inside_ignoreblock) {
continue;
}
bool is_mdsplit_file = std::regex_search(
current_line, sm, gen_with_mdsplit_regex);
if (is_mdsplit_file) {
if (trace_) {
std::cout
<< "Outsider doc file generated by mdsplit: "
<< outsider.string() << std::endl;
}
if (erase_old_mdsplit_files_) {
if (trace_) {
std::cout << "Removing " << outsider.string()
<< std::endl;
}
fs::remove(outsider);
}
break;
}
}
}
}
}
bool mdsplitter::erase_old_mdsplit_files() const {
return erase_old_mdsplit_files_;
}
void mdsplitter::erase_old_mdsplit_files(bool erase_old_mdsplit_files) {
erase_old_mdsplit_files_ = erase_old_mdsplit_files;
}
void mdsplitter::move_parents_to_subdirectories() {
for (size_t i = 0; i < sections_.size() - 1; ++i) {
// ignore level one, which are never put in subdirectories
if (sections_[i].level != 1) {
bool section_has_a_child =
sections_[i].level < sections_[i + 1].level;
if (section_has_a_child) {
fs::path p = sections_[i].filepath;
fs::path stem = p.filename().stem();
p = p.remove_filename();
p /= stem;
p /= "index.md";
sections_[i].filepath = p;
}
}
}
}
void mdsplitter::generate_navigation_files() {
// path -> navigation items in the path
using navigation_content = std::vector<std::string>;
std::map<fs::path, navigation_content> navigations;
// function to add content to these files
auto add_content = [&](const fs::path &p, const std::string &line) {
auto it = navigations.find(p);
if (it == navigations.end()) {
navigations[p] = {"nav:", line};
} else {
navigations[p].emplace_back(line);
}
};
// Add sections in all relevant navigation files
fs::path previous_path = output_dir_;
for (size_t i = 0; i < sections_.size(); ++i) {
// Add file to its own navigation pages (if there's content)
auto §ion = sections_[i];
if (section.has_content()) {
fs::path p = section.filepath.parent_path();
fs::path f = section.filepath.filename();
bool has_children = section.level != 1 &&
i < sections_.size() - 1 &&
sections_[i + 1].level > section.level;
std::string sidebar_name =
has_children ? "Introduction" : section.header_name;
add_content(p, " - " + sidebar_name + ": " + f.string());
}
// Add file to the parent navigation pages (if it's first in this
// directory)
bool is_a_new_directory =
section.filepath.parent_path() != previous_path;
if (is_a_new_directory) {
// check if this is the first file in this dir
bool is_first = true;
for (size_t j = 0; j < i; ++j) {
if (sections_[j].filepath.parent_path() ==
section.filepath.parent_path()) {
is_first = false;
break;
}
}
// if it's first file in this dir
if (is_first) {
// put it in the parent path navigation list too
fs::path grand_path =
section.filepath.parent_path().parent_path();
add_content(grand_path,
" - " + section.header_name + ": " +
fs::relative(section.filepath.parent_path(),
grand_path)
.string());
}
}
previous_path = section.filepath.parent_path();
}
// Save the .pages
for (const auto &[p, content] : navigations) {
fs::path pages_file = p;
pages_file /= ".pages";
// Check if file has changed
std::ifstream fin(pages_file);
bool has_changed = false;
std::string current_line;
size_t content_idx = 0;
while (std::getline(fin, current_line)) {
if (content_idx < content.size()) {
if (current_line != content[content_idx]) {
has_changed = true;
break;
}
++content_idx;
} else {
if (!current_line.empty()) {
has_changed = true;
break;
}
}
}
if (content_idx < content.size()) {
for (size_t i = content_idx; i < content.size(); ++i) {
if (!content[i].empty()) {
has_changed = true;
}
}
}
if (!has_changed) {
std::cout << "File " << pages_file << " has not changed "
<< std::endl;
}
// Save file if its contents have changed
if (has_changed) {
std::ofstream fout(pages_file);
std::cout << "Saving " << pages_file << std::endl;
for (const auto &line : content) {
fout << line << std::endl;
}
}
}
}
} // namespace mdsplit
| 41.221 | 107 | 0.429102 | [
"vector"
] |
8f4cbb3a628daea73a6d2a4c9567756cd3525b26 | 1,637 | cc | C++ | CommBasicObjects/smartsoft/src/CommBasicObjects/CommJoystick.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | null | null | null | CommBasicObjects/smartsoft/src/CommBasicObjects/CommJoystick.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 2 | 2020-08-20T14:49:47.000Z | 2020-10-07T16:10:07.000Z | CommBasicObjects/smartsoft/src/CommBasicObjects/CommJoystick.cc | canonical-robots/DomainModelsRepositories | 68b9286d84837e5feb7b200833b158ab9c2922a4 | [
"BSD-3-Clause"
] | 8 | 2018-06-25T08:41:28.000Z | 2020-08-13T10:39:30.000Z | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Christian Schlegel (schlegel@hs-ulm.de)
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// This file is generated once. Modify this file to your needs.
// If you want the toolchain to re-generate this file, please
// delete it before running the code generator.
//--------------------------------------------------------------------------
#include "CommBasicObjects/CommJoystick.hh"
using namespace CommBasicObjects;
CommJoystick::CommJoystick()
: CommJoystickCore()
{ }
/**
* Constructor to set all values.
* NOTE that you have to keep this constructor consistent with the model!
* Use at your own choice.
*
* The preferred way to set values for initialization is:
* CommRepository::MyCommObject obj;
* obj.setX(1).setY(2).setZ(3)...;
CommJoystick::CommJoystick(const short &xpos, const short &ypos, const short &x2pos, const short &y2pos, const unsigned short &buttons)
: CommJoystickCore() // base constructor sets default values as defined in the model
{
setXpos(xpos);
setYpos(ypos);
setX2pos(x2pos);
setY2pos(y2pos);
setButtons(buttons);
}
*/
CommJoystick::CommJoystick(const CommJoystickCore &commJoystick)
: CommJoystickCore(commJoystick)
{ }
CommJoystick::CommJoystick(const DATATYPE &commJoystick)
: CommJoystickCore(commJoystick)
{ }
CommJoystick::~CommJoystick()
{ }
| 29.232143 | 135 | 0.673794 | [
"model"
] |
8f529396e57305c8d37abdd41d6dd9fdd741df87 | 2,486 | cpp | C++ | C++-Programs/Segment_Tree.cpp | adityaverma121/Simple-Programs | 8450560b97f89e0fa3da16a623ad35c0b26409c9 | [
"MIT"
] | 71 | 2021-09-30T11:25:12.000Z | 2021-10-03T11:33:22.000Z | C++-Programs/Segment_Tree.cpp | adityaverma121/Simple-Programs | 8450560b97f89e0fa3da16a623ad35c0b26409c9 | [
"MIT"
] | 186 | 2021-09-30T12:25:16.000Z | 2021-10-03T13:45:04.000Z | C++-Programs/Segment_Tree.cpp | adityaverma121/Simple-Programs | 8450560b97f89e0fa3da16a623ad35c0b26409c9 | [
"MIT"
] | 385 | 2021-09-30T11:34:23.000Z | 2021-10-03T13:41:00.000Z | #include <bits/stdc++.h>
using namespace std;
// Segment tree implementation. Supports point update and range query.
class segmentTree {
int N;
vector<int> tree;
public:
void init(int _N) {
N = _N;
tree.assign(4 * N + 1, 0);
}
int merge(int left, int right) {
return left + right;
}
void build(vector<int>& a, int node, int L, int R) {
if(L == R) {
if (L < N) {
tree[node] = a[L];
}
return;
}
int M = (L + R) / 2;
build(a, node * 2 + 1, L, M);
build(a, node * 2 + 2, M + 1, R);
tree[node] = merge(tree[node * 2 + 1], tree[node * 2 + 2]);
}
void build(vector<int>& a) {
build(a, 0, 0, N - 1);
}
void update(int node, int L, int R, int pos, int val) {
if(L == R) {
tree[node] = val;
return;
}
int M = (L + R) / 2;
if(pos <= M) {
update(node * 2 + 1, L, M, pos, val);
} else {
update(node * 2 + 2, M + 1, R, pos, val);
}
tree[node] = merge(tree[node * 2 + 1], tree[node * 2 + 2]);
}
void update(int pos, int val) {
update(0, 0, N - 1, pos, val);
}
int query(int node, int lx, int rx, int L, int R) {
if(R < lx || rx < L)
return 0;
if(L <= lx && rx <= R)
return tree[node];
int M = (lx + rx) / 2;
int left = query(node * 2 + 1, lx, M, L, R);
int right = query(node * 2 + 2, M + 1, rx, L, R);
return merge(left, right);
}
int query(int l, int r) {
return query(0, 0, N - 1, l, r);
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
segmentTree st;
st.init(n);
st.build(a);
int queries;
cin >> queries;
while (queries--) {
int type;
cin >> type;
// All indices are 0th based.
if (type == 1) {
// Type = 1, Update value.
int index, val;
cin >> index >> val;
st.update(index, val);
} else {
// Type = 2, range query
int l, r;
cin >> l >> r;
cout << st.query(l, r) << '\n';
}
}
return 0;
}
/*
Sample input:
5
1 2 3 4 5
3
2 0 4
1 2 5
2 0 4
Sample uutput:
15
17
*/ | 21.067797 | 70 | 0.421963 | [
"vector"
] |
8f5867598e149840c28c393085efb13ed52a78ef | 4,652 | hpp | C++ | ThirdParty-mod/java2cpp/java/util/regex/MatchResult.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/java/util/regex/MatchResult.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/java/util/regex/MatchResult.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.util.regex.MatchResult
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_UTIL_REGEX_MATCHRESULT_HPP_DECL
#define J2CPP_JAVA_UTIL_REGEX_MATCHRESULT_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
namespace j2cpp {
namespace java { namespace util { namespace regex {
class MatchResult;
class MatchResult
: public object<MatchResult>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
explicit MatchResult(jobject jobj)
: object<MatchResult>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
jint end();
jint end(jint);
local_ref< java::lang::String > group();
local_ref< java::lang::String > group(jint);
jint groupCount();
jint start();
jint start(jint);
}; //class MatchResult
} //namespace regex
} //namespace util
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_UTIL_REGEX_MATCHRESULT_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_UTIL_REGEX_MATCHRESULT_HPP_IMPL
#define J2CPP_JAVA_UTIL_REGEX_MATCHRESULT_HPP_IMPL
namespace j2cpp {
java::util::regex::MatchResult::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
jint java::util::regex::MatchResult::end()
{
return call_method<
java::util::regex::MatchResult::J2CPP_CLASS_NAME,
java::util::regex::MatchResult::J2CPP_METHOD_NAME(0),
java::util::regex::MatchResult::J2CPP_METHOD_SIGNATURE(0),
jint
>(get_jobject());
}
jint java::util::regex::MatchResult::end(jint a0)
{
return call_method<
java::util::regex::MatchResult::J2CPP_CLASS_NAME,
java::util::regex::MatchResult::J2CPP_METHOD_NAME(1),
java::util::regex::MatchResult::J2CPP_METHOD_SIGNATURE(1),
jint
>(get_jobject(), a0);
}
local_ref< java::lang::String > java::util::regex::MatchResult::group()
{
return call_method<
java::util::regex::MatchResult::J2CPP_CLASS_NAME,
java::util::regex::MatchResult::J2CPP_METHOD_NAME(2),
java::util::regex::MatchResult::J2CPP_METHOD_SIGNATURE(2),
local_ref< java::lang::String >
>(get_jobject());
}
local_ref< java::lang::String > java::util::regex::MatchResult::group(jint a0)
{
return call_method<
java::util::regex::MatchResult::J2CPP_CLASS_NAME,
java::util::regex::MatchResult::J2CPP_METHOD_NAME(3),
java::util::regex::MatchResult::J2CPP_METHOD_SIGNATURE(3),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
jint java::util::regex::MatchResult::groupCount()
{
return call_method<
java::util::regex::MatchResult::J2CPP_CLASS_NAME,
java::util::regex::MatchResult::J2CPP_METHOD_NAME(4),
java::util::regex::MatchResult::J2CPP_METHOD_SIGNATURE(4),
jint
>(get_jobject());
}
jint java::util::regex::MatchResult::start()
{
return call_method<
java::util::regex::MatchResult::J2CPP_CLASS_NAME,
java::util::regex::MatchResult::J2CPP_METHOD_NAME(5),
java::util::regex::MatchResult::J2CPP_METHOD_SIGNATURE(5),
jint
>(get_jobject());
}
jint java::util::regex::MatchResult::start(jint a0)
{
return call_method<
java::util::regex::MatchResult::J2CPP_CLASS_NAME,
java::util::regex::MatchResult::J2CPP_METHOD_NAME(6),
java::util::regex::MatchResult::J2CPP_METHOD_SIGNATURE(6),
jint
>(get_jobject(), a0);
}
J2CPP_DEFINE_CLASS(java::util::regex::MatchResult,"java/util/regex/MatchResult")
J2CPP_DEFINE_METHOD(java::util::regex::MatchResult,0,"end","()I")
J2CPP_DEFINE_METHOD(java::util::regex::MatchResult,1,"end","(I)I")
J2CPP_DEFINE_METHOD(java::util::regex::MatchResult,2,"group","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(java::util::regex::MatchResult,3,"group","(I)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(java::util::regex::MatchResult,4,"groupCount","()I")
J2CPP_DEFINE_METHOD(java::util::regex::MatchResult,5,"start","()I")
J2CPP_DEFINE_METHOD(java::util::regex::MatchResult,6,"start","(I)I")
} //namespace j2cpp
#endif //J2CPP_JAVA_UTIL_REGEX_MATCHRESULT_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 28.024096 | 86 | 0.690671 | [
"object"
] |
8f5d1750fe17bd694d870d6859cae7b295303744 | 7,791 | cpp | C++ | src/linux_parser.cpp | teddyg/ND-System-Monitor | 8f4a35aeae117b7a358b1ca770a6b8246bfeb7b6 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | teddyg/ND-System-Monitor | 8f4a35aeae117b7a358b1ca770a6b8246bfeb7b6 | [
"MIT"
] | null | null | null | src/linux_parser.cpp | teddyg/ND-System-Monitor | 8f4a35aeae117b7a358b1ca770a6b8246bfeb7b6 | [
"MIT"
] | null | null | null | #include <dirent.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <vector>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// reuse logic for running and total process count
int GetProcessData(std::string label);
// DONE: An example of how to read data from the filesystem
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
// DONE: An example of how to read data from the filesystem
string LinuxParser::Kernel() {
string os, kernel, version;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> version >> kernel;
}
return kernel;
}
vector<int> LinuxParser::Pids() {
vector<int> pids;
DIR* directory = opendir(kProcDirectory.c_str());
struct dirent* file;
while ((file = readdir(directory)) != nullptr) {
// Is this a directory?
if (file->d_type == DT_DIR) {
// Is every character of the name a digit?
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
int pid = stoi(filename);
pids.push_back(pid);
}
}
}
closedir(directory);
return pids;
}
float LinuxParser::MemoryUtilization() {
long int memTotal, memFree, buffers, cached, data;
string line, meminfo;
std::ifstream stream(kProcDirectory + kMeminfoFilename);
if (!stream.is_open()) {
return 0.0;
}
while(std::getline(stream, line)) {
std::istringstream linestream(line);
linestream >> meminfo >> data;
if (meminfo == "MemTotal:") memTotal = data;
else if (meminfo == "MemFree:") memFree = data;
else if(meminfo == "Buffers:") buffers = data;
else if(meminfo == "Cached:") cached = data;
}
// calculation done from redhat explaination
return (1-(float)(memTotal - (memFree + buffers + cached))/(float)memTotal);
}
long LinuxParser::UpTime() {
float uptime;
string line;
std::ifstream fstream(kProcDirectory+kUptimeFilename);
if(fstream.is_open()) {
std::getline(fstream, line);
std::istringstream linestream(line);
linestream >> uptime;
return uptime;
}
return 0;
}
// TODO: Read and return the number of jiffies for the system
long LinuxParser::Jiffies(std::vector<long> cpuJiffies) {
return std::accumulate(cpuJiffies.begin(), cpuJiffies.end(), 0);
}
long LinuxParser::ActiveJiffies(int pid) {
string curr, utime, stime, cutime, cstime;
string line;
std::ifstream file(kProcDirectory+to_string(pid)+kStatFilename);
if(!file.is_open())
return 0;
std::getline(file, line);
std::istringstream sstream(line);
for(int i = 0; i < 17 && sstream >> curr; i++) {
if(i == 13) utime = curr;
else if(i == 14) stime = curr;
else if(i == 15) cutime = curr;
else if(i == 16) cstime = curr;
}
// returns sum of all the active jiffies for the process
return (long)(stoi(utime)+stoi(stime)+stoi(cutime)+stoi(cstime));
}
// Read and return the number of active jiffies for the system
long LinuxParser::ActiveJiffies(std::vector<long> cpuJiffies) {
return (std::accumulate(cpuJiffies.begin(), cpuJiffies.end(), 0) - cpuJiffies[3]);
}
// Read and return the number of idle jiffies for the system
long LinuxParser::IdleJiffies(std::vector<long> cpuJiffies) {
return cpuJiffies[3];
}
// Read and return all the jiffies for the cpu
vector<long> LinuxParser::CpuUtilization() {
std::string line;
vector<long> cpuInfo = {};
std::ifstream cpuStream(kProcDirectory+kStatFilename);
if(cpuStream.is_open()) {
// ignore the first 5 characters (cpu label) and skip to next char set
cpuStream.ignore(5, ' ');
std::getline(cpuStream, line);
std::istringstream stream(line);
// add all the cpu jiffies to the vector
for(long cpu; stream >> cpu; cpuInfo.emplace_back(cpu));
}
return cpuInfo;
}
// Read and return the total number of processes
int LinuxParser::TotalProcesses() {
return GetProcessData("processes");
}
// Read and return running processes
int LinuxParser::RunningProcesses() {
return GetProcessData("procs_running");
}
string LinuxParser::Command(int pid) {
string line;
string data;
string cmd;
std::ifstream fstream(kProcDirectory+to_string(pid)+kCmdlineFilename);
if(fstream.is_open()) {
std::getline(fstream, line);
return line;
}
return string();
}
string LinuxParser::Ram(int pid) {
string line;
string data;
size_t ram;
std::ifstream fstream(kProcDirectory+to_string(pid)+kStatusFilename);
if(!fstream.is_open())
return string();
while(std::getline(fstream, line)) {
std::istringstream sstream(line);
if(sstream >> data && data == "VmSize:") {
sstream >> ram;
break;
}
}
return std::to_string(ram/1000);
}
string LinuxParser::Uid(int pid) {
string line;
string data;
string uid;
std::ifstream fstream(kProcDirectory+to_string(pid)+kStatusFilename);
if(!fstream.is_open())
return string();
while(std::getline(fstream, line)) {
std::istringstream sstream(line);
sstream >> data;
if(data != "Uid:") continue;
sstream >> uid;
break;
}
return uid;
}
string LinuxParser::User(int pid) {
string line;
string data;
string sub_token;
string user_name;
bool found_username = false;
size_t next_pos = 0;
size_t prev_pos = 0;
std::ifstream fstream(kPasswordPath);
string uid = LinuxParser::Uid(pid);
if (!fstream.is_open() || uid.length() == 0)
return string();
while (!found_username && std::getline(fstream, line)) {
std::istringstream sstream(line);
sstream >> data;
next_pos = 0;
prev_pos = 0;
// loop through the line splitting on the colon character
// until the correct uid is found
for (int i = 0; (next_pos = data.find(":", prev_pos)) != string::npos; i++) {
sub_token = data.substr(prev_pos, next_pos-prev_pos);
if (i == 0) {
user_name = sub_token;
} else if (i == 2 && sub_token.compare(uid) == 0) {
found_username = true;
break;
}
// reset the previous start position to the current next position
prev_pos = next_pos+1;
}
}
return user_name;
}
long LinuxParser::UpTime(int pid) {
string data;
string line;
std::ifstream fstream(kProcDirectory+to_string(pid)+kStatFilename);
if(!fstream.is_open()) {
return 0;
}
std::getline(fstream, line);
std::istringstream sstream(line);
// get the 21 index value of the line of data
for(int i = 0; i < 22 && sstream >> data; i++);
return (long)(stoi(data)/sysconf(_SC_CLK_TCK));
}
int GetProcessData(std::string label) {
int value;
string data;
string line;
std::ifstream fstream(LinuxParser::kProcDirectory+LinuxParser::kStatFilename);
if(!fstream.is_open())
return 0;
while(std::getline(fstream, line)) {
std::istringstream linestream(line);
linestream >> data;
if(data != label) continue;
// we got the value we need so just break the loop
linestream >> value;
break;
}
return value;
}
| 25.132258 | 84 | 0.646259 | [
"vector"
] |
8f5e9f581560ce7f9094e9502bb4e19bf42c13e3 | 2,832 | cpp | C++ | src/level0/render/vulkan/api_physicaldevice.cpp | hitomi-team/quanta | 048788f4b5172fa9345eff18afc7b4d9cbb8d6dd | [
"BSD-2-Clause"
] | 2 | 2021-12-24T03:08:23.000Z | 2021-12-24T03:16:58.000Z | src/level0/render/vulkan/api_physicaldevice.cpp | hitomi-team/quanta | 048788f4b5172fa9345eff18afc7b4d9cbb8d6dd | [
"BSD-2-Clause"
] | null | null | null | src/level0/render/vulkan/api_physicaldevice.cpp | hitomi-team/quanta | 048788f4b5172fa9345eff18afc7b4d9cbb8d6dd | [
"BSD-2-Clause"
] | null | null | null | #include "level0/pch.h"
#include "api.h"
// CPU Accessible Device Memory
// (Usually the PCI BAR on x86)
static const VkMemoryPropertyFlags VULKAN_ACCESSIBLE_DEVICE_MEMORY = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
VulkanPhysicalDevice::VulkanPhysicalDevice(VkPhysicalDevice _handle)
{
static const std::array< EPhysicalDeviceType, 5 > deviceTypes {
PHYSICAL_DEVICE_TYPE_OTHER,
PHYSICAL_DEVICE_TYPE_INTEGRATED,
PHYSICAL_DEVICE_TYPE_DISCRETE,
PHYSICAL_DEVICE_TYPE_VIRTUAL,
PHYSICAL_DEVICE_TYPE_CPU
};
this->handle = _handle;
VkPhysicalDeviceProperties properties;
VkPhysicalDeviceFeatures features;
vkGetPhysicalDeviceProperties(this->handle, &properties);
vkGetPhysicalDeviceFeatures(this->handle, &features);
uint32_t numExtensions;
vkEnumerateDeviceExtensionProperties(this->handle, nullptr, &numExtensions, nullptr);
std::vector< VkExtensionProperties > extensions;
vkEnumerateDeviceExtensionProperties(this->handle, nullptr, &numExtensions, extensions.data());
vkGetPhysicalDeviceMemoryProperties(this->handle, &this->memProperties);
this->name = properties.deviceName;
this->cachedInfo = {};
this->cachedInfo.hardware.name = properties.deviceName;
this->cachedInfo.hardware.vendorID = properties.vendorID;
this->cachedInfo.hardware.deviceID = properties.deviceID;
this->cachedInfo.hardware.type = deviceTypes[properties.deviceType];
VkPhysicalDeviceMemoryProperties memoryProperties;
vkGetPhysicalDeviceMemoryProperties(this->handle, &memoryProperties);
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) {
VkMemoryType type = memoryProperties.memoryTypes[i];
// look for device local host visible heap
// * Assume SAM off when no such heap is present
if ((type.propertyFlags & VULKAN_ACCESSIBLE_DEVICE_MEMORY) == VULKAN_ACCESSIBLE_DEVICE_MEMORY) {
VkMemoryHeap heap = memoryProperties.memoryHeaps[type.heapIndex];
// now check if the heap is device local
if (heap.flags & (VK_MEMORY_HEAP_DEVICE_LOCAL_BIT | VK_MEMORY_HEAP_MULTI_INSTANCE_BIT)) {
// determine SAM support by checking that BAR heap size is over 256 MiB
// for SoC / integrated solutions we may toggle this always on
if (heap.size > 0x10000000 || this->cachedInfo.hardware.type == PHYSICAL_DEVICE_TYPE_INTEGRATED)
this->apiFeatures.hasSmartAccessMemory = true;
}
}
}
if (this->cachedInfo.hardware.type == PHYSICAL_DEVICE_TYPE_INTEGRATED && properties.vendorID == 0x1002)
this->apiFeatures.vulkanAMDAPUHeapWorkaround = true;
}
RenderPhysicalDeviceInfo VulkanPhysicalDevice::GetInfo()
{
return this->cachedInfo;
}
std::shared_ptr< IRenderDevice > VulkanPhysicalDevice::CreateLogicalDevice()
{
return std::dynamic_pointer_cast< IRenderDevice >(std::make_shared< VulkanDevice >(this));
}
| 37.263158 | 182 | 0.796257 | [
"vector"
] |
8f5fea6245700889b9292948d2b4a8b7fafb2e8f | 30,847 | cpp | C++ | sololink/flightcode/rssi/rssi_send.cpp | meee1/OpenSolo | 6f299639adbad1e8d573c8ae1135832711b600e4 | [
"Apache-2.0"
] | 68 | 2019-09-23T03:27:05.000Z | 2022-03-12T03:00:41.000Z | sololink/flightcode/rssi/rssi_send.cpp | meee1/OpenSolo | 6f299639adbad1e8d573c8ae1135832711b600e4 | [
"Apache-2.0"
] | 22 | 2019-10-26T20:15:56.000Z | 2022-02-12T05:41:56.000Z | sololink/flightcode/rssi/rssi_send.cpp | meee1/OpenSolo | 6f299639adbad1e8d573c8ae1135832711b600e4 | [
"Apache-2.0"
] | 33 | 2019-09-29T19:52:19.000Z | 2022-03-12T03:00:43.000Z | #include <stdio.h>
#include <unistd.h>
#include <net/if.h>
#include <syslog.h>
#include <netlink/netlink.h>
#include <netlink/genl/ctrl.h>
#include <netlink/genl/genl.h>
#include <linux/nl80211.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "../mavlink/c_library/common/mavlink.h"
#include "util.h"
/*
* Retrieve wifi information and:
* - log it
* - send mavlinke rssi message
*
* Netlink documentation: http://www.infradead.org/~tgr/libnl/
* Netlink example: iw
*/
/*
* Implementation notes
*
* Each time this runs it creates a unix socket in /tmp. Since there is no
* "clean" exit from this program, that socket is not deleted until the next
* reboot, and then only because /tmp is not persistent. There is a very
* unlikely failure mode where when this program dies and restarts, it comes
* back with the same PID; if that happens, it will probably fail to bind to
* the unix socket (since it /tmp/rssi_send.<pid> will already exist) and
* exit. Whoever started this program (inittab) will notice and start it
* again. [That case has never been observed to happen.]
*
* The netlink message creation, sending, and parsing is rather mysterious;
* there is little in the way of documentation other than the source code.
* Some basic unknowns are things like when we allocate a message and give it
* to the send function, who should free it? It would be possible to drill
* down further into the source and figure it out, but instead, testing is
* used; a run at 1000 msgs/sec for tens of minutes shows that the program's
* size is not growning, so there are probably no leaks.
*
* Late conversion from C to C++ to add logging.
*
* The netlink stuff returns information in attribute tables. When we get
* one of those, we copy the attributes that are present into a simple
* structure defined here (station_info and rate_info). Each of those
* structures has a name that corresponds with one of the attribute enums
* in linux/nl80211.h, and the struct has fields corresponding to the
* enum values.
*/
/* system and component IDs to use in mavlink header */
static uint8_t system_id = 10; /* change with -s option */
static uint8_t component_id = 0; /* change with -c option */
/* time between rssi messages (default 1 second) */
static unsigned interval_ms = 1000; /* change with -i option */
/* run verbose (debug) */
static int verbose = 0;
#define DBG(X)
/*
* Rate info, contained in station info
*
* Fields commented out are ones where linux/nl80211.h does not say what the
* type is, and we don't need right now, so they are just left out.
*/
typedef struct rate_info {
uint16_t bitrate; /* total bitrate (u16, 100kbit/s) */
uint8_t mcs; /* mcs index for 802.11n (u8) */
/* n40_mhz_width: 40 MHz dualchannel bitrate */
/* short_gi: 400ns guard interval */
uint32_t bitrate32; /* total bitrate (u32, 100kbit/s) */
/* max: highest rate_info number currently defined */
uint8_t vht_mcs; /* MCS index for VHT (u8) */
uint8_t vht_nss; /* number of streams in VHT (u8) */
/* n80_mhz_width: 80 MHz VHT rate */
/* n80p80_mhz_width: 80+80 MHz VHT rate */
/* n160_mhz_width: 160 MHz VHT rate */
} rate_info_t;
/* print structure to a string, debug */
static char *rate_info_str(char *s, const rate_info_t *p)
{
/* 43 chars + 5 u32 = 43 + 5 * 10 = 93 chars max */
sprintf(s, "bitrate=%u mcs=%u bitrate32=%u vht_mcs=%u vht_nss=%u", p->bitrate, p->mcs,
p->bitrate32, p->vht_mcs, p->vht_nss);
return s;
}
/*
* Information retrieved via station info request message
*
* Fields commented out are ones where linux/nl80211.h does not say what the
* type is, and we don't need right now, so they are just left out.
*/
typedef struct station_info {
uint32_t inactive_time; /* time since last activity (u32, msecs) */
uint32_t rx_bytes; /* total received bytes (u32, from this station) */
uint32_t tx_bytes; /* total transmitted bytes (u32, to this station) */
uint64_t rx_bytes64; /* total received bytes (u64, from this station) */
uint64_t tx_bytes64; /* total transmitted bytes (u64, to this station) */
int8_t signal; /* signal strength of last received PPDU (u8, dBm) */
rate_info_t tx_bitrate; /* current unicast tx rate, nested attribute containing
info as possible, see &enum nl80211_rate_info */
uint32_t rx_packets; /* total received packet (u32, from this station) */
uint32_t tx_packets; /* total transmitted packets (u32, to this station) */
uint32_t tx_retries; /* total retries (u32, to this station) */
uint32_t tx_failed; /* total failed packets (u32, to this station) */
int8_t signal_avg; /* signal strength average (u8, dBm) */
/* llid: the station's mesh LLID */
/* plid: the station's mesh PLID */
/* plink_state: peer link state for the station (see %enum nl80211_plink_state) */
rate_info_t rx_bitrate; /* last unicast data frame rx rate, nested attribute,
like NL80211_STA_INFO_TX_BITRATE. */
/* bss_param: current station's view of BSS, nested attribute containing info as
possible, see &enum nl80211_sta_bss_param */
/* connected_time: time since the station is last connected */
/* sta_flags: Contains a struct nl80211_sta_flag_update. */
uint32_t beacon_loss; /* count of times beacon loss was detected (u32) */
int64_t t_offset; /* timing offset with respect to this STA (s64) */
/* local_pm: local mesh STA link-specific power mode */
/* peer_pm: peer mesh STA link-specific power mode */
/* nonpeer_pm: neighbor mesh STA power save mode towards non-peer STA */
} station_info_t;
/*
* Information retrieved via station info request message
*
* Fields commented out are ones where linux/nl80211.h does not say what the
* type is, and we don't need right now, so they are just left out.
*/
typedef struct survey_info {
/*
* NL80211_SURVEY_INFO_FREQUENCY: center frequency of channel
* NL80211_SURVEY_INFO_NOISE: noise level of channel (u8, dBm)
* NL80211_SURVEY_INFO_IN_USE: channel is currently being used
* NL80211_SURVEY_INFO_TIME: amount of time (in ms) that the radio
* was turned on (on channel or globally)
* NL80211_SURVEY_INFO_TIME_BUSY: amount of the time the primary
* channel was sensed busy (either due to activity or energy detect)
* NL80211_SURVEY_INFO_TIME_EXT_BUSY: amount of time the extension
* channel was sensed busy
* NL80211_SURVEY_INFO_TIME_RX: amount of time the radio spent
* receiving data (on channel or globally)
* NL80211_SURVEY_INFO_TIME_TX: amount of time the radio spent
* transmitting data (on channel or globally)
* NL80211_SURVEY_INFO_TIME_SCAN: time the radio spent for scan (on this channel or globally)
*/
bool in_use;
uint32_t freq;
int8_t noise;
uint64_t chan_active_time;
uint64_t chan_busy_time;
uint64_t chan_ext_busy_time;
uint64_t chan_receive_time;
uint64_t chan_transmit_time;
} survey_info_t;
// state related to our netlink context
typedef struct {
struct nl_sock *sock;
int nl80211_id;
unsigned int if_index;
struct nl_cb *cmd_cb;
struct nl_cb *sock_cb;
} nl_state_t;
// items that are referenced in netlink callback context
typedef struct {
volatile int
status; // ensure this is always dereferenced, even when only being written in callbacks
station_info_t station_info;
survey_info_t survey_info;
} cb_ctx_t;
/* print structure to console, debug */
static void station_info_dump(const station_info_t *s)
{
char buf[100];
printf("inactive_time=%u\n", s->inactive_time);
printf("rx_bytes=%u tx_bytes=%u rx_bytes64=%llu tx_bytes64=%llu\n", s->rx_bytes, s->tx_bytes,
s->rx_bytes64, s->tx_bytes64);
printf("signal=%d signal_avg=%d beacon_loss=%u t_offset=%lld\n", s->signal, s->signal_avg,
s->beacon_loss, s->t_offset);
printf("rx_packets=%u tx_packets=%u tx_retries=%u tx_failed=%u\n", s->rx_packets, s->tx_packets,
s->tx_retries, s->tx_failed);
printf("tx_bitrate: %s\n", rate_info_str(buf, &s->tx_bitrate));
printf("rx_bitrate: %s\n", rate_info_str(buf, &s->rx_bitrate));
}
static void send_rssi(int rssi, unsigned retries);
static void get_station_info(cb_ctx_t *cb_ctx, const nl_state_t *nl);
static void get_survey_info(cb_ctx_t *cb_ctx, const nl_state_t *nl);
static int valid_handler(struct nl_msg *msg, void *arg);
static int station_handler(struct nl_msg *msg, station_info_t *station_info);
static int survey_handler(struct nl_msg *msg, survey_info_t *survey_info);
static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg);
static int finish_handler(struct nl_msg *msg, void *arg);
static int ack_handler(struct nl_msg *msg, void *arg);
static bool nl_state_init(nl_state_t *nl);
static bool nl_state_init_callbacks(nl_state_t *nl, cb_ctx_t *cb);
static void usage(void)
{
printf("rssi_send [-i interval_msec] [-s system_id] [-c component_id] [-v]\n");
exit(1);
}
static uint64_t diff_clamp(uint64_t curr, uint64_t prev)
{
if (curr < prev) {
return 0;
}
return curr - prev;
}
static void log_station_info(const station_info_t *curr, const station_info_t *prev)
{
/* station_info.[tr]x_bitrate.bitrate32 is in units of 100,000 */
syslog(LOG_INFO, "station sig=%d txr=%d.%d rxr=%d.%d ret=%llu err=%d", curr->signal_avg,
curr->tx_bitrate.bitrate32 / 10, curr->tx_bitrate.bitrate32 % 10,
curr->rx_bitrate.bitrate32 / 10, curr->rx_bitrate.bitrate32 % 10,
diff_clamp(curr->tx_retries, prev->tx_retries), curr->tx_failed);
}
static void log_survey_info(const survey_info_t *curr, const survey_info_t *prev)
{
syslog(LOG_INFO, "survey freq=%d noise=%d active=%llu busy=%llu ext_busy=%llu rx=%llu tx=%llu",
curr->freq, curr->noise, diff_clamp(curr->chan_active_time, prev->chan_active_time),
diff_clamp(curr->chan_busy_time, prev->chan_busy_time),
diff_clamp(curr->chan_ext_busy_time, prev->chan_ext_busy_time),
diff_clamp(curr->chan_receive_time, prev->chan_receive_time),
diff_clamp(curr->chan_transmit_time, prev->chan_transmit_time));
}
/*
* main program -
* initialize, then loop: read wifi status, log it, send rssi message
*/
int main(int argc, char *argv[])
{
int opt;
uint64_t now_us;
uint64_t next_us;
unsigned interval_us;
cb_ctx_t cb_ctx;
nl_state_t nl_state;
station_info_t last_station_info;
survey_info_t last_survey_info;
/* all arguments are optional; normal use is with no arguments */
while ((opt = getopt(argc, argv, "i:s:c:v:")) != -1) {
switch (opt) {
case 'i':
interval_ms = atoi(optarg);
break;
case 's':
system_id = atoi(optarg);
break;
case 'c':
component_id = atoi(optarg);
break;
case 'v':
verbose = atoi(optarg);
break;
default:
usage();
}
}
memset(&cb_ctx, 0, sizeof cb_ctx);
memset(&last_station_info, 0, sizeof last_station_info);
memset(&last_survey_info, 0, sizeof last_survey_info);
openlog("rssi_send", LOG_NDELAY, LOG_LOCAL3);
syslog(LOG_INFO, "main: built " __DATE__ " " __TIME__);
if (!nl_state_init(&nl_state)) {
syslog(LOG_ERR, "failed to init netlink\n");
exit(1);
}
if (!nl_state_init_callbacks(&nl_state, &cb_ctx)) {
syslog(LOG_ERR, "failed to init callbacks\n");
exit(1);
}
interval_us = interval_ms * 1000;
next_us = clock_gettime_us(CLOCK_MONOTONIC) + interval_us;
while (1) {
// delay until the next message time
now_us = clock_gettime_us(CLOCK_MONOTONIC);
if (next_us > now_us)
usleep(next_us - now_us);
next_us += interval_us;
// both these are blocking
get_station_info(&cb_ctx, &nl_state);
get_survey_info(&cb_ctx, &nl_state);
if (verbose >= 1)
station_info_dump(&cb_ctx.station_info);
log_station_info(&cb_ctx.station_info, &last_station_info);
log_survey_info(&cb_ctx.survey_info, &last_survey_info);
unsigned retries = diff_clamp(cb_ctx.station_info.tx_retries, last_station_info.tx_retries);
memcpy(&last_station_info, &cb_ctx.station_info, sizeof last_station_info);
memcpy(&last_survey_info, &cb_ctx.survey_info, sizeof last_survey_info);
send_rssi(cb_ctx.station_info.signal_avg, retries);
}
return 0;
} /* main */
bool nl_state_init(nl_state_t *nl)
{
/*
* Initialize our netlink context.
*/
memset(nl, 0, sizeof *nl);
nl->sock = nl_socket_alloc();
if (nl->sock == NULL) {
fprintf(stderr, "ERROR allocating netlink socket\n");
goto cleanup;
}
DBG(printf("nl_socket_alloc: nl_sock=%p\n", nl_sock);)
if (genl_connect(nl->sock) != 0) {
fprintf(stderr, "ERROR connecting netlink socket\n");
goto cleanup;
}
DBG(printf("genl_connect: ok\n");)
nl->nl80211_id = genl_ctrl_resolve(nl->sock, "nl80211");
if (nl->nl80211_id < 0) {
fprintf(stderr, "ERROR resolving netlink socket\n");
goto cleanup;
}
DBG(printf("genl_ctrl_resolve: nl80211_id=%d\n", nl80211_id);)
nl->if_index = if_nametoindex("wlan0");
if (nl->if_index == 0) {
fprintf(stderr, "ERROR getting interface index\n");
goto cleanup;
}
DBG(printf("if_nametoindex: if_index=%u\n", if_index);)
return true;
cleanup:
if (nl->sock != NULL)
nl_socket_free(nl->sock);
return false;
}
bool nl_state_init_callbacks(nl_state_t *nl, cb_ctx_t *cb)
{
/*
* Register our callbacks to handle netlink responses/events.
*/
nl->cmd_cb = nl_cb_alloc(NL_CB_DEFAULT);
if (nl->cmd_cb == NULL) {
fprintf(stderr, "ERROR allocating netlink command callback\n");
goto cleanup;
}
DBG(printf("nl_cb_alloc: cmd_cb=%p\n", cmd_cb);)
nl->sock_cb = nl_cb_alloc(NL_CB_DEFAULT);
if (nl->sock_cb == NULL) {
fprintf(stderr, "ERROR allocating netlink socket callback\n");
goto cleanup;
}
DBG(printf("nl_cb_alloc: sock_cb=%p\n", nl->sock_cb);)
// handle all NL_CB_VALID callbacks via valid_handler()
if (nl_cb_set(nl->cmd_cb, NL_CB_VALID, NL_CB_CUSTOM, valid_handler, cb) != 0) {
fprintf(stderr, "ERROR setting command callback\n");
goto cleanup;
}
DBG(printf("nl_cb_set: ok\n");)
// not clear that this is necessary, but following example convention for now...
nl_socket_set_cb(nl->sock, nl->sock_cb);
nl_cb_err(nl->cmd_cb, NL_CB_CUSTOM, error_handler, cb);
nl_cb_set(nl->cmd_cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, cb);
nl_cb_set(nl->cmd_cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, cb);
return true;
cleanup:
if (nl->sock_cb != NULL) {
nl_cb_put(nl->sock_cb);
}
if (nl->cmd_cb != NULL) {
nl_cb_put(nl->cmd_cb);
}
return false;
}
/* send mavlink radio_status (rssi) message */
static void send_rssi(int rssi, unsigned retries)
{
/* socket used to send to telem downlink */
static int fd = -1;
/* destination address */
static struct sockaddr_un sa_dst;
char sock_name[32];
struct sockaddr_un sa_src;
static unsigned const msg_max = 256;
unsigned msg_len;
uint8_t msg_buf[msg_max];
mavlink_message_t msg;
int num_bytes;
uint8_t u8_rssi;
uint8_t u8_retries;
/* one-time init */
if (fd == -1) {
fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1) {
perror("socket");
return;
}
memset(sock_name, 0, sizeof(sock_name));
snprintf(sock_name, sizeof(sock_name) - 1, "/tmp/rssi_send.%u", getpid());
memset(&sa_src, 0, sizeof(sa_src));
sa_src.sun_family = AF_UNIX;
strncpy(sa_src.sun_path, sock_name, sizeof(sa_src.sun_path) - 1);
if (bind(fd, (struct sockaddr *)&sa_src, sizeof(sa_src)) != 0) {
perror("bind");
close(fd);
fd = -1;
return;
}
/* set destination address that will be used for sendto */
memset(sock_name, 0, sizeof(sock_name));
strcpy(sock_name, "/run/telem_downlink");
memset(&sa_dst, 0, sizeof(sa_dst));
sa_dst.sun_family = AF_UNIX;
strncpy(sa_dst.sun_path, sock_name, sizeof(sa_dst.sun_path) - 1);
} /* if (fd...) */
u8_rssi = (uint8_t)rssi;
u8_retries = (uint8_t)retries;
mavlink_msg_radio_status_pack(system_id, component_id, &msg, 0, /* rssi */
u8_rssi, /* remrssi */
0, /* txbuf */
0, /* noise */
0, /* remnoise */
u8_retries, /* rxerrors */
0); /* fixed */
msg_len = mavlink_msg_to_send_buffer(msg_buf, &msg);
if (verbose >= 2)
printf("rssi_send: %02x %02x %02x %02x %02x %02x\n", msg_buf[0], msg_buf[1], msg_buf[2],
msg_buf[3], msg_buf[4], msg_buf[5]);
num_bytes = sendto(fd, msg_buf, msg_len, 0, (struct sockaddr *)&sa_dst, sizeof(sa_dst));
if (num_bytes < 0)
perror("sendto");
} /* send_rssi */
static bool send_nlcmd(const nl_state_t *nl, nl80211_commands c, int nl_msg_flags)
{
/*
* Assemble and send the netlink command 'c'.
*/
void *hdr = NULL;
int num_bytes = -1;
uint32_t if_index_uint32;
struct nl_msg *msg;
bool success = true;
msg = nlmsg_alloc();
if (msg == NULL) {
fprintf(stderr, "ERROR allocating netlink message\n");
success = false;
goto cleanup;
}
DBG(printf("nlmsg_alloc: msg=%p\n", msg);)
hdr = genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, nl->nl80211_id, 0, nl_msg_flags, c, 0);
if (hdr == NULL) {
fprintf(stderr, "ERROR creating netlink message\n");
success = false;
goto cleanup;
}
DBG(printf("genlmsg_put: hdr=%p\n", hdr);)
if_index_uint32 = nl->if_index;
if (nla_put(msg, NL80211_ATTR_IFINDEX, sizeof(uint32_t), &if_index_uint32) != 0) {
fprintf(stderr, "ERROR setting message attribute\n");
success = false;
goto cleanup;
}
DBG(printf("nla_put: ok\n");)
num_bytes = nl_send_auto(nl->sock, msg);
if (num_bytes < 0) {
fprintf(stderr, "ERROR sending netlink message\n");
success = false;
goto cleanup;
}
DBG(printf("nl_send_auto_complete: num_bytes=%d\n", num_bytes);)
cleanup:
if (msg != NULL) {
nlmsg_free(msg);
}
return success;
}
/*
* Get station info from interface via netlink
*
* This sends the request to the kernel to send us the station info,
* then waits for the response to come back. The response comes back
* as a callback (station_handler):
*
* Normal operation:
* this function sends request
* this function calls nl_recvmsgs; inside that, station_handler is called
* station_handler fills in station_info
* this function calls nl_recvmsgs; inside that, finish_handler is called
* finish_handler clears 'status'
* this function sees status is cleared and returns
*
* Almost everything returned is parsed out and available. Only a few items
* are logged, and only the signal strength is used in the mavlink message,
* but pulling them all out of the netlink message should make it easier to
* log more (or something different) if we want.
*/
static void get_station_info(cb_ctx_t *cb_ctx, const nl_state_t *nl)
{
memset(&cb_ctx->station_info, 0, sizeof(cb_ctx->station_info));
cb_ctx->status = 1;
if (!send_nlcmd(nl, NL80211_CMD_GET_STATION, NLM_F_DUMP)) {
return;
}
/* wait for callback to set station_info and set status=0 */
while (cb_ctx->status == 1) {
int rv = nl_recvmsgs(nl->sock, nl->cmd_cb);
if (rv != 0) {
fprintf(stderr, "nl_recvmsgs: %d\n", rv);
}
}
}
void get_survey_info(cb_ctx_t *cb_ctx, const nl_state_t *nl)
{
memset(&cb_ctx->survey_info, 0, sizeof(cb_ctx->survey_info));
cb_ctx->status = 1;
if (!send_nlcmd(nl, NL80211_CMD_GET_SURVEY, NLM_F_DUMP)) {
return;
}
/* wait for callback to set set status=0 */
while (cb_ctx->status == 1) {
int rv = nl_recvmsgs(nl->sock, nl->cmd_cb);
if (rv != 0) {
fprintf(stderr, "nl_recvmsgs: %d\n", rv);
}
}
}
int valid_handler(struct nl_msg *msg, void *arg)
{
/*
* Top level handler for all NL_CB_VALID/NL_CB_CUSTOM responses.
*
* Check the reported cmd and dispatch accordingly.
*/
struct nlmsghdr *nl_hdr = nlmsg_hdr(msg);
struct genlmsghdr *genl_hdr = (struct genlmsghdr *)nlmsg_data(nl_hdr);
cb_ctx_t *ctx = (cb_ctx_t *)arg;
switch (genl_hdr->cmd) {
case NL80211_CMD_NEW_STATION:
return station_handler(msg, &ctx->station_info);
case NL80211_CMD_NEW_SURVEY_RESULTS:
return survey_handler(msg, &ctx->survey_info);
default:
// unexpected msg
return NL_SKIP;
}
}
/*
* Called for each station result message that comes back from the kernel.
* We expect only one before finish_handler is called.
*/
static int station_handler(struct nl_msg *msg, station_info_t *station_info)
{
struct nlattr *tb1[NL80211_ATTR_MAX + 1];
struct nlmsghdr *nl_hdr;
struct genlmsghdr *genl_hdr;
struct nlattr *genl_attr_data;
int genl_attr_len;
struct nlattr *tb2[NL80211_STA_INFO_MAX + 1];
static struct nla_policy policy2[NL80211_STA_INFO_MAX + 1] = {{0}};
struct nlattr *tb3[NL80211_RATE_INFO_MAX + 1];
static struct nla_policy policy3[NL80211_RATE_INFO_MAX + 1] = {{0}};
nl_hdr = nlmsg_hdr(msg);
genl_hdr = (struct genlmsghdr *)nlmsg_data(nl_hdr);
genl_attr_data = genlmsg_attrdata(genl_hdr, 0);
genl_attr_len = genlmsg_attrlen(genl_hdr, 0);
if (nla_parse(tb1, NL80211_ATTR_MAX, genl_attr_data, genl_attr_len, NULL) != 0) {
fprintf(stderr, "ERROR parsing netlink message attributes\n");
return NL_SKIP;
}
if (tb1[NL80211_ATTR_STA_INFO] == NULL) {
printf("no data\n");
return NL_SKIP;
}
if (nla_parse_nested(tb2, NL80211_STA_INFO_MAX, tb1[NL80211_ATTR_STA_INFO], policy2) != 0) {
printf("ERROR parsing netlink message nested attributes\n");
return NL_SKIP;
}
/* Description of what attributes there are is in linux/nl80211.h */
/* For each possible attribute, see if it is present in the info we
* got, and if so, copy it to our station_info_t structure. */
if (tb2[NL80211_STA_INFO_INACTIVE_TIME] != NULL)
station_info->inactive_time = nla_get_u32(tb2[NL80211_STA_INFO_INACTIVE_TIME]);
if (tb2[NL80211_STA_INFO_RX_BYTES] != NULL)
station_info->rx_bytes = nla_get_u32(tb2[NL80211_STA_INFO_RX_BYTES]);
if (tb2[NL80211_STA_INFO_TX_BYTES] != NULL)
station_info->tx_bytes = nla_get_u32(tb2[NL80211_STA_INFO_TX_BYTES]);
if (tb2[NL80211_STA_INFO_RX_BYTES64] != NULL)
station_info->rx_bytes64 = nla_get_u64(tb2[NL80211_STA_INFO_RX_BYTES64]);
if (tb2[NL80211_STA_INFO_TX_BYTES64] != NULL)
station_info->tx_bytes64 = nla_get_u64(tb2[NL80211_STA_INFO_TX_BYTES64]);
/* this appears to be signed dBm, not a u8 */
if (tb2[NL80211_STA_INFO_SIGNAL] != NULL)
station_info->signal = (int8_t)nla_get_u8(tb2[NL80211_STA_INFO_SIGNAL]);
/* tx_bitrate is a nested structure; the station_info points to a nested
* attribute thing that needs to be decoded */
if (tb2[NL80211_STA_INFO_TX_BITRATE] != NULL &&
nla_parse_nested(tb3, NL80211_RATE_INFO_MAX, tb2[NL80211_STA_INFO_TX_BITRATE], policy3) ==
0) {
rate_info_t *rate_info = &station_info->tx_bitrate;
if (tb3[NL80211_RATE_INFO_BITRATE] != NULL)
rate_info->bitrate = nla_get_u16(tb3[NL80211_RATE_INFO_BITRATE]);
if (tb3[NL80211_RATE_INFO_MCS] != NULL)
rate_info->mcs = nla_get_u8(tb3[NL80211_RATE_INFO_MCS]);
if (tb3[NL80211_RATE_INFO_BITRATE32] != NULL)
rate_info->bitrate32 = nla_get_u32(tb3[NL80211_RATE_INFO_BITRATE32]);
if (tb3[NL80211_RATE_INFO_VHT_MCS] != NULL)
rate_info->vht_mcs = nla_get_u8(tb3[NL80211_RATE_INFO_VHT_MCS]);
if (tb3[NL80211_RATE_INFO_VHT_NSS] != NULL)
rate_info->vht_nss = nla_get_u8(tb3[NL80211_RATE_INFO_VHT_NSS]);
}
if (tb2[NL80211_STA_INFO_RX_PACKETS] != NULL)
station_info->rx_packets = nla_get_u32(tb2[NL80211_STA_INFO_RX_PACKETS]);
if (tb2[NL80211_STA_INFO_TX_PACKETS] != NULL)
station_info->tx_packets = nla_get_u32(tb2[NL80211_STA_INFO_TX_PACKETS]);
if (tb2[NL80211_STA_INFO_TX_RETRIES] != NULL)
station_info->tx_retries = nla_get_u32(tb2[NL80211_STA_INFO_TX_RETRIES]);
if (tb2[NL80211_STA_INFO_TX_FAILED] != NULL)
station_info->tx_failed = nla_get_u32(tb2[NL80211_STA_INFO_TX_FAILED]);
/* this appears to be signed dBm, not a u8 */
if (tb2[NL80211_STA_INFO_SIGNAL_AVG] != NULL)
station_info->signal_avg = (int8_t)nla_get_u8(tb2[NL80211_STA_INFO_SIGNAL_AVG]);
/* rx_bitrate is nested, like tx_bitrate */
if (tb2[NL80211_STA_INFO_RX_BITRATE] != NULL &&
nla_parse_nested(tb3, NL80211_RATE_INFO_MAX, tb2[NL80211_STA_INFO_RX_BITRATE], policy3) ==
0) {
rate_info_t *rate_info = &station_info->rx_bitrate;
if (tb3[NL80211_RATE_INFO_BITRATE] != NULL)
rate_info->bitrate = nla_get_u16(tb3[NL80211_RATE_INFO_BITRATE]);
if (tb3[NL80211_RATE_INFO_MCS] != NULL)
rate_info->mcs = nla_get_u8(tb3[NL80211_RATE_INFO_MCS]);
if (tb3[NL80211_RATE_INFO_BITRATE32] != NULL)
rate_info->bitrate32 = nla_get_u32(tb3[NL80211_RATE_INFO_BITRATE32]);
if (tb3[NL80211_RATE_INFO_VHT_MCS] != NULL)
rate_info->vht_mcs = nla_get_u8(tb3[NL80211_RATE_INFO_VHT_MCS]);
if (tb3[NL80211_RATE_INFO_VHT_NSS] != NULL)
rate_info->vht_nss = nla_get_u8(tb3[NL80211_RATE_INFO_VHT_NSS]);
}
if (tb2[NL80211_STA_INFO_BEACON_LOSS] != NULL)
station_info->beacon_loss = nla_get_u32(tb2[NL80211_STA_INFO_BEACON_LOSS]);
if (tb2[NL80211_STA_INFO_T_OFFSET] != NULL)
station_info->t_offset = (int64_t)nla_get_u64(tb2[NL80211_STA_INFO_T_OFFSET]);
return NL_SKIP;
} /* station_handler */
static int survey_handler(struct nl_msg *msg, survey_info_t *survey_info)
{
/*
* https://wireless.wiki.kernel.org/en/users/Documentation/acs says
*
* - active time is the amount of time the radio has spent on the channel
* - busy time is the amount of time the channel has spent on the channel but noticed the
* channel was busy
* and could not initiate communication if it wanted to.
* - tx time is the amount of time the channel has spent on the channel transmitting data.
* - interference factor is defined as the ratio of the observed busy time over the time we
* spent on the channel,
* this value is then amplified by the noise floor observed on the channel in comparison to
* the lowest noise floor
* observed on the entire band.
*/
struct nlattr *tb[NL80211_ATTR_MAX + 1];
struct genlmsghdr *gnlh = (struct genlmsghdr *)nlmsg_data(nlmsg_hdr(msg));
struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
char dev[20];
static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1];
survey_policy[NL80211_SURVEY_INFO_FREQUENCY].type = NLA_U32;
survey_policy[NL80211_SURVEY_INFO_NOISE].type = NLA_U8;
nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL);
if_indextoname(nla_get_u32(tb[NL80211_ATTR_IFINDEX]), dev);
if (!tb[NL80211_ATTR_SURVEY_INFO]) {
fprintf(stderr, "survey data missing!\n");
return NL_SKIP;
}
if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX, tb[NL80211_ATTR_SURVEY_INFO],
survey_policy)) {
fprintf(stderr, "failed to parse nested attributes!\n");
return NL_SKIP;
}
if (sinfo[NL80211_SURVEY_INFO_FREQUENCY]) {
survey_info->in_use = sinfo[NL80211_SURVEY_INFO_IN_USE] ? true : false;
if (!survey_info->in_use) {
return NL_SKIP;
}
survey_info->freq = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
}
if (sinfo[NL80211_SURVEY_INFO_NOISE]) {
survey_info->noise = nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
}
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]) {
survey_info->chan_active_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]);
}
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]) {
survey_info->chan_busy_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]);
}
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_EXT_BUSY]) {
survey_info->chan_ext_busy_time =
nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_EXT_BUSY]);
}
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX]) {
survey_info->chan_receive_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX]);
}
if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX]) {
survey_info->chan_transmit_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX]);
}
#if 0
if (sinfo[NL80211_SURVEY_INFO_TIME_SCAN]) {
survey_info->chan_scan_time = nla_get_u64(sinfo[NL80211_SURVEY_INFO_TIME_SCAN]);
}
#endif
return NL_SKIP;
}
/* Never seen this one called, but the examples have it. */
static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
{
cb_ctx_t *cb_ctx = (cb_ctx_t *)arg;
cb_ctx->status = err->error;
return NL_STOP;
}
/*
* Called after station info message is sent. The calling of this is how we
* know we're done.
*
* Other commands sent to netlink might get several responses back; this is
* more useful in those cases.
*/
static int finish_handler(struct nl_msg *msg, void *arg)
{
cb_ctx_t *cb_ctx = (cb_ctx_t *)arg;
cb_ctx->status = 0;
return NL_SKIP;
}
/* Never seen this one called, but the examples have it. */
static int ack_handler(struct nl_msg *msg, void *arg)
{
cb_ctx_t *cb_ctx = (cb_ctx_t *)arg;
cb_ctx->status = 0;
return NL_STOP;
}
| 35.868605 | 100 | 0.664732 | [
"mesh"
] |
8f603d4b8cb6cc9aa3b5887d7d32b283eef9c850 | 10,048 | cc | C++ | services/network/restricted_cookie_manager.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | services/network/restricted_cookie_manager.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | services/network/restricted_cookie_manager.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/network/restricted_cookie_manager.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "mojo/public/cpp/bindings/message.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/cookies/cookie_constants.h"
#include "net/cookies/cookie_options.h"
#include "net/cookies/cookie_store.h"
namespace network {
namespace {
// TODO(pwnall): De-duplicate from cookie_manager.cc
network::mojom::CookieChangeCause ToCookieChangeCause(
net::CookieChangeCause net_cause) {
switch (net_cause) {
case net::CookieChangeCause::INSERTED:
return network::mojom::CookieChangeCause::INSERTED;
case net::CookieChangeCause::EXPLICIT:
return network::mojom::CookieChangeCause::EXPLICIT;
case net::CookieChangeCause::UNKNOWN_DELETION:
return network::mojom::CookieChangeCause::UNKNOWN_DELETION;
case net::CookieChangeCause::OVERWRITE:
return network::mojom::CookieChangeCause::OVERWRITE;
case net::CookieChangeCause::EXPIRED:
return network::mojom::CookieChangeCause::EXPIRED;
case net::CookieChangeCause::EVICTED:
return network::mojom::CookieChangeCause::EVICTED;
case net::CookieChangeCause::EXPIRED_OVERWRITE:
return network::mojom::CookieChangeCause::EXPIRED_OVERWRITE;
}
NOTREACHED();
return network::mojom::CookieChangeCause::EXPLICIT;
}
} // anonymous namespace
class RestrictedCookieManager::Listener : public base::LinkNode<Listener> {
public:
Listener(net::CookieStore* cookie_store,
const GURL& url,
net::CookieOptions options,
network::mojom::CookieChangeListenerPtr mojo_listener)
: url_(url), options_(options), mojo_listener_(std::move(mojo_listener)) {
// TODO(pwnall): add a constructor w/options to net::CookieChangeDispatcher.
cookie_store_subscription_ =
cookie_store->GetChangeDispatcher().AddCallbackForUrl(
url,
base::BindRepeating(
&Listener::OnCookieChange,
// Safe because net::CookieChangeDispatcher guarantees that the
// callback will stop being called immediately after we remove
// the subscription, and the cookie store lives on the same
// thread as we do.
base::Unretained(this)));
}
~Listener() = default;
network::mojom::CookieChangeListenerPtr& mojo_listener() {
return mojo_listener_;
}
private:
// net::CookieChangeDispatcher callback.
void OnCookieChange(const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) {
if (!cookie.IncludeForRequestURL(url_, options_))
return;
mojo_listener_->OnCookieChange(cookie, ToCookieChangeCause(cause));
}
// The CookieChangeDispatcher subscription used by this listener.
std::unique_ptr<net::CookieChangeSubscription> cookie_store_subscription_;
// The URL whose cookies this listener is interested in.
const GURL url_;
// CanonicalCookie::IncludeForRequestURL options for this listener's interest.
const net::CookieOptions options_;
network::mojom::CookieChangeListenerPtr mojo_listener_;
DISALLOW_COPY_AND_ASSIGN(Listener);
};
RestrictedCookieManager::RestrictedCookieManager(net::CookieStore* cookie_store,
int render_process_id,
int render_frame_id)
: cookie_store_(cookie_store),
render_process_id_(render_process_id),
render_frame_id_(render_frame_id),
weak_ptr_factory_(this) {
DCHECK(cookie_store);
}
RestrictedCookieManager::~RestrictedCookieManager() {
base::LinkNode<Listener>* node = listeners_.head();
while (node != listeners_.end()) {
Listener* listener_reference = node->value();
node = node->next();
// The entire list is going away, no need to remove nodes from it.
delete listener_reference;
}
}
void RestrictedCookieManager::GetAllForUrl(
const GURL& url,
const GURL& site_for_cookies,
mojom::CookieManagerGetOptionsPtr options,
GetAllForUrlCallback callback) {
// TODO(pwnall): Replicate the call to
// ChildProcessSecurityPolicy::CanAccessDataForOrigin() in
// RenderFrameMessageFilter::GetCookies.
net::CookieOptions net_options;
if (net::registry_controlled_domains::SameDomainOrHost(
url, site_for_cookies,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
// TODO(mkwst): This check ought to further distinguish between frames
// initiated in a strict or lax same-site context.
net_options.set_same_site_cookie_mode(
net::CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX);
} else {
net_options.set_same_site_cookie_mode(
net::CookieOptions::SameSiteCookieMode::DO_NOT_INCLUDE);
}
cookie_store_->GetCookieListWithOptionsAsync(
url, net_options,
base::BindOnce(&RestrictedCookieManager::CookieListToGetAllForUrlCallback,
weak_ptr_factory_.GetWeakPtr(), url, site_for_cookies,
std::move(options), std::move(callback)));
}
void RestrictedCookieManager::CookieListToGetAllForUrlCallback(
const GURL& url,
const GURL& site_for_cookies,
mojom::CookieManagerGetOptionsPtr options,
GetAllForUrlCallback callback,
const net::CookieList& cookie_list) {
// TODO(pwnall): Replicate the security checks in
// RenderFrameMessageFilter::CheckPolicyForCookies
// Avoid unused member warnings until these are used for security checks.
(void)(render_frame_id_);
(void)(render_process_id_);
std::vector<net::CanonicalCookie> result;
result.reserve(cookie_list.size());
mojom::CookieMatchType match_type = options->match_type;
const std::string& match_name = options->name;
for (size_t i = 0; i < cookie_list.size(); ++i) {
const net::CanonicalCookie& cookie = cookie_list[i];
const std::string& cookie_name = cookie.Name();
if (match_type == mojom::CookieMatchType::EQUALS) {
if (cookie_name != match_name)
continue;
} else if (match_type == mojom::CookieMatchType::STARTS_WITH) {
if (!base::StartsWith(cookie_name, match_name,
base::CompareCase::SENSITIVE)) {
continue;
}
} else {
NOTREACHED();
}
result.emplace_back(cookie);
}
std::move(callback).Run(std::move(result));
}
void RestrictedCookieManager::SetCanonicalCookie(
const net::CanonicalCookie& cookie,
const GURL& url,
const GURL& site_for_cookies,
SetCanonicalCookieCallback callback) {
// TODO(pwnall): Replicate the call to
// ChildProcessSecurityPolicy::CanAccessDataForOrigin() in
// RenderFrameMessageFilter::SetCookie.
// TODO(pwnall): Validate the CanonicalCookie fields.
// TODO(pwnall): Replicate the AllowSetCookie check in
// RenderFrameMessageFilter::SetCookie.
base::Time now = base::Time::NowFromSystemTime();
// TODO(pwnall): Reason about whether it makes sense to allow a renderer to
// set these fields.
net::CookieSameSite cookie_same_site_mode = net::CookieSameSite::STRICT_MODE;
net::CookiePriority cookie_priority = net::COOKIE_PRIORITY_DEFAULT;
auto sanitized_cookie = std::make_unique<net::CanonicalCookie>(
cookie.Name(), cookie.Value(), cookie.Domain(), cookie.Path(), now,
cookie.ExpiryDate(), now, cookie.IsSecure(), cookie.IsHttpOnly(),
cookie_same_site_mode, cookie_priority);
// TODO(pwnall): secure_source should depend on url, and might depend on the
// renderer.
bool secure_source = true;
bool modify_http_only = false;
cookie_store_->SetCanonicalCookieAsync(std::move(sanitized_cookie),
secure_source, modify_http_only,
std::move(callback));
}
void RestrictedCookieManager::AddChangeListener(
const GURL& url,
const GURL& site_for_cookies,
network::mojom::CookieChangeListenerPtr mojo_listener) {
// TODO(pwnall): Replicate the call to
// ChildProcessSecurityPolicy::CanAccessDataForOrigin() in
// RenderFrameMessageFilter::GetCookies.
net::CookieOptions net_options;
if (net::registry_controlled_domains::SameDomainOrHost(
url, site_for_cookies,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
// TODO(mkwst): This check ought to further distinguish between frames
// initiated in a strict or lax same-site context.
net_options.set_same_site_cookie_mode(
net::CookieOptions::SameSiteCookieMode::INCLUDE_STRICT_AND_LAX);
} else {
net_options.set_same_site_cookie_mode(
net::CookieOptions::SameSiteCookieMode::DO_NOT_INCLUDE);
}
auto listener = std::make_unique<Listener>(cookie_store_, url, net_options,
std::move(mojo_listener));
listener->mojo_listener().set_connection_error_handler(
base::BindOnce(&RestrictedCookieManager::RemoveChangeListener,
weak_ptr_factory_.GetWeakPtr(),
// Safe because this owns the listener, so the listener is
// guaranteed to be alive for as long as the weak pointer
// above resolves.
base::Unretained(listener.get())));
// The linked list takes over the Listener ownership.
listeners_.Append(listener.release());
}
void RestrictedCookieManager::RemoveChangeListener(Listener* listener) {
listener->RemoveFromList();
delete listener;
}
} // namespace network
| 38.945736 | 80 | 0.698447 | [
"vector"
] |
8f65b284b9b25245aed96262b1455fc0b1d121ab | 10,804 | cpp | C++ | ItemRenamer/main.cpp | nacitar/old-projects | e5af376f868124b9828196df1f55adb682969f3d | [
"MIT"
] | 1 | 2016-05-04T04:22:42.000Z | 2016-05-04T04:22:42.000Z | ItemRenamer/main.cpp | nacitar/old-projects | e5af376f868124b9828196df1f55adb682969f3d | [
"MIT"
] | null | null | null | ItemRenamer/main.cpp | nacitar/old-projects | e5af376f868124b9828196df1f55adb682969f3d | [
"MIT"
] | 6 | 2016-05-04T04:23:02.000Z | 2020-11-30T22:32:43.000Z | #include <string.h>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
#include <set>
#include <windows.h>
#include "../include/md5.h"
using namespace std;
std::string StrTrim(std::string str)
{
std::string::size_type posA = str.find_first_not_of(" \t\r\n");
if (posA != std::string::npos)
return str.substr(posA,str.find_last_not_of(" \t\r\n")-posA+1);
return "";
}
std::string GetAppDir(void)
{
char szName [ MAX_PATH+1 ];
GetModuleFileName(NULL,szName,MAX_PATH);
std::string strName = szName;
return strName.substr(0,strName.find_last_of("\\/")+1);
}
bool FileExists(std::string strFileName)
{
WIN32_FIND_DATA obj;
return (FindFirstFile(strFileName.c_str(),&obj) != INVALID_HANDLE_VALUE);
}
std::string GetConquerDir(void)
{
std::string strLine;
std::string strFile = GetAppDir()+"settings.txt";
std::string strDescription = "settings.txt should contain the path to Conquer.exe\r\ne.g:\r\nC:\\Program Files\\Conquer 2.0\\";
if (!FileExists(strFile))
{
cout << "ERROR: The file 'settings.txt' doesn't exist!" << endl << strDescription << endl;
return "";
}
std::ifstream ifs(strFile.c_str());
if (!ifs)
{
cout << "ERROR: Failed to open the file 'settings.txt' even though it exists!" << endl << strDescription << endl;
return "";
}
if (!getline(ifs,strLine))
{
cout << "ERROR: Couldn't read a line from 'settings.txt' even though it was opened successfully!" << endl << strDescription << endl;
return "";
}
ifs.close();
strLine = StrTrim(strLine);
if (strLine.empty())
{
cout << "The first line of 'settings.txt' is empty!" << endl << strDescription << endl;
return "";
}
if (strLine[strLine.size()-1] != '\\')
strLine += '\\';
return strLine;
}
//////////////////////////////////////////////////
void output(ostream&ofs,vector<string>&data)
{
vector<string>::iterator it;
for (it=data.begin();it != data.end();++it)
{
if (it != data.begin())
ofs << " ";
ofs << *it;
}
ofs << endl;
}
string gettype(string thetype)
{
if (thetype == "Plume") return "Plume";
if (thetype == "Headband") return "Headband";
if (thetype == "Warrior`sHelmet") return "Helmet";
if (thetype == "Warrior`sArmor") return "Armor";
if (thetype == "Shield") return "Shield";
if (thetype == "Trojan`sCoronet") return "Coro";
if (thetype == "Trojan`sArmor") return "Mail";
if (thetype == "Taoist`sCap") return "Cap";
if (thetype == "Taoist`sRobe") return "Robe";
if (thetype == "Taoist`sBag") return "Bag";
if (thetype == "Taoist`sBracelet") return "Brace";
if (thetype == "Archer`sCoat") return "Coat";
if (thetype == "Archer`sHat") return "Hat";
if (thetype == "Blade") return "Blade";
if (thetype == "Taoist`sBackSword") return "BackSword";
if (thetype == "Hook") return "Hook";
if (thetype == "Whip") return "Whip";
if (thetype == "Axe") return "Axe";
if (thetype == "Hammer") return "Hammer";
if (thetype == "Club") return "Club";
if (thetype == "Scepter") return "Scepter";
if (thetype == "Dagger") return "Dagger";
if (thetype == "Archer`sBow") return "Bow";
if (thetype == "Sword") return "Sword";
if (thetype == "Glaive") return "Glaive";
if (thetype == "PoleAxe") return "PoleAxe";
if (thetype == "Longhammer") return "LngHammer";
if (thetype == "Spear") return "Spear";
if (thetype == "Wand") return "Wand";
if (thetype == "Halbert") return "Halbert";
if (thetype == "Coat") return "Dress";
if (thetype == "Dress") return "Dress";
if (thetype == "Necklace") return "Necky";
if (thetype == "Ring") return "Ring";
if (thetype == "HeavyRing") return "HvyRing";
if (thetype == "Boots" || thetype == "Boot") return "Boots";
if (thetype == "Earring" || thetype == "Earrings") return "Earrings";
return "";
}
string getquality(string theid)
{
switch (theid[5])
{
case '0': return "[F]";
case '6': return "[R]";
case '7': return "[U]";
case '8': return "[E]";
case '9': return "[S]";
case '3': //n1
case '4': //n2
case '5': //n3
default: break;
}
return "";
}
void OutputError()
{
cout << "Invalid arguments." << endl << "You should pass the program parameters via a shortcut, the Rename <whatever>.bat files are examples" << endl << "Alternatively, you can just run one of the .bat files." << endl;
system("pause");
}
int main(int argc,char*argv[])
{
if (argc != 2)
{
OutputError();
return 1;
}
int rename = 0;
bool tokens = false;
if (argc == 2)
{
string param = argv[1];
if (param.empty() || param.length() > 3 || param[0] != '-')
{
OutputError();
return 1;
}
set<char> stInput;
int mode = 0;
for (int i=1;i<param.length();++i)
{
param[i] = tolower(param[i]);
if (stInput.find(param[i]) != stInput.end())
{
OutputError();
return 1;
}
if (param[i] != 'i' && param[i] != 't' && param[i]!= 'm')
{
OutputError();
return 1;
}
stInput.insert(param[i]);
switch(param[i])
{
case 'i': rename = 1; ++mode; break;
case 't': rename = 2; ++mode; break;
case 'm': tokens = true; break;
}
}
if (mode > 1)
{
OutputError();
return 1;
}
}
if (!rename && !tokens)
{
cout << "No operations to be performed." << endl;
system("pause");
return 0;
}
//BLARGH
string strConquerDir = GetConquerDir();
string strAppDir = GetAppDir();
string strConquerItemTypeFile = strConquerDir+"ini\\itemtype.dat";
string strItemTypeFile = strAppDir+"itemtype.dat";
string strItemTypeTempFile = strAppDir+"itemtype.tmp";
string strDecryptExe = strAppDir+"codecrypt.exe";
string strItemTypeHashFile = strAppDir+"itemtype.hash";
if (!FileExists(strDecryptExe))
{
cout << "Couldn't find codecrypt.exe" << endl << "Please make sure that it is located in the same folder as this executable." << endl << "Folder Path: " << strAppDir << endl;
system("pause");
return 0;
}
if (!FileExists(strConquerItemTypeFile))
{
cout << "Conquer's itemtype.dat is missing!" << endl << "Stop fucking with the files bitch!" << endl << "Full Path: " << strConquerItemTypeFile << endl;
system("pause");
return 0;
}
if (!CopyFile(strConquerItemTypeFile.c_str(),strItemTypeFile.c_str(),FALSE))
{
cout << "Couldn't copy conquer's itemtype.dat to the application folder." << endl << "Full Path: " << strItemTypeFile << endl;
system("pause");
return 0;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&si,0,sizeof(si));
memset(&pi,0,sizeof(pi));
si.cb = sizeof(si);
cout << "Decrypting itemtype.dat..." << endl;
if (!CreateProcess(strDecryptExe.c_str(),
const_cast<char*>((std::string("\"")+strDecryptExe+"\" 0 \""+strItemTypeFile+"\" \""+strItemTypeFile+"\"").c_str()),
NULL,NULL,FALSE,CREATE_DEFAULT_ERROR_MODE|CREATE_NO_WINDOW,NULL,
strAppDir.c_str(),
&si,&pi ))
{
cout << "Couldn't spawn the process for codecrypt.exe" << endl << "Full Path: " << strDecryptExe << endl;
system("pause");
return 0;
}
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
cout << "Applying changes..." << endl;
// Begin processing
ifstream ifs(strItemTypeFile.c_str());
ofstream ofs(strItemTypeTempFile.c_str());
string strLine, strTemp;
while (getline(ifs,strLine))
{
stringstream ss(strLine);
vector<string> vcLines;
while (ss >> strTemp)
vcLines.push_back(strTemp);
// Skip the first line (Amount=###)
if (vcLines.size() < 5 || strncmp(vcLines[0].c_str(),"Amount",6) == 0)
{
output(ofs,vcLines);
continue;
}
//special cases
bool write = false;
if (vcLines[0] == "721010") { vcLines[1] = "PeaceToken"; write = true; }
if (vcLines[0] == "721011") { vcLines[1] = "ChaosToken"; write = true; }
if (vcLines[0] == "721012") { vcLines[1] = "DesertedToken"; write = true; }
if (vcLines[0] == "721013") { vcLines[1] = "ProsperousToken"; write = true; }
if (vcLines[0] == "721014") { vcLines[1] = "DisturbedToken"; write = true; }
if (vcLines[0] == "721015") { vcLines[1] = "CalmedToken"; write = true; }
// if we already renamed it, or if there's no renaming to be done, output it.
if (write || !rename)
{
output(ofs,vcLines);
continue;
}
//other cases
string strPrefix = getquality(vcLines[0]);
string strPostfix = gettype(vcLines[vcLines.size()-2]);
if (strPostfix.size())
{
if (rename==1) //if we're renaming with prefix only
{
//add prefix if it's not there
if (strPrefix.size() && (vcLines[1].size() < strPrefix.size() || strncmp(vcLines[1].c_str(),strPrefix.c_str(),strPrefix.size()) != 0))
vcLines[1] = strPrefix + vcLines[1];
}
else
{
//rename by type
//Got the type, now for the name to be changed
vcLines[1] = strPrefix + strPostfix;
if (vcLines[4] != "0")
vcLines[1] = vcLines[1] + "L" + vcLines[4];
}
}
output(ofs,vcLines);
continue;
}
ifs.close();
ofs.close();
memset(&si,0,sizeof(si));
memset(&pi,0,sizeof(pi));
si.cb = sizeof(si);
cout << "Encrypting itemtype.dat..." << endl;
if (!CreateProcess(strDecryptExe.c_str(),
const_cast<char*>((std::string("\"")+strDecryptExe+"\" 1 \""+strItemTypeTempFile+"\" \""+strItemTypeFile+"\"").c_str()),
NULL,NULL,FALSE,CREATE_DEFAULT_ERROR_MODE|CREATE_NO_WINDOW,NULL,
strAppDir.c_str(),
&si,&pi ))
{
cout << "Couldn't spawn the process for codecrypt.exe" << endl << "Full Path: " << strDecryptExe << endl;
system("pause");
return 0;
}
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
DeleteFile(strItemTypeTempFile.c_str());
// Updating hash..
char*ptr = MD5File(strConquerItemTypeFile.c_str());
if (!ptr)
{
cout << "Error calculating the hash for conquer's 'itemtype.dat' file!" << endl;
system("pause");
return 0;
}
ofstream ofsHash(strItemTypeHashFile.c_str());
ofsHash << ptr;
ofsHash.close();
cout << "Items renamed successfully!" << endl;
system("pause");
return 0;
}
| 31.590643 | 220 | 0.578675 | [
"vector"
] |
8f70d7601110a30b04e87e76cc8adab98c9d8d07 | 1,650 | cpp | C++ | src/urdf_rviz_commander.cpp | mwswartwout/urdf_control | 1bdae927cbac1113f5d8f6eec3a20fdd35b84c9a | [
"MIT"
] | null | null | null | src/urdf_rviz_commander.cpp | mwswartwout/urdf_control | 1bdae927cbac1113f5d8f6eec3a20fdd35b84c9a | [
"MIT"
] | null | null | null | src/urdf_rviz_commander.cpp | mwswartwout/urdf_control | 1bdae927cbac1113f5d8f6eec3a20fdd35b84c9a | [
"MIT"
] | null | null | null | #include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <math.h>
#include <vector>
int main(int argc, char **argv) {
ros::init(argc, argv, "urdf_rviz_commander"); // minimal_commander node
ros::NodeHandle n;
ros::Publisher joint_publisher = n.advertise<sensor_msgs::JointState>("joint_states", 1); // publish to vel_cmd topic
ros::Rate naptime(10); // update @ 10hz
double pi = 3.14159; // value of pi
double t = 0; // current time in calculation
double dt = 0.01; // timestep for calculation
double sine1; // sine output for joint1
double sine2; // sine output for joint2
double amplitude1 = pi; // amplitude value for joint1
double frequency1 = 1; // frequency value for joint1
double amplitude2 = pi; // amplitude value for joint2
double frequency2 = 4; // frequency value for joint2
std::vector<double> position(2, 0);
std::vector<std::string> name;
std::vector<std::string>::iterator nameIt;
name.push_back("joint1");
name.push_back("joint2");
sensor_msgs::JointState output; // message wrapper for sine output
while (ros::ok()) {
sine1 = amplitude1 * sin(2*pi*frequency1*t); // Calculate sine1
sine2 = amplitude2 * sin(2*pi*frequency2*t); // Calculate sine2
output.header.stamp = ros::Time::now();
output.name = name;
position[0] = sine1; // Store sine value in proper message format
position[1] = sine2;
output.position = position;
joint_publisher.publish(output); // Publish value to vel_cmd topic
t += dt; // Increment t by timeset dt
naptime.sleep();
}
}
| 40.243902 | 121 | 0.652121 | [
"vector"
] |
8f7914041edef5bd4131d219368d59bb3a073483 | 1,195 | cpp | C++ | 1101-1200/1172-Dinner Plate Stacks/1172-Dinner Plate Stacks.cpp | jiadaizhao/LeetCode | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 1101-1200/1172-Dinner Plate Stacks/1172-Dinner Plate Stacks.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 1101-1200/1172-Dinner Plate Stacks/1172-Dinner Plate Stacks.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class DinnerPlates {
public:
DinnerPlates(int capacity) {
this->capacity = capacity;
}
void push(int val) {
if (stacks.empty()) {
stacks.insert(table.size());
}
table[*stacks.begin()].push_back(val);
if (table[*stacks.begin()].size() == capacity) {
stacks.erase(stacks.begin());
}
}
int pop() {
if (table.empty()) {
return -1;
}
else {
return popAtStack(table.rbegin()->first);
}
}
int popAtStack(int index) {
if (!table.count(index) || table[index].empty()) {
return -1;
}
int val = table[index].back();
table[index].pop_back();
stacks.insert(index);
if (table[index].empty()) {
table.erase(index);
}
return val;
}
private:
int capacity;
map<int, vector<int>> table;
set<int> stacks;
};
/**
* Your DinnerPlates object will be instantiated and called as such:
* DinnerPlates* obj = new DinnerPlates(capacity);
* obj->push(val);
* int param_2 = obj->pop();
* int param_3 = obj->popAtStack(index);
*/
| 22.54717 | 68 | 0.508787 | [
"object",
"vector"
] |
8f80cbb721ee8ca84639934181e1524275528717 | 5,737 | hpp | C++ | include/low-can/binding/application.hpp | redpesk-common/canbus-binding | 031ebb8657e66129936ba9079faa58e369f97de1 | [
"Apache-2.0"
] | null | null | null | include/low-can/binding/application.hpp | redpesk-common/canbus-binding | 031ebb8657e66129936ba9079faa58e369f97de1 | [
"Apache-2.0"
] | null | null | null | include/low-can/binding/application.hpp | redpesk-common/canbus-binding | 031ebb8657e66129936ba9079faa58e369f97de1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015, 2016 "IoT.bzh"
* Author "Romain Forlot" <romain.forlot@iot.bzh>
*
* 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.
*/
#pragma once
#include <map>
#include <vector>
#include <string>
#include <memory>
#include <low-can/can/can-bus.hpp>
#include <low-can/can/message-set.hpp>
#include <low-can/can/signals.hpp>
#include <low-can/diagnostic/diagnostic-manager.hpp>
#ifdef USE_FEATURE_J1939
#include <low-can/utils/socketcan-j1939/socketcan-j1939-data.hpp>
#include <low-can/utils/socketcan-j1939/socketcan-j1939-addressclaiming.hpp>
#endif
///
/// @brief Class represents a configuration attached to the binding.
///
/// It regroups all object instances from other classes
/// that will be used through the binding life. It receives a global vision
/// on which signals are implemented for that binding.
/// Here, only the definition of the class is given with predefined accessors
/// methods used in the binding.
///
/// It will be the reference point to needed objects.
///
class application_t
{
private:
can_bus_t can_bus_manager_; ///< instanciate the CAN bus manager. It's responsible of initializing the CAN bus devices.
diagnostic_manager_t diagnostic_manager_; ///< Diagnostic manager use to manage diagnostic message communication.
uint8_t active_message_set_ = 0; ///< Which is the active message set ? Default to 0.
std::vector<std::shared_ptr<message_set_t> > message_set_; ///< Vector holding all message set from JSON signals description file
std::map<std::string, std::shared_ptr<low_can_subscription_t> > can_devices_; ///< Map containing all independant opened CAN sockets, key is the socket int value.
json_object *preinit_ = nullptr; ///< Json object coming from config Json section holding the plugin and function name to execute as preinit
json_object *postinit_ = nullptr; ///< Json object coming from config Json section holding the plugin and function name to execute as postinit
#ifdef USE_FEATURE_J1939
std::shared_ptr<low_can_subscription_t> subscription_address_claiming_; ///< Subscription holding the socketcan J1939 which is in charge of handling the address claiming protocol
uint64_t default_j1939_ecu_ = 0x1234; ///< Default ECU j1939 name using noted using a little endianness ie: 0xC0509600227CC7AA
#endif
application_t(); ///< Private constructor with implementation generated by the AGL generator.
void set_parents(std::shared_ptr<message_set_t> new_message_set);
public:
static application_t& instance();
can_bus_t& get_can_bus_manager();
std::map<std::string, std::shared_ptr<low_can_subscription_t> >& get_can_devices();
diagnostic_manager_t& get_diagnostic_manager() ;
uint8_t get_active_message_set() const;
int add_message_set(std::shared_ptr<message_set_t> new_message_set);
std::vector<std::shared_ptr<message_set_t> > get_message_set();
vect_ptr_signal_t get_all_signals();
vect_ptr_diag_msg_t get_diagnostic_messages();
const std::vector<std::string>& get_signals_prefix() const;
vect_ptr_msg_def_t get_messages_definition();
std::vector<std::shared_ptr<message_definition_t>> get_messages_definition(uint32_t id);
uint32_t get_signal_id(diagnostic_message_t& sig) const;
uint32_t get_signal_id(signal_t& sig) const;
bool is_engine_on();
void set_active_message_set(uint8_t id);
json_object* get_preinit() const;
json_object* get_postinit() const;
void set_preinit(json_object *preinit);
void set_postinit(json_object *postinit);
#ifdef USE_FEATURE_J1939
std::shared_ptr<utils::socketcan_t> get_socket_address_claiming();
std::shared_ptr<low_can_subscription_t> get_subscription_address_claiming();
uint64_t get_default_j1939_ecu() const;
void set_default_j1939_ecu(std::string ecu_name);
void set_subscription_address_claiming(std::shared_ptr<low_can_subscription_t> new_subscription);
#endif
/*
/// TODO: implement this function as method into can_bus class
/// @brief Pre initialize actions made before CAN bus initialization
/// @param[in] bus A CanBus struct defining the bus's metadata
/// @param[in] writable Configure the controller in a writable mode. If false, it will be configured as "listen only" and will not allow writes or even CAN ACKs.
/// @param[in] buses An array of all CAN buses.
void pre_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
/// TODO: implement this function as method into can_bus class
/// @brief Post-initialize actions made after CAN bus initialization
/// @param[in] bus A CanBus struct defining the bus's metadata
/// @param[in] writable Configure the controller in a writable mode. If false, it will be configured as "listen only" and will not allow writes or even CAN ACKs.
/// @param[in] buses An array of all CAN buses.
void post_initialize(can_bus_dev_t* bus, bool writable, can_bus_dev_t* buses, const int busCount);
/// TODO: implement this function as method into can_bus class
/// @brief Check if the device is connected to an active CAN bus, i.e. it's received a message in the recent past.
/// @return true if a message was received on the CAN bus within CAN_ACTIVE_TIMEOUT_S seconds.
bool isBusActive(can_bus_dev_t* bus);
*/
};
| 44.472868 | 180 | 0.767997 | [
"object",
"vector"
] |
8f86bc646d18081da364740764f44e80f88d8a65 | 4,072 | cpp | C++ | src/testing/ApiPropertyTest.cpp | nebular-lab/LeapCxxFork | c09b6a7c353364a92040aaf8b8cd513fc2693a4a | [
"Apache-2.0"
] | 48 | 2018-08-05T07:48:16.000Z | 2021-12-28T15:59:08.000Z | src/testing/ApiPropertyTest.cpp | nebular-lab/LeapCxxFork | c09b6a7c353364a92040aaf8b8cd513fc2693a4a | [
"Apache-2.0"
] | 1 | 2019-11-22T08:56:42.000Z | 2019-11-22T08:56:42.000Z | src/testing/ApiPropertyTest.cpp | nebular-lab/LeapCxxFork | c09b6a7c353364a92040aaf8b8cd513fc2693a4a | [
"Apache-2.0"
] | 17 | 2018-09-14T09:18:33.000Z | 2022-03-20T04:32:53.000Z | #include "LeapC++.h"
#include <gtest/gtest.h>
TEST(ApiPropertyTest, ValidateVectorProperties) {
const float* f = nullptr;
f = Leap::Vector::right().toFloatPointer();
EXPECT_EQ(1, f[0]);
EXPECT_EQ(0, f[1]);
EXPECT_EQ(0, f[2]);
f = Leap::Vector::up().toFloatPointer();
EXPECT_EQ(0, f[0]);
EXPECT_EQ(1, f[1]);
EXPECT_EQ(0, f[2]);
f = Leap::Vector::backward().toFloatPointer();
EXPECT_EQ(0, f[0]);
EXPECT_EQ(0, f[1]);
EXPECT_EQ(1, f[2]);
EXPECT_EQ(Leap::Vector(1, 0, 0), Leap::Vector::xAxis());
EXPECT_EQ(Leap::Vector(0, 1, 0), Leap::Vector::yAxis());
EXPECT_EQ(Leap::Vector(0, 0, 1), Leap::Vector::zAxis());
EXPECT_EQ(Leap::Vector(0, 0, 0), Leap::Vector::zero());
}
TEST(ApiPropertyTest, ValidateMatrixProperties) {
Leap::Matrix identity = Leap::Matrix::identity();
EXPECT_EQ(Leap::Matrix::identity(), identity);
}
TEST(ApiPropertyTest, InvalidFrameTest) {
Leap::Controller controller;
Leap::Frame outOfRange = controller.frame(1000000);
Leap::Frame invalidFrame = Leap::Frame::invalid();
EXPECT_NE(invalidFrame, outOfRange);
EXPECT_FALSE(outOfRange.isValid());
EXPECT_EQ(-1, outOfRange.id());
EXPECT_EQ(0, outOfRange.hands().count());
EXPECT_EQ(0, outOfRange.fingers().count());
EXPECT_FALSE(outOfRange.finger(1).isValid());
EXPECT_FALSE(outOfRange.hand(1).isValid());
EXPECT_EQ(0, invalidFrame.images().count()) << "Invalid frames appear to have images attached";
}
TEST(ApiPropertyTest, InvalidFingerTest) {
Leap::Frame invalidFrame = Leap::Frame::invalid();
Leap::Finger badFinger1 = invalidFrame.finger(1);
Leap::Finger badFinger2 = Leap::Finger::invalid();
EXPECT_NE(badFinger1, badFinger2);
EXPECT_FALSE(badFinger2.isValid());
EXPECT_EQ(-1, badFinger2.id());
EXPECT_EQ(Leap::Finger::TYPE_THUMB, badFinger1.type());
}
TEST(ApiPropertyTest, InvalidBoneTest) {
Leap::Frame invalidFrame = Leap::Frame::invalid();
Leap::Bone badBone1 = invalidFrame.finger(1).bone(Leap::Bone::TYPE_METACARPAL);
Leap::Bone badBone2 = Leap::Finger::invalid().bone(Leap::Bone::TYPE_METACARPAL);
EXPECT_NE(badBone1, badBone2);
EXPECT_FALSE(badBone2.isValid());
EXPECT_EQ(Leap::Matrix::identity(), badBone2.basis());
}
TEST(ApiPropertyTest, InvalidHandTest) {
Leap::Frame invalidFrame = Leap::Frame::invalid();
Leap::Hand badHand1 = invalidFrame.hand(1);
Leap::Hand badHand2 = Leap::Hand::invalid();
EXPECT_NE(badHand1, badHand2);
EXPECT_FALSE(badHand2.isValid());
EXPECT_EQ(-1, badHand2.id());
EXPECT_EQ(Leap::Matrix::identity(), badHand2.basis());
EXPECT_EQ(Leap::Matrix::identity(), badHand1.basis());
EXPECT_EQ(0, badHand2.fingers().count());
EXPECT_EQ(Leap::Vector::zero(), badHand2.direction());
EXPECT_EQ(Leap::Vector::zero(), badHand2.palmNormal());
EXPECT_FALSE(badHand2.frame().isValid());
}
TEST(ApiPropertyTest, InvalidArmTest) {
Leap::Frame invalidFrame = Leap::Frame::invalid();
Leap::Arm badArm1 = invalidFrame.hand(1).arm();
Leap::Arm badArm2 = Leap::Arm::invalid();
EXPECT_NE(badArm1, badArm2);
EXPECT_FALSE(badArm2.isValid());
EXPECT_EQ(Leap::Matrix::identity(), badArm2.basis());
EXPECT_EQ(Leap::Matrix::identity(), badArm1.basis());
EXPECT_EQ(Leap::Vector::zero(), badArm2.center());
EXPECT_TRUE(badArm2.direction() == -Leap::Vector(0,0,1));
EXPECT_EQ(Leap::Vector::zero(), badArm2.elbowPosition());
EXPECT_EQ(Leap::Vector::zero(), badArm2.wristPosition());
}
TEST(ApiPropertyTest, InvalidImageTest) {
Leap::Image invalidImage = Leap::Image::invalid();
EXPECT_FALSE(invalidImage.isValid());
EXPECT_EQ(1, invalidImage.bytesPerPixel());
EXPECT_EQ(nullptr, invalidImage.data());
EXPECT_ANY_THROW(invalidImage.distortion());
EXPECT_EQ(Leap::Image::INFRARED, invalidImage.format());
EXPECT_EQ(0, invalidImage.height());
EXPECT_EQ(-1, invalidImage.id());
EXPECT_EQ(-1, invalidImage.sequenceId());
EXPECT_EQ(0, invalidImage.timestamp());
EXPECT_EQ(0, invalidImage.width());
}
TEST(ApiPropertyTest, TimestampTest) {
Leap::Controller controller;
const auto now = controller.now();
EXPECT_TRUE(now > 0);
}
| 33.933333 | 97 | 0.705305 | [
"vector"
] |
8f8afc9936443fe5a698ec746fbc8ad10a465e3c | 7,876 | cpp | C++ | GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/hardware/tests/hardwaretopology.cpp | berkhess/bioexcel-exascale-co-design-benchmarks | c32f811d41a93fb69e49b3e7374f6028e37970d2 | [
"MIT"
] | 1 | 2020-04-20T04:33:11.000Z | 2020-04-20T04:33:11.000Z | GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/hardware/tests/hardwaretopology.cpp | berkhess/bioexcel-exascale-co-design-benchmarks | c32f811d41a93fb69e49b3e7374f6028e37970d2 | [
"MIT"
] | 8 | 2019-07-10T15:18:21.000Z | 2019-07-31T13:38:09.000Z | GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/hardware/tests/hardwaretopology.cpp | berkhess/bioexcel-exascale-co-design-benchmarks | c32f811d41a93fb69e49b3e7374f6028e37970d2 | [
"MIT"
] | 3 | 2019-07-10T10:50:25.000Z | 2020-12-08T13:42:52.000Z | /*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2015,2016,2018, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS 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.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
* \brief
* Tests for gmx::HardwareTopology
*
* \author Erik Lindahl <erik.lindahl@gmail.com>
* \ingroup module_hardware
*/
#include "gmxpre.h"
#include "gromacs/hardware/hardwaretopology.h"
#include "config.h"
#include <algorithm>
#include <gtest/gtest.h>
namespace
{
// There is no way we can compare to any reference data since that
// depends on the architecture, but we can at least make sure that it
// works to execute the tests and that they are self-consistent
// Although it is not strictly an error, for the very basic execution tests
// we also report if we cannot extract the hardware topology on systems
// where we expect to be able to. Since this might happen to users, we
// provide a bit more information and ask them to mail us in this case.
TEST(HardwareTopologyTest, Execute)
{
// There is no way we can compare to any reference data since that
// depends on the architecture, but we can at least make sure that it
// works to execute the tests
gmx::HardwareTopology hwTop(gmx::HardwareTopology::detect());
// If we cannot even find the number of logical processors we want to flag it
EXPECT_GT(hwTop.supportLevel(), gmx::HardwareTopology::SupportLevel::None)
<< "Cannot determine number of processors. " << std::endl
<< "GROMACS might still work, but it will likely hurt your performance." << std::endl
<< "Please mail gmx-developers@gromacs.org so we can try to fix it.";
}
#if GMX_USE_HWLOC
TEST(HardwareTopologyTest, HwlocExecute)
{
#if defined(__linux__)
gmx::HardwareTopology hwTop(gmx::HardwareTopology::detect());
// On Linux with hwloc support we should be able to get at least basic information
EXPECT_GE(hwTop.supportLevel(), gmx::HardwareTopology::SupportLevel::Basic)
<< "Cannot determine basic hardware topology from hwloc. GROMACS will still\n" << std::endl
<< "work, but it might affect your performance for large nodes." << std::endl
<< "Please mail gmx-developers@gromacs.org so we can try to fix it.";
#endif
}
#endif
TEST(HardwareTopologyTest, ProcessorSelfconsistency)
{
gmx::HardwareTopology hwTop(gmx::HardwareTopology::detect());
if (hwTop.supportLevel() >= gmx::HardwareTopology::SupportLevel::Basic)
{
int socketsInMachine = hwTop.machine().sockets.size();
int coresPerSocket = hwTop.machine().sockets[0].cores.size();
int hwThreadsPerCore = hwTop.machine().sockets[0].cores[0].hwThreads.size();
// Check that logical processor information is reasonable
for (auto &l : hwTop.machine().logicalProcessors)
{
EXPECT_TRUE(l.socketRankInMachine >= 0 && l.socketRankInMachine < socketsInMachine);
EXPECT_TRUE(l.coreRankInSocket >= 0 && l.coreRankInSocket < coresPerSocket);
EXPECT_TRUE(l.hwThreadRankInCore >= 0 && l.hwThreadRankInCore < hwThreadsPerCore);
}
// Double-check that the tree is self-consistent with logical processor info
for (int s = 0; s < socketsInMachine; s++)
{
for (int c = 0; c < coresPerSocket; c++)
{
for (int t = 0; t < hwThreadsPerCore; t++)
{
int idx = hwTop.machine().sockets[s].cores[c].hwThreads[t].logicalProcessorId;
EXPECT_LT(idx, hwTop.machine().logicalProcessorCount);
EXPECT_EQ(hwTop.machine().logicalProcessors[idx].socketRankInMachine, s);
EXPECT_EQ(hwTop.machine().logicalProcessors[idx].coreRankInSocket, c) << "logical:" << idx;
EXPECT_EQ(hwTop.machine().logicalProcessors[idx].hwThreadRankInCore, t);
}
}
}
}
}
TEST(HardwareTopologyTest, NumaCacheSelfconsistency)
{
gmx::HardwareTopology hwTop(gmx::HardwareTopology::detect());
if (hwTop.supportLevel() >= gmx::HardwareTopology::SupportLevel::Full)
{
// Check that numa node id corresponds to rank
for (std::size_t i = 0; i < hwTop.machine().numa.nodes.size(); i++)
{
EXPECT_EQ(hwTop.machine().numa.nodes[i].id, i);
}
// Check that the sum of numa domains is the total processor count
int processorsinNumaNudes = 0;
for (auto &n : hwTop.machine().numa.nodes)
{
processorsinNumaNudes += n.logicalProcessorId.size();
}
EXPECT_EQ(processorsinNumaNudes, hwTop.machine().logicalProcessorCount);
// Check that every processor is in a numa domain (i.e., that they are unique)
std::vector<int> v(hwTop.machine().logicalProcessorCount);
for (auto &elem : v)
{
elem = 0;
}
for (auto &n : hwTop.machine().numa.nodes)
{
for (auto &idx : n.logicalProcessorId)
{
v[idx] = 1;
}
}
int uniqueProcessorsinNumaNudes = std::count(v.begin(), v.end(), 1);
EXPECT_EQ(uniqueProcessorsinNumaNudes, hwTop.machine().logicalProcessorCount);
// We must have some memory in a numa node
for (auto &n : hwTop.machine().numa.nodes)
{
EXPECT_GT(n.memory, 0);
}
// Check latency matrix size and contents
EXPECT_GT(hwTop.machine().numa.baseLatency, 0);
EXPECT_GT(hwTop.machine().numa.maxRelativeLatency, 0);
// Check number of rows matches # numa nodes
EXPECT_EQ(hwTop.machine().numa.relativeLatency.size(), hwTop.machine().numa.nodes.size());
for (auto &v2 : hwTop.machine().numa.relativeLatency)
{
// Check that size of each row matches # numa nodes
EXPECT_EQ(v2.size(), hwTop.machine().numa.nodes.size());
for (auto &latency : v2)
{
// Latency values should be positive
EXPECT_GT(latency, 0);
}
}
// Check cache. The hwloc cache detection is fragile and can report
// 0 for line size or associativity (=unknown), so we just check the size.
for (auto &c : hwTop.machine().caches)
{
EXPECT_GT(c.size, 0);
}
}
}
} // namespace
| 39.577889 | 111 | 0.657948 | [
"vector"
] |
8f8ed4a117e4d7e84e04abba9d1898abd27f2428 | 373 | cpp | C++ | 55 canJump.cpp | OliveStar/leetcodecpp | 4558d90cf5633adea9d9fd785fdd36a001442d67 | [
"MIT"
] | null | null | null | 55 canJump.cpp | OliveStar/leetcodecpp | 4558d90cf5633adea9d9fd785fdd36a001442d67 | [
"MIT"
] | null | null | null | 55 canJump.cpp | OliveStar/leetcodecpp | 4558d90cf5633adea9d9fd785fdd36a001442d67 | [
"MIT"
] | null | null | null | class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
int farthest = 0;
for(int i = 0; i < n-1; i++){
// 不断计算能跳到的最远距离
farthest = max(farthest, nums[i] + i);
// 可能碰到0,卡住跳不动了
if(farthest <= i)
return false;
}
return farthest >= n-1;
}
}; | 24.866667 | 50 | 0.442359 | [
"vector"
] |
8f95b715c0e02289ebdb58773f82ff2915b92de6 | 2,039 | cpp | C++ | src/node.cpp | raselashraf21/PentominoSolver | 52ff84de5302d6d8e07a530f4c13211e2f77d4e9 | [
"MIT"
] | null | null | null | src/node.cpp | raselashraf21/PentominoSolver | 52ff84de5302d6d8e07a530f4c13211e2f77d4e9 | [
"MIT"
] | null | null | null | src/node.cpp | raselashraf21/PentominoSolver | 52ff84de5302d6d8e07a530f4c13211e2f77d4e9 | [
"MIT"
] | null | null | null | /*
* node.cpp
*
* Created on: Dec 26, 2020
* Author: ashraf
*/
#include "node.h"
#include <vector>
using namespace std;
bool Node::operator==(const Node& node) const{
if(_left == node._left &&
_right == node._right &&
_up == node._up &&
_down == node._down &&
_head == node._head &&
_id == node._id &&
_row == node._row){
return true;
}else{
return false;
}
}
bool Node::operator!=(const Node& node) const{
return !(*this==node);
}
Node& Node::operator++(){
return *(this->_right);
}
Node* Node::operator++(int){
Node* temp = this;
++(*this);
return temp;
}
Node& Node::operator--(){
return *(this->_left);
}
Node* Node::operator--(int){
Node* temp = this;
--*this;
return temp;
}
Node* Node::begin(){
return _right;
}
Node* Node::end(){
return this;
}
Node* Node::rbegin(){
return _left;
}
Node* Node::rend(){
return this;
}
Node* Node::vbegin(){
return _down;
}
Node* Node::vend(){
return this;
}
Node* Node::rvbegin(){
return _up;
}
Node* Node::rvend(){
return this;
}
void Node::remove(){
_right->_left = _left;
_left->_right = _right;
}
void Node::cover(){
_up->_down = _down;
_down->_up = _up;
}
void Node::uncover(){
_up->_down = this;
_down->_up = this;
}
void Node::restore(){
_right->_left = this;
_left->_right = this;
}
void Node::insert_right(Node* node){
node->_left = this;
_right->_left = node;
node->_right = _right;
_right = node;
}
void Node::insert_down(Node* node){
node->_up = this;
_down->_up = node;
node->_down = _down;
_down = node;
}
Node* Node::right()const{
return _right;
}
Node* Node::down()const{
return _down;
}
Node* Node::left()const{
return _left;
}
Node* Node::up()const{
return _up;
}
vector<Node*> Node::rows(){
vector<Node*> rvec;
for(Node* itr=begin(); itr!= end();
itr=&itr->operator ++()){
rvec.push_back(itr);
}
return rvec;
}
vector<Node*> Node::reverse(){
vector<Node*> rvec;
for(Node::iterator itr = rbegin(); itr!=rend();
itr=itr->left()){
rvec.push_back(itr);
}
return rvec;
}
| 13.414474 | 48 | 0.611084 | [
"vector"
] |
8f9dc2f18a1819acededd3465c8268862182af91 | 753 | cpp | C++ | practice/1191.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | practice/1191.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | practice/1191.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | 2 | 2020-01-01T13:49:08.000Z | 2021-03-06T06:54:26.000Z | #include<iostream>
#include<vector>
#include<stack>
using namespace std;
int n;
vector<vector<int>> adj;
vector<int> path;
vector<int> indegree;
stack<int> stk;
int main(void) {
cin>>n;
adj.assign(n+1, vector<int>());
indegree.assign(n+1, 0);
// input
for(int i=1; i<=n; i++){
while(true){
int x;
cin>>x;
if(x==0) break;
adj[i].push_back(x);
indegree[x]++;
}
}
for(int i=1; i<=n; i++){
if(indegree[i]==0){
stk.push(i);
path.push_back(i);
}
}
while(stk.size()){
int top = stk.top();
stk.pop();
for(auto it:adj[top]){
if(indegree[it]>0){
indegree[it]--;
if(indegree[it]==0){
stk.push(it);
path.push_back(it);
}
}
}
}
for(auto it:path){
cout<<it<<" ";
}
cout<<endl;
}
| 13.446429 | 32 | 0.549801 | [
"vector"
] |
8fa22be5650b5fa8197bafc2da800ef2dbd7714b | 310 | cpp | C++ | chapter-9/9.34.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-9/9.34.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-9/9.34.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // infinite loop, always insert a copy at the front of the fitst encountered odd number.
#include <vector>
using std::vector;
int main()
{
vector<int> vi = {1, 2, 3, 4, 5};
auto iter = vi.begin();
while(iter != vi.end())
{
if(*iter % 2)
iter = vi.insert(iter, *iter);
++iter;
}
}
| 17.222222 | 88 | 0.577419 | [
"vector"
] |
8fa30bb0419ff0d2db89aca4b3b6dabd5d8a15c7 | 3,544 | cpp | C++ | data-manager/tests/server/dataManagerServer/session/Session.integ.cpp | Saafke/4dm | 68e235164afb1f127def35e9c15ca883ec1426d4 | [
"MIT"
] | 8 | 2021-03-16T06:48:57.000Z | 2021-11-30T09:34:09.000Z | data-manager/tests/server/dataManagerServer/session/Session.integ.cpp | Saafke/4dm | 68e235164afb1f127def35e9c15ca883ec1426d4 | [
"MIT"
] | null | null | null | data-manager/tests/server/dataManagerServer/session/Session.integ.cpp | Saafke/4dm | 68e235164afb1f127def35e9c15ca883ec1426d4 | [
"MIT"
] | 3 | 2021-05-02T15:38:17.000Z | 2021-07-07T09:19:48.000Z | /*
* Session.unit.cpp
*
* Created on: May 6, 2019
* Author: mbortolon
*/
#include "gtest/gtest.h"
#include "src/server/dataManagerServer/session/Session.hpp"
#include "src/common/dataManager/protocol/InitMessage.pb.h"
#include "src/common/dataManager/frameContainer/Frame.hpp"
#include "src/server/dataManagerServer/session/Client.hpp"
#include "opencv2/core.hpp"
#include "opencv2/imgcodecs.hpp"
#include "boost/filesystem.hpp"
#include <iostream>
#include <string>
#include <sstream>
#define ADDITIONAL_DATA "aaaaaaaaaa"
#define RESULT_IDENTIFIER "TEST_TEST"
#define PHONEID_1 "PHONE1"
#define PHONEID_2 "PHONE2"
dataManagerServer::session::Session* jpegDecoder;
dataManager::frameContainer::Frame* createFrame() {
cv::Mat decodedImage = cv::Mat::zeros(640, 480, CV_8UC3);
std::vector<uchar> encodedImage = std::vector<uchar>();
cv::imencode(".jpg", decodedImage, encodedImage);
decodedImage.release();
std::string* additionalData = new std::string(ADDITIONAL_DATA);
std::string* frameEncoded = new std::string(encodedImage.begin(), encodedImage.end());
encodedImage.clear();
// Image processing
dataManager::frameContainer::Frame* frame = new dataManager::frameContainer::Frame(0, frameEncoded, additionalData);
return frame;
}
TEST(Session, SessionElaborateAndSaveImage) {
// Image encoding
dataManagerServer::session::Session* session = new dataManagerServer::session::Session(0, RESULT_IDENTIFIER, 2);
std::string init_data = "";
dataManagerServer::session::Client* client1 = session->addClient(PHONEID_1, true, dataManager::protocol::InitMessage_ContentCodec::InitMessage_ContentCodec_MJPEG, init_data);
dataManagerServer::session::Client* client2 = session->addClient(PHONEID_2, true, dataManager::protocol::InitMessage_ContentCodec::InitMessage_ContentCodec_MJPEG, init_data);
client1->enqueueFrame(createFrame());
client2->enqueueFrame(createFrame());
session->closeSession(1);
std::ostringstream resultFolderStream;
resultFolderStream << "/tmp/uploadedImages/" << RESULT_IDENTIFIER << "/";
std::string resultFolder = resultFolderStream.str();
std::ostringstream phoneOneResultFolderStream;
phoneOneResultFolderStream << resultFolder << PHONEID_1 << "/";
std::string phoneOneResultFolder = phoneOneResultFolderStream.str();
std::ostringstream phoneTwoResultFolderStream;
phoneTwoResultFolderStream << resultFolder << PHONEID_2 << "/";
std::string phoneTwoResultFolder = phoneTwoResultFolderStream.str();
std::ostringstream imgOneResultFilepathStream;
imgOneResultFilepathStream << phoneOneResultFolder << "00000.jpg";
std::string imgOneResultFilepath = imgOneResultFilepathStream.str();
std::ostringstream imgTwoResultFilepathStream;
imgTwoResultFilepathStream << phoneTwoResultFolder << "00000.jpg";
std::string imgTwoResultFilepath = imgTwoResultFilepathStream.str();
std::ostringstream binOneResultFilepathStream;
binOneResultFilepathStream << phoneOneResultFolder << "00000.bin";
std::string binOneResultFilepath = binOneResultFilepathStream.str();
std::ostringstream binTwoResultFilepathStream;
binTwoResultFilepathStream << phoneTwoResultFolder << "00000.bin";
std::string binTwoResultFilepath = binTwoResultFilepathStream.str();
EXPECT_TRUE(boost::filesystem::exists(imgOneResultFilepath));
EXPECT_TRUE(boost::filesystem::exists(imgTwoResultFilepath));
EXPECT_TRUE(boost::filesystem::exists(binOneResultFilepath));
EXPECT_TRUE(boost::filesystem::exists(binTwoResultFilepath));
boost::filesystem::remove_all(resultFolder);
delete session;
}
| 34.407767 | 175 | 0.785835 | [
"vector"
] |
8fa7e15a871c447f8290b2a61fdf61b7dafac5a2 | 17,055 | cc | C++ | src/ros/eval_base.cc | raphaelchang/omni_slam_eval | 7df7d76c520c1325ac4f1a85f87b7af07d9628c3 | [
"MIT"
] | 7 | 2020-06-15T01:04:10.000Z | 2021-12-15T03:49:05.000Z | src/ros/eval_base.cc | raphaelchang/omni_slam_eval | 7df7d76c520c1325ac4f1a85f87b7af07d9628c3 | [
"MIT"
] | null | null | null | src/ros/eval_base.cc | raphaelchang/omni_slam_eval | 7df7d76c520c1325ac4f1a85f87b7af07d9628c3 | [
"MIT"
] | 4 | 2020-06-15T16:02:12.000Z | 2021-10-12T07:18:47.000Z | #include "eval_base.h"
#include <rosbag/bag.h>
#include <rosbag/view.h>
#include "camera/double_sphere.h"
#include "camera/unified.h"
#include "camera/perspective.h"
#include "util/tf_util.h"
#include "util/hdf_file.h"
#define USE_GROUND_TRUTH
using namespace Eigen;
namespace omni_slam
{
namespace ros
{
template <>
EvalBase<false>::EvalBase(const ::ros::NodeHandle &nh, const ::ros::NodeHandle &nh_private)
: nh_(nh), nhp_(nh_private), imageTransport_(nh)
{
std::string cameraModel;
nhp_.param("camera_model", cameraModel, std::string("double_sphere"));
nhp_.getParam("camera_parameters", cameraParams_);
nhp_.param("image_topic", imageTopic_, std::string("/camera/image_raw"));
nhp_.param("depth_image_topic", depthImageTopic_, std::string("/depth_camera/image_raw"));
nhp_.param("pose_topic", poseTopic_, std::string("/pose"));
nhp_.param("vignette", vignette_, 0.0);
nhp_.param("vignette_expansion", vignetteExpansion_, 0.01);
if (cameraModel == "double_sphere")
{
cameraModel_.reset(new camera::DoubleSphere<>(cameraParams_["fx"], cameraParams_["fy"], cameraParams_["cx"], cameraParams_["cy"], cameraParams_["chi"], cameraParams_["alpha"], vignette_));
}
else if (cameraModel == "unified")
{
cameraModel_.reset(new camera::Unified<>(cameraParams_["fx"], cameraParams_["fy"], cameraParams_["cx"], cameraParams_["cy"], cameraParams_["chi"], new camera::RadTan<>(cameraParams_["k1"], cameraParams_["k2"], cameraParams_["p1"], cameraParams_["p2"]), vignette_));
}
else if (cameraModel == "perspective")
{
cameraModel_.reset(new camera::Perspective<>(cameraParams_["fx"], cameraParams_["fy"], cameraParams_["cx"], cameraParams_["cy"]));
}
else
{
ROS_ERROR("Invalid camera model specified");
}
}
template <>
EvalBase<true>::EvalBase(const ::ros::NodeHandle &nh, const ::ros::NodeHandle &nh_private)
: nh_(nh), nhp_(nh_private), imageTransport_(nh)
{
std::string cameraModel;
std::map<std::string, double> stereoCameraParams;
nhp_.param("camera_model", cameraModel, std::string("double_sphere"));
nhp_.getParam("camera_parameters", cameraParams_);
nhp_.getParam("stereo_camera_parameters", stereoCameraParams);
nhp_.param("image_topic", imageTopic_, std::string("/camera/image_raw"));
nhp_.param("depth_image_topic", depthImageTopic_, std::string("/depth_camera/image_raw"));
nhp_.param("pose_topic", poseTopic_, std::string("/pose"));
nhp_.param("stereo_image_topic", stereoImageTopic_, std::string("/camera2/image_raw"));
std::vector<double> stereoT;
stereoT.reserve(3);
std::vector<double> stereoR;
stereoR.reserve(4);
nhp_.getParam("stereo_camera_parameters/tf_t", stereoT);
nhp_.getParam("stereo_camera_parameters/tf_r", stereoR);
Quaterniond q(stereoR[3], stereoR[0], stereoR[1], stereoR[2]);
Vector3d t(stereoT[0], stereoT[1], stereoT[2]);
stereoPose_ = util::TFUtil::QuaternionTranslationToPoseMatrix(q, t);
nhp_.param("vignette", vignette_, 0.0);
nhp_.param("vignette_expansion", vignetteExpansion_, 0.01);
if (cameraModel == "double_sphere")
{
cameraModel_.reset(new camera::DoubleSphere<>(cameraParams_["fx"], cameraParams_["fy"], cameraParams_["cx"], cameraParams_["cy"], cameraParams_["chi"], cameraParams_["alpha"], vignette_));
stereoCameraModel_.reset(new camera::DoubleSphere<>(cameraParams_["fx"], cameraParams_["fy"], cameraParams_["cx"], cameraParams_["cy"], cameraParams_["chi"], cameraParams_["alpha"], vignette_));
}
else if (cameraModel == "unified")
{
cameraModel_.reset(new camera::Unified<>(cameraParams_["fx"], cameraParams_["fy"], cameraParams_["cx"], cameraParams_["cy"], cameraParams_["chi"], new camera::RadTan<>(cameraParams_["k1"], cameraParams_["k2"], cameraParams_["p1"], cameraParams_["p2"]), vignette_));
stereoCameraModel_.reset(new camera::Unified<>(stereoCameraParams["fx"], stereoCameraParams["fy"], stereoCameraParams["cx"], stereoCameraParams["cy"], stereoCameraParams["chi"], new camera::RadTan<>(stereoCameraParams["k1"], stereoCameraParams["k2"], stereoCameraParams["p1"], stereoCameraParams["p2"]), vignette_));
}
else if (cameraModel == "perspective")
{
cameraModel_.reset(new camera::Perspective<>(cameraParams_["fx"], cameraParams_["fy"], cameraParams_["cx"], cameraParams_["cy"]));
stereoCameraModel_.reset(new camera::Perspective<>(stereoCameraParams["fx"], stereoCameraParams["fy"], stereoCameraParams["cx"], stereoCameraParams["cy"]));
}
else
{
ROS_ERROR("Invalid camera model specified");
}
}
template <>
void EvalBase<false>::InitSubscribers()
{
imageSubscriber_.subscribe(imageTransport_, imageTopic_, 3);
depthImageSubscriber_.subscribe(imageTransport_, depthImageTopic_, 3);
poseSubscriber_.subscribe(nh_, poseTopic_, 10);
sync_.reset(new message_filters::Synchronizer<MessageFilter>(MessageFilter(5), imageSubscriber_, depthImageSubscriber_, poseSubscriber_));
sync_->registerCallback(boost::bind(&EvalBase<false>::FrameCallback, this, _1, _2, _3));
}
template <>
void EvalBase<true>::InitSubscribers()
{
imageSubscriber_.subscribe(imageTransport_, imageTopic_, 3);
stereoImageSubscriber_.subscribe(imageTransport_, stereoImageTopic_, 3);
depthImageSubscriber_.subscribe(imageTransport_, depthImageTopic_, 3);
poseSubscriber_.subscribe(nh_, poseTopic_, 10);
sync_.reset(new message_filters::Synchronizer<MessageFilter>(MessageFilter(5), imageSubscriber_, stereoImageSubscriber_, depthImageSubscriber_, poseSubscriber_));
sync_->registerCallback(boost::bind(&EvalBase<true>::FrameCallback, this, _1, _2, _3, _4));
}
template <bool Stereo>
void EvalBase<Stereo>::InitPublishers()
{
}
template <bool Stereo>
void EvalBase<Stereo>::FrameCallback(const sensor_msgs::ImageConstPtr &image, const sensor_msgs::ImageConstPtr &depth_image, const geometry_msgs::PoseStamped::ConstPtr &pose)
{
cv_bridge::CvImagePtr cvImage;
cv_bridge::CvImagePtr cvDepthImage;
try
{
cvImage = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);
if (depth_image != nullptr)
{
cvDepthImage = cv_bridge::toCvCopy(depth_image, sensor_msgs::image_encodings::TYPE_16UC1);
}
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
Quaterniond q(pose->pose.orientation.w, pose->pose.orientation.x, pose->pose.orientation.y, pose->pose.orientation.z);
Vector3d t(pose->pose.position.x, pose->pose.position.y, pose->pose.position.z);
Matrix<double, 3, 4> posemat = util::TFUtil::QuaternionTranslationToPoseMatrix(q, t);
if (vignette_ > 0)
{
cv::Mat mask = cv::Mat::zeros(cvImage->image.size(), CV_32FC3);
cv::circle(mask, cv::Point2f(cvImage->image.cols / 2 - 0.5, cvImage->image.rows / 2 - 0.5), std::max(cvImage->image.rows, cvImage->image.cols) * (vignette_ + vignetteExpansion_) / 2, cv::Scalar::all(1), -1);
cv::GaussianBlur(mask, mask, cv::Size(51, 51), 0);
cv::multiply(cvImage->image, mask, cvImage->image, 1, CV_8UC3);
}
cv::Mat monoImg;
cv::cvtColor(cvImage->image, monoImg, CV_BGR2GRAY);
cv::Mat depthFloatImg;
if (depth_image != nullptr)
{
cvDepthImage->image.convertTo(depthFloatImg, CV_64FC1, 500. / 65535);
}
#ifdef USE_GROUND_TRUTH
if (depth_image != nullptr)
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, depthFloatImg, posemat, pose->header.stamp.toSec(), *cameraModel_)));
}
else
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, posemat, pose->header.stamp.toSec(), *cameraModel_)));
}
#else
if (first_)
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, posemat, pose->header.stamp.toSec(), *cameraModel_)));
first_ = false;
}
else
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, pose->header.stamp.toSec(), *cameraModel_)));
}
#endif
Visualize(cvImage);
}
template <bool Stereo>
void EvalBase<Stereo>::FrameCallback(const sensor_msgs::ImageConstPtr &image, const sensor_msgs::ImageConstPtr &stereo_image, const sensor_msgs::ImageConstPtr &depth_image, const geometry_msgs::PoseStamped::ConstPtr &pose)
{
cv_bridge::CvImagePtr cvImage;
cv_bridge::CvImagePtr cvStereoImage;
cv_bridge::CvImagePtr cvDepthImage;
try
{
cvImage = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);
cvStereoImage = cv_bridge::toCvCopy(stereo_image, sensor_msgs::image_encodings::BGR8);
if (depth_image != nullptr)
{
cvDepthImage = cv_bridge::toCvCopy(depth_image, sensor_msgs::image_encodings::TYPE_16UC1);
}
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
Quaterniond q(pose->pose.orientation.w, pose->pose.orientation.x, pose->pose.orientation.y, pose->pose.orientation.z);
Vector3d t(pose->pose.position.x, pose->pose.position.y, pose->pose.position.z);
Matrix<double, 3, 4> posemat = util::TFUtil::QuaternionTranslationToPoseMatrix(q, t);
if (vignette_ > 0)
{
cv::Mat mask = cv::Mat::zeros(cvImage->image.size(), CV_32FC3);
cv::circle(mask, cv::Point2f(cvImage->image.cols / 2 - 0.5, cvImage->image.rows / 2 - 0.5), std::max(cvImage->image.rows, cvImage->image.cols) * (vignette_ + vignetteExpansion_) / 2, cv::Scalar::all(1), -1);
cv::GaussianBlur(mask, mask, cv::Size(51, 51), 0);
cv::multiply(cvImage->image, mask, cvImage->image, 1, CV_8UC3);
cv::multiply(cvStereoImage->image, mask, cvStereoImage->image, 1, CV_8UC3);
}
cv::Mat monoImg;
cv::cvtColor(cvImage->image, monoImg, CV_BGR2GRAY);
cv::Mat monoImg2;
cv::cvtColor(cvStereoImage->image, monoImg2, CV_BGR2GRAY);
cv::equalizeHist(monoImg, monoImg);
cv::equalizeHist(monoImg2, monoImg2);
cv::Mat depthFloatImg;
if (depth_image != nullptr)
{
cvDepthImage->image.convertTo(depthFloatImg, CV_64FC1, 500. / 65535);
}
#ifdef USE_GROUND_TRUTH
if (depth_image != nullptr)
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, monoImg2, depthFloatImg, posemat, stereoPose_, pose->header.stamp.toSec(), *cameraModel_, *stereoCameraModel_)));
}
else
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, monoImg2, posemat, stereoPose_, pose->header.stamp.toSec(), *cameraModel_, *stereoCameraModel_)));
}
#else
if (first_)
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, monoImg2, posemat, stereoPose_, pose->header.stamp.toSec(), *cameraModel_, *stereoCameraModel_)));
first_ = false;
}
else
{
ProcessFrame(std::unique_ptr<data::Frame>(new data::Frame(monoImg, monoImg2, stereoPose_, pose->header.stamp.toSec(), *cameraModel_, *stereoCameraModel_)));
}
#endif
Visualize(cvImage, cvStereoImage);
}
template <bool Stereo>
void EvalBase<Stereo>::Finish()
{
}
template <bool Stereo>
bool EvalBase<Stereo>::GetAttributes(std::map<std::string, std::string> &attributes)
{
return false;
}
template <bool Stereo>
bool EvalBase<Stereo>::GetAttributes(std::map<std::string, double> &attributes)
{
return false;
}
template <bool Stereo>
void EvalBase<Stereo>::Visualize(cv_bridge::CvImagePtr &base_img)
{
}
template <bool Stereo>
void EvalBase<Stereo>::Visualize(cv_bridge::CvImagePtr &base_img, cv_bridge::CvImagePtr &base_stereo_img)
{
Visualize(base_img);
}
template <bool Stereo>
void EvalBase<Stereo>::Run()
{
std::string bagFile;
std::string resultsFile;
nhp_.param("bag_file", bagFile, std::string(""));
nhp_.param("results_file", resultsFile, std::string(""));
if (bagFile == "")
{
InitSubscribers();
InitPublishers();
::ros::spin();
ROS_INFO("Saving results...");
std::map<std::string, std::vector<std::vector<double>>> results;
GetResultsData(results);
omni_slam::util::HDFFile out(resultsFile);
for (auto &dataset : results)
{
out.AddDataset(dataset.first, dataset.second);
}
}
else
{
InitPublishers();
int rate;
nhp_.param("rate", rate, 1);
ROS_INFO("Processing bag...");
rosbag::Bag bag;
bag.open(bagFile);
sensor_msgs::ImageConstPtr imageMsg = nullptr;
sensor_msgs::ImageConstPtr stereoMsg = nullptr;
sensor_msgs::ImageConstPtr depthMsg = nullptr;
geometry_msgs::PoseStamped::ConstPtr poseMsg = nullptr;
nav_msgs::Odometry::ConstPtr odomMsg = nullptr;
geometry_msgs::TransformStamped::ConstPtr tfMsg = nullptr;
int runNext = 0;
int numMsgs = depthImageTopic_ == "" ? 1 : 2;
int skip = 0;
int finished = true;
for (rosbag::MessageInstance const m : rosbag::View(bag))
{
if (!::ros::ok())
{
finished = false;
break;
}
if (depthImageTopic_ != "" && m.getTopic() == depthImageTopic_)
{
depthMsg = m.instantiate<sensor_msgs::Image>();
runNext++;
}
else if (Stereo && m.getTopic() == stereoImageTopic_)
{
stereoMsg = m.instantiate<sensor_msgs::Image>();
runNext++;
}
else if (m.getTopic() == imageTopic_)
{
imageMsg = m.instantiate<sensor_msgs::Image>();
runNext++;
}
else if (runNext >= (Stereo ? numMsgs + 1 : numMsgs) && m.getTopic() == poseTopic_)
{
poseMsg = m.instantiate<geometry_msgs::PoseStamped>();
geometry_msgs::PoseStamped::Ptr pose(new geometry_msgs::PoseStamped());
if (poseMsg == nullptr)
{
odomMsg = m.instantiate<nav_msgs::Odometry>();
if (odomMsg == nullptr)
{
tfMsg = m.instantiate<geometry_msgs::TransformStamped>();
if (tfMsg != nullptr)
{
pose->header = tfMsg->header;
pose->pose.position.x = -tfMsg->transform.translation.y;
pose->pose.position.y = tfMsg->transform.translation.x;
pose->pose.position.z = tfMsg->transform.translation.z;
pose->pose.orientation = tfMsg->transform.rotation;
pose->pose.orientation.x = -tfMsg->transform.rotation.y;
pose->pose.orientation.y = tfMsg->transform.rotation.x;
}
}
else
{
pose->pose = odomMsg->pose.pose;
pose->header = odomMsg->header;
}
}
else
{
*pose = *poseMsg;
}
runNext = 0;
if (skip == 0)
{
if (imageMsg != nullptr && (depthImageTopic_ == "" || depthMsg != nullptr) && (poseMsg != nullptr || odomMsg != nullptr || tfMsg != nullptr) && (!Stereo || stereoMsg != nullptr))
{
if (Stereo)
{
FrameCallback(imageMsg, stereoMsg, depthMsg, pose);
}
else
{
FrameCallback(imageMsg, depthMsg, pose);
}
}
}
skip++;
if (skip >= rate)
{
skip = 0;
}
}
}
if (finished)
{
Finish();
}
ROS_INFO("Saving results...");
std::map<std::string, std::vector<std::vector<double>>> results;
GetResultsData(results);
omni_slam::util::HDFFile out(resultsFile);
for (auto &dataset : results)
{
out.AddDataset(dataset.first, dataset.second);
}
out.AddAttribute("bag_file", bagFile);
out.AddAttribute("rate", rate);
out.AddAttributes(cameraParams_);
out.AddAttribute("fov", cameraModel_->GetFOV() * 180 / M_PI);
std::map<std::string, double> numAttr;
if (GetAttributes(numAttr))
{
out.AddAttributes(numAttr);
}
std::map<std::string, std::string> strAttr;
if (GetAttributes(strAttr))
{
out.AddAttributes(strAttr);
}
}
}
template class EvalBase<true>;
template class EvalBase<false>;
}
}
| 39.662791 | 324 | 0.621519 | [
"vector",
"model",
"transform"
] |
8fb19eb30bda663a7a24e3b273647c8fcc42190b | 5,530 | cpp | C++ | medgpc/src/kernel/c_kernel.cpp | bee-hive/MedGP | 596a24ca519900507cce42cb4e2061319cef801e | [
"BSD-3-Clause"
] | 25 | 2018-03-18T18:09:03.000Z | 2022-02-24T07:47:33.000Z | medgpc/src/kernel/c_kernel.cpp | bee-hive/MedGP | 596a24ca519900507cce42cb4e2061319cef801e | [
"BSD-3-Clause"
] | 3 | 2021-04-12T16:11:00.000Z | 2021-04-12T16:26:17.000Z | medgpc/src/kernel/c_kernel.cpp | bee-hive/MedGP | 596a24ca519900507cce42cb4e2061319cef801e | [
"BSD-3-Clause"
] | 4 | 2019-04-27T23:18:26.000Z | 2021-12-03T20:19:09.000Z | /*
-------------------------------------------------------------------------
This is the function file for top kernel class.
All other kernels can inherit these functions.
-------------------------------------------------------------------------
*/
#include <iostream>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <mkl.h>
#include <omp.h>
#include "kernel/c_kernel.h"
#include "util/global_settings.h"
using namespace std;
c_kernel::c_kernel(){
kernel_name = "c_kernel";
kernel_hyp_num = 0;
kernel_grad_thread = -1;
}
c_kernel::c_kernel(const vector<int> &input_param){
kernel_name = "c_kernel";
kernel_param = input_param;
kernel_grad_thread = -1;
}
c_kernel::c_kernel(const vector<int> &input_param, const vector<double> &input_hyp){
kernel_name = "c_kernel";
kernel_param = input_param;
kernel_hyp = input_hyp;
kernel_grad_thread = -1;
}
void c_kernel::compute_squared_dist(
const vector<float> &x,
const vector<float> &x2,
float *&dist_matrix
){
int dim1, dim2;
int i, j;
dim1 = (x.size());
dim2 = (x2.size());
// use vectorization + openmp
// omp_set_num_threads(GLOBAL_OMP_KERNEL_THREAD_NUM);
#pragma omp parallel for simd private(i, j) firstprivate(dim1, dim2)
for(int index = 0; index < (dim1*dim2); index++){
i = floor(index/dim2);
j = (index % dim2);
dist_matrix[index] = pow((x[i] - x2[j]), 2.0);
}
}
void c_kernel::compute_abs_dist(
const vector<float> &x,
const vector<float> &x2,
float *&dist_matrix
){
int dim1, dim2;
int i, j;
dim1 = (x.size());
dim2 = (x2.size());
// #pragma omp parallel for private(i, j) firstprivate(dim1, dim2)
for(i = 0; i < dim1; i++){
for(j = 0; j < dim2; j++){
dist_matrix[ i * dim2 + j ] = fabs(x[i] - x2[j]);
}
}
}
void c_kernel::compute_sin_dist(
double period,
const vector<float> &x,
const vector<float> &x2,
float *&dist_matrix
){
int dim1, dim2;
int i, j;
dim1 = (x.size());
dim2 = (x2.size());
// #pragma omp parallel for private(i, j) firstprivate(period, dim1, dim2)
for(i = 0; i < dim1; i++){
for(j = 0; j < dim2; j++){
float temp_dist;
temp_dist = fabs((x[i] - x2[j])/period);
dist_matrix[ i * dim2 + j ] = sin(PI*temp_dist);
}
}
}
void c_kernel::compute_scale_abs_dist(
double lengthscale,
const vector<float> &x,
const vector<float> &x2,
float *&dist_matrix
){
int dim1, dim2;
int i, j;
dim1 = (x.size());
dim2 = (x2.size());
// #pragma omp parallel for private(i, j) firstprivate(dim1, dim2)
for(i = 0; i < dim1; i++){
for(j = 0; j < dim2; j++){
dist_matrix[ i * dim2 + j ] = fabs(x[i] - x2[j])/lengthscale;
}
}
}
void c_kernel::compute_scale_squared_dist(
double lengthscale,
const vector<float> &x,
const vector<float> &x2,
float *&dist_matrix
){
int dim1, dim2;
int i, j;
dim1 = (x.size());
dim2 = (x2.size());
#pragma omp parallel for simd private(i, j) firstprivate(lengthscale, dim1, dim2)
for(int index = 0; index < (dim1*dim2); index++){
i = floor(index/dim2);
j = (index % dim2);
float temp_dist = (x[i] - x2[j])/lengthscale;
dist_matrix[index] = pow(temp_dist, 2.0);
}
}
void c_kernel::compute_meta_map(
int dim,
const vector<double> &coregional_matrix,
const vector<int> &meta,
const vector<int> &meta2,
vector<float> &map_matrix
){
int n1, n2;
n1 = int(meta.size());
n2 = int(meta2.size());
#pragma omp parallel for firstprivate(n1, n2, dim)
for(int index = 0; index < (n1*n2); index++){
int i = floor(index/n2);
int j = (index % n2);
int k = meta[i]*dim + meta2[j];
map_matrix[index] = (float)(coregional_matrix[k]);
}
}
void c_kernel::print_kernel(){
cout << "current kernel object: " << kernel_name
<< "; # of hyperparameters: " << kernel_hyp_num << endl;
}
void c_kernel::set_kernel_grad_thread(int input_thread_num){
kernel_grad_thread = input_thread_num;
}
int c_kernel::get_kernel_grad_thread(){
return kernel_grad_thread;
}
int c_kernel::get_kernel_hyp_num(){
return kernel_hyp_num;
}
vector<int> c_kernel::get_kernel_param(){
vector<int> kernel_param_copy(kernel_param);
return kernel_param_copy;
}
vector<double> c_kernel::get_kernel_hyp(){
vector<double> kernel_hyp_copy(kernel_hyp);
return kernel_hyp_copy;
}
| 28.95288 | 85 | 0.488065 | [
"object",
"vector"
] |
8fb20331612d2343abadcb7478f0ffa2926c81f6 | 1,626 | hh | C++ | src/iccf.hh | mmaietta/iconv-corefoundation | 61009c01bbf0a3967dae0809d321cab9865e5117 | [
"MIT"
] | null | null | null | src/iccf.hh | mmaietta/iconv-corefoundation | 61009c01bbf0a3967dae0809d321cab9865e5117 | [
"MIT"
] | 2 | 2021-03-04T07:48:44.000Z | 2021-05-13T20:38:46.000Z | src/iccf.hh | mmaietta/iconv-corefoundation | 61009c01bbf0a3967dae0809d321cab9865e5117 | [
"MIT"
] | 1 | 2021-03-05T16:53:16.000Z | 2021-03-05T16:53:16.000Z | #pragma once
#include "napi.hh"
#include "StringEncoding.hh"
struct Iccf {
const Napi::FunctionReference InvalidEncodedTextError, NotRepresentableError, UnrecognizedEncodingError, _newFormattedTypeError;
const StringEncodingClass StringEncoding;
Iccf(Napi::Object imports, Napi::Object exports);
inline Napi::Error newInvalidEncodedTextError(const Napi::Env env, Napi::Value text, Napi::Object encoding) const {
return InvalidEncodedTextError.New({ text, encoding }).As<Napi::Error>();
}
inline Napi::Error newNotRepresentableError(const Napi::Env env, Napi::Value text, Napi::Object encoding) const {
return NotRepresentableError.New({ text, encoding }).As<Napi::Error>();
}
enum class EncodingSpecifierKind : uint32_t {
CFStringEncoding = 0,
IANACharSetName,
WindowsCodepage,
NSStringEncoding
};
inline Napi::Error newUnrecognizedEncodingErrorWithCustomSpecifierKind(const Napi::Env env, Napi::Value encodingSpecifier, const char *specifierKind) const {
return UnrecognizedEncodingError.New({ encodingSpecifier, Napi::String::New(env, specifierKind) }).As<Napi::Error>();
}
inline Napi::Error newUnrecognizedEncodingError(const Napi::Env env, Napi::Value encodingSpecifier, EncodingSpecifierKind specifierKind) const {
return UnrecognizedEncodingError.New({ encodingSpecifier, Napi::Number::New(env, static_cast<uint32_t>(specifierKind)) }).As<Napi::Error>();
}
inline Napi::TypeError newFormattedTypeError(const Napi::Env env, const char *expected, Napi::Value actual) const {
return _newFormattedTypeError({ Napi::String::New(env, expected), actual }).As<Napi::TypeError>();
}
};
| 41.692308 | 158 | 0.776753 | [
"object"
] |
8fb4c6f02e1571506a25fd86fd92540053ef91e0 | 35,104 | cpp | C++ | src/Plugins/JavaScript/MathBindings/OBBBindings.cpp | realXtend/tundra-urho3d | 436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8 | [
"Apache-2.0"
] | 13 | 2015-02-25T02:42:38.000Z | 2018-07-31T11:40:56.000Z | src/Plugins/JavaScript/MathBindings/OBBBindings.cpp | realXtend/tundra-urho3d | 436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8 | [
"Apache-2.0"
] | 8 | 2015-02-12T22:27:05.000Z | 2017-01-21T15:59:17.000Z | src/Plugins/JavaScript/MathBindings/OBBBindings.cpp | realXtend/tundra-urho3d | 436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8 | [
"Apache-2.0"
] | 12 | 2015-03-25T21:10:50.000Z | 2019-04-10T09:03:10.000Z | // For conditions of distribution and use, see copyright notice in LICENSE
// This file has been autogenerated with BindingsGenerator
#include "StableHeaders.h"
#include "CoreTypes.h"
#include "JavaScriptInstance.h"
#include "LoggingFunctions.h"
#include "Geometry/OBB.h"
#ifdef _MSC_VER
#pragma warning(disable: 4800)
#endif
#include "Math/float3.h"
#include "Geometry/AABB.h"
#include "Math/float3x3.h"
#include "Math/float3x4.h"
#include "Math/float4x4.h"
#include "Math/Quat.h"
#include "Geometry/Sphere.h"
#include "Geometry/LineSegment.h"
#include "Geometry/Plane.h"
#include "Algorithm/Random/LCG.h"
#include "Geometry/Triangle.h"
#include "Geometry/Frustum.h"
#include "Geometry/Ray.h"
#include "Geometry/Line.h"
#include "Geometry/Capsule.h"
using namespace std;
namespace JSBindings
{
static const char* float3_ID = "float3";
static const char* AABB_ID = "AABB";
static const char* float3x3_ID = "float3x3";
static const char* float3x4_ID = "float3x4";
static const char* float4x4_ID = "float4x4";
static const char* Quat_ID = "Quat";
static const char* Sphere_ID = "Sphere";
static const char* LineSegment_ID = "LineSegment";
static const char* Plane_ID = "Plane";
static const char* LCG_ID = "LCG";
static const char* Triangle_ID = "Triangle";
static const char* Frustum_ID = "Frustum";
static const char* Ray_ID = "Ray";
static const char* Line_ID = "Line";
static const char* Capsule_ID = "Capsule";
static duk_ret_t float3_Finalizer(duk_context* ctx)
{
FinalizeValueObject<float3>(ctx, float3_ID);
return 0;
}
static duk_ret_t AABB_Finalizer(duk_context* ctx)
{
FinalizeValueObject<AABB>(ctx, AABB_ID);
return 0;
}
static duk_ret_t Sphere_Finalizer(duk_context* ctx)
{
FinalizeValueObject<Sphere>(ctx, Sphere_ID);
return 0;
}
static duk_ret_t float3x4_Finalizer(duk_context* ctx)
{
FinalizeValueObject<float3x4>(ctx, float3x4_ID);
return 0;
}
static duk_ret_t LineSegment_Finalizer(duk_context* ctx)
{
FinalizeValueObject<LineSegment>(ctx, LineSegment_ID);
return 0;
}
static duk_ret_t Plane_Finalizer(duk_context* ctx)
{
FinalizeValueObject<Plane>(ctx, Plane_ID);
return 0;
}
static const char* OBB_ID = "OBB";
static duk_ret_t OBB_Finalizer(duk_context* ctx)
{
FinalizeValueObject<OBB>(ctx, OBB_ID);
return 0;
}
static duk_ret_t OBB_Set_pos(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& pos = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
thisObj->pos = pos;
return 0;
}
static duk_ret_t OBB_Get_pos(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
PushValueObject<float3>(ctx, &thisObj->pos, float3_ID, nullptr, true);
return 1;
}
static duk_ret_t OBB_Set_r(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& r = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
thisObj->r = r;
return 0;
}
static duk_ret_t OBB_Get_r(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
PushValueObject<float3>(ctx, &thisObj->r, float3_ID, nullptr, true);
return 1;
}
static duk_ret_t OBB_Ctor(duk_context* ctx)
{
OBB* newObj = new OBB();
PushConstructorResult<OBB>(ctx, newObj, OBB_ID, OBB_Finalizer);
return 0;
}
static duk_ret_t OBB_Ctor_float3_float3_float3_float3_float3(duk_context* ctx)
{
float3& pos = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float3& r = *GetCheckedValueObject<float3>(ctx, 1, float3_ID);
float3& axis0 = *GetCheckedValueObject<float3>(ctx, 2, float3_ID);
float3& axis1 = *GetCheckedValueObject<float3>(ctx, 3, float3_ID);
float3& axis2 = *GetCheckedValueObject<float3>(ctx, 4, float3_ID);
OBB* newObj = new OBB(pos, r, axis0, axis1, axis2);
PushConstructorResult<OBB>(ctx, newObj, OBB_ID, OBB_Finalizer);
return 0;
}
static duk_ret_t OBB_Ctor_AABB(duk_context* ctx)
{
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
OBB* newObj = new OBB(aabb);
PushConstructorResult<OBB>(ctx, newObj, OBB_ID, OBB_Finalizer);
return 0;
}
static duk_ret_t OBB_SetNegativeInfinity(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
thisObj->SetNegativeInfinity();
return 0;
}
static duk_ret_t OBB_SetFrom_AABB(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
thisObj->SetFrom(aabb);
return 0;
}
static duk_ret_t OBB_SetFrom_AABB_float3x3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
float3x3& transform = *GetCheckedValueObject<float3x3>(ctx, 1, float3x3_ID);
thisObj->SetFrom(aabb, transform);
return 0;
}
static duk_ret_t OBB_SetFrom_AABB_float3x4(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
float3x4& transform = *GetCheckedValueObject<float3x4>(ctx, 1, float3x4_ID);
thisObj->SetFrom(aabb, transform);
return 0;
}
static duk_ret_t OBB_SetFrom_AABB_float4x4(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
float4x4& transform = *GetCheckedValueObject<float4x4>(ctx, 1, float4x4_ID);
thisObj->SetFrom(aabb, transform);
return 0;
}
static duk_ret_t OBB_SetFrom_AABB_Quat(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
Quat& transform = *GetCheckedValueObject<Quat>(ctx, 1, Quat_ID);
thisObj->SetFrom(aabb, transform);
return 0;
}
static duk_ret_t OBB_SetFrom_Sphere(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Sphere& sphere = *GetCheckedValueObject<Sphere>(ctx, 0, Sphere_ID);
thisObj->SetFrom(sphere);
return 0;
}
static duk_ret_t OBB_MinimalEnclosingAABB(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB ret = thisObj->MinimalEnclosingAABB();
PushValueObjectCopy<AABB>(ctx, ret, AABB_ID, AABB_Finalizer);
return 1;
}
static duk_ret_t OBB_MinimalEnclosingSphere(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Sphere ret = thisObj->MinimalEnclosingSphere();
PushValueObjectCopy<Sphere>(ctx, ret, Sphere_ID, Sphere_Finalizer);
return 1;
}
static duk_ret_t OBB_MaximalContainedSphere(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Sphere ret = thisObj->MaximalContainedSphere();
PushValueObjectCopy<Sphere>(ctx, ret, Sphere_ID, Sphere_Finalizer);
return 1;
}
static duk_ret_t OBB_Size(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3 ret = thisObj->Size();
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_HalfSize(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3 ret = thisObj->HalfSize();
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_Diagonal(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3 ret = thisObj->Diagonal();
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_HalfDiagonal(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3 ret = thisObj->HalfDiagonal();
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_WorldToLocal(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3x4 ret = thisObj->WorldToLocal();
PushValueObjectCopy<float3x4>(ctx, ret, float3x4_ID, float3x4_Finalizer);
return 1;
}
static duk_ret_t OBB_LocalToWorld(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3x4 ret = thisObj->LocalToWorld();
PushValueObjectCopy<float3x4>(ctx, ret, float3x4_ID, float3x4_Finalizer);
return 1;
}
static duk_ret_t OBB_IsFinite(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
bool ret = thisObj->IsFinite();
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_IsDegenerate(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
bool ret = thisObj->IsDegenerate();
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_CenterPoint(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3 ret = thisObj->CenterPoint();
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_Centroid(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3 ret = thisObj->Centroid();
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_AnyPointFast(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3 ret = thisObj->AnyPointFast();
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_Volume(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float ret = thisObj->Volume();
duk_push_number(ctx, ret);
return 1;
}
static duk_ret_t OBB_SurfaceArea(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float ret = thisObj->SurfaceArea();
duk_push_number(ctx, ret);
return 1;
}
static duk_ret_t OBB_PointInside_float_float_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float x = (float)duk_require_number(ctx, 0);
float y = (float)duk_require_number(ctx, 1);
float z = (float)duk_require_number(ctx, 2);
float3 ret = thisObj->PointInside(x, y, z);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_Edge_int(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
int edgeIndex = (int)duk_require_number(ctx, 0);
LineSegment ret = thisObj->Edge(edgeIndex);
PushValueObjectCopy<LineSegment>(ctx, ret, LineSegment_ID, LineSegment_Finalizer);
return 1;
}
static duk_ret_t OBB_CornerPoint_int(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
int cornerIndex = (int)duk_require_number(ctx, 0);
float3 ret = thisObj->CornerPoint(cornerIndex);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_ExtremePoint_float3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& direction = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float3 ret = thisObj->ExtremePoint(direction);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_ExtremePoint_float3_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& direction = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float projectionDistance = (float)duk_require_number(ctx, 1);
float3 ret = thisObj->ExtremePoint(direction, projectionDistance);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_ProjectToAxis_float3_float_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& direction = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float outMin = (float)duk_require_number(ctx, 1);
float outMax = (float)duk_require_number(ctx, 2);
thisObj->ProjectToAxis(direction, outMin, outMax);
return 0;
}
static duk_ret_t OBB_PointOnEdge_int_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
int edgeIndex = (int)duk_require_number(ctx, 0);
float u = (float)duk_require_number(ctx, 1);
float3 ret = thisObj->PointOnEdge(edgeIndex, u);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_FaceCenterPoint_int(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
int faceIndex = (int)duk_require_number(ctx, 0);
float3 ret = thisObj->FaceCenterPoint(faceIndex);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_FacePoint_int_float_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
int faceIndex = (int)duk_require_number(ctx, 0);
float u = (float)duk_require_number(ctx, 1);
float v = (float)duk_require_number(ctx, 2);
float3 ret = thisObj->FacePoint(faceIndex, u, v);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_FacePlane_int(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
int faceIndex = (int)duk_require_number(ctx, 0);
Plane ret = thisObj->FacePlane(faceIndex);
PushValueObjectCopy<Plane>(ctx, ret, Plane_ID, Plane_Finalizer);
return 1;
}
static duk_ret_t OBB_RandomPointInside_LCG(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
LCG& rng = *GetCheckedValueObject<LCG>(ctx, 0, LCG_ID);
float3 ret = thisObj->RandomPointInside(rng);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_RandomPointOnSurface_LCG(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
LCG& rng = *GetCheckedValueObject<LCG>(ctx, 0, LCG_ID);
float3 ret = thisObj->RandomPointOnSurface(rng);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_RandomPointOnEdge_LCG(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
LCG& rng = *GetCheckedValueObject<LCG>(ctx, 0, LCG_ID);
float3 ret = thisObj->RandomPointOnEdge(rng);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_RandomCornerPoint_LCG(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
LCG& rng = *GetCheckedValueObject<LCG>(ctx, 0, LCG_ID);
float3 ret = thisObj->RandomCornerPoint(rng);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_Translate_float3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& offset = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
thisObj->Translate(offset);
return 0;
}
static duk_ret_t OBB_Scale_float3_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& centerPoint = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float scaleFactor = (float)duk_require_number(ctx, 1);
thisObj->Scale(centerPoint, scaleFactor);
return 0;
}
static duk_ret_t OBB_Scale_float3_float3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& centerPoint = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float3& scaleFactor = *GetCheckedValueObject<float3>(ctx, 1, float3_ID);
thisObj->Scale(centerPoint, scaleFactor);
return 0;
}
static duk_ret_t OBB_Transform_float3x3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3x3& transform = *GetCheckedValueObject<float3x3>(ctx, 0, float3x3_ID);
thisObj->Transform(transform);
return 0;
}
static duk_ret_t OBB_Transform_float3x4(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3x4& transform = *GetCheckedValueObject<float3x4>(ctx, 0, float3x4_ID);
thisObj->Transform(transform);
return 0;
}
static duk_ret_t OBB_Transform_float4x4(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float4x4& transform = *GetCheckedValueObject<float4x4>(ctx, 0, float4x4_ID);
thisObj->Transform(transform);
return 0;
}
static duk_ret_t OBB_Transform_Quat(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Quat& transform = *GetCheckedValueObject<Quat>(ctx, 0, Quat_ID);
thisObj->Transform(transform);
return 0;
}
static duk_ret_t OBB_ClosestPoint_float3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& point = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float3 ret = thisObj->ClosestPoint(point);
PushValueObjectCopy<float3>(ctx, ret, float3_ID, float3_Finalizer);
return 1;
}
static duk_ret_t OBB_Distance_float3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& point = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
float ret = thisObj->Distance(point);
duk_push_number(ctx, ret);
return 1;
}
static duk_ret_t OBB_Distance_Sphere(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Sphere& sphere = *GetCheckedValueObject<Sphere>(ctx, 0, Sphere_ID);
float ret = thisObj->Distance(sphere);
duk_push_number(ctx, ret);
return 1;
}
static duk_ret_t OBB_Contains_float3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& point = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
bool ret = thisObj->Contains(point);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Contains_LineSegment(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
LineSegment& lineSegment = *GetCheckedValueObject<LineSegment>(ctx, 0, LineSegment_ID);
bool ret = thisObj->Contains(lineSegment);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Contains_AABB(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
bool ret = thisObj->Contains(aabb);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Contains_OBB(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
OBB& obb = *GetCheckedValueObject<OBB>(ctx, 0, OBB_ID);
bool ret = thisObj->Contains(obb);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Contains_Triangle(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Triangle& triangle = *GetCheckedValueObject<Triangle>(ctx, 0, Triangle_ID);
bool ret = thisObj->Contains(triangle);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Contains_Frustum(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Frustum& frustum = *GetCheckedValueObject<Frustum>(ctx, 0, Frustum_ID);
bool ret = thisObj->Contains(frustum);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_OBB_float(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
OBB& obb = *GetCheckedValueObject<OBB>(ctx, 0, OBB_ID);
float epsilon = numArgs > 1 ? (float)duk_require_number(ctx, 1) : 1e-3f;
bool ret = thisObj->Intersects(obb, epsilon);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_AABB(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
AABB& aabb = *GetCheckedValueObject<AABB>(ctx, 0, AABB_ID);
bool ret = thisObj->Intersects(aabb);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Plane(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Plane& plane = *GetCheckedValueObject<Plane>(ctx, 0, Plane_ID);
bool ret = thisObj->Intersects(plane);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Ray_float_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Ray& ray = *GetCheckedValueObject<Ray>(ctx, 0, Ray_ID);
float dNear = (float)duk_require_number(ctx, 1);
float dFar = (float)duk_require_number(ctx, 2);
bool ret = thisObj->Intersects(ray, dNear, dFar);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Ray(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Ray& ray = *GetCheckedValueObject<Ray>(ctx, 0, Ray_ID);
bool ret = thisObj->Intersects(ray);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Line_float_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Line& line = *GetCheckedValueObject<Line>(ctx, 0, Line_ID);
float dNear = (float)duk_require_number(ctx, 1);
float dFar = (float)duk_require_number(ctx, 2);
bool ret = thisObj->Intersects(line, dNear, dFar);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Line(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Line& line = *GetCheckedValueObject<Line>(ctx, 0, Line_ID);
bool ret = thisObj->Intersects(line);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_LineSegment_float_float(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
LineSegment& lineSegment = *GetCheckedValueObject<LineSegment>(ctx, 0, LineSegment_ID);
float dNear = (float)duk_require_number(ctx, 1);
float dFar = (float)duk_require_number(ctx, 2);
bool ret = thisObj->Intersects(lineSegment, dNear, dFar);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_LineSegment(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
LineSegment& lineSegment = *GetCheckedValueObject<LineSegment>(ctx, 0, LineSegment_ID);
bool ret = thisObj->Intersects(lineSegment);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Capsule(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Capsule& capsule = *GetCheckedValueObject<Capsule>(ctx, 0, Capsule_ID);
bool ret = thisObj->Intersects(capsule);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Triangle(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Triangle& triangle = *GetCheckedValueObject<Triangle>(ctx, 0, Triangle_ID);
bool ret = thisObj->Intersects(triangle);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Intersects_Frustum(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
Frustum& frustum = *GetCheckedValueObject<Frustum>(ctx, 0, Frustum_ID);
bool ret = thisObj->Intersects(frustum);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Enclose_float3(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
float3& point = *GetCheckedValueObject<float3>(ctx, 0, float3_ID);
thisObj->Enclose(point);
return 0;
}
static duk_ret_t OBB_ToString(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
string ret = thisObj->ToString();
duk_push_string(ctx, ret.c_str());
return 1;
}
static duk_ret_t OBB_SerializeToString(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
string ret = thisObj->SerializeToString();
duk_push_string(ctx, ret.c_str());
return 1;
}
static duk_ret_t OBB_SerializeToCodeString(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
string ret = thisObj->SerializeToCodeString();
duk_push_string(ctx, ret.c_str());
return 1;
}
static duk_ret_t OBB_Equals_OBB_float(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
OBB& rhs = *GetCheckedValueObject<OBB>(ctx, 0, OBB_ID);
float epsilon = numArgs > 1 ? (float)duk_require_number(ctx, 1) : 1e-3f;
bool ret = thisObj->Equals(rhs, epsilon);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_BitEquals_OBB(duk_context* ctx)
{
OBB* thisObj = GetThisValueObject<OBB>(ctx, OBB_ID);
OBB& other = *GetCheckedValueObject<OBB>(ctx, 0, OBB_ID);
bool ret = thisObj->BitEquals(other);
duk_push_boolean(ctx, ret);
return 1;
}
static duk_ret_t OBB_Ctor_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 5 && GetValueObject<float3>(ctx, 0, float3_ID) && GetValueObject<float3>(ctx, 1, float3_ID) && GetValueObject<float3>(ctx, 2, float3_ID) && GetValueObject<float3>(ctx, 3, float3_ID) && GetValueObject<float3>(ctx, 4, float3_ID))
return OBB_Ctor_float3_float3_float3_float3_float3(ctx);
if (numArgs == 1 && GetValueObject<AABB>(ctx, 0, AABB_ID))
return OBB_Ctor_AABB(ctx);
if (numArgs == 0)
return OBB_Ctor(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_SetFrom_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 2 && GetValueObject<AABB>(ctx, 0, AABB_ID) && GetValueObject<Quat>(ctx, 1, Quat_ID))
return OBB_SetFrom_AABB_Quat(ctx);
if (numArgs == 2 && GetValueObject<AABB>(ctx, 0, AABB_ID) && GetValueObject<float4x4>(ctx, 1, float4x4_ID))
return OBB_SetFrom_AABB_float4x4(ctx);
if (numArgs == 2 && GetValueObject<AABB>(ctx, 0, AABB_ID) && GetValueObject<float3x4>(ctx, 1, float3x4_ID))
return OBB_SetFrom_AABB_float3x4(ctx);
if (numArgs == 2 && GetValueObject<AABB>(ctx, 0, AABB_ID) && GetValueObject<float3x3>(ctx, 1, float3x3_ID))
return OBB_SetFrom_AABB_float3x3(ctx);
if (numArgs == 1 && GetValueObject<Sphere>(ctx, 0, Sphere_ID))
return OBB_SetFrom_Sphere(ctx);
if (numArgs == 1 && GetValueObject<AABB>(ctx, 0, AABB_ID))
return OBB_SetFrom_AABB(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_ExtremePoint_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 2 && GetValueObject<float3>(ctx, 0, float3_ID) && duk_is_number(ctx, 1))
return OBB_ExtremePoint_float3_float(ctx);
if (numArgs == 1 && GetValueObject<float3>(ctx, 0, float3_ID))
return OBB_ExtremePoint_float3(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_Scale_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 2 && GetValueObject<float3>(ctx, 0, float3_ID) && GetValueObject<float3>(ctx, 1, float3_ID))
return OBB_Scale_float3_float3(ctx);
if (numArgs == 2 && GetValueObject<float3>(ctx, 0, float3_ID) && duk_is_number(ctx, 1))
return OBB_Scale_float3_float(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_Transform_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 1 && GetValueObject<float4x4>(ctx, 0, float4x4_ID))
return OBB_Transform_float4x4(ctx);
if (numArgs == 1 && GetValueObject<Quat>(ctx, 0, Quat_ID))
return OBB_Transform_Quat(ctx);
if (numArgs == 1 && GetValueObject<float3x3>(ctx, 0, float3x3_ID))
return OBB_Transform_float3x3(ctx);
if (numArgs == 1 && GetValueObject<float3x4>(ctx, 0, float3x4_ID))
return OBB_Transform_float3x4(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_Distance_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 1 && GetValueObject<Sphere>(ctx, 0, Sphere_ID))
return OBB_Distance_Sphere(ctx);
if (numArgs == 1 && GetValueObject<float3>(ctx, 0, float3_ID))
return OBB_Distance_float3(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_Contains_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 1 && GetValueObject<OBB>(ctx, 0, OBB_ID))
return OBB_Contains_OBB(ctx);
if (numArgs == 1 && GetValueObject<Triangle>(ctx, 0, Triangle_ID))
return OBB_Contains_Triangle(ctx);
if (numArgs == 1 && GetValueObject<Frustum>(ctx, 0, Frustum_ID))
return OBB_Contains_Frustum(ctx);
if (numArgs == 1 && GetValueObject<float3>(ctx, 0, float3_ID))
return OBB_Contains_float3(ctx);
if (numArgs == 1 && GetValueObject<LineSegment>(ctx, 0, LineSegment_ID))
return OBB_Contains_LineSegment(ctx);
if (numArgs == 1 && GetValueObject<AABB>(ctx, 0, AABB_ID))
return OBB_Contains_AABB(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_Intersects_Selector(duk_context* ctx)
{
int numArgs = duk_get_top(ctx);
if (numArgs == 3 && GetValueObject<Ray>(ctx, 0, Ray_ID) && duk_is_number(ctx, 1) && duk_is_number(ctx, 2))
return OBB_Intersects_Ray_float_float(ctx);
if (numArgs == 3 && GetValueObject<LineSegment>(ctx, 0, LineSegment_ID) && duk_is_number(ctx, 1) && duk_is_number(ctx, 2))
return OBB_Intersects_LineSegment_float_float(ctx);
if (numArgs == 3 && GetValueObject<Line>(ctx, 0, Line_ID) && duk_is_number(ctx, 1) && duk_is_number(ctx, 2))
return OBB_Intersects_Line_float_float(ctx);
if (numArgs == 1 && GetValueObject<LineSegment>(ctx, 0, LineSegment_ID))
return OBB_Intersects_LineSegment(ctx);
if (numArgs == 1 && GetValueObject<Triangle>(ctx, 0, Triangle_ID))
return OBB_Intersects_Triangle(ctx);
if (numArgs == 1 && GetValueObject<Frustum>(ctx, 0, Frustum_ID))
return OBB_Intersects_Frustum(ctx);
if (numArgs == 1 && GetValueObject<Capsule>(ctx, 0, Capsule_ID))
return OBB_Intersects_Capsule(ctx);
if (numArgs == 1 && GetValueObject<Plane>(ctx, 0, Plane_ID))
return OBB_Intersects_Plane(ctx);
if (numArgs == 1 && GetValueObject<AABB>(ctx, 0, AABB_ID))
return OBB_Intersects_AABB(ctx);
if (numArgs == 1 && GetValueObject<Ray>(ctx, 0, Ray_ID))
return OBB_Intersects_Ray(ctx);
if (numArgs == 1 && GetValueObject<Line>(ctx, 0, Line_ID))
return OBB_Intersects_Line(ctx);
if (numArgs >= 1 && GetValueObject<OBB>(ctx, 0, OBB_ID))
return OBB_Intersects_OBB_float(ctx);
duk_error(ctx, DUK_ERR_ERROR, "Could not select function overload");
}
static duk_ret_t OBB_NumVerticesInTriangulation_Static_int_int_int(duk_context* ctx)
{
int numFacesX = (int)duk_require_number(ctx, 0);
int numFacesY = (int)duk_require_number(ctx, 1);
int numFacesZ = (int)duk_require_number(ctx, 2);
int ret = OBB::NumVerticesInTriangulation(numFacesX, numFacesY, numFacesZ);
duk_push_number(ctx, ret);
return 1;
}
static duk_ret_t OBB_NumVerticesInEdgeList_Static(duk_context* ctx)
{
int ret = OBB::NumVerticesInEdgeList();
duk_push_number(ctx, ret);
return 1;
}
static duk_ret_t OBB_FromString_Static_string(duk_context* ctx)
{
string str = duk_require_string(ctx, 0);
OBB ret = OBB::FromString(str);
PushValueObjectCopy<OBB>(ctx, ret, OBB_ID, OBB_Finalizer);
return 1;
}
static const duk_function_list_entry OBB_Functions[] = {
{"SetNegativeInfinity", OBB_SetNegativeInfinity, 0}
,{"SetFrom", OBB_SetFrom_Selector, DUK_VARARGS}
,{"MinimalEnclosingAABB", OBB_MinimalEnclosingAABB, 0}
,{"MinimalEnclosingSphere", OBB_MinimalEnclosingSphere, 0}
,{"MaximalContainedSphere", OBB_MaximalContainedSphere, 0}
,{"Size", OBB_Size, 0}
,{"HalfSize", OBB_HalfSize, 0}
,{"Diagonal", OBB_Diagonal, 0}
,{"HalfDiagonal", OBB_HalfDiagonal, 0}
,{"WorldToLocal", OBB_WorldToLocal, 0}
,{"LocalToWorld", OBB_LocalToWorld, 0}
,{"IsFinite", OBB_IsFinite, 0}
,{"IsDegenerate", OBB_IsDegenerate, 0}
,{"CenterPoint", OBB_CenterPoint, 0}
,{"Centroid", OBB_Centroid, 0}
,{"AnyPointFast", OBB_AnyPointFast, 0}
,{"Volume", OBB_Volume, 0}
,{"SurfaceArea", OBB_SurfaceArea, 0}
,{"PointInside", OBB_PointInside_float_float_float, 3}
,{"Edge", OBB_Edge_int, 1}
,{"CornerPoint", OBB_CornerPoint_int, 1}
,{"ExtremePoint", OBB_ExtremePoint_Selector, DUK_VARARGS}
,{"ProjectToAxis", OBB_ProjectToAxis_float3_float_float, 3}
,{"PointOnEdge", OBB_PointOnEdge_int_float, 2}
,{"FaceCenterPoint", OBB_FaceCenterPoint_int, 1}
,{"FacePoint", OBB_FacePoint_int_float_float, 3}
,{"FacePlane", OBB_FacePlane_int, 1}
,{"RandomPointInside", OBB_RandomPointInside_LCG, 1}
,{"RandomPointOnSurface", OBB_RandomPointOnSurface_LCG, 1}
,{"RandomPointOnEdge", OBB_RandomPointOnEdge_LCG, 1}
,{"RandomCornerPoint", OBB_RandomCornerPoint_LCG, 1}
,{"Translate", OBB_Translate_float3, 1}
,{"Scale", OBB_Scale_Selector, DUK_VARARGS}
,{"Transform", OBB_Transform_Selector, DUK_VARARGS}
,{"ClosestPoint", OBB_ClosestPoint_float3, 1}
,{"Distance", OBB_Distance_Selector, DUK_VARARGS}
,{"Contains", OBB_Contains_Selector, DUK_VARARGS}
,{"Intersects", OBB_Intersects_Selector, DUK_VARARGS}
,{"Enclose", OBB_Enclose_float3, 1}
,{"ToString", OBB_ToString, 0}
,{"SerializeToString", OBB_SerializeToString, 0}
,{"SerializeToCodeString", OBB_SerializeToCodeString, 0}
,{"Equals", OBB_Equals_OBB_float, DUK_VARARGS}
,{"BitEquals", OBB_BitEquals_OBB, 1}
,{nullptr, nullptr, 0}
};
static const duk_function_list_entry OBB_StaticFunctions[] = {
{"NumVerticesInTriangulation", OBB_NumVerticesInTriangulation_Static_int_int_int, 3}
,{"NumVerticesInEdgeList", OBB_NumVerticesInEdgeList_Static, 0}
,{"FromString", OBB_FromString_Static_string, 1}
,{nullptr, nullptr, 0}
};
void Expose_OBB(duk_context* ctx)
{
duk_push_c_function(ctx, OBB_Ctor_Selector, DUK_VARARGS);
duk_put_function_list(ctx, -1, OBB_StaticFunctions);
duk_push_object(ctx);
duk_put_function_list(ctx, -1, OBB_Functions);
DefineProperty(ctx, "pos", OBB_Get_pos, OBB_Set_pos);
DefineProperty(ctx, "r", OBB_Get_r, OBB_Set_r);
duk_put_prop_string(ctx, -2, "prototype");
duk_put_global_string(ctx, OBB_ID);
}
}
| 35.280402 | 247 | 0.696787 | [
"geometry",
"transform"
] |
8fb7c2415138cb88495ddcb1b7ab6df733f2aaad | 1,601 | hpp | C++ | compiler/printer.hpp | jb55/clay | db0bd2702ab0b6e48965cd85f8859bbd5f60e48e | [
"BSD-2-Clause"
] | 185 | 2015-01-04T09:33:17.000Z | 2022-03-18T04:53:38.000Z | compiler/printer.hpp | Lencof/clay | 14939b88388eff73c8881dfd7f5a5dff5a7e8f91 | [
"BSD-2-Clause"
] | 7 | 2015-03-22T06:13:42.000Z | 2015-12-28T19:07:24.000Z | compiler/printer.hpp | Lencof/clay | 14939b88388eff73c8881dfd7f5a5dff5a7e8f91 | [
"BSD-2-Clause"
] | 20 | 2015-01-09T22:24:46.000Z | 2022-03-18T04:54:59.000Z | #pragma once
#include "clay.hpp"
namespace clay {
template <class T>
inline llvm::raw_ostream &operator<<(llvm::raw_ostream &out, llvm::ArrayRef<T> v)
{
out << "[";
const T *i, *end;
bool first = true;
for (i = v.begin(), end = v.end(); i != end; ++i) {
if (!first)
out << ", ";
first = false;
out << *i;
}
out << "]";
return out;
}
//
// printer module
//
llvm::raw_ostream &operator<<(llvm::raw_ostream &out, const Object &obj);
llvm::raw_ostream &operator<<(llvm::raw_ostream &out, const Object *obj);
llvm::raw_ostream &operator<<(llvm::raw_ostream &out, PVData const &pv);
template <class T>
llvm::raw_ostream &operator<<(llvm::raw_ostream &out, const Pointer<T> &p)
{
out << *p;
return out;
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &out, const PatternVar &pvar);
void enableSafePrintName();
void disableSafePrintName();
struct SafePrintNameEnabler {
SafePrintNameEnabler() { enableSafePrintName(); }
~SafePrintNameEnabler() { disableSafePrintName(); }
};
void printNameList(llvm::raw_ostream &out, llvm::ArrayRef<ObjectPtr> x);
void printNameList(llvm::raw_ostream &out, llvm::ArrayRef<ObjectPtr> x, llvm::ArrayRef<unsigned> dispatchIndices);
void printNameList(llvm::raw_ostream &out, llvm::ArrayRef<TypePtr> x);
void printStaticName(llvm::raw_ostream &out, ObjectPtr x);
void printName(llvm::raw_ostream &out, ObjectPtr x);
void printTypeAndValue(llvm::raw_ostream &out, EValuePtr ev);
void printValue(llvm::raw_ostream &out, EValuePtr ev);
string shortString(llvm::StringRef in);
}
| 23.544118 | 114 | 0.677077 | [
"object"
] |
263398a8e81a74bef0e43029cc56ffa60f471074 | 2,193 | cpp | C++ | samples/TilesApp/TilesApp.cpp | r3dl3g/guipp | 3d3179be3022935b46b59f1b988a029abeabfcbf | [
"MIT"
] | null | null | null | samples/TilesApp/TilesApp.cpp | r3dl3g/guipp | 3d3179be3022935b46b59f1b988a029abeabfcbf | [
"MIT"
] | null | null | null | samples/TilesApp/TilesApp.cpp | r3dl3g/guipp | 3d3179be3022935b46b59f1b988a029abeabfcbf | [
"MIT"
] | null | null | null |
#include <gui/layout/layout_container.h>
#include <gui/layout/grid_layout.h>
#include <gui/ctrl/split_view.h>
#include <gui/ctrl/tile_view.h>
#include <gui/ctrl/look/table.h>
using namespace gui;
using namespace gui::win;
using namespace gui::layout;
using namespace gui::ctrl;
using namespace gui::draw;
using namespace gui::core;
template<std::size_t S, frame::drawer F = frame::raised_relief>
struct tile_drawer : public list_data {
std::size_t size () const override { return S; }
void draw_at (std::size_t idx, graphics& g, const core::rectangle& r, const brush& b, item_state s) const override {
look::text_cell<std::size_t, F>(idx, g, r, text_origin_t::center, color::black, b.color(), s);
}
};
// --------------------------------------------------------------------------
int gui_main(const std::vector<std::string>& /*args*/) {
layout_main_window<grid_adaption<2, 2>> main;
horizontal_scrollable_tile_view htileview;
horizontal_scrollable_multi_tile_view htileview_m;
vertical_scrollable_tile_view vtileview;
vertical_scrollable_multi_tile_view vtileview_m;
htileview->set_item_size({ 110, 33 });
htileview->set_background(color::very_very_light_gray);
htileview->set_border({ 10, 20 });
htileview->set_spacing({ 5, 5 });
htileview->set_data(tile_drawer<97>());
htileview_m->set_item_size({ 110, 33 });
htileview_m->set_background(color::very_very_light_gray);
htileview_m->set_border({ 10, 20 });
htileview_m->set_spacing({ 5, 5 });
htileview_m->set_data(tile_drawer<97>());
vtileview->set_item_size({ 330, 33 });
vtileview->set_background(color::very_very_light_gray);
vtileview->set_border({ 10, 20 });
vtileview->set_spacing({ 5, 5 });
vtileview->set_data(tile_drawer<97>());
vtileview_m->set_item_size({ 330, 33 });
vtileview_m->set_background(color::very_very_light_gray);
vtileview_m->set_border({ 10, 20 });
vtileview_m->set_spacing({ 5, 5 });
vtileview_m->set_data(tile_drawer<97>());
main.add({htileview, htileview_m, vtileview, vtileview_m});
main.create({50, 50, 800, 600});
main.on_destroy(&quit_main_loop);
main.set_title("Tile View");
main.set_visible();
return run_main_loop();
}
| 31.782609 | 118 | 0.700866 | [
"vector"
] |
2639e3d331abd87303114df567abc574dc98ffa0 | 15,219 | cc | C++ | Cassie_Example/opt_two_step/gen/anim/Link_pelvis_to_hip_abduction_right_bar.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | Cassie_Example/opt_two_step/gen/anim/Link_pelvis_to_hip_abduction_right_bar.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | Cassie_Example/opt_two_step/gen/anim/Link_pelvis_to_hip_abduction_right_bar.cc | prem-chand/Cassie_CFROST | da4bd51442f86e852cbb630cc91c9a380a10b66d | [
"BSD-3-Clause"
] | null | null | null | /*
* Automatically Generated from Mathematica.
* Sat 13 Nov 2021 15:03:17 GMT-05:00
*/
#ifdef MATLAB_MEX_FILE
#include <stdexcept>
#include <cmath>
#include<math.h>
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
inline double Power(double x, double y) { return pow(x, y); }
inline double Sqrt(double x) { return sqrt(x); }
inline double Abs(double x) { return fabs(x); }
inline double Exp(double x) { return exp(x); }
inline double Log(double x) { return log(x); }
inline double Sin(double x) { return sin(x); }
inline double Cos(double x) { return cos(x); }
inline double Tan(double x) { return tan(x); }
inline double ArcSin(double x) { return asin(x); }
inline double ArcCos(double x) { return acos(x); }
inline double ArcTan(double x) { return atan(x); }
/* update ArcTan function to use atan2 instead. */
inline double ArcTan(double x, double y) { return atan2(y,x); }
inline double Sinh(double x) { return sinh(x); }
inline double Cosh(double x) { return cosh(x); }
inline double Tanh(double x) { return tanh(x); }
const double E = 2.71828182845904523536029;
const double Pi = 3.14159265358979323846264;
const double Degree = 0.01745329251994329576924;
inline double Sec(double x) { return 1/cos(x); }
inline double Csc(double x) { return 1/sin(x); }
#endif
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1)
{
double t1465;
double t1510;
double t1545;
double t1520;
double t1585;
double t1486;
double t1534;
double t1607;
double t1616;
double t1621;
double t1623;
double t1624;
double t1496;
double t1620;
double t1625;
double t1627;
double t1831;
double t1832;
double t1833;
double t1835;
double t1836;
double t1837;
double t1830;
double t1834;
double t1838;
double t1839;
double t1914;
double t1915;
double t1916;
double t1917;
double t1633;
double t1647;
double t1656;
double t1678;
double t1713;
double t1728;
double t1733;
double t1739;
double t1748;
double t1761;
double t1783;
double t1803;
double t1807;
double t1811;
double t1815;
double t1819;
double t1823;
double t1827;
double t1990;
double t1991;
double t1992;
double t1841;
double t1845;
double t1849;
double t1853;
double t1858;
double t1862;
double t1866;
double t1870;
double t1874;
double t1878;
double t1882;
double t1886;
double t1890;
double t1894;
double t1898;
double t1902;
double t1906;
double t1910;
double t2048;
double t2049;
double t2050;
double t1918;
double t1922;
double t1926;
double t1930;
double t1934;
double t1938;
double t1942;
double t1946;
double t1950;
double t1954;
double t1958;
double t1962;
double t1966;
double t1970;
double t1974;
double t1978;
double t1982;
double t1986;
double t2105;
double t2106;
double t2107;
t1465 = Cos(var1[3]);
t1510 = Cos(var1[5]);
t1545 = Sin(var1[3]);
t1520 = Sin(var1[4]);
t1585 = Sin(var1[5]);
t1486 = Cos(var1[4]);
t1534 = t1465*t1510*t1520;
t1607 = t1545*t1585;
t1616 = t1534 + t1607;
t1621 = -1.*t1510*t1545;
t1623 = t1465*t1520*t1585;
t1624 = t1621 + t1623;
t1496 = 0.00757*t1465*t1486;
t1620 = 0.012655*t1616;
t1625 = -0.002748*t1624;
t1627 = var1[0] + t1496 + t1620 + t1625;
t1831 = t1510*t1545*t1520;
t1832 = -1.*t1465*t1585;
t1833 = t1831 + t1832;
t1835 = t1465*t1510;
t1836 = t1545*t1520*t1585;
t1837 = t1835 + t1836;
t1830 = 0.00757*t1486*t1545;
t1834 = 0.012655*t1833;
t1838 = -0.002748*t1837;
t1839 = var1[1] + t1830 + t1834 + t1838;
t1914 = 0.012655*t1486*t1510;
t1915 = -0.00757*t1520;
t1916 = -0.002748*t1486*t1585;
t1917 = var1[2] + t1914 + t1915 + t1916;
t1633 = 0.014584*t1616;
t1647 = 0.014933*t1616;
t1656 = 0.013664*t1616;
t1678 = 0.010914*t1616;
t1713 = 0.006981*t1616;
t1728 = 0.002292*t1616;
t1733 = -0.002646*t1616;
t1739 = -0.007297*t1616;
t1748 = -0.011157*t1616;
t1761 = -0.013808*t1616;
t1783 = -0.014963*t1616;
t1803 = -0.014496*t1616;
t1807 = -0.012458*t1616;
t1811 = -0.009071*t1616;
t1815 = -0.0047*t1616;
t1819 = 0.000179*t1616;
t1823 = 0.00504*t1616;
t1827 = 0.009354*t1616;
t1990 = -0.04143*t1465*t1486;
t1991 = -0.137748*t1624;
t1992 = var1[0] + t1990 + t1620 + t1991;
t1841 = 0.014584*t1833;
t1845 = 0.014933*t1833;
t1849 = 0.013664*t1833;
t1853 = 0.010914*t1833;
t1858 = 0.006981*t1833;
t1862 = 0.002292*t1833;
t1866 = -0.002646*t1833;
t1870 = -0.007297*t1833;
t1874 = -0.011157*t1833;
t1878 = -0.013808*t1833;
t1882 = -0.014963*t1833;
t1886 = -0.014496*t1833;
t1890 = -0.012458*t1833;
t1894 = -0.009071*t1833;
t1898 = -0.0047*t1833;
t1902 = 0.000179*t1833;
t1906 = 0.00504*t1833;
t1910 = 0.009354*t1833;
t2048 = -0.04143*t1486*t1545;
t2049 = -0.137748*t1837;
t2050 = var1[1] + t2048 + t1834 + t2049;
t1918 = 0.014584*t1486*t1510;
t1922 = 0.014933*t1486*t1510;
t1926 = 0.013664*t1486*t1510;
t1930 = 0.010914*t1486*t1510;
t1934 = 0.006981*t1486*t1510;
t1938 = 0.002292*t1486*t1510;
t1942 = -0.002646*t1486*t1510;
t1946 = -0.007297*t1486*t1510;
t1950 = -0.011157*t1486*t1510;
t1954 = -0.013808*t1486*t1510;
t1958 = -0.014963*t1486*t1510;
t1962 = -0.014496*t1486*t1510;
t1966 = -0.012458*t1486*t1510;
t1970 = -0.009071*t1486*t1510;
t1974 = -0.0047*t1486*t1510;
t1978 = 0.000179*t1486*t1510;
t1982 = 0.00504*t1486*t1510;
t1986 = 0.009354*t1486*t1510;
t2105 = 0.04143*t1520;
t2106 = -0.137748*t1486*t1585;
t2107 = var1[2] + t1914 + t2105 + t2106;
p_output1[0]=t1627;
p_output1[1]=0.003298*t1465*t1486 - 0.001197*t1624 + t1633 + var1[0];
p_output1[2]=-0.001332*t1465*t1486 + 0.000484*t1624 + t1647 + var1[0];
p_output1[3]=-0.005818*t1465*t1486 + 0.002112*t1624 + t1656 + var1[0];
p_output1[4]=-0.009673*t1465*t1486 + 0.003511*t1624 + t1678 + var1[0];
p_output1[5]=-0.01248*t1465*t1486 + 0.00453*t1624 + t1713 + var1[0];
p_output1[6]=-0.013934*t1465*t1486 + 0.005058*t1624 + t1728 + var1[0];
p_output1[7]=-0.013879*t1465*t1486 + 0.005038*t1624 + t1733 + var1[0];
p_output1[8]=-0.012319*t1465*t1486 + 0.004471*t1624 + t1739 + var1[0];
p_output1[9]=-0.009425*t1465*t1486 + 0.003421*t1624 + t1748 + var1[0];
p_output1[10]=-0.005509*t1465*t1486 + 0.002*t1624 + t1761 + var1[0];
p_output1[11]=-0.000996*t1465*t1486 + 0.000362*t1624 + t1783 + var1[0];
p_output1[12]=0.003625*t1465*t1486 - 0.001316*t1624 + t1803 + var1[0];
p_output1[13]=0.007853*t1465*t1486 - 0.00285*t1624 + t1807 + var1[0];
p_output1[14]=0.01123*t1465*t1486 - 0.004076*t1624 + t1811 + var1[0];
p_output1[15]=0.01339*t1465*t1486 - 0.00486*t1624 + t1815 + var1[0];
p_output1[16]=0.014099*t1465*t1486 - 0.005117*t1624 + t1819 + var1[0];
p_output1[17]=0.01328*t1465*t1486 - 0.00482*t1624 + t1823 + var1[0];
p_output1[18]=0.011022*t1465*t1486 - 0.004001*t1624 + t1827 + var1[0];
p_output1[19]=t1627;
p_output1[20]=t1839;
p_output1[21]=0.003298*t1486*t1545 - 0.001197*t1837 + t1841 + var1[1];
p_output1[22]=-0.001332*t1486*t1545 + 0.000484*t1837 + t1845 + var1[1];
p_output1[23]=-0.005818*t1486*t1545 + 0.002112*t1837 + t1849 + var1[1];
p_output1[24]=-0.009673*t1486*t1545 + 0.003511*t1837 + t1853 + var1[1];
p_output1[25]=-0.01248*t1486*t1545 + 0.00453*t1837 + t1858 + var1[1];
p_output1[26]=-0.013934*t1486*t1545 + 0.005058*t1837 + t1862 + var1[1];
p_output1[27]=-0.013879*t1486*t1545 + 0.005038*t1837 + t1866 + var1[1];
p_output1[28]=-0.012319*t1486*t1545 + 0.004471*t1837 + t1870 + var1[1];
p_output1[29]=-0.009425*t1486*t1545 + 0.003421*t1837 + t1874 + var1[1];
p_output1[30]=-0.005509*t1486*t1545 + 0.002*t1837 + t1878 + var1[1];
p_output1[31]=-0.000996*t1486*t1545 + 0.000362*t1837 + t1882 + var1[1];
p_output1[32]=0.003625*t1486*t1545 - 0.001316*t1837 + t1886 + var1[1];
p_output1[33]=0.007853*t1486*t1545 - 0.00285*t1837 + t1890 + var1[1];
p_output1[34]=0.01123*t1486*t1545 - 0.004076*t1837 + t1894 + var1[1];
p_output1[35]=0.01339*t1486*t1545 - 0.00486*t1837 + t1898 + var1[1];
p_output1[36]=0.014099*t1486*t1545 - 0.005117*t1837 + t1902 + var1[1];
p_output1[37]=0.01328*t1486*t1545 - 0.00482*t1837 + t1906 + var1[1];
p_output1[38]=0.011022*t1486*t1545 - 0.004001*t1837 + t1910 + var1[1];
p_output1[39]=t1839;
p_output1[40]=t1917;
p_output1[41]=-0.003298*t1520 - 0.001197*t1486*t1585 + t1918 + var1[2];
p_output1[42]=0.001332*t1520 + 0.000484*t1486*t1585 + t1922 + var1[2];
p_output1[43]=0.005818*t1520 + 0.002112*t1486*t1585 + t1926 + var1[2];
p_output1[44]=0.009673*t1520 + 0.003511*t1486*t1585 + t1930 + var1[2];
p_output1[45]=0.01248*t1520 + 0.00453*t1486*t1585 + t1934 + var1[2];
p_output1[46]=0.013934*t1520 + 0.005058*t1486*t1585 + t1938 + var1[2];
p_output1[47]=0.013879*t1520 + 0.005038*t1486*t1585 + t1942 + var1[2];
p_output1[48]=0.012319*t1520 + 0.004471*t1486*t1585 + t1946 + var1[2];
p_output1[49]=0.009425*t1520 + 0.003421*t1486*t1585 + t1950 + var1[2];
p_output1[50]=0.005509*t1520 + 0.002*t1486*t1585 + t1954 + var1[2];
p_output1[51]=0.000996*t1520 + 0.000362*t1486*t1585 + t1958 + var1[2];
p_output1[52]=-0.003625*t1520 - 0.001316*t1486*t1585 + t1962 + var1[2];
p_output1[53]=-0.007853*t1520 - 0.00285*t1486*t1585 + t1966 + var1[2];
p_output1[54]=-0.01123*t1520 - 0.004076*t1486*t1585 + t1970 + var1[2];
p_output1[55]=-0.01339*t1520 - 0.00486*t1486*t1585 + t1974 + var1[2];
p_output1[56]=-0.014099*t1520 - 0.005117*t1486*t1585 + t1978 + var1[2];
p_output1[57]=-0.01328*t1520 - 0.00482*t1486*t1585 + t1982 + var1[2];
p_output1[58]=-0.011022*t1520 - 0.004001*t1486*t1585 + t1986 + var1[2];
p_output1[59]=t1917;
p_output1[60]=t1992;
p_output1[61]=-0.045702*t1465*t1486 - 0.136197*t1624 + t1633 + var1[0];
p_output1[62]=-0.050332*t1465*t1486 - 0.134516*t1624 + t1647 + var1[0];
p_output1[63]=-0.054818*t1465*t1486 - 0.132888*t1624 + t1656 + var1[0];
p_output1[64]=-0.058673*t1465*t1486 - 0.131489*t1624 + t1678 + var1[0];
p_output1[65]=-0.06148*t1465*t1486 - 0.13047*t1624 + t1713 + var1[0];
p_output1[66]=-0.062934*t1465*t1486 - 0.129942*t1624 + t1728 + var1[0];
p_output1[67]=-0.062879*t1465*t1486 - 0.129962*t1624 + t1733 + var1[0];
p_output1[68]=-0.061319*t1465*t1486 - 0.130529*t1624 + t1739 + var1[0];
p_output1[69]=-0.058425*t1465*t1486 - 0.131579*t1624 + t1748 + var1[0];
p_output1[70]=-0.054509*t1465*t1486 - 0.133*t1624 + t1761 + var1[0];
p_output1[71]=-0.049996*t1465*t1486 - 0.134638*t1624 + t1783 + var1[0];
p_output1[72]=-0.045375*t1465*t1486 - 0.136316*t1624 + t1803 + var1[0];
p_output1[73]=-0.041147*t1465*t1486 - 0.13785*t1624 + t1807 + var1[0];
p_output1[74]=-0.03777*t1465*t1486 - 0.139076*t1624 + t1811 + var1[0];
p_output1[75]=-0.03561*t1465*t1486 - 0.13986*t1624 + t1815 + var1[0];
p_output1[76]=-0.034901*t1465*t1486 - 0.140117*t1624 + t1819 + var1[0];
p_output1[77]=-0.03572*t1465*t1486 - 0.13982*t1624 + t1823 + var1[0];
p_output1[78]=-0.037978*t1465*t1486 - 0.139001*t1624 + t1827 + var1[0];
p_output1[79]=t1992;
p_output1[80]=t2050;
p_output1[81]=-0.045702*t1486*t1545 - 0.136197*t1837 + t1841 + var1[1];
p_output1[82]=-0.050332*t1486*t1545 - 0.134516*t1837 + t1845 + var1[1];
p_output1[83]=-0.054818*t1486*t1545 - 0.132888*t1837 + t1849 + var1[1];
p_output1[84]=-0.058673*t1486*t1545 - 0.131489*t1837 + t1853 + var1[1];
p_output1[85]=-0.06148*t1486*t1545 - 0.13047*t1837 + t1858 + var1[1];
p_output1[86]=-0.062934*t1486*t1545 - 0.129942*t1837 + t1862 + var1[1];
p_output1[87]=-0.062879*t1486*t1545 - 0.129962*t1837 + t1866 + var1[1];
p_output1[88]=-0.061319*t1486*t1545 - 0.130529*t1837 + t1870 + var1[1];
p_output1[89]=-0.058425*t1486*t1545 - 0.131579*t1837 + t1874 + var1[1];
p_output1[90]=-0.054509*t1486*t1545 - 0.133*t1837 + t1878 + var1[1];
p_output1[91]=-0.049996*t1486*t1545 - 0.134638*t1837 + t1882 + var1[1];
p_output1[92]=-0.045375*t1486*t1545 - 0.136316*t1837 + t1886 + var1[1];
p_output1[93]=-0.041147*t1486*t1545 - 0.13785*t1837 + t1890 + var1[1];
p_output1[94]=-0.03777*t1486*t1545 - 0.139076*t1837 + t1894 + var1[1];
p_output1[95]=-0.03561*t1486*t1545 - 0.13986*t1837 + t1898 + var1[1];
p_output1[96]=-0.034901*t1486*t1545 - 0.140117*t1837 + t1902 + var1[1];
p_output1[97]=-0.03572*t1486*t1545 - 0.13982*t1837 + t1906 + var1[1];
p_output1[98]=-0.037978*t1486*t1545 - 0.139001*t1837 + t1910 + var1[1];
p_output1[99]=t2050;
p_output1[100]=t2107;
p_output1[101]=0.045702*t1520 - 0.136197*t1486*t1585 + t1918 + var1[2];
p_output1[102]=0.050332*t1520 - 0.134516*t1486*t1585 + t1922 + var1[2];
p_output1[103]=0.054818*t1520 - 0.132888*t1486*t1585 + t1926 + var1[2];
p_output1[104]=0.058673*t1520 - 0.131489*t1486*t1585 + t1930 + var1[2];
p_output1[105]=0.06148*t1520 - 0.13047*t1486*t1585 + t1934 + var1[2];
p_output1[106]=0.062934*t1520 - 0.129942*t1486*t1585 + t1938 + var1[2];
p_output1[107]=0.062879*t1520 - 0.129962*t1486*t1585 + t1942 + var1[2];
p_output1[108]=0.061319*t1520 - 0.130529*t1486*t1585 + t1946 + var1[2];
p_output1[109]=0.058425*t1520 - 0.131579*t1486*t1585 + t1950 + var1[2];
p_output1[110]=0.054509*t1520 - 0.133*t1486*t1585 + t1954 + var1[2];
p_output1[111]=0.049996*t1520 - 0.134638*t1486*t1585 + t1958 + var1[2];
p_output1[112]=0.045375*t1520 - 0.136316*t1486*t1585 + t1962 + var1[2];
p_output1[113]=0.041147*t1520 - 0.13785*t1486*t1585 + t1966 + var1[2];
p_output1[114]=0.03777*t1520 - 0.139076*t1486*t1585 + t1970 + var1[2];
p_output1[115]=0.03561*t1520 - 0.13986*t1486*t1585 + t1974 + var1[2];
p_output1[116]=0.034901*t1520 - 0.140117*t1486*t1585 + t1978 + var1[2];
p_output1[117]=0.03572*t1520 - 0.13982*t1486*t1585 + t1982 + var1[2];
p_output1[118]=0.037978*t1520 - 0.139001*t1486*t1585 + t1986 + var1[2];
p_output1[119]=t2107;
}
#ifdef MATLAB_MEX_FILE
#include "mex.h"
/*
* Main function
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
size_t mrows, ncols;
double *var1;
double *p_output1;
/* Check for proper number of arguments. */
if( nrhs != 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1).");
}
else if( nlhs > 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments.");
}
/* The input must be a noncomplex double vector or scaler. */
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
( !(mrows == 20 && ncols == 1) &&
!(mrows == 1 && ncols == 20)))
{
mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong.");
}
/* Assign pointers to each input. */
var1 = mxGetPr(prhs[0]);
/* Create matrices for return arguments. */
plhs[0] = mxCreateDoubleMatrix((mwSize) 20, (mwSize) 6, mxREAL);
p_output1 = mxGetPr(plhs[0]);
/* Call the calculation subroutine. */
output1(p_output1,var1);
}
#else // MATLAB_MEX_FILE
#include "Link_pelvis_to_hip_abduction_right_bar.hh"
namespace SymFunction
{
void Link_pelvis_to_hip_abduction_right_bar_raw(double *p_output1, const double *var1)
{
// Call Subroutines
output1(p_output1, var1);
}
}
#endif // MATLAB_MEX_FILE
| 35.475524 | 92 | 0.670741 | [
"vector"
] |
2639ee11bacdee4d5b2b9fc954ebcede56f2e7f1 | 5,835 | cpp | C++ | rf.cpp | Legendexo/Control-car | 45732c7cea4f810c5666158ba535dfcf64983b12 | [
"MIT"
] | 56 | 2016-09-01T20:42:43.000Z | 2022-03-21T19:52:32.000Z | rf.cpp | nocomp/rf-car | b62fa5c762f03e2e0bad218e79c861c3552a18af | [
"MIT"
] | null | null | null | rf.cpp | nocomp/rf-car | b62fa5c762f03e2e0bad218e79c861c3552a18af | [
"MIT"
] | 11 | 2016-09-16T03:08:13.000Z | 2022-03-14T23:09:33.000Z | #include <libhackrf/hackrf.h>
#include <cstdio>
#include <vector>
#include "rf.h"
using namespace std;
struct global_args_t rf_global_args;
static vector<int> patterns[9];
static vector<float> filter;
static volatile Direction last_dir = none;
static volatile unsigned int pos = 0;
static hackrf_device *device = NULL;
static int last_gain_tx = 20;
void swap_direction(Direction *a, Direction *b) {
Direction tmp = *a;
*a = *b;
*b = tmp;
}
void set_direction_map(struct direction_map_t *map, bool invert_steering, bool invert_throttle, bool swap_axes) {
/* we are going to treat our struct like a 3x3 array */
Direction *map_arr = (Direction *)map;
map_arr[0] = fwd_left;
map_arr[1] = fwd;
map_arr[2] = fwd_right;
map_arr[3] = left;
map_arr[4] = none;
map_arr[5] = right;
map_arr[6] = back_left;
map_arr[7] = back;
map_arr[8] = back_right;
if (swap_axes) {
/* treat map_arr as 3x3 array, transform s.t. map_arr[i][j] becomes map_arr[j][i] */
/* do this first so that invert_* work on the transformed values */
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
if (i<j) {
swap_direction(map_arr + 3*j + i, map_arr + 3*i+ j);
}
}
}
}
if (invert_steering) {
/* treat map_arr as a 3x3 array, swap left and right columns */
for (int i = 0; i < 9; i+=3) {
swap_direction(map_arr + i, map_arr + i + 2);
}
}
if (invert_throttle) {
/* treat map_arr as a 3x3 array, swap top and bottom rows */
for (int i = 0; i < 3; i++) {
swap_direction(map_arr + i, map_arr + i + 6);
}
}
}
static void make_short_pulses(vector<int> &v, int num)
{
for (int i = 0 ; i < num ; i++) {
v.push_back(1);
v.push_back(0);
}
}
static void init_patterns()
{
for (int i = 0 ; i < 8 ; i++) {
// each pattern start with 4 long pulses
for (int j = 0 ; j < 4 ; j++) {
patterns[i].push_back(1);
patterns[i].push_back(1);
patterns[i].push_back(1);
patterns[i].push_back(0);
}
}
make_short_pulses(patterns[fwd], 10);
make_short_pulses(patterns[fwd_left], 28);
make_short_pulses(patterns[fwd_right], 34);
make_short_pulses(patterns[back], 40);
make_short_pulses(patterns[back_left], 52);
make_short_pulses(patterns[back_right], 46);
make_short_pulses(patterns[left], 58);
make_short_pulses(patterns[right], 64);
patterns[none].push_back(0);
patterns[none].push_back(0);
patterns[none].push_back(0);
// moving averarge can be implemented more efficiently
// but this allows playing with other type of filters
for (int i = 0 ; i < 20 ; i++) {
filter.push_back(0.9/20);
}
}
static int tx_callback(hackrf_transfer* transfer) {
int spb = rf_global_args.SAMPLE_RATE / rf_global_args.SYMBOL_RATE; // samples per bit
for (int i = 0 ; i < transfer->valid_length/2 ; i++) {
vector<int> &pattern = patterns[last_dir];
int pattern_size = pattern.size();
float sum = 0;
for (int j = 0 ; j < (int)filter.size() ; j++) {
int sample = pattern[((pos + j)/spb) % pattern_size];
sum += filter[j] * sample;
}
pos += 1;
transfer->buffer[i*2] = sum * 127;
transfer->buffer[i*2+1] = 0;
}
return 0;
}
bool init_rf()
{
init_patterns();
int result = hackrf_init();
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_init() failed: (%d)\n", result);
return false;
}
return true;
}
static void start_tx()
{
int result = hackrf_open(&device);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_open() failed: (%d)\n", result);
}
result = hackrf_set_sample_rate_manual(device, rf_global_args.SAMPLE_RATE, 1);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_sample_rate_set() failed: (%d)\n", result);
}
uint32_t baseband_filter_bw_hz = hackrf_compute_baseband_filter_bw_round_down_lt(rf_global_args.SAMPLE_RATE);
result = hackrf_set_baseband_filter_bandwidth(device, baseband_filter_bw_hz);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_baseband_filter_bandwidth_set() failed: (%d)\n", result);
}
result = hackrf_set_freq(device, rf_global_args.FREQ);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_set_freq() failed: (%d)\n", result);
}
result = hackrf_set_amp_enable(device, 1);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_set_amp_enable() failed: (%d)\n", result);
}
result = hackrf_set_txvga_gain(device, last_gain_tx);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_set_txvga_gain() failed: (%d)\n", result);
}
result = hackrf_start_tx(device, tx_callback, NULL);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_start_tx() failed: (%d)\n", result);
}
}
static void stop_tx()
{
int result = hackrf_stop_tx(device);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_stop_tx() failed: (%d)\n", result);
}
result = hackrf_close(device);
if (result != HACKRF_SUCCESS) {
fprintf(stderr, "hackrf_close() failed: (%d)\n", result);
}
}
void state_change(Direction dir, int gain_tx)
{
if (gain_tx != last_gain_tx) {
last_gain_tx = gain_tx;
}
if (dir != last_dir) {
if (last_dir == none) {
last_dir = dir;
pos = 0;
start_tx();
return;
} else if (dir == none) {
stop_tx();
}
last_dir = dir;
pos = 0;
}
}
void close_rf()
{
hackrf_exit();
}
| 29.321608 | 113 | 0.594002 | [
"vector",
"transform"
] |
264ea6219e6e2c4624440c4183373dacfc97de9d | 2,127 | cpp | C++ | src/configure/commands/header_dependencies.cpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 1 | 2015-11-13T10:37:35.000Z | 2015-11-13T10:37:35.000Z | src/configure/commands/header_dependencies.cpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | 19 | 2015-02-10T17:18:58.000Z | 2015-07-11T11:31:08.000Z | src/configure/commands/header_dependencies.cpp | hotgloupi/configure | 888cf725c93df5a1cf01794cc0a581586a82855c | [
"BSD-3-Clause"
] | null | null | null | #include "header_dependencies.hpp"
#include <boost/filesystem.hpp>
#include <fstream>
#include <set>
namespace configure { namespace commands {
namespace fs = boost::filesystem;
static
void inspect(fs::path const& source,
std::set<fs::path>& seen,
std::vector<fs::path> const& include_directories)
{
if (!fs::is_regular_file(source))
return;
std::vector<boost::filesystem::path> found;
std::ifstream f(source.string());
std::string line;
while (std::getline(f, line))
{
char const* ptr = line.c_str();
while (*ptr == ' ' || *ptr == '\t') // XXX should use isblank
ptr += 1;
if (*ptr != '#')
continue;
ptr += 1;
if (std::strncmp(ptr, "include", sizeof("include") - 1) != 0)
continue;
ptr += sizeof("include");
while (*ptr == ' ' || *ptr == '\t') // XXX should use isblank
ptr += 1;
if (*ptr != '<' && *ptr != '"')
continue;
ptr += 1;
size_t i = 0;
while (ptr[i] != '\0' && ptr[i] != '>' && ptr[i] != '"')
i += 1;
found.push_back(std::string(ptr, i));
}
fs::path source_dir = source.parent_path();
for (auto& el: found)
{
fs::path local = source_dir / el;
if (fs::is_regular_file(local))
{
local = fs::canonical(local);
if (seen.insert(local).second == true)
inspect(local, seen, include_directories);
continue;
}
for (auto const& include_dir: include_directories)
{
fs::path local = include_dir / el;
if (fs::is_regular_file(local))
{
local = fs::canonical(local);
if (seen.insert(local).second == true)
inspect(local, seen, include_directories);
continue;
}
}
}
}
void header_dependencies(
std::ostream& out,
boost::filesystem::path const& source,
std::vector<boost::filesystem::path> const& targets,
std::vector<boost::filesystem::path> const& include_directories)
{
std::set<fs::path> seen;
inspect(source, seen, include_directories);
for (auto& target: targets)
out << target.string() << ' ';
out << ":";
for (auto& el: seen)
out << " \\\n " << el.string();
out << "\n";
}
}}
| 23.373626 | 69 | 0.5811 | [
"vector"
] |
265449978d497e33c2a85b5ad1fbbf3830dd3381 | 1,341 | cpp | C++ | tests/bin/readLevelfile.cpp | villaa/nrCascadeSim | 83fac469648dc940585c9eee64dbe9488e0fe434 | [
"MIT"
] | null | null | null | tests/bin/readLevelfile.cpp | villaa/nrCascadeSim | 83fac469648dc940585c9eee64dbe9488e0fe434 | [
"MIT"
] | null | null | null | tests/bin/readLevelfile.cpp | villaa/nrCascadeSim | 83fac469648dc940585c9eee64dbe9488e0fe434 | [
"MIT"
] | null | null | null | //library commands
#include "cascadeProd.h"
#include "lindhard.h"
#include "weisskopf.h"
#include "isotope_info.h"
#include <iostream>
#include <iomanip>
//ROOT stuff
#include "rootUtil.h"
//get the file name
string filenames="inputfile.txt";
//read the contents of a file into a cli object
int numc;
bool success=false;
vector<cli> cascadeFile = readCascadeDistributionFile(numc,filenames,success);
int main(){
//print the info that was read in
for(int i=0;i<numc;i++){
std::cout << "Cascade ID: " << i+1 << "/" << numc << endl;
std::cout << "Fraction of this cascade: " << cascadeFile[i].frac << endl;
std::cout << "Neutron separation: " << cascadeFile[i].Sn << endl;
std::cout << "Mass number: " << cascadeFile[i].A << endl;
std::cout << "Number of steps: " << cascadeFile[i].n << endl;
std::cout << endl;
std::cout << "Energy Levels (keV)\t|\ttau (fs)" << endl;
std::cout << "------------------------------------------------" << endl;
std::cout << std::setfill('0') << std::setw(5) << std::setprecision(5);
std::cout << " ***** " << "\t \t" << " ***** " << endl;
for(int j=0;j<cascadeFile[i].n;j++){
std::cout << " "<< cascadeFile[i].Elev[j] << " " << "\t \t" << " "<< cascadeFile[i].taus[j] << " " << endl;
}
}
return 0;
} | 35.289474 | 126 | 0.542878 | [
"object",
"vector"
] |
2655e00544fdb3f055a41837f87977824a264996 | 3,814 | cpp | C++ | VisualStudio/VectorTools/VectorTools/VectorLocatorDrawOverride.cpp | diseraluca/VectorTools | 766352637eaf0c8d5b11f0b9e0e5ddcd45b27fef | [
"MIT"
] | null | null | null | VisualStudio/VectorTools/VectorTools/VectorLocatorDrawOverride.cpp | diseraluca/VectorTools | 766352637eaf0c8d5b11f0b9e0e5ddcd45b27fef | [
"MIT"
] | null | null | null | VisualStudio/VectorTools/VectorTools/VectorLocatorDrawOverride.cpp | diseraluca/VectorTools | 766352637eaf0c8d5b11f0b9e0e5ddcd45b27fef | [
"MIT"
] | null | null | null | // Copyright 2018 Luca Di Sera
// This code is licensed under the MIT License ( see LICENSE.txt for details )
#include "VectorLocatorDrawOverride.h"
#include "VectorLocatorData.h"
#include <maya/MEventMessage.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MHardwareRenderer.h>
MVector _vectorFromPlug(const MPlug& plug) {
float vector[3];
for (int index{ 0 }; index < 3; index++) {
MPlug vectorAxis{ plug.child(index) };
vector[index] = vectorAxis.asFloat();
}
return MVector{ vector };
}
MColor _colorFromPlug(const MPlug& plug) {
float color[3];
for (int index{ 0 }; index < 3; index++) {
MPlug vectorAxis{ plug.child(index) };
color[index] = vectorAxis.asFloat();
}
return MColor{ color };
}
VectorLocatorDrawOverride::VectorLocatorDrawOverride(const MObject& obj) :MHWRender::MPxDrawOverride{ obj, NULL, false } {
fModelEditorChangedCbId = MEventMessage::addEventCallback("onModelEditorChanged", VectorLocatorDrawOverride::OnModelEditorChanged, this);
MStatus status{};
MFnDependencyNode vectorLocatorNode{ obj, &status };
fVectorLocator = status ? dynamic_cast<VectorLocator*>(vectorLocatorNode.userNode()) : NULL;
}
VectorLocatorDrawOverride::~VectorLocatorDrawOverride()
{
fVectorLocator = NULL;
if (fModelEditorChangedCbId != 0) {
MEventMessage::removeCallback(fModelEditorChangedCbId);
fModelEditorChangedCbId = 0;
}
}
void VectorLocatorDrawOverride::OnModelEditorChanged(void *clientData) {
VectorLocatorDrawOverride* override = static_cast<VectorLocatorDrawOverride*>(clientData);
if (override && override->fVectorLocator) {
MHWRender::MRenderer::setGeometryDrawDirty(override->fVectorLocator->thisMObject());
}
}
MHWRender::MPxDrawOverride * VectorLocatorDrawOverride::Creator(const MObject & obj)
{
return new VectorLocatorDrawOverride(obj);
}
MHWRender::DrawAPI VectorLocatorDrawOverride::supportedDrawAPIs() const
{
return (MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile | MHWRender::kDirectX11 );
}
MUserData * VectorLocatorDrawOverride::prepareForDraw(const MDagPath & objPath, const MDagPath & cameraPath, const MHWRender::MFrameContext & frameContext, MUserData * oldData)
{
VectorLocatorData* data = dynamic_cast<VectorLocatorData*>(oldData);
if (!oldData) {
data = new VectorLocatorData;
}
MObject vectorLocatorNode{ objPath.node() };
MPlug basePointPlug{ vectorLocatorNode, VectorLocator::basePoint };
data->basePoint = _vectorFromPlug(basePointPlug);
MPlug endPointPlug{ vectorLocatorNode, VectorLocator::endPoint };
data->endPoint = _vectorFromPlug(endPointPlug);
MPlug colorPlug{ vectorLocatorNode, VectorLocator::color };
data->color = _colorFromPlug(colorPlug);
return data;
}
bool VectorLocatorDrawOverride::hasUIDrawables() const
{
return true;
}
void VectorLocatorDrawOverride::addUIDrawables(const MDagPath & objPath, MHWRender::MUIDrawManager & drawManager, const MHWRender::MFrameContext & frameContext, const MUserData * data)
{
VectorLocatorData* vectorLocatorData = (VectorLocatorData*)data;
if (!vectorLocatorData) {
return;
}
drawManager.beginDrawable();
drawManager.setColor(vectorLocatorData->color);
drawManager.line(vectorLocatorData->basePoint, vectorLocatorData->endPoint);
MVector line{ vectorLocatorData->endPoint - vectorLocatorData->basePoint };
double lineLength{ line.length() };
double coneRadius{ frameContext.getGlobalLineWidth() / 2};
double coneHeigth = (lineLength > coneRadius) ? coneRadius : lineLength / 4;
MVector coneDirection{ line.normal() };
// Reduce the vector to position the base so that the cone tip lies on vectorLocatorData->endPoint
MVector coneBase{ (coneDirection * (coneHeigth - lineLength) * -1) + vectorLocatorData->basePoint };
drawManager.cone(coneBase, coneDirection, coneRadius, coneHeigth, true);
drawManager.endDrawable();
} | 32.322034 | 184 | 0.773466 | [
"vector"
] |
266c4d1ce78aeb537a37d96aead19272ed3f4d2f | 1,645 | cpp | C++ | graph-source-code/456-E/7408300.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/456-E/7408300.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/456-E/7408300.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <vector>
#include <algorithm>
#define pb push_back
using namespace std;
vector<int> s,p,v,v2,l;
vector<vector<int> > e;
int far,maxd;
int par(int nd){
if(p[nd]==nd) return nd;
return p[nd]=par(p[nd]);
}
int dfs(int nd,int pr,int ds){
if(v[nd]) return 0;
v[nd]=1;
p[nd]=pr;
if(ds>maxd) far=nd,maxd=ds;
int size=1;
for(int i=0;i<e[nd].size();i++){
size += dfs(e[nd][i],pr,ds+1);
}
return s[nd]=size;
}
void dfs2(int nd,int ds){
if(v2[nd]) return;
v2[nd]=1;
if(ds>maxd) far=nd,maxd=ds;
for(int i=0;i<e[nd].size();i++){
dfs2(e[nd][i],ds+1);
}
}
int main(){
ios_base::sync_with_stdio(0);
int n,m,q,x,y,z;
cin >> n >> m >> q;
e.resize(n);
s.resize(n,0);
p.resize(n,0);
v.resize(n,0);
v2.resize(n,0);
l.resize(n,0);
for(int i=0;i<m;i++){
cin >> x >> y;
x--; y--;
e[x].pb(y);
e[y].pb(x);
}
for(int i=0;i<n;i++){
far=i;
maxd=0;
//v.clear(); v.resize(n,0);
dfs(i,i,0);
//v.clear(); v.resize(n,0);
maxd=0;
dfs2(far,0);
l[i] = maxd;
}
for(int i=0;i<q;i++){
cin >> z;
if(z==1){
cin >> x;
x--;
//cout << x << " " << par(x) << " " << l[par(x)] << endl;
cout << l[par(x)] << "\n";
}
else {
cin >> x >> y;
x--; y--;
x = par(x); y = par(y);
if(x==y) continue;
if(s[x]<s[y]) swap(x,y);
p[y] = x;
s[x] += s[y];
l[x] = max((l[x]>>1) + (l[y]>>1) + (l[x]&1) + (l[y]&1) + 1,l[x]);
l[x] = max(l[y],l[x]);
//cout << x << " " << par(x) << " " << l[par(x)] << " : " << y << " " << par(y) << " " << l[par(y)] << endl;
}
}
return 0;
} | 19.819277 | 112 | 0.449848 | [
"vector"
] |
26773d5fe4e939a5065e8ae49b7d11d450bf7136 | 14,937 | cpp | C++ | Source/HoudiniNiagara/Private/HoudiniPointCacheLoaderBJSON.cpp | GarmOfGnipahellir/HoudiniNiagara | fdc48ab130e26c5ef6df6298d3eb0633b65e48de | [
"BSD-3-Clause"
] | 172 | 2020-04-18T17:36:38.000Z | 2022-03-23T16:33:08.000Z | Source/HoudiniNiagara/Private/HoudiniPointCacheLoaderBJSON.cpp | GarmOfGnipahellir/HoudiniNiagara | fdc48ab130e26c5ef6df6298d3eb0633b65e48de | [
"BSD-3-Clause"
] | 17 | 2020-05-11T04:32:35.000Z | 2022-01-20T14:09:19.000Z | Source/HoudiniNiagara/Private/HoudiniPointCacheLoaderBJSON.cpp | GarmOfGnipahellir/HoudiniNiagara | fdc48ab130e26c5ef6df6298d3eb0633b65e48de | [
"BSD-3-Clause"
] | 37 | 2020-05-16T04:28:33.000Z | 2022-03-07T09:34:13.000Z | #include "HoudiniPointCacheLoaderBJSON.h"
#include "HoudiniPointCache.h"
#include "HAL/FileManager.h"
#include "Misc/FileHelper.h"
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeChar;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeInt8;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeUInt8;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeBool;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeInt16;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeUInt16;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeInt32;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeUInt32;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeInt64;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeUInt64;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeFloat32;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeFloat64;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerTypeString;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerObjectStart;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerObjectEnd;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerArrayStart;
const unsigned char FHoudiniPointCacheLoaderBJSON::MarkerArrayEnd;
FHoudiniPointCacheLoaderBJSON::FHoudiniPointCacheLoaderBJSON(const FString& InFilePath) :
FHoudiniPointCacheLoaderJSONBase(InFilePath)
{
}
bool FHoudiniPointCacheLoaderBJSON::LoadToAsset(UHoudiniPointCache *InAsset)
{
const FString& InFilePath = GetFilePath();
FScopedLoadingState ScopedLoadingState(*InFilePath);
// Pre-allocate and reset buffer
Buffer.SetNumZeroed(1024);
// Get file stream
Reader = MakeShareable(IFileManager::Get().CreateFileReader(*InFilePath));
if (!Reader)
{
UE_LOG(LogHoudiniNiagara, Warning, TEXT("Failed to read file '%s' error."), *InFilePath);
return false;
}
// Read start of root object
unsigned char Marker = '\0';
if (!ReadMarker(Marker) || Marker != MarkerObjectStart)
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Expected root object start."));
return false;
}
FString ObjectKey;
if (!ReadNonContainerValue(ObjectKey, false))
return false;
if (ObjectKey != TEXT("header"))
return false;
// Found header
FHoudiniPointCacheJSONHeader Header;
if (!ReadHeader(Header))
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Could not read header."));
return false;
}
// Set up the Attribute and SpecialAttributeIndexes arrays in the asset,
// expanding attributes with size > 1
// If time was not an attribute in the file, we add it as an attribute
// but we always set time to the frame's time, irrespective of the existence of a time
// attribute in the file
uint32 NumAttributesPerFileSample = Header.NumAttributeComponents;
ParseAttributesAndInitAsset(InAsset, Header);
// Get Age attribute index, we'll use this to ensure we sort point spawn time correctly
int32 IDAttributeIndex = InAsset->GetAttributeAttributeIndex(EHoudiniAttributes::POINTID);
int32 AgeAttributeIndex = InAsset->GetAttributeAttributeIndex(EHoudiniAttributes::AGE);
// Due to the way that some of the DI functions work,
// we expect that the point IDs start at zero, and increment as the points are spawned
// Make sure this is the case by converting the point IDs as we read them
int32 NextPointID = 0;
TMap<int32, int32> HoudiniIDToNiagaraIDMap;
// Expect cache_data key, object start, frames key
if (!ReadNonContainerValue(ObjectKey, false, MarkerTypeString) || ObjectKey != TEXT("cache_data"))
return false;
if (!ReadMarker(Marker) || Marker != MarkerObjectStart)
return false;
if (!ReadNonContainerValue(ObjectKey, false, MarkerTypeString) || ObjectKey != TEXT("frames"))
return false;
// Read the frames array, each entry contains a 'frame' object
// Expect array start
if (!ReadMarker(Marker) || Marker != MarkerArrayStart)
return false;
uint32 NumFramesRead = 0;
uint32 FrameStartSampleIndex = 0;
TArray<TArray<float>> TempFrameData;
while (!Reader->AtEnd() && !IsNext(MarkerArrayEnd))
{
// Expect object start
if (!ReadMarker(Marker) || Marker != MarkerObjectStart)
return false;
float FrameNumber = 0.0f;
float Time = 0;
uint32 NumPointsInFrame = 0;
// Read 'number' (frame number)
if (!ReadNonContainerValue(ObjectKey, false, MarkerTypeString) || ObjectKey != TEXT("number"))
return false;
if (!ReadNonContainerValue(FrameNumber, false, MarkerTypeUInt32))
return false;
// Read 'time'
if (!ReadNonContainerValue(ObjectKey, false, MarkerTypeString) || ObjectKey != TEXT("time"))
return false;
if (!ReadNonContainerValue(Time, false, MarkerTypeFloat32))
return false;
// Read 'num_points' (number of points in frame)
if (!ReadNonContainerValue(ObjectKey, false, MarkerTypeString) || ObjectKey != TEXT("num_points"))
return false;
if (!ReadNonContainerValue(NumPointsInFrame, false, MarkerTypeUInt32))
return false;
// Expect 'frame_data' key
if (!ReadNonContainerValue(ObjectKey, false, MarkerTypeString) || ObjectKey != TEXT("frame_data"))
return false;
// Expect array start marker
if (!ReadMarker(Marker) || Marker != MarkerArrayStart)
return false;
// Ensure we have enough space in our FrameData array to read the samples for this frame
TempFrameData.SetNum(NumPointsInFrame);
float PreviousAge = 0.0f;
bool bNeedToSort = false;
for (uint32 SampleIndex = 0; SampleIndex < NumPointsInFrame; ++SampleIndex)
{
// Initialize attributes for this sample
TempFrameData[SampleIndex].Init(0, NumAttributesPerFileSample);
// Expect array start marker
if (!ReadMarker(Marker) || Marker != MarkerArrayStart)
return false;
for (uint32 AttrIndex = 0; AttrIndex < NumAttributesPerFileSample; ++AttrIndex)
{
float& Value = TempFrameData[SampleIndex][AttrIndex];
// Read a value
if (!ReadNonContainerValue(Value, false, Header.AttributeComponentDataTypes[AttrIndex]))
return false;
if (AgeAttributeIndex != INDEX_NONE && AttrIndex == AgeAttributeIndex)
{
if (SampleIndex == 0)
{
PreviousAge = Value;
}
else if (PreviousAge < Value)
{
bNeedToSort = true;
}
}
}
// Expect array end marker
if (!ReadMarker(Marker) || Marker != MarkerArrayEnd)
return false;
}
// Sort this frame's data by age
if (bNeedToSort)
{
TempFrameData.Sort<FHoudiniPointCacheSortPredicate>(FHoudiniPointCacheSortPredicate(INDEX_NONE, AgeAttributeIndex, IDAttributeIndex));
}
ProcessFrame(InAsset, FrameNumber, TempFrameData, Time, FrameStartSampleIndex, NumPointsInFrame, NumAttributesPerFileSample, Header, HoudiniIDToNiagaraIDMap, NextPointID);
// Expect array end marker
if (!ReadMarker(Marker) || Marker != MarkerArrayEnd)
return false;
// Expect object end
if (!ReadMarker(Marker) || Marker != MarkerObjectEnd)
return false;
FrameStartSampleIndex += NumPointsInFrame;
NumFramesRead++;
}
if (NumFramesRead != Header.NumFrames)
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Inconsistent num_frames in header vs body: %d vs %d"), Header.NumFrames, NumFramesRead);
return false;
}
// Expect array end - frames
if (!ReadMarker(Marker) || Marker != MarkerArrayEnd)
return false;
// Expect object end - cache_data
if (!ReadMarker(Marker) || Marker != MarkerObjectEnd)
return false;
// Expect object end - root
if (!ReadMarker(Marker) || Marker != MarkerObjectEnd)
return false;
return true;
}
bool FHoudiniPointCacheLoaderBJSON::ReadMarker(unsigned char &OutMarker)
{
if (!CheckReader())
return false;
// Read TYPE (1 byte)
Reader->Serialize(Buffer.GetData(), 1);
OutMarker = Buffer[0];
return true;
}
bool FHoudiniPointCacheLoaderBJSON::ReadHeader(FHoudiniPointCacheJSONHeader &OutHeader)
{
// Expect object start
unsigned char Marker = '\0';
if (!ReadMarker(Marker) || Marker != MarkerObjectStart)
return false;
// Attempt to reach each key and value of the header, return false if any value is missing or
// not of the expected type
FString HeaderKey;
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("version"))
return false;
if (!ReadNonContainerValue(OutHeader.Version, false, MarkerTypeString))
return false;
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("num_samples"))
return false;
if (!ReadNonContainerValue(OutHeader.NumSamples, false, MarkerTypeUInt32))
return false;
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("num_frames"))
return false;
if (!ReadNonContainerValue(OutHeader.NumFrames, false, MarkerTypeUInt32))
return false;
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("num_points"))
return false;
if (!ReadNonContainerValue(OutHeader.NumPoints, false, MarkerTypeUInt32))
return false;
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("num_attrib"))
return false;
if (!ReadNonContainerValue(OutHeader.NumAttributes, false, MarkerTypeUInt16))
return false;
// Preallocate Attribute arrays from NumAttributes
OutHeader.Attributes.Empty(OutHeader.NumAttributes);
OutHeader.AttributeSizes.Empty(OutHeader.NumAttributes);
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("attrib_name"))
return false;
if (!ReadArray(OutHeader.Attributes, MarkerTypeString))
return false;
// Check that attrib_name was the expected size
if (OutHeader.Attributes.Num() != OutHeader.NumAttributes)
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Header inconsistent: attrib_name array size mismatch: %d vs %d"), OutHeader.Attributes.Num(), OutHeader.NumAttributes);
return false;
}
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("attrib_size"))
return false;
if (!ReadArray(OutHeader.AttributeSizes, MarkerTypeUInt8))
return false;
// Check that attrib_size was the expected size
if (OutHeader.AttributeSizes.Num() != OutHeader.NumAttributes)
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Header inconsistent: attrib_size array size mismatch: %d vs %d"), OutHeader.AttributeSizes.Num(), OutHeader.NumAttributes);
return false;
}
// Calculate the number of attribute components (sum of attribute size over all attributes)
OutHeader.NumAttributeComponents = 0;
for (uint32 AttrSize : OutHeader.AttributeSizes)
{
OutHeader.NumAttributeComponents += AttrSize;
}
OutHeader.AttributeComponentDataTypes.Empty(OutHeader.NumAttributeComponents);
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("attrib_data_type"))
return false;
if (!ReadArray(OutHeader.AttributeComponentDataTypes, MarkerTypeChar))
return false;
// Check that attrib_data_type was the expected size
if (OutHeader.AttributeComponentDataTypes.Num() != OutHeader.NumAttributeComponents)
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Header inconsistent: attrib_data_type array size mismatch: %d vs %d"), OutHeader.AttributeComponentDataTypes.Num(), OutHeader.NumAttributeComponents);
return false;
}
if (!ReadNonContainerValue(HeaderKey, false, MarkerTypeString) || HeaderKey != TEXT("data_type"))
return false;
if (!ReadNonContainerValue(OutHeader.DataType, false, MarkerTypeString))
return false;
// Expect object end
if (!ReadMarker(Marker) || Marker != MarkerObjectEnd)
return false;
return true;
}
bool FHoudiniPointCacheLoaderBJSON::ReadNonContainerValue(FString &OutValue, bool bInReadMarkerType, unsigned char InMarkerType)
{
if (!CheckReader())
return false;
uint32 Size = 0;
unsigned char MarkerType = '\0';
if (bInReadMarkerType)
{
// Read TYPE (1 byte)
Reader->Serialize(Buffer.GetData(), 1);
MarkerType = Buffer[0];
}
else
{
MarkerType = InMarkerType;
}
if (MarkerType != MarkerTypeString && MarkerType != MarkerTypeChar)
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Expected string or char, found type %c"), MarkerType);
return false;
}
if (MarkerType == MarkerTypeString)
{
// Get the number of characters in the string as Size
if (!ReadNonContainerValue(Size, true))
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Could not determine string size."));
return false;
}
// Strings are encoded with utf-8, calculate number of bytes to read
Size = Size * sizeof(UTF8CHAR);
}
else
{
// char 1 byte
Size = 1;
}
Reader->Serialize(Buffer.GetData(), Size);
if (Size >= static_cast<uint32>(Buffer.Num()))
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Buffer too small to read string with size %d"), Size)
return false;
}
Buffer[Size] = '\0';
OutValue = UTF8_TO_TCHAR(Buffer.GetData());
return true;
}
bool FHoudiniPointCacheLoaderBJSON::Peek(int32 InSize)
{
if (!CheckReader())
return false;
int64 Position = Reader->Tell();
if (Reader->TotalSize() - Position < InSize)
{
return false;
}
Reader->ByteOrderSerialize(Buffer.GetData(), InSize);
Reader->Seek(Position);
return true;
}
bool FHoudiniPointCacheLoaderBJSON::CheckReader(bool bInCheckAtEnd) const
{
if (!Reader || !Reader.IsValid())
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Binary JSON reader is not valid."))
return false;
}
// Check that we are not at the end of the archive
if (bInCheckAtEnd && Reader->AtEnd())
{
UE_LOG(LogHoudiniNiagara, Error, TEXT("Binary JSON reader reach EOF early."))
return false;
}
return true;
}
| 36.520782 | 197 | 0.676508 | [
"object"
] |
269c667873b48e21b1cd91958cabfb34ba7ecf2f | 21,933 | cpp | C++ | src/objectxml.cpp | MelvinG24/dust3d | c4936fd900a9a48220ebb811dfeaea0effbae3ee | [
"MIT"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | src/objectxml.cpp | MelvinG24/dust3d | c4936fd900a9a48220ebb811dfeaea0effbae3ee | [
"MIT"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | src/objectxml.cpp | MelvinG24/dust3d | c4936fd900a9a48220ebb811dfeaea0effbae3ee | [
"MIT"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | #include <stack>
#include <QUuid>
#include <QDebug>
#include <QStringList>
#include <QRegExp>
#include "objectxml.h"
#include "util.h"
void saveObjectToXmlStream(const Object *object, QXmlStreamWriter *writer)
{
std::map<std::pair<QUuid, QUuid>, size_t> nodeIdMap;
for (size_t i = 0; i < object->nodes.size(); ++i) {
const auto &it = object->nodes[i];
nodeIdMap.insert({{it.partId, it.nodeId}, i});
}
writer->setAutoFormatting(true);
writer->writeStartDocument();
writer->writeStartElement("object");
if (object->alphaEnabled)
writer->writeAttribute("alphaEnabled", "true");
writer->writeStartElement("nodes");
for (const auto &node: object->nodes) {
writer->writeStartElement("node");
writer->writeAttribute("partId", node.partId.toString());
writer->writeAttribute("id", node.nodeId.toString());
writer->writeAttribute("x", QString::number(node.origin.x()));
writer->writeAttribute("y", QString::number(node.origin.y()));
writer->writeAttribute("z", QString::number(node.origin.z()));
writer->writeAttribute("radius", QString::number(node.radius));
writer->writeAttribute("color", node.color.name(QColor::HexArgb));
writer->writeAttribute("colorSolubility", QString::number(node.colorSolubility));
writer->writeAttribute("metallic", QString::number(node.metalness));
writer->writeAttribute("roughness", QString::number(node.roughness));
if (!node.materialId.isNull())
writer->writeAttribute("materialId", node.materialId.toString());
if (node.countershaded)
writer->writeAttribute("countershaded", "true");
if (!node.mirrorFromPartId.isNull())
writer->writeAttribute("mirrorFromPartId", node.mirrorFromPartId.toString());
if (!node.mirroredByPartId.isNull())
writer->writeAttribute("mirroredByPartId", node.mirroredByPartId.toString());
if (node.boneMark != BoneMark::None)
writer->writeAttribute("boneMark", BoneMarkToString(node.boneMark));
if (!node.joined)
writer->writeAttribute("joined", "false");
writer->writeEndElement();
}
writer->writeEndElement();
writer->writeStartElement("edges");
for (const auto &edge: object->edges) {
writer->writeStartElement("edge");
writer->writeAttribute("fromPartId", edge.first.first.toString());
writer->writeAttribute("fromNodeId", edge.first.second.toString());
writer->writeAttribute("toPartId", edge.second.first.toString());
writer->writeAttribute("toNodeId", edge.second.second.toString());
writer->writeEndElement();
}
writer->writeEndElement();
writer->writeStartElement("vertices");
QStringList vertexList;
for (const auto &vertex: object->vertices) {
vertexList += QString::number(vertex.x()) + "," + QString::number(vertex.y()) + "," + QString::number(vertex.z());
}
writer->writeCharacters(vertexList.join(" "));
writer->writeEndElement();
writer->writeStartElement("vertexSourceNodes");
QStringList vertexSourceNodeList;
for (const auto &it: object->vertexSourceNodes) {
auto findIndex = nodeIdMap.find(it);
if (findIndex == nodeIdMap.end()) {
vertexSourceNodeList += "-1";
} else {
vertexSourceNodeList += QString::number(findIndex->second);
}
}
writer->writeCharacters(vertexSourceNodeList.join(" "));
writer->writeEndElement();
writer->writeStartElement("triangleAndQuads");
QStringList triangleAndQuadList;
for (const auto &it: object->triangleAndQuads) {
QStringList face;
for (const auto &index: it)
face += QString::number(index);
triangleAndQuadList += face.join(",");
}
writer->writeCharacters(triangleAndQuadList.join(" "));
writer->writeEndElement();
writer->writeStartElement("triangles");
QStringList triangleList;
for (const auto &it: object->triangles) {
QStringList face;
for (const auto &index: it)
face += QString::number(index);
triangleList += face.join(",");
}
writer->writeCharacters(triangleList.join(" "));
writer->writeEndElement();
writer->writeStartElement("triangleNormals");
QStringList triangleNormalList;
for (const auto &normal: object->triangleNormals) {
triangleNormalList += QString::number(normal.x()) + "," + QString::number(normal.y()) + "," + QString::number(normal.z());
}
writer->writeCharacters(triangleNormalList.join(" "));
writer->writeEndElement();
writer->writeStartElement("triangleColors");
QStringList triangleColorList;
for (const auto &color: object->triangleColors) {
triangleColorList += color.name(QColor::HexArgb);
}
writer->writeCharacters(triangleColorList.join(" "));
writer->writeEndElement();
const std::vector<std::pair<QUuid, QUuid>> *triangleSourceNodes = object->triangleSourceNodes();
if (nullptr != triangleSourceNodes) {
writer->writeStartElement("triangleSourceNodes");
QStringList triangleSourceNodeList;
for (const auto &it: *triangleSourceNodes) {
auto findIndex = nodeIdMap.find(it);
if (findIndex == nodeIdMap.end()) {
triangleSourceNodeList += "-1";
} else {
triangleSourceNodeList += QString::number(findIndex->second);
}
}
writer->writeCharacters(triangleSourceNodeList.join(" "));
writer->writeEndElement();
}
const std::vector<std::vector<QVector2D>> *triangleVertexUvs = object->triangleVertexUvs();
if (nullptr != triangleVertexUvs) {
writer->writeStartElement("triangleVertexUvs");
QStringList triangleVertexUvList;
for (const auto &triangleUvs: *triangleVertexUvs) {
for (const auto &uv: triangleUvs) {
triangleVertexUvList += QString::number(uv.x()) + "," + QString::number(uv.y());
}
}
writer->writeCharacters(triangleVertexUvList.join(" "));
writer->writeEndElement();
}
const std::vector<std::vector<QVector3D>> *triangleVertexNormals = object->triangleVertexNormals();
if (nullptr != triangleVertexNormals) {
writer->writeStartElement("triangleVertexNormals");
QStringList triangleVertexNormalList;
for (const auto &triangleNormals: *triangleVertexNormals) {
for (const auto &normal: triangleNormals) {
triangleVertexNormalList += QString::number(normal.x()) + "," + QString::number(normal.y()) + "," + QString::number(normal.z());
}
}
writer->writeCharacters(triangleVertexNormalList.join(" "));
writer->writeEndElement();
}
const std::vector<QVector3D> *triangleTangents = object->triangleTangents();
if (nullptr != triangleTangents) {
writer->writeStartElement("triangleTangents");
QStringList triangleTangentList;
for (const auto &tangent: *triangleTangents) {
triangleTangentList += QString::number(tangent.x()) + "," + QString::number(tangent.y()) + "," + QString::number(tangent.z());
}
writer->writeCharacters(triangleTangentList.join(" "));
writer->writeEndElement();
}
const std::map<QUuid, std::vector<QRectF>> *partUvRects = object->partUvRects();
if (nullptr != partUvRects) {
writer->writeStartElement("uvAreas");
for (const auto &it: *partUvRects) {
for (const auto &rect: it.second) {
writer->writeStartElement("uvArea");
writer->writeAttribute("partId", it.first.toString());
writer->writeAttribute("left", QString::number(rect.left()));
writer->writeAttribute("top", QString::number(rect.top()));
writer->writeAttribute("width", QString::number(rect.width()));
writer->writeAttribute("height", QString::number(rect.height()));
writer->writeEndElement();
}
}
writer->writeEndElement();
}
const std::vector<std::pair<std::pair<size_t, size_t>, std::pair<size_t, size_t>>> *triangleLinks = object->triangleLinks();
if (nullptr != triangleLinks) {
writer->writeStartElement("triangleLinks");
QStringList triangleLinkList;
for (const auto &link: *triangleLinks) {
triangleLinkList += QString::number(link.first.first) + "," + QString::number(link.first.second) + "," + QString::number(link.second.first) + "," + QString::number(link.second.second);
}
writer->writeCharacters(triangleLinkList.join(" "));
writer->writeEndElement();
}
writer->writeEndElement();
writer->writeEndDocument();
}
void loadObjectFromXmlStream(Object *object, QXmlStreamReader &reader)
{
std::map<QUuid, std::vector<QRectF>> partUvRects;
std::vector<QString> elementNameStack;
while (!reader.atEnd()) {
reader.readNext();
if (!reader.isStartElement() && !reader.isEndElement() && !reader.isCharacters()) {
if (!reader.name().toString().isEmpty())
qDebug() << "Skip xml element:" << reader.name().toString() << " tokenType:" << reader.tokenType();
continue;
}
QString baseName = reader.name().toString();
if (reader.isStartElement())
elementNameStack.push_back(baseName);
QStringList nameItems;
for (const auto &nameItem: elementNameStack) {
nameItems.append(nameItem);
}
QString fullName = nameItems.join(".");
if (reader.isEndElement())
elementNameStack.pop_back();
if (reader.isStartElement()) {
if (fullName == "object") {
object->alphaEnabled = isTrueValueString(reader.attributes().value("alphaEnabled").toString());
} else if (fullName == "object.nodes.node") {
QString nodeId = reader.attributes().value("id").toString();
if (nodeId.isEmpty())
continue;
ObjectNode node;
node.nodeId = QUuid(nodeId);
node.partId = QUuid(reader.attributes().value("partId").toString());
node.origin.setX(reader.attributes().value("x").toFloat());
node.origin.setY(reader.attributes().value("y").toFloat());
node.origin.setZ(reader.attributes().value("z").toFloat());
node.radius = reader.attributes().value("radius").toFloat();
node.color = QColor(reader.attributes().value("color").toString());
node.colorSolubility = reader.attributes().value("colorSolubility").toFloat();
node.metalness = reader.attributes().value("metallic").toFloat();
node.roughness = reader.attributes().value("roughness").toFloat();
node.materialId = QUuid(reader.attributes().value("materialId").toString());
node.countershaded = isTrueValueString(reader.attributes().value("countershaded").toString());
node.mirrorFromPartId = QUuid(reader.attributes().value("mirrorFromPartId").toString());
node.mirroredByPartId = QUuid(reader.attributes().value("mirroredByPartId").toString());
node.boneMark = BoneMarkFromString(reader.attributes().value("boneMark").toString().toUtf8().constData());
QString joinedString = reader.attributes().value("joined").toString();
if (!joinedString.isEmpty())
node.joined = isTrueValueString(joinedString);
object->nodes.push_back(node);
} else if (fullName == "object.edges.edge") {
std::pair<std::pair<QUuid, QUuid>, std::pair<QUuid, QUuid>> edge;
edge.first.first = QUuid(reader.attributes().value("fromPartId").toString());
edge.first.second = QUuid(reader.attributes().value("fromNodeId").toString());
edge.second.first = QUuid(reader.attributes().value("toPartId").toString());
edge.second.second = QUuid(reader.attributes().value("toNodeId").toString());
object->edges.push_back(edge);
} else if (fullName == "object.uvAreas.uvArea") {
QUuid partId = QUuid(reader.attributes().value("partId").toString());
if (!partId.isNull()) {
QRectF area(reader.attributes().value("left").toFloat(),
reader.attributes().value("top").toFloat(),
reader.attributes().value("width").toFloat(),
reader.attributes().value("height").toFloat());
partUvRects[partId].push_back(area);
}
}
} else if (reader.isEndElement()) {
if (fullName == "object.uvAreas") {
object->setPartUvRects(partUvRects);
}
} else if (reader.isCharacters()) {
if (fullName == "object.vertices") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
for (const auto &item: list) {
auto subItems = item.split(",");
if (3 != subItems.size())
continue;
object->vertices.push_back({subItems[0].toFloat(),
subItems[1].toFloat(),
subItems[2].toFloat()});
}
} else if (fullName == "object.vertexSourceNodes") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
for (const auto &item: list) {
int index = item.toInt();
if (index < 0 || index >= object->nodes.size()) {
object->vertexSourceNodes.push_back({QUuid(), QUuid()});
} else {
const auto &node = object->nodes[index];
object->vertexSourceNodes.push_back({node.partId, node.nodeId});
}
}
} else if (fullName == "object.triangleAndQuads") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
for (const auto &item: list) {
auto subItems = item.split(",");
if (3 == subItems.size()) {
object->triangleAndQuads.push_back({(size_t)subItems[0].toInt(),
(size_t)subItems[1].toInt(),
(size_t)subItems[2].toInt()});
} else if (4 == subItems.size()) {
object->triangleAndQuads.push_back({(size_t)subItems[0].toInt(),
(size_t)subItems[1].toInt(),
(size_t)subItems[2].toInt(),
(size_t)subItems[3].toInt()});
}
}
} else if (fullName == "object.triangles") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
for (const auto &item: list) {
auto subItems = item.split(",");
if (3 == subItems.size()) {
object->triangles.push_back({(size_t)subItems[0].toInt(),
(size_t)subItems[1].toInt(),
(size_t)subItems[2].toInt()});
}
}
} else if (fullName == "object.triangleNormals") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
for (const auto &item: list) {
auto subItems = item.split(",");
if (3 != subItems.size())
continue;
object->triangleNormals.push_back({subItems[0].toFloat(),
subItems[1].toFloat(),
subItems[2].toFloat()});
}
} else if (fullName == "object.triangleColors") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
for (const auto &item: list) {
object->triangleColors.push_back(QColor(item));
}
} else if (fullName == "object.triangleSourceNodes") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
std::vector<std::pair<QUuid, QUuid>> triangleSourceNodes;
for (const auto &item: list) {
int index = item.toInt();
if (index < 0 || index >= object->nodes.size()) {
triangleSourceNodes.push_back({QUuid(), QUuid()});
} else {
const auto &node = object->nodes[index];
triangleSourceNodes.push_back({node.partId, node.nodeId});
}
}
if (triangleSourceNodes.size() == object->triangles.size())
object->setTriangleSourceNodes(triangleSourceNodes);
} else if (fullName == "object.triangleVertexUvs") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
std::vector<QVector2D> uvs;
for (const auto &item: list) {
auto subItems = item.split(",");
if (2 != subItems.size())
continue;
uvs.push_back({subItems[0].toFloat(),
subItems[1].toFloat()});
}
std::vector<std::vector<QVector2D>> triangleVertexUvs;
if (0 == uvs.size() % 3) {
for (size_t i = 0; i < uvs.size(); i += 3) {
triangleVertexUvs.push_back({
uvs[i], uvs[i + 1], uvs[i + 2]
});
}
}
if (triangleVertexUvs.size() == object->triangles.size())
object->setTriangleVertexUvs(triangleVertexUvs);
} else if (fullName == "object.triangleVertexNormals") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
std::vector<QVector3D> normals;
for (const auto &item: list) {
auto subItems = item.split(",");
if (3 != subItems.size())
continue;
normals.push_back({subItems[0].toFloat(),
subItems[1].toFloat(),
subItems[2].toFloat()});
}
std::vector<std::vector<QVector3D>> triangleVertexNormals;
if (0 == normals.size() % 3) {
for (size_t i = 0; i < normals.size(); i += 3) {
triangleVertexNormals.push_back({
normals[i], normals[i + 1], normals[i + 2]
});
}
}
if (triangleVertexNormals.size() == object->triangles.size())
object->setTriangleVertexNormals(triangleVertexNormals);
} else if (fullName == "object.triangleTangents") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
std::vector<QVector3D> triangleTangents;
for (const auto &item: list) {
auto subItems = item.split(",");
if (3 != subItems.size())
continue;
triangleTangents.push_back({subItems[0].toFloat(),
subItems[1].toFloat(),
subItems[2].toFloat()});
}
if (triangleTangents.size() == object->triangles.size())
object->setTriangleTangents(triangleTangents);
} else if (fullName == "object.triangleLinks") {
QStringList list = reader.text().toString().split(QRegExp("\\s+"), QString::SkipEmptyParts);
std::vector<std::pair<std::pair<size_t, size_t>, std::pair<size_t, size_t>>> triangleLinks;
for (const auto &item: list) {
auto subItems = item.split(",");
if (4 != subItems.size())
continue;
triangleLinks.push_back({{(size_t)subItems[0].toInt(), (size_t)subItems[1].toInt()},
{(size_t)subItems[2].toInt(), (size_t)subItems[3].toInt()}});
}
if (triangleLinks.size() == object->triangles.size())
object->setTriangleLinks(triangleLinks);
}
}
}
}
| 51.973934 | 200 | 0.535449 | [
"object",
"vector"
] |
269dc60c99afd7f82bb984738a90a425cdd512ed | 733 | hpp | C++ | ToolkitNF/Widgets/SliderWidget.hpp | SlyVTT/Widget_NF_Nspire_and_PC | cdf921cc931eaa99ed765d1640253e060bc259cb | [
"MIT"
] | 3 | 2021-08-06T19:16:58.000Z | 2021-08-07T10:32:15.000Z | ToolkitNF/Widgets/SliderWidget.hpp | SlyVTT/Widget_NF_Nspire_and_PC | cdf921cc931eaa99ed765d1640253e060bc259cb | [
"MIT"
] | null | null | null | ToolkitNF/Widgets/SliderWidget.hpp | SlyVTT/Widget_NF_Nspire_and_PC | cdf921cc931eaa99ed765d1640253e060bc259cb | [
"MIT"
] | null | null | null | #ifndef SLIDERWIDGET_H
#define SLIDERWIDGET_H
#include "Widget.hpp"
class SliderWidget : public Widget
{
public:
SliderWidget();
SliderWidget( std::string l, unsigned int x, unsigned int y, unsigned int w, unsigned int h, Widget *p );
~SliderWidget();
int GetValueInt();
float GetValueFloat();
void SetRangeInt( int minvalue, int maxvalue);
void SetRangeFloat( float minvalue, float maxvalue );
virtual void Logic( void ) override;
virtual void Render( void ) override;
protected:
bool is_pressed = false;
int length_pixels = 0;
int position_cursor_pixels = 0;
int intmin=0;
int intmax=100;
float floatmin=0.0;
float floatmax=1.0;
};
#endif // SLIDERWIDGET_H
| 20.361111 | 109 | 0.686221 | [
"render"
] |
26a4c22fe73f6acf024e9df412f09e635e7b800a | 5,580 | cpp | C++ | client/src/process_packet_daily_update.cpp | Lukasz98/Free-Imperium | fadbcf0394474ce710b0370ea6762af2da958c53 | [
"MIT"
] | 2 | 2020-04-09T09:34:53.000Z | 2022-01-22T14:31:57.000Z | client/src/process_packet_daily_update.cpp | Lukasz98/Free-Imperium | fadbcf0394474ce710b0370ea6762af2da958c53 | [
"MIT"
] | null | null | null | client/src/process_packet_daily_update.cpp | Lukasz98/Free-Imperium | fadbcf0394474ce710b0370ea6762af2da958c53 | [
"MIT"
] | null | null | null | #include "process_packet.h"
void ProcessPacket::DailyUpdate(sf::Packet & packet, Gui & gui, std::vector<War> & wars, std::vector<std::unique_ptr<Province>> & provinces, std::vector<std::shared_ptr<Country>> & countries, Map & map)
{
std::unordered_map<std::string, std::string> values;
std::string strData;
float floatData = 0;
int intData = 0;
int countryCounter = 0;
packet >> countryCounter;
for (int i = 0; i < countryCounter; i++) {
packet >> strData;
values["countryName"] = strData;
packet >> floatData;
values["countryGold"] = ftos(floatData);
packet >> floatData;
values["countryIncome"] = ftos(floatData);
packet >> floatData;
values["armyMaintenance"] = ftos(floatData);
packet >> intData;
values["countryManpower"] = itos(intData);
packet >> intData;
values["countryManpowerRecovery"] = itos(intData);
packet >> strData;
values["date"] = strData;
packet >> intData;
values["dateSpeed"] = std::to_string(intData);
gui.Update(values, "topBar");
int provCount;
packet >> provCount;
for (int i = 0; i < provCount; i++) {
int id, manpower, development;
int population;
//float autonomy, unrest, prosperity, administration
float treasury;
float monthIncome, totalMonthIncome;
packet >> id;
//packet >> population;
packet >> manpower;
packet >> development;
//packet >> autonomy;
//packet >> unrest;
//packet >> prosperity;
//packet >> administration;
packet >> treasury;
packet >> monthIncome;
packet >> totalMonthIncome;
auto provIt = std::find_if(provinces.begin(), provinces.end(), [id](const std::unique_ptr<Province> & prov){
return prov->GetId() == id;
});
if (provIt != provinces.end()) {
//(*provIt).SetPopulation(population);
(*provIt)->SetManpower(manpower);
(*provIt)->SetDevelopment(development);
//(*provIt).SetAutonomy(autonomy);
//(*provIt).SetUnrest(unrest);
//(*provIt).SetProsperity(prosperity);
//(*provIt).SetAdministration(administration);
(*provIt)->SetTreasury(treasury);
(*provIt)->SetMonthIncome(monthIncome);
(*provIt)->SetTotalMonthIncome(totalMonthIncome);
}
}
int warsCount = 0;
packet >> warsCount;
for (int i = 0; i < warsCount; i++) {
int id;
packet >> id;
int score;
packet >> score;
int attackersCount, defendersCount;
std::vector<std::string> attackers, defenders;
packet >> attackersCount;
for (int att = 0; att < attackersCount; att++) {
std::string str;
packet >> str;
attackers.push_back(str);
}
packet >> defendersCount;
for (int def = 0; def < defendersCount; def++) {
std::string str;
packet >> str;
defenders.push_back(str);
}
for (auto & war : wars) {
if (war.GetId() == id) {
war.SetWarScore(score);
break;
}
}
}
int siegedProvincesCount;
packet >> siegedProvincesCount;
//for (auto & prov : provinces)
//prov->ResetSieging();
for (int i = 0; i < siegedProvincesCount; i++) {
std::string provName, siegeCountry;
int sieged, siegeSoldiers;
packet >> provName;
packet >> sieged;
packet >> siegeCountry;
packet >> siegeSoldiers;
auto provIt = std::find_if(provinces.begin(), provinces.end(), [provName](const std::unique_ptr<Province> & prov){
return prov->GetName() == provName;
});
if (provIt != provinces.end()) {
if (sieged == 100 && (*provIt)->GetSieged() != 100) {
auto scIt = std::find_if(countries.begin(), countries.end(), [siegeCountry](std::shared_ptr<Country> & ccc) {
return ccc->GetName() == siegeCountry;
});
if (scIt != countries.end())
map.DrawSieged((*provIt)->GetColor(), (*scIt)->GetColor());
}
(*provIt)->Sieging(siegeCountry, sieged, siegeSoldiers);
}
}
for (auto & prov : provinces) {
if (!prov->WasSiegeUpdated()) {
if (prov->GetSieged() != 0) {
auto scIt = std::find_if(countries.begin(), countries.end(), [cccc = prov->GetCountry()](std::shared_ptr<Country> & ccc) {
return ccc->GetName() == cccc;
});
if (scIt != countries.end())
map.DrawSieged(prov->GetColor(), (*scIt)->GetColor());
}
prov->ResetSieging();
}
}
}
}
| 36.470588 | 202 | 0.474014 | [
"vector"
] |
26a8c7d3c62b6fbf3a2cedfc48b793ac2cb855ca | 2,512 | cpp | C++ | UVA/vol-012/1234.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | 3 | 2017-05-12T14:45:37.000Z | 2020-01-18T16:51:25.000Z | UVA/vol-012/1234.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | UVA/vol-012/1234.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
inline char readchar() {
const int N = 4194304;
static char buf[N];
static char *p = buf, *end = buf;
bool fin = 0;
if (fin) return EOF;
if (p == end) {
if ((end = buf + fread(buf, 1, N, stdin)) == buf) {
fin = 1;
return EOF;
}
p = buf;
}
return *p++;
}
inline bool isdigit(char ch) { return ch>='0' && ch<='9'; }
inline int readInt() {
char ch;
unsigned int r=0;
while (!isdigit(ch=readchar()))
if (ch == EOF)
return EOF;
r = ch-'0';
while (isdigit(ch=readchar()))
r = (r<<3) + (r<<1) + ch-'0';
// skip trailing precision/etc
while (ch!=' ' && ch!='\n')
ch = readchar();
return r;
}
// -----------------------------------------------------------------
int par[10017];
int find(int u) { return par[u]<0 ? u : par[u]=find(par[u]); }
bool join(int u, int v) {
if ((u=find(u)) != (v=find(v))) {
if (par[v] < par[u])
swap(u, v);
par[u] += par[v];
par[v] = u;
return 1;
}
return 0;
}
// ---------------------------------------
#define MAXD 1007
struct Pair {
int u, v;
Pair(int u, int v):u(u),v(v){}
};
int maxd, mind;
vector<Pair> adj[MAXD];
void qClear() { maxd = 0; mind = MAXD; }
bool qEmpty() { return maxd<mind; }
void qPush(int u, int v, int d) {
if (d>=MAXD || d<0) while(1);
adj[d].push_back(Pair(u, v));
if (d < mind) mind = d;
if (d > maxd) maxd = d;
}
int qPop(int &u, int &v) {
Pair &p = adj[maxd].back();
u = p.u; v = p.v;
int d = maxd;
adj[maxd].pop_back();
while (!qEmpty() && adj[maxd].empty())
--maxd;
return d;
}
// ---------------------------------------
int main() {
int T = readInt();
while (T--) {
int n = readInt(),
m = readInt();
qClear();
memset(par, -1, n*sizeof(int));
for (int i=0; i<m; ++i) {
int u = readInt()-1,
v = readInt()-1,
d = readInt();
qPush(u, v, d);
}
int sum = 0;
for (int cnt=1; cnt<n && !qEmpty(); ) {
int u, v, d = qPop(u, v);
if (join(u, v)) ++cnt;
else sum += d;
}
for (int i=mind; i<=maxd; ++i) {
sum += i*adj[i].size();
adj[i].clear();
}
printf("%d\n", sum);
}
}
| 20.933333 | 68 | 0.416799 | [
"vector"
] |
26a9655cb8c10e5df932f2dad7a1ad3f7826f575 | 44,117 | hpp | C++ | tests/utilities.hpp | stjordanis/QuEST | 9494994729b42f21efc97be99738bf71dcffde34 | [
"MIT"
] | 281 | 2019-01-02T23:18:29.000Z | 2022-03-30T00:05:17.000Z | tests/utilities.hpp | stjordanis/QuEST | 9494994729b42f21efc97be99738bf71dcffde34 | [
"MIT"
] | 175 | 2019-01-02T18:04:36.000Z | 2022-02-24T10:42:08.000Z | tests/utilities.hpp | TysonRayJones/QuEST | 9494994729b42f21efc97be99738bf71dcffde34 | [
"MIT"
] | 117 | 2019-01-17T11:54:35.000Z | 2022-03-14T12:16:03.000Z | /** @file
* Unoptimised, analytic implementations of matrix operations used by QuEST's unit tests
*
* @defgroup unittest Unit tests
* Unit tests of the QuEST API, using Catch2 in C++14.
* @defgroup testutilities Unit test utilities
* Functions used in the unit testing. These are mostly unoptimised, analytic implementations
* of the complex linear algebra that QuEST ultimately effects on quantum states.
* These are not part of the QuEST API, and require C++14.
*
* @author Tyson Jones
*/
#ifndef QUEST_TEST_UTILS_H
#define QUEST_TEST_UTILS_H
#include "QuEST.h"
#include "QuEST_complex.h"
#include "catch.hpp"
#include <vector>
/** The single QuESTEnv environment created before the Catch tests begin,
* and destroyed thereafter.
*/
extern QuESTEnv QUEST_ENV;
/** The default number of qubits in the registers created for unit testing
* (both statevectors and density matrices). Creation of non-NUM_QUBITS sized
* Quregs should be justified in a comment.
* Note that the smaller this number is, the fewer nodes can be employed in
* distribution testing, since each node must contain at least one amplitude.
* Furthermore, the larger this number is, the greater the deviation of correct
* results from their expected value, due to numerical error; this is especially
* apparent for density matrices.
*/
#define NUM_QUBITS 5
/** A complex square matrix.
* Should be initialised with getZeroMatrix().
* These have all the natural linear-algebra operator overloads, including
* left-multiplication onto a vector.
*
* This data-structure is not partitioned between nodes in distributed mode.
* That is, every node has a complete copy, allowing for safe comparisons.
*
* @ingroup testutilities
* @author Tyson Jones
*/
typedef std::vector<std::vector<qcomp>> QMatrix;
/** A complex vector, which can be zero-initialised with QVector(numAmps).
* These have all the natural linear-algebra operator overloads.
*
* This data-structure is not partitioned between nodes in distributed mode.
* That is, every node has a complete copy, allowing for safe comparisons.
*
* @ingroup testutilities
* @author Tyson Jones
*/
typedef std::vector<qcomp> QVector;
/* (Excluded from Doxygen doc)
*
* Define QVector and QMatrix operator overloads.
* Note that QMatrix overloads don't simply use QVector
* overloads, since the complex vector dot product involves
* conjugation, which doesn't occur in complex matrix multiplication.
* Note too we also avoid defining operators in terms of other operators
* (e.g. minus is plus(negative times)) since compiler optimisations
* may change the order of operations and confuse the overloads invoked.
* Definition of division using multiplication can furthermore
* heighten numerical errors.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector operator + (const QVector& v1, const QVector& v2);
QVector operator - (const QVector& v1, const QVector& v2);
QVector operator * (const qcomp& a, const QVector& v);
QVector operator * (const QVector& v, const qcomp& a);
QVector operator / (const QVector& v, const qcomp& a);
qcomp operator * (const QVector &v1, const QVector& v2);
void operator += (QVector& v1, const QVector& v2);
void operator -= (QVector& v1, const QVector& v2);
void operator *= (QVector& v1, const qcomp& a);
void operator /= (QVector& v1, const qcomp& a);
QMatrix operator + (const QMatrix& m1, const QMatrix& m2);
QMatrix operator - (const QMatrix& m1, const QMatrix& m2);
QMatrix operator * (const qcomp& a, const QMatrix& m);
QMatrix operator * (const QMatrix& m, const qcomp& a);
QMatrix operator / (const QMatrix& m, const qcomp& a);
QMatrix operator * (const QMatrix& m1, const QMatrix& m2);
void operator += (QMatrix& m1, const QMatrix& m2);
void operator -= (QMatrix& m1, const QMatrix& m2);
void operator *= (QMatrix& m1, const qreal& a);
void operator /= (QMatrix& m1, const qreal& a);
void operator *= (QMatrix& m1, const QMatrix& m2);
QVector operator * (const QMatrix& m, const QVector& v);
/** Returns an equal-size copy of the given state-vector \p qureg.
* In GPU mode, this function involves a copy of \p qureg from GPU memory to RAM.
* In distributed mode, this involves an all-to-all broadcast of \p qureg.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector toQVector(Qureg qureg);
/** Returns a vector with the same of the full diagonal operator,
* populated with \p op's elements.
* In distributed mode, this involves an all-to-all broadcast of \p op.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector toQVector(DiagonalOp op);
/** Returns an equal-size copy of the given density matrix \p qureg.
* In GPU mode, this function involves a copy of \p qureg from GPU memory to RAM.
* In distributed mode, this involves an all-to-all broadcast of \p qureg.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(Qureg qureg);
/** Returns the matrix (where a=\p alpha, b=\p beta)
* {{a, -conj(b)}, {b, conj(a)}} using the \p qcomp complex type.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(Complex alpha, Complex beta);
/** Returns a copy of the given 2-by-2 matrix.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(ComplexMatrix2 src);
/** Returns a copy of the given 4-by-4 matrix.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(ComplexMatrix4 src);
/** Returns a copy of the given 2^\p N-by-2^\p N matrix
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(ComplexMatrixN src);
/** Returns a 2^\p N-by-2^\p N Hermitian matrix form of the specified
* weighted sum of Pauli products
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(qreal* coeffs, pauliOpType* paulis, int numQubits, int numTerms);
/** Returns a 2^\p N-by-2^\p N Hermitian matrix form of the PauliHamil
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(PauliHamil hamil);
/** Returns a 2^\p N-by-2^\p N complex diagonal matrix form of the DiagonalOp
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toQMatrix(DiagonalOp op);
/** Returns a diagonal complex matrix formed by the given vector
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix toDiagonalQMatrix(QVector vec);
/** Returns a \p ComplexMatrix2 copy of QMatix \p qm.
* Demands that \p qm is a 2-by-2 matrix.
*
* @ingroup testutilities
* @author Tyson Jones
*/
ComplexMatrix2 toComplexMatrix2(QMatrix qm);
/** Returns a \p ComplexMatrix4 copy of QMatix \p qm.
* Demands that \p qm is a 4-by-4 matrix.
*
* @ingroup testutilities
* @author Tyson Jones
*/
ComplexMatrix4 toComplexMatrix4(QMatrix qm);
/** Initialises \p cm with the values of \p qm.
* Demands that \p cm is a previously created ComplexMatrixN instance, with
* the same dimensions as \p qm.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void toComplexMatrixN(QMatrix qm, ComplexMatrixN cm);
/** Initialises the state-vector \p qureg to have the same amplitudes as \p vec.
* Demands \p qureg is a state-vector of an equal size to \p vec.
* In GPU mode, this function involves a copy from RAM to GPU memory.
* This function has no communication cost in distributed mode.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void toQureg(Qureg qureg, QVector vec);
/** Initialises the density matrix \p qureg to have the same amplitudes as \p mat.
* Demands \p qureg is a density matrix of equal dimensions to \p mat.
* In GPU mode, this function involves a copy from RAM to GPU memory.
* This function has no communication cost in distributed mode.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void toQureg(Qureg qureg, QMatrix mat);
/** Returns b (otimes) a. If b and a are state-vectors, the resulting kronecker
* product is the seperable state formed by joining the qubits in the state-vectors,
* producing |b>|a> (a is least significant)
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector getKroneckerProduct(QVector b, QVector a);
/** Returns a dim-by-dim square complex matrix, initialised to all zeroes.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getZeroMatrix(size_t dim);
/** Returns a dim-by-dim identity matrix
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getIdentityMatrix(size_t dim);
/** Returns the matrix exponential of a diagonal, square, complex matrix.
* This method explicitly checks that the passed matrix \p a is diagonal.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getExponentialOfDiagonalMatrix(QMatrix a);
/** Returns the matrix exponential of a kronecker product of pauli matrices
* (or of any involutory matrices), with exponent factor (-i \p angle / 2).
* This method will not explicitly check that the passed matrix \p a is
* kronecker product of involutory matrices, but will otherwise return an
* incorrect exponential.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getExponentialOfPauliMatrix(qreal angle, QMatrix a);
/** Returns the kronecker product of \p a and \p b, where \p a and \p b are
* square but possibly differently-sized complex matrices.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getKroneckerProduct(QMatrix a, QMatrix b);
/** Returns the 2^\p numQb-by-2^\p numQb unitary matrix which swaps qubits
* \p qb1 and \p qb2; the SWAP gate of not-necessarily-adjacent qubits.
* If \p qb1 == \p qb2, returns the identity matrix.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getSwapMatrix(int qb1, int qb2, int numQb);
/** Takes a 2^\p numTargs-by-2^\p numTargs matrix \p op and a returns a
* 2^\p numQubits-by-2^\p numQubits matrix where \p op is controlled on the given
* \p ctrls qubits. The union of {\p ctrls} and {\p targs} must be unique (though
* this is not explicitly checked), and every element must be >= 0 (not checked).
* The passed {\p ctrls} and {\p targs} arrays are unmodified.
*
* This funciton works by first swapping {\p targs} and {\p ctrls} (via swap unitaries)
* to be strictly increasing {0,1,...}, building controlled(\p op), tensoring it to
* the full Hilbert space, and then 'unswapping'. The returned matrix has form:
* swap1 ... swapN . controlled(\p op) . swapN ... swap1
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getFullOperatorMatrix(int* ctrls, int numCtrls, int *targs, int numTargs, QMatrix op, int numQubits);
/** Returns the matrix |\p ket><\p bra|, with ith-jth element \p ket(i) conj(\p bra(j)), since
* |\p ket><\p bra| = sum_i a_i|i> sum_j b_j* <j| = sum_{ij} a_i b_j* |i><j|.
* The dimensions of bra and ket must agree, and the returned square complex matrix
* has dimensions size(bra) x size(bra).
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getKetBra(QVector ket, QVector bra);
/** Returns the conjugate transpose of the complex square matrix \p a
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getConjugateTranspose(QMatrix a);
/** Returns a random integer between \p min (inclusive) and \p max (exclusive),
* from the uniform distribution.
* Demands that \p max > \p min.
*
* @ingroup testutilities
* @author Tyson Jones
*/
int getRandomInt(int min, int max);
/** Returns a random real between \p min (inclusive) and \p max (exclusive),
* from the uniform distribution.
* Demands that \p max > \p min.
*
* @ingroup testutilities
* @author Tyson Jones
*/
qreal getRandomReal(qreal min, qreal max);
/** Returns a random complex number within the square closing (-1-i) and (1+i),
* from a distribution uniformly randomising the individual real and imaginary
* components in their domains.
*
* @ingroup testutilities
* @author Tyson Jones
*/
qcomp getRandomComplex();
/** Returns a \p dim-length vector with random complex amplitudes in the
* square joining {-1-i, 1+i}, of an undisclosed distribution. The resulting
* vector is NOT L2-normalised.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector getRandomQVector(int dim);
/** Returns a \p dim-by-\p dim complex matrix, where the real and imaginary value of
* each element are independently random, under the standard normal distribution
* (mean 0, standard deviation 1).
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getRandomQMatrix(int dim);
/** Returns a uniformly random (under Haar) 2^\p numQb-by-2^\p numQb unitary matrix.
* This function works by first generating a complex matrix where
* each element is independently random; the real and imaginary component thereof are
* independent standard normally-distributed (mean 0, standard-dev 1).
* Then, the matrix is orthonormalised via the Gram Schmidt algorithm.
* The resulting unitary matrix MAY be uniformly distributed under the Haar
* measure, but we make no assurance.
* This routine may return an identity matrix if it was unable to sufficiently
* precisely produce a unitary of the given size.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getRandomUnitary(int numQb);
/** Returns a random \p numQb-length L2-normalised state-vector from an
* undisclosed distribution. This function works by randomly generating each
* complex amplitude, then L2-normalising.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector getRandomStateVector(int numQb);
/** Returns a random \p numQb-by-\p numQb density matrix, from an undisclosed
* distribution, in a very mixed state. This function works by generating
* 2^\p numQb random pure states, and mixing them with random probabilities.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getRandomDensityMatrix(int numQb);
/** Returns a random \p numQb-by-\p numQb density matrix, from an undisclosed
* distribution, which is pure (corresponds to a random state-vector)
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getRandomPureDensityMatrix(int numQb);
/** Returns a density matrix initialised into the given pure state
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getPureDensityMatrix(QVector state);
/** Returns the diagonal vector of the given matrix
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector getMatrixDiagonal(QMatrix matr);
/** Returns a random Kraus map of #`numOps` 2^\p numQb-by-2^\p numQb operators,
* from an undisclosed distribution.
* Note this method is very simple and cannot generate all possible Kraus maps.
* It works by generating \p numOps random unitary matrices, and randomly
* re-normalising them, such that the sum of ops[j]^dagger ops[j] = 1
*
* @ingroup testutilities
* @author Tyson Jones
*/
std::vector<QMatrix> getRandomKrausMap(int numQb, int numOps);
/** Returns a list of random real scalars, each in [0, 1], which sum to unity.
*
* @ingroup testutilities
* @author Tyson Jones
*/
std::vector<qreal> getRandomProbabilities(int numProbs);
/** Returns a list of random orthonormal complex vectors, from an undisclosed
* distribution.
*
* @ingroup testutilities
* @author Tyson Jones
*/
std::vector<QVector> getRandomOrthonormalVectors(int numQb, int numStates);
/** Returns a mixed density matrix formed from mixing the given pure states,
* which are assumed normalised, but not necessarily orthogonal.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QMatrix getMixedDensityMatrix(std::vector<qreal> probs, std::vector<QVector> states);
/** Returns an L2-normalised copy of \p vec, using Kahan summation for improved accuracy.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector getNormalised(QVector vec);
/** Returns the discrete fourier transform of vector in
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector getDFT(QVector in);
/** Returns the discrete fourier transform of a sub-partition of the vector in.
*
* @ingroup testutilities
* @author Tyson Jones
*/
QVector getDFT(QVector in, int* targs, int numTargs);
/** Returns the integer value of the targeted sub-register for the given
* full state index \p ind.
*
* @ingroup testutilities
* @author Tyson Jones
*/
long long int getValueOfTargets(long long int ind, int* targs, int numTargs);
/** Modifies \p dest by overwriting its submatrix (from top-left corner
* (\p r, \p c) to bottom-right corner (\p r + \p dest.size(), \p c + \p dest.size())
* with the complete elements of sub.
* This demands that dest.size() >= sub.size() + max(r,c).
*
* @ingroup testutilities
* @author Tyson Jones
*/
void setSubMatrix(QMatrix &dest, QMatrix sub, size_t r, size_t c);
/** Modifies the density matrix \p state to be the result of applying the multi-target operator
* matrix \p op, with the specified control and target qubits (in \p ctrls and \p targs
* respectively). This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 2^\p numTargs-by-2^\p numTargs matrix. Furthermore, every element of \p targs
* must not appear in \p ctrls (and vice-versa), though this is not explicitly checked.
* Elements of \p targs and \p ctrls should be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int* ctrls, int numCtrls, int *targs, int numTargs, QMatrix op);
/** Modifies the density matrix \p state to be the result of applying the two-target operator
* matrix \p op, with the specified control qubits (in \p ctrls).
* This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 4-by-4 matrix. Both \p targ1 and \p targ2 must not appear in \p ctrls,
* though this is not explicitly checked. Elements of \p ctrls, and \p targ1 and \p targ2,
* should be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int* ctrls, int numCtrls, int targ1, int targ2, QMatrix op);
/** Modifies the density matrix \p state to be the result of applying the single-target
* operator matrix \p op, with the specified control qubits (in \p ctrls).
* This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 2-by-2 matrix. \p target must not appear in \p ctrls,
* though this is not explicitly checked.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int* ctrls, int numCtrls, int target, QMatrix op);
/** Modifies the density matrix \p state to be the result of applying the multi-target
* operator matrix \p op, with no control qubits.
* This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 2^\p numTargs-by-2^\p numTargs matrix.
* Every element in \p targs should be unique, though this is not explicitly checked.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int *targs, int numTargs, QMatrix op);
/** Modifies the density matrix \p state to be the result of applying the single-control
* single-target operator matrix \p op.
* This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 2-by-2 matrix, and \p ctrl and \p targ should be different.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int ctrl, int targ, QMatrix op);
/** Modifies the density matrix \p state to be the result of applying the multi-target
* operator matrix \p op, with a single control qubit \p ctrl.
* This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 2^\p numTargs-by-2^\p numTargs matrix, and \p ctrl must not
* appear in \p targs (though this is not explicitly checked).
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int ctrl, int* targs, int numTargs, QMatrix op);
/** Modifies the density matrix \p state to be the result of applying the two-target
* operator matrix \p op, with a single control qubit \p ctrl.
* This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 4-by-4 matrix, and \p ctrl, \p targ1 and \p targ2 must be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int ctrl, int targ1, int targ2, QMatrix op);
/** Modifies the density matrix \p state to be the result of applying the single-target
* operator matrix \p op, with no control qubit.
* This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state} \, \text{op}^\dagger
* \f]
* even if \p op is not unitary (which is useful for applying Kraus operators).
*
* \p op must be a 2-by-2 matrix.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multipling it to \p state, then right-multiplying its
* conjugate transpose onto the result.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QMatrix &state, int targ, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the multi-target operator
* matrix \p op, with the specified control and target qubits (in \p ctrls and \p targs
* respectively). This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 2^\p numTargs-by-2^\p numTargs matrix. Furthermore, every element of \p targs
* must not appear in \p ctrls (and vice-versa), though this is not explicitly checked.
* Elements of \p targs and \p ctrls should be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int* ctrls, int numCtrls, int *targs, int numTargs, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the two-target operator
* matrix \p op, with the specified control qubits (in \p ctrls). This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 4-by-4 matrix. Furthermore, \p ctrls, \p targ1 and \p targ2 should
* all be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int* ctrls, int numCtrls, int targ1, int targ2, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the single-target operator
* matrix \p op, with the specified control qubits (in \p ctrls). This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 2-by-2 matrix. Furthermore, elements in \p ctrls and \p target should
* all be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int* ctrls, int numCtrls, int target, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the multi-target operator
* matrix \p op, with no contorl qubits. This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 2^\p numTargs-by-2^\p numTargs matrix. Furthermore, elements in \p targs should be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int *targs, int numTargs, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the single-target operator
* matrix \p op, with a single control qubit (\p ctrl). This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 2-by-2 matrix. Furthermore, \p ctrl and \p targ must be different.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int ctrl, int targ, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the multi-target operator
* matrix \p op, with a single control qubit (\p ctrl) This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 2^\p numTargs-by-2^\p numTargs matrix. Furthermore, elements
* in \p targs and \p ctrl should be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int ctrl, int* targs, int numTargs, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the two-target operator
* matrix \p op, with a single control qubit (\p ctrl). This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 4-by-4 matrix. Furthermore, \p ctrl, \p targ1 and \p targ2 should
* all be unique.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int ctrl, int targ1, int targ2, QMatrix op);
/** Modifies the state-vector \p state to be the result of applying the single-target operator
* matrix \p op, with no contorl qubits. This updates \p state under
* \f[
\text{state} \to \text{op} \, \text{state}
* \f]
* even if \p op is not unitary.
*
* \p op must be a 2-by-2 matrix.
*
* This function works by computing getFullOperatorMatrix() from the given
* arguments, and left-multiplying it onto \p state.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceOp(QVector &state, int targ, QMatrix op);
/** Modifies the state-vector \p state to be the result of left-multiplying the multi-target operator
* matrix \p op, with the specified control and target qubits (in \p ctrls and \p targs
* respectively). This is an alias of applyReferenceOp(), since operators are always
* left-multiplied as matrices onto state-vectors.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceMatrix(QVector &state, int* ctrls, int numCtrls, int *targs, int numTargs, QMatrix op);
/** Modifies the density matrix \p state to be the result of left-multiplying the multi-target operator
* matrix \p op, with the specified control and target qubits (in \p ctrls and \p targs
* respectively). Here, \p op is treated like a simple matrix and is hence left-multiplied
* onto the state once.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void applyReferenceMatrix(QMatrix &state, int* ctrls, int numCtrls, int *targs, int numTargs, QMatrix op);
/** Performs a hardware-agnostic comparison of the given quregs, checking
* whether the difference between the real and imaginary components of every amplitude
* is smaller than the QuEST_PREC-specific REAL_EPS (defined in QuEST_precision) precision.
* This function demands that \p qureg1 and \p qureg2 are of the same type
* (i.e. both state-vectors or both density matrices), and of an equal number
* of qubits.
*
* In GPU mode, this function involves a GPU to CPU memory copy overhead.
* In distributed mode, it involves a all-to-all single-int broadcast.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(Qureg qureg1, Qureg qureg2);
/** Performs a hardware-agnostic comparison of state-vector \p qureg to \p vec, checking
* whether the difference between the real and imaginary components of every amplitude
* is smaller than the QuEST_PREC-specific REAL_EPS (defined in QuEST_precision) precision.
* This function demands \p qureg is a state-vector, and that \p qureg and
* \p vec have the same number of amplitudes.
*
* In GPU mode, this function involves a GPU to CPU memory copy overhead.
* In distributed mode, it involves a all-to-all single-int broadcast.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(Qureg qureg, QVector vec);
/** Performs a hardware-agnostic comparison of density-matrix \p qureg to \p matr, checking
* whether the difference between the real and imaginary components of every amplitude
* is smaller than the QuEST_PREC-specific REAL_EPS (defined in QuEST_precision) precision.
* This function demands \p qureg is a density matrix, and that \p qureg and \p matr have
* equal dimensions.
*
* In GPU mode, this function involves a GPU to CPU memory copy overhead.
* In distributed mode, it involves a all-to-all single-int broadcast.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(Qureg qureg, QMatrix matr);
/** Performs a hardware-agnostic comparison of the given quregs, checking
* whether the difference between the real and imaginary components of every amplitude
* is smaller than \p precision.
* This function demands that \p qureg1 and \p qureg2 are of the same type
* (i.e. both state-vectors or both density matrices), and of an equal number
* of qubits.
*
* In GPU mode, this function involves a GPU to CPU memory copy overhead.
* In distributed mode, it involves a all-to-all single-int broadcast.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(Qureg qureg1, Qureg qureg2, qreal precision);
/** Performs a hardware-agnostic comparison of state-vector \p qureg to \p vec, checking
* whether the difference between the real and imaginary components of every amplitude
* is smaller than \p precision.
* This function demands \p qureg is a state-vector, and that \p qureg and
* \p vec have the same number of amplitudes.
*
* In GPU mode, this function involves a GPU to CPU memory copy overhead.
* In distributed mode, it involves a all-to-all single-int broadcast.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(Qureg qureg, QVector vec, qreal precision);
/** Performs a hardware-agnostic comparison of density-matrix \p qureg to \p matr, checking
* whether the difference between the real and imaginary components of every amplitude
* is smaller than \p precision.
* This function demands \p qureg is a density matrix, and that \p qureg and \p matr have
* equal dimensions.
*
* In GPU mode, this function involves a GPU to CPU memory copy overhead.
* In distributed mode, it involves a all-to-all single-int broadcast.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(Qureg qureg, QMatrix matr, qreal precision);
/** Returns true if the absolute value of the difference between every amplitude in
* vectors \p a and \p b is less than \p REAL_EPS.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(QVector a, QVector b);
/** Returns true if the absolute value of the difference between every amplitude in
* matrices \p a and \p b is less than \p REAL_EPS.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(QMatrix a, QMatrix b);
/** Returns true if the absolute value of the difference between every element in
* \p vec and those implied by \p reals and \p imags, is less than \p REAL_EPS.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(QVector vec, qreal* reals, qreal* imags);
/** Returns true if the absolute value of the difference between every element in
* \p vec (which must be strictly real) and those implied by \p reals, is less
* than \p REAL_EPS.
*
* @ingroup testutilities
* @author Tyson Jones
*/
bool areEqual(QVector vec, qreal* reals);
/** Returns the unit-norm complex number exp(i*\p phase). This function uses the
* Euler formula, and avoids problems with calling exp(__complex__) in a platform
* agnostic way
*/
qcomp expI(qreal phase);
/** Returns log2 of numbers which must be gauranteed to be 2^n
*
* @ingroup testutilities
* @author Tyson Jones
*/
unsigned int calcLog2(long unsigned int res);
/** Populates the \p coeffs array with random qreals in (-5, 5), and
* populates \p codes with random Pauli codes
*
* @ingroup testutilities
* @author Tyson Jones
*/
void setRandomPauliSum(qreal* coeffs, pauliOpType* codes, int numQubits, int numTerms);
/** Populates \p hamil with random coefficients and pauli codes
*
* @ingroup testutilities
* @author Tyson Jones
*/
void setRandomPauliSum(PauliHamil hamil);
/** Populates \p hamil with random coefficients and a random amount number of
* PAULI_I and PAULI_Z operators.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void setRandomDiagPauliHamil(PauliHamil hamil);
/** Returns the two's complement signed encoding of the unsigned number decimal,
* which must be a number between 0 and 2^numBits (exclusive). The returned number
* lies in [-2^(numBits-1), 2^(numBits-1)-1]
*
* @ingroup testutilities
* @author Tyson Jones
*/
long long int getTwosComplement(long long int decimal, int numBits);
/** Return the unsigned value of a number, made of `#numBits` bits, which under
* two's complement, encodes the signed number twosComp. The returned number
* lies in [0, 2^(numBits)-1]
*
* @ingroup testutilities
* @author Tyson Jones
*/
long long int getUnsigned(long long int twosComp, int numBits);
/** Modifies the given diagonal matrix such that the diagonal elements which
* correspond to the coordinates in overrideInds are replaced with exp(i phase), as
* prescribed by overridePhases. This function assumes that the given registers
* are contiguous, are in order of increasing significance, and that the matrix
* is proportionately sized and structured to act on the space of all registers
* combined. Overrides can be repeated, and only the first encountered for a given
* index will be effected (much like applyMultiVarPhaseFuncOverrides()).
*
* @ingroup testutilities
* @author Tyson Jones
*/
void setDiagMatrixOverrides(QMatrix &matr, int* numQubitsPerReg, int numRegs, enum bitEncoding encoding, long long int* overrideInds, qreal* overridePhases, int numOverrides);
/** Modifies outFn to be a filename of format prefix_NUM.txt where NUM
* is a new unique integer so far. This is useful for getting unique filenames for
* independent test cases of functions requiring reading/writing to file, to
* avoid IO locks (especially common in distributed mode).
*
* @ingroup testutilities
* @author Tyson Jones
*/
void setUniqueFilename(char* outFn, char* prefix);
/** Writes contents to the file with filename fn, which is created and/or overwritten.
* In distributed mode, the master node writes while the other nodes wait until complete.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void writeToFileSynch(char* fn, const string& contents);
/** Deletes all files with filename starting with prefix. In distributed mode, the
* master node deletes while the other nodes wait until complete.
*
* @ingroup testutilities
* @author Tyson Jones
*/
void deleteFilesWithPrefixSynch(char* prefix);
// makes below signatures more concise
template<class T> using CatchGen = Catch::Generators::GeneratorWrapper<T>;
/** Returns a Catch2 generator of every length-\p sublen sublist of length-\p len
* \p list, in increasing lexographic order. This generates every fixed-length
* combination of the given list and every permutation of each.
& If the sublist length is the full list length, this generator produces every
* permutation correctly. Note that the sublist must not be modified, else further
& generation may break (QuEST's internal functions will indeed modify but restore
* the qubit index lists given to them, which is ok).
* Assumes \p list contains no duplicates, otherwise the generated sublists may be
* duplicated.
*
* This function can be used like
*
* int list[4] = {1,2,3,4};
* int sublen = 2;
* int* sublist = GENERATE_COPY( sublists(list, 4, sublen) );
*
* to generate {1,2}, {1,3}, {1,4}, {2,1}, {2,3}, {2,4}, {3,1}, {3,2}, {3, 4},
* {4,1}, {4,2}, {4, 3}.
*
* @ingroup testutilities
* @author Tyson Jones
*/
CatchGen<int*> sublists(int* list, int len, int sublen);
/** Returns a Catch2 generator of every length-\p sublen sublist of the elements
* generated by \p gen, which exclude all elements in \p exclude, in increasing lexographic order.
* This generates every fixed-length combination of \p gen's elements the nominated exclusions,
* and every permutation of each.
*
* There is on need for the elements of \p exclude to actually appear in those of \p gen.
* \p sublen must less than or equal to the number of elements in \p gen, after
* the nominated exclusions.
*
* Note that the sublist must not be modified, else further generation may break (QuEST's
* internal functions will indeed modify but restore the qubit index lists given
* to them, which is ok). Assumes \p list contains no duplicates,
* otherwise the generated sublists may be duplicated.
*
* This function can be used like
*
* int sublen = 2;
* int exclude[2] = {3,4};
* int* sublist = GENERATE_COPY( sublists(range(1,6), sublen, exclude, 2) );
*
* to generate {1,2}, {1,5}, {2,1}, {2,5}, {5,1}, {5,2}
*
* @ingroup testutilities
* @author Tyson Jones
*/
CatchGen<int*> sublists(CatchGen<int>&& gen, int numSamps, const int* exclude, int numExclude);
/** Returns a Catch2 generator of every length-\p sublen sublist of the elements
* generated by \p gen which exclude element \p excluded, in increasing lexographic order.
* This generates every fixed-length combination of \p gen's elements the nominated exclusions,
* and every permutation of each.
*
* \p sublen must less than or equal to the number of elements in \p gen, after
* the nominated exclusion. There is no need for \p excluded to actually appear
* in the elements of \p gen.
*
* Note that the sublist must not be modified, else further generation may break (QuEST's
* internal functions will indeed modify but restore the qubit index lists given
* to them, which is ok). Assumes \p list contains no duplicates,
* otherwise the generated sublists may be duplicated.
*
* This function can be used like
*
* int sublen = 2;
* int excluded = 1;
* int* sublist = GENERATE_COPY( sublists(range(1,4), sublen, excluded) );
*
* to generate {2,3}, {3,2}.
*
* @ingroup testutilities
* @author Tyson Jones
*/
CatchGen<int*> sublists(CatchGen<int>&& gen, int numSamps, int excluded);
/** Returns a Catch2 generator of every length-\p sublen sublist of the elements
* generated by \p gen, in increasing lexographic order. This generates every fixed-length
* combination of \p gen's elements, and every permutation of each.
* Note that the produced sublist must not be modified, else further
* generation may break (QuEST's internal functions will indeed modify but restore
* the qubit index lists given to them, which is ok).
* Assumes \p list contains no duplicates, otherwise the generated sublists may be
* duplicated.
*
* This function can be used like
*
* int sublen = 2;
* int* sublist = GENERATE_COPY( sublists(list, 4, sublen) );
*
* to generate {1,2}, {1,3}, {1,4}, {2,1}, {2,3}, {2,4}, {3,1}, {3,2}, {3, 4},
* {4,1}, {4,2}, {4, 3}.
*
* @ingroup testutilities
* @author Tyson Jones
*/
CatchGen<int*> sublists(CatchGen<int>&& gen, int sublen);
/** Returns a Catch2 generator of every \p numBits-length bit-set,
* in increasing lexographic order,
* where left-most (zero index) bit is treated as LEAST significant (opposite
* typical convention). Note that the produced bitset must not be modified during generation.
*
* This function can be used like
*
* int* bits = GENERATE( bitsets(3) );
*
* to produce {0,0,0}, {1,0,0}, {0,1,0}, {1,1,0}, {0,0,1}, {1,0,1}, {0,1,1}, {1,1,1}.
*
* @ingroup testutilities
* @author Tyson Jones
*/
CatchGen<int*> bitsets(int numBits);
/** Returns a Catch2 generator of every \p numDigits-length sequence in the given
* \p base, in increasing lexographic order,
* where left-most (zero index) bit is treated as LEAST significant (opposite
* typical convention). Note that the sequence must not be modified during generation.
*
* This function can be used like
*
* int base = 3;
* int numDigits = 2;
* int* seq = GENERATE_COPY( sequences(base, numDigits) );
*
* to produce {0,0}, {1,0}, {2,0}, {0,1}, {1,1}, {2,1}, {0,2}, {1,2}, {2,2}.
*
* @ingroup testutilities
* @author Tyson Jones
*/
CatchGen<int*> sequences(int base, int numDigits);
/** Returns a Catch2 generator of every \p numPaulis-length set of Pauli-matrix
* types (or base-4 integers).
* Generates in increasing lexographic order, where the left-most (zero index)
* pauli is treated as LEAST significant.
* Note that the sequence must not be modified during generation.
*
* This function can be used like
*
* pauliOpType* set = GENERATE( pauliseqs(2) );
*
* to produce {I,I}, {X,I}, {Y,I}, {Z,I}, {I,X}, {X,X}, {Y,X}, {Z,X}, {I,Y},
* {X,Y}, {Y,Y}, {Z,Y}, {I,Z}, {X,Z}, {Y,Z}, {Z,Z}/
*
* @ingroup testutilities
* @author Tyson Jones
*/
CatchGen<pauliOpType*> pauliseqs(int numPaulis);
#endif // QUEST_TEST_UTILS_H
| 37.229536 | 175 | 0.714033 | [
"vector",
"transform"
] |
26b01f9e89284769c622109d3f859417f41d524b | 984 | cpp | C++ | visualstudio/litegraph_cpp/main.cpp | h3r/litegraph_native | d67d6f9e3fc0d6887829df5d6038fcc81ca0de7b | [
"MIT"
] | 8 | 2020-02-21T14:11:39.000Z | 2022-02-27T02:15:15.000Z | visualstudio/litegraph_cpp/main.cpp | h3r/litegraph_native | d67d6f9e3fc0d6887829df5d6038fcc81ca0de7b | [
"MIT"
] | 1 | 2020-02-28T23:58:51.000Z | 2020-02-28T23:58:51.000Z | visualstudio/litegraph_cpp/main.cpp | h3r/litegraph_native | d67d6f9e3fc0d6887829df5d6038fcc81ca0de7b | [
"MIT"
] | 3 | 2020-09-07T06:20:09.000Z | 2022-02-27T02:15:16.000Z |
#include <fstream>
#include <iostream>
#include <vector>
#include "../../src/litegraph.h"
//used only for sleep and keypress
#include <windows.h>
int main()
{
std::cout << "LiteGraph v0.1\n*********************\n";
std::string filename;
filename = "data/events2.JSON";
//this will register all the base nodes
LiteGraph::init();
//register here your own nodes
//...
std::cout << "Node types registered: " << LiteGraph::node_types.size() << std::endl;
std::cout << "Loading graph..." << filename << std::endl;
std::string data = LiteGraph::getFileContent( filename.c_str() );
if (!data.size())
std::cout << "file not found or empty:" << filename << std::endl;
LiteGraph::LGraph mygraph;
if (!mygraph.configure(data))
exit(1);
std::cout << "Starting graph execution ****" << std::endl;
while (1)
{
mygraph.runStep(0.01f);
Sleep(10);
if ( (GetKeyState(' ') | GetKeyState(27)) & 0x8000 ) /*Check if high-order bit is set (1 << 15)*/
break;
}
}
| 22.883721 | 99 | 0.619919 | [
"vector"
] |
564c2c064b35709829f3b865b8e1c2c2dd3c387c | 1,296 | cpp | C++ | c++/leetcode/0289-Game_of_Life-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | 1 | 2020-03-02T10:56:22.000Z | 2020-03-02T10:56:22.000Z | c++/leetcode/0289-Game_of_Life-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | c++/leetcode/0289-Game_of_Life-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | // 289 Game of Life
// https://leetcode.com/problems/game-of-life
// version: 1; create time: 2020-02-01 17:28:25;
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
const int m = board.size();
if (m == 0) return;
const int n = board[0].size();
if (n == 0) return;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int cnt = 0;
constexpr int offsets[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1,1},{1,-1},{-1,-1}};
for (int k = 0; k < 8; ++k) {
const int ni = i + offsets[k][0];
const int nj = j + offsets[k][1];
if (ni < 0 || ni >= m || nj < 0 || nj >= n) continue;
cnt += board[ni][nj] & 0x1;
}
if (board[i][j]) {
if (cnt == 2 || cnt == 3) {
board[i][j] |= 0x2;
}
} else {
if (cnt == 3) {
board[i][j] |= 0x2;
}
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
board[i][j] >>= 1;
}
}
}
};
| 30.857143 | 102 | 0.325617 | [
"vector"
] |
564e7b4fcc10f76bf0081f160f5e87193236183a | 1,630 | hpp | C++ | VVGL/include/GLContextWindowBacking.hpp | mrRay/VVISF-GL | 96b00da11e4497da304041ea2a5ffc6e3a8c9454 | [
"BSD-3-Clause"
] | 24 | 2019-01-17T17:56:18.000Z | 2022-02-27T19:57:13.000Z | VVGL/include/GLContextWindowBacking.hpp | mrRay/VVISF-GL | 96b00da11e4497da304041ea2a5ffc6e3a8c9454 | [
"BSD-3-Clause"
] | 6 | 2019-01-17T17:17:12.000Z | 2020-06-19T11:27:50.000Z | VVGL/include/GLContextWindowBacking.hpp | mrRay/VVISF-GL | 96b00da11e4497da304041ea2a5ffc6e3a8c9454 | [
"BSD-3-Clause"
] | 2 | 2020-12-25T04:57:31.000Z | 2021-03-02T22:05:31.000Z | #ifndef VVGL_GLContextWindowBacking_hpp
#define VVGL_GLContextWindowBacking_hpp
#if defined(VVGL_SDK_WIN)
#include <Windows.h>
#include <tchar.h>
#include <iostream>
#include <functional>
#include "VVGL.hpp"
/* This class exists to wrap an invisible/offscreen window from the Windows SDK- it exists because we need the window's "device context"
to create an OpenGL context (GL contexts on windows appear to require actual windows as backings to access hardware acceleration).
you'll probably never have to create an instance of this class manually- GLContext will do so automatically */
namespace VVGL
{
class GLContextWindowBacking {
public:
using RenderCallback = std::function<void (const GLContextWindowBacking & inWinBacking)>;
private:
HWND _wnd;
HDC _dc;
// it's not being used at the moment but this render callback could be used to perform drawing when the backing window receives a paint command
RenderCallback _renderCallback = nullptr;
public:
GLContextWindowBacking(const Rect & inRect = Rect(0, 0, 640, 480));
~GLContextWindowBacking();
GLContextWindowBacking& operator=(const GLContextWindowBacking &) = delete;
HWND wnd() { return _wnd; }
HDC dc() { return _dc; }
void performRenderCallback() { if (_renderCallback != nullptr) _renderCallback(*this); }
static GLContextWindowBackingRef CreateWindowBackingRef(const Rect & inRect=Rect(0,0,640,480)){
return std::make_shared<GLContextWindowBacking>(inRect);
}
};
} // namespace VVGL
#endif // VVGL_SDK_WIN
#endif // VVGL_GLContextWindowBacking_hpp | 25.076923 | 145 | 0.734969 | [
"render"
] |
565f56c8e9d1f03f277a0287df474adf0d683e0a | 6,580 | cpp | C++ | test_gui/main_window.cpp | ashaduri/qt-cctalk | fcd8165d7fed941e7afdf5048bc4b962ad64c858 | [
"BSD-3-Clause"
] | 4 | 2021-02-18T12:50:37.000Z | 2022-02-14T11:38:00.000Z | test_gui/main_window.cpp | ashaduri/qt-cctalk | fcd8165d7fed941e7afdf5048bc4b962ad64c858 | [
"BSD-3-Clause"
] | null | null | null | test_gui/main_window.cpp | ashaduri/qt-cctalk | fcd8165d7fed941e7afdf5048bc4b962ad64c858 | [
"BSD-3-Clause"
] | 1 | 2022-01-10T11:00:08.000Z | 2022-01-10T11:00:08.000Z | /**************************************************************************
Copyright: (C) 2014 - 2021 Alexander Shaduri
License: BSD-3-Clause
***************************************************************************/
#include <QMessageBox>
#include <QTimer>
#include <Qt>
#include <QSerialPortInfo>
#include <QAction>
#include <QPointer>
#include <cmath>
#include "cctalk/helpers/debug.h"
#include "app_settings.h"
#include "main_window.h"
#include "ui_main_window.h"
#include "gui_application.h"
#include "cctalk_tools.h"
using qtcc::CcDeviceState;
MainWindow::MainWindow()
{
ui.reset(new Ui::MainWindow());
ui->setupUi(this);
// Still show the tooltips if the window is unfocusted.
setAttribute(Qt::WA_AlwaysShowToolTips);
// Main menubar
{
QPointer<QAction> action_quit(new QAction(QObject::tr("&Quit"), this));
connect(action_quit.data(), SIGNAL(triggered()), this, SLOT(onQuitActionTriggered()));
ui->menu_file->addAction(action_quit.data());
}
connect(ui->start_stop_bill_validator_button, SIGNAL(clicked(bool)), this, SLOT(onStartStopBillValidatorClicked()));
connect(ui->toggle_bill_accept_button, SIGNAL(clicked(bool)), this, SLOT(onToggleBillAcceptClicked()));
connect(ui->start_stop_coin_acceptor_button, SIGNAL(clicked(bool)), this, SLOT(onStartStopCoinAcceptorClicked()));
connect(ui->toggle_coin_accept_button, SIGNAL(clicked(bool)), this, SLOT(onToggleCoinAcceptClicked()));
// Restore geometry
if (AppSettings::valueExists(QStringLiteral("main_window/geometry"))) {
restoreGeometry(AppSettings::getValue<QByteArray>(QStringLiteral("main_window/geometry")));
} else {
move(QPoint(10, 10));
resize(QSize(900, 600));
}
// Restore toolbar / dockwidget states
if (AppSettings::valueExists(QStringLiteral("main_window/window_state"))) {
restoreState(AppSettings::getValue<QByteArray>(QStringLiteral("main_window/window_state")));
}
QTimer::singleShot(0, this, SLOT(runSerialThreads()));
}
MainWindow::~MainWindow()
{
debug_out_dump("MainWindow deleting...");
}
void MainWindow::closeEvent(QCloseEvent* ev)
{
if (this->closeRequested()) {
ev->accept(); // accept close
} else {
ev->ignore();
}
}
bool MainWindow::closeRequested()
{
// Save geometry and toolbar / dock window state
AppSettings::setValue(QStringLiteral("main_window/geometry"), saveGeometry());
AppSettings::setValue(QStringLiteral("main_window/window_state"), saveState());
GuiApplication::quit();
return true; // won't reach
}
void MainWindow::logMessage(QString msg)
{
msg = ccProcessLoggingMessage(msg, true);
if (!msg.isEmpty()) {
ui->status_log_textedit->append(msg);
}
}
void MainWindow::runSerialThreads()
{
// Set cctalk options
QString setup_error = setUpCctalkDevices(&bill_validator_, &coin_acceptor_, [=](QString message) {
logMessage(message);
});
if (!setup_error.isEmpty()) {
logMessage(setup_error);
return;
}
// Bill validator
{
connect(&bill_validator_, &qtcc::CctalkDevice::creditAccepted, [this]([[maybe_unused]] quint8 id, const qtcc::CcIdentifier& identifier) {
const char* prop_name = "integral_value";
quint64 existing_value = ui->entered_bills_lineedit->property(prop_name).toULongLong();
quint64 divisor = 0;
quint64 value = identifier.getValue(divisor); // in cents
existing_value += value;
ui->entered_bills_lineedit->setProperty(prop_name, existing_value);
ui->entered_bills_lineedit->setText(QString::number(double(existing_value) / std::pow(10., int(divisor)), 'f', 2));
});
}
// Coin acceptor
{
connect(&coin_acceptor_, &qtcc::CctalkDevice::creditAccepted, [this]([[maybe_unused]] quint8 id, const qtcc::CcIdentifier& identifier) {
const char* prop_name = "integral_value";
quint64 existing_value = ui->entered_coins_lineedit->property(prop_name).toULongLong();
quint64 divisor = 0;
quint64 value = identifier.getValue(divisor); // in cents
existing_value += value;
ui->entered_coins_lineedit->setProperty(prop_name, existing_value);
ui->entered_coins_lineedit->setText(QString::number(double(existing_value) / std::pow(10., int(divisor)), 'f', 2));
});
}
}
void MainWindow::onStartStopBillValidatorClicked()
{
if (bill_validator_.getDeviceState() == CcDeviceState::ShutDown) {
bill_validator_.getLinkController().openPort([this](const QString& error_msg) {
if (error_msg.isEmpty()) {
bill_validator_.initialize([]([[maybe_unused]] const QString& init_error_msg) { });
}
});
} else {
bill_validator_.shutdown([this]([[maybe_unused]] const QString& error_msg) {
// Close the port once the device is "shut down"
bill_validator_.getLinkController().closePort();
});
}
}
void MainWindow::onToggleBillAcceptClicked()
{
bool accepting = bill_validator_.getDeviceState() == CcDeviceState::NormalAccepting;
bool rejecting = bill_validator_.getDeviceState() == CcDeviceState::NormalRejecting;
if (accepting || rejecting) {
CcDeviceState new_state = accepting ? CcDeviceState::NormalRejecting : CcDeviceState::NormalAccepting;
bill_validator_.requestSwitchDeviceState(new_state, []([[maybe_unused]] const QString& error_msg) {
// nothing
});
} else {
logMessage(tr("! Cannot toggle bill accept mode, the device is in %1 state.")
.arg(ccDeviceStateGetDisplayableName(bill_validator_.getDeviceState())));
}
}
void MainWindow::onStartStopCoinAcceptorClicked()
{
if (coin_acceptor_.getDeviceState() == CcDeviceState::ShutDown) {
coin_acceptor_.getLinkController().openPort([this](const QString& error_msg) {
if (error_msg.isEmpty()) {
coin_acceptor_.initialize([]([[maybe_unused]] const QString& init_error_msg) { });
}
});
} else {
coin_acceptor_.shutdown([this]([[maybe_unused]] const QString& error_msg) {
// Close the port once the device is "shut down"
coin_acceptor_.getLinkController().closePort();
});
}
}
void MainWindow::onToggleCoinAcceptClicked()
{
bool accepting = coin_acceptor_.getDeviceState() == CcDeviceState::NormalAccepting;
bool rejecting = coin_acceptor_.getDeviceState() == CcDeviceState::NormalRejecting;
if (accepting || rejecting) {
CcDeviceState new_state = accepting ? CcDeviceState::NormalRejecting : CcDeviceState::NormalAccepting;
coin_acceptor_.requestSwitchDeviceState(new_state, []([[maybe_unused]] const QString& error_msg) {
// nothing
});
} else {
logMessage(tr("! Cannot toggle coin accept mode, the device is in %1 state.")
.arg(ccDeviceStateGetDisplayableName(bill_validator_.getDeviceState())));
}
}
void MainWindow::onQuitActionTriggered()
{
this->closeRequested();
}
| 28.733624 | 139 | 0.717477 | [
"geometry"
] |
566b109510a23683f0c18ee4336a70b2b3b394cb | 6,016 | cpp | C++ | EditorLib/LogFile.cpp | elix22/UrhoEditor | 8b2578610b21e60f4126e351a1c7e01d639be695 | [
"MIT"
] | 23 | 2017-06-14T02:22:10.000Z | 2021-11-25T05:09:21.000Z | EditorLib/LogFile.cpp | elix22/UrhoEditor | 8b2578610b21e60f4126e351a1c7e01d639be695 | [
"MIT"
] | null | null | null | EditorLib/LogFile.cpp | elix22/UrhoEditor | 8b2578610b21e60f4126e351a1c7e01d639be695 | [
"MIT"
] | 22 | 2017-06-15T12:09:23.000Z | 2021-01-02T13:05:15.000Z | #include "LogFile.h"
#include "Platform/VideoCard.h"
//#include <CL/cl.hpp>
#include <QDateTime>
#include <QSysInfo>
#include <vector>
#ifdef WIN32
#include <Windows.h>
#endif
#ifdef WIN32
static void GetCPUInfo(QString& brandName, int& coreCount, double& cpuSpeed)
{
int CPUInfo[4] = { -1 };
unsigned nExIds, i = 0;
char CPUBrandString[0x40];
// Get the information associated with each extended ID.
__cpuid(CPUInfo, 0x80000000);
nExIds = CPUInfo[0];
for (i = 0x80000000; i <= nExIds; ++i)
{
__cpuid(CPUInfo, i);
// Interpret CPU brand string
if (i == 0x80000002)
memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
else if (i == 0x80000003)
memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
else if (i == 0x80000004)
memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
}
//string includes manufacturer, model and clockspeed
brandName = CPUBrandString;
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
coreCount = sysInfo.dwNumberOfProcessors;
wchar_t Buffer[_MAX_PATH];
DWORD BufSize = _MAX_PATH;
DWORD dwMHz = _MAX_PATH;
HKEY hKey;
// open the key where the proc speed is hidden:
long lError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKey);
if (lError != ERROR_SUCCESS)
{
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, lError, 0, Buffer, _MAX_PATH, 0);
wprintf(Buffer);
return;
}
// query the key:
RegQueryValueEx(hKey, L"~MHz", NULL, NULL, (LPBYTE)&dwMHz, &BufSize);
cpuSpeed = (double)dwMHz;
}
#endif
static QString size_human(unsigned size)
{
float num = size;
QStringList list;
list /*<< "KB"*/ << "MB" << "GB" << "TB";
QStringListIterator i(list);
QString unit("kb");
while (num >= 1024.0 && i.hasNext())
{
unit = i.next();
num /= 1024.0;
}
return QString().setNum(num, 'f', 2) + " " + unit;
}
LogFile* LogFile::instance_ = 0x0;
LogFile::LogFile(const QString& path, const QString& logName, const QString& extraHeaderData) :
QObject(),
file_(path),
logName_(logName)
{
instance_ = this;
file_.open(QIODevice::WriteOnly);
stream_ = new QTextStream(&file_);
#ifndef SPRUE_HTML_LOG
QTextStream& str = *stream_;
#ifdef WIN32
MEMORYSTATUSEX data;
GlobalMemoryStatusEx(&data);
ULONGLONG memoryBytes;
GetPhysicallyInstalledSystemMemory(&memoryBytes);
unsigned totalRam = memoryBytes; // data.ullTotalPhys + data.ullAvailPhys;
#endif
QString brand;
int cores = 0;
double mhz = 0.0;
GetCPUInfo(brand, cores, mhz);
VideoCard card;
str << "<html>\r\n<head>\r\n<title>SprueKit Log</title>\r\n<style>table { border: dashed #777777; } p { color: #CCCCCC; } h1 { color: #CCCCCC; } tr.INFO { color: #CCCCCC; } tr.WARNING { background: #CCCC00; } tr.ERROR { border: solid #FF0000; background: #AA0000; color: CCCCCC; } tr.DEBUG { background: #007700; color: #CCCCCC; }</style></head>\r\n<body bgcolor='333333'>\r\n<h1>SprueKit Log</h1>\r\n";
str << "<p>Began: " << QDateTime::currentDateTime().toString() << "</p>\r\n";
str << "<p><b>OS:</b> " << QSysInfo::prettyProductName();
str << "<br/><b>Arch:</b> " << QSysInfo::buildCpuArchitecture();
str << "<br/><b>CPU:</b> " << brand;
str << "<br/><b>RAM:</b> " << size_human(totalRam);
str << "<br/><b>GPU:</b> " << card.cardName << " v" << card.deviceVersion;
str << "<br/><b>GPU Status:</b> " << card.errorStatus;
str << "<br/><b>GPU Memory:</b> " << card.videoMemory;
if (!extraHeaderData.isEmpty())
str << extraHeaderData;
//??std::vector<cl::Platform> platforms;
//??cl::Platform::get(&platforms);
//??for (auto &p : platforms) {
//?? str << "<br/>Supports " << p.getInfo<CL_PLATFORM_VERSION>().c_str();
//??}
str << "</p>\r\n";
str << "<div id='messages'>\r\n";
str << "<p><input class=\"search\" placeholder=\"Search\" /></p>\r\n";
str << "<table>\r\n<tbody class = 'list'>\r\n";
str << "<script src=\"http://listjs.com/assets/javascripts/list.min.js\"></script>\r\n";
str << "<script type='text/javascript'>\r\n";
str << "document.addEventListener('DOMContentLoaded', function() {\r\n";
str << " var options = { valueNames: ['time', 'source', 'level', 'msg'] };\r\n";
str << " var userList = new List('messages', options);\r\n";
str << "}, false);\r\n";
str << "</script>\r\n";
stream_->flush();
#endif
}
LogFile::~LogFile()
{
*stream_ << "</tbody></table></body></html>";
stream_->flush();
file_.flush();
file_.close();
delete stream_;
}
LogFile* LogFile::GetInstance()
{
return instance_;
}
void LogFile::Write(const QString& source, const QString& message, int level)
{
QMutexLocker locker(&mutex_);
// Prevent flooding the log with duplicate messages, assume that repeated failures are identifiable
if (lastMessage_.compare(message) == 0)
return;
lastMessage_ = message;
QString levelMsg;
switch (level)
{
case 1:
levelMsg = "ERROR";
break;
case 2:
levelMsg = "WARNING";
break;
case 3:
levelMsg = "INFO";
break;
case 4:
levelMsg = "DEBUG";
break;
}
#ifndef SPRUE_HTML_LOG
*stream_ << QString("<tr class='%2'><td class='time'>%1</td><td class='source'>%4</td><td class='level'>%2</td><td class='msg'>%3</td></tr>\r\n").arg(QDateTime::currentDateTime().toString(), levelMsg, message, source);
stream_->flush();
#else
*stream_ << QString("%1: %2: %3\r\n").arg(QDateTime::currentDateTime().toString(), levelMsg, message);
stream_->flush();
#endif
emit LogUpdated();
emit NewMessage(source, message, levelMsg);
}
void LOGFILE_CALLBACK(const char* msg, int level)
{
LogFile::GetInstance()->Write(LogFile::GetInstance()->GetName(), msg, level + 1);
} | 29.930348 | 408 | 0.609209 | [
"vector",
"model",
"solid"
] |
5676fb4571b8e0522752353c0e200877db39167a | 759 | cpp | C++ | main.cpp | jlusPrivat/privBox-offApp | d697ff430c6f31998ef406656fce4200b4597da1 | [
"MIT"
] | null | null | null | main.cpp | jlusPrivat/privBox-offApp | d697ff430c6f31998ef406656fce4200b4597da1 | [
"MIT"
] | null | null | null | main.cpp | jlusPrivat/privBox-offApp | d697ff430c6f31998ef406656fce4200b4597da1 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include "model/pins/OutputPin.h"
#include "model/messenger/InputMessenger.h"
using namespace std;
int main () {
initializeCore();
OutputPin* p1 = OutputPin::factory(100, digital);
p1->digitalWrite(true);
OutputPin* p2 = OutputPin::factory(101, digital);
p2->digitalWrite(false);
OutputPin* p3 = OutputPin::factory(102, digital);
p3->digitalWrite(true);
OutputPin* p4 = OutputPin::factory(103, digital);
p4->digitalWrite(false);
char path[] = "/tmp/pbOffApp.socket";
InputMessenger msger((const char*) &path, [](string &input)->void{
cout << input << endl;
});
if (msger.getErrorId())
cout << "error: " << msger.getErrorId() << endl;
else
msger.runLoop();
} | 23.71875 | 68 | 0.653491 | [
"model"
] |
567bcaad2ff7088ba7aac7f50ac10a400d464c77 | 2,259 | cpp | C++ | PrevEngine/src/platform/glfw/imguiglfwinit.cpp | preversewharf45/PrevEngine | 3e4ee1517867ccd9ca24bbf39d25408755b8eb25 | [
"MIT"
] | 1 | 2019-01-11T09:55:19.000Z | 2019-01-11T09:55:19.000Z | PrevEngine/src/platform/glfw/imguiglfwinit.cpp | preversewharf45/PrevEngine | 3e4ee1517867ccd9ca24bbf39d25408755b8eb25 | [
"MIT"
] | 4 | 2019-02-17T18:58:36.000Z | 2019-03-22T15:07:09.000Z | PrevEngine/src/platform/glfw/imguiglfwinit.cpp | preversewharf45/PrevEngine | 3e4ee1517867ccd9ca24bbf39d25408755b8eb25 | [
"MIT"
] | 2 | 2019-03-05T09:27:23.000Z | 2019-03-05T13:18:12.000Z | #include "pch.h"
#include "imguiglfwinit.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <imgui.h>
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#include "examples/imgui_impl_opengl3.h"
#include "examples/imgui_impl_opengl3.cpp"
#include "examples/imgui_impl_glfw.h"
#include "examples/imgui_impl_glfw.cpp"
#include "application.h"
namespace prev {
ImGuiWrapper * ImGuiWrapper::Initialize() {
return new glfw::ImGuiGlfwInit();
}
namespace glfw {
ImGuiGlfwInit::ImGuiGlfwInit() {
m_WindowWidth = Application::GetApplicationInstance()->GetWindow().GetWidth();
m_WindowHeight = Application::GetApplicationInstance()->GetWindow().GetHeight();
}
ImGuiGlfwInit::~ImGuiGlfwInit() {
}
void ImGuiGlfwInit::Init() {
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO & io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
ImGui::StyleColorsDark();
ImGuiStyle & style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
ImGui_ImplGlfw_InitForOpenGL((GLFWwindow*)Application::GetApplicationInstance()->GetWindow().GetRawWindow(), true);
ImGui_ImplOpenGL3_Init("#version 460 core");
}
void ImGuiGlfwInit::NewFrame() {
/*ImGuiIO & io = ImGui::GetIO();
io.DisplaySize = ImVec2((float)m_WindowWidth, (float)m_WindowHeight);
io.DeltaTime = Timer::GetDeltaTime();*/
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void ImGuiGlfwInit::Render() {
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
ImGuiIO & io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
GLFWwindow * backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context);
}
}
void ImGuiGlfwInit::OnEvent(Event & event) {
}
}
} | 27.54878 | 118 | 0.72023 | [
"render"
] |
5684228134941b004d3f83dc4394afff825b5319 | 7,917 | cpp | C++ | lib/ExpressionParser.cpp | hoppe93/symachin | 559c3d1e676fc6afb28e40a5fee1906cf62ad07f | [
"MIT"
] | null | null | null | lib/ExpressionParser.cpp | hoppe93/symachin | 559c3d1e676fc6afb28e40a5fee1906cf62ad07f | [
"MIT"
] | null | null | null | lib/ExpressionParser.cpp | hoppe93/symachin | 559c3d1e676fc6afb28e40a5fee1906cf62ad07f | [
"MIT"
] | null | null | null | /**
* Implementation of the 'ExpressionParser' class.
*/
#include <string>
#include <vector>
#include "symachin/Expression.h"
#include "symachin/ExpressionParser.h"
#include "symachin/ExpressionParserException.h"
using namespace std;
using namespace symachin;
/**
* Constructor.
*/
ExpressionParser::ExpressionParser() {}
/**
* Parse the given string as a mathematical
* expression. SYMACHIN recognizes five different symbols:
*
* 1. PLUS (+)
* 2. MINUS (-)
* 3. MULTIPLICATION (*)
* 4. PARANTHESES ( '(', '[', '{', ')', ']', '}' )
* 5. OTHER TEXT
*/
ExpressionPtr ExpressionParser::Parse(const string &expr) {
return Parse(&expr);
}
ExpressionPtr ExpressionParser::Parse(const string *expr) {
buffer = new string(*expr);
bufindx = -1;
operator_stack.clear();
symbol_stack.clear();
// Pre-process string
PreProcessBuffer();
// Convert string to tokens in Postfix form
ToPostfix();
// Now, the output stack is set up as
// a postfix expression and is ready to
// be interpreted.
ExpressionPtr e = ParsePostfix();
return e;
}
/**
* Parse an expression in postfix form.
*/
ExpressionPtr ExpressionParser::ParsePostfix() {
vector<ExpressionPtr> *exprs = new vector<ExpressionPtr>();
for (
vector<struct intp_token*>::iterator it = output_queue.begin();
it != output_queue.end();
it++
) {
struct intp_token *tkn = *it;
// If operator...
if (tkn->type == SYMACHIN_TTYPE_OPERATOR) {
if (exprs->size() < 2)
throw ExpressionParserException("Syntax error in expression.");
ExpressionPtr op2 = exprs->back();
exprs->pop_back();
ExpressionPtr op1 = exprs->back();
exprs->pop_back();
switch (tkn->text.front()) {
case '+':
op1->Add(*op2);
break;
case '-':
if (op1->IsZero()) {
op1 = op2;
op1->Negate();
} else
op1->Subtract(*op2);
break;
case '*':
op1->Multiply(*op2);
break;
default:
throw ExpressionParserException("Unrecognized operator: "+tkn->text);
}
exprs->push_back(op1);
} else { // Symbol
Term t(tkn->text);
ExpressionPtr ep(new Expression(t));
exprs->push_back(ep);
}
}
if (exprs->size() != 1)
throw ExpressionParserException("Expression stack does not contain a single element as expected.");
ExpressionPtr expr = exprs->back();
exprs->pop_back();
return expr;
}
/**
* Pre-process the buffer:
* - Make sure that if the first non-ignoreable
* character of the buffer is an operator, a
* zero is inserted right before it.
*/
void ExpressionParser::PreProcessBuffer() {
unsigned int i, l = buffer->length();
for (i = 0; i < l; i++) {
if (is_ignoreable(buffer->at(i)))
continue;
else if (is_operator(buffer->at(i)))
buffer->insert(0, "0");
break;
}
}
/**
* Convert the buffer string to postfix notation.
*/
void ExpressionParser::ToPostfix() {
struct intp_token *tkn;
while (!eoe() && (tkn=next())!=nullptr) {
switch (tkn->type) {
case SYMACHIN_TTYPE_SYMBOL:
output_queue.push_back(tkn);
break;
case SYMACHIN_TTYPE_OPERATOR: {
while (
operator_stack.size() > 0 &&
operator_stack.back()->precedence >= tkn->precedence &&
operator_stack.back()->type != SYMACHIN_TTYPE_LPAR
) {
output_queue.push_back(operator_stack.back());
operator_stack.pop_back();
}
operator_stack.push_back(tkn);
} break;
case SYMACHIN_TTYPE_LPAR:
operator_stack.push_back(tkn);
break;
case SYMACHIN_TTYPE_RPAR: {
while (
operator_stack.size() > 0 &&
operator_stack.back()->type != SYMACHIN_TTYPE_LPAR
) {
output_queue.push_back(operator_stack.back());
operator_stack.pop_back();
}
if (operator_stack.size() == 0)
throw ExpressionParserException("Mismatched parenthesis in expression.");
// Pop left parenthesis
struct intp_token *tok = operator_stack.back();
operator_stack.pop_back();
delete tok;
delete tkn;
} break;
default:
throw ExpressionParserException("Unrecognized token type.");
}
}
while (operator_stack.size() > 0) {
if (operator_stack.back()->type == SYMACHIN_TTYPE_LPAR)
throw ExpressionParserException("Mismatched parenthesis in expression.");
output_queue.push_back(operator_stack.back());
operator_stack.pop_back();
}
}
/**********************
* INTERNAL FUNCTIONS *
**********************/
/**
* End-of-expression reached?
*/
bool ExpressionParser::eoe() const { return (bufindx >= (signed)buffer->size()); }
/**
* Check if the given character is ignorable.
*/
bool ExpressionParser::is_ignoreable(char c) const {
switch (c) {
case ' ': case '\t': case '\n': return true;
default: return false;
}
}
/**
* Check if the given character classifies as an operator.
* Returns the operator precedence level.
*/
int ExpressionParser::is_operator(char c) const {
switch (c) {
case '+': return 1;
case '-': return 2;
case '*': return 3;
default:
return 0;
}
}
/**
* Check if the given character is a parenthesis.
* Returns either 'SYMACHIN_TTYPE_LPAR' or
* 'SYMACHIN_TTYPE_RPAR' if the character is a left
* or right parenthesis, respectively, and returns
* 'SYMACHIN_TTYPE_SYMBOL' otherwise.
*/
enum intp_ttype ExpressionParser::is_parenthesis(char c) const {
switch (c) {
case '(':
case '[':
case '{':
return SYMACHIN_TTYPE_LPAR;
case ')':
case ']':
case '}':
return SYMACHIN_TTYPE_RPAR;
default:
return SYMACHIN_TTYPE_SYMBOL;
}
}
/**
* Get the next token in the stream.
*/
struct intp_token *ExpressionParser::next() {
string s;
char c;
struct intp_token *tok = new struct intp_token;
int p;
tok->precedence = 0;
for (bufindx++; !eoe(); bufindx++) {
c = buffer->at(bufindx);
if (is_ignoreable(c)) {
if (s.length() == 0)
continue;
else {
break;
}
} else if ((p=is_operator(c)) > 0) {
if (s.length() > 0) {
bufindx--;
break;
} else {
tok->type = SYMACHIN_TTYPE_OPERATOR;
tok->precedence = p;
tok->text = c;
return tok;
}
} else if ((tok->type=is_parenthesis(c)) != SYMACHIN_TTYPE_SYMBOL) {
if (s.length() > 0) {
bufindx--;
break;
} else {
if (tok->type == SYMACHIN_TTYPE_LPAR)
tok->text = '(';
else if (tok->type == SYMACHIN_TTYPE_RPAR)
tok->text = ')';
return tok;
}
} else
s += c;
}
tok->type = SYMACHIN_TTYPE_SYMBOL;
tok->text = s;
if (s == "") return nullptr;
else return tok;
}
| 27.3 | 107 | 0.519768 | [
"vector"
] |
568484361b38e950bd1f3a6c446fee6ce6e0220f | 310 | cpp | C++ | LeetCode/problems/Two Sum/main.cpp | object-oriented-human/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | 1 | 2022-02-21T15:43:01.000Z | 2022-02-21T15:43:01.000Z | LeetCode/problems/Two Sum/main.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | LeetCode/problems/Two Sum/main.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> M;
for (int i = 0; i < nums.size(); i++) {
int c = target - nums[i];
if (M[c] != 0) return {M[c]-1, i};
M[nums[i]] = i+1;
}
return {0, 0};
}
}; | 25.833333 | 55 | 0.419355 | [
"vector"
] |
56899a634907736de943f89f88dce0f1ead5827d | 1,125 | cpp | C++ | src/BabylonCpp/src/meshes/simplification/simplification_queue.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/BabylonCpp/src/meshes/simplification/simplification_queue.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/BabylonCpp/src/meshes/simplification/simplification_queue.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/meshes/simplification/simplification_queue.h>
#include <babylon/meshes/simplification/simplification_settings.h>
namespace BABYLON {
SimplificationQueue::SimplificationQueue() : running{false}
{
}
SimplificationQueue::~SimplificationQueue() = default;
void SimplificationQueue::addTask(const ISimplificationTask& task)
{
_simplificationQueue.emplace(task);
}
void SimplificationQueue::executeNext()
{
if (!_simplificationQueue.empty()) {
running = true;
const ISimplificationTask& task = _simplificationQueue.front();
_simplificationQueue.pop();
runSimplification(task);
}
else {
running = false;
}
}
void SimplificationQueue::runSimplification(const ISimplificationTask& /*task*/)
{
}
ISimplifier* SimplificationQueue::getSimplifier(const ISimplificationTask& task)
{
switch (task.simplificationType) {
case SimplificationType::QUADRATIC:
default:
// TODO FIXME
return nullptr;
// return new QuadraticErrorSimplification(task.mesh);
}
}
} // end of namespace BABYLON
| 23.93617 | 81 | 0.703111 | [
"mesh"
] |
568f2a387f89bffddacea577990aca979fce92f6 | 1,415 | cpp | C++ | Source/PraticeActor/CLobbyPC.cpp | CitrusNyamNyam/Unreal-Portfolio | f5a63fbe796e0531604470767207831b5c523b54 | [
"MIT"
] | 1 | 2018-11-25T10:40:10.000Z | 2018-11-25T10:40:10.000Z | Source/PraticeActor/CLobbyPC.cpp | CitrusNyamNyam/Unreal-Portfolio | f5a63fbe796e0531604470767207831b5c523b54 | [
"MIT"
] | null | null | null | Source/PraticeActor/CLobbyPC.cpp | CitrusNyamNyam/Unreal-Portfolio | f5a63fbe796e0531604470767207831b5c523b54 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "CLobbyPC.h"
#include "CLobby_Widget.h"
#include "Sound/SoundCue.h"
#include "UserWidget.h"
#include "Engine.h"
ACLobbyPC::ACLobbyPC()
{
static ConstructorHelpers::FObjectFinder<USoundCue> battleCue(TEXT("/Game/BGM/BattleGround_Cue.BattleGround_Cue"));
if (battleCue.Succeeded())
BattleCue = battleCue.Object;
static ConstructorHelpers::FObjectFinder<UClass> lobbyWidget(TEXT("/Game/GameMode/Lobby/WidgetBP_Lobby.WidgetBP_Lobby_C"));
if (lobbyWidget.Object)
TSubLobbyWidget = lobbyWidget.Object;
}
void ACLobbyPC::BeginPlay()
{
UGameplayStatics::PlaySound2D(GetWorld(), BattleCue);
TArray<AActor*> outActors;
UGameplayStatics::GetAllActorsWithTag(GetWorld(), FName("MainCamera"), outActors);
if (outActors.Num()>0)
{
ACameraActor* camera = Cast<ACameraActor>(outActors[0]);
if (camera)
this->SetViewTargetWithBlend(camera);
}
LobbyWidget = CreateWidget<UCLobby_Widget>(GetWorld(), TSubLobbyWidget);
if (LobbyWidget)
{
LobbyWidget->AddToViewport();
FInputModeUIOnly mode;
mode.SetWidgetToFocus(LobbyWidget->GetCachedWidget());
SetInputMode(mode);
bShowMouseCursor = true;
}
}
void ACLobbyPC::JoinServer(FString ipAdress)
{
FString NextMap;
FString option = TEXT("NextMap=");
NextMap = option + ipAdress;
UGameplayStatics::OpenLevel(GetWorld(), FName("Loading"),true, NextMap);
}
| 26.203704 | 124 | 0.759011 | [
"object"
] |
5697f2f78f6f628bfabe579186e9ecbe1158513d | 7,128 | cpp | C++ | src/infixExpr/ExprTree.cpp | PGZXB/PGBigNumber | a0f128a0b415bd1a63929c55c2f952205c1a59df | [
"MIT"
] | 2 | 2021-10-25T23:56:54.000Z | 2022-01-02T06:35:49.000Z | src/infixExpr/ExprTree.cpp | PGZXB/PGBigNumber | a0f128a0b415bd1a63929c55c2f952205c1a59df | [
"MIT"
] | 1 | 2021-11-12T09:03:39.000Z | 2021-12-27T02:03:41.000Z | src/infixExpr/ExprTree.cpp | PGZXB/PGBigNumber | a0f128a0b415bd1a63929c55c2f952205c1a59df | [
"MIT"
] | null | null | null | #include "ExprTree.h"
using namespace pgbn;
using namespace pgbn::infixExpr;
PGBN_INFIXEXPR_NAMESPACE_START namespace detail {
inline static Value eval(ExprNode * node, bool peval) {
return peval ?
node->valPromise.get_future().get() : // Wait
node->evalCallback(node, false);
}
static Value ifElseNodeEvalCallback(ExprNode * node, bool peval) {
PGZXB_DEBUG_ASSERT(node->children.size() == 3);
auto & ch = node->children;
return !eval(ch[0], peval).isZero() ? eval(ch[1], peval) : eval(ch[2], peval);
}
static Value binOpEvalCallback(ExprNode * node, bool peval) {
#define lOpAssRAndReturn(op) left.op##Assign(right); return left
PGZXB_DEBUG_ASSERT(node->children.size() == 2);
auto & ch = node->children;
auto left = eval(ch[0], peval);
auto right = eval(ch[1], peval);
switch (node->nodeType) {
case TokenType::OR :
lOpAssRAndReturn(or);
case TokenType::XOR :
lOpAssRAndReturn(xor);
case TokenType::AND :
lOpAssRAndReturn(and);
case TokenType::EQU :
return Value(left.cmp(right) == 0);
case TokenType::NEQU :
return Value(left.cmp(right) != 0);
case TokenType::LT :
return Value(left.cmp(right) < 0);
case TokenType::LE :
return Value(left.cmp(right) <= 0);
case TokenType::GT :
return Value(left.cmp(right) > 0);
case TokenType::GE :
return Value(left.cmp(right) >= 0);
case TokenType::ADD :
lOpAssRAndReturn(add);
case TokenType::SUB :
lOpAssRAndReturn(sub);
case TokenType::MUL :
lOpAssRAndReturn(mul);
case TokenType::DIV :
lOpAssRAndReturn(div);
case TokenType::SHIFTLEFT :
left.shiftLeftAssign(right.toU64());
return left;
case TokenType::SHIFTRIGHT :
left.shiftRightAssign(right.toU64());
return left;
case TokenType::POW :
// TODO: Opt it
if (right.isZero()) {
return Value(0);
}
{
auto res = Value(1);
while (right.cmp(0) > 0) {
res.mulAssign(left);
right.dec();
}
return res;
}
default :
PGZXB_DEBUG_ASSERT_EX("Can Not Be Reached", false);
}
return {};
#undef HELPER
}
static Value unaryOpEvalCallback(ExprNode * node, bool peval) {
PGZXB_DEBUG_ASSERT(node->children.size() == 1);
auto & ch = node->children[0];
auto val = eval(ch, peval);
switch(node->nodeType) {
case TokenType::ADD : // +
return val;
case TokenType::SUB : // -
val.negate(); return val;
case TokenType::NOT : // ~
val.notSelf(); return val;
case TokenType::FACT : // !
if (val.isZero()) return Value(1);
if (val.flagsContains(BNFlag::NEGATIVE)) return Value(0);
{
Value res(1);
while (!val.isOne()) {
res.mulAssign(val);
val.dec();
}
return res;
}
default :
PGZXB_DEBUG_ASSERT_EX("Can Not Be Reached", false);
}
return {};
}
static Value valEvalCallback(ExprNode * node, bool) {
PGZXB_DEBUG_ASSERT(node->children.empty());
if (node->nodeType == ExprNode::NodeType::LITERAL)
return node->val;
else if (node->nodeType == ExprNode::NodeType::BUILTINCONSTANT)
return node->symbol->as<Value>();
PGZXB_DEBUG_ASSERT_EX("Cannot Be Reached", false);
return {};
}
static Value builtinFuncEvalCallback(ExprNode * node, bool peval) {
PGZXB_DEBUG_ASSERT(node->nodeType == ExprNode::NodeType::BUILTINFUNC);
Func func = node->symbol->as<Func>();
if (func.argCount != -1 && static_cast<SizeType>(func.argCount) != node->children.size()) PGBN_GetGlobalStatus() = ErrCode::PARSE_INFIXEXPR_BUILTINFUNC_CALL_NOT_MATCH;
PGZXB_DEBUG_ASSERT(!!func.nativeCall);
std::vector<Value> args;
for (auto * ch : node->children) {
args.push_back(eval(ch, peval));
}
return func.nativeCall(args);
}
static void pevalTask(ExprNode * node) {
// std::ostringstream oss;
// oss << std::this_thread::get_id();
// std::cerr << pgfmt::format("Thread#{0} node#{1} start\n", oss.str(), (std::uint64_t)node );
auto temp = node->evalCallback(node, true);
node->valPromise.set_value(temp);
// std::cerr << pgfmt::format("Thread#{0} node#{1}: peval = {2}\n", oss.str(),
// (std::uint64_t)node, temp.cmp(INT64_MAX) == 1 ? temp.toString(10).substr(0, 50).append("...") : temp.toString(10));
}
} PGBN_INFIXEXPR_NAMESPACE_END
using Node = ExprNode;
// NodePool's public-funcitons
NodePool::NodePool() = default;
Node * NodePool::get(std::uint32_t index) {
PGZXB_DEBUG_ASSERT_EX("index out of bound", index < m_count);
if (index < INIT_BUF_SIZE)
return &m_initBuffer[index];
return &m_exBuffer[index - INIT_BUF_SIZE];
}
std::uint32_t NodePool::count() const {
return m_count;
}
Node * NodePool::newNode() {
Node * res = nullptr;
if (m_count >= INIT_BUF_SIZE) {
m_exBuffer.push_back(Node{});
res = &m_exBuffer.back();
} else {
res = &m_initBuffer[m_count];
}
res->indexInPool = m_count++; // from 0
res->pevalTask = detail::pevalTask;
return res;
}
Node * NodePool::newIfElseNode(Node * cond, Node * then, Node * els) {
Node * ptr = newNode();
ptr->children = { cond, then, els };
ptr->type = Node::Type::FUNCCALL_NODE;
ptr->nodeType = Node::NodeType::QMARK;
ptr->evalCallback = detail::ifElseNodeEvalCallback;
return ptr;
}
Node * NodePool::newBinOpNode(Node::NodeType op, Node * lNode, Node * rNode) {
Node * ptr = newNode();
ptr->children = { lNode, rNode };
ptr->type = Node::Type::FUNCCALL_NODE;
ptr->nodeType = op;
ptr->evalCallback = detail::binOpEvalCallback;
return ptr;
}
Node * NodePool::newUnaryOpNode(Node::NodeType op, Node * child) {
Node * ptr = newNode();
ptr->children = { child };
ptr->type = Node::Type::FUNCCALL_NODE;
ptr->nodeType = op;
ptr->evalCallback = detail::unaryOpEvalCallback;
return ptr;
}
Node * NodePool::newLiteralNode(Value val) {
Node * ptr = newNode();
ptr->val = val;
ptr->type = Node::Type::VAL_NODE;
ptr->nodeType = Node::NodeType::LITERAL;
ptr->evalCallback = detail::valEvalCallback;
return ptr;
}
Node * NodePool::newBuiltinValNode(SymbolTable::Symbol * symbol) {
Node * ptr = newNode();
ptr->symbol = symbol;
ptr->type = Node::Type::VAL_NODE;
ptr->nodeType = Node::NodeType::BUILTINCONSTANT;
ptr->evalCallback = detail::valEvalCallback;
return ptr;
}
Node * NodePool::newFunctionCallNode(SymbolTable::Symbol * symbol, std::vector<Node*> argNodes) {
Node * ptr = newNode();
ptr->children = std::move(argNodes);
ptr->symbol = symbol;
ptr->type = Node::Type::FUNCCALL_NODE;
ptr->nodeType = Node::NodeType::BUILTINFUNC;
ptr->evalCallback = detail::builtinFuncEvalCallback;
return ptr;
}
// NodePool's static-function
NodePool * NodePool::getDefaultInstance() {
static NodePool ins;
return &ins;
}
| 30.461538 | 171 | 0.618547 | [
"vector"
] |
569c759bcc9e56821ca7574130362d5923cc8649 | 16,974 | cpp | C++ | src/EvaluatorState.cpp | daveshah1/ElasticC | 2e28e7fa819573caa43c1e385cf99bf19acd6a60 | [
"MIT"
] | 18 | 2018-03-18T20:12:16.000Z | 2021-08-13T17:51:07.000Z | src/EvaluatorState.cpp | daveshah1/ElasticC | 2e28e7fa819573caa43c1e385cf99bf19acd6a60 | [
"MIT"
] | 8 | 2018-03-18T22:09:32.000Z | 2018-03-22T20:28:39.000Z | src/EvaluatorState.cpp | daveshah1/ElasticC | 2e28e7fa819573caa43c1e385cf99bf19acd6a60 | [
"MIT"
] | 2 | 2018-06-26T15:59:53.000Z | 2020-10-04T22:24:07.000Z | #include "EvaluatorState.hpp"
#include "EvalObject.hpp"
#include "Evaluator.hpp"
#include "Util.hpp"
#include "hdl/HDLCoreDevices.hpp"
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
namespace ElasticC {
VariableDir::VariableDir(bool _input, bool _output, bool _toplvl)
: is_input(_input), is_output(_output), is_toplevel(_toplvl){};
/* EvaluatorVariable base*/
EvaluatorVariable::EvaluatorVariable(VariableDir _dir) : dir(_dir) {}
EvaluatorVariable::EvaluatorVariable(VariableDir _dir, string _name)
: name(_name), dir(_dir){};
EvaluatorVariable::EvaluatorVariable(VariableDir _dir, string _name,
const AttributeSet &_attr)
: name(_name), attributes(_attr), dir(_dir){};
EvaluatorVariable *EvaluatorVariable::Create(VariableDir _dir, string _name,
DataType *_type, bool _is_static) {
// TODO: restructure this once in the long future; perhaps once a better
// typing system is created
IntegerType *it = dynamic_cast<IntegerType *>(_type);
ArrayType *arrt = dynamic_cast<ArrayType *>(_type);
StructureType *st = dynamic_cast<StructureType *>(_type);
RAMType *rt = dynamic_cast<RAMType *>(_type);
if (it != nullptr) {
return new ScalarEvaluatorVariable(_dir, _name, it, _is_static);
} else if (arrt != nullptr) {
return new ArrayEvaluatorVariable(_dir, _name, arrt, _is_static);
} else if (rt != nullptr) {
return new ExternalMemoryEvaluatorVariable(_dir, _name, rt);
} else if (st != nullptr) {
return new StructureEvaluatorVariable(_dir, _name, st, _is_static);
} else {
throw eval_error("unable to create variable ===" + _name +
"===: unsupported type");
}
}
vector<EvaluatorVariable *> EvaluatorVariable::GetArrayChildren() {
return vector<EvaluatorVariable *>{};
}
vector<EvaluatorVariable *> EvaluatorVariable::GetAllChildren() {
return vector<EvaluatorVariable *>{};
}
EvaluatorVariable *EvaluatorVariable::GetChildByName(string name) {
throw eval_error("variable ===" + name +
"=== does not contain member ===" + name + "===");
}
bool EvaluatorVariable::HasDefaultValue() { return false; }
BitConstant EvaluatorVariable::GetDefaultValue() {
throw eval_error("variable ===" + name + "=== does not have default value");
}
EvalObject *EvaluatorVariable::HandleRead(Evaluator *genst) {
return genst->GetVariableValue(this);
}
void EvaluatorVariable::HandleWrite(Evaluator *genst, EvalObject *value) {
genst->SetVariableValue(this, value);
}
bool EvaluatorVariable::IsNonTrivialArrayAccess() { return false; };
EvalObject *
EvaluatorVariable::HandleSubscriptedRead(Evaluator *genst,
vector<EvalObject *> index) {
throw eval_error(
"HandleSubscriptedRead not supported for variable ===" + name + "===");
};
void EvaluatorVariable::HandleSubscriptedWrite(Evaluator *genst,
vector<EvalObject *> index,
EvalObject *value) {
throw eval_error(
"HandleSubscriptedWrite not supported for variable ===" + name + "===");
}
void EvaluatorVariable::HandlePush(Evaluator *genst, EvalObject *value) {
throw eval_error("push (operator<<) not supported for variable ===" + name +
"===");
}
EvalObject *EvaluatorVariable::HandlePop(Evaluator *genst) {
throw eval_error("pop (operator>>) not supported for variable ===" + name +
"===");
}
void EvaluatorVariable::SetBitOffset(int _bitoffset) {
bitoffset = _bitoffset;
};
int EvaluatorVariable::GetBitOffset() { return bitoffset; }
VariableDir EvaluatorVariable::GetDir() { return dir; }
void EvaluatorVariable::Synthesise(SynthContext &sc) {}
/* ScalarEvaluatorVariable */
ScalarEvaluatorVariable::ScalarEvaluatorVariable(VariableDir _dir, string _name,
IntegerType *_type,
bool _is_static)
: EvaluatorVariable(_dir, _name), type(_type), is_static(_is_static) {
if (is_static) {
dir.is_input = true;
write_enable = new ScalarEvaluatorVariable(
VariableDir(false, true, false), name + "_wren",
new IntegerType(1, false), false);
write_enable->hasDefaultValue = true;
write_enable->defaultValue = BitConstant(0);
written_value = new ScalarEvaluatorVariable(VariableDir(false, true, false),
name + "_wrval", type, false);
written_value->hasDefaultValue = true;
written_value->defaultValue =
BitConstant(0); // arguablly this should be "don't care"
}
}
DataType *ScalarEvaluatorVariable::GetType() { return type; };
bool ScalarEvaluatorVariable::IsScalar() { return true; };
bool ScalarEvaluatorVariable::HasDefaultValue() { return hasDefaultValue; };
BitConstant ScalarEvaluatorVariable::GetDefaultValue() { return defaultValue; };
void ScalarEvaluatorVariable::SetDefaultValue(BitConstant defval) {
hasDefaultValue = true;
defaultValue = defval;
};
EvaluatorVariable *ScalarEvaluatorVariable::GetChildByName(string name) {
if (is_static) {
if (name == "_wren") {
return write_enable;
} else if (name == "_wrval") {
return written_value;
}
}
// Unless any more special meta-children are added, this will always throw
return EvaluatorVariable::GetChildByName(name);
}
vector<EvaluatorVariable *> ScalarEvaluatorVariable::GetAllChildren() {
if (is_static) {
return vector<EvaluatorVariable *>{write_enable, written_value};
} else {
return vector<EvaluatorVariable *>{};
}
}
void ScalarEvaluatorVariable::HandleWrite(Evaluator *genst, EvalObject *value) {
if (is_static) {
genst->SetVariableValue(written_value, value);
genst->SetVariableValue(write_enable, new EvalConstant(BitConstant(1)));
} else {
genst->SetVariableValue(this, value);
}
}
void ScalarEvaluatorVariable::Synthesise(SynthContext &sc) {
if (sc.varSignals.find(this) != sc.varSignals.end())
return;
HDLGen::HDLSignal *sig =
sc.design->CreateTempSignal(type->GetHDLType(), "sig_" + name);
// Set clock domains
sig->pipeline_latency = HDLGen::HDLTimingValue<int>(sc.clock, 0);
sig->timing_delay = HDLGen::HDLTimingValue<double>(sc.clock, 0);
sc.varSignals[this] = sig;
if (is_static) {
write_enable->Synthesise(sc);
written_value->Synthesise(sc);
// Deal with enable gating
HDLGen::HDLSignal *gated_1 = sc.design->CreateTempSignal(
new HDLGen::LogicSignalPortType(), "enable");
sc.design->AddDevice(new HDLGen::OperationHDLDevice(
OperationType::B_BWAND,
{sc.varSignals.at(write_enable), sc.input_valid}, gated_1));
HDLGen::HDLSignal *gated_2 = sc.design->CreateTempSignal(
new HDLGen::LogicSignalPortType(), "enable");
sc.design->AddDevice(new HDLGen::OperationHDLDevice(
OperationType::B_BWAND, {gated_1, sc.clock_enable}, gated_2));
sc.design->AddDevice(
new HDLGen::RegisterHDLDevice(sc.varSignals.at(written_value), sc.clock,
sig, gated_2, sc.reset, false));
}
}
ArrayEvaluatorVariable::ArrayEvaluatorVariable(VariableDir _dir, string _name,
ArrayType *_type,
bool _is_static)
: EvaluatorVariable(_dir, _name), type(_type) {
for (int i = 0; i < type->length; i++) {
arrayItems.push_back(EvaluatorVariable::Create(
VariableDir(dir.is_input, dir.is_output, false),
_name + "_itm" + to_string(i), type->baseType, _is_static));
}
SetBitOffset(0);
}
DataType *ArrayEvaluatorVariable::GetType() { return type; }
bool ArrayEvaluatorVariable::IsScalar() { return false; };
vector<EvaluatorVariable *> ArrayEvaluatorVariable::GetArrayChildren() {
return arrayItems;
}
vector<EvaluatorVariable *> ArrayEvaluatorVariable::GetAllChildren() {
return arrayItems;
}
void ArrayEvaluatorVariable::SetBitOffset(int _bitoffset) {
int offset = _bitoffset;
for_each(arrayItems.begin(), arrayItems.end(), [&](EvaluatorVariable *c) {
c->SetBitOffset(offset);
offset += type->baseType->GetWidth();
});
EvaluatorVariable::SetBitOffset(_bitoffset);
}
EvalObject *ArrayEvaluatorVariable::HandleRead(Evaluator *genst) {
vector<EvalObject *> childValues;
transform(
arrayItems.begin(), arrayItems.end(), back_inserter(childValues),
[genst](EvaluatorVariable *child) { return child->HandleRead(genst); });
return new EvalArray(type, childValues);
}
void ArrayEvaluatorVariable::HandleWrite(Evaluator *genst, EvalObject *value) {
// TODO: multidimensional
for (int i = 0; i < arrayItems.size(); i++) {
arrayItems[i]->HandleWrite(
genst, value->ApplyArraySubscriptRead(genst, {new EvalConstant(i)}));
}
}
StructureEvaluatorVariable::StructureEvaluatorVariable(VariableDir _dir,
string _name,
StructureType *_type,
bool _is_static)
: EvaluatorVariable(_dir, _name), type(_type) {
transform(type->content.begin(), type->content.end(),
back_inserter(structItems), [&](DataStructureItem itm) {
return EvaluatorVariable::Create(
VariableDir(dir.is_input, dir.is_output, dir.is_toplevel),
name + "_" + itm.name, itm.type, _is_static);
});
};
DataType *StructureEvaluatorVariable::GetType() { return type; };
bool StructureEvaluatorVariable::IsScalar() { return false; };
vector<EvaluatorVariable *> StructureEvaluatorVariable::GetAllChildren() {
return structItems;
};
EvaluatorVariable *StructureEvaluatorVariable::GetChildByName(string name) {
// find item in struct
auto iter =
find_if(type->content.begin(), type->content.end(),
[name](DataStructureItem itm) { return itm.name == name; });
if (iter == type->content.end()) {
// this will probably throw, as 'name' probably isn't a member
return EvaluatorVariable::GetChildByName(name);
} else {
return structItems[distance(type->content.begin(), iter)];
}
}
void StructureEvaluatorVariable::SetBitOffset(int _bitoffset) {
int offset = _bitoffset;
for_each(structItems.begin(), structItems.end(), [&](EvaluatorVariable *c) {
c->SetBitOffset(offset);
offset += c->GetType()->GetWidth();
});
EvaluatorVariable::SetBitOffset(_bitoffset);
}
EvalObject *StructureEvaluatorVariable::HandleRead(Evaluator *genst) {
map<string, EvalObject *> structValues;
transform(type->content.begin(), type->content.end(),
inserter(structValues, structValues.end()),
[this, genst](const DataStructureItem &itm) {
return make_pair(itm.name,
GetChildByName(itm.name)->HandleRead(genst));
});
return new EvalStruct(type, structValues);
}
void StructureEvaluatorVariable::HandleWrite(Evaluator *genst,
EvalObject *value) {
for (auto itm : type->content) {
GetChildByName(itm.name)->HandleWrite(
genst, value->GetStructureMember(genst, itm.name));
}
}
ExternalMemoryEvaluatorVariable::ExternalMemoryEvaluatorVariable(
VariableDir _dir, string _name, RAMType *_type)
: EvaluatorVariable(_dir, _name), type(_type) {
ports["_address"] = new ScalarEvaluatorVariable(
VariableDir(false, true, _dir.is_toplevel), _name + "_address",
new IntegerType(GetAddressBusSize(type->length), false), false);
ports["_address"]->SetDefaultValue(BitConstant(0));
ports["_q"] =
new ScalarEvaluatorVariable(VariableDir(true, false, _dir.is_toplevel),
_name + "_q", &(type->baseType), false);
if (!type->is_rom) {
ports["_wren"] = new ScalarEvaluatorVariable(
VariableDir(false, true, _dir.is_toplevel), _name + "_wren",
new IntegerType(1, false), false);
ports["_wren"]->SetDefaultValue(BitConstant(0));
ports["_data"] =
new ScalarEvaluatorVariable(VariableDir(false, true, _dir.is_toplevel),
_name + "_data", &(type->baseType), false);
}
dir.is_toplevel = false;
};
DataType *ExternalMemoryEvaluatorVariable::GetType() { return type; }
bool ExternalMemoryEvaluatorVariable::IsScalar() { return false; }
vector<EvaluatorVariable *> ExternalMemoryEvaluatorVariable::GetAllChildren() {
vector<EvaluatorVariable *> children;
transform(ports.begin(), ports.end(), back_inserter(children),
[](pair<string, ScalarEvaluatorVariable *> c) { return c.second; });
return children;
};
EvaluatorVariable *
ExternalMemoryEvaluatorVariable::GetChildByName(string name) {
auto iter = ports.find(name);
if (iter != ports.end()) {
return iter->second;
} else {
return EvaluatorVariable::GetChildByName(name);
}
}
MemoryDeviceParameters ExternalMemoryEvaluatorVariable::GetMemoryParams() {
MemoryDeviceParameters mdp;
mdp.canRead = true;
mdp.canWrite = !type->is_rom;
mdp.hasRden = false;
mdp.hasWren = mdp.canWrite;
mdp.readLatency = 1;
mdp.seperateRWports = false;
return mdp;
}
bool ExternalMemoryEvaluatorVariable::IsNonTrivialArrayAccess() {
return true;
};
EvalObject *ExternalMemoryEvaluatorVariable::HandleSubscriptedRead(
Evaluator *genst, vector<EvalObject *> index) {
// perhaps should warn if already accessed?
if (index.size() != 1) {
throw eval_error("invalid dimensions for access to variable ===" + name +
"===");
}
genst->SetVariableValue(ports.at("_address"), index[0]);
return new EvalVariable(ports.at("_q"));
}
void ExternalMemoryEvaluatorVariable::HandleSubscriptedWrite(
Evaluator *genst, vector<EvalObject *> index, EvalObject *value) {
if (index.size() != 1) {
throw eval_error("invalid dimensions for access to variable ===" + name +
"===");
}
if (type->is_rom) {
throw eval_error("cannot write to ROM type variable ===" + name + "===");
}
genst->SetVariableValue(ports.at("_address"), index[0]);
genst->SetVariableValue(ports.at("_wren"), new EvalConstant(BitConstant(1)));
genst->SetVariableValue(ports.at("_data"), value);
}
EvalObject *ExternalMemoryEvaluatorVariable::HandleRead(Evaluator *genst) {
throw eval_error("ROM device ===" + name + "=== must always be addressed");
}
void ExternalMemoryEvaluatorVariable::HandleWrite(Evaluator *genst,
EvalObject *value) {
throw eval_error("ROM device ===" + name + "=== must always be addressed");
}
StreamEvaluatorVariable::StreamEvaluatorVariable(VariableDir _dir, string _name,
StreamType *_type)
: EvaluatorVariable(_dir, _name), type(_type) {
int totalSize;
if (type->isStream2d) {
totalSize = type->length * type->height;
} else {
totalSize = type->length;
}
for (int i = 0; i < totalSize; i++) {
streamWindow.push_back(EvaluatorVariable::Create(
VariableDir(true, false, false), _name + "_itm" + to_string(i),
type->baseType, false));
}
written_value = EvaluatorVariable::Create(
VariableDir(false, true, false), _name + "_wrval", type->baseType,
false); // TODO: default value for this
write_enable = new ScalarEvaluatorVariable(VariableDir(false, true, false),
name + "_wren",
new IntegerType(1, false), false);
write_enable->SetDefaultValue(BitConstant(0));
dir.is_toplevel = false;
};
DataType *StreamEvaluatorVariable::GetType() { return type; };
bool StreamEvaluatorVariable::IsScalar() { return false; };
vector<EvaluatorVariable *> StreamEvaluatorVariable::GetAllChildren() {
vector<EvaluatorVariable *> children;
children.insert(children.end(), streamWindow.begin(), streamWindow.end());
children.push_back(write_enable);
children.push_back(written_value);
return children;
}
vector<EvaluatorVariable *> StreamEvaluatorVariable::GetArrayChildren() {
return streamWindow;
}
EvaluatorVariable *StreamEvaluatorVariable::GetChildByName(string name) {
if (name == "_wrval")
return written_value;
else if (name == "_wren")
return write_enable;
else
return EvaluatorVariable::GetChildByName(name);
}
void StreamEvaluatorVariable::HandlePush(Evaluator *genst, EvalObject *value) {
genst->SetVariableValue(write_enable, new EvalConstant(BitConstant(1)));
genst->SetVariableValue(written_value, value);
}
void StreamEvaluatorVariable::HandleWrite(Evaluator *genst, EvalObject *value) {
throw eval_error("cannot assign to stream ===" + name +
"===, use operator<< instead");
}
} // namespace ElasticC
| 36.74026 | 80 | 0.668552 | [
"vector",
"transform"
] |
56a5dd1f087e4fefd25d4405479690c3407cd118 | 22,124 | cc | C++ | libclingcon/src/propagator.cc | potassco/clingcon | 289b80ca4b2f936625bb6e6d35d7c6a4da6e3fd7 | [
"MIT"
] | 18 | 2016-07-07T16:22:55.000Z | 2021-11-11T21:25:11.000Z | libclingcon/src/propagator.cc | potassco/clingcon | 289b80ca4b2f936625bb6e6d35d7c6a4da6e3fd7 | [
"MIT"
] | 74 | 2017-05-05T14:03:42.000Z | 2022-02-23T09:36:19.000Z | libclingcon/src/propagator.cc | potassco/clingcon | 289b80ca4b2f936625bb6e6d35d7c6a4da6e3fd7 | [
"MIT"
] | 5 | 2019-06-20T08:49:22.000Z | 2021-06-04T16:35:12.000Z | // {{{ MIT License
//
// Copyright 2020 Roland Kaminski
//
// 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 "clingcon/propagator.hh"
#include "clingcon/parsing.hh"
namespace Clingcon {
namespace {
//! CSP builder to use with the parse_theory function.
class ConstraintBuilder final : public AbstractConstraintBuilder {
public:
ConstraintBuilder(Propagator &propgator, InitClauseCreator &cc, UniqueMinimizeConstraint minimize)
: propagator_{propgator}
, cc_{cc}
, minimize_{std::move(minimize)} {
}
ConstraintBuilder(ConstraintBuilder const &) = delete;
ConstraintBuilder(ConstraintBuilder &&) noexcept = delete;
ConstraintBuilder& operator=(ConstraintBuilder const &) = delete;
ConstraintBuilder& operator=(ConstraintBuilder &&) noexcept = delete;
~ConstraintBuilder() override = default;
[[nodiscard]] lit_t solver_literal(lit_t literal) override {
return cc_.solver_literal(literal);
}
[[nodiscard]] lit_t add_literal() override {
return cc_.add_literal();
}
[[nodiscard]] bool is_true(lit_t literal) override {
return cc_.assignment().is_true(literal);
}
[[nodiscard]] bool add_clause(Clingo::LiteralSpan clause) override {
return cc_.add_clause(clause);
}
void add_show() override {
propagator_.show();
}
void show_signature(char const *name, size_t arity) override {
propagator_.show_signature(name, arity);
}
void show_variable(var_t var) override {
propagator_.show_variable(var);
}
[[nodiscard]] var_t add_variable(Clingo::Symbol sym) override {
return propagator_.add_variable(sym);
}
[[nodiscard]] bool add_constraint(lit_t lit, CoVarVec const &elems, val_t rhs, bool strict) override {
if (!strict && cc_.assignment().is_false(lit)) {
return true;
}
if (elems.size() == 1) {
auto [co, var] = elems.front();
return propagator_.add_simple(cc_, lit, co, var, rhs, strict);
}
propagator_.add_constraint(SumConstraint::create(lit, rhs, elems, propagator_.config().sort_constraints));
if (strict) {
CoVarVec ielems;
ielems.reserve(elems.size());
for (auto const &elem : elems) {
ielems.emplace_back(safe_inv(elem.first), elem.second);
}
propagator_.add_constraint(SumConstraint::create(-lit, safe_inv(safe_add(rhs, 1)), ielems, propagator_.config().sort_constraints));
}
return true;
}
void add_minimize(val_t co, var_t var) override {
minimize_elems_.emplace_back(co, var);
}
//! Add a distinct constraint.
//!
//! Binary distinct constraints will be represented with a sum constraint.
[[nodiscard]] bool add_distinct(lit_t lit, std::vector<std::pair<CoVarVec, val_t>> const &elems) override {
auto truth = cc_.assignment().truth_value(lit);
if (truth == Clingo::TruthValue::False) {
return true;
}
if (elems.size() > 2) {
propagator_.add_constraint(DistinctConstraint::create(lit, elems, propagator_.config().sort_constraints));
return true;
}
// Note: even though translation is also handled in constraints, it is
// easier to do it here right away because at this point we can also
// add trivial constraints that will be simplified further later on.
// The only advantage of doing it in the constraint would be that we
// potentially have to introduce fewer literals.
CoVarVec celems;
for (auto it = elems.begin(), ie = elems.end(); it != ie; ++it) {
for (auto jt = it + 1; jt != ie; ++jt) {
auto rhs = jt->second - it->second;
celems.assign(it->first.begin(), it->first.end());
for (auto [co, var] : jt->first) {
celems.emplace_back(-co, var);
}
rhs += simplify(celems, true);
if (celems.empty()) {
if (rhs == 0) {
return cc_.add_clause({-lit});
}
continue;
}
auto a = cc_.add_literal();
auto b = -a;
if (truth != Clingo::TruthValue::True) {
b = cc_.add_literal();
if (!cc_.add_clause({a, b, -lit})) {
return false;
}
if (!cc_.add_clause({-a, -b})) {
return false;
}
if (!cc_.add_clause({lit, -a})) {
return false;
}
if (!cc_.add_clause({lit, -b})) {
return false;
}
}
if (!add_constraint(a, celems, check_valid_value(rhs-1), false)) {
return false;
}
for (auto &co_var : celems) {
co_var.first = -co_var.first;
}
if (!add_constraint(b, celems, check_valid_value(-rhs-1), false)) {
return false;
}
}
}
return true;
}
static std::tuple<lit_t, CoVarVec, val_t> translate_disjoint_(var_t const &i, var_t const &j, val_t rhs) {
CoVarVec elems;
elems.emplace_back(1, i);
elems.emplace_back(-1, j);
rhs += simplify(elems);
lit_t lit = 0;
if (elems.empty()) {
lit = rhs >= 0 ? TRUE_LIT : -TRUE_LIT;
}
return {lit, elems, rhs};
}
bool translate_disjoint_(lit_t &lit, CoVarVec const &elems, val_t rhs) {
if (lit == 0) {
lit = add_literal();
if (!add_constraint(lit, elems, rhs, true)) {
return false;
}
}
return true;
}
bool translate_disjoint_(lit_t lit, co_var_t const &i, co_var_t const &j) {
assert (i.first > 0 && j.first > 0);
// lower_i >= lower_j (lower_j - lower_i <= 0)
auto [lit_a, elems_a, rhs_a] = translate_disjoint_(j.second, i.second, 0);
if (lit_a == -TRUE_LIT) {
return true;
}
// lower_i <= upper_j (lower_i - upper_j <= 0)
auto [lit_b, elems_b, rhs_b] = translate_disjoint_(i.second, j.second, j.first - 1);
if (lit_b == -TRUE_LIT) {
return true;
}
if (!translate_disjoint_(lit_a, elems_a, rhs_a)) {
return false;
}
if (!translate_disjoint_(lit_b, elems_b, rhs_b)) {
return false;
}
return cc_.add_clause({-lit, -lit_a, -lit_b});
}
[[nodiscard]] bool add_disjoint(lit_t lit, CoVarVec const &elems) override {
if (cc_.assignment().is_false(lit)) {
return true;
}
if (elems.size() > 2) {
propagator_.add_constraint(DisjointConstraint::create(lit, elems));
return true;
}
CoVarVec celems;
for (auto it = elems.begin(), ie = elems.end(); it != ie; ++it) {
for (auto jt = it + 1; jt != ie; ++jt) {
// TODO: this is a really bad translation. The following would
// be way better:
//
// c = add_literal()
// c => start_i >= end_j
// -c => start_j >= end_i
//
// But currently it is
//
// :- start_i >= start_j, start_i <= end_j.
// :- start_j >= start_i, start_j <= end_i.
//
// using *strict* constraints.
if (!translate_disjoint_(lit, *it, *jt) || !translate_disjoint_(lit, *jt, *it)) {
return false;
}
}
}
return true;
}
[[nodiscard]] bool add_dom(lit_t lit, var_t var, IntervalSet<val_t> const &elems) override {
return cc_.assignment().is_false(lit) || propagator_.add_dom(cc_, lit, var, elems);
}
//! Prepare the minimize constraint.
UniqueMinimizeConstraint prepare_minimize() {
// copy values of old minimize constraint
if (minimize_ != nullptr) {
for (auto elem : *minimize_) {
minimize_elems_.emplace_back(elem);
}
minimize_elems_.emplace_back(minimize_->adjust(), INVALID_VAR);
}
// simplify minimize
if (!minimize_elems_.empty()) {
auto adjust = simplify(minimize_elems_, true);
minimize_ = MinimizeConstraint::create(adjust, minimize_elems_, propagator_.config().sort_constraints);
}
return std::move(minimize_);
}
private:
Propagator &propagator_;
InitClauseCreator &cc_;
UniqueMinimizeConstraint minimize_;
CoVarVec minimize_elems_;
};
} // namespace
void Propagator::on_model(Clingo::Model &model) {
std::vector<Clingo::Symbol> symbols_;
for (auto [sym, var] : sym_map_) {
if (shown(var)) {
auto value = Clingo::Number(get_value(var, model.thread_id()));
symbols_.emplace_back(Clingo::Function("__csp", {sym, value}));
}
}
if (has_minimize()) {
auto bound = get_minimize_value(model.thread_id());
auto value = Clingo::String(std::to_string(bound).c_str());
symbols_.emplace_back(Clingo::Function("__csp_cost", {value}));
if (bound <= minimize_bound_.load(std::memory_order_relaxed)) {
stats_step_.cost = bound;
update_minimize(bound - 1);
}
}
model.extend(symbols_);
}
void Propagator::on_statistics(Clingo::UserStatistics &step, Clingo::UserStatistics &accu) {
stats_accu_.accu(stats_step_);
add_statistics_(step, stats_step_);
add_statistics_(accu, stats_accu_);
stats_step_.reset();
}
void Propagator::add_statistics_(Clingo::UserStatistics &root, Statistics &stats) {
using namespace Clingo;
UserStatistics clingcon = root.add_subkey("Clingcon", StatisticsType::Map);
if (stats.cost.has_value()) {
clingcon.add_subkey("Cost", StatisticsType::Value).set_value(*stats.cost);
}
auto init_time = clingcon.add_subkey("Init time in seconds", StatisticsType::Map);
init_time.add_subkey("Total", StatisticsType::Value).set_value(stats.time_init);
init_time.add_subkey("Simplify", StatisticsType::Value).set_value(stats.time_simplify);
init_time.add_subkey("Translate", StatisticsType::Value).set_value(stats.time_translate);
auto problem = clingcon.add_subkey("Problem", StatisticsType::Map);
problem.add_subkey("Constraints", StatisticsType::Value).set_value(stats.num_constraints);
problem.add_subkey("Variables", StatisticsType::Value).set_value(stats.num_variables);
problem.add_subkey("Clauses", StatisticsType::Value).set_value(stats.num_clauses);
problem.add_subkey("Literals", StatisticsType::Value).set_value(stats.num_literals);
auto translate = clingcon.add_subkey("Translate", StatisticsType::Map);
translate.add_subkey("Constraints removed", StatisticsType::Value).set_value(stats.translate_removed);
translate.add_subkey("Constraints added", StatisticsType::Value).set_value(stats.translate_added);
translate.add_subkey("Clauses", StatisticsType::Value).set_value(stats.translate_clauses);
translate.add_subkey("Weight constraints", StatisticsType::Value).set_value(stats.translate_wcs);
translate.add_subkey("Literals", StatisticsType::Value).set_value(stats.translate_literals);
UserStatistics threads = clingcon.add_subkey("Thread", StatisticsType::Array);
threads.ensure_size(std::distance(stats.solver_statistics.begin(), stats.solver_statistics.end()), StatisticsType::Map);
size_t i = 0;
for (auto &solver_stat : stats.solver_statistics) {
auto thread = threads[i++];
auto time = thread.add_subkey("Time in seconds", StatisticsType::Map);
auto total = solver_stat.time_propagate + solver_stat.time_check + solver_stat.time_undo;
time.add_subkey("Total", StatisticsType::Value).set_value(total);
time.add_subkey("Propagation", StatisticsType::Value).set_value(solver_stat.time_propagate);
time.add_subkey("Check", StatisticsType::Value).set_value(solver_stat.time_check);
time.add_subkey("Undo", StatisticsType::Value).set_value(solver_stat.time_undo);
thread.add_subkey("Refined reason", StatisticsType::Value).set_value(solver_stat.refined_reason);
thread.add_subkey("Introduced reason", StatisticsType::Value).set_value(solver_stat.introduced_reason);
thread.add_subkey("Literals introduced", StatisticsType::Value).set_value(solver_stat.literals);
}
}
var_t Propagator::add_variable(Clingo::Symbol sym) {
auto [it, ret] = sym_map_.emplace(sym, 0);
if (ret) {
it->second = master_().add_variable(config_.min_int, config_.max_int);
var_map_.emplace(it->second, sym);
++stats_step_.num_variables;
}
return it->second;
}
void Propagator::show_variable(var_t var) {
show_variable_.emplace(var);
}
void Propagator::show_signature(char const *name, size_t arity) {
show_signature_.emplace(Clingo::Signature(name, arity));
}
bool Propagator::add_dom(AbstractClauseCreator &cc, lit_t lit, var_t var, IntervalSet<val_t> const &domain) {
return master_().add_dom(cc, lit, var, domain);
}
bool Propagator::add_simple(AbstractClauseCreator &cc, lit_t clit, val_t co, var_t var, val_t rhs, bool strict) {
return master_().add_simple(cc, clit, co, var, rhs, strict);
}
void Propagator::add_constraint_(UniqueConstraint constraint) {
constraints_.emplace_back(std::move(constraint));
}
void Propagator::add_constraint(UniqueConstraint constraint) {
++stats_step_.num_constraints;
master_().add_constraint(*constraint);
add_constraint_(std::move(constraint));
}
void Propagator::init(Clingo::PropagateInit &init) {
init.set_check_mode(Clingo::PropagatorCheckMode::Partial);
Timer timer{stats_step_.time_init};
InitClauseCreator cc{init, stats_step_};
// remove minimize constraint
UniqueMinimizeConstraint minimize{remove_minimize()};
// remove solve step local and fixed literals
for (auto &solver : solvers_) {
solver.update(cc);
}
// add constraints
ConstraintBuilder builder{*this, cc, std::move(minimize)};
if (!parse(builder, init.theory_atoms())) {
return;
}
// get the master solver and make sure it stays valid
solvers_.reserve(init.number_of_threads());
auto &master = master_();
// gather bounds of states in master
for (auto it = solvers_.begin() + 1, ie = solvers_.end(); it != ie; ++it) {
if (!master.update_bounds(cc, *it, config_.check_state)) {
return;
}
}
// propagate the newly added constraints
if (!simplify_(cc)) {
return;
}
// translate (simple enough) constraints
if (!translate_(cc, builder.prepare_minimize())) {
return;
}
// watch all the remaining constraints
for (auto &constraint : constraints_) {
cc.add_watch(constraint->literal());
}
if (!cc.commit()) {
return;
}
// copy order literals from master to other states
auto n = static_cast<size_t>(init.number_of_threads());
for (size_t i = solvers_.size(); i < n; ++i) {
solvers_.emplace_back(config_.solver_config(i), stats_step_.solver_stats(i));
}
while (solvers_.size() > n) {
solvers_.pop_back();
}
master.shrink_to_fit();
for (auto it = solvers_.begin() + 1, ie = solvers_.end(); it != ie; ++it) {
it->copy_state(master);
}
// If there is a minimize constraint we have to enable total checks subject
// to the model lock too.
if (has_minimize()) {
init.set_check_mode(Clingo::PropagatorCheckMode::Both);
}
}
bool Propagator::simplify_(AbstractClauseCreator &cc) {
Timer timer{stats_step_.time_simplify};
struct Reset{ // NOLINT
~Reset() {
master.statistics().time_propagate = 0;
master.statistics().time_check = 0;
}
Solver &master;
} reset{master_()};
return master_().simplify(cc, config_.check_state);
}
bool Propagator::translate_(InitClauseCreator &cc, UniqueMinimizeConstraint minimize ) {
Timer timer{stats_step_.time_translate};
// add minimize constraint
// Note: the minimize constraint is added after simplification to avoid
// propagating tagged clauses, which is not supported at the moment.
if (minimize != nullptr) {
add_minimize_(std::move(minimize));
}
// translate (simple enough) constraints
cc.set_state(InitState::Translate);
bool ret = master_().translate(cc, stats_step_, config_, constraints_);
if (!ret) {
return false;
}
cc.set_state(InitState::Init);
// mark minimize constraint as translated if necessary
if (minimize_ != nullptr && master_().translate_minimize()) {
minimize_ = nullptr;
}
return true;
}
void Propagator::propagate(Clingo::PropagateControl &control, Clingo::LiteralSpan changes) {
auto &solver = solver_(control.thread_id());
ControlClauseCreator cc{control, solver.statistics()};
static_cast<void>(solver.propagate(cc, changes));
}
void Propagator::check(Clingo::PropagateControl &control) {
auto ass = control.assignment();
auto size = ass.size();
auto &solver = solver_(control.thread_id());
auto dl = ass.decision_level();
if (minimize_ != nullptr) {
auto minimize_bound = minimize_bound_.load(std::memory_order_relaxed);
if (minimize_bound != no_bound) {
auto bound = minimize_bound + minimize_->adjust();
solver.update_minimize(*minimize_, dl, bound);
}
}
ControlClauseCreator cc{control, solver.statistics()};
if (!solver.check(cc, config_.check_state)) {
return;
}
// Note: Makes sure that all variables are assigned in the end. But even if
// the assignment is total, we do not have to introduce fresh variables if
// variables have been introduced during check. In this case, there is a
// guaranteed follow-up propagate call because all newly introduced
// variables are watched.
if (size == ass.size() && ass.is_total()) {
solver.check_full(cc, config_.check_solution);
}
}
void Propagator::undo(Clingo::PropagateControl const &control, Clingo::LiteralSpan changes) noexcept {
static_cast<void>(changes);
solver_(control.thread_id()).undo();
}
lit_t Propagator::decide(Clingo::id_t thread_id, Clingo::Assignment const &assign, lit_t fallback) {
return solver_(thread_id).decide(assign, fallback);
}
bool Propagator::shown(var_t var) {
auto sym = get_symbol(var);
if (!sym.has_value()) {
return false;
}
if (!show_) {
return true;
}
if (show_variable_.find(var) != show_variable_.end()) {
return true;
}
return
sym->type() == Clingo::SymbolType::Function &&
show_signature_.find(Clingo::Signature(sym->name(), sym->arguments().size())) != show_signature_.end();
}
std::optional<var_t> Propagator::get_index(Clingo::Symbol sym) const {
auto it = sym_map_.find(sym);
if (it != sym_map_.end()) {
return it->second;
}
return std::nullopt;
}
std::optional<Clingo::Symbol> Propagator::get_symbol(var_t var) const {
auto it = var_map_.find(var);
if (it != var_map_.end()) {
return it->second;
}
return std::nullopt;
}
val_t Propagator::get_value(var_t var, uint32_t thread_id) const {
return solver_(thread_id).get_value(var);
}
void Propagator::add_minimize_(UniqueMinimizeConstraint minimize) {
assert(minimize_ == nullptr);
minimize_ = minimize.get();
add_constraint(std::move(minimize));
}
UniqueMinimizeConstraint Propagator::remove_minimize() {
if (minimize_ == nullptr) {
return nullptr;
}
--stats_step_.num_constraints;
auto it = std::find_if(constraints_.begin(), constraints_.end(), [this](UniqueConstraint const &x) {
return x.get() == minimize_;
});
assert(it != constraints_.end());
UniqueMinimizeConstraint minimize{(it->release(), minimize_)};
for (auto &solver : solvers_) {
solver.remove_constraint(*minimize_);
}
constraints_.erase(it);
minimize_ = nullptr;
return minimize;
}
sum_t Propagator::get_minimize_value(uint32_t thread_id) {
assert (has_minimize());
auto &solver = solver_(thread_id);
sum_t bound = 0;
for (auto [co, var] : *minimize_) {
bound += static_cast<sum_t>(co) * solver.get_value(var);
}
return bound - minimize_->adjust();
}
void Propagator::update_minimize(sum_t bound) {
assert (has_minimize());
minimize_bound_ = bound;
}
} // namespace Clingcon
| 35.341853 | 143 | 0.627825 | [
"vector",
"model"
] |
56b7bf0fcbbac9b8ac5d9c42b90ff6028191463e | 8,597 | cpp | C++ | source/Application.cpp | aviktorov/pbr-sandbox-demo | 9ee9f87cfd401e5535cc8d8708483cc6c38bc3fa | [
"MIT"
] | null | null | null | source/Application.cpp | aviktorov/pbr-sandbox-demo | 9ee9f87cfd401e5535cc8d8708483cc6c38bc3fa | [
"MIT"
] | null | null | null | source/Application.cpp | aviktorov/pbr-sandbox-demo | 9ee9f87cfd401e5535cc8d8708483cc6c38bc3fa | [
"MIT"
] | null | null | null | #include "Application.h"
#include "IO.h"
#include "RenderGraph.h"
#include "ResourceManager.h"
#include "SwapChain.h"
#include "GameModule.h"
#include <game/World.h>
#include <render/shaders/Compiler.h>
#include <render/backend/Driver.h>
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#include <glm/gtc/matrix_transform.hpp>
#include <cassert>
#include <iostream>
struct GameState
{
game::Entity camera;
};
struct InputState
{
glm::vec3 move_delta;
glm::vec2 look_delta;
double last_cursor_x {0};
double last_cursor_y {0};
bool cursor_captured {false};
};
static GameState game_state;
static InputState input_state;
/*
*/
void Application::init(int window_width, int window_height)
{
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
window = glfwCreateWindow(window_width, window_height, "Scapes Demo v0.1.0", nullptr, nullptr);
glfwSetWindowUserPointer(window, this);
glfwSetFramebufferSizeCallback(window, &Application::onGLFWResizeEvent);
glfwSetKeyCallback(window, Application::onGLFWKeyEvent);
glfwSetMouseButtonCallback(window, Application::onGLFWMouseButtonEvent);
glfwGetCursorPos(window, &input_state.last_cursor_x, &input_state.last_cursor_y);
file_system = new ApplicationFileSystem("assets/");
driver = render::backend::Driver::create("Scapes Demo", "Scapes", render::backend::Api::VULKAN);
compiler = render::shaders::Compiler::create(render::shaders::ShaderILType::SPIRV, file_system);
world = game::World::create();
initGame(world, window_width, window_height);
resource_manager = new ResourceManager(driver, compiler, file_system);
swap_chain = new SwapChain(driver);
swap_chain->init(getNativeHandle());
render_graph = new RenderGraph(driver, compiler, resource_manager);
render_graph->init(window_width, window_height);
running = true;
}
void Application::shutdown()
{
driver->wait();
shutdownGame(world);
game::World::destroy(world);
world = nullptr;
delete resource_manager;
resource_manager = nullptr;
delete render_graph;
render_graph = nullptr;
delete swap_chain;
swap_chain = nullptr;
render::backend::Driver::destroy(driver);
driver = nullptr;
render::shaders::Compiler::destroy(compiler);
compiler = nullptr;
delete file_system;
file_system = nullptr;
glfwDestroyWindow(window);
window = nullptr;
running = false;
}
void Application::initGame(game::World *world, int width, int height)
{
ecs::game::init(world);
game::Entity camera = game::Entity(world);
camera.addComponent<ecs::game::FPSCameraTransform>();
camera.addComponent<ecs::game::Camera>();
ecs::game::FPSCameraTransform &camera_transform = camera.getComponent<ecs::game::FPSCameraTransform>();
camera_transform.up = glm::vec3(0.0f, 0.0f, 1.0f);
camera_transform.position = glm::vec3(1.0f, 1.0f, 1.0f);
camera_transform.horizontal_angle = 0.0f;
camera_transform.vertical_angle = 0.0f;
game_state.camera = camera;
resizeGame(world, width, height);
}
void Application::resizeGame(game::World *world, int width, int height)
{
ecs::game::Camera &camera_parameters = game_state.camera.getComponent<ecs::game::Camera>();
const float znear = 0.1f;
const float zfar = 1000.0f;
const float fov = 70.0f;
float aspect = static_cast<float>(width) / height;
camera_parameters.main = true;
camera_parameters.parameters = glm::vec4(znear, zfar, 1.0f / znear, 1.0f / zfar);
camera_parameters.projection = glm::perspective(fov, aspect, znear, zfar);
camera_parameters.projection[1][1] *= -1.0f; // Invert for Vulkan
}
void Application::shutdownGame(game::World *world)
{
ecs::game::shutdown(world);
}
/*
*/
void Application::update(float dt)
{
updateInput();
const float move_speed = 8.0f;
const float look_speed = 70.0f;
running = !glfwWindowShouldClose(window);
ecs::game::FPSCameraTransform &camera_transform = game_state.camera.getComponent<ecs::game::FPSCameraTransform>();
float vertical_angle_limit = 89.9f;
float horizontal_angle_limit = 360.0f;
camera_transform.position += input_state.move_delta * dt * move_speed;
camera_transform.vertical_angle = glm::clamp(camera_transform.vertical_angle + input_state.look_delta.y * dt * look_speed, -vertical_angle_limit, vertical_angle_limit);
camera_transform.horizontal_angle += input_state.look_delta.x * dt * look_speed;
camera_transform.horizontal_angle = glm::mod(camera_transform.horizontal_angle, horizontal_angle_limit);
}
void Application::render()
{
render::backend::CommandBuffer *command_buffer = swap_chain->acquire();
assert(command_buffer);
driver->resetCommandBuffer(command_buffer);
driver->beginCommandBuffer(command_buffer);
const ecs::game::Camera &camera_parameters = game_state.camera.getComponent<ecs::game::Camera>();
const ecs::game::FPSCameraTransform &camera_transform = game_state.camera.getComponent<ecs::game::FPSCameraTransform>();
const glm::vec3 &direction = ecs::game::getDirection(camera_transform);
RenderGraphData data;
data.projection = camera_parameters.projection;
data.view = glm::lookAt(camera_transform.position, camera_transform.position + direction, camera_transform.up);
render_graph->render(command_buffer, swap_chain->getBackend(), data);
driver->endCommandBuffer(command_buffer);
}
void Application::present()
{
swap_chain->present();
}
/*
*/
void Application::updateInput()
{
input_state.move_delta = glm::vec3(0.0f);
input_state.look_delta = glm::vec2(0.0f);
double cursor_x = 0.0f;
double cursor_y = 0.0f;
glfwGetCursorPos(window, &cursor_x, &cursor_y);
if (input_state.cursor_captured)
{
// camera look
input_state.look_delta.x = static_cast<float>(input_state.last_cursor_x - cursor_x);
input_state.look_delta.y = static_cast<float>(input_state.last_cursor_y - cursor_y);
// camera motion
const ecs::game::FPSCameraTransform &camera_transform = game_state.camera.getComponent<ecs::game::FPSCameraTransform>();
const glm::vec3 &forward = ecs::game::getDirection(camera_transform);
const glm::vec3 &right = glm::cross(forward, camera_transform.up);
const glm::vec3 &up = glm::cross(right, forward);
glm::vec3 &move = input_state.move_delta;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
move += forward;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
move -= forward;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
move += right;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
move -= right;
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
move += up;
if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
move -= up;
if (glm::dot(move, move) > 0.0f)
move = glm::normalize(move);
}
input_state.last_cursor_x = cursor_x;
input_state.last_cursor_y = cursor_y;
}
/*
*/
void Application::onResizeEvent(int width, int height)
{
driver->wait();
swap_chain->recreate(getNativeHandle());
render_graph->resize(width, height);
resizeGame(world, width, height);
}
void Application::onKeyEvent(int key, int scancode, int action, int mods)
{
if (!input_state.cursor_captured)
return;
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
input_state.cursor_captured = false;
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
void Application::onMouseButtonEvent(int button, int action, int mods)
{
if (input_state.cursor_captured)
return;
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
{
input_state.cursor_captured = true;
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
}
/*
*/
void Application::onGLFWResizeEvent(GLFWwindow *window, int width, int height)
{
if (width == 0 || height == 0)
return;
Application *application = reinterpret_cast<Application *>(glfwGetWindowUserPointer(window));
assert(application != nullptr);
application->onResizeEvent(width, height);
}
void Application::onGLFWKeyEvent(GLFWwindow *window, int key, int scancode, int action, int mods)
{
Application *application = reinterpret_cast<Application *>(glfwGetWindowUserPointer(window));
assert(application != nullptr);
application->onKeyEvent(key, scancode, action, mods);
}
void Application::onGLFWMouseButtonEvent(GLFWwindow *window, int button, int action, int mods)
{
Application *application = reinterpret_cast<Application *>(glfwGetWindowUserPointer(window));
assert(application != nullptr);
application->onMouseButtonEvent(button, action, mods);
}
/*
*/
void *Application::getNativeHandle() const
{
#if defined(GLFW_EXPOSE_NATIVE_WIN32)
return glfwGetWin32Window(window);
#else
#error "Platform is not supported"
#endif
}
| 27.378981 | 169 | 0.752239 | [
"render"
] |
56c249119b2b933ba508d87933e1c9d4ab3d4aa5 | 3,047 | cc | C++ | hackerrank/algorithms/dynamic-programming/maxsubarray.cc | fdavidcl/problems | a917a0e61fd80be38610e607eb86e6685323baa3 | [
"MIT"
] | null | null | null | hackerrank/algorithms/dynamic-programming/maxsubarray.cc | fdavidcl/problems | a917a0e61fd80be38610e607eb86e6685323baa3 | [
"MIT"
] | null | null | null | hackerrank/algorithms/dynamic-programming/maxsubarray.cc | fdavidcl/problems | a917a0e61fd80be38610e607eb86e6685323baa3 | [
"MIT"
] | null | null | null | // https://www.hackerrank.com/challenges/maxsubarray
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// max_subarray_with_last
// Retrieves the maximum sum for a contiguous subarray
// containing the last element of the array (array[size-1])
int max_subarray_with_last(int* array, int size) {
int current_sum = array[size - 1];
int max = current_sum;
// Add elements from the last and get the maximum possible sum
for (int first = size - 2; first >= 0; first--) {
current_sum += array[first];
if (current_sum > max)
max = current_sum;
}
return max;
}
// recursive solution
// The maximum value for a subarray is either the maximum value
// of a subarray that doesn't contain the last value or the maximum
// subarray that contains the last value
// Times out on test #1
int max_subarray_recursive(int* array, int size) {
if (size == 1) {
return array[0];
} else {
return max(max_subarray_recursive(array, size - 1),
max_subarray_with_last(array, size));
}
}
// iterative solution
// for each element, find the best subarray finishing with that element
// Times out on test #1
int max_subarray_iter(int* array, int size) {
int best_solution = numeric_limits<int>::min();
for (int s = 0; s < size; s++) {
best_solution = max(best_solution, max_subarray_with_last(array, s + 1));
}
return best_solution;
}
// memoized solution
// calculate all the sums for any subarray and store them as partial results
// in a matrix, and find the best
// Aborts on test #1 (maybe reserving too much memory?)
int max_subarray_memoized(int* array, int size) {
int** sums = new int*[size];
for (int i = 0; i < size; i++) sums[i] = new int[size];
int max = numeric_limits<int>::min();
for (int first = 0; first < size; first++) {
sums[first][first] = array[first];
if (array[first] > max)
max = array[first];
for (int last = first + 1; last < size; last++) {
sums[first][last] = sums[first][last - 1] + array[last];
if (sums[first][last] > max)
max = sums[first][last];
}
}
return max;
}
// Select your solution here:
int (*max_subarray)(int*, int) = max_subarray_memoized;
// Find the maximum non-contiguous non-empty subarray
int sum_positives(int* array, int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += array[i] * (array[i] > 0);
}
// Consider always at least one element
if (sum == 0) {
int max = numeric_limits<int>::min();
for (int i = 0; i < size; i++) {
if (array[i] == 0) return 0;
else if (array[i] > max) max = array[i];
}
return max;
}
return sum;
}
int main() {
unsigned tests;
cin >> tests;
for (int _t = 0; _t < tests; _t++) {
unsigned size;
cin >> size;
int* arr = new int[size];
for (int i = 0; i < size; i++)
cin >> arr[i];
cout << max_subarray(arr, size) << " " << sum_positives(arr, size) << endl;
delete[] arr;
}
return 0;
}
| 25.605042 | 79 | 0.629472 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.