hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bb73c42cfd1672b2dacbf2f87caabe1641b86080 | 492 | cpp | C++ | Engine/Source/UISliderComponent.cpp | Osvak/TurboTribble | fd4f565d2fb67894adc138d0446ffb8cf24323e6 | [
"MIT"
] | null | null | null | Engine/Source/UISliderComponent.cpp | Osvak/TurboTribble | fd4f565d2fb67894adc138d0446ffb8cf24323e6 | [
"MIT"
] | 1 | 2022-01-18T16:30:42.000Z | 2022-01-18T16:30:42.000Z | Engine/Source/UISliderComponent.cpp | Osvak/TurboTribble | fd4f565d2fb67894adc138d0446ffb8cf24323e6 | [
"MIT"
] | null | null | null | #include "Application.h"
#include "SDL.h"
#include "UISliderComponent.h"
#include "ModuleCamera3D.h"
#include "CameraComponent.h"
UISliderComponent::UISliderComponent(int id, std::string text)
{
type = ComponentType::UI_SLIDER;
value = 0;
minValue = 50;
maxValue = 100;
sliderText.SetText(text, float2(5, 5), 0.5f, float4(255,255,255,255));
}
UISliderComponent::~UISliderComponent()
{
}
bool UISliderComponent::Update(float dt)
{
return true;
}
void UISliderComponent::Draw()
{
} | 16.965517 | 71 | 0.727642 | Osvak |
bb74cdb8f97444680bafab6b6d9d3bcf49ccaa0a | 3,009 | cc | C++ | client/src/client.cc | zinhart/kvs | decac5308007bde0921f50200cf76d81b2b32251 | [
"MIT"
] | null | null | null | client/src/client.cc | zinhart/kvs | decac5308007bde0921f50200cf76d81b2b32251 | [
"MIT"
] | null | null | null | client/src/client.cc | zinhart/kvs | decac5308007bde0921f50200cf76d81b2b32251 | [
"MIT"
] | null | null | null | //#include "common"
#include <iostream>
#include <algorithm>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT "4000" // the port client will be connecting to
#define MAXDATASIZE 100 // max number of bytes we can get at once
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET)
{
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(int argc, char *argv[])
{
if(argc <= 4)
{
std::cerr<<"USAGE: ./client <hostname> <portnum> <cmds>\n";
std::cerr<<"ACTIONS: <GET> key\n<PUT> <key> <value>\n<Delete> <key> <value>\n";
std::exit(1);
}
std::int32_t error, i;
std::string packet_buffer;
std::uint32_t packet_length;
char * host_name, * port, * cmd, * key, * value;
host_name = argv[1];
port = argv[2];
cmd = argv[3];
key = argv[4];
value = (argc <= 4) ? NULL : argv[5];
std::int32_t sockfd, numbytes;
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(host_name, port, &hints, &servinfo)) != 0)
{
//std::cerr<<"getaddrinfo: %s\n", gai_strerror(rv)<<"\n";
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
{
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
perror("client: connect");
close(sockfd);
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
printf("client: connecting to %s\n", s);
std::uint32_t size = 1 + strlen(cmd) + strlen(key) + (value == NULL) ? 0 : strlen(value);
char packet[size];
strcpy(packet,cmd);
strcpy(packet+ strlen(cmd), key);
(value == NULL) ? 0 : strcpy(packet+ strlen(key), value) ;
freeaddrinfo(servinfo); // all done with this structur
printf("packet: %s %s %s length %d\n", packet, cmd, key,strlen(packet));
//send command, key, and possibly value
if( (numbytes = sendto(sockfd, packet, strlen(packet), 0, p->ai_addr, p->ai_addrlen)) == -1)
{
std::cerr<<"sendto\n";
std::exit(1);
}
//recieve value strlen(cmd) determins the number of bytes to wait for and must be coordinated with what the server sends
if ((numbytes = recv(sockfd, packet, strlen(packet), 0)) == -1)
{
std::cerr<<"recv\n";
std::exit(1);
}
packet[numbytes] = '\0';
printf("client: received '%s'\n", packet);
close(sockfd);
return 0;
}
| 27.354545 | 122 | 0.636092 | zinhart |
bb74d5a004cf7c24fff1b74c9805452df806caf5 | 114 | cpp | C++ | source/serviceclass/worklist_scp.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 15 | 2016-01-28T16:54:57.000Z | 2021-04-16T08:28:21.000Z | source/serviceclass/worklist_scp.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | null | null | null | source/serviceclass/worklist_scp.cpp | mariusherzog/dicom | 826a1dadb294637f350a665b9c4f97f2cd46439d | [
"MIT"
] | 3 | 2016-07-16T05:22:11.000Z | 2020-04-03T08:59:26.000Z | #include "worklist_scp.hpp"
namespace dicom
{
namespace serviceclass
{
worklist_scp::worklist_scp()
{
}
}
}
| 6.705882 | 28 | 0.710526 | mariusherzog |
bb82118acf1af34ea093d1ef19a9bc66ba77650d | 2,470 | cpp | C++ | libs/tex/generate_texture_views.cpp | sucongCJS/mvs-texturing | 413ad0619eaadb1a9416ae347ff1f9989b29ca59 | [
"BSD-3-Clause"
] | null | null | null | libs/tex/generate_texture_views.cpp | sucongCJS/mvs-texturing | 413ad0619eaadb1a9416ae347ff1f9989b29ca59 | [
"BSD-3-Clause"
] | null | null | null | libs/tex/generate_texture_views.cpp | sucongCJS/mvs-texturing | 413ad0619eaadb1a9416ae347ff1f9989b29ca59 | [
"BSD-3-Clause"
] | null | null | null | #include <util/timer.h>
#include <util/tokenizer.h>
#include <util/file_system.h>
#include <mve/image_io.h>
#include <mve/image_tools.h>
#include <mve/bundle_io.h>
#include <mve/scene.h>
#include "texturing.h"
#include "progress_counter.h"
TEX_NAMESPACE_BEGIN
void from_mve_scene(std::string const & scene_dir, std::string const & image_name, TextureViews * texture_views){
mve::Scene::Ptr scene;
try{
scene = mve::Scene::create(scene_dir);
}
catch(std::exception & e){
std::cerr<<"无法打开scene目录: "<<e.what()<<std::endl;
std::exit(EXIT_FAILURE);
}
std::size_t num_views = scene->get_views().size();
texture_views->reserve(num_views);
ProgressCounter view_counter("\t加载视角图片: ", num_views);
for(std::size_t i=0; i<num_views; ++i){ // 遍历每一个view
view_counter.progress<SIMPLE>();
mve::View::Ptr view = scene->get_view_by_id(i);
if(view == NULL){
view_counter.inc();
continue;
}
if(!view->has_image(image_name, mve::IMAGE_TYPE_UINT8)){
std::cout<<"警告: 视角"<<view->get_name()<<"没有字节图片"<<image_name<<std::endl;
continue;
}
mve::View::ImageProxy const * image_proxy = view->get_image_proxy(image_name);
if (image_proxy->channels < 3) {
std::cerr<<"图片"<<image_name<<"在视角"<<view->get_name()<<"中不是三通道的图片!"<<std::endl;
exit(EXIT_FAILURE);
}
texture_views->push_back(
TextureView(view->get_id(), view->get_camera(), util::fs::abspath(util::fs::join_path(view->get_directory(), image_proxy->filename))));
view_counter.inc();
}
}
void generate_texture_views(std::string const & in_scene, TextureViews * texture_views, std::string const & tmp_dir){
/* MVE_SCENE::EMBEDDING */
size_t pos = in_scene.rfind("::");
if (pos != std::string::npos) {
std::string scene_dir = in_scene.substr(0, pos);
std::string image_name = in_scene.substr(pos + 2, in_scene.size());
from_mve_scene(scene_dir, image_name, texture_views);
}
std::sort(texture_views->begin(), texture_views->end(),
[] (TextureView const & l, TextureView const & r) -> bool {
return l.get_id() < r.get_id();
}
); // 按id排序
std::size_t num_views = texture_views->size();
if(num_views == 0){
std::cerr<< "没有正确地导入scene目录里的内容"<< std::endl;
exit(EXIT_FAILURE);
}
}
TEX_NAMESPACE_END | 31.265823 | 147 | 0.615385 | sucongCJS |
bb8a200aea6523c5d3ee51471472beb68474090c | 659 | cpp | C++ | src/0028.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | 38 | 2020-03-05T06:38:32.000Z | 2022-03-11T02:32:14.000Z | src/0028.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | null | null | null | src/0028.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | 16 | 2020-04-02T15:13:20.000Z | 2022-02-25T07:34:35.000Z | class Solution {
public:
int strStr(string haystack, string needle) {
if (empty(needle)) {
return 0;
}
vector<int> pi(size(needle));
for (int i = 1, j = 0; i < size(pi); ++i) {
while (j > 0 && needle[i] != needle[j]) {
j = pi[j - 1];
}
if (needle[i] == needle[j]) {
++j;
}
pi[i] = j;
}
for (int i = 0, j = 0; i < size(haystack); ++i) {
while (j > 0 && haystack[i] != needle[j]) {
j = pi[j - 1];
}
if (haystack[i] == needle[j]) {
++j;
}
if (j == size(needle)) {
return i - size(needle) + 1;
}
}
return -1;
}
};
| 21.258065 | 53 | 0.408194 | downdemo |
bb8eac9f978ff2afac67af52fd866c14e8027207 | 1,186 | cpp | C++ | IndexBuilder/main.cpp | Dudi119/SearchYA | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 5 | 2017-08-29T15:33:16.000Z | 2020-12-09T08:34:02.000Z | IndexBuilder/main.cpp | Dudi119/MesosBenchMark | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 1 | 2017-09-26T11:44:01.000Z | 2017-09-27T06:40:01.000Z | IndexBuilder/main.cpp | Dudi119/MesosBenchMark | a3468dedcd3fc8d63350a2c79b16b6949fdc7e41 | [
"MIT"
] | 2 | 2017-08-19T04:41:16.000Z | 2020-07-21T17:38:16.000Z | #include <memory>
#include "Core/src/Enviorment.h"
#include "Core/src/Logger.h"
#include "Core/src/CommandLine.h"
#include "Core/src/Logger.h"
#include "Core/src/TraceListener.h"
#include "cppkin/cppkin.h"
#include "IndexBuilder.h"
using namespace core;
using namespace std;
int main(int argc, char** argv)
{
CommandLine::Instance().Parse(argc, const_cast<const char**>(argv));
const string& workinDir = CommandLine::Instance().GetArgument("workingdir");
Enviorment::Instance().Init();
Logger::Instance().AddListener(make_shared<FileRotationListener>(TraceSeverity::Info, workinDir + "/IndexBuilder", 50 * 1024 * 1024, 20));
Logger::Instance().Start(TraceSeverity::Info);
TRACE_INFO("Index Builder starting");
cppkin::GeneralParams cppkinParams;
cppkinParams.AddParam(cppkin::ConfigTags::HOST_ADDRESS, string("127.0.0.1"));//ConfigParams::Instance().GetZipkinHostAddress());
cppkinParams.AddParam(cppkin::ConfigTags::PORT, 9410);
cppkinParams.AddParam(cppkin::ConfigTags::SERVICE_NAME, string("Index_Builder"));
INIT(cppkinParams);
IndexBuilder::Instance().InitializeMesos();
IndexBuilder::Instance().WaitForCompletion();
Logger::Instance().Flush();
return 0;
}
| 37.0625 | 139 | 0.752108 | Dudi119 |
bb8ffb56b7c980e985717913696e97f8883cc384 | 380 | hpp | C++ | Ladybug3D/Libraries/Renderer/SceneObject.hpp | wlsvy/Ladybug3D | 9cd92843bf6cdff806aa4283c5594028a53e20b3 | [
"MIT"
] | null | null | null | Ladybug3D/Libraries/Renderer/SceneObject.hpp | wlsvy/Ladybug3D | 9cd92843bf6cdff806aa4283c5594028a53e20b3 | [
"MIT"
] | null | null | null | Ladybug3D/Libraries/Renderer/SceneObject.hpp | wlsvy/Ladybug3D | 9cd92843bf6cdff806aa4283c5594028a53e20b3 | [
"MIT"
] | null | null | null | #pragma once
#include "Object.hpp"
namespace Ladybug3D {
class Transform;
class Model;
class SceneObject : public Object {
public:
SceneObject(const std::string& name = "SceneObject");
~SceneObject();
auto& GetTransform() { return m_Transform; }
void OnImGui() override;
std::shared_ptr<Model> Model;
protected:
std::shared_ptr<Transform> m_Transform;
};
} | 17.272727 | 55 | 0.710526 | wlsvy |
bb95bed7c3fa0b21fa19c5cff9430e306cd3c1d5 | 599 | hpp | C++ | libs/opencl/include/sge/opencl/platform/object_sequence.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/opencl/include/sge/opencl/platform/object_sequence.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/opencl/include/sge/opencl/platform/object_sequence.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_OPENCL_PLATFORM_OBJECT_SEQUENCE_HPP_INCLUDED
#define SGE_OPENCL_PLATFORM_OBJECT_SEQUENCE_HPP_INCLUDED
#include <sge/opencl/platform/object_fwd.hpp>
#include <fcppt/config/external_begin.hpp>
#include <vector>
#include <fcppt/config/external_end.hpp>
namespace sge::opencl::platform
{
using object_sequence = std::vector<sge::opencl::platform::object>;
}
#endif
| 27.227273 | 67 | 0.764608 | cpreh |
bb9b9f11072857fdc7000753e3fe7bd5d78aa9d5 | 14,429 | cpp | C++ | connecter/mmloop_test/getopt.cpp | mqtter/mqtter | a60f57d866f3e50ffc3abe5020737fe8d0aeeba3 | [
"MIT"
] | 2 | 2018-07-25T13:04:14.000Z | 2019-01-14T03:58:54.000Z | mmloop_test/getopt.cpp | skybosi/maomao | 88e556cb4c56ebc0dbf597f0a5835a495d8ab5df | [
"MIT"
] | 1 | 2017-07-29T02:19:59.000Z | 2017-07-30T12:48:21.000Z | mmloop_test/getopt.cpp | skybosi/maomao | 88e556cb4c56ebc0dbf597f0a5835a495d8ab5df | [
"MIT"
] | 2 | 2017-11-27T14:40:42.000Z | 2019-01-14T03:58:56.000Z | #include "getopt.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int opterr; /* if error message should be printed */
int optind; /* index into parent argv vector */
int optopt; /* character checked for validity */
int optreset; /* reset getopt */
char *optarg; /* argument associated with option */
const char *_getopt_initialize (int argc, char *const *argv, const char *optstring);
static int first_nonopt;
static int last_nonopt;
static char *nextchar;
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
} ordering;
static char *posixly_correct;
static void exchange (char **);
int __getopt_initialized;
int _getopt_internal (int argc,char *const *argv,const char *optstring,const struct option *longopts, int *longind,int long_only)
{
int print_errors = opterr;
if (optstring[0] == ':')
print_errors = 0;
if (argc < 1)
return -1;
optarg = NULL;
if (optind == 0 || !__getopt_initialized)
{
if (optind == 0)
optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
}
#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
if (nextchar == NULL || *nextchar == '\0')
{
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > optind)
last_nonopt = optind;
if (first_nonopt > optind)
first_nonopt = optind;
if (ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (last_nonopt != optind)
first_nonopt = optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (optind < argc && NONOPTION_P)
optind++;
last_nonopt = optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (optind != argc && !strcmp (argv[optind], "--"))
{
optind++;
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = optind;
last_nonopt = argc;
optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (ordering == REQUIRE_ORDER)
return -1;
optarg = argv[optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[optind] + 1
+ (longopts != NULL && argv[optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[optind][1] == '-'
|| (long_only && (argv[optind][2] || !strchr(optstring, argv[optind][1])))))
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */
;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar)
== (unsigned int) strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else if (long_only
|| pfound->has_arg != p->has_arg
|| pfound->flag != p->flag
|| pfound->val != p->val)
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (print_errors)
{
fprintf (stderr, "%s: option `%s' is ambiguous\n",argv[0], argv[optind]);
}
nextchar += strlen (nextchar);
optind++;
optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (print_errors)
{
if (argv[optind - 1][1] == '-')
{
fprintf (stderr, "%s: option `--%s' doesn't allow an argument\n",argv[0], pfound->name);
}
else
{
fprintf (stderr, "%s: option `%c%s' doesn't allow an argument\n",argv[0], argv[optind - 1][0], pfound->name);
}
}
nextchar += strlen (nextchar);
optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (print_errors)
{
fprintf (stderr,"%s: option `%s' requires an argument\n",argv[0], argv[optind - 1]);
}
nextchar += strlen (nextchar);
optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[optind][1] == '-'
|| strchr(optstring, *nextchar) == NULL)
{
if (print_errors)
{
if (argv[optind][1] == '-')
{
/* --option */
fprintf (stderr, "%s: unrecognized option `--%s'\n",argv[0], nextchar);
}
else
{
/* +option or -option */
fprintf (stderr, "%s: unrecognized option `%c%s'\n",argv[0], argv[optind][0], nextchar);
}
}
nextchar = (char *) "";
optind++;
optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
const char *temp = strchr(optstring, c);
/* Increment `optind' when we start to process its last character. */
if (*nextchar == '\0')
++optind;
if (temp == NULL || c == ':')
{
if (print_errors)
{
if (posixly_correct)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
}
else
{
fprintf (stderr, "%s: invalid option -- %c\n", argv[0], c);
}
}
optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (print_errors)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr, "%s: option requires an argument -- %c\n",argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
/* optarg is now the argument, see if it's in the
table of longopts. */
for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */
;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar) == strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (print_errors)
{
fprintf (stderr, "%s: option `-W %s' is ambiguous\n",argv[0], argv[optind]);
}
nextchar += strlen (nextchar);
optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (print_errors)
{
fprintf (stderr, "%s: option `-W %s' doesn't allow an argument\n",argv[0], pfound->name);
}
nextchar += strlen (nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (print_errors)
{
fprintf (stderr,"%s: option `%s' requires an argument\n",argv[0], argv[optind - 1]);
}
nextchar += strlen (nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0')
{
optarg = nextchar;
optind++;
}
else
optarg = NULL;
nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (print_errors)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr,"%s: option requires an argument -- %c\n",argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
nextchar = NULL;
}
}
return c;
}
}
const char *_getopt_initialize (int argc, char *const *argv, const char *optstring)
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = optind;
nextchar = NULL;
posixly_correct = getenv ("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
return optstring;
}
void exchange (char **argv)
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
first_nonopt += (optind - last_nonopt);
last_nonopt = optind;
}
int getopt (int argc,char *const *argv,const char *optstring)
{
return _getopt_internal (argc, argv, optstring,(const struct option *) 0,(int *) 0,0);
}
int getopt_long (int argc,char *const *argv,const char *options,const struct option *long_options,int *opt_index)
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
}
| 24.877586 | 129 | 0.584933 | mqtter |
bba7f4103dff199da36fc105011c01580921bb83 | 656 | hpp | C++ | source/framework/python/src/command_line.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 2 | 2021-02-26T22:45:56.000Z | 2021-05-02T10:28:48.000Z | source/framework/python/src/command_line.hpp | pcraster/lue | e64c18f78a8b6d8a602b7578a2572e9740969202 | [
"MIT"
] | 262 | 2016-08-11T10:12:02.000Z | 2020-10-13T18:09:16.000Z | source/framework/python/src/command_line.hpp | computationalgeography/lue | 71993169bae67a9863d7bd7646d207405dc6f767 | [
"MIT"
] | 1 | 2020-03-11T09:49:41.000Z | 2020-03-11T09:49:41.000Z | #pragma once
#include "lue/py/configure.hpp"
#include <functional>
#include <memory>
#include <vector>
namespace lue {
class CommandLine
{
public:
CommandLine();
int argc() const;
char** argv() const;
private:
// For each argument a string
std::vector<std::string> _argument_strings;
// For each argument a pointer to the array of characters
std::vector<char*> _argument_pointers;
// Command line arguments, to be used by HPX runtime startup code
int _argc;
char** _argv;
};
} // namespace lue
| 18.222222 | 77 | 0.559451 | computationalgeography |
bbab7f4d1e831fc0c378a8ce92e6bd1731f92d0f | 1,384 | cc | C++ | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/ext/profile/replace_new.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/ext/profile/replace_new.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/ext/profile/replace_new.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | // -*- C++ -*-
// Copyright (C) 2006-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-require-profile-mode "" }
#include <vector>
#include <testsuite_hooks.h>
using std::vector;
void* operator new(std::size_t size) THROW(std::bad_alloc)
{
void* p = std::malloc(size);
if (!p)
throw std::bad_alloc();
return p;
}
void* operator new (std::size_t size, const std::nothrow_t&) throw()
{
// With _GLIBCXX_PROFILE, the instrumentation of the vector constructor
// will call back into this new operator.
vector<int> v;
return std::malloc(size);
}
void operator delete(void* p) throw()
{
if (p)
std::free(p);
}
int
main()
{
vector<int> v;
return 0;
}
| 25.163636 | 74 | 0.695087 | best08618 |
bbb7c5dc56e6f5c60b0485f0896f159ce624ad07 | 1,224 | cpp | C++ | src/powerext/DnaInfo/DnaInfo.cpp | ssidpat/powerext | dd89281cf2008fdfda6eb1090cd381eb004e8f6c | [
"BSD-3-Clause"
] | 15 | 2017-07-15T02:10:58.000Z | 2022-01-04T23:09:23.000Z | src/powerext/DnaInfo/DnaInfo.cpp | ssidpat/powerext | dd89281cf2008fdfda6eb1090cd381eb004e8f6c | [
"BSD-3-Clause"
] | 2 | 2017-12-07T19:12:23.000Z | 2020-09-30T19:05:23.000Z | src/powerext/DnaInfo/DnaInfo.cpp | ssidpat/powerext | dd89281cf2008fdfda6eb1090cd381eb004e8f6c | [
"BSD-3-Clause"
] | 3 | 2019-01-18T00:55:00.000Z | 2021-09-08T11:06:45.000Z | // DnaInfo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "../PowerExt/AssemblyName.h"
#include "../PowerExt/HResultDecoder.h"
#include <iostream>
#include <string>
int _tmain(int argc, TCHAR* argv[])
{
std::wcout << _T("DnaInfo.exe (.NET Assembly Information)") << std::endl << std::endl;
if (argc < 2)
{
std::wcout << _T("Usage:") << std::endl;
std::wcout << std::endl;
std::wcout << _T("DnaInfo.exe <assembly>") << std::endl;
std::wcout << std::endl;
std::wcout << _T(" <assembly> = Path to a .NET dll or exe") << std::endl;
return 1;
}
std::wstring assemblyFile(argv[1]);
std::wcout << assemblyFile << std::endl << std::endl;
try
{
AssemblyName assemblyName(assemblyFile);
std::wstring fullName = assemblyName.GetFullName();
std::wcout << std::endl << std::endl << _T("FullName:") << std::endl;
std::wcout << fullName << std::endl << std::endl;
}
catch (std::exception& e)
{
std::wcout << L"Error: " << e.what() << std::endl << std::endl ;
}
catch (HResultDecoder e)
{
std::wcout << L"Error: " << e.GetErrorCode()
<< L" (" << e.GetHexErrorCode() << L") -- "
<< e.GetErrorMessage() << std::endl << std::endl;
}
return 0;
}
| 25.5 | 87 | 0.606209 | ssidpat |
c7de29be989e742aa72b87500b286f1742317a29 | 6,081 | cc | C++ | spot/spot/twaalgos/translate.cc | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | 1 | 2018-03-02T14:29:57.000Z | 2018-03-02T14:29:57.000Z | spot/spot/twaalgos/translate.cc | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | null | null | null | spot/spot/twaalgos/translate.cc | mcc-petrinets/formulas | 10f835d67c7deedfe98fbbd55a56bd549a5bae9b | [
"MIT"
] | 1 | 2015-06-05T12:42:07.000Z | 2015-06-05T12:42:07.000Z | // -*- coding: utf-8 -*-
// Copyright (C) 2013-2017 Laboratoire de Recherche et Développement
// de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot 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.
//
// Spot 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 <spot/twaalgos/translate.hh>
#include <spot/twaalgos/ltl2tgba_fm.hh>
#include <spot/twaalgos/compsusp.hh>
#include <spot/misc/optionmap.hh>
#include <spot/tl/relabel.hh>
#include <spot/twaalgos/relabel.hh>
namespace spot
{
void translator::setup_opt(const option_map* opt)
{
comp_susp_ = early_susp_ = skel_wdba_ = skel_simul_ = 0;
relabel_bool_ = tls_impl_ = -1;
if (!opt)
return;
relabel_bool_ = opt->get("relabel-bool", 4);
comp_susp_ = opt->get("comp-susp", 0);
if (comp_susp_ == 1)
{
early_susp_ = opt->get("early-susp", 0);
skel_wdba_ = opt->get("skel-wdba", -1);
skel_simul_ = opt->get("skel-simul", 1);
}
tls_impl_ = opt->get("tls-impl", -1);
}
void translator::build_simplifier(const bdd_dict_ptr& dict)
{
tl_simplifier_options options(false, false, false);
switch (level_)
{
case High:
options.containment_checks = true;
options.containment_checks_stronger = true;
SPOT_FALLTHROUGH;
case Medium:
options.synt_impl = true;
SPOT_FALLTHROUGH;
case Low:
options.reduce_basics = true;
options.event_univ = true;
}
// User-supplied fine-tuning?
if (tls_impl_ >= 0)
switch (tls_impl_)
{
case 0:
options.synt_impl = false;
options.containment_checks = false;
options.containment_checks_stronger = false;
break;
case 1:
options.synt_impl = true;
options.containment_checks = false;
options.containment_checks_stronger = false;
break;
case 2:
options.synt_impl = true;
options.containment_checks = true;
options.containment_checks_stronger = false;
break;
case 3:
options.synt_impl = true;
options.containment_checks = true;
options.containment_checks_stronger = true;
break;
default:
throw std::runtime_error
("tls-impl should take a value between 0 and 3");
}
simpl_owned_ = simpl_ = new tl_simplifier(options, dict);
}
twa_graph_ptr translator::run(formula* f)
{
bool unambiguous = (pref_ & postprocessor::Unambiguous);
if (unambiguous && type_ == postprocessor::Monitor)
{
// Deterministic monitor are unambiguous, so the unambiguous
// option is not really relevant for monitors.
unambiguous = false;
set_pref(pref_ | postprocessor::Deterministic);
}
// Do we want to relabel Boolean subformulas?
// If we have a huge formula such as
// (a1 & a2 & ... & an) U (b1 | b2 | ... | bm)
// then it is more efficient to translate
// a U b
// and then fix the automaton. We use relabel_bse() to find
// sub-formulas that are Boolean but do not have common terms.
//
// This rewriting is enabled only if the formula
// 1) has some Boolean subformula
// 2) has more than relabel_bool_ atomic propositions (the default
// is 4, but this can be changed)
// 3) relabel_bse() actually reduces the number of atomic
// propositions.
relabeling_map m;
formula to_work_on = *f;
if (relabel_bool_ > 0)
{
bool has_boolean_sub = false; // that is not atomic
std::set<formula> aps;
to_work_on.traverse([&](const formula& f)
{
if (f.is(op::ap))
aps.insert(f);
else if (f.is_boolean())
has_boolean_sub = true;
return false;
});
unsigned atomic_props = aps.size();
if (has_boolean_sub && (atomic_props >= (unsigned) relabel_bool_))
{
formula relabeled = relabel_bse(to_work_on, Pnn, &m);
if (m.size() < atomic_props)
to_work_on = relabeled;
else
m.clear();
}
}
formula r = simpl_->simplify(to_work_on);
if (to_work_on == *f)
*f = r;
// This helps ltl_to_tgba_fm() to order BDD variables in a more
// natural way (improving the degeneralization).
simpl_->clear_as_bdd_cache();
twa_graph_ptr aut;
if (comp_susp_ > 0)
{
// FIXME: Handle unambiguous_ automata?
int skel_wdba = skel_wdba_;
if (skel_wdba < 0)
skel_wdba = (pref_ == postprocessor::Deterministic) ? 1 : 2;
aut = compsusp(r, simpl_->get_dict(), skel_wdba == 0,
skel_simul_ == 0, early_susp_ != 0,
comp_susp_ == 2, skel_wdba == 2, false);
}
else
{
bool exprop = unambiguous || level_ == postprocessor::High;
aut = ltl_to_tgba_fm(r, simpl_->get_dict(), exprop,
true, false, false, nullptr, nullptr,
unambiguous);
}
aut = this->postprocessor::run(aut, r);
if (!m.empty())
relabel_here(aut, &m);
return aut;
}
twa_graph_ptr translator::run(formula f)
{
return run(&f);
}
void translator::clear_caches()
{
simpl_->clear_caches();
}
}
| 31.671875 | 74 | 0.588226 | mcc-petrinets |
c7e42f144afc7e32cc637eb5589570661ffe69d5 | 3,533 | cpp | C++ | src/atta/memorySystem/tests/speed.cpp | brenocq/atta | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 5 | 2021-11-18T02:44:45.000Z | 2021-12-21T17:46:10.000Z | src/atta/memorySystem/tests/speed.cpp | Brenocq/RobotSimulator | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 6 | 2021-03-11T21:01:27.000Z | 2021-09-06T19:41:46.000Z | src/atta/memorySystem/tests/speed.cpp | Brenocq/RobotSimulator | dc0f3429c26be9b0a340e63076f00f996e9282cc | [
"MIT"
] | 3 | 2020-09-10T07:17:00.000Z | 2020-11-05T10:24:41.000Z | //--------------------------------------------------
// Atta Memory Tests
// speed.cpp
// Date: 2021-08-20
// By Breno Cunha Queiroz
//--------------------------------------------------
#include <gtest/gtest.h>
#include <atta/core/stringId.h>
#include <atta/memorySystem/memoryManager.h>
#include <atta/memorySystem/allocatedObject.h>
#include <atta/memorySystem/allocators/stackAllocator.h>
#include <atta/memorySystem/allocators/mallocAllocator.h>
using namespace atta;
namespace
{
constexpr int NUM_IT = 1000;
constexpr int NUM_OBJ = 5000;
struct TestStack : public AllocatedObject<TestStack, SID("Stack")>
{
int x, y, z;
};
struct TestMalloc : public AllocatedObject<TestMalloc, SID("Malloc")>
{
int x, y, z;
};
struct TestCpp
{
int x, y, z;
};
class Memory_Speed : public ::testing::Test
{
public:
void SetUp()
{
MemoryManager::registerAllocator(
SID("Stack"),
static_cast<Allocator*>(new StackAllocator(sizeof(TestStack)*NUM_OBJ)));
MemoryManager::registerAllocator(
SID("Malloc"),
static_cast<Allocator*>(new MallocAllocator()));
}
};
TEST_F(Memory_Speed, DefaultNewCpp)
{
TestCpp* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new TestCpp();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
delete a[i];
}
}
}
TEST_F(Memory_Speed, MallocWithMemoryManager)
{
TestMalloc* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new TestMalloc();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
delete a[i];
}
}
}
TEST_F(Memory_Speed, StackObj)
{
StackAllocator stack = StackAllocator(sizeof(TestStack)*NUM_OBJ);
TestStack* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new (stack.alloc<TestStack>()) TestStack();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
stack.free<TestStack>(a[i]);
}
}
}
TEST_F(Memory_Speed, StackPtr)
{
StackAllocator* stack = MemoryManager::getAllocator<StackAllocator>(SID("Stack"));
TestStack* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new (stack->alloc<TestStack>()) TestStack();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
stack->free<TestStack>(a[i]);
}
}
EXPECT_EQ(stack->getUsedMemory(), 0);
}
TEST_F(Memory_Speed, StackWithMemoryManager)
{
TestStack* a[NUM_OBJ];
for(int it = 0; it < NUM_IT; it++)
{
for(int i = 0; i < NUM_OBJ; i++)
{
a[i] = new TestStack();
}
for(int i = NUM_OBJ-1; i >= 0; i--)
{
delete a[i];
}
}
StackAllocator* stack = MemoryManager::getAllocator<StackAllocator>(SID("Stack"));
EXPECT_EQ(stack->getUsedMemory(), 0);
}
}
| 25.977941 | 92 | 0.463063 | brenocq |
c7ea1e1dbdf21ac93cb344d6fcf42752583cc5a7 | 2,067 | cpp | C++ | src/SelfGravity/Init_FFTW.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 3 | 2019-04-13T02:08:01.000Z | 2020-11-17T12:45:37.000Z | src/SelfGravity/Init_FFTW.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | null | null | null | src/SelfGravity/Init_FFTW.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 2 | 2019-11-12T02:00:20.000Z | 2019-12-09T14:52:31.000Z |
#include "DAINO.h"
#ifdef GRAVITY
#ifdef SERIAL
rfftwnd_plan FFTW_Plan, FFTW_Plan_Inv;
#else
rfftwnd_mpi_plan FFTW_Plan, FFTW_Plan_Inv;
#endif
//-------------------------------------------------------------------------------------------------------
// Function : Init_FFTW
// Description : Create the FFTW plans
//-------------------------------------------------------------------------------------------------------
void Init_FFTW()
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s ... ", __FUNCTION__ );
# ifdef SERIAL
FFTW_Plan = rfftw3d_create_plan( NX0_TOT[2], NX0_TOT[1], NX0_TOT[0], FFTW_REAL_TO_COMPLEX,
FFTW_ESTIMATE | FFTW_IN_PLACE );
FFTW_Plan_Inv = rfftw3d_create_plan( NX0_TOT[2], NX0_TOT[1], NX0_TOT[0], FFTW_COMPLEX_TO_REAL,
FFTW_ESTIMATE | FFTW_IN_PLACE );
# else
FFTW_Plan = rfftw3d_mpi_create_plan( MPI_COMM_WORLD, NX0_TOT[2], NX0_TOT[1], NX0_TOT[0],
FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE );
FFTW_Plan_Inv = rfftw3d_mpi_create_plan( MPI_COMM_WORLD, NX0_TOT[2], NX0_TOT[1], NX0_TOT[0],
FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE );
# endif
if ( MPI_Rank == 0 ) Aux_Message( stdout, "done\n" );
} // FUNCTION : Init_FFTW
//-------------------------------------------------------------------------------------------------------
// Function : End_FFTW
// Description : Delete the FFTW plans
//-------------------------------------------------------------------------------------------------------
void End_FFTW()
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s ... ", __FUNCTION__ );
# ifdef SERIAL
rfftwnd_destroy_plan ( FFTW_Plan );
rfftwnd_destroy_plan ( FFTW_Plan_Inv );
# else
rfftwnd_mpi_destroy_plan( FFTW_Plan );
rfftwnd_mpi_destroy_plan( FFTW_Plan_Inv );
# endif
if ( MPI_Rank == 0 ) Aux_Message( stdout, "done\n" );
} // FUNCTION : End_FFTW
#endif // #ifdef GRAVITY
| 27.932432 | 105 | 0.490082 | zhulianhua |
c7f08fc096d3392d0f15755c7d8791cb590f6508 | 552 | hpp | C++ | android-31/java/lang/LinkageError.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/lang/LinkageError.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/lang/LinkageError.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "./Error.hpp"
class JString;
class JThrowable;
namespace java::lang
{
class LinkageError : public java::lang::Error
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit LinkageError(const char *className, const char *sig, Ts...agv) : java::lang::Error(className, sig, std::forward<Ts>(agv)...) {}
LinkageError(QJniObject obj);
// Constructors
LinkageError();
LinkageError(JString arg0);
LinkageError(JString arg0, JThrowable arg1);
// Methods
};
} // namespace java::lang
| 19.714286 | 163 | 0.688406 | YJBeetle |
c7f19c0e759845db014af34b2e387e65bb1dfc3e | 786 | cc | C++ | src/obj/object.cc | abyss7/libgit- | 0e2dee26fbe64ebfb6a6cfa332b8dc4a3bdea11d | [
"MIT"
] | 1 | 2019-11-09T22:22:23.000Z | 2019-11-09T22:22:23.000Z | src/obj/object.cc | abyss7/libgitxx | 0e2dee26fbe64ebfb6a6cfa332b8dc4a3bdea11d | [
"MIT"
] | null | null | null | src/obj/object.cc | abyss7/libgitxx | 0e2dee26fbe64ebfb6a6cfa332b8dc4a3bdea11d | [
"MIT"
] | null | null | null | #include "object.hh"
#include <base/exception.hh>
namespace git {
Object::Type Object::type() const {
switch (git_object_type(raw_object())) {
case GIT_OBJ_BLOB:
return BLOB;
case GIT_OBJ_COMMIT:
return COMMIT;
case GIT_OBJ_TREE:
return TREE;
default:
return UNKNOWN;
}
}
Object::Id::Id(const String& content, Type type) : _id(new git_oid) {
git_otype git_type;
switch (type) {
case BLOB:
git_type = GIT_OBJ_BLOB;
break;
case COMMIT:
git_type = GIT_OBJ_COMMIT;
break;
case TREE:
git_type = GIT_OBJ_TREE;
break;
default:
git_type = GIT_OBJ_BAD;
}
TryGitCall(git_odb_hash(const_cast<git_oid*>(_id.get()), content.data(), content.size(), git_type));
}
} // namespace git
| 19.170732 | 102 | 0.63486 | abyss7 |
c7f448a0f4c0ed6170eca03602a0725b897d3871 | 404 | cpp | C++ | swig_example/third party/swig-example.cpp | Lukemtesta/python-binding | bef3978ac48ce4e683014798ccac9a88cfd73ee0 | [
"Apache-2.0"
] | null | null | null | swig_example/third party/swig-example.cpp | Lukemtesta/python-binding | bef3978ac48ce4e683014798ccac9a88cfd73ee0 | [
"Apache-2.0"
] | null | null | null | swig_example/third party/swig-example.cpp | Lukemtesta/python-binding | bef3978ac48ce4e683014798ccac9a88cfd73ee0 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include "liba.h"
#include "swig-example.h"
void swig_example_hello()
{
std::cout << "Hello from swig-example" << std::endl;
}
void link_liba_hello()
{
liba_hello();
}
void blah()
{
std::cout << "blah" << std::endl;
}
void vector_print()
{
std::cout << "vector print" << std::endl;
}
std::vector<int> random_vector_int()
{
return std::vector<int>{ 1, 2, 3, 4, 5 };
} | 13.466667 | 56 | 0.618812 | Lukemtesta |
c7f53d3c297632110eedc8c7962b70178fa1f375 | 667 | cpp | C++ | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/VolumeEvent.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 4 | 2016-03-29T21:45:21.000Z | 2016-12-20T00:50:38.000Z | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/VolumeEvent.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | null | null | null | src/tests/add-ons/kernel/file_systems/userlandfs/r5/src/test/netfs/client/VolumeEvent.cpp | axeld/haiku | e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4 | [
"MIT"
] | 3 | 2018-12-17T13:07:38.000Z | 2021-09-08T13:07:31.000Z | // VolumeEvent.cpp
#include "VolumeEvent.h"
// constructor
VolumeEvent::VolumeEvent(uint32 type, vnode_id target)
: Referencable(true),
fType(type),
fTarget(target)
{
}
// destructor
VolumeEvent::~VolumeEvent()
{
}
// GetType
uint32
VolumeEvent::GetType() const
{
return fType;
}
// SetTarget
void
VolumeEvent::SetTarget(vnode_id target)
{
fTarget = target;
}
// GetTarget
vnode_id
VolumeEvent::GetTarget() const
{
return fTarget;
}
// #pragma mark -
// constructor
ConnectionBrokenEvent::ConnectionBrokenEvent(vnode_id target)
: VolumeEvent(CONNECTION_BROKEN_EVENT, target)
{
}
// destructor
ConnectionBrokenEvent::~ConnectionBrokenEvent()
{
}
| 12.584906 | 61 | 0.736132 | axeld |
c7fe942d4e6736080ae2b254888cb2a4396eb117 | 5,140 | cc | C++ | src/cpp/charmove.cc | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | 32 | 2015-02-21T17:11:50.000Z | 2022-02-10T16:34:16.000Z | src/cpp/charmove.cc | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | null | null | null | src/cpp/charmove.cc | Tomius/LoD | 6011e3a80367009d541ef6668aeb6d61d381d348 | [
"MIT"
] | 8 | 2016-05-30T07:24:19.000Z | 2021-11-13T10:46:27.000Z | // Copyright (c) 2014, Tamas Csala
#include "./charmove.h"
#include <GLFW/glfw3.h>
#include <algorithm>
#include "engine/game_engine.h"
CharacterMovement::CharacterMovement(engine::GameObject *parent,
float horizontal_speed,
float rotationSpeed_PerSec)
: engine::GameObject(parent)
, transform_(*parent->transform())
, curr_rot_(0)
, dest_rot_(0)
, rot_speed_(rotationSpeed_PerSec)
, vert_speed_(0)
, horiz_speed_(horizontal_speed)
, horiz_speed_factor_(1.0f)
, walking_(false)
, jumping_(false)
, flip_(false)
, can_flip_(true)
, transition_(false)
, anim_(nullptr)
, camera_(nullptr)
, can_jump_functor_(nullptr)
, can_flip_functor_(nullptr)
{ }
void CharacterMovement::handleSpacePressed() {
if (!jumping_) {
if (can_jump_functor_ == nullptr || can_jump_functor_()) {
jumping_ = true;
flip_ = false;
vert_speed_ = 10.0f;
horiz_speed_factor_ = 1.0f;
}
} else if (can_flip_) {
if (can_flip_functor_ == nullptr || can_flip_functor_()) {
can_flip_ = false;
flip_ = true;
vert_speed_ = 11.0f;
horiz_speed_factor_ = 1.3f;
}
}
}
void CharacterMovement::update() {
float time = scene_->game_time().current;
const engine::Camera& cam = *camera_;
glm::vec2 character_offset = anim_->offsetSinceLastFrame();
static float prevTime = 0;
float dt = time - prevTime;
prevTime = time;
glm::ivec2 moveDir; // up and right is positive
bool w = glfwGetKey(scene_->window(), GLFW_KEY_W) == GLFW_PRESS;
bool a = glfwGetKey(scene_->window(), GLFW_KEY_A) == GLFW_PRESS;
bool s = glfwGetKey(scene_->window(), GLFW_KEY_S) == GLFW_PRESS;
bool d = glfwGetKey(scene_->window(), GLFW_KEY_D) == GLFW_PRESS;
if (w && !s) {
moveDir.y = 1;
} else if (s && !w) {
moveDir.y = -1;
}
if (d && !a) {
moveDir.x = 1;
} else if (a && !d) {
moveDir.x = -1;
}
static glm::ivec2 lastMoveDir;
bool lastWalking = walking_;
walking_ = moveDir.x || moveDir.y;
transition_ = transition_ || (walking_ != lastWalking) ||
(lastMoveDir != moveDir);
lastMoveDir = moveDir;
if (walking_) {
glm::vec3 fwd = cam.transform()->forward();
double cameraRot = -atan2(fwd.z, fwd.x);
double moveRot = atan2(moveDir.y, moveDir.x); // +y is forward
dest_rot_ = cameraRot + moveRot;
dest_rot_ = fmod(dest_rot_, 2*M_PI);
double diff = dest_rot_ - curr_rot_;
double sign = diff / fabs(diff);
// Take the shorter path.
while (fabs(diff) > M_PI) {
dest_rot_ -= sign * 2*M_PI;
diff = dest_rot_ - curr_rot_;
sign = diff / fabs(diff);
}
if (transition_) {
if (fabs(diff) > rot_speed_ / 20.0f) {
curr_rot_ += sign * dt * rot_speed_;
curr_rot_ = fmod(curr_rot_, 2*M_PI);
} else {
transition_ = false;
}
} else {
curr_rot_ = fmod(dest_rot_, 2*M_PI);
}
}
glm::mat4 rotation = glm::rotate(glm::mat4(),
static_cast<float>(fmod(curr_rot_, 2*M_PI)),
glm::vec3(0, 1, 0));
transform_.set_rot(glm::quat_cast(rotation));
glm::vec3 pos = transform_.pos();
pos += glm::mat3(rotation) *
glm::vec3(character_offset.x, 0, character_offset.y);
if (jumping_) {
pos += glm::mat3(rotation) *
glm::vec3(0, 0, horiz_speed_ * horiz_speed_factor_ * dt);
}
transform_.set_pos(pos);
updateHeight(time);
}
void CharacterMovement::keyAction(int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
handleSpacePressed();
}
}
void CharacterMovement::updateHeight(float time) {
glm::vec3 local_pos = transform_.local_pos();
static float prevTime = 0;
float diff_time = time - prevTime;
prevTime = time;
while (diff_time > 0) {
float time_step = 0.01f;
float dt = std::min(time_step, diff_time);
diff_time -= time_step;
if (local_pos.y < 0 && jumping_ && vert_speed_ < 0) {
jumping_ = false;
flip_ = false;
can_flip_ = true;
local_pos.y = 0;
return;
}
if (!jumping_) {
const float offs =
std::max<float>(fabs(local_pos.y / 2.0f), 0.05f) * dt * 20.0f;
if (fabs(local_pos.y) > offs) {
local_pos.y -= local_pos.y / fabs(local_pos.y) * offs;
}
} else {
if (local_pos.y < 0) {
local_pos.y += std::max(local_pos.y, vert_speed_) * dt;
} else {
local_pos.y += vert_speed_ * dt;
}
vert_speed_ -= dt * scene_->gravity();
}
}
transform_.set_local_pos(local_pos);
}
bool CharacterMovement::isJumping() const {
return jumping_;
}
bool CharacterMovement::isJumpingRise() const {
return jumping_ && !flip_ && vert_speed_ > 0;
}
bool CharacterMovement::isJumpingFall() const {
return jumping_ && !flip_ && vert_speed_ < 0;
}
bool CharacterMovement::isDoingFlip() const {
return flip_;
}
void CharacterMovement::setFlip(bool flip) {
flip_ = flip;
}
bool CharacterMovement::isWalking() const {
return walking_;
}
| 26.091371 | 80 | 0.6107 | Tomius |
2a0ae0111bb4284ec5b9af8e8406546f232bdd2b | 215 | cpp | C++ | Plugins/VirtuosoInput/Source/VirtuosoInput/Private/VirtuosoTrackingState.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | 3 | 2021-05-26T14:12:01.000Z | 2022-01-09T01:15:12.000Z | Plugins/VirtuosoInput/Source/VirtuosoInput/Private/VirtuosoTrackingState.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | null | null | null | Plugins/VirtuosoInput/Source/VirtuosoInput/Private/VirtuosoTrackingState.cpp | charles-river-analytics/VSDK-Unreal | 0f99ec140f6d6660a09148163bdd006c5ecc67d5 | [
"MIT"
] | null | null | null | // Copyright 2020 Charles River Analytics, Inc. All Rights Reserved.
#include "VirtuosoTrackingState.h"
UVirtuosoTrackingState::UVirtuosoTrackingState()
{
}
UVirtuosoTrackingState::~UVirtuosoTrackingState()
{
}
| 16.538462 | 68 | 0.795349 | charles-river-analytics |
2a0f66cf05f312fc1cc7e36ec7f09caf9c29361f | 13,868 | cpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AudioPlayer/volume_bar.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AudioPlayer/volume_bar.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/images/src/AudioPlayer/volume_bar.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | // Generated by imageconverter. Please, do not edit!
#include <touchgfx/hal/Config.hpp>
LOCATION_EXTFLASH_PRAGMA
KEEP extern const unsigned char _volume_bar[] LOCATION_EXTFLASH_ATTRIBUTE = { // 170x4 ARGB8888 pixels.
0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x27,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x27,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,
0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x33,0xff,0xff,0xff,0x27
};
| 252.145455 | 320 | 0.797159 | ramkumarkoppu |
2a101a79b18945b9f171d6ce995edb45c666134c | 7,774 | cpp | C++ | src/hash_tables.cpp | dfwteinos/Search-Clustering | 174a26ac7aabf9d3a7ce06976e3ebe77c6a8c1bd | [
"MIT"
] | null | null | null | src/hash_tables.cpp | dfwteinos/Search-Clustering | 174a26ac7aabf9d3a7ce06976e3ebe77c6a8c1bd | [
"MIT"
] | null | null | null | src/hash_tables.cpp | dfwteinos/Search-Clustering | 174a26ac7aabf9d3a7ce06976e3ebe77c6a8c1bd | [
"MIT"
] | null | null | null | #include "../include/hash_tables.h"
#include "../include/arguments.h"
template <class T>
HashTable<T>::HashTable(vector_list_collection<T> data_set, int k_value, int l_value, int R_value, int N_value, double C_value)
{
table_size = data_set.size() / 16;
vector_size = data_set[0].second.size();
K = k_value;
L = l_value;
R = R_value;
N = N_value;
c = C_value;
}
template <class T>
T manhattan_distance(std::vector<T> x, std::vector<T> y)
{
T result = 0;
typename std::vector<T>::iterator it;
typename std::vector<T>::iterator ti;
for (it = x.begin(), ti = y.begin(); it != x.end(); ++it, ++ti)
{
result += abs(*it - *ti);
}
return result;
}
template <class T>
bool sortbysec(cand_img<T> &a, cand_img<T> &b)
{
return (a.second < b.second);
}
template <class T>
image<T> bruteforce(vector_list_collection<T> data_set, image<T> query, T &res)
{
image<T> best;
T best_distance = std::numeric_limits<T>::max();
T current;
for (ssize_t i = 0; i < data_set.size(); i++)
{
current = manhattan_distance<T>(data_set[i].second, query.second);
if (current < best_distance)
{
best_distance = current;
best = data_set[i];
}
}
res = best_distance;
return best;
}
template <class T>
std::vector<cand_img<T>> bruteforcelsh(vector_list_collection<T> data_set, image<T> query, int N)
{
std::vector<cand_img<T>> best_imgs(N); //Vector with <Key:Image , Value:Distance>
best_imgs.clear();
image<T> temp_img; //Each image that we check
T temp_dist; //Each distance that we check
cand_img<T> temp_cand; //A pair of image and its distance
for (int i = 0; i < data_set.size(); i++)
{
temp_img = data_set[i];
temp_dist = manhattan_distance<T>(data_set[i].second, query.second);
temp_cand = make_pair(temp_img, temp_dist);
if (i <= N)
{ //If our list is not full
if (i == N)
{
std::sort(best_imgs.begin(), best_imgs.end(), sortbysec<T>);
if (temp_dist < best_imgs.back().second)
{ //If the temp. distance if lower than the last item of our candidates, then replace it
best_imgs[N - 1] = temp_cand; //If doesen't work, try vector.insert(vector.end(), x)
std::sort(best_imgs.begin(), best_imgs.end(), sortbysec<T>);
}
}
else
best_imgs.push_back(temp_cand);
}
else
{ //If our list is full, then we need to compare the elements
if (temp_dist < best_imgs.back().second)
{ //If the temp. distance if lower than the last item of our candidates, then replace it
best_imgs[N - 1] = temp_cand; //If doesen't work, try vector.insert(vector.end(), x)
std::sort(best_imgs.begin(), best_imgs.end(), sortbysec<T>);
}
}
}
return best_imgs;
}
uint32_t swap_endian(uint32_t val)
{
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | (val >> 16);
}
void read_metadata(std::ifstream &file, uint32_t &magic_num, uint32_t &num_of_images, uint32_t &rows, uint32_t &columns, int size)
{ //Take the metadata (magic number, number of images, rows and columns)
file.read(reinterpret_cast<char *>(&magic_num), size); //we are doing this type of cast bcz we are playing with bits, and bcz we want to convert: 0x00000803 -> 2051
magic_num = swap_endian(magic_num);
std::cout << "magic num: " << magic_num << std::endl;
file.read(reinterpret_cast<char *>(&num_of_images), size);
num_of_images = swap_endian(num_of_images);
std::cout << "#images: " << num_of_images << std::endl;
file.read(reinterpret_cast<char *>(&rows), size);
rows = swap_endian(rows);
std::cout << "#rows: " << rows << std::endl;
file.read(reinterpret_cast<char *>(&columns), size);
columns = swap_endian(columns);
std::cout << "#columns: " << columns << std::endl;
}
template <class T>
vector_list_collection<T> HashTable<T>::vectorise_data(std::string file_name)
{
vector_list_collection<T> data;
std::ifstream file; // Stream class to read from files
file.open(file_name, std::ios::in | std::ios::binary); // in(open for input operations), binary(open in binary mode)
if (file.is_open()) //If the file has successfully opened
{
uint32_t magic_num = 0, num_of_images = 0, rows = 0, columns = 0; //uint32_t => unsigned byte, [ 0, 2^32 -1 ]. That's the type of the magic num, noi,r, c, according to the assignment.
read_metadata(file, magic_num, num_of_images, rows, columns, 4);
for (uint32_t i = 0; i < num_of_images; ++i)
{
data.push_back(std::pair<int, std::vector<T>>(i, std::vector<T>()));
for (uint32_t r = 0; r < rows; ++r)
{
for (uint32_t c = 0; c < columns; ++c)
{
unsigned char temp = 0;
file.read((char *)&temp, sizeof(temp));
data[i].second.push_back((int)temp); //each pixel of image (Question(?)) => Why not (char) temp? Each pixel is 0 until 255. Int is a waste of memory(?)
}
}
}
std::cout << "done reading files" << std::endl;
}
else
{
std::cout << "Something went wrong while reading the file " << file_name << std::endl;
exit(EXIT_FAILURE);
}
return data;
}
template <class T>
void HashTable<T>::get_neighbours(std::ostream &my_file)
{
if (this->R != 0)
{
for (auto it = this->neighbours.begin(); it != this->neighbours.end(); it++)
{
my_file << (*it).first << std::endl;
}
}
this->neighbours.clear();
return;
}
template <class T>
bool handle_conflicts(vector_list_collection<T> ¢roids, image<T> &image, clusters<T> &i2c, int dist)
{
for (auto it = i2c.begin(); it != i2c.end(); ++it) //For all vectors of centroids
{
int index = 0;
for (auto ti = (it->second).begin(); ti < (it->second).end(); ++ti) //Check if given image is part of any cluster
{
if (image.first == ti->first) //If yes, calculate the Manhattan distance between cluster's centroid and image
{
if (manhattan_distance(image.second, (it->first).second) > dist)
{
(it->second).erase((it->second).begin() + index); //If distance is larger than given distance erase image from current cluster
return true;
}
else
{
return false;
}
}
index++;
}
}
return true; //If it reaches that point, given image wasn't part of any cluster yet
}
template class HashTable<int>;
template class HashTable<double>;
template image<int> bruteforce(vector_list_collection<int>, image<int>, int &);
template image<double> bruteforce(vector_list_collection<double>, image<double>, double &);
template std::vector<cand_img<int>> bruteforcelsh(vector_list_collection<int>, image<int>, int);
template std::vector<cand_img<double>> bruteforcelsh(vector_list_collection<double>, image<double>, int);
template bool sortbysec<int>(cand_img<int> &a, cand_img<int> &b);
template bool sortbysec<double>(cand_img<double> &a, cand_img<double> &b);
template bool handle_conflicts<int>(vector_list_collection<int> &, image<int> &, clusters<int> &, int);
template bool handle_conflicts<double>(vector_list_collection<double> &, image<double> &, clusters<double> &, int);
| 33.65368 | 191 | 0.593645 | dfwteinos |
2a13ee99d2c4490dda1e4ba956ef71fd24d735c8 | 16,691 | cpp | C++ | src/test/dag/temporal_components.cpp | arashbm/dag | 26559581f696fabf7aacb3fbc045df811ddbd37d | [
"MIT"
] | null | null | null | src/test/dag/temporal_components.cpp | arashbm/dag | 26559581f696fabf7aacb3fbc045df811ddbd37d | [
"MIT"
] | 14 | 2021-05-24T12:11:05.000Z | 2022-03-02T22:15:01.000Z | src/test/dag/temporal_components.cpp | arashbm/dag | 26559581f696fabf7aacb3fbc045df811ddbd37d | [
"MIT"
] | null | null | null | #include <vector>
#include <set>
#include <unordered_set>
#include <catch2/catch.hpp>
using Catch::Matchers::UnorderedEquals;
using Catch::Matchers::Equals;
#include <dag/temporal_components.hpp>
#include <dag/temporal_edges.hpp>
#include <dag/estimators.hpp>
TEST_CASE("temporal components", "[dag::temporal_component]") {
using EdgeType = dag::directed_delayed_temporal_edge<int, int>;
dag::temporal_component<EdgeType, dag::exact_estimator> comp(0ul);
EdgeType a(1, 2, 1, 3), b(2, 1, 2, 1), c(2, 3, 6, 1);
comp.insert(a, a.mutated_verts());
comp.insert(b, b.mutated_verts());
SECTION("correct basic properties") {
REQUIRE(comp.node_set().set() == std::unordered_set<int>({1, 2}));
REQUIRE(comp.edge_set().set() == std::unordered_set<EdgeType>({a, b}));
REQUIRE(comp.cause_lifetime() == std::make_pair(1, 2));
REQUIRE(comp.effect_lifetime() == std::make_pair(3, 4));
}
SECTION("insertion") {
comp.insert(c, c.mutated_verts());
REQUIRE(comp.node_set().set() == std::unordered_set<int>({1, 2, 3}));
REQUIRE(comp.edge_set().set() == std::unordered_set<EdgeType>({a, b, c}));
REQUIRE(comp.cause_lifetime() == std::make_pair(1, 6));
REQUIRE(comp.effect_lifetime() == std::make_pair(3, 7));
}
SECTION("merging") {
dag::temporal_component<EdgeType, dag::exact_estimator> comp2(0ul);
comp2.insert(c, c.mutated_verts());
comp.merge(comp2);
REQUIRE(comp.node_set().set() == std::unordered_set<int>({1, 2, 3}));
REQUIRE(comp.edge_set().set() == std::unordered_set<EdgeType>({a, b, c}));
REQUIRE(comp.cause_lifetime() == std::make_pair(1, 6));
REQUIRE(comp.effect_lifetime() == std::make_pair(3, 7));
}
}
#include "../../../include/dag/implicit_event_graph.hpp"
TEST_CASE("in- and out- components for implicit event graph",
"[dag::out_component][dag::in_component]"
"[dag::out_components][dag::in_components]") {
SECTION("undirected temporal network") {
using EdgeType = dag::undirected_temporal_edge<int, int>;
using ProbType = dag::adjacency_prob::deterministic<EdgeType>;
using CompType = dag::temporal_component<EdgeType, dag::exact_estimator>;
dag::network<EdgeType> network(
{{1, 2, 1}, {2, 1, 2}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}, {5, 6, 1}});
ProbType prob(3);
dag::implicit_event_graph<EdgeType, ProbType> eg(network, prob, 0ul);
SECTION("out component") {
CompType c = dag::out_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {3, 4, 8}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 3, 4}));
}
SECTION("in component") {
CompType c = dag::in_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {1, 2, 5}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 3, 1}));
}
SECTION("all out components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_oc({
{{1, 2, 1}, {{1, 2, 1}, {2, 1, 2}}},
{{2, 1, 2}, {{2, 1, 2}}},
{{1, 2, 5}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{2, 3, 6}, {{2, 3, 6}, {3, 4, 8}}},
{{3, 4, 8}, {{3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{1, 2, 1}, {1, 2, 5}, {5, 6, 1}})));
}
SECTION("root and non-root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("all in components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_ic({
{{2, 1, 2}, {{2, 1, 2}, {1, 2, 1}}},
{{1, 2, 1}, {{1, 2, 1}}},
{{1, 2, 5}, {{1, 2, 5}}},
{{2, 3, 6}, {{1, 2, 5}, {2, 3, 6}}},
{{3, 4, 8}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{2, 1, 2}, {3, 4, 8}, {5, 6, 1}})));
}
SECTION("root and non-root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("weakly connected components") {
std::set<EdgeType>
w1({{1, 2, 1}, {2, 1, 2}}),
w2({{2, 3, 6}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}}),
w3({{5, 6, 1}});
SECTION("with singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2, w3}));
}
SECTION("without singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul, false);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2}));
}
}
}
SECTION("directed temporal network") {
using EdgeType = dag::directed_temporal_edge<int, int>;
using ProbType = dag::adjacency_prob::deterministic<EdgeType>;
using CompType = dag::temporal_component<EdgeType, dag::exact_estimator>;
dag::network<EdgeType> network(
{{1, 2, 1}, {2, 1, 2}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}, {5, 6, 1}});
ProbType prob(3);
dag::implicit_event_graph<EdgeType, ProbType> eg(network, prob, 0ul);
SECTION("out component") {
CompType c = dag::out_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {3, 4, 8}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({3, 4}));
}
SECTION("in component") {
CompType c = dag::in_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6}, {1, 2, 5}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 1}));
}
SECTION("all out components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_oc({
{{1, 2, 1}, {{1, 2, 1}, {2, 1, 2}}},
{{2, 1, 2}, {{2, 1, 2}}},
{{1, 2, 5}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{2, 3, 6}, {{2, 3, 6}, {3, 4, 8}}},
{{3, 4, 8}, {{3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{1, 2, 1}, {1, 2, 5}, {5, 6, 1}})));
}
SECTION("root and non-root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("all in components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_ic({
{{2, 1, 2}, {{2, 1, 2}, {1, 2, 1}}},
{{1, 2, 1}, {{1, 2, 1}}},
{{1, 2, 5}, {{1, 2, 5}}},
{{2, 3, 6}, {{1, 2, 5}, {2, 3, 6}}},
{{3, 4, 8}, {{1, 2, 5}, {2, 3, 6}, {3, 4, 8}}},
{{5, 6, 1}, {{5, 6, 1}}},
});
SECTION("root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{2, 1, 2}, {3, 4, 8}, {5, 6, 1}})));
}
SECTION("root and non-root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("weakly connected components") {
std::set<EdgeType>
w1({{1, 2, 1}, {2, 1, 2}}),
w2({{2, 3, 6}, {1, 2, 5}, {2, 3, 6}, {3, 4, 8}}),
w3({{5, 6, 1}});
SECTION("with singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2, w3}));
}
SECTION("without singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul, false);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results ==
std::set<std::set<EdgeType>>({w1, w2}));
}
}
}
SECTION("directed delayed temporal network") {
using EdgeType = dag::directed_delayed_temporal_edge<int, int>;
using ProbType = dag::adjacency_prob::deterministic<EdgeType>;
using CompType = dag::temporal_component<EdgeType, dag::exact_estimator>;
dag::network<EdgeType> network(
{{1, 2, 1, 4}, {2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1}, {3, 4, 8, 1},
{5, 6, 1, 2}});
ProbType prob(3);
dag::implicit_event_graph<EdgeType, ProbType> eg(network, prob, 0ul);
SECTION("out component") {
CompType c = dag::out_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6, 1}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>({{2, 3, 6, 1}, {3, 4, 8, 1}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({3, 4}));
}
SECTION("in component") {
CompType c = dag::in_component<EdgeType, ProbType, dag::exact_estimator>(
eg, {2, 3, 6, 1}, 0ul);
REQUIRE(c.edge_set().set() ==
std::unordered_set<EdgeType>(
{{2, 1, 2, 1}, {2, 3, 6, 1}, {1, 2, 5, 0}, {1, 2, 1, 4}}));
REQUIRE(c.node_set().set() ==
std::unordered_set<int>({2, 1}));
}
SECTION("all out components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_oc({
{{1, 2, 1, 4}, {{1, 2, 1, 4}, {2, 3, 6, 1}, {3, 4, 8, 1}}},
{{2, 1, 2, 1},
{{2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1}, {3, 4, 8, 1}}},
{{1, 2, 5, 0}, {{1, 2, 5, 0}, {2, 3, 6, 1}, {3, 4, 8, 1}}},
{{2, 3, 6, 1}, {{2, 3, 6, 1}, {3, 4, 8, 1}}},
{{3, 4, 8, 1}, {{3, 4, 8, 1}}},
{{5, 6, 1, 2}, {{5, 6, 1, 2}}},
});
SECTION("root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>(
{{1, 2, 1, 4}, {2, 1, 2, 1}, {5, 6, 1, 2}})));
}
SECTION("root and non-root out components") {
auto out_comps = dag::out_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: out_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_oc[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("all in components") {
std::unordered_map<EdgeType, std::unordered_set<EdgeType>> true_ic({
{{1, 2, 1, 4}, {{1, 2, 1, 4}}},
{{2, 1, 2, 1}, {{2, 1, 2, 1}}},
{{1, 2, 5, 0}, {{1, 2, 5, 0}, {2, 1, 2, 1}}},
{{2, 3, 6, 1},
{{2, 3, 6, 1}, {1, 2, 5, 0}, {2, 1, 2, 1}, {1, 2, 1, 4}}},
{{3, 4, 8, 1},
{{2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1},
{1, 2, 1, 4}, {3, 4, 8, 1}}},
{{5, 6, 1, 2}, {{5, 6, 1, 2}}},
});
SECTION("root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul, true);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys,
UnorderedEquals(
std::vector<EdgeType>({{3, 4, 8, 1}, {5, 6, 1, 2}})));
}
SECTION("root and non-root in components") {
auto in_comps = dag::in_components<
EdgeType, ProbType, dag::exact_estimator, dag::exact_estimator>(
eg, 0ul);
std::vector<EdgeType> keys;
for (auto&& [e, c]: in_comps) {
keys.push_back(e);
REQUIRE(c.edge_set().set() == true_ic[e]);
}
REQUIRE_THAT(keys, UnorderedEquals(network.edges_cause()));
}
}
SECTION("weakly connected components") {
std::set<EdgeType>
w1({{1, 2, 1, 4}, {2, 1, 2, 1}, {1, 2, 5, 0}, {2, 3, 6, 1},
{3, 4, 8, 1}}),
w2({{5, 6, 1, 2}});
SECTION("with singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results == std::set<std::set<EdgeType>>({w1, w2}));
}
SECTION("without singletons") {
auto weakly_comps = dag::weakly_connected_components<
EdgeType, ProbType, dag::exact_estimator>(eg, 0ul, false);
std::set<std::set<EdgeType>> results;
for (auto&& c: weakly_comps)
results.emplace(c.edge_set().set().begin(), c.edge_set().set().end());
REQUIRE(results == std::set<std::set<EdgeType>>({w1}));
}
}
}
}
| 36.60307 | 80 | 0.522617 | arashbm |
2a14be0a116e52c8069e13b13ed08e3b958a4d5b | 11,002 | cpp | C++ | HoloIntervention/Source/Rendering/CameraResources.cpp | adamrankin/HoloIntervention | 0f2a4dc702729a0a04af5c210884ef4e08e49267 | [
"Apache-2.0"
] | 2 | 2020-06-17T09:55:59.000Z | 2021-04-03T16:18:29.000Z | HoloIntervention/Source/Rendering/CameraResources.cpp | adamrankin/HoloIntervention | 0f2a4dc702729a0a04af5c210884ef4e08e49267 | [
"Apache-2.0"
] | 1 | 2018-09-02T02:39:21.000Z | 2018-09-02T02:39:21.000Z | HoloIntervention/Source/Rendering/CameraResources.cpp | adamrankin/HoloIntervention | 0f2a4dc702729a0a04af5c210884ef4e08e49267 | [
"Apache-2.0"
] | null | null | null | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
// Local includes
#include "pch.h"
#include "CameraResources.h"
#include "DeviceResources.h"
#include "DirectXHelper.h"
// WinRT includes
#include <windows.graphics.directx.direct3d11.interop.h>
// Unnecessary, but reduces intellisense errors
#include <WindowsNumerics.h>
using namespace DirectX;
using namespace Microsoft::WRL;
using namespace Windows::Foundation::Numerics;
using namespace Windows::Graphics::DirectX::Direct3D11;
using namespace Windows::Graphics::Holographic;
using namespace Windows::Perception::Spatial;
namespace DX
{
//----------------------------------------------------------------------------
CameraResources::CameraResources(HolographicCamera^ camera)
: m_holographicCamera(camera)
, m_isStereo(camera->IsStereo)
, m_d3dRenderTargetSize(camera->RenderTargetSize)
{
m_d3dViewport = CD3D11_VIEWPORT(0.f, 0.f, m_d3dRenderTargetSize.Width, m_d3dRenderTargetSize.Height);
};
//----------------------------------------------------------------------------
void CameraResources::CreateResourcesForBackBuffer(
DX::DeviceResources* pDeviceResources,
HolographicCameraRenderingParameters^ cameraParameters
)
{
const auto device = pDeviceResources->GetD3DDevice();
IDirect3DSurface^ surface = cameraParameters->Direct3D11BackBuffer;
ComPtr<ID3D11Resource> resource;
DX::ThrowIfFailed(GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(&resource)));
ComPtr<ID3D11Texture2D> cameraBackBuffer;
DX::ThrowIfFailed(resource.As(&cameraBackBuffer));
if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
{
m_d3dBackBuffer = cameraBackBuffer;
DX::ThrowIfFailed(device->CreateRenderTargetView(m_d3dBackBuffer.Get(), nullptr, &m_d3dRenderTargetView));
D3D11_TEXTURE2D_DESC backBufferDesc;
m_d3dBackBuffer->GetDesc(&backBufferDesc);
m_dxgiFormat = backBufferDesc.Format;
Windows::Foundation::Size currentSize = m_holographicCamera->RenderTargetSize;
if (m_d3dRenderTargetSize != currentSize)
{
m_d3dRenderTargetSize = currentSize;
m_d3dDepthStencilView.Reset();
}
}
// Refresh depth stencil resources, if needed.
if (m_d3dDepthStencilView == nullptr)
{
CD3D11_TEXTURE2D_DESC depthStencilDesc(DXGI_FORMAT_D16_UNORM, static_cast<UINT>(m_d3dRenderTargetSize.Width), static_cast<UINT>(m_d3dRenderTargetSize.Height),
m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
1, // Use a single mipmap level.
D3D11_BIND_DEPTH_STENCIL
);
ComPtr<ID3D11Texture2D> depthStencil;
DX::ThrowIfFailed(device->CreateTexture2D(&depthStencilDesc, nullptr, &depthStencil));
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D);
DX::ThrowIfFailed(device->CreateDepthStencilView(depthStencil.Get(), &depthStencilViewDesc, &m_d3dDepthStencilView));
}
// Create the constant buffer, if needed.
if (m_viewProjectionConstantBuffer == nullptr)
{
// Create a constant buffer to store view and projection matrices for the camera.
CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
DX::ThrowIfFailed(device->CreateBuffer(&constantBufferDesc, nullptr, &m_viewProjectionConstantBuffer));
}
}
//----------------------------------------------------------------------------
void CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
{
const auto context = pDeviceResources->GetD3DDeviceContext();
// Release camera-specific resources.
m_d3dBackBuffer.Reset();
m_d3dRenderTargetView.Reset();
m_d3dDepthStencilView.Reset();
m_viewProjectionConstantBuffer.Reset();
// Ensure system references to the back buffer are released by clearing the render
// target from the graphics pipeline state, and then flushing the Direct3D context.
ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
context->Flush();
}
//----------------------------------------------------------------------------
bool CameraResources::Update(std::shared_ptr<DX::DeviceResources> deviceResources, HolographicCameraPose^ cameraPose, SpatialCoordinateSystem^ coordinateSystem)
{
m_d3dViewport = CD3D11_VIEWPORT(cameraPose->Viewport.Left, cameraPose->Viewport.Top, cameraPose->Viewport.Width, cameraPose->Viewport.Height);
HolographicStereoTransform cameraProjectionTransform = cameraPose->ProjectionTransform;
Platform::IBox<HolographicStereoTransform>^ viewTransformContainer = cameraPose->TryGetViewTransform(coordinateSystem);
auto frustrumBox = cameraPose->TryGetCullingFrustum(coordinateSystem);
if (frustrumBox != nullptr)
{
m_spatialBoundingFrustum = std::make_shared<SpatialBoundingFrustum>(frustrumBox->Value);
}
bool viewTransformAcquired = viewTransformContainer != nullptr;
if (viewTransformAcquired)
{
HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer->Value;
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.hmdToView[0], XMLoadFloat4x4(&viewCoordinateSystemTransform.Left));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.hmdToView[1], XMLoadFloat4x4(&viewCoordinateSystemTransform.Right));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.projection[0], XMLoadFloat4x4(&cameraProjectionTransform.Left));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.projection[1], XMLoadFloat4x4(&cameraProjectionTransform.Right));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.viewProjection[0], XMLoadFloat4x4(&viewCoordinateSystemTransform.Left) * XMLoadFloat4x4(&cameraProjectionTransform.Left));
XMStoreFloat4x4(&m_cpuViewProjectionConstantBuffer.viewProjection[1], XMLoadFloat4x4(&viewCoordinateSystemTransform.Right) * XMLoadFloat4x4(&cameraProjectionTransform.Right));
float4x4 viewInverse;
bool invertible = Windows::Foundation::Numerics::invert(viewCoordinateSystemTransform.Left, &viewInverse);
if (invertible)
{
float4 cameraPosition = float4(viewInverse.m41, viewInverse.m42, viewInverse.m43, 0.f);
float4 lightPosition = cameraPosition + float4(0.f, 0.25f, 0.f, 0.f);
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.cameraPosition[0], DirectX::XMLoadFloat4(&cameraPosition));
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.lightPosition[0], DirectX::XMLoadFloat4(&lightPosition));
}
invertible = Windows::Foundation::Numerics::invert(viewCoordinateSystemTransform.Right, &viewInverse);
if (invertible)
{
float4 cameraPosition = float4(viewInverse.m41, viewInverse.m42, viewInverse.m43, 0.f);
float4 lightPosition = cameraPosition + float4(0.f, 0.25f, 0.f, 0.f);
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.cameraPosition[1], DirectX::XMLoadFloat4(&cameraPosition));
XMStoreFloat4(&m_cpuViewProjectionConstantBuffer.lightPosition[1], DirectX::XMLoadFloat4(&lightPosition));
}
}
const auto context = deviceResources->GetD3DDeviceContext();
if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
{
m_framePending = false;
return false;
}
else
{
context->UpdateSubresource(m_viewProjectionConstantBuffer.Get(), 0, nullptr, &m_cpuViewProjectionConstantBuffer, 0, 0);
m_framePending = true;
return true;
}
}
//----------------------------------------------------------------------------
bool CameraResources::Attach(std::shared_ptr<DX::DeviceResources> deviceResources)
{
const auto context = deviceResources->GetD3DDeviceContext();
if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
{
return false;
}
context->RSSetViewports(1, &m_d3dViewport);
context->VSSetConstantBuffers(1, 1, m_viewProjectionConstantBuffer.GetAddressOf());
context->PSSetConstantBuffers(1, 1, m_viewProjectionConstantBuffer.GetAddressOf());
m_framePending = false;
return true;
}
//----------------------------------------------------------------------------
DX::ViewProjectionConstantBuffer CameraResources::GetLatestViewProjectionBuffer() const
{
return m_cpuViewProjectionConstantBuffer;
}
//----------------------------------------------------------------------------
bool CameraResources::GetLatestSpatialBoundingFrustum(Windows::Perception::Spatial::SpatialBoundingFrustum& outFrustum) const
{
if (m_spatialBoundingFrustum == nullptr)
{
return false;
}
outFrustum = *m_spatialBoundingFrustum;
return true;
}
//----------------------------------------------------------------------------
ID3D11RenderTargetView* CameraResources::GetBackBufferRenderTargetView() const
{
return m_d3dRenderTargetView.Get();
}
//----------------------------------------------------------------------------
ID3D11DepthStencilView* CameraResources::GetDepthStencilView() const
{
return m_d3dDepthStencilView.Get();
}
//----------------------------------------------------------------------------
ID3D11Texture2D* CameraResources::GetBackBufferTexture2D() const
{
return m_d3dBackBuffer.Get();
}
//----------------------------------------------------------------------------
D3D11_VIEWPORT CameraResources::GetViewport() const
{
return m_d3dViewport;
}
//----------------------------------------------------------------------------
DXGI_FORMAT CameraResources::GetBackBufferDXGIFormat() const
{
return m_dxgiFormat;
}
//----------------------------------------------------------------------------
Windows::Foundation::Size CameraResources::GetRenderTargetSize() const
{
return m_d3dRenderTargetSize;
}
//----------------------------------------------------------------------------
bool CameraResources::IsRenderingStereoscopic() const
{
return m_isStereo;
}
//----------------------------------------------------------------------------
Windows::Graphics::Holographic::HolographicCamera^ CameraResources::GetHolographicCamera() const
{
return m_holographicCamera;
}
} | 41.052239 | 181 | 0.655699 | adamrankin |
2a1cd6d8c00eae8458bd896922ab1595262bf9d6 | 6,012 | cpp | C++ | src/libawkward/typedbuilder/IndexedOptionArrayBuilder.cpp | ioanaif/awkward-1.0 | 22501ba218646dc24dc515c4394eb22f126d340d | [
"BSD-3-Clause"
] | null | null | null | src/libawkward/typedbuilder/IndexedOptionArrayBuilder.cpp | ioanaif/awkward-1.0 | 22501ba218646dc24dc515c4394eb22f126d340d | [
"BSD-3-Clause"
] | null | null | null | src/libawkward/typedbuilder/IndexedOptionArrayBuilder.cpp | ioanaif/awkward-1.0 | 22501ba218646dc24dc515c4394eb22f126d340d | [
"BSD-3-Clause"
] | null | null | null | // BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
#define FILENAME(line) FILENAME_FOR_EXCEPTIONS("src/libawkward/builder/IndexedOptionArrayBuilder.cpp", line)
#include "awkward/typedbuilder/IndexedOptionArrayBuilder.h"
#include "awkward/typedbuilder/TypedArrayBuilder.h"
#include "awkward/array/IndexedArray.h"
namespace awkward {
///
IndexedOptionArrayBuilder::IndexedOptionArrayBuilder(const IndexedOptionFormPtr& form,
const std::string attribute,
const std::string partition)
: form_(form),
form_key_(!form.get()->form_key() ?
std::make_shared<std::string>(std::string("node-id")
+ std::to_string(TypedArrayBuilder::next_id()))
: form.get()->form_key()),
attribute_(attribute),
partition_(partition),
content_(TypedArrayBuilder::formBuilderFromA(form.get()->content())) {
vm_output_data_ = std::string("part")
.append(partition_).append("-")
.append(*form_key_).append("-")
.append(attribute_);
vm_func_name_ = std::string(*form_key_).append("-").append(attribute_);
vm_func_type_ = content_.get()->vm_func_type();
vm_output_ = std::string("output ")
.append(vm_output_data_)
.append(" ")
.append(index_form_to_name(form_.get()->index()))
.append("\n")
.append(content_.get()->vm_output());
vm_func_.append(content_.get()->vm_func())
.append(": ").append(vm_func_name()).append("\n")
.append("dup ").append(std::to_string(static_cast<utype>(state::null)))
.append(" = if").append("\n")
.append("drop\n")
.append("variable null -1 null !").append("\n")
.append("null @ ")
.append(vm_output_data_).append(" <- stack").append("\n")
.append("exit\n")
.append("else\n")
.append("variable index 1 index +!").append("\n")
.append("index @ 1- ")
.append(vm_output_data_).append(" <- stack").append("\n")
.append(content_.get()->vm_func_name()).append("\n")
.append("then\n")
.append(";").append("\n");
vm_data_from_stack_ = std::string(content_.get()->vm_from_stack())
.append("0 ").append(vm_output_data_).append(" <- stack").append("\n");
vm_error_ = content_.get()->vm_error();
validate();
}
void
IndexedOptionArrayBuilder::validate() const {
if (form_.get()->parameter_equals("__array__", "\"categorical\"")) {
throw std::invalid_argument(
std::string("categorical form of a ") + classname()
+ std::string(" is not supported yet ")
+ FILENAME(__LINE__));
}
}
const std::string
IndexedOptionArrayBuilder::classname() const {
return "IndexedOptionArrayBuilder";
}
const ContentPtr
IndexedOptionArrayBuilder::snapshot(const ForthOutputBufferMap& outputs) const {
auto search = outputs.find(vm_output_data_);
if (search != outputs.end()) {
switch (form_.get()->index()) {
// case Index::Form::i8:
case Index::Form::i32:
return std::make_shared<IndexedOptionArray32>(
Identities::none(),
form_.get()->parameters(),
Index32(std::static_pointer_cast<int32_t>(search->second.get()->ptr()),
1,
search->second.get()->len() - 1,
kernel::lib::cpu),
content_.get()->snapshot(outputs));
case Index::Form::i64:
return std::make_shared<IndexedOptionArray64>(
Identities::none(),
form_.get()->parameters(),
Index64(std::static_pointer_cast<int64_t>(search->second.get()->ptr()),
1,
search->second.get()->len() - 1,
kernel::lib::cpu),
content_.get()->snapshot(outputs));
default:
break;
};
}
throw std::invalid_argument(
std::string("Snapshot of a ") + classname()
+ std::string(" needs an index ")
+ FILENAME(__LINE__));
}
const FormPtr
IndexedOptionArrayBuilder::form() const {
return std::static_pointer_cast<Form>(form_);
}
const std::string
IndexedOptionArrayBuilder::vm_output() const {
return vm_output_;
}
const std::string
IndexedOptionArrayBuilder::vm_output_data() const {
return vm_output_data_;
}
const std::string
IndexedOptionArrayBuilder::vm_func() const {
return vm_func_;
}
const std::string
IndexedOptionArrayBuilder::vm_func_name() const {
return vm_func_name_;
}
const std::string
IndexedOptionArrayBuilder::vm_func_type() const {
return vm_func_type_;
}
const std::string
IndexedOptionArrayBuilder::vm_from_stack() const {
return vm_data_from_stack_;
}
const std::string
IndexedOptionArrayBuilder::vm_error() const {
return vm_error_;
}
void
IndexedOptionArrayBuilder::boolean(bool x, TypedArrayBuilder* builder) {
content_.get()->boolean(x, builder);
}
void
IndexedOptionArrayBuilder::int64(int64_t x, TypedArrayBuilder* builder) {
content_.get()->int64(x, builder);
}
void
IndexedOptionArrayBuilder::float64(double x, TypedArrayBuilder* builder) {
content_.get()->float64(x, builder);
}
void
IndexedOptionArrayBuilder::complex(std::complex<double> x, TypedArrayBuilder* builder) {
content_.get()->complex(x, builder);
}
void
IndexedOptionArrayBuilder::bytestring(const std::string& x, TypedArrayBuilder* builder) {
content_.get()->bytestring(x, builder);
}
void
IndexedOptionArrayBuilder::string(const std::string& x, TypedArrayBuilder* builder) {
content_.get()->string(x, builder);
}
void
IndexedOptionArrayBuilder::begin_list(TypedArrayBuilder* builder) {
content_.get()->begin_list(builder);
}
void
IndexedOptionArrayBuilder::end_list(TypedArrayBuilder* builder) {
content_.get()->end_list(builder);
}
}
| 31.150259 | 108 | 0.626414 | ioanaif |
2a1d3fd812f5cbf3af8e947032ee73c06d113109 | 921 | hpp | C++ | include/Module/Source/User/Source_user_binary.hpp | FredrikBlomgren/aff3ct | fa616bd923b2dcf03a4cf119cceca51cf810d483 | [
"MIT"
] | 315 | 2016-06-21T13:32:14.000Z | 2022-03-28T09:33:59.000Z | include/Module/Source/User/Source_user_binary.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 153 | 2017-01-17T03:51:06.000Z | 2022-03-24T15:39:26.000Z | include/Module/Source/User/Source_user_binary.hpp | a-panella/aff3ct | 61509eb756ae3725b8a67c2d26a5af5ba95186fb | [
"MIT"
] | 119 | 2017-01-04T14:31:58.000Z | 2022-03-21T08:34:16.000Z | #ifndef SOURCE_USER_BINARY_HPP_
#define SOURCE_USER_BINARY_HPP_
#include <string>
#include <vector>
#include <fstream>
#include <memory>
#include "Module/Source/Source.hpp"
namespace aff3ct
{
namespace module
{
template <typename B = int32_t>
class Source_user_binary : public Source<B>
{
private:
std::ifstream source_file;
const bool auto_reset;
const bool fifo_mode;
bool done;
size_t n_left;
std::vector<char> memblk;
std::vector<B> left_bits; // to store bits that are left by last call (n_left & n_completing)
public:
Source_user_binary(const int K,
const std::string &filename,
const bool auto_reset = true,
const bool fifo_mode = false);
virtual ~Source_user_binary() = default;
virtual bool is_done() const;
virtual void reset();
protected:
void _generate(B *U_K, const size_t frame_id);
};
}
}
#endif /* SOURCE_USER_BINARY_HPP_ */
| 20.466667 | 94 | 0.703583 | FredrikBlomgren |
2a21d57b9949a9f12817b8dbc9977955ced6201b | 7,174 | cpp | C++ | Visual Mercutio/zBaseLib/PSS_PLFNAutoNumbered.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 1 | 2022-01-31T06:24:24.000Z | 2022-01-31T06:24:24.000Z | Visual Mercutio/zBaseLib/PSS_PLFNAutoNumbered.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-04-11T15:50:42.000Z | 2021-06-05T08:23:04.000Z | Visual Mercutio/zBaseLib/PSS_PLFNAutoNumbered.cpp | Jeanmilost/Visual-Mercutio | f079730005b6ce93d5e184bb7c0893ccced3e3ab | [
"MIT"
] | 2 | 2021-01-08T00:55:18.000Z | 2022-01-31T06:24:18.000Z | /****************************************************************************
* ==> PSS_PLFNAutoNumbered ------------------------------------------------*
****************************************************************************
* Description : Provides an financial plan auto-numbered object *
* Developer : Processsoft *
****************************************************************************/
#include <StdAfx.h>
#include "PSS_PLFNAutoNumbered.h"
// processsoft
#include "PSS_Document.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//---------------------------------------------------------------------------
// Serialization
//---------------------------------------------------------------------------
IMPLEMENT_SERIAL(PSS_PLFNAutoNumbered, PSS_PlanFinObject, g_DefVersion)
//---------------------------------------------------------------------------
// PSS_PLFNAutoNumbered
//---------------------------------------------------------------------------
PSS_PLFNAutoNumbered::PSS_PLFNAutoNumbered() :
PSS_PlanFinObject(),
m_pObject(NULL),
m_TextOffset(20),
m_SectionNumber(0),
m_Level(0),
m_AutoCalculate(TRUE)
{}
//---------------------------------------------------------------------------
PSS_PLFNAutoNumbered::PSS_PLFNAutoNumbered(const PSS_PLFNAutoNumbered& other) :
PSS_PlanFinObject(),
m_pObject(NULL),
m_TextOffset(20),
m_SectionNumber(0),
m_Level(0),
m_AutoCalculate(TRUE)
{
*this = other;
}
//---------------------------------------------------------------------------
PSS_PLFNAutoNumbered::~PSS_PLFNAutoNumbered()
{
if (m_pObject)
delete m_pObject;
}
//---------------------------------------------------------------------------
const PSS_PLFNAutoNumbered& PSS_PLFNAutoNumbered::operator = (const PSS_PLFNAutoNumbered& other)
{
PSS_PlanFinObject::operator = ((inherited&)other);
m_TextLevel = other.m_TextLevel;
m_pObject = other.m_pObject->Clone();
m_TextOffset = other.m_TextOffset;
m_SectionNumber = other.m_SectionNumber;
m_Level = other.m_Level;
m_AutoCalculate = other.m_AutoCalculate;
return *this;
}
//---------------------------------------------------------------------------
const PSS_PLFNAutoNumbered& PSS_PLFNAutoNumbered::operator = (const PSS_PLFNAutoNumbered* pOther)
{
PSS_PlanFinObject::operator = ((inherited*)pOther);
if (!pOther)
{
m_pObject = NULL;
m_TextOffset = 20;
m_SectionNumber = 0;
m_Level = 0;
m_AutoCalculate = TRUE;
}
else
{
m_TextLevel = pOther->m_TextLevel;
m_pObject = pOther->m_pObject->Clone();
m_TextOffset = pOther->m_TextOffset;
m_SectionNumber = pOther->m_SectionNumber;
m_Level = pOther->m_Level;
m_AutoCalculate = pOther->m_AutoCalculate;
}
return *this;
}
//---------------------------------------------------------------------------
PSS_PlanFinObject* PSS_PLFNAutoNumbered::Clone() const
{
return new PSS_PLFNAutoNumbered(*this);
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::CopyObject(PSS_PlanFinObject* pSrc)
{
operator = (dynamic_cast<PSS_PLFNAutoNumbered*>(pSrc));
}
//---------------------------------------------------------------------------
CString PSS_PLFNAutoNumbered::GetFormattedObject()
{
if (m_pObject)
return m_pObject->GetFormattedObject();
return "";
}
//---------------------------------------------------------------------------
BOOL PSS_PLFNAutoNumbered::ConvertFormattedObject(const CString& value, BOOL locateFormat, BOOL emptyWhenZero)
{
if (m_pObject)
return m_pObject->ConvertFormattedObject(value, locateFormat, emptyWhenZero);
// hasn't changed
return FALSE;
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::DrawObject(CDC* pDC, PSS_View* pView)
{
DrawFillObject(pDC, pView);
m_TextLevel.DrawObject(pDC, pView);
// must draw the object
if (m_pObject)
m_pObject->DrawObject(pDC, pView);
PSS_PlanFinObject::DrawObject(pDC, pView);
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::SizePositionHasChanged()
{
if (!m_pObject)
return;
// call the basic fonction
PSS_PlanFinObject::SizePositionHasChanged();
// recalculate all element positions.
GetTextLevel().SetClientRect(m_ObjectRect);
m_pObject->SetClientRect(m_ObjectRect);
m_pObject->GetClientRect().left += GetTextOffset();
// if automatic recalculation of section
if (GetAutoCalculate())
{
CWnd* pWnd = ::AfxGetMainWnd();
if (pWnd)
pWnd->SendMessageToDescendants(UM_REBUILDAUTOMATICNUMBER);
}
}
//---------------------------------------------------------------------------
CString PSS_PLFNAutoNumbered::GetUnformattedObject()
{
if (m_pObject)
return m_pObject->GetUnformattedObject();
return "";
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::SetStyle(PSS_Style::Handle hStyle)
{
if (m_pObject)
m_pObject->SetStyle(hStyle);
}
//---------------------------------------------------------------------------
const COLORREF PSS_PLFNAutoNumbered::GetFillColor() const
{
if (m_pObject)
return m_pObject->GetFillColor();
return 0;
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::SetFillColor(COLORREF value)
{
if (m_pObject)
m_pObject->SetFillColor(value);
}
//---------------------------------------------------------------------------
void PSS_PLFNAutoNumbered::Serialize(CArchive& ar)
{
PSS_PlanFinObject::Serialize(ar);
if (ar.IsStoring())
{
// write the elements
ar << WORD(m_TextOffset);
ar << WORD(m_AutoCalculate);
ar << WORD(m_SectionNumber);
ar << WORD(m_Level);
// serialize the defined object
ar << m_pObject;
}
else
{
// read the elements
WORD wValue;
ar >> wValue;
m_TextOffset = wValue;
ar >> wValue;
m_AutoCalculate = wValue;
ar >> wValue;
m_SectionNumber = wValue;
ar >> wValue;
m_Level = wValue;
// serialize the defined object
ar >> m_pObject;
}
// should serialize the static member, serialize the Text Level
m_TextLevel.Serialize(ar);
}
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNAutoNumbered::AssertValid() const
{
CObject::AssertValid();
}
#endif
//---------------------------------------------------------------------------
#ifdef _DEBUG
void PSS_PLFNAutoNumbered::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
}
#endif
//---------------------------------------------------------------------------
| 30.922414 | 110 | 0.476164 | Jeanmilost |
2a24a43d5020c4e757efdc26e46e319dcae98a08 | 1,584 | cpp | C++ | sources/UseCases/Multithreading/f1/function1.cpp | alrinach/ARISS | b84ace8412ebb037d7c1690ee488c111aef57b64 | [
"CECILL-B",
"MIT"
] | null | null | null | sources/UseCases/Multithreading/f1/function1.cpp | alrinach/ARISS | b84ace8412ebb037d7c1690ee488c111aef57b64 | [
"CECILL-B",
"MIT"
] | null | null | null | sources/UseCases/Multithreading/f1/function1.cpp | alrinach/ARISS | b84ace8412ebb037d7c1690ee488c111aef57b64 | [
"CECILL-B",
"MIT"
] | null | null | null | #include "CBasefunction.h"
#include <iostream>
#include <stdlib.h>
#define SEMKEY_1 50000
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * fonction_thread(void * arg) {
long numero = (long) arg;
std::cout << "numéro vaut : " << numero << std::endl;
//usleep(random());
std::cout << "Before while " << std::endl;
while (1) {
fprintf(stderr, "[%d] demande le mutexn\n", numero);
if (numero != 2)
while (pthread_mutex_trylock(& mutex) != 0)
;
else
pthread_mutex_lock(& mutex);
fprintf(stderr, " [%d] tient le mutexn\n", numero);
sleep(1);
fprintf(stderr, "[%d] lache le mutexn\n", numero);
pthread_mutex_unlock(& mutex);
usleep(100);
}
std::cout << "exit thread " << std::endl;
return NULL;
}
#define NB_THREADS 5
int main(int argc, char *argv[]) {
int redemarrage = atoi(argv[7]);
int position = atoi(argv[6]);
GUI_ARINC_partition("Partition1", position, redemarrage);
long i;
pthread_t thread[NB_THREADS];
pthread_mutex_lock(& mutex);
for (i = 0; i < NB_THREADS; i++) {
long argument = i + 1;
std::cout << "argument vaut : " << argument << std::endl;
pthread_create(& thread[i], NULL, fonction_thread, (void *) argument);
usleep(10000);
}
sleep(1);
fprintf(stderr, "Liberation initiale du mutex\n");
pthread_mutex_unlock(& mutex);
for (i = 0; i < NB_THREADS; i++)
pthread_join(thread[i], NULL);
return EXIT_SUCCESS;
}
| 24.75 | 78 | 0.581439 | alrinach |
2a26d9cdad17739ee5bd7f530447d991615bbd4e | 1,243 | cpp | C++ | source/Game/Entities/Aircraft.cpp | zhiayang/controller_game | a0800f991067e81850d44d7298d80b8772c5384f | [
"Apache-2.0"
] | 1 | 2021-02-07T08:42:12.000Z | 2021-02-07T08:42:12.000Z | source/Game/Entities/Aircraft.cpp | zhiayang/controller_game | a0800f991067e81850d44d7298d80b8772c5384f | [
"Apache-2.0"
] | null | null | null | source/Game/Entities/Aircraft.cpp | zhiayang/controller_game | a0800f991067e81850d44d7298d80b8772c5384f | [
"Apache-2.0"
] | null | null | null | // Aircraft.cpp
// Copyright (c) 2014 - The Foreseeable Future, zhiayang@gmail.com
// Licensed under the Apache License Version 2.0.
#include "Game.h"
#include <random>
#include "Config.h"
#include "Game/Scene.h"
#include "Game/Aircraft.h"
namespace Game
{
Aircraft::Aircraft(Entity* p) : MovingEntity(p), ai(this)
{
}
Aircraft::~Aircraft()
{
}
void Aircraft::Render(SDL::Renderer* r)
{
glPushMatrix();
// move the shape to local origin, then rotate it, then move it back
// prevents the rotation from screwing with position
glTranslated(this->pos().x, this->pos().y, 0);
glRotated(Math::Vector2(this->velocity.x, this->velocity.y).angle(), 0, 0, 1);
glTranslated(-this->pos().x, -this->pos().y, 0);
r->SetColour(this->colour);
r->RenderEqTriangle(Math::Vector2(this->pos().x, this->pos().y), 12);
glPopMatrix();
// render our callsign
r->SetColour(Util::Colour::white());
SDL::Font* f = Util::Font::get("menlo", 8, true);
r->RenderText(this->callsign, f, Math::Vector2(this->pos().x, this->pos().y) + Math::Vector2(3, 3));
// render our children
this->MovingEntity::Render(r);
}
void Aircraft::Update(float dt)
{
this->ai.UpdateAI(dt);
this->MovingEntity::Update(dt);
}
}
| 19.123077 | 102 | 0.652454 | zhiayang |
2a270ca12258cf80c0517bd0c8d8a56ad38daa67 | 382 | ipp | C++ | include/particles/implementation/component/ParticleEmitterSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | 3 | 2021-06-24T10:20:12.000Z | 2021-07-18T14:43:19.000Z | include/particles/implementation/component/ParticleEmitterSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | 2 | 2021-07-22T15:31:03.000Z | 2021-07-28T14:27:28.000Z | include/particles/implementation/component/ParticleEmitterSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | 1 | 2021-07-22T15:24:24.000Z | 2021-07-22T15:24:24.000Z | /**
* @file
* @author University of Warwick
* @version 1.0
*
* @section LICENSE
*
* @section DESCRIPTION
*
* Description
*
* Contains header level definitions for the ParticleEmitterSimple Class
*
*/
#ifndef CUPCFD_PARTICLES_PARTICLE_EMITTER_SIMPLE_IPP_H
#define CUPCFD_PARTICLES_PARTICLE_EMITTER_SIMPLE_IPP_H
namespace cupcfd
{
namespace particles
{
}
}
#endif
| 13.642857 | 72 | 0.746073 | thorbenlouw |
2a27b02e1482815b9058d92ded33c79b7818caa3 | 2,947 | cpp | C++ | oshgui/Controls/RadioButton.cpp | zhuhuibeishadiao/osh_sdk | 087df8876443c36254b6de127b732e74ddf77167 | [
"MIT"
] | 6 | 2018-10-31T12:53:37.000Z | 2019-01-12T23:12:43.000Z | OSHGui/Controls/RadioButton.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 4 | 2018-10-31T16:39:43.000Z | 2019-01-14T07:30:24.000Z | OSHGui/Controls/RadioButton.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 2 | 2021-01-20T21:17:35.000Z | 2022-03-12T08:18:43.000Z | /*
* OldSchoolHack GUI
*
* by KN4CK3R https://www.oldschoolhack.me/
*
* See license in OSHGui.hpp
*/
#include "RadioButton.hpp"
#include "Label.hpp"
#include "../Misc/Exceptions.hpp"
namespace OSHGui
{
//---------------------------------------------------------------------------
//Constructor
//---------------------------------------------------------------------------
RadioButton::RadioButton()
{
type_ = ControlType::RadioButton;
}
//---------------------------------------------------------------------------
//Getter/Setter
//---------------------------------------------------------------------------
void RadioButton::SetChecked(bool checked)
{
if (checked_ != checked)
{
if (GetParent() != nullptr)
{
//uncheck other radiobuttons
for (auto &control : GetParent()->GetControls())
{
if (control->GetType() == ControlType::RadioButton)
{
static_cast<RadioButton*>(control)->SetCheckedInternal(false);
}
}
SetCheckedInternal(checked);
}
}
}
//---------------------------------------------------------------------------
void RadioButton::SetCheckedInternal(bool checked)
{
if (checked_ != checked)
{
checked_ = checked;
checkedChangedEvent_.Invoke(this);
Invalidate();
}
}
//---------------------------------------------------------------------------
void RadioButton::PopulateGeometry()
{
using namespace Drawing;
Graphics g(*geometry_);
g.FillRectangle(GetBackColor(), RectangleF(PointF(0, 0), SizeF(DefaultCheckBoxSize, DefaultCheckBoxSize)));
g.FillRectangleGradient(ColorRectangle(Color::White(), Color::White() - Color::FromARGB(0, 137, 137, 137)), RectangleF(PointF(1, 1), SizeF(15, 15)));
g.FillRectangleGradient(ColorRectangle(GetBackColor(), GetBackColor() + Color::FromARGB(0, 55, 55, 55)), RectangleF(PointF(2, 2), SizeF(13, 13)));
if (checked_)
{
g.FillRectangle(Color::White() - Color::FromARGB(0, 128, 128, 128), RectangleF(PointF(5, 7), SizeF(7, 3)));
const ColorRectangle colors(Color::White(), Color::White() - Color::FromARGB(0, 137, 137, 137));
g.FillRectangleGradient(colors, RectangleF(PointF(7, 5), SizeF(3, 7)));
g.FillRectangleGradient(colors, RectangleF(PointF(6, 6), SizeF(5, 5)));
}
}
//---------------------------------------------------------------------------
//Event-Handling
//---------------------------------------------------------------------------
void RadioButton::OnMouseClick(const MouseMessage &mouse)
{
Control::OnMouseClick(mouse);
SetChecked(true);
}
//---------------------------------------------------------------------------
bool RadioButton::OnKeyUp(const KeyboardMessage &keyboard)
{
if (!Control::OnKeyUp(keyboard))
{
if (keyboard.GetKeyCode() == Key::Space)
{
SetChecked(true);
clickEvent_.Invoke(this);
}
}
return true;
}
//---------------------------------------------------------------------------
} | 28.892157 | 151 | 0.491686 | zhuhuibeishadiao |
2a28eca7795b2d1148dcae007a3dfd6f2fb9b78b | 625 | cc | C++ | caffe2/core/event_test.cc | huiqun2001/caffe2 | 97209961b675c8bea3831450ba46c9e8b7bad3de | [
"MIT"
] | null | null | null | caffe2/core/event_test.cc | huiqun2001/caffe2 | 97209961b675c8bea3831450ba46c9e8b7bad3de | [
"MIT"
] | null | null | null | caffe2/core/event_test.cc | huiqun2001/caffe2 | 97209961b675c8bea3831450ba46c9e8b7bad3de | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "caffe2/core/context.h"
#include "caffe2/core/event.h"
namespace caffe2 {
// For the CPU event test, we only test if these functions are properly
// registered. Nothing special needs to be checked since CPU events are no-ops.
TEST(EventCPUTest, EventBasics) {
DeviceOption device_option;
device_option.set_device_type(CPU);
Event event(device_option);
CPUContext context;
// Calling from Context
context.WaitEvent(event);
context.Record(&event);
// Calling from Event
event.Finish();
event.Record(CPU, &context);
event.Wait(CPU, &context);
}
} // namespace caffe2
| 24.038462 | 79 | 0.736 | huiqun2001 |
2a29354894a525a0b0963bffe5958b6445acdf82 | 10,172 | cpp | C++ | PinGUI/GUI_Elements/ComboBox.cpp | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 60 | 2017-04-16T15:31:13.000Z | 2021-12-22T19:01:07.000Z | PinGUI/GUI_Elements/ComboBox.cpp | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 4 | 2017-02-14T19:05:21.000Z | 2020-07-16T10:04:27.000Z | PinGUI/GUI_Elements/ComboBox.cpp | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 20 | 2017-02-15T19:07:17.000Z | 2021-12-22T19:01:07.000Z | /**
PinGUI
Copyright (c) 2017 Lubomir Barantal <l.pinsius@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
**/
#include "ComboBox.h"
ComboBox::ComboBox(GUIPos x,
GUIPos y,
std::vector<std::string> itemList,
clipboardData data,
std::vector<std::shared_ptr<GUI_Element>>* ELEMENTS,
int maxNumOfItems,
bool* update):
_maxNumberOfItems(maxNumOfItems),
_needUpdate(update),
_scroller(nullptr),
_mainItem(nullptr),
_ELEMENTS(ELEMENTS),
_clickable(true),
_rollbackVect(0,0)
{
_position.x = x;
_position.y = y;
_data.texter = data.texter;
_maxSize = 0;
findLongestWord(itemList);
initMainSprites(x,y,data);
for (std::size_t i = 0; i < itemList.size(); i++)
addItem(itemList[i]);
initScroller();
}
ComboBox::ComboBox(GUIPos x,
GUIPos y,
std::vector<std::string> itemList,
clipboardData data,
std::vector<std::shared_ptr<GUI_Element>>* ELEMENTS,
int maxNumOfItems,
bool* update,
int maxSize):
_maxNumberOfItems(maxNumOfItems),
_needUpdate(update),
_scroller(nullptr),
_mainItem(nullptr),
_ELEMENTS(ELEMENTS),
_clickable(true),
_rollbackVect(0,0)
{
_position.x = x;
_position.y = y;
_data.texter = data.texter;
_maxSize = maxSize;
initMainSprites(x,y,data);
for (std::size_t i = 0; i < itemList.size(); i++)
addItem(itemList[i]);
initScroller();
}
ComboBox::~ComboBox()
{
_ITEMS.clear();
}
void ComboBox::initMainSprites(const GUIPos& x, const GUIPos& y, clipboardData& data){
SDL_Surface* tmpSurface;
int tmp_width, tmp_height;
fakeInputText(tmp_width,tmp_height,data);
addCollider(x,y,tmp_width,tmp_height);
_offsetCollider = *(getCollider());
_textStorage = std::make_shared<TextStorage>(data.texter);
initText();
//Now need to rearrange the width by adding the width of scroller
tmp_width += PINGUI_WINDOW_DEFAULT_SCROLLER_W-BORDER_LINE;
tmpSurface = SheetManager::createRectangle(tmp_width,tmp_height,BOARD,BORDER_LINE);
SheetManager::putOnSurface(tmpSurface,COMBO_BOX_ARROW,tmp_width - POSITION_OF_COMBO_ARROW_X,(tmp_height/2)-(PINGUI_COMBO_BOX_ARROW_H/2));
addSprite(x,y,tmpSurface);
deleteCollider(0);
addCollider(x,y,tmp_width,tmp_height);
SDL_FreeSurface(tmpSurface);
}
void ComboBox::initScroller(){
PinGUI::Vector2<GUIPos> tmpPos(_offsetCollider.x + _offsetCollider.w - BORDER_LINE,
_offsetCollider.y - (_maxNumberOfItems * (_offsetCollider.h-BORDER_LINE) ));
int height = _maxNumberOfItems * (_offsetCollider.h-BORDER_LINE);
_scroller = std::make_shared<VerticalScroller>(tmpPos,height,_needUpdate,_ELEMENTS);
//Now init cropRect and add function that performs it
_cropRect.rect.x = getSprite()->getX();
int num;
if (_ITEMS.size()>=_maxNumberOfItems)
num = _maxNumberOfItems;
else
num = int(_ITEMS.size());
_cropRect.rect.w = _offsetCollider.w;
_cropRect.rect.h = num * _offsetCollider.h;
_cropRect.rect.y = _position.y - _cropRect.rect.h;
_cropRect.realRect = _cropRect.rect;
//Set clFunction
PinGUI::scrollFuncPointer f;
f._function = boost::bind(&ComboBox::updateCropArea,this,_1);
_scroller->setCamRollFunction(f);
_scroller->setNetworking(true);
_ELEMENTS->push_back(_scroller);
_scroller->createArrows(_ELEMENTS);
_scroller->hideScroller();
}
void ComboBox::updateCropArea(PinGUI::Vector2<GUIPos> vect){
_rollbackVect += vect;
for (std::size_t i = 0; i < _ITEMS.size(); i++){
_ITEMS[i]->moveElement(vect);
_ITEMS[i]->cropElement(_cropRect.rect);
}
*_needUpdate = true;
}
std::vector<std::string> ComboBox::getStringVector(){
std::vector<std::string> tmp;
for (std::size_t i = 0; i < _ITEMS.size(); i++)
tmp.push_back(_ITEMS[i]->getStorage()->getText()->getString());
return tmp;
}
void ComboBox::findLongestWord(std::vector<std::string>& itemList){
for (std::size_t i = 0; i < itemList.size(); i++){
if (itemList[i].size() > _maxSize)
_maxSize = int(itemList[i].size());
}
}
void ComboBox::addItem(std::string name){
PinGUI::Vector2<GUIPos> tmpPos (_position.x, getPosOfNextItem());
PinGUI::basicPointer f(boost::bind(&ComboBox::uploadContent,this));
auto ptr = std::make_shared<ComboBoxItem>(tmpPos,name,&_mainItem,f,_maxSize,_data);
_ITEMS.push_back(ptr);
_ELEMENTS->push_back(_ITEMS.back());
_ITEMS.back()->setOption(int(_ITEMS.size()));
if (!_clickable)
_ITEMS.back()->setCollidable(false);
*_needUpdate = true;
}
void ComboBox::deleteItem(std::string name){
for (std::size_t i = 0; i < _ITEMS.size(); i++){
if (_ITEMS[i]->getStorage()->getText()->getString()==name){
_ITEMS[i]->setExist(false);
_ITEMS.erase(_ITEMS.begin() + i);
}
}
reMoveTabs();
}
void ComboBox::clearComboBox(){
for (std::size_t i = 0; i < _ITEMS.size(); i++){
_ITEMS[i]->setExist(false);
}
_ITEMS.clear();
}
void ComboBox::reMoveTabs(){
PinGUI::Vector2<GUIPos> tmp(0.0f,float(_offsetCollider.h-BORDER_LINE));
for (std::size_t i = 0; i < _ITEMS.size(); i++){
_ITEMS[i]->moveElement(tmp);
}
*_needUpdate = true;
}
GUIPos ComboBox::getPosOfNextItem(){
return (_position.y - (getSprite()->getH() * (_ITEMS.size()+1)) + (_ITEMS.size()+1));
}
void ComboBox::moveElement(const PinGUI::Vector2<GUIPos>& vect){
ClipBoard::moveElement(vect);
_scroller->moveElement(vect);
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->moveElement(vect);
moveCollider(_offsetCollider,vect);
moveCollider(_cropRect.realRect,vect);
moveCollider(_cropRect.rect,vect);
}
void ComboBox::onClick(){
if (_cropRect.rect != _cropRect.realRect){
ErrorManager::infoLog("PinGUI error 2","Combobox list cannot be loaded due to cropped area. Move it to normal area");
return;
}
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setShow(true);
PinGUI::basicPointer tmpF;
tmpF._function = boost::bind(&ComboBox::hideContent,this);
PinGUI::Input_Manager::setCallbackFunction(tmpF);
_cropRect.rect.x = _offsetCollider.x;
_cropRect.rect.w = _offsetCollider.w;
_cropRect.rect.h = _maxNumberOfItems * (_offsetCollider.h-BORDER_LINE);
if (_ITEMS.size()>_maxNumberOfItems){
_cropRect.rect.w += PINGUI_WINDOW_DEFAULT_SCROLLER_W-BORDER_LINE;
_cropRect.rect.h = _maxNumberOfItems * (_offsetCollider.h-BORDER_LINE);
} else {
_cropRect.rect.h = int(_ITEMS.size()) * (_offsetCollider.h-BORDER_LINE);
}
_cropRect.rect.y = _offsetCollider.y - _cropRect.rect.h;
_cropRect.realRect = _cropRect.rect;
PinGUI::Input_Manager::setTarget(true,_cropRect.rect);
if (_maxNumberOfItems< _ITEMS.size()){
loadScroller();
_scroller->setShow(true);
PinGUI::basicPointer f;
f._function = boost::bind(&Scroller::checkForWheelMove,_scroller);
PinGUI::Input_Manager::setTMPWheeledInfo(_scroller->getSprite(1),_needUpdate,f);
}
updateCropArea(_rollbackVect);
}
void ComboBox::loadScroller(){
_scroller->loadScrollMover(_cropRect.rect.h,(int(_ITEMS.size()) * (_offsetCollider.h-1)));
}
bool ComboBox::listenForClick(manip_Element manipulatingElement){
return GUI_Element::listenForClick(manipulatingElement);
}
void ComboBox::hideContent(){
_rollbackVect.y *= -1;
updateCropArea(_rollbackVect);
_rollbackVect.clearVector();
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setShow(false);
if (_maxNumberOfItems< _ITEMS.size()){
_scroller->hideScroller();
PinGUI::Input_Manager::cancelTMPWheeledInfo();
PinGUI::Input_Manager::setAllowWheel(false);
}
}
void ComboBox::uploadContent(){
setClipboardText(_mainItem->getStorage()->getText()->getString(),_offsetCollider);
_func.exec(_mainItem->getOption());
hideContent();
}
void ComboBox::setShow(bool state){
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setShow(state);
if (_maxNumberOfItems< _ITEMS.size()){
loadScroller();
}
}
elementType ComboBox::getElementType(){
return COMBOBOX;
}
void ComboBox::cropElement(PinGUI::Rect& rect){
ClipBoard::cropElement(rect);
CropManager::cropRect(rect,_cropRect);
}
void ComboBox::setFunc(PinGUI::comboBoxFuncPointer func){
_func = func;
}
void ComboBox::setUnclickable(){
for (std::size_t i = 0; i < _ITEMS.size(); i++)
_ITEMS[i]->setCollidable(false);
_clickable = false;
}
| 26.1491 | 142 | 0.630161 | Pinsius |
2a2df2581625dc70da8397d83fcb7692a5abd9db | 1,061 | cpp | C++ | chapter_06/Emirp.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | chapter_06/Emirp.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | 31 | 2021-05-14T03:37:24.000Z | 2022-03-13T17:38:32.000Z | chapter_06/Emirp.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | // Exercise 6.23 - Emirp
#include <iostream>
#include <iomanip>
bool isPrime(int number)
{
for (int divisor = 2; divisor <= number / 2; divisor++)
{
if (number % divisor == 0)
{
return false;
}
}
return true;
}
int reverseNumber(int extract)
{
int reverseNumber = 0;
while (extract > 0)
{
reverseNumber = (reverseNumber * 10) + (extract % 10);
extract /= 10;
}
return reverseNumber;
}
bool hasEmirp(int number)
{
if (isPrime(reverseNumber(number)))
{
return true;
}
return false;
}
void displayEmirp(int displayAmount, int amountPerLine)
{
int count = 2, displayed = 1;
while (displayed <= displayAmount)
{
if (isPrime(count) && hasEmirp(count))
{
std::cout << std::setw(6) << std::right << count;
if (displayed % amountPerLine == 0)
std::cout << std::endl;
displayed++;
}
count++;
}
}
int main()
{
displayEmirp(100, 10);
return 0;
} | 17.683333 | 62 | 0.528746 | Kevin-Oudai |
2a3085cc6a7a51b8ae06a24d22cc51647488b9aa | 1,877 | cpp | C++ | src/texture/Texture.cpp | Owlinated/Chess | 0a4e7d02bca1af6423ed88ed780b8fb0cae1ccb8 | [
"MIT"
] | 1 | 2022-01-05T18:37:47.000Z | 2022-01-05T18:37:47.000Z | src/texture/Texture.cpp | flostellbrink/Chess | 0a4e7d02bca1af6423ed88ed780b8fb0cae1ccb8 | [
"MIT"
] | null | null | null | src/texture/Texture.cpp | flostellbrink/Chess | 0a4e7d02bca1af6423ed88ed780b8fb0cae1ccb8 | [
"MIT"
] | null | null | null | #include <GL/glew.h>
#include "Texture.h"
#include <src/texture/Image.h>
Texture::Texture() : texture_handle_()
{
}
Texture::Texture(const std::string& texturePath, const GLenum target, const GLenum repeatMode)
{
texture_handle_ = 0;
glGenTextures(1, &texture_handle_);
glBindTexture(target, texture_handle_);
if (target == GL_TEXTURE_CUBE_MAP)
{
for (GLuint i = 0; i < 6; i++)
{
auto image = Image(texturePath + std::to_string(i) + ".png");
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0,
GL_RGBA,
image.GetWidth(),
image.GetHeight(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image.GetData());
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
auto image = Image(texturePath);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
image.GetWidth(),
image.GetHeight(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
image.GetData());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeatMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeatMode);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
void Texture::Bind(const GLenum target, const unsigned int textureNum) const
{
glActiveTexture(GL_TEXTURE0 + textureNum);
glBindTexture(target, texture_handle_);
}
Texture::~Texture()
{
glDeleteTextures(1, &texture_handle_);
}
| 27.602941 | 94 | 0.631327 | Owlinated |
2a354182883b2e7e1caaf1490d9b37b87a3becba | 564 | cpp | C++ | 450/Utkarsh/array/firstAndLastX.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | 1 | 2021-07-27T03:54:41.000Z | 2021-07-27T03:54:41.000Z | 450/Utkarsh/array/firstAndLastX.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | null | null | null | 450/Utkarsh/array/firstAndLastX.cpp | stunnerhash/Competitive-Programming | 7ef3e36dd1bf5744fb2edea5e64e851c5a02f631 | [
"MIT"
] | null | null | null | //https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x/1
#include <bits/stdc++.h>
using namespace std;
void firstAndLastX(int a[], int n, int x)
{
if (binary_search(a, a + n, x) == 0) cout<<"-1";
else cout<< lower_bound(a, a + n, x)-a <<" "<<upper_bound(a, a + n, x)-1-a;
}
int main()
{
int T;
cin >> T;
while(T--)
{
int N, X;
cin >> N >> X;
int arr[N];
for(int i = 0; i < N; i++)
cin >> arr[i];
firstAndLastX(arr, N, X);
cout << endl;
}
return 0;
} | 21.692308 | 79 | 0.498227 | stunnerhash |
2a3723e5f939c1099664bd34f378158ccf76eae6 | 4,623 | cpp | C++ | Core/Contents/Source/PolyGLSLProgram.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | 1 | 2020-08-25T06:30:49.000Z | 2020-08-25T06:30:49.000Z | Core/Contents/Source/PolyGLSLProgram.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | null | null | null | Core/Contents/Source/PolyGLSLProgram.cpp | Guendeli/Polycode | f458010cb81a4c78874e29ff7738eae4e13b12bb | [
"MIT"
] | null | null | null | /*
Copyright (C) 2011 by Ivan Safrin
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 "PolyGLSLProgram.h"
#include "PolyVector3.h"
#include "PolyVector2.h"
#include "PolyColor.h"
#include "PolyLogger.h"
#ifdef _WINDOWS
#include <windows.h>
#endif
#include "PolyGLHeaders.h"
using std::vector;
#ifdef _WINDOWS
extern PFNGLUSEPROGRAMPROC glUseProgram;
extern PFNGLUNIFORM1IPROC glUniform1i;
extern PFNGLACTIVETEXTUREPROC glActiveTexture;
extern PFNGLCREATESHADERPROC glCreateShader;
extern PFNGLSHADERSOURCEPROC glShaderSource;
extern PFNGLCOMPILESHADERPROC glCompileShader;
extern PFNGLCREATEPROGRAMPROC glCreateProgram;
extern PFNGLATTACHSHADERPROC glAttachShader;
extern PFNGLLINKPROGRAMPROC glLinkProgram;
extern PFNGLDETACHSHADERPROC glDetachShader;
extern PFNGLDELETESHADERPROC glDeleteShader;
extern PFNGLDELETEPROGRAMPROC glDeleteProgram;
#ifndef _MINGW
extern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation;
#endif
#endif
using namespace Polycode;
GLSLProgram::GLSLProgram(int type) : Resource(Resource::RESOURCE_PROGRAM) {
this->type = type;
}
GLSLProgram::~GLSLProgram() {
glDeleteShader(program);
}
GLSLProgramParam GLSLProgram::addParam(const String& name, const String& typeString, const String& valueString, bool isAuto, int autoID, int paramType, void *defaultData, void *minData, void *maxData) {
GLSLProgramParam newParam;
newParam.name = name;
newParam.typeString = typeString;
newParam.valueString = valueString;
newParam.paramType = paramType;
newParam.defaultData = defaultData;
newParam.minValue = minData;
newParam.maxValue = maxData;
newParam.isAuto = isAuto;
newParam.autoID = autoID;
params.push_back(newParam);
return newParam;
}
void GLSLProgramParam::createParamData(int *retType, const String& type, const String& value, const String& min, const String& max, void **valueRes, void **minRes, void **maxRes) {
(*valueRes) = NULL;
(*minRes) = NULL;
(*maxRes) = NULL;
if(type == "Number") {
*retType = GLSLProgramParam::PARAM_Number;
Number *val = new Number();
*val = atof(value.c_str());
(*valueRes) = (void*)val;
val = new Number();
*val = atof(min.c_str());
(*minRes) = (void*)val;
val = new Number();
*val = atof(max.c_str());
(*maxRes) = (void*)val;
return;
} else if(type == "Vector2") {
*retType = GLSLProgramParam::PARAM_Vector2;
Vector2 *val = new Vector2();
(*valueRes) = (void*)val;
vector<String> values = value.split(" ");
if(values.size() == 2) {
val->set(atof(values[0].c_str()), atof(values[1].c_str()));
} else {
Logger::log("Error: A Vector2 must have 2 values (%d provided)!\n", values.size());
}
return;
} else if(type == "Vector3") {
*retType = GLSLProgramParam::PARAM_Vector3;
Vector3 *val = new Vector3();
(*valueRes) = (void*)val;
vector<String> values = value.split(" ");
if(values.size() == 3) {
val->set(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()));
} else {
Logger::log("Error: A Vector3 must have 3 values (%d provided)!\n", values.size());
}
return;
} else if(type == "Color") {
*retType = GLSLProgramParam::PARAM_Color;
Color *val = new Color();
(*valueRes) = (void*)val;
vector<String> values = value.split(" ");
if(values.size() == 4) {
val->setColor(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()), atof(values[3].c_str()));
} else {
Logger::log("Error: A Color must have 4 values (%d provided)!\n", values.size());
}
return;
} else {
*retType = GLSLProgramParam::PARAM_UNKNOWN;
(*valueRes) = NULL;
}
}
| 32.787234 | 202 | 0.717932 | Guendeli |
2a374262715fee77b0dc8a70db55bc86ed65192d | 1,633 | hpp | C++ | include/sre/Resource.hpp | estrac/SimpleRenderEngine | af8f25378e1394448a12b50fd9a19297e5de28d2 | [
"MIT"
] | 313 | 2017-01-13T10:54:58.000Z | 2022-03-18T03:08:53.000Z | include/sre/Resource.hpp | AntonyChan818/SimpleRenderEngine | 7e52507ecf6e93c1ddce7f9c2175acb159f49492 | [
"MIT"
] | 13 | 2016-09-29T12:50:23.000Z | 2019-04-21T05:17:33.000Z | include/sre/Resource.hpp | AntonyChan818/SimpleRenderEngine | 7e52507ecf6e93c1ddce7f9c2175acb159f49492 | [
"MIT"
] | 61 | 2016-08-31T07:34:42.000Z | 2022-03-16T23:02:11.000Z | /*
* SimpleRenderEngine (https://github.com/mortennobel/SimpleRenderEngine)
*
* Created by Morten Nobel-Jørgensen ( http://www.nobel-joergensen.com/ )
* License: MIT
*/
#pragma once
#include <string>
#include <set>
#include <map>
namespace sre {
enum ResourceType {
BuiltIn = 0b001,
File = 0b010,
Memory = 0b100,
All = 0b111,
};
// The resource class allows accessing resources in a uniform way. The resources are either built-in resources,
// file-resources or memory resources. File resources overwrites built-in resources, and memory resources overwrites
// both built-in and file-resources.
// The resource class is a key-value map, where each key must be uses a filename notation.
class Resource {
public:
// load resource from built-in, filesystem or memory
// returns empty string if not found
static std::string loadText(std::string key, ResourceType filter = ResourceType::All);
// set memory resource
static void set(const std::string& key, const std::string& value);
static void reset(); // reset memory resources
// get keys in resource system
static std::set<std::string> getKeys(ResourceType filter = ResourceType::All);
private:
static std::map<std::string,std::string> memoryOnlyResources;
};
} | 41.871795 | 120 | 0.560931 | estrac |
2a3d8ae74318d4784bb0a7ebb271d69e305c468b | 1,462 | cpp | C++ | Modules/SegmentationUI/Qmitk/QmitkRegionGrowingToolGUI.cpp | samsmu/MITK | c93dce6dc38d8f4c961de4440e4dd113b9841c8c | [
"BSD-3-Clause"
] | 5 | 2015-02-05T10:58:41.000Z | 2019-04-17T15:04:07.000Z | Modules/SegmentationUI/Qmitk/QmitkRegionGrowingToolGUI.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Modules/SegmentationUI/Qmitk/QmitkRegionGrowingToolGUI.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | #include "QmitkRegionGrowingToolGUI.h"
MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkRegionGrowingToolGUI, "")
QmitkRegionGrowingToolGUI::QmitkRegionGrowingToolGUI()
: QmitkToolGUI()
{
m_Controls.setupUi(this);
connect(this, SIGNAL(NewToolAssociated(mitk::Tool*)), this, SLOT(OnNewToolAssociated(mitk::Tool*)));
}
QmitkRegionGrowingToolGUI::~QmitkRegionGrowingToolGUI()
{
if (m_RegionGrowingTool.IsNotNull())
{
m_RegionGrowingTool->thresholdsChanged -=
mitk::MessageDelegate2<QmitkRegionGrowingToolGUI, double, double>(this, &QmitkRegionGrowingToolGUI::onThresholdsChanged);
}
}
void QmitkRegionGrowingToolGUI::OnNewToolAssociated(mitk::Tool* tool)
{
if (m_RegionGrowingTool.IsNotNull())
{
m_RegionGrowingTool->thresholdsChanged -=
mitk::MessageDelegate2<QmitkRegionGrowingToolGUI, double, double>(this, &QmitkRegionGrowingToolGUI::onThresholdsChanged);
}
m_RegionGrowingTool = dynamic_cast<mitk::RegionGrowingTool*>(m_Tool.GetPointer());
if (m_RegionGrowingTool.IsNotNull())
{
m_RegionGrowingTool->thresholdsChanged +=
mitk::MessageDelegate2<QmitkRegionGrowingToolGUI, double, double>(this, &QmitkRegionGrowingToolGUI::onThresholdsChanged);
}
}
void QmitkRegionGrowingToolGUI::onThresholdsChanged(double lowThreshold, double highThreshold)
{
m_Controls.lowThresholdValue->setText(QString::number(lowThreshold));
m_Controls.highThresholdValue->setText(QString::number(highThreshold));
}
| 32.488889 | 127 | 0.792066 | samsmu |
2a3e7982560ba836040315476accb9cbc193c9f4 | 4,524 | cpp | C++ | src/fluxions_renderer_gles30_snapshot.cpp | microwerx/fluxions-renderer | d461ac437e9c410577eeb609b52b6dd386e03b03 | [
"MIT"
] | null | null | null | src/fluxions_renderer_gles30_snapshot.cpp | microwerx/fluxions-renderer | d461ac437e9c410577eeb609b52b6dd386e03b03 | [
"MIT"
] | null | null | null | src/fluxions_renderer_gles30_snapshot.cpp | microwerx/fluxions-renderer | d461ac437e9c410577eeb609b52b6dd386e03b03 | [
"MIT"
] | null | null | null | #include "fluxions_renderer_pch.hpp"
#include <fluxions_renderer_gles30_snapshot.hpp>
namespace Fluxions {
//////////////////////////////////////////////////////////////////////
// RendererGLES30Snapshot ///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
RendererGLES30Snapshot::RendererGLES30Snapshot() {}
RendererGLES30Snapshot::~RendererGLES30Snapshot() {}
void RendererGLES30Snapshot::save() {
glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTexture);
if (activeTexture >= GL_TEXTURE0)
activeTexture -= GL_TEXTURE0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture2D);
glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &textureCubeMap);
glActiveTexture(GL_TEXTURE0);
glGetIntegerv(GL_CURRENT_PROGRAM, &program);
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer);
glGetIntegerv(GL_RENDERBUFFER_BINDING, &renderbuffer);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &arrayBuffer);
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &elementArrayBuffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &vertexArray);
glGetIntegerv(GL_BLEND_SRC_RGB, &blendSrcRgb);
glGetIntegerv(GL_BLEND_DST_RGB, &blendDstRgb);
glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrcAlpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDstAlpha);
glGetIntegerv(GL_BLEND_EQUATION_RGB, &blendEquationRgb);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blendEquationAlpha);
glGetIntegerv(GL_VIEWPORT, viewport.v());
glGetIntegerv(GL_SCISSOR_BOX, scissorBox.v());
glGetIntegerv(GL_DEPTH_FUNC, &depthFunc);
glGetIntegerv(GL_STENCIL_FUNC, &stencilFunc);
glGetIntegerv(GL_STENCIL_REF, &stencilRef);
glGetIntegerv(GL_STENCIL_VALUE_MASK, &stencilValueMask);
glGetIntegerv(GL_STENCIL_BACK_FUNC, &stencilBackFunc);
glGetIntegerv(GL_STENCIL_BACK_VALUE_MASK, &stencilBackValueMask);
glGetIntegerv(GL_STENCIL_BACK_REF, &stencilBackRef);
glGetIntegerv(GL_STENCIL_FAIL, &stencilFail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &stencilPassDepthFail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &stencilPassDepthPass);
glGetIntegerv(GL_STENCIL_BACK_FAIL, &stencilBackFail);
glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_FAIL, &stencilBackPassDepthFail);
glGetIntegerv(GL_STENCIL_BACK_PASS_DEPTH_PASS, &stencilBackPassDepthPass);
glGetIntegerv(GL_CULL_FACE_MODE, &cullFaceMode);
glGetFloatv(GL_COLOR_CLEAR_VALUE, colorClearValue.ptr());
blendEnabled = glIsEnabled(GL_BLEND);
cullFaceEnabled = glIsEnabled(GL_CULL_FACE);
depthTestEnabled = glIsEnabled(GL_DEPTH_TEST);
scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
stencilTestEnabled = glIsEnabled(GL_STENCIL_TEST);
framebufferSrgbEnabled = glIsEnabled(GL_FRAMEBUFFER_SRGB);
}
void RendererGLES30Snapshot::restore() {
glUseProgram(program);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glActiveTexture(GL_TEXTURE0 + activeTexture);
glBindTexture(GL_TEXTURE_2D, texture2D);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureCubeMap);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glBindVertexArray(vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementArrayBuffer);
glBlendEquationSeparate(blendEquationRgb, blendEquationAlpha);
glBlendFuncSeparate(blendSrcRgb, blendDstRgb, blendSrcAlpha, blendDstAlpha);
glDepthFunc(depthFunc);
glStencilFuncSeparate(GL_FRONT, stencilFunc, stencilRef, stencilValueMask);
glStencilFuncSeparate(GL_BACK, stencilBackFunc, stencilBackRef, stencilBackValueMask);
glStencilOpSeparate(GL_FRONT, stencilFail, stencilPassDepthFail, stencilPassDepthPass);
glStencilOpSeparate(GL_BACK, stencilBackFail, stencilBackPassDepthFail, stencilBackPassDepthPass);
glCullFace(cullFaceMode);
glClearColor(colorClearValue.r, colorClearValue.g, colorClearValue.b, colorClearValue.a);
if (blendEnabled)
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
if (cullFaceEnabled)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
if (depthTestEnabled)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
if (scissorTestEnabled)
glEnable(GL_SCISSOR_TEST);
else
glDisable(GL_SCISSOR_TEST);
if (stencilTestEnabled)
glEnable(GL_STENCIL_TEST);
else
glDisable(GL_STENCIL_TEST);
if (framebufferSrgbEnabled)
glEnable(GL_FRAMEBUFFER_SRGB);
else
glDisable(GL_FRAMEBUFFER_SRGB);
glViewport(viewport.x, viewport.y, viewport.w, viewport.h);
glScissor(scissorBox.x, scissorBox.y, scissorBox.w, scissorBox.h);
}
}
| 41.888889 | 100 | 0.782051 | microwerx |
2a48a46382db2584bb71399229333cf710812a53 | 35,596 | cpp | C++ | src/lib/pubkey/newhope/newhope.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | 1 | 2018-01-07T03:42:28.000Z | 2018-01-07T03:42:28.000Z | src/lib/pubkey/newhope/newhope.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | null | null | null | src/lib/pubkey/newhope/newhope.cpp | reneme/botan | b8b50eaf392a5da53d59f28919af0dcfd16b6f4d | [
"BSD-2-Clause"
] | null | null | null | /*
* NEWHOPE Ring-LWE scheme
* Based on the public domain reference implementation by the
* designers (https://github.com/tpoeppelmann/newhope)
*
* Further changes
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/newhope.h>
#include <botan/hash.h>
#include <botan/stream_cipher.h>
#include <botan/loadstor.h>
namespace Botan {
typedef newhope_poly poly;
// Don't change this :)
#define PARAM_Q 12289
#define PARAM_N 1024
#define NEWHOPE_POLY_BYTES 1792
#define NEWHOPE_SEED_BYTES 32
namespace {
/* Incomplete-reduction routines; for details on allowed input ranges
* and produced output ranges, see the description in the paper:
* https://cryptojedi.org/papers/#newhope */
inline uint16_t montgomery_reduce(uint32_t a)
{
const uint32_t qinv = 12287; // -inverse_mod(p,2^18)
const uint32_t rlog = 18;
uint32_t u;
u = (a * qinv);
u &= ((1<<rlog)-1);
u *= PARAM_Q;
a = a + u;
return a >> 18;
}
inline uint16_t barrett_reduce(uint16_t a)
{
uint32_t u = (static_cast<uint32_t>(a) * 5) >> 16;
u *= PARAM_Q;
a -= u;
return a;
}
inline void mul_coefficients(uint16_t* poly, const uint16_t* factors)
{
for(size_t i = 0; i < PARAM_N; i++)
poly[i] = montgomery_reduce((poly[i] * factors[i]));
}
/* GS_bo_to_no; omegas need to be in Montgomery domain */
inline void ntt(uint16_t * a, const uint16_t* omega)
{
for(size_t i=0;i<10;i+=2)
{
// Even level
size_t distance = (1<<i);
for(size_t start = 0; start < distance;start++)
{
size_t jTwiddle = 0;
for(size_t j=start;j<PARAM_N-1;j+=2*distance)
{
uint16_t W = omega[jTwiddle++];
uint16_t temp = a[j];
a[j] = (temp + a[j + distance]); // Omit reduction (be lazy)
a[j + distance] = montgomery_reduce((W * (static_cast<uint32_t>(temp) + 3*PARAM_Q - a[j + distance])));
}
}
// Odd level
distance <<= 1;
for(size_t start = 0; start < distance;start++)
{
size_t jTwiddle = 0;
for(size_t j=start;j<PARAM_N-1;j+=2*distance)
{
uint16_t W = omega[jTwiddle++];
uint16_t temp = a[j];
a[j] = barrett_reduce((temp + a[j + distance]));
a[j + distance] = montgomery_reduce((W * (static_cast<uint32_t>(temp) + 3*PARAM_Q - a[j + distance])));
}
}
}
}
inline void poly_frombytes(poly *r, const uint8_t *a)
{
for(size_t i=0;i<PARAM_N/4;i++)
{
r->coeffs[4*i+0] = a[7*i+0] | ((static_cast<uint16_t>(a[7*i+1]) & 0x3f) << 8);
r->coeffs[4*i+1] = (a[7*i+1] >> 6) | (static_cast<uint16_t>(a[7*i+2]) << 2) | (static_cast<uint16_t>(a[7*i+3] & 0x0f) << 10);
r->coeffs[4*i+2] = (a[7*i+3] >> 4) | (static_cast<uint16_t>(a[7*i+4]) << 4) | (static_cast<uint16_t>(a[7*i+5] & 0x03) << 12);
r->coeffs[4*i+3] = (a[7*i+5] >> 2) | (static_cast<uint16_t>(a[7*i+6]) << 6);
}
}
inline void poly_tobytes(uint8_t *r, const poly *p)
{
for(size_t i=0;i<PARAM_N/4;i++)
{
uint16_t t0 = barrett_reduce(p->coeffs[4*i+0]); //Make sure that coefficients have only 14 bits
uint16_t t1 = barrett_reduce(p->coeffs[4*i+1]);
uint16_t t2 = barrett_reduce(p->coeffs[4*i+2]);
uint16_t t3 = barrett_reduce(p->coeffs[4*i+3]);
uint16_t m;
int16_t c;
m = t0 - PARAM_Q;
c = m;
c >>= 15;
t0 = m ^ ((t0^m)&c); // <Make sure that coefficients are in [0,q]
m = t1 - PARAM_Q;
c = m;
c >>= 15;
t1 = m ^ ((t1^m)&c); // <Make sure that coefficients are in [0,q]
m = t2 - PARAM_Q;
c = m;
c >>= 15;
t2 = m ^ ((t2^m)&c); // <Make sure that coefficients are in [0,q]
m = t3 - PARAM_Q;
c = m;
c >>= 15;
t3 = m ^ ((t3^m)&c); // <Make sure that coefficients are in [0,q]
r[7*i+0] = t0 & 0xff;
r[7*i+1] = (t0 >> 8) | (t1 << 6);
r[7*i+2] = (t1 >> 2);
r[7*i+3] = (t1 >> 10) | (t2 << 4);
r[7*i+4] = (t2 >> 4);
r[7*i+5] = (t2 >> 12) | (t3 << 2);
r[7*i+6] = (t3 >> 6);
}
}
inline void poly_getnoise(Botan::RandomNumberGenerator& rng, poly *r)
{
uint8_t buf[4*PARAM_N];
rng.randomize(buf, 4*PARAM_N);
for(size_t i=0;i<PARAM_N;i++)
{
uint32_t t = load_le<uint32_t>(buf, i);
uint32_t d = 0;
for(int j=0;j<8;j++)
d += (t >> j) & 0x01010101;
uint32_t a = ((d >> 8) & 0xff) + (d & 0xff);
uint32_t b = (d >> 24) + ((d >> 16) & 0xff);
r->coeffs[i] = a + PARAM_Q - b;
}
}
inline void poly_pointwise(poly *r, const poly *a, const poly *b)
{
for(size_t i=0;i<PARAM_N;i++)
{
uint16_t t = montgomery_reduce(3186*b->coeffs[i]); /* t is now in Montgomery domain */
r->coeffs[i] = montgomery_reduce(a->coeffs[i] * t); /* r->coeffs[i] is back in normal domain */
}
}
inline void poly_add(poly *r, const poly *a, const poly *b)
{
for(size_t i=0;i<PARAM_N;i++)
r->coeffs[i] = barrett_reduce(a->coeffs[i] + b->coeffs[i]);
}
inline void poly_ntt(poly *r)
{
static const uint16_t omegas_montgomery[PARAM_N/2] = {
4075, 6974, 7373, 7965, 3262, 5079, 522, 2169, 6364, 1018, 1041, 8775, 2344,
11011, 5574, 1973, 4536, 1050, 6844, 3860, 3818, 6118, 2683, 1190, 4789,
7822, 7540, 6752, 5456, 4449, 3789, 12142, 11973, 382, 3988, 468, 6843, 5339,
6196, 3710, 11316, 1254, 5435, 10930, 3998, 10256, 10367, 3879, 11889, 1728,
6137, 4948, 5862, 6136, 3643, 6874, 8724, 654, 10302, 1702, 7083, 6760, 56,
3199, 9987, 605, 11785, 8076, 5594, 9260, 6403, 4782, 6212, 4624, 9026, 8689,
4080, 11868, 6221, 3602, 975, 8077, 8851, 9445, 5681, 3477, 1105, 142, 241,
12231, 1003, 3532, 5009, 1956, 6008, 11404, 7377, 2049, 10968, 12097, 7591,
5057, 3445, 4780, 2920, 7048, 3127, 8120, 11279, 6821, 11502, 8807, 12138,
2127, 2839, 3957, 431, 1579, 6383, 9784, 5874, 677, 3336, 6234, 2766, 1323,
9115, 12237, 2031, 6956, 6413, 2281, 3969, 3991, 12133, 9522, 4737, 10996,
4774, 5429, 11871, 3772, 453, 5908, 2882, 1805, 2051, 1954, 11713, 3963,
2447, 6142, 8174, 3030, 1843, 2361, 12071, 2908, 3529, 3434, 3202, 7796,
2057, 5369, 11939, 1512, 6906, 10474, 11026, 49, 10806, 5915, 1489, 9789,
5942, 10706, 10431, 7535, 426, 8974, 3757, 10314, 9364, 347, 5868, 9551,
9634, 6554, 10596, 9280, 11566, 174, 2948, 2503, 6507, 10723, 11606, 2459,
64, 3656, 8455, 5257, 5919, 7856, 1747, 9166, 5486, 9235, 6065, 835, 3570,
4240, 11580, 4046, 10970, 9139, 1058, 8210, 11848, 922, 7967, 1958, 10211,
1112, 3728, 4049, 11130, 5990, 1404, 325, 948, 11143, 6190, 295, 11637, 5766,
8212, 8273, 2919, 8527, 6119, 6992, 8333, 1360, 2555, 6167, 1200, 7105, 7991,
3329, 9597, 12121, 5106, 5961, 10695, 10327, 3051, 9923, 4896, 9326, 81,
3091, 1000, 7969, 4611, 726, 1853, 12149, 4255, 11112, 2768, 10654, 1062,
2294, 3553, 4805, 2747, 4846, 8577, 9154, 1170, 2319, 790, 11334, 9275, 9088,
1326, 5086, 9094, 6429, 11077, 10643, 3504, 3542, 8668, 9744, 1479, 1, 8246,
7143, 11567, 10984, 4134, 5736, 4978, 10938, 5777, 8961, 4591, 5728, 6461,
5023, 9650, 7468, 949, 9664, 2975, 11726, 2744, 9283, 10092, 5067, 12171,
2476, 3748, 11336, 6522, 827, 9452, 5374, 12159, 7935, 3296, 3949, 9893,
4452, 10908, 2525, 3584, 8112, 8011, 10616, 4989, 6958, 11809, 9447, 12280,
1022, 11950, 9821, 11745, 5791, 5092, 2089, 9005, 2881, 3289, 2013, 9048,
729, 7901, 1260, 5755, 4632, 11955, 2426, 10593, 1428, 4890, 5911, 3932,
9558, 8830, 3637, 5542, 145, 5179, 8595, 3707, 10530, 355, 3382, 4231, 9741,
1207, 9041, 7012, 1168, 10146, 11224, 4645, 11885, 10911, 10377, 435, 7952,
4096, 493, 9908, 6845, 6039, 2422, 2187, 9723, 8643, 9852, 9302, 6022, 7278,
1002, 4284, 5088, 1607, 7313, 875, 8509, 9430, 1045, 2481, 5012, 7428, 354,
6591, 9377, 11847, 2401, 1067, 7188, 11516, 390, 8511, 8456, 7270, 545, 8585,
9611, 12047, 1537, 4143, 4714, 4885, 1017, 5084, 1632, 3066, 27, 1440, 8526,
9273, 12046, 11618, 9289, 3400, 9890, 3136, 7098, 8758, 11813, 7384, 3985,
11869, 6730, 10745, 10111, 2249, 4048, 2884, 11136, 2126, 1630, 9103, 5407,
2686, 9042, 2969, 8311, 9424, 9919, 8779, 5332, 10626, 1777, 4654, 10863,
7351, 3636, 9585, 5291, 8374, 2166, 4919, 12176, 9140, 12129, 7852, 12286,
4895, 10805, 2780, 5195, 2305, 7247, 9644, 4053, 10600, 3364, 3271, 4057,
4414, 9442, 7917, 2174};
static const uint16_t psis_bitrev_montgomery[PARAM_N] = {
4075, 6974, 7373, 7965, 3262, 5079, 522, 2169, 6364, 1018, 1041, 8775, 2344,
11011, 5574, 1973, 4536, 1050, 6844, 3860, 3818, 6118, 2683, 1190, 4789,
7822, 7540, 6752, 5456, 4449, 3789, 12142, 11973, 382, 3988, 468, 6843, 5339,
6196, 3710, 11316, 1254, 5435, 10930, 3998, 10256, 10367, 3879, 11889, 1728,
6137, 4948, 5862, 6136, 3643, 6874, 8724, 654, 10302, 1702, 7083, 6760, 56,
3199, 9987, 605, 11785, 8076, 5594, 9260, 6403, 4782, 6212, 4624, 9026, 8689,
4080, 11868, 6221, 3602, 975, 8077, 8851, 9445, 5681, 3477, 1105, 142, 241,
12231, 1003, 3532, 5009, 1956, 6008, 11404, 7377, 2049, 10968, 12097, 7591,
5057, 3445, 4780, 2920, 7048, 3127, 8120, 11279, 6821, 11502, 8807, 12138,
2127, 2839, 3957, 431, 1579, 6383, 9784, 5874, 677, 3336, 6234, 2766, 1323,
9115, 12237, 2031, 6956, 6413, 2281, 3969, 3991, 12133, 9522, 4737, 10996,
4774, 5429, 11871, 3772, 453, 5908, 2882, 1805, 2051, 1954, 11713, 3963,
2447, 6142, 8174, 3030, 1843, 2361, 12071, 2908, 3529, 3434, 3202, 7796,
2057, 5369, 11939, 1512, 6906, 10474, 11026, 49, 10806, 5915, 1489, 9789,
5942, 10706, 10431, 7535, 426, 8974, 3757, 10314, 9364, 347, 5868, 9551,
9634, 6554, 10596, 9280, 11566, 174, 2948, 2503, 6507, 10723, 11606, 2459,
64, 3656, 8455, 5257, 5919, 7856, 1747, 9166, 5486, 9235, 6065, 835, 3570,
4240, 11580, 4046, 10970, 9139, 1058, 8210, 11848, 922, 7967, 1958, 10211,
1112, 3728, 4049, 11130, 5990, 1404, 325, 948, 11143, 6190, 295, 11637, 5766,
8212, 8273, 2919, 8527, 6119, 6992, 8333, 1360, 2555, 6167, 1200, 7105, 7991,
3329, 9597, 12121, 5106, 5961, 10695, 10327, 3051, 9923, 4896, 9326, 81,
3091, 1000, 7969, 4611, 726, 1853, 12149, 4255, 11112, 2768, 10654, 1062,
2294, 3553, 4805, 2747, 4846, 8577, 9154, 1170, 2319, 790, 11334, 9275, 9088,
1326, 5086, 9094, 6429, 11077, 10643, 3504, 3542, 8668, 9744, 1479, 1, 8246,
7143, 11567, 10984, 4134, 5736, 4978, 10938, 5777, 8961, 4591, 5728, 6461,
5023, 9650, 7468, 949, 9664, 2975, 11726, 2744, 9283, 10092, 5067, 12171,
2476, 3748, 11336, 6522, 827, 9452, 5374, 12159, 7935, 3296, 3949, 9893,
4452, 10908, 2525, 3584, 8112, 8011, 10616, 4989, 6958, 11809, 9447, 12280,
1022, 11950, 9821, 11745, 5791, 5092, 2089, 9005, 2881, 3289, 2013, 9048,
729, 7901, 1260, 5755, 4632, 11955, 2426, 10593, 1428, 4890, 5911, 3932,
9558, 8830, 3637, 5542, 145, 5179, 8595, 3707, 10530, 355, 3382, 4231, 9741,
1207, 9041, 7012, 1168, 10146, 11224, 4645, 11885, 10911, 10377, 435, 7952,
4096, 493, 9908, 6845, 6039, 2422, 2187, 9723, 8643, 9852, 9302, 6022, 7278,
1002, 4284, 5088, 1607, 7313, 875, 8509, 9430, 1045, 2481, 5012, 7428, 354,
6591, 9377, 11847, 2401, 1067, 7188, 11516, 390, 8511, 8456, 7270, 545, 8585,
9611, 12047, 1537, 4143, 4714, 4885, 1017, 5084, 1632, 3066, 27, 1440, 8526,
9273, 12046, 11618, 9289, 3400, 9890, 3136, 7098, 8758, 11813, 7384, 3985,
11869, 6730, 10745, 10111, 2249, 4048, 2884, 11136, 2126, 1630, 9103, 5407,
2686, 9042, 2969, 8311, 9424, 9919, 8779, 5332, 10626, 1777, 4654, 10863,
7351, 3636, 9585, 5291, 8374, 2166, 4919, 12176, 9140, 12129, 7852, 12286,
4895, 10805, 2780, 5195, 2305, 7247, 9644, 4053, 10600, 3364, 3271, 4057,
4414, 9442, 7917, 2174, 3947, 11951, 2455, 6599, 10545, 10975, 3654, 2894,
7681, 7126, 7287, 12269, 4119, 3343, 2151, 1522, 7174, 7350, 11041, 2442,
2148, 5959, 6492, 8330, 8945, 5598, 3624, 10397, 1325, 6565, 1945, 11260,
10077, 2674, 3338, 3276, 11034, 506, 6505, 1392, 5478, 8778, 1178, 2776,
3408, 10347, 11124, 2575, 9489, 12096, 6092, 10058, 4167, 6085, 923, 11251,
11912, 4578, 10669, 11914, 425, 10453, 392, 10104, 8464, 4235, 8761, 7376,
2291, 3375, 7954, 8896, 6617, 7790, 1737, 11667, 3982, 9342, 6680, 636, 6825,
7383, 512, 4670, 2900, 12050, 7735, 994, 1687, 11883, 7021, 146, 10485, 1403,
5189, 6094, 2483, 2054, 3042, 10945, 3981, 10821, 11826, 8882, 8151, 180,
9600, 7684, 5219, 10880, 6780, 204, 11232, 2600, 7584, 3121, 3017, 11053,
7814, 7043, 4251, 4739, 11063, 6771, 7073, 9261, 2360, 11925, 1928, 11825,
8024, 3678, 3205, 3359, 11197, 5209, 8581, 3238, 8840, 1136, 9363, 1826,
3171, 4489, 7885, 346, 2068, 1389, 8257, 3163, 4840, 6127, 8062, 8921, 612,
4238, 10763, 8067, 125, 11749, 10125, 5416, 2110, 716, 9839, 10584, 11475,
11873, 3448, 343, 1908, 4538, 10423, 7078, 4727, 1208, 11572, 3589, 2982,
1373, 1721, 10753, 4103, 2429, 4209, 5412, 5993, 9011, 438, 3515, 7228, 1218,
8347, 5232, 8682, 1327, 7508, 4924, 448, 1014, 10029, 12221, 4566, 5836,
12229, 2717, 1535, 3200, 5588, 5845, 412, 5102, 7326, 3744, 3056, 2528, 7406,
8314, 9202, 6454, 6613, 1417, 10032, 7784, 1518, 3765, 4176, 5063, 9828,
2275, 6636, 4267, 6463, 2065, 7725, 3495, 8328, 8755, 8144, 10533, 5966,
12077, 9175, 9520, 5596, 6302, 8400, 579, 6781, 11014, 5734, 11113, 11164,
4860, 1131, 10844, 9068, 8016, 9694, 3837, 567, 9348, 7000, 6627, 7699, 5082,
682, 11309, 5207, 4050, 7087, 844, 7434, 3769, 293, 9057, 6940, 9344, 10883,
2633, 8190, 3944, 5530, 5604, 3480, 2171, 9282, 11024, 2213, 8136, 3805, 767,
12239, 216, 11520, 6763, 10353, 7, 8566, 845, 7235, 3154, 4360, 3285, 10268,
2832, 3572, 1282, 7559, 3229, 8360, 10583, 6105, 3120, 6643, 6203, 8536,
8348, 6919, 3536, 9199, 10891, 11463, 5043, 1658, 5618, 8787, 5789, 4719,
751, 11379, 6389, 10783, 3065, 7806, 6586, 2622, 5386, 510, 7628, 6921, 578,
10345, 11839, 8929, 4684, 12226, 7154, 9916, 7302, 8481, 3670, 11066, 2334,
1590, 7878, 10734, 1802, 1891, 5103, 6151, 8820, 3418, 7846, 9951, 4693, 417,
9996, 9652, 4510, 2946, 5461, 365, 881, 1927, 1015, 11675, 11009, 1371,
12265, 2485, 11385, 5039, 6742, 8449, 1842, 12217, 8176, 9577, 4834, 7937,
9461, 2643, 11194, 3045, 6508, 4094, 3451, 7911, 11048, 5406, 4665, 3020,
6616, 11345, 7519, 3669, 5287, 1790, 7014, 5410, 11038, 11249, 2035, 6125,
10407, 4565, 7315, 5078, 10506, 2840, 2478, 9270, 4194, 9195, 4518, 7469,
1160, 6878, 2730, 10421, 10036, 1734, 3815, 10939, 5832, 10595, 10759, 4423,
8420, 9617, 7119, 11010, 11424, 9173, 189, 10080, 10526, 3466, 10588, 7592,
3578, 11511, 7785, 9663, 530, 12150, 8957, 2532, 3317, 9349, 10243, 1481,
9332, 3454, 3758, 7899, 4218, 2593, 11410, 2276, 982, 6513, 1849, 8494, 9021,
4523, 7988, 8, 457, 648, 150, 8000, 2307, 2301, 874, 5650, 170, 9462, 2873,
9855, 11498, 2535, 11169, 5808, 12268, 9687, 1901, 7171, 11787, 3846, 1573,
6063, 3793, 466, 11259, 10608, 3821, 6320, 4649, 6263, 2929};
mul_coefficients(r->coeffs, psis_bitrev_montgomery);
ntt(r->coeffs, omegas_montgomery);
}
inline void bitrev_vector(uint16_t* poly)
{
static const uint16_t bitrev_table[1024] = {
0,512,256,768,128,640,384,896,64,576,320,832,192,704,448,960,32,544,288,800,160,672,416,928,96,608,352,864,224,736,480,992,
16,528,272,784,144,656,400,912,80,592,336,848,208,720,464,976,48,560,304,816,176,688,432,944,112,624,368,880,240,752,496,1008,
8,520,264,776,136,648,392,904,72,584,328,840,200,712,456,968,40,552,296,808,168,680,424,936,104,616,360,872,232,744,488,1000,
24,536,280,792,152,664,408,920,88,600,344,856,216,728,472,984,56,568,312,824,184,696,440,952,120,632,376,888,248,760,504,1016,
4,516,260,772,132,644,388,900,68,580,324,836,196,708,452,964,36,548,292,804,164,676,420,932,100,612,356,868,228,740,484,996,
20,532,276,788,148,660,404,916,84,596,340,852,212,724,468,980,52,564,308,820,180,692,436,948,116,628,372,884,244,756,500,1012,
12,524,268,780,140,652,396,908,76,588,332,844,204,716,460,972,44,556,300,812,172,684,428,940,108,620,364,876,236,748,492,1004,
28,540,284,796,156,668,412,924,92,604,348,860,220,732,476,988,60,572,316,828,188,700,444,956,124,636,380,892,252,764,508,1020,
2,514,258,770,130,642,386,898,66,578,322,834,194,706,450,962,34,546,290,802,162,674,418,930,98,610,354,866,226,738,482,994,
18,530,274,786,146,658,402,914,82,594,338,850,210,722,466,978,50,562,306,818,178,690,434,946,114,626,370,882,242,754,498,1010,
10,522,266,778,138,650,394,906,74,586,330,842,202,714,458,970,42,554,298,810,170,682,426,938,106,618,362,874,234,746,490,1002,
26,538,282,794,154,666,410,922,90,602,346,858,218,730,474,986,58,570,314,826,186,698,442,954,122,634,378,890,250,762,506,1018,
6,518,262,774,134,646,390,902,70,582,326,838,198,710,454,966,38,550,294,806,166,678,422,934,102,614,358,870,230,742,486,998,
22,534,278,790,150,662,406,918,86,598,342,854,214,726,470,982,54,566,310,822,182,694,438,950,118,630,374,886,246,758,502,1014,
14,526,270,782,142,654,398,910,78,590,334,846,206,718,462,974,46,558,302,814,174,686,430,942,110,622,366,878,238,750,494,1006,
30,542,286,798,158,670,414,926,94,606,350,862,222,734,478,990,62,574,318,830,190,702,446,958,126,638,382,894,254,766,510,1022,
1,513,257,769,129,641,385,897,65,577,321,833,193,705,449,961,33,545,289,801,161,673,417,929,97,609,353,865,225,737,481,993,
17,529,273,785,145,657,401,913,81,593,337,849,209,721,465,977,49,561,305,817,177,689,433,945,113,625,369,881,241,753,497,1009,
9,521,265,777,137,649,393,905,73,585,329,841,201,713,457,969,41,553,297,809,169,681,425,937,105,617,361,873,233,745,489,1001,
25,537,281,793,153,665,409,921,89,601,345,857,217,729,473,985,57,569,313,825,185,697,441,953,121,633,377,889,249,761,505,1017,
5,517,261,773,133,645,389,901,69,581,325,837,197,709,453,965,37,549,293,805,165,677,421,933,101,613,357,869,229,741,485,997,
21,533,277,789,149,661,405,917,85,597,341,853,213,725,469,981,53,565,309,821,181,693,437,949,117,629,373,885,245,757,501,1013,
13,525,269,781,141,653,397,909,77,589,333,845,205,717,461,973,45,557,301,813,173,685,429,941,109,621,365,877,237,749,493,1005,
29,541,285,797,157,669,413,925,93,605,349,861,221,733,477,989,61,573,317,829,189,701,445,957,125,637,381,893,253,765,509,1021,
3,515,259,771,131,643,387,899,67,579,323,835,195,707,451,963,35,547,291,803,163,675,419,931,99,611,355,867,227,739,483,995,
19,531,275,787,147,659,403,915,83,595,339,851,211,723,467,979,51,563,307,819,179,691,435,947,115,627,371,883,243,755,499,1011,
11,523,267,779,139,651,395,907,75,587,331,843,203,715,459,971,43,555,299,811,171,683,427,939,107,619,363,875,235,747,491,1003,
27,539,283,795,155,667,411,923,91,603,347,859,219,731,475,987,59,571,315,827,187,699,443,955,123,635,379,891,251,763,507,1019,
7,519,263,775,135,647,391,903,71,583,327,839,199,711,455,967,39,551,295,807,167,679,423,935,103,615,359,871,231,743,487,999,
23,535,279,791,151,663,407,919,87,599,343,855,215,727,471,983,55,567,311,823,183,695,439,951,119,631,375,887,247,759,503,1015,
15,527,271,783,143,655,399,911,79,591,335,847,207,719,463,975,47,559,303,815,175,687,431,943,111,623,367,879,239,751,495,1007,
31,543,287,799,159,671,415,927,95,607,351,863,223,735,479,991,63,575,319,831,191,703,447,959,127,639,383,895,255,767,511,1023
};
unsigned int i,r;
uint16_t tmp;
for(i = 0; i < PARAM_N; i++)
{
r = bitrev_table[i];
if (i < r)
{
tmp = poly[i];
poly[i] = poly[r];
poly[r] = tmp;
}
}
}
inline void poly_invntt(poly *r)
{
static const uint16_t omegas_inv_montgomery[PARAM_N/2] = {
4075, 5315, 4324, 4916, 10120, 11767, 7210, 9027, 10316, 6715, 1278, 9945,
3514, 11248, 11271, 5925, 147, 8500, 7840, 6833, 5537, 4749, 4467, 7500,
11099, 9606, 6171, 8471, 8429, 5445, 11239, 7753, 9090, 12233, 5529, 5206,
10587, 1987, 11635, 3565, 5415, 8646, 6153, 6427, 7341, 6152, 10561, 400,
8410, 1922, 2033, 8291, 1359, 6854, 11035, 973, 8579, 6093, 6950, 5446,
11821, 8301, 11907, 316, 52, 3174, 10966, 9523, 6055, 8953, 11612, 6415,
2505, 5906, 10710, 11858, 8332, 9450, 10162, 151, 3482, 787, 5468, 1010,
4169, 9162, 5241, 9369, 7509, 8844, 7232, 4698, 192, 1321, 10240, 4912, 885,
6281, 10333, 7280, 8757, 11286, 58, 12048, 12147, 11184, 8812, 6608, 2844,
3438, 4212, 11314, 8687, 6068, 421, 8209, 3600, 3263, 7665, 6077, 7507, 5886,
3029, 6695, 4213, 504, 11684, 2302, 1962, 1594, 6328, 7183, 168, 2692, 8960,
4298, 5184, 11089, 6122, 9734, 10929, 3956, 5297, 6170, 3762, 9370, 4016,
4077, 6523, 652, 11994, 6099, 1146, 11341, 11964, 10885, 6299, 1159, 8240,
8561, 11177, 2078, 10331, 4322, 11367, 441, 4079, 11231, 3150, 1319, 8243,
709, 8049, 8719, 11454, 6224, 3054, 6803, 3123, 10542, 4433, 6370, 7032,
3834, 8633, 12225, 9830, 683, 1566, 5782, 9786, 9341, 12115, 723, 3009, 1693,
5735, 2655, 2738, 6421, 11942, 2925, 1975, 8532, 3315, 11863, 4754, 1858,
1583, 6347, 2500, 10800, 6374, 1483, 12240, 1263, 1815, 5383, 10777, 350,
6920, 10232, 4493, 9087, 8855, 8760, 9381, 218, 9928, 10446, 9259, 4115,
6147, 9842, 8326, 576, 10335, 10238, 10484, 9407, 6381, 11836, 8517, 418,
6860, 7515, 1293, 7552, 2767, 156, 8298, 8320, 10008, 5876, 5333, 10258,
10115, 4372, 2847, 7875, 8232, 9018, 8925, 1689, 8236, 2645, 5042, 9984,
7094, 9509, 1484, 7394, 3, 4437, 160, 3149, 113, 7370, 10123, 3915, 6998,
2704, 8653, 4938, 1426, 7635, 10512, 1663, 6957, 3510, 2370, 2865, 3978,
9320, 3247, 9603, 6882, 3186, 10659, 10163, 1153, 9405, 8241, 10040, 2178,
1544, 5559, 420, 8304, 4905, 476, 3531, 5191, 9153, 2399, 8889, 3000, 671,
243, 3016, 3763, 10849, 12262, 9223, 10657, 7205, 11272, 7404, 7575, 8146,
10752, 242, 2678, 3704, 11744, 5019, 3833, 3778, 11899, 773, 5101, 11222,
9888, 442, 2912, 5698, 11935, 4861, 7277, 9808, 11244, 2859, 3780, 11414,
4976, 10682, 7201, 8005, 11287, 5011, 6267, 2987, 2437, 3646, 2566, 10102,
9867, 6250, 5444, 2381, 11796, 8193, 4337, 11854, 1912, 1378, 404, 7644,
1065, 2143, 11121, 5277, 3248, 11082, 2548, 8058, 8907, 11934, 1759, 8582,
3694, 7110, 12144, 6747, 8652, 3459, 2731, 8357, 6378, 7399, 10861, 1696,
9863, 334, 7657, 6534, 11029, 4388, 11560, 3241, 10276, 9000, 9408, 3284,
10200, 7197, 6498, 544, 2468, 339, 11267, 9, 2842, 480, 5331, 7300, 1673,
4278, 4177, 8705, 9764, 1381, 7837, 2396, 8340, 8993, 4354, 130, 6915, 2837,
11462, 5767, 953, 8541, 9813, 118, 7222, 2197, 3006, 9545, 563, 9314, 2625,
11340, 4821, 2639, 7266, 5828, 6561, 7698, 3328, 6512, 1351, 7311, 6553,
8155, 1305, 722, 5146, 4043, 12288, 10810, 2545, 3621, 8747, 8785, 1646,
1212, 5860, 3195, 7203, 10963, 3201, 3014, 955, 11499, 9970, 11119, 3135,
3712, 7443, 9542, 7484, 8736, 9995, 11227, 1635, 9521, 1177, 8034, 140,
10436, 11563, 7678, 4320, 11289, 9198, 12208, 2963, 7393, 2366, 9238 };
static const uint16_t psis_inv_montgomery[PARAM_N] = {
256, 10570, 1510, 7238, 1034, 7170, 6291, 7921, 11665, 3422, 4000, 2327,
2088, 5565, 795, 10647, 1521, 5484, 2539, 7385, 1055, 7173, 8047, 11683,
1669, 1994, 3796, 5809, 4341, 9398, 11876, 12230, 10525, 12037, 12253, 3506,
4012, 9351, 4847, 2448, 7372, 9831, 3160, 2207, 5582, 2553, 7387, 6322, 9681,
1383, 10731, 1533, 219, 5298, 4268, 7632, 6357, 9686, 8406, 4712, 9451,
10128, 4958, 5975, 11387, 8649, 11769, 6948, 11526, 12180, 1740, 10782, 6807,
2728, 7412, 4570, 4164, 4106, 11120, 12122, 8754, 11784, 3439, 5758, 11356,
6889, 9762, 11928, 1704, 1999, 10819, 12079, 12259, 7018, 11536, 1648, 1991,
2040, 2047, 2048, 10826, 12080, 8748, 8272, 8204, 1172, 1923, 7297, 2798,
7422, 6327, 4415, 7653, 6360, 11442, 12168, 7005, 8023, 9924, 8440, 8228,
2931, 7441, 1063, 3663, 5790, 9605, 10150, 1450, 8985, 11817, 10466, 10273,
12001, 3470, 7518, 1074, 1909, 7295, 9820, 4914, 702, 5367, 7789, 8135, 9940,
1420, 3714, 11064, 12114, 12264, 1752, 5517, 9566, 11900, 1700, 3754, 5803,
829, 1874, 7290, 2797, 10933, 5073, 7747, 8129, 6428, 6185, 11417, 1631, 233,
5300, 9535, 10140, 11982, 8734, 8270, 2937, 10953, 8587, 8249, 2934, 9197,
4825, 5956, 4362, 9401, 1343, 3703, 529, 10609, 12049, 6988, 6265, 895, 3639,
4031, 4087, 4095, 585, 10617, 8539, 4731, 4187, 9376, 3095, 9220, 10095,
10220, 1460, 10742, 12068, 1724, 5513, 11321, 6884, 2739, 5658, 6075, 4379,
11159, 10372, 8504, 4726, 9453, 3106, 7466, 11600, 10435, 8513, 9994, 8450,
9985, 3182, 10988, 8592, 2983, 9204, 4826, 2445, 5616, 6069, 867, 3635, 5786,
11360, 5134, 2489, 10889, 12089, 1727, 7269, 2794, 9177, 1311, 5454, 9557,
6632, 2703, 9164, 10087, 1441, 3717, 531, 3587, 2268, 324, 5313, 759, 1864,
5533, 2546, 7386, 9833, 8427, 4715, 11207, 1601, 7251, 4547, 11183, 12131,
1733, 10781, 10318, 1474, 10744, 5046, 4232, 11138, 10369, 6748, 964, 7160,
4534, 7670, 8118, 8182, 4680, 11202, 6867, 981, 8918, 1274, 182, 26, 7026,
8026, 11680, 12202, 10521, 1503, 7237, 4545, 5916, 9623, 8397, 11733, 10454,
3249, 9242, 6587, 941, 1890, 270, 10572, 6777, 9746, 6659, 6218, 6155, 6146,
878, 1881, 7291, 11575, 12187, 1741, 7271, 8061, 11685, 6936, 4502, 9421,
4857, 4205, 7623, 1089, 10689, 1527, 8996, 10063, 11971, 10488, 6765, 2722,
3900, 9335, 11867, 6962, 11528, 5158, 4248, 4118, 5855, 2592, 5637, 6072,
2623, 7397, 8079, 9932, 4930, 5971, 853, 3633, 519, 8852, 11798, 3441, 11025,
1575, 225, 8810, 11792, 12218, 3501, 9278, 3081, 9218, 4828, 7712, 8124,
11694, 12204, 3499, 4011, 573, 3593, 5780, 7848, 9899, 10192, 1456, 208,
7052, 2763, 7417, 11593, 10434, 12024, 8740, 11782, 10461, 3250, 5731, 7841,
9898, 1414, 202, 3540, 7528, 2831, 2160, 10842, 5060, 4234, 4116, 588, 84,
12, 7024, 2759, 9172, 6577, 11473, 1639, 9012, 3043, 7457, 6332, 11438, 1634,
1989, 9062, 11828, 8712, 11778, 12216, 10523, 6770, 9745, 10170, 4964, 9487,
6622, 946, 8913, 6540, 6201, 4397, 9406, 8366, 9973, 8447, 8229, 11709, 8695,
10020, 3187, 5722, 2573, 10901, 6824, 4486, 4152, 9371, 8361, 2950, 2177,
311, 1800, 9035, 8313, 11721, 3430, 490, 70, 10, 1757, 251, 3547, 7529,
11609, 3414, 7510, 4584, 4166, 9373, 1339, 5458, 7802, 11648, 1664, 7260,
9815, 10180, 6721, 9738, 10169, 8475, 8233, 9954, 1422, 8981, 1283, 5450,
11312, 1616, 3742, 11068, 10359, 4991, 713, 3613, 9294, 8350, 4704, 672, 96,
7036, 9783, 11931, 3460, 5761, 823, 10651, 12055, 10500, 1500, 5481, 783,
3623, 11051, 8601, 8251, 8201, 11705, 10450, 5004, 4226, 7626, 2845, 2162,
3820, 7568, 9859, 3164, 452, 10598, 1514, 5483, 6050, 6131, 4387, 7649, 8115,
6426, 918, 8909, 8295, 1185, 5436, 11310, 8638, 1234, 5443, 11311, 5127,
2488, 2111, 10835, 5059, 7745, 2862, 3920, 560, 80, 1767, 2008, 3798, 11076,
6849, 2734, 10924, 12094, 8750, 1250, 10712, 6797, 971, 7161, 1023, 8924,
4786, 7706, 4612, 4170, 7618, 6355, 4419, 5898, 11376, 10403, 10264, 6733,
4473, 639, 5358, 2521, 9138, 3061, 5704, 4326, 618, 5355, 765, 5376, 768,
7132, 4530, 9425, 3102, 9221, 6584, 11474, 10417, 10266, 12000, 6981, 6264,
4406, 2385, 7363, 4563, 4163, 7617, 9866, 3165, 9230, 11852, 10471, 5007,
5982, 11388, 5138, 734, 3616, 11050, 12112, 6997, 11533, 12181, 10518, 12036,
3475, 2252, 7344, 9827, 4915, 9480, 6621, 4457, 7659, 9872, 6677, 4465, 4149,
7615, 4599, 657, 3605, 515, 10607, 6782, 4480, 640, 1847, 3775, 5806, 2585,
5636, 9583, 1369, 10729, 8555, 10000, 11962, 5220, 7768, 8132, 8184, 9947,
1421, 203, 29, 8782, 11788, 1684, 10774, 10317, 4985, 9490, 8378, 4708,
11206, 5112, 5997, 7879, 11659, 12199, 8765, 10030, 4944, 5973, 6120, 6141,
6144, 7900, 11662, 1666, 238, 34, 3516, 5769, 9602, 8394, 9977, 6692, 956,
10670, 6791, 9748, 11926, 8726, 11780, 5194, 742, 106, 8793, 10034, 3189,
10989, 5081, 4237, 5872, 4350, 2377, 10873, 6820, 6241, 11425, 10410, 10265,
3222, 5727, 9596, 4882, 2453, 2106, 3812, 11078, 12116, 5242, 4260, 11142,
8614, 11764, 12214, 5256, 4262, 4120, 11122, 5100, 11262, 5120, 2487, 5622,
9581, 8391, 8221, 2930, 10952, 12098, 6995, 6266, 9673, 4893, 699, 3611,
4027, 5842, 11368, 1624, 232, 8811, 8281, 1183, 169, 8802, 3013, 2186, 5579,
797, 3625, 4029, 11109, 1587, 7249, 11569, 8675, 6506, 2685, 10917, 12093,
12261, 12285, 1755, 7273, 1039, 1904, 272, 3550, 9285, 3082, 5707, 6082,
4380, 7648, 11626, 5172, 4250, 9385, 8363, 8217, 4685, 5936, 848, 8899, 6538,
934, 1889, 3781, 9318, 10109, 10222, 6727, 961, 5404, 772, 5377, 9546, 8386,
1198, 8949, 3034, 2189, 7335, 4559, 5918, 2601, 10905, 5069, 9502, 3113,
7467, 8089, 11689, 5181, 9518, 8382, 2953, 3933, 4073, 4093, 7607, 8109,
2914, 5683, 4323, 11151, 1593, 10761, 6804, 972, 3650, 2277, 5592, 4310,
7638, 9869, 4921, 703, 1856, 9043, 4803, 9464, 1352, 8971, 11815, 5199, 7765,
6376, 4422, 7654, 2849, 407, 8836, 6529, 7955, 2892, 9191, 1313, 10721,
12065, 12257, 1751, 9028, 8312, 2943, 2176, 3822, 546, 78, 8789, 11789,
10462, 12028, 6985, 4509, 9422, 1346, 5459, 4291, 613, 10621, 6784, 9747,
3148, 7472, 2823, 5670, 810, 7138, 8042, 4660, 7688, 6365, 6176, 6149, 2634,
5643, 9584, 10147, 11983, 5223, 9524, 11894, 10477, 8519, 1217, 3685, 2282,
326, 10580, 3267, 7489, 4581, 2410, 5611, 11335, 6886, 8006, 8166, 11700,
3427, 11023, 8597, 10006, 3185, 455, 65, 5276, 7776, 4622, 5927, 7869, 9902,
11948, 5218, 2501, 5624, 2559, 10899, 1557, 1978, 10816, 10323, 8497, 4725,
675, 1852, 10798, 12076, 10503, 3256, 9243, 3076, 2195, 10847, 12083, 10504,
12034, 10497 };
bitrev_vector(r->coeffs);
ntt(r->coeffs, omegas_inv_montgomery);
mul_coefficients(r->coeffs, psis_inv_montgomery);
}
inline void encode_a(uint8_t *r, const poly *pk, const uint8_t *seed)
{
int i;
poly_tobytes(r, pk);
for(i=0;i<NEWHOPE_SEED_BYTES;i++)
r[NEWHOPE_POLY_BYTES+i] = seed[i];
}
inline void decode_a(poly *pk, uint8_t *seed, const uint8_t *r)
{
int i;
poly_frombytes(pk, r);
for(i=0;i<NEWHOPE_SEED_BYTES;i++)
seed[i] = r[NEWHOPE_POLY_BYTES+i];
}
inline void encode_b(uint8_t *r, const poly *b, const poly *c)
{
poly_tobytes(r,b);
for(size_t i=0;i<PARAM_N/4;i++)
r[NEWHOPE_POLY_BYTES+i] = c->coeffs[4*i] | (c->coeffs[4*i+1] << 2) | (c->coeffs[4*i+2] << 4) | (c->coeffs[4*i+3] << 6);
}
inline void decode_b(poly *b, poly *c, const uint8_t *r)
{
poly_frombytes(b, r);
for(size_t i=0;i<PARAM_N/4;i++)
{
c->coeffs[4*i+0] = r[NEWHOPE_POLY_BYTES+i] & 0x03;
c->coeffs[4*i+1] = (r[NEWHOPE_POLY_BYTES+i] >> 2) & 0x03;
c->coeffs[4*i+2] = (r[NEWHOPE_POLY_BYTES+i] >> 4) & 0x03;
c->coeffs[4*i+3] = (r[NEWHOPE_POLY_BYTES+i] >> 6);
}
}
inline int32_t ct_abs(int32_t v)
{
int32_t mask = v >> 31;
return (v ^ mask) - mask;
}
inline int32_t f(int32_t *v0, int32_t *v1, int32_t x)
{
int32_t xit, t, r, b;
// Next 6 lines compute t = x/PARAM_Q;
b = x*2730;
t = b >> 25;
b = x - t*12289;
b = 12288 - b;
b >>= 31;
t -= b;
r = t & 1;
xit = (t>>1);
*v0 = xit+r; // v0 = round(x/(2*PARAM_Q))
t -= 1;
r = t & 1;
*v1 = (t>>1)+r;
return ct_abs(x-((*v0)*2*PARAM_Q));
}
inline int32_t g(int32_t x)
{
int32_t t,c,b;
// Next 6 lines compute t = x/(4*PARAM_Q);
b = x*2730;
t = b >> 27;
b = x - t*49156;
b = 49155 - b;
b >>= 31;
t -= b;
c = t & 1;
t = (t >> 1) + c; // t = round(x/(8*PARAM_Q))
t *= 8*PARAM_Q;
return ct_abs(t - x);
}
inline int16_t LDDecode(int32_t xi0, int32_t xi1, int32_t xi2, int32_t xi3)
{
int32_t t;
t = g(xi0);
t += g(xi1);
t += g(xi2);
t += g(xi3);
t -= 8*PARAM_Q;
t >>= 31;
return t&1;
}
inline void helprec(poly *c, const poly *v, RandomNumberGenerator& rng)
{
int32_t v0[4], v1[4];
uint8_t rand[32];
int i;
rng.randomize(rand, 32);
for(i=0; i<256; i++)
{
uint8_t rbit = (rand[i>>3] >> (i&7)) & 1;
int32_t k;
k = f(v0+0, v1+0, 8*v->coeffs[ 0+i] + 4*rbit);
k += f(v0+1, v1+1, 8*v->coeffs[256+i] + 4*rbit);
k += f(v0+2, v1+2, 8*v->coeffs[512+i] + 4*rbit);
k += f(v0+3, v1+3, 8*v->coeffs[768+i] + 4*rbit);
k = (2*PARAM_Q-1-k) >> 31;
int32_t v_tmp[4];
v_tmp[0] = ((~k) & v0[0]) ^ (k & v1[0]);
v_tmp[1] = ((~k) & v0[1]) ^ (k & v1[1]);
v_tmp[2] = ((~k) & v0[2]) ^ (k & v1[2]);
v_tmp[3] = ((~k) & v0[3]) ^ (k & v1[3]);
c->coeffs[ 0+i] = (v_tmp[0] - v_tmp[3]) & 3;
c->coeffs[256+i] = (v_tmp[1] - v_tmp[3]) & 3;
c->coeffs[512+i] = (v_tmp[2] - v_tmp[3]) & 3;
c->coeffs[768+i] = ( -k + 2*v_tmp[3]) & 3;
}
}
inline void rec(uint8_t *key, const poly *v, const poly *c)
{
int i;
int32_t tmp[4];
for(i=0;i<32;i++)
key[i] = 0;
for(i=0; i<256; i++)
{
tmp[0] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[ 0+i]) - PARAM_Q * (2*c->coeffs[ 0+i]+c->coeffs[768+i]);
tmp[1] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[256+i]) - PARAM_Q * (2*c->coeffs[256+i]+c->coeffs[768+i]);
tmp[2] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[512+i]) - PARAM_Q * (2*c->coeffs[512+i]+c->coeffs[768+i]);
tmp[3] = 16*PARAM_Q + 8*static_cast<int32_t>(v->coeffs[768+i]) - PARAM_Q * ( c->coeffs[768+i]);
key[i>>3] |= LDDecode(tmp[0], tmp[1], tmp[2], tmp[3]) << (i & 7);
}
}
void gen_a(poly *a, const uint8_t *seed, Newhope_Mode mode)
{
std::vector<uint8_t> buf(168*16);
std::unique_ptr<StreamCipher> xof;
if(mode == Newhope_Mode::BoringSSL)
{
xof = StreamCipher::create_or_throw("CTR-BE(AES-128)");
xof->set_key(seed, 16);
xof->set_iv(seed + 16, 16);
}
else
{
xof = StreamCipher::create_or_throw("SHAKE-128");
xof->set_key(seed, NEWHOPE_SEED_BYTES);
}
zeroise(buf);
xof->encrypt(buf);
unsigned int pos=0, ctr=0;
while(ctr < PARAM_N)
{
uint16_t val = (buf[pos] | (static_cast<uint16_t>(buf[pos+1]) << 8)) & 0x3fff; // Specialized for q = 12889
if(val < PARAM_Q)
a->coeffs[ctr++] = val;
pos += 2;
if(pos >= buf.size())
{
zeroise(buf);
xof->encrypt(buf);
pos = 0;
}
}
}
}
// API FUNCTIONS
void newhope_keygen(uint8_t *send, poly *sk, RandomNumberGenerator& rng,
Newhope_Mode mode)
{
poly a, e, r, pk;
uint8_t seed[NEWHOPE_SEED_BYTES];
rng.randomize(seed, NEWHOPE_SEED_BYTES);
gen_a(&a, seed, mode);
poly_getnoise(rng, sk);
poly_ntt(sk);
poly_getnoise(rng, &e);
poly_ntt(&e);
poly_pointwise(&r,sk,&a);
poly_add(&pk,&e,&r);
encode_a(send, &pk, seed);
}
void newhope_sharedb(uint8_t *sharedkey, uint8_t *send, const uint8_t *received,
RandomNumberGenerator& rng,
Newhope_Mode mode)
{
poly sp, ep, v, a, pka, c, epp, bp;
uint8_t seed[NEWHOPE_SEED_BYTES];
decode_a(&pka, seed, received);
gen_a(&a, seed, mode);
poly_getnoise(rng, &sp);
poly_ntt(&sp);
poly_getnoise(rng, &ep);
poly_ntt(&ep);
poly_pointwise(&bp, &a, &sp);
poly_add(&bp, &bp, &ep);
poly_pointwise(&v, &pka, &sp);
poly_invntt(&v);
poly_getnoise(rng, &epp);
poly_add(&v, &v, &epp);
helprec(&c, &v, rng);
encode_b(send, &bp, &c);
rec(sharedkey, &v, &c);
std::unique_ptr<HashFunction> hash(HashFunction::create(
(mode == Newhope_Mode::SHA3) ? "SHA-3(256)" : "SHA-256"));
if(!hash)
throw Exception("NewHope hash function not available");
hash->update(sharedkey, 32);
hash->final(sharedkey);
}
void newhope_shareda(uint8_t *sharedkey, const poly *sk, const uint8_t *received,
Newhope_Mode mode)
{
poly v,bp, c;
decode_b(&bp, &c, received);
poly_pointwise(&v,sk,&bp);
poly_invntt(&v);
rec(sharedkey, &v, &c);
std::unique_ptr<HashFunction> hash(HashFunction::create(
(mode == Newhope_Mode::SHA3) ? "SHA-3(256)" : "SHA-256"));
if(!hash)
throw Exception("NewHope hash function not available");
hash->update(sharedkey, 32);
hash->final(sharedkey);
}
}
#undef PARAM_N
#undef PARAM_Q
| 44.944444 | 129 | 0.631504 | reneme |
2a5579b49e8dcaecd38d4cb1636e32896d144f31 | 149 | hpp | C++ | RPC/GpApiRPC.hpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | RPC/GpApiRPC.hpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | RPC/GpApiRPC.hpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "RqRs/GpApiRqRs.hpp"
#include "Client/GpApiClient.hpp"
#include "Server/GpApiServer.hpp"
#include "GpApiVoidDesc.hpp"
| 18.625 | 34 | 0.738255 | ITBear |
2a58dfc89d20ff1d53638ffe6f7f9e24b9ed8eb4 | 48,690 | cpp | C++ | Intersectable.cpp | jambolo/Math | 470d58579a9aa18930f419f00332f10a7a2fd008 | [
"MIT"
] | null | null | null | Intersectable.cpp | jambolo/Math | 470d58579a9aa18930f419f00332f10a7a2fd008 | [
"MIT"
] | null | null | null | Intersectable.cpp | jambolo/Math | 470d58579a9aa18930f419f00332f10a7a2fd008 | [
"MIT"
] | null | null | null | #include "Intersectable.h"
#include "Box.h"
#include "Cone.h"
#include "Frustum.h"
#include "Line.h"
#include "MyMath.h"
#include "Plane.h"
#include "Point.h"
#include "Sphere.h"
#pragma warning( disable : 4100 ) // 'identifier' : unreferenced formal parameter
//! @param a The point to test.
//! @param b The point to test.
Intersectable::Result Intersectable::Intersects(Point const & a, Point const & b)
{
if ( MyMath::IsRelativelyCloseTo(a.value_.m_X, b.value_.m_X)
&& MyMath::IsRelativelyCloseTo(a.value_.m_Y, b.value_.m_Y)
&& MyMath::IsRelativelyCloseTo(a.value_.m_Z, b.value_.m_Z))
{
return INTERSECTS;
}
else
return NO_INTERSECTION;
}
//! @param point The point to test.
//! @param line The line to test.
//!
//! @return Returns NO_INTERSECTION or INTERSECTS
Intersectable::Result Intersectable::Intersects(Point const & point, Line const & line)
{
// // The point is on the line if the distance is close to 0
//
// return MyMath::IsCloseToZero( line.Distance( point ) );
//
// Yes, but also ...
// point is on the line if the distance from m_B to point is the same as the distance from m_B to the projection
// of point onto the line (which implies distance squared is a valid test, too).
Vector3 const pb = point.value_ - line.m_B; // Vector from m_B to point
float const d = Dot(pb, line.m_M); // Distance from m_B to the projection
if (MyMath::IsRelativelyCloseTo(d * d, pb.Length2()))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test.
//! @param ray The ray to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Ray const & ray)
{
// // The point is on the line if the distance is close to 0
//
// return MyMath::IsCloseToZero( ray.Distance( point ) );
//
// Yes, but also like the line ...
// point is on the ray if the distance from m_B to point is the same as the distance from m_B to the projection
// of point onto the line (which implies distance squared is a valid test, too), and t >= 0. Note that t is the
// distance from m_B to the projection of point onto the line. Zoinks!
Vector3 const pb = point.value_ - ray.m_B; // Vector from m_B to point
float const t = Dot(pb, ray.m_M); // Also, distance from m_B to the projection
if (t >= 0.f && MyMath::IsRelativelyCloseTo(t * t, pb.Length2()))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param segment The segment to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Segment const & segment)
{
// // The point is on the segment if the distance is close to 0
//
// return MyMath::IsCloseToZero( segment.Distance( point ) );
//
// Yes, but also like the line ...
// point is on the ray if the distance from m_B to point is the same as the distance from m_B to the projection
// of point onto the line (which implies distance squared is a valid test, too), and 0 <= t <= 1. Note that the
// length of m_M is the length of the segment in this case. Yowzer! That means the math is simple but it is not
// so obvious.
Vector3 const pb = point.value_ - segment.m_B; // Vector from m_B to point
float const s2 = segment.m_M.Length2(); // Length of segment squared
float const a = Dot(pb, segment.m_M); // t * s2
if (a >= 0.f && a <= s2 && MyMath::IsRelativelyCloseTo(a * a, pb.Length2()))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param plane The plane to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Plane const & plane)
{
if (MyMath::IsCloseToZero(Distance(point, plane)))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Point const & point, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param sphere The sphere to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Sphere const & sphere)
{
float const d2 = (point.value_ - sphere.m_C).Length2(); // Distance from center to point squared
if (d2 <= sphere.m_R * sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param cone The cone to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Cone const & cone)
{
Vector3 const p = point.value_ - cone.m_V;
float const ddp = Dot(cone.m_D, p);
if (ddp >= 0.f && ddp * ddp >= p.Length2() * cone.m_A * cone.m_A)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param aabox The AA box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, AABox const & aabox)
{
Vector3 const xpoint = point.value_ - aabox.m_Position;
if ( 0 <= xpoint.m_X && xpoint.m_X <= aabox.m_Scale.m_X
&& 0 <= xpoint.m_Y && xpoint.m_Y <= aabox.m_Scale.m_Y
&& 0 <= xpoint.m_Z && xpoint.m_Z <= aabox.m_Scale.m_Z)
{
return INTERSECTS;
}
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param box The oriented box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Box const & box)
{
Vector3 const xpoint = box.m_InverseOrientation * (point.value_ - box.m_Position);
if ( 0 <= xpoint.m_X && xpoint.m_X <= box.m_Scale.m_X
&& 0 <= xpoint.m_Y && xpoint.m_Y <= box.m_Scale.m_Y
&& 0 <= xpoint.m_Z && xpoint.m_Z <= box.m_Scale.m_Z)
{
return INTERSECTS;
}
else
return NO_INTERSECTION;
}
//! @param point The point to test
//! @param frustum The frustum to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, Frustum const & frustum)
{
for (auto const & side : frustum.sides_)
{
if (side.DirectedDistance(point) > 0.f)
return NO_INTERSECTION;
}
return INTERSECTS;
}
//! @param a The line to test
//! @param b The line to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & a, Line const & b)
{
if (MyMath::IsCloseToZero(Distance(a, b)))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param ray The ray to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Ray const & ray)
{
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param segment The segment to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Segment const & segment)
{
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param plane The plane to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, Plane const & plane)
{
if (!MyMath::IsCloseToZero(Dot(line.m_M, plane.m_N)))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param sphere The sphere to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, Sphere const & sphere)
{
if (Distance(sphere.m_C, line) <= sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param aabox The AA box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, AABox const & aabox)
{
Vector3 const box_max = aabox.m_Position + aabox.m_Scale; // Convenience and speed
// If the line intersects the yz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(line.m_M.m_X))
{
// Check the min yz plane
float const umin = (aabox.m_Position.m_X - line.m_B.m_X) / line.m_M.m_X;
float const ymin = line.m_B.m_Y + umin * line.m_M.m_Y;
float const zmin = line.m_B.m_Z + umin * line.m_M.m_Z;
if ( ymin >= aabox.m_Position.m_Y && ymin <= box_max.m_Y
&& zmin >= aabox.m_Position.m_Z && zmin <= box_max.m_Z)
{
return INTERSECTS;
}
// Check the max yz plane
float const umax = (box_max.m_X - line.m_B.m_X) / line.m_M.m_X;
float const ymax = line.m_B.m_Y + umax * line.m_M.m_Y;
float const zmax = line.m_B.m_Z + umax * line.m_M.m_Z;
if ( ymax >= aabox.m_Position.m_Y && ymax <= box_max.m_Y
&& zmax >= aabox.m_Position.m_Z && zmax <= box_max.m_Z)
{
return INTERSECTS;
}
}
// If the line intersects the xz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(line.m_M.m_Y))
{
// Check the min xz plane
float const umin = (aabox.m_Position.m_Y - line.m_B.m_Y) / line.m_M.m_Y;
float const xmin = line.m_B.m_X + umin * line.m_M.m_X;
float const zmin = line.m_B.m_Z + umin * line.m_M.m_Z;
if ( xmin >= aabox.m_Position.m_X && xmin <= box_max.m_X
&& zmin >= aabox.m_Position.m_Z && zmin <= box_max.m_Z)
{
return INTERSECTS;
}
// Check the max xz plane
float const umax = (box_max.m_Y - line.m_B.m_Y) / line.m_M.m_Y;
float const xmax = line.m_B.m_X + umax * line.m_M.m_X;
float const zmax = line.m_B.m_Z + umax * line.m_M.m_Z;
if ( xmax >= aabox.m_Position.m_X && xmax <= box_max.m_X
&& zmax >= aabox.m_Position.m_Z && zmax <= box_max.m_Z)
{
return INTERSECTS;
}
}
// If the line intersects the xy planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(line.m_M.m_Z))
{
// Check the min xy plane
float const umin = (aabox.m_Position.m_Z - line.m_B.m_Z) / line.m_M.m_Z;
float const xmin = line.m_B.m_X + umin * line.m_M.m_X;
float const ymin = line.m_B.m_Y + umin * line.m_M.m_Y;
if ( xmin >= aabox.m_Position.m_X && xmin <= box_max.m_X
&& ymin >= aabox.m_Position.m_Y && ymin <= box_max.m_Y)
{
return INTERSECTS;
}
// Check the max xy plane
float const umax = (box_max.m_Z - line.m_B.m_Z) / line.m_M.m_Z;
float const xmax = line.m_B.m_X + umax * line.m_M.m_X;
float const ymax = line.m_B.m_Y + umax * line.m_M.m_Y;
if ( xmax >= aabox.m_Position.m_X && xmax <= box_max.m_X
&& ymax >= aabox.m_Position.m_Y && ymax <= box_max.m_Y)
{
return INTERSECTS;
}
}
return NO_INTERSECTION;
}
//! @param line The line to test
//! @param box The oriented box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, Box const & box)
{
// Transform the line into the box's space (except for scale)
Vector3 const tb = box.m_InverseOrientation * (line.m_B - box.m_Position);
Vector3 const tm = box.m_InverseOrientation * line.m_M;
// If the line intersects the yz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(tm.m_X))
{
// Check the min yz plane
float const umin = (0.f - tb.m_X) / tm.m_X;
float const ymin = tb.m_Y + umin * tm.m_Y;
float const zmin = tb.m_Z + umin * tm.m_Z;
if (ymin >= 0.f && ymin <= box.m_Scale.m_Y && zmin >= 0.f && zmin <= box.m_Scale.m_Z)
return INTERSECTS;
// Check the max yz plane
float const umax = (box.m_Scale.m_X - tb.m_X) / tm.m_X;
float const ymax = tb.m_Y + umax * tm.m_Y;
float const zmax = tb.m_Z + umax * tm.m_Z;
if (ymax >= 0.f && ymax <= box.m_Scale.m_Y && zmax >= 0.f && zmax <= box.m_Scale.m_Z)
return INTERSECTS;
}
// If the line intersects the xz planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(tm.m_Y))
{
// Check the min xz plane
float const umin = (0.f - tb.m_Y) / tm.m_Y;
float const xmin = tb.m_X + umin * tm.m_X;
float const zmin = tb.m_Z + umin * tm.m_Z;
if (xmin >= 0.f && xmin <= box.m_Scale.m_X && zmin >= 0.f && zmin <= box.m_Scale.m_Z)
return INTERSECTS;
// Check the max xz plane
float const umax = (box.m_Scale.m_Y - tb.m_Y) / tm.m_Y;
float const xmax = tb.m_X + umax * tm.m_X;
float const zmax = tb.m_Z + umax * tm.m_Z;
if (xmax >= 0.f && xmax <= box.m_Scale.m_X && zmax >= 0.f && zmax <= box.m_Scale.m_Z)
return INTERSECTS;
}
// If the line intersects the xy planes, check each plane to see if any intersection is within the box
if (!MyMath::IsCloseToZero(tm.m_Z))
{
// Check the min xy plane
float const umin = (0.f - tb.m_Z) / tm.m_Z;
float const xmin = tb.m_X + umin * tm.m_X;
float const ymin = tb.m_Y + umin * tm.m_Y;
if (xmin >= 0.f && xmin <= box.m_Scale.m_X && ymin >= 0.f && ymin <= box.m_Scale.m_Y)
return INTERSECTS;
// Check the max xy plane
float const umax = (box.m_Scale.m_Z - tb.m_Z) / tm.m_Z;
float const xmax = tb.m_X + umax * tm.m_X;
float const ymax = tb.m_Y + umax * tm.m_Y;
if (xmax >= 0.f && xmax <= box.m_Scale.m_X && ymax >= 0.f && ymax <= box.m_Scale.m_Y)
return INTERSECTS;
}
return NO_INTERSECTION;
}
//! @param line The line to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Line const & line, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The ray to test.
//! @param b The ray to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & a, Ray const & b)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param segment The segment to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Segment const & segment)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param plane The plane to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Plane const & plane)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param sphere The sphere to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Box const & box)
{
return NO_INTERSECTION;
}
//! @param ray The ray to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The line segment to test
//! @param b The line segment to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Segment const & a, Segment const & b)
{
// First of all, reject if the AABoxes don't intersect.
if (Intersectable::Intersects(AABox(a.m_B, a.m_M), AABox(b.m_B, b.m_M)) == NO_INTERSECTION)
return NO_INTERSECTION;
// The line segments a and b intersect if 0<=s<=1 and 0<=t<=1 when a.m_B + s * a.m_M == b.m_B + t * b.m_M.
//
// Solving for s and t:
//
// a.m_B + s * a.m_M = b.m_B + t * b.m_M
// a.m_B - b.m_B = t * b.m_M - s * a.m_M
// c = t * b.m_M - s * a.m_M, c = a.m_B - b.m_B
//
// c.x = t * b.m_M.m_X - s * a.m_M.m_X
// c.y = t * b.m_M.m_Y - s * a.m_M.m_Y
// c.z = t * b.m_M.m_Z - s * a.m_M.m_Z
//
// sxy = ( c.x * b.m_M.m_Y - c.y * b.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Y - b.m_M.m_Y * a.m_M.m_X )
// txy = ( c.x * a.m_M.m_Y - c.y * a.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Y - b.m_M.m_Y * a.m_M.m_X )
// sxz = ( c.x * b.m_M.m_Z - c.z * b.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_X )
// txz = ( c.x * a.m_M.m_Z - c.z * a.m_M.m_X ) / ( b.m_M.m_X * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_X )
// syz = ( c.y * b.m_M.m_Z - c.z * b.m_M.m_Y ) / ( b.m_M.m_Y * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_Y )
// tyz = ( c.y * a.m_M.m_Z - c.z * a.m_M.m_Y ) / ( b.m_M.m_Y * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_Y )
//
// The segments intersect if sxy == sxz == syz and txy == txz == tyz, and 0<=s<=1 and 0<=t<=1, s = sxy and t = txy.
//
// Ideally only two of each of the three computations need to be checked, because the third is redundant. Rather
// than just picking two, all three are checked and the segments are considered to intersect if two of the three
// pass. Also, the division is never done -- it is integrated into the range test. These steps avoid precision
// problems and divide-by-0 when one or both segments are (nearly) parallel to an axis.
Vector3 const c = a.m_B - b.m_B;
int pass = 0; // Number of tests that pass
// Check if they intersect in the xy plane.
float const sxy = (c.m_X * b.m_M.m_Y - c.m_Y * b.m_M.m_X);
float const txy = (c.m_X * a.m_M.m_Y - c.m_Y * a.m_M.m_X);
float const dxy = b.m_M.m_X * a.m_M.m_Y - b.m_M.m_Y * a.m_M.m_X;
if (dxy > 0.f)
{
if (sxy >= 0.f && sxy <= dxy && txy >= 0 && txy <= dxy)
++pass;
}
else
{
if (sxy <= 0.f && sxy >= dxy && txy <= 0 && txy >= dxy)
++pass;
}
// Check if they intersect in the xz plane.
float const sxz = (c.m_X * b.m_M.m_Z - c.m_Z * b.m_M.m_X);
float const txz = (c.m_X * a.m_M.m_Z - c.m_Z * a.m_M.m_X);
float const dxz = b.m_M.m_X * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_X;
if (dxz > 0.f)
{
if (sxz >= 0.f && sxz <= dxz && txz >= 0 && txz <= dxz)
++pass;
}
else
{
if (sxz <= 0.f && sxz >= dxz && txz <= 0 && txz >= dxz)
++pass;
}
// Check if they intersect in the yz plane.
// The third test is needed only if one of the previous passed and one failed.
if (pass == 1)
{
float const syz = (c.m_Y * b.m_M.m_Z - c.m_Z * b.m_M.m_Y);
float const tyz = (c.m_Y * a.m_M.m_Z - c.m_Z * a.m_M.m_Y);
float const dyz = b.m_M.m_Y * a.m_M.m_Z - b.m_M.m_Z * a.m_M.m_Y;
if (dyz > 0.f)
{
if (syz >= 0.f && syz <= dyz && tyz >= 0 && tyz <= dyz)
++pass;
}
else
{
if (syz <= 0.f && syz >= dyz && tyz <= 0 && tyz >= dyz)
++pass;
}
}
if (pass >= 2)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param plane The plane to test.
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Segment const & segment, Plane const & plane)
{
float const da = plane.DirectedDistance(segment.m_B);
float const db = plane.DirectedDistance(segment.m_B + segment.m_M);
if (MyMath::IsCloseToZero(da) || MyMath::IsCloseToZero(db) || da * db < 0.f)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param sphere The sphere to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param aabox The line AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Box const & box)
{
return NO_INTERSECTION;
}
//! @param segment The line segment to test.
//! @param frustum The line frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The plane to test
//! @param b The plane to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Plane const & a, Plane const & b)
{
float const dot = Dot(a.m_N, b.m_N);
if (!MyMath::IsCloseTo(fabsf(dot), 1.0))
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param poly The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param sphere The sphere to test.
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Plane const & plane, Sphere const & sphere)
{
if (Distance(sphere.m_C, plane) <= sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param aabox The AA box to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Plane const & plane, AABox const & aabox)
{
HalfSpace const halfspace(plane);
if (Intersects(halfspace, aabox) == INTERSECTS)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Box const & box)
{
// // Plane equation: z = - ( plane.m_D + plane.m_N.m_X * x + plane.m_N.m_Y * y ) / plane.m_N.m_Z
// if ( !MyMath::IsCloseToZero( plane.m_N.m_X )
// {
// float const yy = plane.m_N.m_X * box.m_X;
// float const yyh = plane.m_N.m_X * ( box.m_X + box.m_W );
// float const zz = plane.m_N.m_Z * box.m_Z;
// float const zzd = plane.m_N.m_Z * ( box.m_Z + box.m_D );
// float const xw = box.m_X + box.m_W;
// float x;
// x = - ( plane.m_D + yy + zz ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// x = - ( plane.m_D + yyh + zz ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// x = - ( plane.m_D + yy + zzd ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// x = - ( plane.m_D + yyh + zzd ) / plane.m_N.m_X;
// if ( box.m_X <= x && x <= xw )
// {
// return INTERSECTS;
// }
// }
// if ( !MyMath::IsCloseToZero( plane.m_N.m_Y )
// {
// float const xx = plane.m_N.m_X * box.m_X;
// float const xxw = plane.m_N.m_X * ( box.m_X + box.m_W );
// float const zz = plane.m_N.m_Z * box.m_Z;
// float const zzd = plane.m_N.m_Z * ( box.m_Z + box.m_D );
// float const yh = box.m_Y + box.m_H;
// float y;
// y = - ( plane.m_D + xx + zz ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// y = - ( plane.m_D + xxw + zz ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// y = - ( plane.m_D + xx + zzd ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// y = - ( plane.m_D + xxw + zzd ) / plane.m_N.m_Y;
// if ( box.m_Y <= y && y <= yh )
// {
// return INTERSECTS;
// }
// }
// if ( !MyMath::IsCloseToZero( plane.m_N.m_Z )
// {
// float const xx = plane.m_N.m_X * box.m_X;
// float const xxw = plane.m_N.m_X * ( box.m_X + box.m_W );
// float const yy = plane.m_N.m_Y * box.m_Y;
// float const yyh = plane.m_N.m_Y * ( box.m_Y + box.m_H );
// float const zd = box.m_Z + box.m_D;
// float z;
// z = - ( plane.m_D + xx + yy ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// z = - ( plane.m_D + xxw + yy ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// z = - ( plane.m_D + xx + yyh ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// z = - ( plane.m_D + xxw + yyh ) / plane.m_N.m_Z;
// if ( box.m_Z <= z && z <= zd )
// {
// return INTERSECTS;
// }
// }
return NO_INTERSECTION;
}
//! @param plane The plane to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The poly to test.
//! @param b The poly to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & a, Poly const & b)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param sphere The sphere to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param cone The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Box const & box)
{
return NO_INTERSECTION;
}
//! @param poly The poly to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Poly const & poly, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The sphere to test.
//! @param b The sphere to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
Intersectable::Result Intersectable::Intersects(Sphere const & a, Sphere const & b)
{
float const dc2 = (a.m_C - b.m_C).Length2();
if (dc2 <= (a.m_R + b.m_R) * (a.m_R + b.m_R))
{
if (dc2 <= (a.m_R - b.m_R) * (a.m_R - b.m_R))
{
if (a.m_R < b.m_R)
return ENCLOSED_BY;
else
return ENCLOSES;
}
else
{
return INTERSECTS;
}
}
else
{
return NO_INTERSECTION;
}
}
//! @param sphere The sphere to test.
//! @param cone The cone to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
//!
//! @warning Not sure if this works
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, Cone const & cone)
{
float const c2 = cone.m_A * cone.m_A;
Vector3 const v1 = sphere.m_C - cone.m_V;
Vector3 const v2 = sqrtf(1.f - c2) * v1 + sphere.m_R * cone.m_D;
float const ddv2 = Dot(cone.m_D, v2);
if (ddv2 < 0.f || ddv2 * ddv2 < v2.Length2() * c2)
return NO_INTERSECTION;
float const ddv1 = Dot(cone.m_D, v1);
float const ld2 = v1.Length2();
if (ddv1 > 0.f || ddv1 * ddv1 < ld2 * (1.f - c2) || ld2 <= sphere.m_R * sphere.m_R)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param sphere The sphere to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param sphere The sphere to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, Box const & box)
{
return NO_INTERSECTION;
}
//! @param sphere The sphere to test.
//! @param frustum The frustum to test
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
//!
//! @warning This test returns false positives near the corners of the frustum.
//! @warning This function returns INTERSECTS when it should return ENCLOSES.
Intersectable::Result Intersectable::Intersects(Sphere const & sphere, Frustum const & frustum)
{
Result intersection = ENCLOSED_BY;
for (auto const & side : frustum.sides_)
{
float const d = side.DirectedDistance(sphere.m_C);
if (d > sphere.m_R)
return NO_INTERSECTION;
if (d > -sphere.m_R)
intersection = INTERSECTS;
}
return intersection;
}
//! @param a The cone to test.
//! @param b The cone to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & a, Cone const & b)
{
return NO_INTERSECTION;
}
//! @param cone The cone to test.
//! @param aabox The AA box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & cone, AABox const & aabox)
{
return NO_INTERSECTION;
}
//! @param cone The cone to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & cone, Box const & box)
{
return NO_INTERSECTION;
}
//! @param cone The cone to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Cone const & cone, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The AABox to test.
//! @param b The AABox to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, ENCLOSES, or ENCLOSED_BY.
Intersectable::Result Intersectable::Intersects(AABox const & a, AABox const & b)
{
float const ax0 = a.m_Position.m_X;
float const ay0 = a.m_Position.m_Y;
float const az0 = a.m_Position.m_Z;
float const ax1 = a.m_Position.m_X + a.m_Scale.m_X;
float const ay1 = a.m_Position.m_Y + a.m_Scale.m_Y;
float const az1 = a.m_Position.m_Z + a.m_Scale.m_Z;
float const bx0 = b.m_Position.m_X;
float const by0 = b.m_Position.m_Y;
float const bz0 = b.m_Position.m_Z;
float const bx1 = b.m_Position.m_X + b.m_Scale.m_X;
float const by1 = b.m_Position.m_Y + b.m_Scale.m_Y;
float const bz1 = b.m_Position.m_Z + b.m_Scale.m_Z;
assert(a.m_Scale.m_X >= 0.0f);
assert(a.m_Scale.m_Y >= 0.0f);
assert(a.m_Scale.m_Z >= 0.0f);
assert(b.m_Scale.m_X >= 0.0f);
assert(b.m_Scale.m_Y >= 0.0f);
assert(b.m_Scale.m_Z >= 0.0f);
if (ax0 <= bx1 && bx0 <= ax1 && ay0 <= by1 && by0 <= ay1 && az0 <= bz1 && bz0 <= az1)
{
if (bx0 <= ax0 && ax1 <= bx1 && by0 <= ay0 && ay1 <= by1 && bz0 <= az0 && az1 <= bz1)
return ENCLOSED_BY;
else if (ax0 <= bx0 && bx1 <= ax1 && ay0 <= by0 && by1 <= ay1 && az0 <= bz0 && bz1 <= az1)
return ENCLOSES;
else
return INTERSECTS;
}
else
{
return NO_INTERSECTION;
}
}
//! @param aabox The AABox to test.
//! @param box The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(AABox const & aabox, Box const & box)
{
return NO_INTERSECTION;
}
//! @param aabox The AABox to test.
//! @param frustum The frustum to test.
//!
//! @return Returns NO_INTERSECTION, INTERSECTS, or ENCLOSED_BY
//!
//! @warning Returns INTERSECTS when it should return ENCLOSES.
Intersectable::Result Intersectable::Intersects(AABox const & aabox, Frustum const & frustum)
{
// from Moller, Thomas. Realtime Rendering, 2nd Ed., pp. 612-3
//
// The box intersects the frustum if it is not in front of any of the planes of the frustum. The box is enclosed by the frustum
// if none of its vertexes is in front of any of the planes
// of the frustum.
bool intersectsAnyPlane = false;
for (auto const & side : frustum.sides_)
{
Result ic = Intersects(HalfSpace(side), aabox);
if (ic == NO_INTERSECTION)
return NO_INTERSECTION;
if (ic == INTERSECTS)
intersectsAnyPlane = true;
}
// Since it is not completely outside the frustum, if it intersects any plane then it intersects the frustum.
// Otherwise it is completely inside.
if (intersectsAnyPlane)
return INTERSECTS;
else
return ENCLOSED_BY;
}
//! @param a The oriented box to test.
//! @param b The oriented box to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Box const & a, Box const & b)
{
return NO_INTERSECTION;
}
//! @param box The oriented box to test.
//! @param frustum The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Box const & box, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The frustum to test.
//! @param b The frustum to test.
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Frustum const & a, Frustum const & b)
{
return NO_INTERSECTION;
}
//! @param point point to test
//! @param halfspace halfspace to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Point const & point, HalfSpace const & halfspace)
{
if (halfspace.m_Plane.DirectedDistance(point) <= 0.0f)
return INTERSECTS;
else
return NO_INTERSECTION;
}
//! @param line line to test
//! @param halfspace halfspace to test
//!
//! @return Returns NO_INTERSECTION or INTERSECTS.
Intersectable::Result Intersectable::Intersects(Line const & line, HalfSpace const & halfspace)
{
if (MyMath::IsCloseToZero(Dot(line.m_M, halfspace.m_Plane.m_N)))
return Intersects(Point(line.m_B), halfspace);
else
return INTERSECTS;
}
//! @param ray ray to test
//! @param halfspace halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Ray const & ray, HalfSpace const & halfspace)
{
return NO_INTERSECTION;
}
//! @param segment line segment to test
//! @param halfspace halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Segment const & segment, HalfSpace const & halfspace)
{
return NO_INTERSECTION;
}
//! @param plane plane to test
//! @param halfspace halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(Plane const & plane, HalfSpace const & halfspace)
{
return NO_INTERSECTION;
}
//! @param a halfspace to test
//! @param b halfspace to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & a, HalfSpace const & b)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param poly poly to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Poly const & poly)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param sphere sphere to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Sphere const & sphere)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param cone cone to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Cone const & cone)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param aabox AA box to test
//!
//! @return Returns NO_INTERSECTION, INTERSECTS or ENCLOSES.
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, AABox const & aabox)
{
// from Moller, Thomas. Realtime Rendering, 2nd Ed., pp. 586-8
//
// The box intersects the plane if at least one of the vertexes of the box is not on the same side as the
// one of the others. An optimization is to test only two vertexes along the diagonal most closely aligned
// with the plane's normal.
Point p0;
Point p1;
// Find the diagonal of the box (with endpoints p0 and p1) most closely aligned with the plane's normal
if (halfspace.m_Plane.m_N.m_X >= 0.0f)
{
p0.value_.m_X = aabox.m_Position.m_X;
p1.value_.m_X = aabox.m_Position.m_X + aabox.m_Scale.m_X;
}
else
{
p0.value_.m_X = aabox.m_Position.m_X + aabox.m_Scale.m_X;
p1.value_.m_X = aabox.m_Position.m_X;
}
if (halfspace.m_Plane.m_N.m_Y >= 0.0f)
{
p0.value_.m_Y = aabox.m_Position.m_Y;
p1.value_.m_Y = aabox.m_Position.m_Y + aabox.m_Scale.m_Y;
}
else
{
p0.value_.m_Y = aabox.m_Position.m_Y + aabox.m_Scale.m_Y;
p1.value_.m_Y = aabox.m_Position.m_Y;
}
if (halfspace.m_Plane.m_N.m_Z >= 0.0f)
{
p0.value_.m_Z = aabox.m_Position.m_Z;
p1.value_.m_Z = aabox.m_Position.m_Z + aabox.m_Scale.m_Z;
}
else
{
p0.value_.m_Z = aabox.m_Position.m_Z + aabox.m_Scale.m_Z;
p1.value_.m_Z = aabox.m_Position.m_Z;
}
// If p0 is in front of the plane then the box is outside the half-space. If p1 is behind the plane then the
// box is enclosed by the half-space. Otherwise, the box intersects the plane. Other cases do not need to be
// considered because in the direction of the normal p1 is always greater than p0.
if (halfspace.m_Plane.DirectedDistance(p0) > 0.0f)
return NO_INTERSECTION;
else if (halfspace.m_Plane.DirectedDistance(p1) < 0.0f)
return ENCLOSES;
else
return INTERSECTS;
}
//! @param halfspace halfspace to test
//! @param box oriented box to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Box const & box)
{
return NO_INTERSECTION;
}
//! @param halfspace halfspace to test
//! @param frustum frustum to test
//!
//! @todo Not implemented
Intersectable::Result Intersectable::Intersects(HalfSpace const & halfspace, Frustum const & frustum)
{
return NO_INTERSECTION;
}
//! @param a The line to test.
//! @param b The line to test.
//! @param ps The place to store the parameter for line @a a where the intersection occurs.
//! @param pt The place to store the parameter for line @a b where the intersection occurs.
//!
//! @return Number of intersections
int Intersectable::Intersection(Line const & a, Line const & b, float * ps, float * pt)
{
Vector3 const n = Cross(a.m_M, b.m_M);
Vector3 const ab = b.m_B - a.m_B;
// If the lines are parallel, then there are either 0 or infinite intersections ...
if (MyMath::IsCloseToZero(n.Length2(), 2. * MyMath::DEFAULT_FLOAT_TOLERANCE))
{
float const d = Dot(ab, a.m_M);
if (MyMath::IsRelativelyCloseTo(ab.Length2(), d * d, 2. * MyMath::DEFAULT_FLOAT_TOLERANCE))
return std::numeric_limits<int>::max(); // Co-linear, return infinity
else
return 0; // No intersection, return 0
}
// ... they are not parallel but if the distance between them is > 0 ...
else if (!MyMath::IsCloseToZero(Dot(n, ab)))
{
return 0; // No intersection, return 0
}
// ... otherwise, they intersect at a single point ...
else
{
// Source: http://www.flipcode.com/geometry/gprimer2_issue02.shtml
// Use the minor with largest determinant to maintain precision and prevent divide-by-0
if (fabs(n.m_Z) > fabs(n.m_X) && fabs(n.m_Z) > fabs(n.m_Y))
{
*ps = (ab.m_X * b.m_M.m_Y - ab.m_Y * b.m_M.m_X) / n.m_Z;
*pt = -(ab.m_X * a.m_M.m_Y - ab.m_Y * a.m_M.m_X) / n.m_Z;
}
else if (fabs(n.m_X) > fabs(n.m_Y))
{
*ps = (ab.m_Y * b.m_M.m_Z - ab.m_Z * b.m_M.m_Y) / n.m_X;
*pt = -(ab.m_Y * a.m_M.m_Z - ab.m_Z * a.m_M.m_Y) / n.m_X;
}
else
{
*ps = (ab.m_Z * b.m_M.m_X - ab.m_X * b.m_M.m_Z) / n.m_Y;
*pt = -(ab.m_Z * a.m_M.m_X - ab.m_X * a.m_M.m_Z) / n.m_Y;
}
return 1; // 1 intersection, return 1
}
}
//! @param a The line to test.
//! @param b The line to test.
//! @param pi The place to store the point of the intersection
//!
//! @return The number of intersections.
int Intersectable::Intersection(Line const & a, Line const & b, Point * pi)
{
float t, u;
int const n = Intersection(a, b, &t, &u);
if (n == 1)
*pi = a.m_M * t + a.m_B;
return n;
}
//! @param a The line segment to test.
//! @param b The line segment to test.
//! @param pi The place to store the point of the intersection (if the intersection is a point)
//!
//! @return The number of intersections.
int Intersectable::Intersection(Segment const & a, Segment const & b, Point * pi)
{
float t, u;
int const n = Intersection(Line(a.m_M, a.m_B), Line(b.m_M, b.m_B), &t, &u);
if (n == 1)
{
t *= a.m_M.ILength();
u *= b.m_M.ILength();
if (t < 0.f || t > 1.f || u < 0.f || u > 1.f)
return 0;
*pi = a.m_M * t + a.m_B;
}
return n;
}
//! @param line The line to test.
//! @param plane The plane to test.
//! @param pt Where to store the line's value of t at the intersection.
//!
//! @return Number of intersections
int Intersectable::Intersection(Line const & line, Plane const & plane, float * pt)
{
float const dot = Dot(line.m_M, plane.m_N);
float const distance = Distance(line.m_B, plane);
// If the line and the plane are parallel then there are 0 or > 1 intersections
if (MyMath::IsCloseToZero(dot))
{
if (MyMath::IsCloseToZero(distance))
return std::numeric_limits<int>::max(); // Line is co-planar
else
return 0; // Line does not intersect
}
*pt = -distance / dot;
return 1; // 1 intersection
}
//! @param line The line to test.
//! @param plane The plane to test.
//! @param pi The place to store the point of the intersection (if the intersection is a point)
//!
//! @return Number of intersections
int Intersectable::Intersection(Line const & line, Plane const & plane, Point * pi)
{
float t;
int const n = Intersection(line, plane, &t);
if (n == 1)
*pi = line.m_M * t + line.m_B;
return n;
}
//! @param a The plane to test.
//! @param b The plane to test.
//! @param pi The place to store the intersection (if the intersection is a line)
//!
//! @return Number of intersections
int Intersectable::Intersection(Plane const & a, Plane const & b, Line * pi)
{
float const n1n2 = Dot(a.m_N, b.m_N);
// If the Cross product of the normals is close to 0, the planes are parallel and possibly coincident
if (MyMath::IsCloseTo(fabsf(n1n2), 1.))
{
// The planes are parallel, if the D values are the same, the planes are coincident, otherwise the do
// not intersect
if (MyMath::IsRelativelyCloseTo(a.m_D, b.m_D))
return std::numeric_limits<int>::max();
else
return 0;
}
else
{
// p = ( c1 * N1 + c2 * N2 ) + u * ( N1 ^ N2 )
float const n1n1 = Dot(a.m_N, a.m_N);
float const n2n2 = Dot(b.m_N, b.m_N);
float const d = n1n1 * n2n2 - n1n2 * n1n2;
float const c1 = (b.m_D * n1n2 - a.m_D * n2n2) / d;
float const c2 = (a.m_D * n1n2 - b.m_D * n1n1) / d;
pi->m_B = a.m_N * c1 + b.m_N * c2;
pi->m_M = Cross(a.m_N, b.m_N);
return 1;
}
}
//! @param a The point to test.
//! @param b The point to test.
//!
//! Returns the distance between the points.
float Distance(Point const & a, Point const & b)
{
return (a.value_ - b.value_).Length();
}
//! @param point The point to test.
//! @param line The line to test.
//!
//! Returns the distance between the point and the line.
float Distance(Point const & point, Line const & line)
{
// Distance in n-space is
//
// || (P - B) - ((P - B) dot M)M ||
//
// but in 3D/2D, it is also
//
// || M cross (P - B) ||
//
// which is slightly faster
return Cross(point.value_ - line.m_B, line.m_M).Length();
}
//! @param point The point to test.
//! @param ray The ray to test.
//!
//! Returns the distance between the point and the ray.
float Distance(Point const & point, Ray const & ray)
{
float const t = Dot((point.value_ - ray.m_B), ray.m_M);
if (t <= 0.f)
return Distance(point, ray.m_B);
else
return Distance(point, ray.m_B + ray.m_M * t);
}
//! @param point The point to test.
//! @param segment The line segment to test.
//!
//! Returns the distance between the point and the line segment.
float Distance(Point const & point, Segment const & segment)
{
assert(!MyMath::IsCloseToZero(segment.m_M.Length2()));
float const t = Dot((point.value_ - segment.m_B), segment.m_M) / segment.m_M.Length2();
if (t <= 0.f)
return Distance(point, segment.m_B);
else if (t < 1.f)
return Distance(point, segment.m_B + segment.m_M * t);
else
return Distance(point, segment.m_B + segment.m_M);
}
//! @param point The point to test.
//! @param plane The plane to test.
//!
//! Returns the distance between the point and the plane.
float Distance(Point const & point, Plane const & plane)
{
return fabsf(Dot(plane.m_N, point.value_) + plane.m_D);
}
//! @param a The line to test.
//! @param b The line to test.
//!
//! Returns the distance between the lines.
float Distance(Line const & a, Line const & b)
{
// The distance between two lines is abs( ( a.m_M cross b.m_M ) dot ( a.m_B - b.m_B ) ) assuming the lines
// are not parallel. If the lines are parallel, the distance is the distance from the line to any point
// on the other line.
Vector3 const cross = Cross(a.m_M, b.m_M);
if (!MyMath::IsCloseToZero(cross.Length2(), 2. * MyMath::DEFAULT_FLOAT_TOLERANCE))
return fabsf(Dot(cross, (a.m_B - b.m_B)));
else
return Distance(a.m_B, b);
}
| 28.507026 | 131 | 0.625488 | jambolo |
2a595f10e7726880050db0c4ae8725f99808f58c | 4,668 | cpp | C++ | src/CAENDigitizerException.cpp | flagarde/CAENcpp | f008098ec7b0a4ca609e217df9d13b87179491c9 | [
"MIT"
] | null | null | null | src/CAENDigitizerException.cpp | flagarde/CAENcpp | f008098ec7b0a4ca609e217df9d13b87179491c9 | [
"MIT"
] | null | null | null | src/CAENDigitizerException.cpp | flagarde/CAENcpp | f008098ec7b0a4ca609e217df9d13b87179491c9 | [
"MIT"
] | null | null | null | #include "CAENDigitizerException.hpp"
#include "CAENDigitizerType.h"
namespace CAEN
{
const char* Exception::what() const noexcept
{
return m_What.c_str();
}
const char* Exception::description() const noexcept
{
return m_Description.c_str();
}
std::int_least8_t Exception::code() const noexcept
{
return m_Code;
}
Exception::Exception(const int_least8_t& code,const source_location& location) : source_location(location), m_Code(code)
{
constructMessage();
if(code != CAEN_DGTZ_Success) throw *this;
}
void Exception::constructMessage()
{
switch(m_Code)
{
case CAEN_DGTZ_Success:
m_Description = "Operation completed successfully";
break;
case CAEN_DGTZ_CommError:
m_Description = "Communication error";
break;
case CAEN_DGTZ_GenericError:
m_Description = "Unspecified error";
break;
case CAEN_DGTZ_InvalidParam:
m_Description = "Invalid parameter";
break;
case CAEN_DGTZ_InvalidLinkType:
m_Description = "Invalid Link Type";
break;
case CAEN_DGTZ_InvalidHandle:
m_Description = "Invalid device handle";
break;
case CAEN_DGTZ_MaxDevicesError:
m_Description = "Maximum number of devices exceeded";
break;
case CAEN_DGTZ_BadBoardType:
m_Description = "The operation is not allowed on this type of board";
break;
case CAEN_DGTZ_BadInterruptLev:
m_Description = "The interrupt level is not allowed";
break;
case CAEN_DGTZ_BadEventNumber:
m_Description = "The event number is bad";
break;
case CAEN_DGTZ_ReadDeviceRegisterFail:
m_Description = "Unable to read the registry";
break;
case CAEN_DGTZ_WriteDeviceRegisterFail:
m_Description = "Unable to write into the registry";
break;
case CAEN_DGTZ_InvalidChannelNumber:
m_Description = "The channel number is invalid";
break;
case CAEN_DGTZ_ChannelBusy:
m_Description = "The Channel is busy";
break;
case CAEN_DGTZ_FPIOModeInvalid:
m_Description = "Invalid FPIO Mode";
break;
case CAEN_DGTZ_WrongAcqMode:
m_Description = "Wrong acquisition mode";
break;
case CAEN_DGTZ_FunctionNotAllowed:
m_Description = "This function is not allowed for this module";
break;
case CAEN_DGTZ_Timeout:
m_Description = "Communication Timeout";
break;
case CAEN_DGTZ_InvalidBuffer:
m_Description = "The buffer is invalid";
break;
case CAEN_DGTZ_EventNotFound:
m_Description = "The event is not found";
break;
case CAEN_DGTZ_InvalidEvent:
m_Description = "The vent is invalid";
break;
case CAEN_DGTZ_OutOfMemory:
m_Description = "Out of memory";
break;
case CAEN_DGTZ_CalibrationError:
m_Description = "Unable to calibrate the board";
break;
case CAEN_DGTZ_DigitizerNotFound:
m_Description = "Unable to open the digitizer";
break;
case CAEN_DGTZ_DigitizerAlreadyOpen:
m_Description = "The Digitizer is already open";
break;
case CAEN_DGTZ_DigitizerNotReady:
m_Description = "The Digitizer is not ready to operate";
break;
case CAEN_DGTZ_InterruptNotConfigured:
m_Description = "The Digitizer has not the IRQ configured";\
break;
case CAEN_DGTZ_DigitizerMemoryCorrupted:
m_Description = "The digitizer flash memory is corrupted";
break;
case CAEN_DGTZ_DPPFirmwareNotSupported:
m_Description = "The digitizer dpp firmware is not supported in this lib version";
break;
case CAEN_DGTZ_InvalidLicense:
m_Description = "Invalid Firmware License";
break;
case CAEN_DGTZ_InvalidDigitizerStatus:
m_Description = "The digitizer is found in a corrupted status";
break;
case CAEN_DGTZ_UnsupportedTrace:
m_Description = "The given trace is not supported by the digitizer";
break;
case CAEN_DGTZ_InvalidProbe:
m_Description = "The given probe is not supported for the given digitizer's trace";
break;
case CAEN_DGTZ_UnsupportedBaseAddress:
m_Description = "The Base Address is not supported, it's a Desktop device ?";
break;
case CAEN_DGTZ_NotYetImplemented:
m_Description = "The function is not yet implemented";
break;
default:
m_Description = "Error code unknown";
break;
}
m_What = "\n\t[Code] : "+std::to_string(m_Code)+"\n\t[Description] : "+m_Description+"\n\t[File] : "+file_name()+"\n\t[Function] : "+function_name()+"\n\t[Line] : "+std::to_string(line())+"\n\t[Column] : "+std::to_string(column())+"\n";
}
};
| 31.972603 | 238 | 0.687875 | flagarde |
39895bee8a6c943606dcdb78e1e39735de17bf14 | 9,824 | cpp | C++ | RendererCore/src/WindowRegister.cpp | Gaiyitp9/TGRenderLab | 9251161088643bacdd82586210e468e28b4ce5d7 | [
"MIT"
] | null | null | null | RendererCore/src/WindowRegister.cpp | Gaiyitp9/TGRenderLab | 9251161088643bacdd82586210e468e28b4ce5d7 | [
"MIT"
] | null | null | null | RendererCore/src/WindowRegister.cpp | Gaiyitp9/TGRenderLab | 9251161088643bacdd82586210e468e28b4ce5d7 | [
"MIT"
] | null | null | null | /****************************************************************
* TianGong RenderLab *
* Copyright (c) Gaiyitp9. All rights reserved. *
* This code is licensed under the MIT License (MIT). *
*****************************************************************/
#include "WindowRegister.hpp"
#include "Window.hpp"
#include "Diagnostics/Debug.hpp"
#include <format>
#define REGISTER_MESSAGE(msg) {msg, L#msg}
namespace LCH
{
WindowRegister::WindowRegister()
: windowMessage({
REGISTER_MESSAGE(WM_NULL),
REGISTER_MESSAGE(WM_CREATE),
REGISTER_MESSAGE(WM_DESTROY),
REGISTER_MESSAGE(WM_MOVE),
REGISTER_MESSAGE(WM_SIZE),
REGISTER_MESSAGE(WM_ACTIVATE),
REGISTER_MESSAGE(WM_SETFOCUS),
REGISTER_MESSAGE(WM_KILLFOCUS),
REGISTER_MESSAGE(WM_ENABLE),
REGISTER_MESSAGE(WM_SETREDRAW),
REGISTER_MESSAGE(WM_SETTEXT),
REGISTER_MESSAGE(WM_GETTEXT),
REGISTER_MESSAGE(WM_GETTEXTLENGTH),
REGISTER_MESSAGE(WM_PAINT),
REGISTER_MESSAGE(WM_CLOSE),
REGISTER_MESSAGE(WM_QUERYENDSESSION),
REGISTER_MESSAGE(WM_QUIT),
REGISTER_MESSAGE(WM_QUERYOPEN),
REGISTER_MESSAGE(WM_ERASEBKGND),
REGISTER_MESSAGE(WM_SYSCOLORCHANGE),
REGISTER_MESSAGE(WM_ENDSESSION),
REGISTER_MESSAGE(WM_SHOWWINDOW),
REGISTER_MESSAGE(WM_CTLCOLORMSGBOX),
REGISTER_MESSAGE(WM_CTLCOLOREDIT),
REGISTER_MESSAGE(WM_CTLCOLORLISTBOX),
REGISTER_MESSAGE(WM_CTLCOLORBTN),
REGISTER_MESSAGE(WM_CTLCOLORDLG),
REGISTER_MESSAGE(WM_CTLCOLORSCROLLBAR),
REGISTER_MESSAGE(WM_CTLCOLORSTATIC),
REGISTER_MESSAGE(WM_WININICHANGE),
REGISTER_MESSAGE(WM_SETTINGCHANGE),
REGISTER_MESSAGE(WM_DEVMODECHANGE),
REGISTER_MESSAGE(WM_ACTIVATEAPP),
REGISTER_MESSAGE(WM_FONTCHANGE),
REGISTER_MESSAGE(WM_TIMECHANGE),
REGISTER_MESSAGE(WM_CANCELMODE),
REGISTER_MESSAGE(WM_SETCURSOR),
REGISTER_MESSAGE(WM_MOUSEACTIVATE),
REGISTER_MESSAGE(WM_CHILDACTIVATE),
REGISTER_MESSAGE(WM_QUEUESYNC),
REGISTER_MESSAGE(WM_GETMINMAXINFO),
REGISTER_MESSAGE(WM_ICONERASEBKGND),
REGISTER_MESSAGE(WM_NEXTDLGCTL),
REGISTER_MESSAGE(WM_SPOOLERSTATUS),
REGISTER_MESSAGE(WM_DRAWITEM),
REGISTER_MESSAGE(WM_MEASUREITEM),
REGISTER_MESSAGE(WM_DELETEITEM),
REGISTER_MESSAGE(WM_VKEYTOITEM),
REGISTER_MESSAGE(WM_CHARTOITEM),
REGISTER_MESSAGE(WM_SETFONT),
REGISTER_MESSAGE(WM_GETFONT),
REGISTER_MESSAGE(WM_QUERYDRAGICON),
REGISTER_MESSAGE(WM_COMPAREITEM),
REGISTER_MESSAGE(WM_GETOBJECT),
REGISTER_MESSAGE(WM_COMPACTING),
REGISTER_MESSAGE(WM_NCCREATE),
REGISTER_MESSAGE(WM_NCDESTROY),
REGISTER_MESSAGE(WM_NCCALCSIZE),
REGISTER_MESSAGE(WM_NCHITTEST),
REGISTER_MESSAGE(WM_NCPAINT),
REGISTER_MESSAGE(WM_NCACTIVATE),
REGISTER_MESSAGE(WM_GETDLGCODE),
REGISTER_MESSAGE(WM_NCMOUSEMOVE),
REGISTER_MESSAGE(WM_NCLBUTTONDOWN),
REGISTER_MESSAGE(WM_NCLBUTTONUP),
REGISTER_MESSAGE(WM_NCLBUTTONDBLCLK),
REGISTER_MESSAGE(WM_NCRBUTTONDOWN),
REGISTER_MESSAGE(WM_NCRBUTTONUP),
REGISTER_MESSAGE(WM_NCRBUTTONDBLCLK),
REGISTER_MESSAGE(WM_NCMBUTTONDOWN),
REGISTER_MESSAGE(WM_NCMBUTTONUP),
REGISTER_MESSAGE(WM_NCMBUTTONDBLCLK),
REGISTER_MESSAGE(WM_KEYDOWN),
REGISTER_MESSAGE(WM_KEYUP),
REGISTER_MESSAGE(WM_CHAR),
REGISTER_MESSAGE(WM_DEADCHAR),
REGISTER_MESSAGE(WM_SYSKEYDOWN),
REGISTER_MESSAGE(WM_SYSKEYUP),
REGISTER_MESSAGE(WM_SYSCHAR),
REGISTER_MESSAGE(WM_SYSDEADCHAR),
REGISTER_MESSAGE(WM_KEYLAST),
REGISTER_MESSAGE(WM_INITDIALOG),
REGISTER_MESSAGE(WM_COMMAND),
REGISTER_MESSAGE(WM_SYSCOMMAND),
REGISTER_MESSAGE(WM_TIMER),
REGISTER_MESSAGE(WM_HSCROLL),
REGISTER_MESSAGE(WM_VSCROLL),
REGISTER_MESSAGE(WM_INITMENU),
REGISTER_MESSAGE(WM_INITMENUPOPUP),
REGISTER_MESSAGE(WM_MENUSELECT),
REGISTER_MESSAGE(WM_MENUCHAR),
REGISTER_MESSAGE(WM_ENTERIDLE),
REGISTER_MESSAGE(WM_MOUSEWHEEL),
REGISTER_MESSAGE(WM_MOUSEMOVE),
REGISTER_MESSAGE(WM_LBUTTONDOWN),
REGISTER_MESSAGE(WM_LBUTTONUP),
REGISTER_MESSAGE(WM_LBUTTONDBLCLK),
REGISTER_MESSAGE(WM_RBUTTONDOWN),
REGISTER_MESSAGE(WM_RBUTTONUP),
REGISTER_MESSAGE(WM_RBUTTONDBLCLK),
REGISTER_MESSAGE(WM_MBUTTONDOWN),
REGISTER_MESSAGE(WM_MBUTTONUP),
REGISTER_MESSAGE(WM_MBUTTONDBLCLK),
REGISTER_MESSAGE(WM_PARENTNOTIFY),
REGISTER_MESSAGE(WM_MDICREATE),
REGISTER_MESSAGE(WM_MDIDESTROY),
REGISTER_MESSAGE(WM_MDIACTIVATE),
REGISTER_MESSAGE(WM_MDIRESTORE),
REGISTER_MESSAGE(WM_MDINEXT),
REGISTER_MESSAGE(WM_MDIMAXIMIZE),
REGISTER_MESSAGE(WM_MDITILE),
REGISTER_MESSAGE(WM_MDICASCADE),
REGISTER_MESSAGE(WM_MDIICONARRANGE),
REGISTER_MESSAGE(WM_MDIGETACTIVE),
REGISTER_MESSAGE(WM_MDISETMENU),
REGISTER_MESSAGE(WM_CUT),
REGISTER_MESSAGE(WM_COPYDATA),
REGISTER_MESSAGE(WM_COPY),
REGISTER_MESSAGE(WM_PASTE),
REGISTER_MESSAGE(WM_CLEAR),
REGISTER_MESSAGE(WM_UNDO),
REGISTER_MESSAGE(WM_RENDERFORMAT),
REGISTER_MESSAGE(WM_RENDERALLFORMATS),
REGISTER_MESSAGE(WM_DESTROYCLIPBOARD),
REGISTER_MESSAGE(WM_DRAWCLIPBOARD),
REGISTER_MESSAGE(WM_PAINTCLIPBOARD),
REGISTER_MESSAGE(WM_VSCROLLCLIPBOARD),
REGISTER_MESSAGE(WM_SIZECLIPBOARD),
REGISTER_MESSAGE(WM_ASKCBFORMATNAME),
REGISTER_MESSAGE(WM_CHANGECBCHAIN),
REGISTER_MESSAGE(WM_HSCROLLCLIPBOARD),
REGISTER_MESSAGE(WM_QUERYNEWPALETTE),
REGISTER_MESSAGE(WM_PALETTEISCHANGING),
REGISTER_MESSAGE(WM_PALETTECHANGED),
REGISTER_MESSAGE(WM_DROPFILES),
REGISTER_MESSAGE(WM_POWER),
REGISTER_MESSAGE(WM_WINDOWPOSCHANGED),
REGISTER_MESSAGE(WM_WINDOWPOSCHANGING),
REGISTER_MESSAGE(WM_HELP),
REGISTER_MESSAGE(WM_NOTIFY),
REGISTER_MESSAGE(WM_CONTEXTMENU),
REGISTER_MESSAGE(WM_TCARD),
REGISTER_MESSAGE(WM_MDIREFRESHMENU),
REGISTER_MESSAGE(WM_MOVING),
REGISTER_MESSAGE(WM_STYLECHANGED),
REGISTER_MESSAGE(WM_STYLECHANGING),
REGISTER_MESSAGE(WM_SIZING),
REGISTER_MESSAGE(WM_SETHOTKEY),
REGISTER_MESSAGE(WM_PRINT),
REGISTER_MESSAGE(WM_PRINTCLIENT),
REGISTER_MESSAGE(WM_POWERBROADCAST),
REGISTER_MESSAGE(WM_HOTKEY),
REGISTER_MESSAGE(WM_GETICON),
REGISTER_MESSAGE(WM_EXITMENULOOP),
REGISTER_MESSAGE(WM_ENTERMENULOOP),
REGISTER_MESSAGE(WM_DISPLAYCHANGE),
REGISTER_MESSAGE(WM_STYLECHANGED),
REGISTER_MESSAGE(WM_STYLECHANGING),
REGISTER_MESSAGE(WM_GETICON),
REGISTER_MESSAGE(WM_SETICON),
REGISTER_MESSAGE(WM_SIZING),
REGISTER_MESSAGE(WM_MOVING),
REGISTER_MESSAGE(WM_CAPTURECHANGED),
REGISTER_MESSAGE(WM_DEVICECHANGE),
REGISTER_MESSAGE(WM_PRINT),
REGISTER_MESSAGE(WM_PRINTCLIENT),
REGISTER_MESSAGE(WM_IME_SETCONTEXT),
REGISTER_MESSAGE(WM_IME_NOTIFY),
REGISTER_MESSAGE(WM_NCMOUSELEAVE),
REGISTER_MESSAGE(WM_EXITSIZEMOVE),
REGISTER_MESSAGE(WM_DWMNCRENDERINGCHANGED),
REGISTER_MESSAGE(WM_ENTERSIZEMOVE),
})
{
if (hInstance = GetModuleHandleW(nullptr))
ThrowLastError();
WNDCLASSEX wc = {};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WindowProcSetup;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = nullptr;
wc.hCursor = nullptr;
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.hIconSm = nullptr;
wc.lpszMenuName = nullptr;
wc.lpszClassName = L"Default";
if (RegisterClassExW(&wc))
ThrowLastError();
windowClassName[WindowType::Default] = L"Default";
}
WindowRegister::~WindowRegister()
{
for (auto& pair : windowClassName)
UnregisterClassW(pair.second.c_str(), hInstance);
}
LRESULT WindowRegister::WindowProcSetup(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// 注:窗口处理函数不能向上传递异常,还没有想到好的解决方案。这个项目里的异常主要是为了定位,
// 而且涉及的函数主要是一些简单的WIN32函数和c++的STL,基本上不会出错,所以在这里不处理异常
if (msg == WM_NCCREATE)
{
const CREATESTRUCT* const pCreate = reinterpret_cast<CREATESTRUCT*>(lParam);
Window* const pWnd = static_cast<Window*>(pCreate->lpCreateParams);
SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd));
SetWindowLongPtrW(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(WindowProcThunk));
return pWnd->WindowProc(hwnd, msg, wParam, lParam);
}
// 处理WM_NCCREATE之前的消息
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
LRESULT WindowRegister::WindowProcThunk(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
// 注:窗口处理函数不能向上传递异常,还没有想到好的解决方案。这个项目里的异常主要是为了定位,
// 涉及的函数是一些简单的WIN32函数和c++的STL,基本上不会出错,所以在这里不处理异常
Window* const pWnd = reinterpret_cast<Window*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
// 是否监控窗口消息
if (pWnd->spyMessage)
Debug::LogLine(WindowRegister::GetInstance().GetWindowMesssageInfo(pWnd->name, msg, wParam, lParam));
// 窗口被销毁后,窗口类也需要被销毁
if (msg == WM_DESTROY)
pWnd->destroy = true;
return pWnd->WindowProc(hwnd, msg, wParam, lParam);
}
WindowRegister& WindowRegister::GetInstance()
{
static WindowRegister s;
return s;
}
HINSTANCE WindowRegister::GetHInstance() const noexcept
{
return hInstance;
}
const std::wstring& WindowRegister::GetWindowClassName(const WindowType& type) const
{
return windowClassName.at(type);
}
std::wstring WindowRegister::GetWindowMesssageInfo(const std::wstring& window, UINT msg, WPARAM wp, LPARAM lp) const
{
std::wstring msgInfo;
msgInfo += std::format(L"{:<10}", window);
const auto it = windowMessage.find(msg);
if (it == windowMessage.end())
{
msgInfo += std::format(L" {:<25}", std::format(L"Unknown message: {:#x}", msg));
}
else
{
msgInfo += std::format(L" {:<25}", it->second);
}
msgInfo += std::format(L" LP: {:#018x}", lp);
msgInfo += std::format(L" WP: {:#018x}", wp);
return msgInfo;
}
} | 33.99308 | 118 | 0.739414 | Gaiyitp9 |
3989ab37c948861fd15cf884e9a594898755aee8 | 5,586 | cpp | C++ | owGame/WMO/WMO.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 30 | 2017-09-02T20:25:47.000Z | 2021-12-31T10:12:07.000Z | owGame/WMO/WMO.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | null | null | null | owGame/WMO/WMO.cpp | Chaos192/OpenWow | 1d91a51fafeedadc67122a3e9372ec4637a48434 | [
"Apache-2.0"
] | 23 | 2018-02-04T17:18:33.000Z | 2022-03-22T09:45:36.000Z | #include "stdafx.h"
#ifdef USE_WMO_MODELS
// Include
#include "WMO_Base_Instance.h"
// General
#include "WMO.h"
CWMO::CWMO(const IBaseManager& BaseManager, IRenderDevice& RenderDevice, const std::string& Filename)
: m_FileName(Filename)
, m_TexturesNames(nullptr)
, m_DoodadsFilenames(nullptr)
, m_BaseManager(BaseManager)
, m_RenderDevice(RenderDevice)
{
m_ChunkReader = std::make_unique<WoWChunkReader>(m_BaseManager, m_FileName);
// Version
{
auto buffer = m_ChunkReader->OpenChunk("MVER");
uint32 version;
buffer->readBytes(&version, 4);
_ASSERT(version == 17);
}
// Header
{
auto buffer = m_ChunkReader->OpenChunk("MOHD");
buffer->readBytes(&m_Header, sizeof(SWMO_MOHD));
m_Bounds = m_Header.bounding_box.Convert();
}
}
CWMO::~CWMO()
{
//Log::Error("Deleted.");
}
//
// ISceneNodeProvider
//
void CWMO::CreateInsances(const std::shared_ptr<CWMO_Base_Instance>& Parent) const
{
for (const auto& it : m_Groups)
{
auto groupInstance = Parent->CreateSceneNode<CWMO_Group_Instance>(Parent->GetWorldClient(), it);
Parent->AddGroupInstance(groupInstance);
//if (it->IsOutdoor())
// Parent->AddOutdoorGroupInstance(groupInstance);
m_BaseManager.GetManager<ILoader>()->AddToLoadQueue(groupInstance);
}
}
//
// ILoadable
//
bool CWMO::Load()
{
// Textures
if (auto buffer = m_ChunkReader->OpenChunk("MOTX"))
{
m_TexturesNames = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(m_TexturesNames.get(), buffer->getSize());
m_TexturesNames[buffer->getSize()] = '\0';
}
// Materials
for (const auto& mat : m_ChunkReader->OpenChunkT<SWMO_MOMT>("MOMT"))
{
auto material = MakeShared(WMO_Part_Material, m_RenderDevice, *this, mat);
m_Materials.push_back(material);
}
if (m_Materials.size() != m_Header.nTextures)
throw CException("WMO::Load: Materials count '%d' isn't equal textures count '%d'.", m_Materials.size(), m_Header.nTextures);
// Group names
if (auto buffer = m_ChunkReader->OpenChunk("MOGN"))
{
m_GroupNames = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(m_GroupNames.get(), buffer->getSize());
m_GroupNames[buffer->getSize()] = '\0';
}
// Skybox
if (auto buffer = m_ChunkReader->OpenChunk("MOSB"))
{
if (buffer->getSize() > 4)
{
std::unique_ptr<char[]> skyboxFilename = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(skyboxFilename.get(), buffer->getSize());
skyboxFilename[buffer->getSize()] = '\0';
Log::Error("WMO[%s]: Skybox [%s]", m_FileName.c_str(), skyboxFilename.get());
}
}
// Portal vertices
std::vector<glm::vec3> portalVertices;
for (const auto& pv : m_ChunkReader->OpenChunkT<glm::vec3>("MOPV"))
{
portalVertices.push_back(Fix_From_XZmY_To_XYZ(pv));
}
// Portal defs
std::vector<CWMO_Part_Portal> portals;
for (const auto& pt : m_ChunkReader->OpenChunkT<SWMO_MOPT>("MOPT"))
{
portals.push_back(CWMO_Part_Portal(portalVertices, pt));
}
// Portal references
std::vector<SWMO_MOPR> portalsReferences;
for (const auto& pr : m_ChunkReader->OpenChunkT<SWMO_MOPR>("MOPR"))
{
_ASSERT(pr.portalIndex >= 0 && pr.portalIndex < portals.size());
auto& portal = portals[pr.portalIndex];
portal.setGroup(pr.groupIndex, pr.side);
portalsReferences.push_back(pr);
}
#if 0
// Visible vertices
for (const auto& vv : m_ChunkReader->OpenChunkT<glm::vec3>("MOVV"))
{
m_VisibleBlockVertices.push_back(Fix_From_XZmY_To_XYZ(vv));
}
// Visible blocks
for (const auto& vb : m_ChunkReader->OpenChunkT<SWMO_MOVB>("MOVB"))
{
m_VisibleBlockList.push_back(vb);
}
#endif
// Lights
for (const auto& lt : m_ChunkReader->OpenChunkT<SWMO_MOLT>("MOLT"))
{
m_Lights.push_back(MakeShared(WMO_Part_Light, lt));
}
// Doodads set
for (const auto& ds : m_ChunkReader->OpenChunkT<SWMO_MODS>("MODS"))
{
m_DoodadsSetInfos.push_back(ds);
}
// Doodads filenames
if (auto buffer = m_ChunkReader->OpenChunk("MODN"))
{
m_DoodadsFilenames = std::unique_ptr<char[]>(new char[buffer->getSize() + 1]);
buffer->readBytes(m_DoodadsFilenames.get(), buffer->getSize());
m_DoodadsFilenames[buffer->getSize()] = '\0';
}
// Doodads placemnts
for (const auto& dd : m_ChunkReader->OpenChunkT<SWMO_MODD>("MODD"))
{
m_DoodadsPlacementInfos.push_back(dd);
}
// HACK! INCORRECT SIZE
//m_Header.nDoodadDefs = m_DoodadsPlacementInfos.size();
// Fog
for (const auto& fog : m_ChunkReader->OpenChunkT<SWMO_MFOG>("MFOG"))
{
m_Fogs.push_back(MakeShared(WMO_Part_Fog, fog));
}
// Group info
{
uint32 cntr = 0;
for (const auto& gi : m_ChunkReader->OpenChunkT<SWMO_MOGI>("MOGI"))
{
auto wmoGroup = MakeShared(CWMOGroup, m_BaseManager, m_RenderDevice, *this, cntr++, gi);
wmoGroup->AddParentLoadable(shared_from_this());
m_BaseManager.GetManager<ILoader>()->AddToLoadQueue(wmoGroup);
m_Groups.push_back(wmoGroup);
}
//for (const auto& groupIt : m_Groups)
}
m_ChunkReader.reset();
// Setup group portals
{
for (const auto& ref : portalsReferences)
{
auto portal = portals[ref.portalIndex];
auto group = m_Groups[ref.groupIndex];
if (ref.groupIndex == group->GetGroupIndex())
{
group->AddPortal(portal);
}
else _ASSERT(false);
}
}
/*
// Create portal controller
if (portals.size() > 0)
{
#ifdef USE_WMO_PORTALS_CULLING
m_PortalController = MakeShared(CWMO_PortalsComponent);
for (const auto& it : portalsReferences)
{
_ASSERT(it.portalIndex < portals.size());
_ASSERT(it.groupIndex < m_Groups.size());
}
#endif
}*/
return true;
}
bool CWMO::Delete()
{
return false;
}
#endif
| 23.470588 | 127 | 0.697637 | Chaos192 |
398a014d168421009d498635e782844e8a350fa4 | 16,655 | cxx | C++ | osprey/common/com/wn_simp.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/wn_simp.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/wn_simp.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2004, 2005, 2006 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
/* ====================================================================
* ====================================================================
*
* Module: wn_simp
*
* ====================================================================
* ====================================================================
*/
#include <stdint.h>
#ifdef USE_PCH
#include "common_com_pch.h"
#endif /* USE_PCH */
#pragma hdrstop
#include "defs.h"
#include "errors.h"
#include "erglob.h"
#include "tracing.h"
#include "wn.h"
#include "stab.h"
#include "wn_util.h"
#include "ir_reader.h"
#include "config.h"
#include "config_opt.h"
#include "config_targ.h"
#include "const.h"
#include "targ_const.h"
#ifdef BACK_END
#include "opt_alias_interface.h"
#endif
#include "wn_simp.h"
#if defined(KEY) && defined(Is_True_On)
#include "config_opt.h"
#endif
#ifdef BACK_END
BOOL WN_Simp_Fold_ILOAD = TRUE;
#else
BOOL WN_Simp_Fold_ILOAD = FALSE;
#endif
BOOL WN_Simp_Fold_LDA = FALSE;
#ifdef KEY
BOOL WN_Simp_Rsqrt_Newton_Raphson = TRUE;
#endif
/* Parent maps from LNO and anyone else who wants it */
WN_MAP WN_SimpParentMap = WN_MAP_UNDEFINED;
#define TRACEFILE TFile
/* To tell wn_simp_code.h that it's working on WHIRL */
#define WN_SIMP_WORKING_ON_WHIRL
/* Definitions for wn_simp_code.h */
/* Type definition */
typedef WN * simpnode;
/* Accessors */
#define SIMPNODE_operator(x) WN_operator(x)
#define SIMPNODE_rtype(x) WN_rtype(x)
#define SIMPNODE_desc(x) WN_desc(x)
#define SIMPNODE_opcode WN_opcode
#define SIMPNODE_load_offset WN_load_offset
#define SIMPNODE_cvtl_bits WN_cvtl_bits
#define SIMPNODE_st WN_st
#define SIMPNODE_st_idx WN_st_idx
#define SIMPNODE_ty WN_ty
#define SIMPNODE_object_ty WN_object_ty
#define SIMPNODE_load_addr_ty WN_load_addr_ty
#define SIMPNODE_kid0 WN_kid0
#define SIMPNODE_kid1 WN_kid1
#define SIMPNODE_kid WN_kid
#define SIMPNODE_element_size WN_element_size
#define SIMPNODE_idname_offset WN_idname_offset
#define SIMPNODE_lda_offset WN_lda_offset
#define SIMPNODE_label_number WN_label_number
#define SIMPNODE_num_dim WN_num_dim
#define SIMPNODE_array_base WN_array_base
#define SIMPNODE_array_index WN_array_index
#define SIMPNODE_array_dim WN_array_dim
#define SIMPNODE_intrinsic WN_intrinsic
#define SIMPNODE_kid_count WN_kid_count
#define SIMPNODE_kid WN_kid
#define SIMPNODE_const_val WN_const_val
#define SIMPNODE_fconst_val Const_Val
#define SIMPNODE_field_id WN_field_id // get the field id
#define SIMPNODE_i_field_id WN_field_id // get the field id
#define SIMPNODE_bit_offset WN_bit_offset // get the bit offset
#define SIMPNODE_i_bit_offset WN_bit_offset // get the bit offset
#define SIMPNODE_enable Enable_WN_Simp
#define SIMPNODE_op_bit_offset WN_bit_offset
#define SIMPNODE_op_bit_size WN_bit_size
/* Functions */
#define SIMPNODE_SimpCreateExp1 WN_SimpCreateExp1
#define SIMPNODE_SimpCreateExp2 WN_SimpCreateExp2
#define SIMPNODE_SimpCreateExp3 WN_SimpCreateExp3
#define SIMPNODE_SimpCreateCvtl WN_SimpCreateCvtl
#define SIMPNODE_SimpCreateExtract WN_SimpCreateExtract
#define SIMPNODE_SimpCreateDeposit WN_SimpCreateDeposit
#define SIMPNODE_TREE_DELETE WN_DELETE_Tree
#define SIMPNODE_DELETE WN_Delete
#define SIMPNODE_CopyNode WN_CopyNode
#define SIMPNODE_CreateIntconst WN_CreateIntconst
#define SIMPNODE_CreateFloatconstFromTcon Make_Const
#ifdef TARG_X8664
#define SIMPNODE_CreateSIMDconstFromTcon Make_Const
#endif
#define SIMPNODE_Simplify_Initialize WN_Simplify_Initialize
#define SIMPNODE_Compare_Symbols WN_Compare_Symbols
#define SIMPNODE_is_volatile WN_Is_Volatile_Mem
/* externally visible routines. These three are defined in wn_simp_code.h.
* They need a name defined here and in whatever external interface file
* exists for the routine
*/
#define SIMPNODE_SimplifyExp1 WN_SimplifyExp1
#define SIMPNODE_SimplifyExp2 WN_SimplifyExp2
#define SIMPNODE_SimplifyExp3 WN_SimplifyExp3
#define SIMPNODE_SimplifyCvtl WN_SimplifyCvtl
#define SIMPNODE_SimplifyIntrinsic WN_SimplifyIntrinsic
#define SIMPNODE_SimplifyIload WN_SimplifyIload
#define SIMPNODE_SimplifyIstore WN_SimplifyIstore
#define SIMPNODE_Simp_Compare_Trees WN_Simp_Compare_Trees
static void show_tree(OPCODE opc, WN *k0, WN *k1, WN *r)
{
fprintf(TRACEFILE,"\nBefore:\n");
fdump_tree(TRACEFILE,k0);
if (OPCODE_operator(opc) != OPR_CVTL) {
if (k1)
fdump_tree(TRACEFILE,k1);
fprintf(TRACEFILE,"%s\n",OPCODE_name(opc));
} else
fprintf(TRACEFILE,"%s %d\n",OPCODE_name(opc),(INT) (INTPS) k1);
fprintf(TRACEFILE,"=====\nAfter:\n");
fdump_tree(TRACEFILE,r);
fprintf(TRACEFILE,
"-----------------------------------------------------\n");
}
/* Walk a tree, simplifying from the bottom up. For operators
* that the simplifier doesn't know how to deal with, simplify and replace the
* children. For those that it does, simplify the children, then try and
* simplify the argument with new children.
*/
WN *WN_Simplify_Tree(WN *t, ALIAS_MANAGER *alias_manager)
{
OPCODE op;
OPERATOR opr;
WN *k0, *k1, *k2, *r=NULL, *temp, *result, *next, *prev;
INT16 numkids;
INT32 i;
numkids = WN_kid_count(t);
op = WN_opcode(t);
opr = OPCODE_operator(op);
result = t;
if (op == OPC_BLOCK) {
result = t;
r = WN_first(t);
while (r) {
prev = WN_prev(r);
next = WN_next(r);
temp = WN_Simplify_Tree(r);
if (temp != r) {
/* a simplification happened */
WN_next(temp) = next;
WN_prev(temp) = prev;
if (next) WN_prev(next) = temp;
if (prev) WN_next(prev) = temp;
if (WN_first(t) == r) WN_first(t) = temp;
if (WN_last(t) == r) WN_last(t) = temp;
}
r = next;
}
} else if (opr == OPR_ILOAD) {
k0 = WN_Simplify_Tree(WN_kid0(t));
r = WN_SimplifyIload(op,WN_load_offset(t),WN_ty(t),WN_field_id(t),WN_load_addr_ty(t),k0);
if (r) {
#ifdef BACK_END
if (alias_manager) {
Copy_alias_info(alias_manager,t,r);
}
#endif
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
result = t;
}
} else if (opr == OPR_ISTORE) {
k0 = WN_Simplify_Tree(WN_kid0(t));
k1 = WN_Simplify_Tree(WN_kid1(t));
r = WN_SimplifyIstore(op,WN_load_offset(t),WN_ty(t),WN_field_id(t),k0,k1);
if (r) {
#ifdef BACK_END
if (alias_manager) {
Copy_alias_info(alias_manager,t,r);
}
#endif
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
WN_kid1(t) = k1;
result = t;
}
} else if (opr == OPR_INTRINSIC_OP) {
for (i=0; i < numkids; i++) {
WN_kid(t,i) = WN_Simplify_Tree(WN_kid(t,i));
}
r = WN_SimplifyIntrinsic(op, WN_intrinsic(t), numkids, &WN_kid0(t));
if (r) {
WN_Delete(t);
result = r;
} else {
result = t;
}
} else if (opr == OPR_IO_ITEM) {
// For IO_ITEM, just simplify the kids
for (i=0; i < numkids; i++) {
WN_kid(t,i) = WN_Simplify_Tree(WN_kid(t,i));
}
result = t;
} else if (numkids == 1) {
k0 = WN_Simplify_Tree(WN_kid0(t));
if (WN_operator(t) != OPR_CVTL) {
r = WN_SimplifyExp1(op, k0);
} else {
r = WN_SimplifyCvtl(op, WN_cvtl_bits(t),k0);
}
if (r) {
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
result = t;
}
} else if (numkids == 2) {
k0 = WN_Simplify_Tree(WN_kid0(t));
k1 = WN_Simplify_Tree(WN_kid1(t));
r = WN_SimplifyExp2(op, k0, k1);
if (r) {
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
WN_kid1(t) = k1;
result = t;
}
} else if (numkids == 3) {
k0 = WN_Simplify_Tree(WN_kid0(t));
k1 = WN_Simplify_Tree(WN_kid1(t));
k2 = WN_Simplify_Tree(WN_kid(t,2));
r = WN_SimplifyExp3(op, k0, k1, k2);
if (r) {
WN_Delete(t);
result = r;
} else {
WN_kid0(t) = k0;
WN_kid1(t) = k1;
WN_kid(t,2) = k2;
result = t;
}
} else {
for (i=0; i < numkids; i++) {
WN_kid(t,i) = WN_Simplify_Tree(WN_kid(t,i));
}
result = t;
}
/* Update parent pointers */
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
numkids = WN_kid_count(result);
for (i=0; i < numkids; i++) {
WN_MAP_Set(WN_SimpParentMap, WN_kid(result,i), (void *) result);
}
}
return (result);
}
/* Assume that all children are already simplified, rebuild a tree using the new children.
* This only applies itself to a subset of expression nodes.
*/
WN *WN_Simplify_Rebuild_Expr_Tree(WN *t,ALIAS_MANAGER *alias_manager)
{
OPCODE op;
OPERATOR opr;
WN *k0, *k1, *k2, *r=NULL, *result;
INT16 numkids;
# if defined(KEY) && defined(Is_True_On)
static INT cur_idx = 0;
# endif
op = WN_opcode(t);
if (!OPCODE_is_expression(op)) return (t);
numkids = WN_kid_count(t);
opr = OPCODE_operator(op);
result = t;
if (opr == OPR_ILOAD) {
k0 = WN_kid0(t);
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyIload(op,WN_load_offset(t),WN_ty(t),WN_field_id(t),WN_load_addr_ty(t),k0);
if (r) {
# ifdef BACK_END
if (alias_manager) {
Copy_alias_info(alias_manager,t,r);
}
# endif
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else if (opr == OPR_INTRINSIC_OP) {
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyIntrinsic(op, WN_intrinsic(t), numkids, &WN_kid0(t));
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else if (numkids == 1) {
k0 = WN_kid0(t);
if (WN_operator(t) != OPR_CVTL) {
if (WN_operator(t) == OPR_EXTRACT_BITS) {
r = WN_SimplifyExp1(op,t);
} else {
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyExp1(op, k0);
}
} else {
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyCvtl(op, WN_cvtl_bits(t),k0);
}
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
WN_kid0(t) = k0;
result = t;
}
} else if (numkids == 2) {
k0 = WN_kid0(t);
k1 = WN_kid1(t);
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
#ifdef KEY // bug 13507
if (opr != OPR_PAIR)
#endif
r = WN_SimplifyExp2(op, k0, k1);
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else if (numkids == 3) {
k0 = WN_kid0(t);
k1 = WN_kid1(t);
k2 = WN_kid(t,2);
# if defined (KEY) && defined (Is_True_On)
if (Enable_WN_Simp_Expr_Limit == -1 || (Enable_WN_Simp_Expr_Limit != -1 && cur_idx < Enable_WN_Simp_Expr_Limit))
# endif
r = WN_SimplifyExp3(op, k0, k1, k2);
if (r) {
WN_CopyMap(r, WN_MAP_ALIAS_CGNODE, t);
WN_Delete(t);
result = r;
# if defined (KEY) && defined (Is_True_On)
cur_idx ++;
# endif
} else {
result = t;
}
} else {
result = t;
}
return (result);
}
/* Allow the simplifier to be turned on and off */
BOOL WN_Simplifier_Enable(BOOL enable)
{
BOOL r = Enable_WN_Simp;
Enable_WN_Simp = enable;
return (r);
}
/* Utility procedure which does a comparison on two symbols */
static INT32 WN_Compare_Symbols(simpnode t1, simpnode t2)
{
ST_IDX s1 = SIMPNODE_st_idx(t1);
ST_IDX s2 = SIMPNODE_st_idx(t2);
if (s1 < s2)
return -1;
else if (s1 > s2)
return 1;
else
return 0;
}
/************ The code is here *******************/
#include "wn_simp_code.h"
/**************************************************/
/* Things which need to be written by the user */
/* Interface to WN_CreateExp3, checking for parent updates */
static simpnode WN_SimpCreateExp3(OPCODE opc,
simpnode k0, simpnode k1, simpnode k2)
{
simpnode wn;
wn = WN_SimplifyExp3(opc, k0, k1, k2);
if (!wn) {
wn = WN_Create(opc,3);
WN_kid0(wn) = k0;
WN_kid1(wn) = k1;
WN_kid(wn,2) = k2;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k1, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k2, (void *) wn);
}
}
return(wn);
}
/* Interface to WN_CreateExp2, checking for parent updates */
static simpnode WN_SimpCreateExp2(OPCODE opc, simpnode k0, simpnode k1)
{
simpnode wn;
wn = WN_SimplifyExp2(opc, k0, k1);
if (!wn) {
wn = WN_Create(opc,2);
WN_kid0(wn) = k0;
WN_kid1(wn) = k1;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k1, (void *) wn);
}
}
return(wn);
}
/* Interface to WN_CreateExp1, checking for parent updates */
static simpnode WN_SimpCreateExp1(OPCODE opc, simpnode k0)
{
simpnode wn;
wn = WN_SimplifyExp1(opc, k0);
if (!wn) {
wn = WN_Create(opc,1);
WN_kid0(wn) = k0;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
}
}
return(wn);
}
/* Interface to WN_CreateCvtl, checking for parent updates */
static simpnode WN_SimpCreateCvtl(OPCODE opc, INT16 bits, simpnode k0)
{
simpnode wn;
wn = WN_SimplifyCvtl(opc, bits, k0);
if (!wn) {
wn = WN_Create(opc,1);
WN_kid0(wn) = k0;
WN_cvtl_bits(wn) = bits;
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
}
}
return(wn);
}
static simpnode WN_SimpCreateExtract(OPCODE opc, INT16 boffset, INT16 bsize, simpnode k0)
{
simpnode wn;
wn = WN_Create(opc,1);
WN_kid0(wn) = k0;
WN_set_bit_offset_size(wn,boffset,bsize);
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
}
return(wn);
}
static simpnode WN_SimpCreateDeposit(OPCODE opc, INT16 boffset, INT16 bsize, simpnode k0, simpnode k1)
{
simpnode wn;
wn = WN_Create(opc,2);
WN_kid0(wn) = k0;
WN_kid1(wn) = k1;
WN_set_bit_offset_size(wn,boffset,bsize);
if (WN_SimpParentMap != WN_MAP_UNDEFINED) {
WN_MAP_Set(WN_SimpParentMap, k0, (void *) wn);
WN_MAP_Set(WN_SimpParentMap, k1, (void *) wn);
}
return(wn);
}
static void SIMPNODE_Simplify_Initialize( void )
{
trace_rules = (Get_Trace(TP_WHIRLSIMP, 1) != 0);
trace_trees = (Get_Trace(TP_WHIRLSIMP, 2) != 0);
SIMPNODE_simp_initialized = TRUE;
}
| 27.620232 | 124 | 0.653197 | sharugupta |
398a765b86b2c2511401a8ffcded4ab9c2fa53d7 | 5,374 | cpp | C++ | D3/BillboardParticles.cpp | Sudoka/D3 | 40c43bfc8bc619a344796c69a720be752e660eac | [
"CC-BY-3.0"
] | 1 | 2018-06-21T04:04:45.000Z | 2018-06-21T04:04:45.000Z | D3/BillboardParticles.cpp | Sudoka/D3 | 40c43bfc8bc619a344796c69a720be752e660eac | [
"CC-BY-3.0"
] | null | null | null | D3/BillboardParticles.cpp | Sudoka/D3 | 40c43bfc8bc619a344796c69a720be752e660eac | [
"CC-BY-3.0"
] | null | null | null | //
// BillboardParticles.cpp
// D3
//
// Created by Srđan Rašić on 10/7/12.
// Copyright (c) 2012 Srđan Rašić. All rights reserved.
//
#include "BillboardParticles.hpp"
namespace d3 {
BillboardParticles::BillboardParticles(shared_ptr<ParticleSystem> particle_system) : emitter(particle_system)
{
unsigned max_particle_count = emitter->max_particle_count;
/* Create index buffer */
ibo = shared_ptr<VertexData>(new BufferedVertexData(sizeof(unsigned) * max_particle_count * 6,
sizeof(unsigned), GL_STATIC_DRAW, GL_ELEMENT_ARRAY_BUFFER, NULL));
unsigned * indices = (unsigned *)ibo->mapData();
IndexTemplate tmp;
for (int i = 0; i < max_particle_count * 6; i++)
indices[i] = (i/6)*4 + tmp.indices[i%6];
ibo->unmapData();
/* Create texcoord buffer */
tbo = shared_ptr<VertexData>(new BufferedVertexData(sizeof(Vec3) * 4 * max_particle_count,
sizeof(Vec3), GL_STATIC_DRAW, GL_ARRAY_BUFFER, NULL));
Vec3 * texcoords = (Vec3 *)tbo->mapData();
for (int i = 0; i < max_particle_count; i++) {
texcoords[i*4+0] = Vec3(0, 0, 0);
texcoords[i*4+1] = Vec3(1, 0, 0);
texcoords[i*4+2] = Vec3(1, 1, 0);
texcoords[i*4+3] = Vec3(0, 1, 0);
}
tbo->unmapData();
tbo->setAttribute("in_texcoord", VertexData::AttribProps(0, 2, GL_FLOAT));
/* Create position and colour buffer */
vbo_size = sizeof(VertexTemplate) * 4 * max_particle_count;
vbo = shared_ptr<VertexData>(new BufferedVertexData(vbo_size * getNumberOfOccurrences(),
sizeof(VertexTemplate), GL_STREAM_DRAW, GL_ARRAY_BUFFER, NULL));
vbo->setAttribute("in_position", VertexData::AttribProps(0, 3, GL_FLOAT));
vbo->setAttribute("in_color", VertexData::AttribProps(sizeof(Vec3), 4, GL_UNSIGNED_BYTE, GL_TRUE));
}
//! SceneSimulator::Updatable:: Updates VBO
void BillboardParticles::update(float dt)
{
this->particle_count = emitter->particle_count;
/* Set positions and colors */
vbo->resetSize(sizeof(VertexTemplate) * 4 * particle_count * getNumberOfOccurrences());
VertexTemplate * vbo_array = (VertexTemplate *)vbo->mapData();
unsigned ctr = 0;
for (SceneNode * node : getOriginList()) {
Mat4 cam_transform = Application::get().getScene().getCamera().getTransform() * node->getCachedTransformRef();
Vec3 up(cam_transform.a01, cam_transform.a11, cam_transform.a21);
Vec3 right(cam_transform.a00, cam_transform.a10, cam_transform.a20);
for (unsigned i = 0; i < particle_count; i++) {
unsigned index = (particle_count * ctr + i) * 4;
float size = emitter->properties_array[i].size;
Vec3 position = emitter->properties_array[i].position;
int color = to8BitVec4(emitter->properties_array[i].color);
//Vec4 color = emitter->properties_array[i].color;
vbo_array[index+0].color = color; vbo_array[index+0].position = (up * (-1) - right) * size + position;
vbo_array[index+1].color = color; vbo_array[index+1].position = (up - right) * size + position;
vbo_array[index+2].color = color; vbo_array[index+2].position = (up + right) * size + position;
vbo_array[index+3].color = color; vbo_array[index+3].position = (right - up) * size + position;
}
ctr++;
}
vbo->unmapData();
}
//! Drawable:: Called upon drawing
void BillboardParticles::preDraw(SceneRenderer & renderer)
{
renderer.useProgram("BillboardParticleShader.shader");
renderer.setDepthMask(false);
renderer.setBlend(true);
renderer.setBlendFunc(GL_SRC_ALPHA, GL_ONE);
renderer.useTexture(emitter->properties->texture);
renderer.getProgram().setVertexData(tbo.get());
current_node = 0;
}
//! Drawable:: Draw one occurrence
void BillboardParticles::drawOccurrence(SceneRenderer & renderer, SceneNode & node)
{
Mat4 model_view = node.getScene().getCamera().getTransform() * node.getCachedTransformRef();
Mat4 model_view_projection = node.getScene().getCamera().getProjection() * model_view;
renderer.getProgram().setParamMat4("model_view_projection_matrix", model_view_projection);
renderer.getProgram().setVertexData(vbo.get(), current_node * sizeof(VertexTemplate) * particle_count * 4);
renderer.drawElements(GL_TRIANGLE_STRIP, particle_count * 6, ibo);
current_node++;
}
//! Drawable:: Called after drawing
void BillboardParticles::postDraw(SceneRenderer & renderer)
{
renderer.setDepthMask(true);
renderer.setBlend(false);
renderer.getProgram().disableArrayPtr("in_position");
renderer.getProgram().disableArrayPtr("in_texcoord");
renderer.getProgram().disableArrayPtr("in_color");
}
} | 44.783333 | 126 | 0.598995 | Sudoka |
398a8aa8d2a685a8d41d5aacc5e7cf810d75073b | 8,341 | cpp | C++ | jit.gl.isf/jit.gl.isf/ISFFileManager_Win.cpp | mrRay/jit.gl.isf | 81553e0c48f6030fcd67e0df2a48d38f0d98ee90 | [
"MIT"
] | 19 | 2019-04-28T11:53:46.000Z | 2021-04-16T21:05:58.000Z | jit.gl.isf/jit.gl.isf/ISFFileManager_Win.cpp | mrRay/jit.gl.isf | 81553e0c48f6030fcd67e0df2a48d38f0d98ee90 | [
"MIT"
] | 6 | 2019-05-25T17:27:18.000Z | 2020-09-01T01:11:25.000Z | jit.gl.isf/jit.gl.isf/ISFFileManager_Win.cpp | mrRay/jit.gl.isf | 81553e0c48f6030fcd67e0df2a48d38f0d98ee90 | [
"MIT"
] | 1 | 2020-08-14T15:39:10.000Z | 2020-08-14T15:39:10.000Z | #include "ISFFileManager_Win.hpp"
#include "VVISF.hpp"
//#include <unistd.h>
#include <sys/types.h>
//#include <pwd.h>
#include <algorithm>
/*
#include "jit.common.h"
#include "jit.gl.h"
//#include "ext_mess.h"
*/
#include <filesystem>
using namespace std;
using namespace VVGL;
using namespace VVISF;
void ISFFileManager_Win::populateEntries() {
//post("%s",__func__);
//cout << __PRETTY_FUNCTION__ << endl;
lock_guard<recursive_mutex> lock(_lock);
_fileEntries.clear();
GLContext::bootstrapGLEnvironmentIfNecessary();
// make a global buffer pool. we're going to destroy it before this method exits, we just need the pool so the ISFDocs we're about to create don't throw exceptions b/c they're unable to load image resources to disk (b/c there's no buffer pool)
GLContextRef tmpCtx = CreateNewGLContextRef(NULL, AllocGL4ContextAttribs().get());
tmpCtx->makeCurrent();
CreateGlobalBufferPool(tmpCtx);
// add the built-in 'color bars' ISF
addBuiltInColorBarsISF();
// add the files in the global ISF library
//insertFilesFromDirectory(string("/ProgramData/ISF"), true);
// now add the files for the user-centric ISF library. this will overwrite any duplicate entries from the global lib.
// under windows, the global ISF repository is /ProgramData/ISF on the boot drive
const UINT maxPathLen = 300;
UINT tmpPathLen = 0;
TCHAR tmpPathBuf[maxPathLen];
// try to get the system directory
tmpPathLen = GetSystemDirectory(tmpPathBuf, maxPathLen);
std::filesystem::path rootPath;
if (tmpPathLen > 0) {
//wstring tmpWStr(tmpPathBuf);
//string tmpStr(tmpPathBuf, tmpPathLen);
//string tmpStr(tmpWStr.begin(), tmpWStr.end());
string tmpStr(tmpPathBuf);
std::filesystem::path tmpPath(tmpStr);
rootPath = tmpPath.root_path();
}
// else we couldn't get the system directory for some reason...
else {
// get the root path for the current directory, assume that's the boot drive
std::filesystem::path tmpPath = std::filesystem::current_path();
rootPath = tmpPath.root_path();
}
//cout << "root path is " << rootPath << endl;
std::filesystem::path isfDir = rootPath;
isfDir /= "ProgramData";
isfDir /= "ISF";
if (std::filesystem::exists(isfDir)) {
insertFilesFromDirectory(isfDir.string(), true);
}
/*
cout << "exists() = " << std::filesystem::exists(isfDir) << endl;
cout << "root_name() = " << isfDir.root_name() << endl;
cout << "root_path() = " << isfDir.root_path() << endl;
cout << "relative_path() = " << isfDir.relative_path() << endl;
cout << "parent_path() = " << isfDir.parent_path() << endl;
cout << "filename() = " << isfDir.filename() << endl;
cout << "stem() = " << isfDir.stem() << endl;
cout << "extension() = " << isfDir.extension() << endl;
cout << "************************" << endl;
// now add the default color bars ISF, so there's always at least one ISF loaded
//string filename = string("Default ColorBars");
string tmpPathStr("c:/ProgramData/ISF");
std::filesystem::path tmpPath(tmpPathStr);
cout << "exists() = " << std::filesystem::exists(tmpPath) << endl;
cout << "root_name() = " << tmpPath.root_name() << endl;
cout << "root_path() = " << tmpPath.root_path() << endl;
cout << "relative_path() = " << tmpPath.relative_path() << endl;
cout << "parent_path() = " << tmpPath.parent_path() << endl;
cout << "filename() = " << tmpPath.filename() << endl;
cout << "stem() = " << tmpPath.stem() << endl;
cout << "extension() = " << tmpPath.extension() << endl;
*/
// DON'T FORGET TO DESTROY THIS GLOBAL BUFFER POOL
SetGlobalBufferPool();
}
ISFFile ISFFileManager_Win::fileEntryForName(const string & inName) {
lock_guard<recursive_mutex> lock(_lock);
ISFFile returnMe = ISFFile(string(""), string(""), ISFFileType_None, string(""), vector<string>());
try {
returnMe = _fileEntries.at(inName);
}
catch (...) {
}
return returnMe;
}
vector<string> ISFFileManager_Win::fileNames() {
lock_guard<recursive_mutex> lock(_lock);
vector<string> returnMe;
returnMe.reserve(_fileEntries.size());
for (const auto & fileIt : _fileEntries) {
returnMe.push_back(fileIt.first);
}
return returnMe;
}
vector<string> ISFFileManager_Win::generatorNames() {
lock_guard<recursive_mutex> lock(_lock);
vector<string> returnMe;
returnMe.reserve(_fileEntries.size());
for (const auto & fileIt : _fileEntries) {
if ((fileIt.second.type() & ISFFileType_Source) == ISFFileType_Source)
returnMe.push_back(fileIt.first);
}
return returnMe;
}
vector<string> ISFFileManager_Win::filterNames() {
lock_guard<recursive_mutex> lock(_lock);
vector<string> returnMe;
returnMe.reserve(_fileEntries.size());
for (const auto & fileIt : _fileEntries) {
if ((fileIt.second.type() & ISFFileType_Filter) == ISFFileType_Filter)
returnMe.push_back(fileIt.first);
}
return returnMe;
}
vector<string> ISFFileManager_Win::transitionNames() {
lock_guard<recursive_mutex> lock(_lock);
vector<string> returnMe;
returnMe.reserve(_fileEntries.size());
for (const auto & fileIt : _fileEntries) {
if ((fileIt.second.type() & ISFFileType_Transition) == ISFFileType_Transition)
returnMe.push_back(fileIt.first);
}
return returnMe;
}
vector<string> ISFFileManager_Win::categories() {
//cout << __PRETTY_FUNCTION__ << endl;
lock_guard<recursive_mutex> lock(_lock);
vector<string> returnMe;
// iterate through all the entries in the map
for (const auto & fileIt : _fileEntries) {
//cout << "\tchecking file " << fileIt.first << ", its cats are: ";
// run through every cat in this entry's categories vector
for (const auto & fileCat : fileIt.second.categories()) {
//cout << fileCat << " ";
// if the vector we're returning doesn't contain this category yet, add it
if (find(returnMe.begin(), returnMe.end(), fileCat) == returnMe.end()) {
returnMe.push_back(fileCat);
}
}
//cout << endl;
}
return returnMe;
}
vector<string> ISFFileManager_Win::fileNamesForCategory(const string & inCategory) {
lock_guard<recursive_mutex> lock(_lock);
vector<string> returnMe;
// iterate through all the entries in the map
for (const auto & fileIt : _fileEntries) {
// run through every cat in this entry's categories
for (const auto & fileCat : fileIt.second.categories()) {
// if this category is a match for the passed category, add it
if (CaseInsensitiveCompare(fileCat, inCategory)) {
returnMe.push_back(fileIt.first);
break;
}
}
}
return returnMe;
}
void ISFFileManager_Win::insertFilesFromDirectory(const string & inDirRaw, const bool & inRecursive) {
//post("%s ... %s, %d",__func__,inDirRaw.c_str(),inRecursive);
//cout << __PRETTY_FUNCTION__ << "... " << inDirRaw << " : " << inRecursive << endl;
// some static strings to avoid churn
static string *_fsstr = nullptr;
static string *_fragstr = nullptr;
if (_fsstr == nullptr) {
_fsstr = new string(".fs");
_fragstr = new string(".frag");
}
filesystem::path inDir(inDirRaw);
for (const auto & tmpDirEntry : std::filesystem::directory_iterator(inDir)) {
string tmpExt = tmpDirEntry.path().extension().string();
//cout << "\ttmpDirEntry is " << tmpDirEntry.path() << ", ext is " << tmpExt << endl;
bool isDir = tmpDirEntry.is_directory();
if (!isDir && (CaseInsensitiveCompare(tmpExt, *_fsstr) || CaseInsensitiveCompare(tmpExt, *_fragstr))) {
ISFFile tmpFile = CreateISFFileFromPath(tmpDirEntry.path().string());
if (tmpFile.isValid()) {
_fileEntries[tmpFile.filename()] = tmpFile;
}
}
if (inRecursive && isDir) {
insertFilesFromDirectory(tmpDirEntry.path().string(), inRecursive);
}
}
}
ISFFile CreateISFFileFromPath(const string & inPath) {
//cout << __PRETTY_FUNCTION__ << "... " << inPath << endl;
string filename = StringByDeletingExtension(LastPathComponent(inPath));
string filepath = inPath;
//ISFFileType type;
//string description;
//vector<string> categories;
ISFDocRef doc = CreateISFDocRef(filepath, nullptr, false);
if (doc == nullptr) {
return ISFFile(string(""), string(""), ISFFileType_None, string(""), vector<string>());
}
//type = doc->type();
//description = doc->descripton();
//categories = doc->categories();
//return ISFFile(filename, filepath, type, description, categories);
return ISFFile(filename, filepath, doc->type(), doc->description(), doc->categories());
}
| 32.582031 | 245 | 0.687927 | mrRay |
39906832e9940940eb1e4d81e5ad9fd0bd6da26f | 172 | hpp | C++ | include/TextureManager.hpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | include/TextureManager.hpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | include/TextureManager.hpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | #ifndef TEXTURE_MANAGER_HPP_
#define TEXTURE_MANAGER_HPP_
#include <iostream>
#include <vector>
#include "stb/stb_image.h"
class TextureManager
{
private:
public:
};
#endif | 15.636364 | 28 | 0.796512 | Frostie314159 |
39906b9a591240b78755180ee0087bdcebf54ed5 | 1,647 | cpp | C++ | 018/4Sum.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | 1 | 2018-06-24T13:58:07.000Z | 2018-06-24T13:58:07.000Z | 018/4Sum.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | 018/4Sum.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<vector<int>> fourSum(vector<int>&nums, int target){
vector<vector<int>> total;
int n = nums.size();
if(n<4) return total;
sort(nums.begin(),nums.end());
for (int i=0;i<n-3;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;
if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;
for (int j = i+1;j<n-2;j++){
if(j>i+1&&nums[j]==nums[j-1]) continue;
if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;
if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target) continue;
int left = j+1, right = n-1;
while(left<right){
int sum = nums[i]+nums[j]+nums[left]+nums[right];
if(sum <target)
left++;
else if(sum>target)
right--;
else{
total.push_back(vector<int>{nums[i],nums[j],nums[left],nums[right]});
do{left++;}while(left<right&&nums[left]==nums[left-1]);
do{right--;}while(left<right&&nums[right]==nums[right+1]);
}
}
}
}
return total;
}
int main(){
vector<int>nums = {1, 0, -1, 0, -2, 2};
vector<vector<int>>res = fourSum(nums, 0);
for(int i = 0;i<res.size();i++){
for(int j = 0;j < res[0].size();j++)
cout<<res[i][j];
cout<<endl;
}
return 0;
}
| 35.804348 | 93 | 0.453552 | Lixu518 |
39990e6a9d4dd6137bf85bcf89a84be908e31afd | 5,553 | cpp | C++ | src/rrrobot_ws/src/rrrobot/src/rrrobot_node.cpp | EECS-467-W20-RRRobot-Project/RRRobot | f5bfccab3b96e1908a81a987d5fed51ae3b9c738 | [
"MIT"
] | 1 | 2020-04-10T21:19:03.000Z | 2020-04-10T21:19:03.000Z | src/rrrobot_ws/src/rrrobot/src/rrrobot_node.cpp | EECS-467-W20-RRRobot-Project/RRRobot | f5bfccab3b96e1908a81a987d5fed51ae3b9c738 | [
"MIT"
] | 9 | 2020-04-10T18:47:54.000Z | 2020-04-10T18:57:52.000Z | src/rrrobot_ws/src/rrrobot/src/rrrobot_node.cpp | EECS-467-W20-RRRobot-Project/RRRobot | f5bfccab3b96e1908a81a987d5fed51ae3b9c738 | [
"MIT"
] | null | null | null | // rrrobot_node.cpp
#include <algorithm>
#include <vector>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <iostream>
#include <ros/ros.h>
#include <osrf_gear/LogicalCameraImage.h>
#include <osrf_gear/Order.h>
#include <osrf_gear/Proximity.h>
#include <osrf_gear/VacuumGripperState.h>
#include <osrf_gear/ConveyorBeltControl.h>
#include <sensor_msgs/JointState.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/Range.h>
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <std_srvs/Trigger.h>
#include <trajectory_msgs/JointTrajectory.h>
#include "topic_names.h"
#include "rrrobot/arm_command.h"
using namespace std;
class Position
{
public:
float x, y, z;
Position(float x, float y, float z) : x(x), y(y), z(z){};
Position() : x(0), y(0), z(0) {}
};
class RRRobot
{
public:
RRRobot(ros::NodeHandle &node)
: current_robot_state(RobotState::WAITING_FOR_CLASSIFICATION | RobotState::WAITING_FOR_GRAB_LOCATION),
nh(node)
{
cv_classification_sub = nh.subscribe(CV_CLASSIFICATION_CHANNEL, 1000, &RRRobot::cv_classification_callback, this);
gripper_state_sub = nh.subscribe(GRIPPER_STATE_CHANNEL, 1000, &RRRobot::gripper_state_callback, this);
depth_camera_sub = nh.subscribe(DESIRED_GRASP_POSE_CHANNEL, 1000, &RRRobot::grasp_pose_callback, this);
conveyor_pub = nh.serviceClient<osrf_gear::ConveyorBeltControl>(CONVEYOR_POWER_CHANNEL);
arm_destination_pub = nh.advertise<rrrobot::arm_command>(ARM_DESTINATION_CHANNEL, 1000);
// start competition
ros::ServiceClient comp_start = nh.serviceClient<std_srvs::Trigger>(START_COMPETITION_CHANNEL);
std_srvs::Trigger trg;
comp_start.call(trg);
}
void cv_classification_callback(const std_msgs::String &classification)
{
std::string type = classification.data.substr(classification.data.find(":") + 1);
Position drop_point = destination(type);
desired_drop_pose.position.x = drop_point.x;
desired_drop_pose.position.y = drop_point.y;
desired_drop_pose.position.z = drop_point.z;
// update state
if (current_robot_state & RobotState::WAITING_FOR_GRAB_LOCATION)
{
current_robot_state &= ~RobotState::WAITING_FOR_CLASSIFICATION;
}
else if ((current_robot_state & RobotState::MOVING_ARM) == 0x0)
{
current_robot_state = RobotState::MOVING_ARM;
// tell the arm to move to grab the object
publish_arm_command();
}
// print_state();
}
void gripper_state_callback(const osrf_gear::VacuumGripperState &state)
{
if (state.attached)
{
current_robot_state = RobotState::MOVING_ARM;
if (!gripper_state.attached)
{
// start the conveyor belt again
set_conveyor(100);
}
}
// just dropped the object
else if (gripper_state.attached /* && !state.attached */)
{
current_robot_state = RobotState::WAITING_FOR_CLASSIFICATION | RobotState::WAITING_FOR_GRAB_LOCATION;
}
// store current state
gripper_state = state;
// print_state();
}
void grasp_pose_callback(const geometry_msgs::Pose &grasp_pose)
{
// stop conveyor belt
set_conveyor(0);
desired_grasp_pose = grasp_pose;
// Add z offset so end effector doesn't hit object
desired_grasp_pose.position.z += 0.01;
if (current_robot_state & RobotState::WAITING_FOR_CLASSIFICATION)
{
current_robot_state &= ~RobotState::WAITING_FOR_GRAB_LOCATION;
}
else if ((current_robot_state & RobotState::MOVING_ARM) == 0x0)
{
current_robot_state = RobotState::MOVING_ARM;
publish_arm_command();
}
// print_state();
}
private:
enum RobotState
{
WAITING_FOR_CLASSIFICATION = 0x1,
WAITING_FOR_GRAB_LOCATION = 0x1 << 1,
MOVING_ARM = 0x1 << 2
};
int current_robot_state;
osrf_gear::VacuumGripperState gripper_state;
geometry_msgs::Pose desired_grasp_pose;
geometry_msgs::Pose desired_drop_pose;
ros::NodeHandle nh;
ros::Subscriber cv_classification_sub;
ros::Subscriber gripper_state_sub; // know when item has been grabbed, so conveyor can be started
ros::Subscriber depth_camera_sub; // get desired grab location
ros::ServiceClient conveyor_pub;
ros::Publisher arm_destination_pub;
Position trash_bin = Position(-0.3, 0.383, 1);
Position recycle_bin = Position(-0.3, 1.15, 1);
// Determine item destination bin based on classification
Position destination(const std::string &type) const
{
Position pos;
if (type == "trash")
{
pos = trash_bin;
}
else
{
pos = recycle_bin;
}
return pos;
}
// Publish message including grab and drop off location for arm controller
void publish_arm_command()
{
rrrobot::arm_command cmd;
cmd.grab_location = desired_grasp_pose;
cmd.drop_location = desired_drop_pose;
arm_destination_pub.publish(cmd);
ros::spinOnce();
}
// Set conveyor power (0 or 50-100)
void set_conveyor(int power)
{
if (power != 0 && (power < 50 || power > 100))
{
return;
}
osrf_gear::ConveyorBeltControl cmd;
cmd.request.power = power;
conveyor_pub.call(cmd);
}
// Print current state for debugging
void print_state()
{
if (current_robot_state & RobotState::WAITING_FOR_CLASSIFICATION)
{
cout << "Waiting for classification\t";
}
if (current_robot_state & RobotState::WAITING_FOR_GRAB_LOCATION)
{
cout << "Waiting for grab location\t";
}
if (current_robot_state & RobotState::MOVING_ARM)
{
cout << "Moving Arm\t";
}
cout << endl;
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "rrrobot");
ros::NodeHandle node;
RRRobot robot(node);
ros::spin(); // This executes callbacks on new data until ctrl-c.
return 0;
}
| 24.355263 | 116 | 0.730956 | EECS-467-W20-RRRobot-Project |
399c99bd2be8831407f02b878cc0f7c6deb5856b | 4,738 | cpp | C++ | shirabeengine/shirabeengine/modules/vulkan_integration/code/source/resources/types/vulkanshadermoduleresource.cpp | BoneCrasher/ShirabeEngine | 39b3aa2c5173084d59b96b7f60c15207bff0ad04 | [
"MIT"
] | 5 | 2019-12-02T12:28:57.000Z | 2021-04-07T21:21:13.000Z | shirabeengine/shirabeengine/modules/vulkan_integration/code/source/resources/types/vulkanshadermoduleresource.cpp | BoneCrasher/ShirabeEngine | 39b3aa2c5173084d59b96b7f60c15207bff0ad04 | [
"MIT"
] | null | null | null | shirabeengine/shirabeengine/modules/vulkan_integration/code/source/resources/types/vulkanshadermoduleresource.cpp | BoneCrasher/ShirabeEngine | 39b3aa2c5173084d59b96b7f60c15207bff0ad04 | [
"MIT"
] | 1 | 2020-01-09T14:25:42.000Z | 2020-01-09T14:25:42.000Z | //
// Created by dottideveloper on 29.10.19.
//
#include <material/serialization.h>
#include "vulkan_integration/resources/types/vulkanshadermoduleresource.h"
#include "vulkan_integration/vulkandevicecapabilities.h"
namespace engine::vulkan
{
//<-----------------------------------------------------------------------------
//
//<-----------------------------------------------------------------------------
//<-----------------------------------------------------------------------------
//<-----------------------------------------------------------------------------
//
//<-----------------------------------------------------------------------------
CEngineResult<> CVulkanShaderModuleResource::create( SShaderModuleDescriptor const &aDescription
, SNoDependencies const &aDependencies
, GpuApiResourceDependencies_t const &aResolvedDependencies)
{
SHIRABE_UNUSED(aResolvedDependencies);
CVkApiResource<SShaderModule>::create(aDescription, aDependencies, aResolvedDependencies);
Shared<IVkGlobalContext> vkContext = getVkContext();
VkDevice device = vkContext->getLogicalDevice();
std::unordered_map<VkShaderStageFlags, VkShaderModule> vkShaderModules {};
for(auto const &[stage, dataAccessor] : aDescription.shaderStages)
{
if(not dataAccessor)
{
// If we don't have any data to access, then don't create a shader module.
continue;
}
ByteBuffer const data = dataAccessor();
// We need to convert from a regular 8-bit data buffer to uint32 words of SPIR-V.
// TODO: Refactor the asset system to permit loading 32-bit buffers...
std::vector<uint8_t> const &srcData = data.dataVector();
uint32_t const srcDataSize = srcData.size();
std::vector<uint32_t> convData {};
convData.resize( srcDataSize / 4 );
for(uint32_t k=0; k<srcDataSize; k += 4)
{
uint32_t const value = *reinterpret_cast<uint32_t const*>( srcData.data() + k );
convData[ k / 4 ] = value;
}
VkShaderModuleCreateInfo shaderModuleCreateInfo {};
shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shaderModuleCreateInfo.pNext = nullptr;
shaderModuleCreateInfo.flags = 0;
shaderModuleCreateInfo.pCode = convData.data();
shaderModuleCreateInfo.codeSize = srcData.size();
VkShaderModule vkShaderModule = VK_NULL_HANDLE;
VkResult const moduleCreationResult = vkCreateShaderModule(device, &shaderModuleCreateInfo, nullptr, &vkShaderModule);
if(VkResult::VK_SUCCESS != moduleCreationResult)
{
CLog::Error(logTag(), "Failed to create shader module for stage {}", stage);
continue;
}
vkShaderModules.insert({ stage, vkShaderModule });
}
this->handles = vkShaderModules;
return { EEngineStatus::Ok };
}
//<-----------------------------------------------------------------------------
//<-----------------------------------------------------------------------------
//
//<-----------------------------------------------------------------------------
CEngineResult<> CVulkanShaderModuleResource::load() const
{
return { EEngineStatus::Ok };
}
//<-----------------------------------------------------------------------------
//<-----------------------------------------------------------------------------
//
//<-----------------------------------------------------------------------------
CEngineResult<> CVulkanShaderModuleResource::unload() const
{
return { EEngineStatus::Ok };
}
//<-----------------------------------------------------------------------------
//<-----------------------------------------------------------------------------
//
//<-----------------------------------------------------------------------------
CEngineResult<> CVulkanShaderModuleResource::destroy()
{
VkDevice device = getVkContext()->getLogicalDevice();
for(auto const &[stage, module] : this->handles)
{
vkDestroyShaderModule(device, module, nullptr);
}
this->handles.clear();
return EEngineStatus::Ok;
}
//<-----------------------------------------------------------------------------
}
| 41.2 | 130 | 0.436471 | BoneCrasher |
399d5128af1add1705289fa1dbfa47b61822ea4c | 5,855 | cc | C++ | gazebo/physics/Atmosphere_TEST.cc | SamFerwerda/Gazebo10-commits | b33ac5982fb75cac894fa145f7268146d44e0724 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2018-07-17T00:17:13.000Z | 2020-05-26T08:39:25.000Z | gazebo/physics/Atmosphere_TEST.cc | SamFerwerda/Gazebo10-commits | b33ac5982fb75cac894fa145f7268146d44e0724 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-06-04T10:26:04.000Z | 2020-06-04T10:26:04.000Z | gazebo/physics/Atmosphere_TEST.cc | SamFerwerda/Gazebo10-commits | b33ac5982fb75cac894fa145f7268146d44e0724 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-11-10T07:19:09.000Z | 2019-11-21T19:11:11.000Z | /*
* Copyright (C) 2016 Open Source Robotics Foundation
*
* 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 "gazebo/test/ServerFixture.hh"
#include "gazebo/msgs/msgs.hh"
using namespace gazebo;
class AtmosphereTest : public ServerFixture,
public testing::WithParamInterface<const char*>
{
/// \brief Callback for gztopic "~/response".
/// \param[in] _msg Message received from topic.
public: void OnAtmosphereMsgResponse(ConstResponsePtr &_msg);
/// \brief Test getting/setting atmosphere model parameters.
/// \param[in] _atmosphere Name of the atmosphere model.
public: void AtmosphereParam(const std::string &_atmosphere);
/// \brief Test default atmosphere model parameters
/// \param[in] _atmosphere Name of the atmosphere model.
public: void AtmosphereParamBool(const std::string &_atmosphere);
/// \brief Incoming atmosphere message.
public: static msgs::Atmosphere atmospherePubMsg;
/// \brief Received atmosphere message.
public: static msgs::Atmosphere atmosphereResponseMsg;
};
msgs::Atmosphere AtmosphereTest::atmospherePubMsg;
msgs::Atmosphere AtmosphereTest::atmosphereResponseMsg;
/////////////////////////////////////////////////
void AtmosphereTest::OnAtmosphereMsgResponse(ConstResponsePtr &_msg)
{
if (_msg->type() == atmospherePubMsg.GetTypeName())
atmosphereResponseMsg.ParseFromString(_msg->serialized_data());
}
/////////////////////////////////////////////////
void AtmosphereTest::AtmosphereParam(const std::string &_atmosphere)
{
atmospherePubMsg.Clear();
atmosphereResponseMsg.Clear();
this->Load("worlds/empty.world", false);
physics::WorldPtr world = physics::get_world("default");
ASSERT_TRUE(world != NULL);
transport::NodePtr atmosphereNode;
atmosphereNode = transport::NodePtr(new transport::Node());
atmosphereNode->Init();
transport::PublisherPtr atmospherePub
= atmosphereNode->Advertise<msgs::Atmosphere>("~/atmosphere");
transport::PublisherPtr requestPub
= atmosphereNode->Advertise<msgs::Request>("~/request");
transport::SubscriberPtr responsePub = atmosphereNode->Subscribe("~/response",
&AtmosphereTest::OnAtmosphereMsgResponse, this);
ASSERT_EQ(_atmosphere, "adiabatic");
atmospherePubMsg.set_type(msgs::Atmosphere::ADIABATIC);
atmospherePubMsg.set_temperature(0.01);
atmospherePubMsg.set_pressure(500);
atmospherePubMsg.set_mass_density(174.18084087484144);
atmospherePub->Publish(atmospherePubMsg);
msgs::Request *requestMsg = msgs::CreateRequest("atmosphere_info", "");
requestPub->Publish(*requestMsg);
int waitCount = 0, maxWaitCount = 3000;
while (atmosphereResponseMsg.ByteSize() == 0 && ++waitCount < maxWaitCount)
common::Time::MSleep(10);
ASSERT_LT(waitCount, maxWaitCount);
EXPECT_DOUBLE_EQ(atmosphereResponseMsg.temperature(),
atmospherePubMsg.temperature());
EXPECT_DOUBLE_EQ(atmosphereResponseMsg.pressure(),
atmospherePubMsg.pressure());
EXPECT_DOUBLE_EQ(atmosphereResponseMsg.mass_density(),
atmospherePubMsg.mass_density());
// Test Atmosphere::[GS]etParam()
{
physics::Atmosphere &atmosphere = world->Atmosphere();
double temperature = atmosphere.Temperature();
EXPECT_DOUBLE_EQ(temperature, atmospherePubMsg.temperature());
}
// Test SetParam for non-implementation-specific parameters
physics::Atmosphere &atmosphere = world->Atmosphere();
double temperature = 0.02;
double pressure = 0.03;
double temperatureGradient = 0.05;
atmosphere.SetTemperature(temperature);
EXPECT_NEAR(atmosphere.Temperature(), temperature, 1e-6);
atmosphere.SetPressure(pressure);
EXPECT_NEAR(atmosphere.Pressure(), pressure, 1e-6);
atmosphere.SetTemperatureGradient(temperatureGradient);
EXPECT_NEAR(atmosphere.TemperatureGradient(), temperatureGradient, 1e-6);
atmosphereNode->Fini();
}
/////////////////////////////////////////////////
TEST_P(AtmosphereTest, AtmosphereParam)
{
AtmosphereParam(this->GetParam());
}
/////////////////////////////////////////////////
void AtmosphereTest::AtmosphereParamBool
(const std::string &_atmosphere)
{
Load("worlds/empty.world", false);
physics::WorldPtr world = physics::get_world("default");
ASSERT_TRUE(world != NULL);
physics::Atmosphere &atmosphere = world->Atmosphere();
// Test shared atmosphere model parameter(s)
EXPECT_NEAR(atmosphere.Temperature(), 288.15, 1e-6);
EXPECT_NEAR(atmosphere.MassDensity(), 1.2249782197913108, 1e-6);
EXPECT_NEAR(atmosphere.Pressure(), 101325, 1e-6);
EXPECT_NEAR(atmosphere.TemperatureGradient(), -0.0065, 1e-6);
EXPECT_EQ(atmosphere.Type(), _atmosphere);
// Test atmosphere model parameters at a given altitude
if (_atmosphere == "adiabatic")
{
double altitude = 1000;
EXPECT_NEAR(atmosphere.Temperature(altitude), 281.64999999999998, 1e-6);
EXPECT_NEAR(atmosphere.MassDensity(altitude), 1.1117154882870524, 1e-6);
EXPECT_NEAR(atmosphere.Pressure(altitude), 89882.063292207444, 1e-6);
}
}
/////////////////////////////////////////////////
TEST_P(AtmosphereTest, AtmosphereParamBool)
{
AtmosphereParamBool(this->GetParam());
}
INSTANTIATE_TEST_CASE_P(Atmospheres, AtmosphereTest,
::testing::Values("adiabatic"));
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 34.64497 | 80 | 0.713749 | SamFerwerda |
399db7b9cb01f3cad58f6479f2145cf6826b3046 | 14,799 | inl | C++ | include/UDRefl/details/Object.inl | zerger/UDRefl | 1a2f67a3d94f191d6eafd520359428ac3d579ab2 | [
"MIT"
] | null | null | null | include/UDRefl/details/Object.inl | zerger/UDRefl | 1a2f67a3d94f191d6eafd520359428ac3d579ab2 | [
"MIT"
] | null | null | null | include/UDRefl/details/Object.inl | zerger/UDRefl | 1a2f67a3d94f191d6eafd520359428ac3d579ab2 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
namespace Ubpa::UDRefl {
//
// ObjectPtrBase
//////////////////
template<typename... Args>
InvocableResult ObjectPtrBase::IsInvocable(StrID methodID) const noexcept {
std::array argTypeIDs = { TypeID::of<Args>... };
return IsInvocable(ID, methodID, Span<const TypeID>{argTypeIDs});
}
template<typename T>
T ObjectPtrBase::InvokeRet(StrID methodID, Span<const TypeID> argTypeIDs, void* args_buffer) const {
using U = std::conditional_t<std::is_reference_v<T>, std::add_pointer_t<T>, T>;
std::uint8_t result_buffer[sizeof(U)];
auto result = Invoke(methodID, result_buffer, argTypeIDs, args_buffer);
assert(result.resultID == TypeID::of<T>);
return result.Move<T>(result_buffer);
}
template<typename... Args>
InvokeResult ObjectPtrBase::InvokeArgs(StrID methodID, void* result_buffer, Args... args) const {
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { TypeID::of<Args>... };
std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... };
return Invoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), result_buffer);
}
else
return Invoke(methodID, {}, nullptr, result_buffer);
}
template<typename T, typename... Args>
T ObjectPtrBase::Invoke(StrID methodID, Args... args) const {
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { TypeID::of<Args>... };
std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... };
return InvokeRet<T>(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()));
}
else
return InvokeRet<T>(methodID);
}
template<typename... Args>
SharedObject ObjectPtrBase::MInvoke(
StrID methodID,
std::pmr::memory_resource* rst_rsrc,
Args... args) const
{
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { TypeID::of<Args>... };
std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... };
return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc);
}
else
return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc);
}
template<typename... Args>
SharedObject ObjectPtrBase::DMInvoke(
StrID methodID,
Args... args) const
{
return MInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...);
}
template<typename... Args>
SharedObject ObjectPtrBase::AMInvoke(
StrID methodID,
std::pmr::memory_resource* rst_rsrc,
Args... args) const
{
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { ArgID<Args>(std::forward<Args>(args))... };
std::array args_buffer{ reinterpret_cast<std::size_t>(ArgPtr(args))... };
return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc);
}
else
return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc);
}
template<typename... Args>
SharedObject ObjectPtrBase::ADMInvoke(
StrID methodID,
Args... args) const
{
return AMInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...);
}
//
// ObjectPtr
//////////////
template<typename... Args>
InvocableResult ObjectPtr::IsInvocable(StrID methodID) const noexcept {
std::array argTypeIDs = { TypeID::of<Args>... };
return IsInvocable(ID, methodID, Span<const TypeID>{argTypeIDs});
}
template<typename T>
T ObjectPtr::InvokeRet(StrID methodID, Span<const TypeID> argTypeIDs, void* args_buffer) const {\
if constexpr (!std::is_void_v<T>) {
using U = std::conditional_t<std::is_reference_v<T>, std::add_pointer_t<T>, T>;
std::uint8_t result_buffer[sizeof(U)];
auto result = Invoke(methodID, result_buffer, argTypeIDs, args_buffer);
assert(result.resultID == TypeID::of<T>);
return result.Move<T>(result_buffer);
}
else
Invoke(methodID, nullptr, argTypeIDs, args_buffer);
}
template<typename... Args>
InvokeResult ObjectPtr::InvokeArgs(StrID methodID, void* result_buffer, Args... args) const {
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { TypeID::of<Args>... };
std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... };
return Invoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), result_buffer);
}
else
return Invoke(methodID, {}, nullptr, result_buffer);
}
template<typename T, typename... Args>
T ObjectPtr::Invoke(StrID methodID, Args... args) const {
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { TypeID::of<Args>... };
std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... };
return InvokeRet<T>(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()));
}
else
return InvokeRet<T>(methodID);
}
template<typename... Args>
SharedObject ObjectPtr::MInvoke(
StrID methodID,
std::pmr::memory_resource* rst_rsrc,
Args... args) const
{
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { TypeID::of<Args>... };
std::array args_buffer{ reinterpret_cast<std::size_t>(&args)... };
return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc);
}
else
return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc);
}
template<typename... Args>
SharedObject ObjectPtr::DMInvoke(
StrID methodID,
Args... args) const
{
return MInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...);
}
template<typename... Args>
SharedObject ObjectPtr::AMInvoke(
StrID methodID,
std::pmr::memory_resource* rst_rsrc,
Args... args) const
{
if constexpr (sizeof...(Args) > 0) {
static_assert(!((std::is_const_v<Args> || std::is_volatile_v<Args>) || ...));
std::array argTypeIDs = { ArgID<Args>(std::forward<Args>(args))... };
std::array args_buffer{ reinterpret_cast<std::size_t>(ArgPtr(args))... };
return MInvoke(methodID, Span<const TypeID>{ argTypeIDs }, static_cast<void*>(args_buffer.data()), rst_rsrc);
}
else
return MInvoke(methodID, Span<const TypeID>{}, static_cast<void*>(nullptr), rst_rsrc);
}
template<typename... Args>
SharedObject ObjectPtr::ADMInvoke(
StrID methodID,
Args... args) const
{
return AMInvoke<Args...>(methodID, std::pmr::get_default_resource(), std::forward<Args>(args)...);
}
}
template<>
struct std::hash<Ubpa::UDRefl::ObjectPtr> {
std::size_t operator()(const Ubpa::UDRefl::ObjectPtr& obj) const noexcept {
return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr());
}
};
template<>
struct std::hash<Ubpa::UDRefl::ConstObjectPtr> {
std::size_t operator()(const Ubpa::UDRefl::ConstObjectPtr& obj) const noexcept {
return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr());
}
};
template<>
struct std::hash<Ubpa::UDRefl::SharedObject> {
std::size_t operator()(const Ubpa::UDRefl::SharedObject& obj) const noexcept {
return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr());
}
};
template<>
struct std::hash<Ubpa::UDRefl::SharedConstObject> {
std::size_t operator()(const Ubpa::UDRefl::SharedConstObject& obj) const noexcept {
return obj.GetID().GetValue() ^ std::hash<const void*>()(obj.GetPtr());
}
};
namespace std {
inline void swap(Ubpa::UDRefl::SharedObject& left, Ubpa::UDRefl::SharedObject& right) noexcept {
left.Swap(right);
}
inline void swap(Ubpa::UDRefl::SharedConstObject& left, Ubpa::UDRefl::SharedConstObject& right) noexcept {
left.Swap(right);
}
}
template<typename T>
struct Ubpa::UDRefl::IsObjectOrPtr {
private:
using U = std::remove_cv_t<T>;
public:
static constexpr bool value =
std::is_same_v<T, ObjectPtr>
|| std::is_same_v<T, ConstObjectPtr>
|| std::is_same_v<T, SharedObject>
|| std::is_same_v<T, SharedConstObject>;
};
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator==(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) == Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator!=(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) != Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) < Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) > Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<=(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) <= Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>=(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) >= Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
T& operator<<(T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
return ptr >> lhs;
}
//template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
//Ubpa::UDRefl::SharedObject operator>>(const T& lhs, Ubpa::UDRefl::ConstObjectPtr ptr) {
// return ptr << lhs;
//}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator==(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) == ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator!=(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) != ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) < ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) > ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<=(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) <= ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>=(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return Ubpa::UDRefl::Ptr(lhs) >= ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
T& operator<<(T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return ptr >> lhs;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
Ubpa::UDRefl::SharedObject operator>>(const T& lhs, Ubpa::UDRefl::ObjectPtr ptr) {
return ptr << lhs;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator==(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) == Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator!=(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) != Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) < Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) > Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<=(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) <= Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>=(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) >= Ubpa::UDRefl::ConstCast(ptr);
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
T& operator<<(T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
return ptr >> lhs;
}
//template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
//Ubpa::UDRefl::SharedObject operator>>(const T& lhs, const Ubpa::UDRefl::SharedConstObject& ptr) {
// return ptr << lhs;
//}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator==(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) == ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator!=(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) != ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) < ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) > ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator<=(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) <= ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
bool operator>=(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return Ubpa::UDRefl::Ptr(lhs) >= ptr;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
T& operator<<(T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return ptr >> lhs;
}
template<typename T, std::enable_if_t<!Ubpa::UDRefl::IsObjectOrPtr_v<T>, int> = 0>
Ubpa::UDRefl::SharedObject operator>>(const T& lhs, const Ubpa::UDRefl::SharedObject& ptr) {
return ptr << lhs;
}
| 36.905237 | 116 | 0.693493 | zerger |
39a22d72475d40fe80590b67e8c7068a5926cedf | 821 | cpp | C++ | HackerRank/Challenges/compare-the-triplets.cpp | Diggzinc/solutions-spoj | eb552311011e466039e059cce07894fea0817613 | [
"MIT"
] | null | null | null | HackerRank/Challenges/compare-the-triplets.cpp | Diggzinc/solutions-spoj | eb552311011e466039e059cce07894fea0817613 | [
"MIT"
] | null | null | null | HackerRank/Challenges/compare-the-triplets.cpp | Diggzinc/solutions-spoj | eb552311011e466039e059cce07894fea0817613 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
void addIf(vector<int> &results, int a, int b)
{
if (a > b)
{
results[0]++;
}
else if (a < b)
{
results[1]++;
}
}
vector<int> solve(int a0, int a1, int a2, int b0, int b1, int b2)
{
vector<int> results = vector<int>(2, 0);
addIf(results, a0, b0);
addIf(results, a1, b1);
addIf(results, a2, b2);
return results;
}
int main()
{
int a0;
int a1;
int a2;
cin >> a0 >> a1 >> a2;
int b0;
int b1;
int b2;
cin >> b0 >> b1 >> b2;
vector<int> result = solve(a0, a1, a2, b0, b1, b2);
for (ssize_t i = 0; i < result.size(); i++)
{
cout << result[i] << (i != result.size() - 1 ? " " : "");
}
cout << endl;
return EXIT_SUCCESS;
} | 17.847826 | 65 | 0.501827 | Diggzinc |
39a5cab860d715ba666ff4c97e096f82308098f1 | 5,307 | cpp | C++ | Bebop2cpp-master/SNAP/SNAP_rudi.cpp | jmenden1/SNAP | a253aa052e4568cdc35e7ff5789b3e716ccbb4da | [
"MIT"
] | null | null | null | Bebop2cpp-master/SNAP/SNAP_rudi.cpp | jmenden1/SNAP | a253aa052e4568cdc35e7ff5789b3e716ccbb4da | [
"MIT"
] | null | null | null | Bebop2cpp-master/SNAP/SNAP_rudi.cpp | jmenden1/SNAP | a253aa052e4568cdc35e7ff5789b3e716ccbb4da | [
"MIT"
] | null | null | null | #include <vector>
#include "Drone.h"
#include <math.h>
#include <boost/asio/io_service.hpp>
#include <Fullnavdata.h>
#include <gnuplot_iostream.h>
#include <deque>
#include <fstream>
#include <iostream>
#include <sstream>
/*
* PRIVATE HEADER
*/
#define DRONE_IP "192.168.42.1"
#define DRONE_MAX_ALTITUDE 1.0
#define DRONE_MAX_HORIZONTAL_SPEED 0.3
#define DRONE_MAX_VERTICAL_SPEED 0.3
#define LAND_AFTER_LAST_WAYPOINT true
#define CALIBRATION_FILE "res/calib_bd2.xml"
#define HULLPROTECTIONON true
#define LOOK_FOR_CHESSBOARD false
#define MAX_COORD 10000000
using namespace std;
void ReadyToReadScan();
void ReadScanFile(string fn);
double * CheckSmallestCoord(double x, double y, int check_x_or_y, double current_min[], int negative);
/* TODO: Need to uncomment drone code if trying to use drone;
currently just trying to make a droneless code */
//Drone bebop;
/* Signal catches; if a process dies, we need drone to emergency stop */
/*
void kill_handler (int junk)
{
signal(SIGINT, kill_handler);
cout << endl << "AHHHHHHHHHHHH, WHAT ARE YOU DOING" << endl;
bebop.emergency();
exit(1);
}
*/
int main(int argc, char *argv[]) {
cout << argc << endl;
if( argc != 2 )
{
//need to put the file name of where the scans will go;
// this assumes all scans will go to the same file
cout << "PUT IN A FILE NAME, FOOL!" << endl;
exit(0);
}
/* SETUP FOR DONE */
/* signal(SIGINT, kill_handler);
bebop.connect();
while(!bebop.isRunning()){ sleep(1); }
bebop.setMaxAltitude(DRONE_MAX_ALTITUDE);
bebop.setMaxHorizontalSpeed(DRONE_MAX_HORIZONTAL_SPEED);
bebop.setMaxVerticalSpeed(DRONE_MAX_VERTICAL_SPEED);
if(bebop.blockingFlatTrim())
{
std::cout << "FLAT TRIM IS OK" << std::endl;
}
else
{
std::cerr << "FLAT TRIM NOT OK" << std::endl;
return 1;
}
*/ /*END SETUP*/
/*
This is very rudimentary; the drone cannot currently fly with
everything on it.
*/
string file_name = argv[1];
bool getting_info_loop = true;
while(getting_info_loop)
{
ReadyToReadScan();
ReadScanFile(file_name);
}
exit(0);
}
/*
This just makes sure the user is
*/
void ReadyToReadScan()
{
char scan_ready;
cout << "Ready for next scan (y for yes; e for exit)" << endl;
bool scan_ready_loop = true;
while(scan_ready_loop)
{
cin >> scan_ready;
switch(scan_ready)
{
case 'y':
scan_ready_loop = false;
break;
case 'e':
exit(0);
break;
default:
cout << "FOOL, DO NOT TEST ME!" << endl;
}
}
}
void ReadScanFile(string fn)
{
ifstream fin;
double x_info;
double y_info;
double z_info;
/*
double smallest_forward_x[2] = {MAX_COORD, MAX_COORD};
double smallest_backward_x[2] = {MAX_COORD, MAX_COORD};
double smallest_left_y[2] = {MAX_COORD, MAX_COORD};
double smallest_right_y[2] = {MAX_COORD, MAX_COORD};
*/
double *smallest_forward_x = NULL;
double *smallest_backward_x = NULL;
double *smallest_left_y = NULL;
double *smallest_right_y = NULL;
string info_line;
fin.open(fn);
//the first line is the "NODE" line, which should be discarded here
getline(fin, info_line);
//getting each x and y pair of data
while( getline(fin, info_line) )
{
cout << info_line << endl;
istringstream iss(info_line);
iss >> x_info;
iss >> y_info;
iss >> z_info;
if( x_info < 0)
{
smallest_backward_x = CheckSmallestCoord(x_info, y_info, 0, smallest_backward_x, 1);
}
if( x_info >= 0 )
{
smallest_forward_x = CheckSmallestCoord(x_info, y_info, 0, smallest_forward_x, 0);
}
//TODO: THIS MIGHT BE BACKWARDS, need to check!!!!!!!!!!!!!!!!!!!!
if( y_info < 0 )
{
smallest_left_y = CheckSmallestCoord(x_info, y_info, 1, smallest_left_y, 1);
}
if( y_info >= 0 )
{
smallest_right_y = CheckSmallestCoord(x_info, y_info, 1, smallest_right_y, 0);
}
}
cout << "SBX: " << smallest_backward_x[0] << " " << smallest_backward_x[1] << endl;
cout << "SFX: " << smallest_forward_x[0] << " " << smallest_forward_x[1] << endl;
cout << "SLY: " << smallest_left_y[0] << " " << smallest_left_y[1] << endl;
cout << "SRY: " << smallest_right_y[0] << " " << smallest_right_y[1] << endl;
fin.close();
}
/*
check_x_or_y means which index it should be checking in the array:
0 for x, 1 for y
*/
double * CheckSmallestCoord(double x, double y, int check_x_or_y, double current_min[], int negative)
{
double * new_min_array = new double[2];
//if it is the first loop, need to set the min to current point
if( current_min == NULL )
{
new_min_array[0] = x;
new_min_array[1] = y;
return new_min_array;
}
double check_min = current_min[check_x_or_y];
new_min_array[0] = current_min[0];
new_min_array[1] = current_min[1];
//checking x
if( check_x_or_y == 0 )
{
if( check_min > x && negative == 0)
{
new_min_array[0] = x;
new_min_array[1] = y;
}
else if( check_min < x && negative == 1)
{
new_min_array[0] = x;
new_min_array[1] = y;
}
}
//checking y
if( check_x_or_y == 1 )
{
if( check_min > y && negative == 0 )
{
new_min_array[0] = x;
new_min_array[1] = y;
}
else if( check_min < y && negative == 1)
{
new_min_array[0] = x;
new_min_array[1] = y;
}
}
delete[] current_min;
return new_min_array;
}
| 21.313253 | 102 | 0.655172 | jmenden1 |
39b190ab03896db9404c35ee98c9abbbe5ec8e95 | 1,898 | cpp | C++ | od/audio/SampleSaver.cpp | bapch/er-301 | e652eb9253009897747b0de7cfc57a27ac0cde1a | [
"MIT"
] | 1 | 2021-06-29T19:26:35.000Z | 2021-06-29T19:26:35.000Z | od/audio/SampleSaver.cpp | bapch/er-301 | e652eb9253009897747b0de7cfc57a27ac0cde1a | [
"MIT"
] | 1 | 2021-04-28T07:54:41.000Z | 2021-04-28T07:54:41.000Z | od/audio/SampleSaver.cpp | bapch/er-301 | e652eb9253009897747b0de7cfc57a27ac0cde1a | [
"MIT"
] | 1 | 2021-03-02T21:32:52.000Z | 2021-03-02T21:32:52.000Z | /*
* SampleSaver.cpp
*
* Created on: 24 Oct 2016
* Author: clarkson
*/
#include <od/audio/SampleSaver.h>
#include <od/audio/WavFileWriter.h>
namespace od
{
SampleSaver::SampleSaver()
{
}
SampleSaver::~SampleSaver()
{
}
bool SampleSaver::set(Sample *sample, const char *filename)
{
if (mStatus == STATUS_WORKING || sample == 0 || filename == 0)
return false;
mpSample = sample;
mpSample->attach();
mFilename = filename;
mStatus = STATUS_WORKING;
return true;
}
void SampleSaver::work()
{
if (mpSample)
{
mStatus = save();
mpSample->release();
mpSample = NULL;
}
}
int SampleSaver::save()
{
WavFileWriter writer(mpSample->mSampleRate, mpSample->mChannelCount,
wavFloat);
uint32_t sw;
float *buffer = mpSample->mpData;
if (buffer == NULL)
{
return STATUS_SAMPLE_NOT_PREPARED;
}
mPercentDone = 0.0f;
mSamplesWritten = 0;
if (!writer.open(mFilename))
{
return STATUS_ERROR_OPENING_FILE;
}
mSamplesRemaining = mpSample->mSampleCount;
while (mSamplesRemaining)
{
if (mCancelRequested)
{
return STATUS_CANCELED;
}
if (mSamplesRemaining < mSamplesPerBlock)
sw = mSamplesRemaining;
else
sw = mSamplesPerBlock;
if (writer.writeSamples(buffer, sw) != sw)
{
return STATUS_ERROR_WRITING_FILE;
}
else
{
buffer += sw * mpSample->mChannelCount;
mSamplesWritten += sw;
mSamplesRemaining -= sw;
if (mpSample->mSampleCount < mSamplesPerBlock)
{
mPercentDone = 100.0f;
}
else
{
mPercentDone = 100.0f * (float)(mSamplesWritten / mSamplesPerBlock) / (float)(mpSample->mSampleCount / mSamplesPerBlock);
}
}
}
mpSample->mDirty = false;
writer.close();
return STATUS_FINISHED;
}
} /* namespace od */
| 18.427184 | 127 | 0.611697 | bapch |
39b3080d167cecd1cf34fe5bdca3aea61bbf180c | 1,991 | hpp | C++ | ThreadPool.hpp | Linsexy/thread-pool | 0e9667c8c95fefc65054d8022c1a736aebf330d5 | [
"MIT"
] | null | null | null | ThreadPool.hpp | Linsexy/thread-pool | 0e9667c8c95fefc65054d8022c1a736aebf330d5 | [
"MIT"
] | 1 | 2018-03-27T19:43:26.000Z | 2018-03-28T14:04:40.000Z | ThreadPool.hpp | Linsexy/thread-pool | 0e9667c8c95fefc65054d8022c1a736aebf330d5 | [
"MIT"
] | null | null | null | //
// Created by benito on 3/25/18.
//
#ifndef THREAD_POOL_THREADPOOL_HPP
#define THREAD_POOL_THREADPOOL_HPP
/* Written for the Arfang Engine
*
* https://github.com/Linsexy/arfang-engine
*
*/
#include <array>
#include <vector>
#include <functional>
#include <list>
#include <future>
#include <queue>
#include <iostream>
#include "Thread.hpp"
namespace Af
{
class ThreadPool
{
public:
ThreadPool(int, Thread::DestroyBehavior behavior=Thread::DestroyBehavior::DETACH);
~ThreadPool();
ThreadPool(ThreadPool&&) = default;
ThreadPool(ThreadPool const&) = delete;
template <typename Func, typename... Args>
auto runAsyncTask(Func&& toCall, Args&&... args)
{
using RetType = typename std::result_of<Func(Args...)>::type;
std::promise<RetType> promise;
auto ret = promise.get_future();
auto task = std::make_unique<Thread::Task<RetType, Func, Args...>>(std::move(promise),
std::forward<Func>(toCall),
std::forward<Args>(args)...);
// std::cout << "threadpool acquiring mutex" << std::endl;
std::unique_lock lk(*_mut);
_tasks.emplace(std::move(task));
lk.unlock();
_cond->notify_one();
return std::move(ret);
}
void finishTasks() noexcept;
class Error : public std::runtime_error
{
public:
Error(const std::string& err) : std::runtime_error(err) {}
};
private:
Thread::DestroyBehavior _behavior;
std::shared_ptr<std::condition_variable> _cond;
std::shared_ptr<std::mutex> _mut;
std::queue<std::unique_ptr<Thread::ITask>> _tasks;
std::vector<Thread> _threads;
};
}
#endif //THREAD_POOL_THREADPOOL_HPP
| 27.273973 | 108 | 0.549975 | Linsexy |
39c13e97f233560c6fdf20a9c88db6c3884accb5 | 758 | cpp | C++ | Win32/GroupBox.cpp | soncfe/Win32GUI | c7bf6f24f2d4a66456c701017005e58f75a57c3c | [
"Unlicense"
] | 36 | 2020-03-29T19:23:00.000Z | 2022-03-28T22:07:11.000Z | Win32/GroupBox.cpp | soncfe/Win32GUI | c7bf6f24f2d4a66456c701017005e58f75a57c3c | [
"Unlicense"
] | 7 | 2020-08-01T13:35:16.000Z | 2022-01-27T00:43:44.000Z | Win32/GroupBox.cpp | soncfe/Win32GUI | c7bf6f24f2d4a66456c701017005e58f75a57c3c | [
"Unlicense"
] | 10 | 2020-04-07T15:55:44.000Z | 2021-12-16T20:25:12.000Z | #include "GroupBox.h"
GroupBox::GroupBox()
{
}
GroupBox::GroupBox(Control* parent, std::string name, RECT rect)
: Control(parent, name, rect.right, rect.bottom)
{
cmnControlInit(ICC_STANDARD_CLASSES);
setLocation(rect.left, rect.top);
mStyle = WS_CHILD | WS_VISIBLE | BS_GROUPBOX | BS_NOTIFY;
mType = WC_BUTTON;
create();
}
GroupBox::GroupBox(Control* parent, std::string name, int width, int height)
: Control(parent, name, width, height)
{
cmnControlInit(ICC_STANDARD_CLASSES);
mStyle = WS_CHILD | WS_VISIBLE | BS_GROUPBOX | BS_NOTIFY;
mType = WC_BUTTON;
create();
}
LRESULT GroupBox::drawctl(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
SetBkMode((HDC)wParam, TRANSPARENT);
SetTextColor((HDC)wParam, mFtColor);
return (LRESULT)mBkBrush;
}
| 23.6875 | 76 | 0.738786 | soncfe |
39c7bed1fe699371925ee5a737b47ce59df42389 | 156 | cpp | C++ | chapter04/4.6_The_Member_Access_Operators .cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | 9 | 2019-05-10T05:39:21.000Z | 2022-02-22T08:04:52.000Z | chapter04/4.6_The_Member_Access_Operators .cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | null | null | null | chapter04/4.6_The_Member_Access_Operators .cpp | NorthFacing/step-by-c | bc0e4f0c0fe45042ae367a28a87d03b5c3c787e3 | [
"MIT"
] | 6 | 2019-05-13T13:39:19.000Z | 2022-02-22T08:05:01.000Z | /**
* 4.6 成员访问运算符
* @Author Bob
* @Eamil 0haizhu0@gmail.com
* @Date 2017/7/28
*/
int main(){
/**
* p->size(); 等价于 (*p).size()
*/
return 0;
}
| 12 | 31 | 0.49359 | NorthFacing |
39ca362c7922dde9d34d3c17724aa77e6c4c43ce | 652 | hpp | C++ | Sources/Physics/Colliders/ColliderSphere.hpp | dreadris/Acid | 1af276edce8e6481c44d475633bf69266e16ed87 | [
"MIT"
] | null | null | null | Sources/Physics/Colliders/ColliderSphere.hpp | dreadris/Acid | 1af276edce8e6481c44d475633bf69266e16ed87 | [
"MIT"
] | null | null | null | Sources/Physics/Colliders/ColliderSphere.hpp | dreadris/Acid | 1af276edce8e6481c44d475633bf69266e16ed87 | [
"MIT"
] | null | null | null | #pragma once
#include "Collider.hpp"
class btSphereShape;
namespace acid {
class ACID_EXPORT ColliderSphere : public Collider::Registrar<ColliderSphere> {
public:
explicit ColliderSphere(float radius = 0.5f, const Transform &localTransform = {});
~ColliderSphere();
btCollisionShape *GetCollisionShape() const override;
float GetRadius() const { return m_radius; }
void SetRadius(float radius);
friend const Node &operator>>(const Node &node, ColliderSphere &collider);
friend Node &operator<<(Node &node, const ColliderSphere &collider);
private:
static bool registered;
std::unique_ptr<btSphereShape> m_shape;
float m_radius;
};
}
| 22.482759 | 84 | 0.76227 | dreadris |
39ca7ec225ef050296a50f9a169889b1a73db298 | 3,314 | hpp | C++ | tests/data.hpp | ChrisAHolland/constexpr-sql | 3ea390a3f8a5d0e1dcb9b5f187121d4649e5f9c3 | [
"MIT"
] | 121 | 2020-04-21T13:21:55.000Z | 2021-11-15T09:48:47.000Z | tests/data.hpp | ChrisAHolland/constexpr-sql | 3ea390a3f8a5d0e1dcb9b5f187121d4649e5f9c3 | [
"MIT"
] | 3 | 2020-04-23T05:29:54.000Z | 2021-07-18T18:37:57.000Z | tests/data.hpp | ChrisAHolland/constexpr-sql | 3ea390a3f8a5d0e1dcb9b5f187121d4649e5f9c3 | [
"MIT"
] | 5 | 2020-04-23T05:01:02.000Z | 2022-02-21T21:00:30.000Z | #pragma once
#include <string>
#include <type_traits>
#include "sql.hpp"
using books =
sql::schema<
"books", sql::index<>,
#ifdef CROSS
sql::column<"book", std::string>,
#else
sql::column<"title", std::string>,
#endif
sql::column<"genre", std::string>,
sql::column<"year", unsigned>,
sql::column<"pages", unsigned>
>;
using stories =
sql::schema<
"stories", sql::index<>,
#ifdef CROSS
sql::column<"story", std::string>,
#else
sql::column<"title", std::string>,
#endif
sql::column<"genre", std::string>,
sql::column<"year", unsigned>
>;
using authored =
sql::schema<
"authored", sql::index<>,
sql::column<"title", std::string>,
sql::column<"name", std::string>
>;
using collected =
sql::schema<
"collected", sql::index<>,
sql::column<"title", std::string>,
sql::column<"collection", std::string>,
sql::column<"pages", unsigned>
>;
const std::string data_folder{ "./data/" };
const std::string perf_folder{ "../data/" };
const std::string books_data{ "books.tsv" };
const std::string stories_data{ "stories.tsv" };
const std::string authored_data{ "authored.tsv" };
const std::string collected_data{ "collected.tsv" };
using books_row = std::tuple<std::string, std::string, int, int>;
using books_type = std::vector<books_row>;
using stories_row = std::tuple<std::string, std::string, int>;
using stories_type = std::vector<stories_row>;
using authored_row = std::tuple<std::string, std::string>;
using authored_type = std::vector<authored_row>;
using collected_row = std::tuple<std::string, std::string, int>;
using collected_type = std::vector<collected_row>;
constexpr std::size_t iters{ 65536 };
constexpr std::size_t offset{ 512 };
template <char Delim>
books_type books_load()
{
auto file{ std::fstream(perf_folder + books_data) };
books_type table{};
while (file)
{
books_row row{};
std::getline(file, std::get<0>(row), Delim);
std::getline(file, std::get<1>(row), Delim);
file >> std::get<2>(row);
file >> std::get<3>(row);
table.push_back(std::move(row));
if (file.get() != '\n')
{
file.unget();
}
}
return table;
}
template <char Delim>
stories_type stories_load()
{
auto file{ std::fstream(perf_folder + stories_data) };
stories_type table{};
while (file)
{
stories_row row{};
std::getline(file, std::get<0>(row), Delim);
std::getline(file, std::get<1>(row), Delim);
file >> std::get<2>(row);
table.push_back(std::move(row));
if (file.get() != '\n')
{
file.unget();
}
}
return table;
}
template <char Delim>
authored_type authored_load()
{
auto file{ std::fstream(perf_folder + authored_data) };
authored_type table{};
while (file)
{
authored_row row{};
std::getline(file, std::get<0>(row), Delim);
std::getline(file, std::get<1>(row), Delim);
table.push_back(std::move(row));
if (file.get() != '\n')
{
file.unget();
}
}
return table;
}
template <char Delim>
collected_type collected_load()
{
auto file{ std::fstream(perf_folder + collected_data) };
collected_type table{};
while (file)
{
collected_row row{};
std::getline(file, std::get<0>(row), Delim);
std::getline(file, std::get<1>(row), Delim);
file >> std::get<2>(row);
table.push_back(std::move(row));
if (file.get() != '\n')
{
file.unget();
}
}
return table;
}
| 20.45679 | 65 | 0.646952 | ChrisAHolland |
39cadcd1cc8192bf943bc237abdaabb52e2fa9fe | 1,578 | hpp | C++ | include/DREAM/ConvergenceChecker.hpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 12 | 2020-09-07T11:19:10.000Z | 2022-02-17T17:40:19.000Z | include/DREAM/ConvergenceChecker.hpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 110 | 2020-09-02T15:29:24.000Z | 2022-03-09T09:50:01.000Z | include/DREAM/ConvergenceChecker.hpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 3 | 2021-05-21T13:24:31.000Z | 2022-02-11T14:43:12.000Z | #ifndef _DREAM_CONVERGENCE_CHECKER_HPP
#define _DREAM_CONVERGENCE_CHECKER_HPP
#include <string>
#include <unordered_map>
#include <vector>
#include "FVM/NormEvaluator.hpp"
#include "FVM/UnknownQuantityHandler.hpp"
namespace DREAM {
class ConvergenceChecker : public FVM::NormEvaluator {
private:
std::unordered_map<len_t, real_t> absTols;
std::unordered_map<len_t, real_t> relTols;
void DefineAbsoluteTolerances();
real_t GetDefaultAbsTol(const std::string&);
len_t dx_size = 0;
real_t *dx_buffer=nullptr;
len_t nNontrivials;
real_t *x_2norm=nullptr;
real_t *dx_2norm=nullptr;
public:
ConvergenceChecker(
FVM::UnknownQuantityHandler*, const std::vector<len_t>&,
const real_t reltol=1e-6
);
virtual ~ConvergenceChecker();
void AllocateBuffer(const len_t);
void DeallocateBuffer();
const std::string &GetNonTrivialName(const len_t i)
{ return this->unknowns->GetUnknown(nontrivials[i])->GetName(); }
bool IsConverged(const real_t*, const real_t*, bool verbose=false);
bool IsConverged(const real_t*, const real_t*, const real_t*, bool verbose=false);
const real_t *GetErrorNorms() { return this->dx_2norm; }
const real_t GetErrorScale(const len_t);
void SetAbsoluteTolerance(const len_t, const real_t);
void SetRelativeTolerance(const real_t);
void SetRelativeTolerance(const len_t, const real_t);
};
}
#endif/*_DREAM_CONVERGENCE_CHECKER_HPP*/
| 30.346154 | 90 | 0.679975 | chalmersplasmatheory |
39cd665f158df7b7981492c8c02d51edefce8d11 | 1,872 | cpp | C++ | src/question34.cpp | lxb1226/leetcode_cpp | 554280de6be2a77e2fe41a5e77cdd0f884ac2e20 | [
"MIT"
] | null | null | null | src/question34.cpp | lxb1226/leetcode_cpp | 554280de6be2a77e2fe41a5e77cdd0f884ac2e20 | [
"MIT"
] | null | null | null | src/question34.cpp | lxb1226/leetcode_cpp | 554280de6be2a77e2fe41a5e77cdd0f884ac2e20 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
// 法一:
vector<int> searchRange1(vector<int>& nums, int target) {
if(nums.size() == 0) return {-1, -1};
int l = 0, r = nums.size() - 1;
int mid = 0;
while(l <= r){
mid = l + (r - l) / 2;
if(nums[mid] == target){
break;
}else if(nums[mid] > target){
r = mid - 1;
}else{
l = mid + 1;
}
}
// cout << "mid = " << mid << endl;
if(l > r) return {-1, -1};
int i = mid, j = mid;
while(i >= 0 && nums[i] == target) i--;
while(j < nums.size() && nums[j] == target) j++;
return {i + 1, j - 1};
}
// 法二:
int binarySearch(vector<int>& nums, int target, bool lower){
int l = 0, r = nums.size() - 1, ans = nums.size();
while(l <= r){
int mid = (l + r) / 2;
if(nums[mid] > target || (lower && nums[mid] >= target)){
r = mid - 1;
ans = mid;
}else{
l = mid + 1;
}
}
return ans;
}
vector<int> searchRange(vector<int>& nums, int target) {
int leftIdx = binarySearch(nums, target, true);
int rightIdx = binarySearch(nums, target, false);
if(leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target){
return vector<int>{leftIdx, rightIdx};
}
return {-1, -1};
}
};
int main(){
// vector<int> nums{5,7,7,8,8,10};
// int target = 8;
vector<int> nums{5,7,7,8,8,10};
int target = 6;
Solution s;
auto ans = s.searchRange(nums, target);
for(auto num : ans){
cout << num << " ";
}
cout << endl;
} | 27.130435 | 113 | 0.444444 | lxb1226 |
39d7c9e0998fda2cdc29ac309fb7e0712ae06c90 | 1,709 | cc | C++ | src/sheet_painter.cc | d0iasm/liumos | f9600bd26f15ebd194d35d5e76877650e25b9733 | [
"MIT"
] | null | null | null | src/sheet_painter.cc | d0iasm/liumos | f9600bd26f15ebd194d35d5e76877650e25b9733 | [
"MIT"
] | null | null | null | src/sheet_painter.cc | d0iasm/liumos | f9600bd26f15ebd194d35d5e76877650e25b9733 | [
"MIT"
] | null | null | null | #include "sheet_painter.h"
#include "asm.h"
// @font.gen.c
extern uint8_t font[0x100][16];
void SheetPainter::DrawCharacter(Sheet& s,
char c,
int px,
int py,
bool do_flush) {
if (!s.buf_)
return;
uint32_t* b32 = reinterpret_cast<uint32_t*>(s.buf_);
for (int dy = 0; dy < 16; dy++) {
for (int dx = 0; dx < 8; dx++) {
uint32_t col = ((font[(uint8_t)c][dy] >> (7 - dx)) & 1) ? 0xffffff : 0;
int x = px + dx;
int y = py + dy;
b32[y * s.pixels_per_scan_line_ + x] = col;
}
}
if (do_flush)
s.Flush(px, py, 8, 16);
}
void SheetPainter::DrawRect(Sheet& s,
int px,
int py,
int w,
int h,
uint32_t col,
bool do_flush) {
if (!s.buf_)
return;
uint32_t* b32 = reinterpret_cast<uint32_t*>(s.buf_);
if (w & 1) {
for (int y = py; y < py + h; y++) {
RepeatStore4Bytes(w, &b32[y * s.pixels_per_scan_line_ + px], col);
}
} else {
for (int y = py; y < py + h; y++) {
RepeatStore8Bytes(w / 2, &b32[y * s.pixels_per_scan_line_ + px],
((uint64_t)col << 32) | col);
}
}
if (do_flush)
s.Flush(px, py, w, h);
}
void SheetPainter::DrawPoint(Sheet& s,
int px,
int py,
uint32_t col,
bool do_flush) {
s.buf_[py * s.pixels_per_scan_line_ + px] = col;
if (do_flush)
s.Flush(px, py, 1, 1);
}
| 28.016393 | 77 | 0.426565 | d0iasm |
39d8dafd5118ea5b48ded9852aee0f07e48802f6 | 813 | hpp | C++ | include/cues.hpp | stefanofortu/intoTheWild | 000af8d5b7a480e0f14e1a2deb047899c8469b41 | [
"Unlicense"
] | null | null | null | include/cues.hpp | stefanofortu/intoTheWild | 000af8d5b7a480e0f14e1a2deb047899c8469b41 | [
"Unlicense"
] | 1 | 2015-12-23T16:26:12.000Z | 2015-12-23T16:26:34.000Z | include/cues.hpp | stefanofortu/intothewild | 000af8d5b7a480e0f14e1a2deb047899c8469b41 | [
"Unlicense"
] | null | null | null | #ifndef _CUES_HPP_
#define _CUES_HPP_
#include "config.hpp"
vector<double> ComputeEHOG(Mat source, vector<vector<Point> > regions);
vector<double> ComputePD(Mat source, vector<vector<Point> > regions);
vector<double> ComputeStrokeWidth(Mat source, vector<vector<Point> > regions);
vector<int> regions_cue(vector<double> cue, double positive_dist[51], double negative_dist[51], Mat source, vector<vector<Point> > regions, int numero, Mat *risultato);
Mat Bayes(double positive_dist_SW[51], double negative_dist_SW[51], double positive_dist_PD[51],
double negative_dist_PD[51], double positive_dist_EHOG[51], double negative_dist_EHOG[51],
vector<double> SW, vector<double> PD, vector<double> EHOG, Mat source, vector<vector<Point> > regions);
#endif // _CUES_HPP_
| 42.789474 | 168 | 0.738007 | stefanofortu |
39d9cd2a51eb44da0fd11031f2d53dd4e72bed47 | 45 | cpp | C++ | src/NGFX/Private/Vulkan/vk_log.cpp | PixPh/kaleido3d | 8a8356586f33a1746ebbb0cfe46b7889d0ae94e9 | [
"MIT"
] | 38 | 2019-01-10T03:10:12.000Z | 2021-01-27T03:14:47.000Z | src/NGFX/Private/Vulkan/vk_log.cpp | fuqifacai/kaleido3d | ec77753b516949bed74e959738ef55a0bd670064 | [
"MIT"
] | null | null | null | src/NGFX/Private/Vulkan/vk_log.cpp | fuqifacai/kaleido3d | ec77753b516949bed74e959738ef55a0bd670064 | [
"MIT"
] | 8 | 2019-04-16T07:56:27.000Z | 2020-11-19T02:38:37.000Z | #include "vk_common.h"
namespace vulkan
{
} | 7.5 | 22 | 0.711111 | PixPh |
39de3ef7de48233da97491f31e295f3e2792d4b0 | 9,319 | cpp | C++ | programming/sampleProject/startScanner.cpp | ljyang100/dataScience | ad2b243673c570c18d83ab1a0cd1bb4694c17eac | [
"MIT"
] | 2 | 2020-12-10T02:05:29.000Z | 2021-05-30T15:23:56.000Z | programming/sampleProject/startScanner.cpp | ljyang100/dataScience | ad2b243673c570c18d83ab1a0cd1bb4694c17eac | [
"MIT"
] | null | null | null | programming/sampleProject/startScanner.cpp | ljyang100/dataScience | ad2b243673c570c18d83ab1a0cd1bb4694c17eac | [
"MIT"
] | 1 | 2020-04-21T11:18:18.000Z | 2020-04-21T11:18:18.000Z | #include "startScanner.h"
void StartScanner::StartEntryPoint()
{
AllData a;
a.initializeTraderParameters(); a.initializeOtherParameters();
a.initializeSymbolVectors_Prev();
a.m_backTest = false; //**** IMPORTANT! This must be false all the time for real trading.
a.initializeSymbolVectors();
a.initializeBaseVector("EMPTY"); a.initializeCurrentDataVector(); a.initializeOtherVectors();
a.unhandledSymbols();
int err = _beginthread(AllData::MessageLimitationStatic, 0, &a); if (err < 0) { printf("Could not start new threads.\n"); } // This is for handling 50 message limitation.
CommonFunctions cfs(a);
cfs.initialization();
HistoricalDataL historicalDataL(cfs, a);
historicalDataL.connectToTWS();
HistoricalDataNormal historicalDataS(cfs, a);
historicalDataS.connectToTWS();
//Liquidity_EC->reqScannerSubscription(100, m_ScannerSubscription);
if (time(0) > a.m_tradingEndTime){//Preparing data for tomorrow. When runing this, must make sure SPY dayBar for today is already available. The application will complain if this is not true.
a.m_timeNow = time(0);
a.m_numSymbolsToDownload = 1; a.m_historicalDataDone = false; historicalDataL.downloadHistoricalData_Single(); //****After this call, a.m_numDataOfSingleSymbolL will be set with a value.
a.L_BarVectorDefaul();
a.update_manualsVector();
a.earningReportDate(); //**** This is actually not necessary here. Just for testing purpose. It only matters in trading process.
a.m_numSymbolsToDownload = a.m_newtxtVector.size(); a.m_historicalDataDone = false;
err = _beginthread(HistoricalDataL::HistoricalDataStaticEntryPoint, 0, &historicalDataL); if (err < 0) { printf("Could not start new threads.\n"); }
while (1) { if (a.m_historicalDataDone) break; else Sleep(1000); }
Sleep(10000);
time_t now = time(0); struct tm *ts; char buf[80]; ts = localtime(&now); strftime(buf, sizeof(buf), "%m-%d %H:%M:%S", ts); std::string tempString = buf; //strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", ts); // "ddd yyyy-mm-dd hh:mm:ss zzz"
exit(0);
}
else{ //time(0) <= tradingEndTime. During or before trading.
a.m_timeNow = time(0) - 13 * 60 * 60; //****If I changed it into eastern time, I need modify this?
a.m_numSymbolsToDownload = 1; a.m_historicalDataDone = false; historicalDataL.downloadHistoricalData_Single(); //****After this call, numDataOfSingleSymbolL will be set with a value.
a.L_BarVectorDefaul();
a.update_manualsVector();
a.earningReportDate();
a.update_historyVector();
time_t startTime = time(0), timePassed, nextHeartBeat = time(0);
a.m_numSymbolsToDownload = a.m_newtxtVector.size(); a.m_historicalDataDone = false;
err = _beginthread(HistoricalDataL::HistoricalDataStaticEntryPoint, 0, &historicalDataL); if (err < 0) { printf("Could not start new threads.\n"); }
while (1){
timePassed = time(0) - startTime;
if (a.m_historicalDataDone) break;
Sleep(100);
if (time(0) > nextHeartBeat) { printf("I am waiting %d seconds for most historical data download done.\n", a.m_traderParameters.timeToContinue); nextHeartBeat = nextHeartBeat + 60; }
}
cfs.calculateBaseVector();
a.m_numSymbolsToDownload = 1; a.m_historicalDataDone = false; historicalDataS.downloadHistoricalData_Single(); //****After this call, numDataOfSingleSymbolL will be set with a value.
a.S_BarVectorDefaul();
//**** Similarly I can download s bars if necessary
}
EClientL0 *EC_datafeed, *EC_Long, *EC_Short; //**** ECLientL0 is abstract class and cannot be instantiated. However, we can create pointers to an abstract class.
DatafeedNormal datafeed(a);
EC_datafeed = EClientL0::New(&datafeed); if (EC_datafeed == NULL) { printf("Creating EClient for dataFeed failed.\n"); getchar(); exit(0); } //**** Avoid using exit(0) as it may cause memory leaks if not properly used.
bool returnValue = false;
std::chrono::high_resolution_clock::time_point now;
while (1){
bool b = true;
try { a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b){
if (a.m_timeDeque.size() < a.m_messageLimitPerSecond){
returnValue = EC_datafeed->eConnect("", a.m_port, a.m_clientId_MarketData); //***** This function starts a new thread automatically. Therefore, this function can never be in another threadEntryPoint function. I once made very big mistake and wastes my many hours.
now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime.
a.m_timeDeque.push_back(now);
}
a.m_csTimeDeque.LeaveCriticalSection();
}
printf(" socket client is being created for datafeed in start.cpp.\n");
if (returnValue == true) break; else { Sleep(20000); }
} //end of while(1)
datafeed.set_EC(EC_datafeed);
TraderEWrapperNormalLong traderEWrapperLong(a);
EC_Long = EClientL0::New(&traderEWrapperLong); if (EC_Long == NULL) { printf("Creating EClient failed.\n"); getchar(); exit(0); } //**** Avoid using exit(0) as it may cause memory leaks if not properly used.
returnValue = false;
while (1){
bool b = true;
try { a.m_csTimeDeque.EnterCriticalSection(); }catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b){
if (a.m_timeDeque.size() < a.m_messageLimitPerSecond){
returnValue = EC_Long->eConnect("", a.m_port, a.m_clientIdLong); //***** This function starts a new thread automatically. Therefore, this function can never be in another threadEntryPoint function. I once made very big mistake and wastes my many hours.
now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime.
a.m_timeDeque.push_back(now);
}
a.m_csTimeDeque.LeaveCriticalSection();
}
printf(" long socket client is being created in startNormal.cpp.\n");
if (returnValue == true) break; else { Sleep(20000); }
} //end of while(1)
TraderNormalLong trader1(cfs, a, EC_Long, traderEWrapperLong);
traderEWrapperLong.set_EC(EC_Long);
traderEWrapperLong.update_traderStructureVector_by_EWrappers();
TraderEWrapperNormalShort traderEWrapperShort(a);
EC_Short = EClientL0::New(&traderEWrapperShort); if (EC_Short == NULL) { printf("Creating EClient failed.\n"); getchar(); exit(0); } //**** Avoid using exit(0) as it may cause memory leaks if not properly used.
returnValue = false;
while (1){
bool b = true;
try { a.m_csTimeDeque.EnterCriticalSection(); } catch (...) { printf("***CS*** %s %d\n", __FILE__, __LINE__); b = false; } if (b){
if (a.m_timeDeque.size() < a.m_messageLimitPerSecond){
returnValue = EC_Short->eConnect("", a.m_port, a.m_clientIdShort); //***** This function starts a new thread automatically. Therefore, this function can never be in another threadEntryPoint function. I once made very big mistake and wastes my many hours.
now = std::chrono::high_resolution_clock::now(); //GetSystemTimeAsFileTime is system API, and can also be called as ::GetSystemTimeAsFileTime.
a.m_timeDeque.push_back(now);
}
a.m_csTimeDeque.LeaveCriticalSection();
}
printf(" short socket client is being created in startNormal.cpp.\n");
if (returnValue == true) break; else { Sleep(20000); }
} //end of while(1)
traderEWrapperShort.set_EC(EC_Short);
traderEWrapperShort.update_traderStructureVector_by_EWrappers();
TraderNormalShort trader2(cfs, a, EC_Short, traderEWrapperShort);
//Sleep(10000); //It seems here above does not have problems.
if (time(0) <= a.m_tradingEndTime){ //Preparing data for tomorrow. When runing this, must make sure SPY dayBar for today is already available. The application will complain if this is not true.
err = _beginthread(DatafeedNormal::DatafeedStaticEntryPoint, 0, &datafeed); if (err < 0) { printf("Could not start new threads.\n"); }
err = _beginthread(TraderNormalLong::TraderNormalLongStaticEntryPoint, 0, &trader1); if (err < 0) { printf("Could not start new threads for normalLong.\n"); }
err = _beginthread(TraderNormalShort::TraderNormalShortStaticEntryPoint, 0, &trader2); if (err < 0) { printf("Could not start new threads for normalShort.\n"); }
//**** Note to keep the threads initiated here alive. I must keep the thead here alive. Otherwise all threads will be dead tother with weird errors.
///************** Don't comment this line
//*************** Two IMPORTANT Points: [1] If without the Sleep(100000000) below, then once the main thread is gone, then all other threads will be done. [2] When starting a new thread I need make sure that the class instance
//*************** used in the new thread will not be dead. The class instance should be alive all the time when the application is running, unless I really don't need the thread to be alive that long. In the main() above,
//*************** I define several class instances but not define them in a new class member function. This is because when that member function is gone, then class instance will often be gone too. If that happens, I will get errors such as "pure virtual funtion call " or "invalid access" or "unhandled exception" etc.
Sleep(100000000); // This is critically important for old C++ standard. Without it, the termination of main thread will terminate all other running threads.
}
}
| 65.167832 | 322 | 0.725722 | ljyang100 |
39e2e124b0dbd8950a1a7d138a1b5ee8464995d5 | 656 | cpp | C++ | src/gui/widget/BodyWidget/BodyController.cpp | bartkessels/GetIt | 8adde91005d00d83a73227a91b08706657513f41 | [
"MIT"
] | 16 | 2020-09-07T18:53:39.000Z | 2022-03-21T08:15:55.000Z | src/gui/widget/BodyWidget/BodyController.cpp | bartkessels/GetIt | 8adde91005d00d83a73227a91b08706657513f41 | [
"MIT"
] | 23 | 2017-03-29T21:21:43.000Z | 2022-03-23T07:27:55.000Z | src/gui/widget/BodyWidget/BodyController.cpp | bartkessels/GetIt | 8adde91005d00d83a73227a91b08706657513f41 | [
"MIT"
] | 4 | 2020-06-15T12:51:10.000Z | 2021-09-05T20:50:46.000Z | #include "gui/widget/BodyWidget/BodyController.hpp"
using namespace getit::gui::widget;
BodyController::BodyController(std::shared_ptr<IBodyView> view):
view(view)
{
}
void BodyController::registerTab(std::shared_ptr<getit::domain::BeforeRequestPipeline> controller, std::shared_ptr<QWidget> tab, std::string name)
{
this->tabControllers.push_back(controller);
view->addBodyTab(tab.get(), name);
}
void BodyController::executeBeforeRequest(std::shared_ptr<getit::domain::RequestData> data)
{
int currentTabIndex = view->getSelectedTabIndex();
auto body = tabControllers.at(currentTabIndex);
body->executeBeforeRequest(data);
} | 28.521739 | 146 | 0.760671 | bartkessels |
39e2e6f4d2351b8444b28edacee97376057ee6d6 | 665 | hpp | C++ | core/impl/memory/free_first_fit.hpp | auyunli/enhance | ca99530c80b42842e713ed4b62e40d12e56ee24a | [
"BSD-2-Clause"
] | null | null | null | core/impl/memory/free_first_fit.hpp | auyunli/enhance | ca99530c80b42842e713ed4b62e40d12e56ee24a | [
"BSD-2-Clause"
] | null | null | null | core/impl/memory/free_first_fit.hpp | auyunli/enhance | ca99530c80b42842e713ed4b62e40d12e56ee24a | [
"BSD-2-Clause"
] | null | null | null | #ifndef E2_FREE_FIRST_FIT_HPP
#define E2_FREE_FIRST_FIT_HPP
#include "i_free.hpp"
#include "memory_common.hpp"
namespace e2 { namespace memory {
class free_first_fit_impl {
public:
template< class T >
bool deleting( void * p_mem_start, size_t p_mem_len, std::list< memory_block_info > * mem_blocks, std::list< memory_block_info > * mem_lent, T * p );
bool freeing( void * p_mem_start, size_t p_mem_len, std::list< memory_block_info > * mem_blocks, std::list< memory_block_info > * mem_lent, void * p );
};
#include "free_first_fit.tpp"
class free_first_fit : public ::e2::interface::i_free< free_first_fit_impl > {};
} }
#endif
| 28.913043 | 161 | 0.714286 | auyunli |
39e3b63b95788224b22bcbcfb41c9ecca1964d06 | 457 | cpp | C++ | ExampleTemplate/ExampleTemplate.cpp | siretty/BrotBoxEngine | e1eb95152ffb8a7051e96a8937aa62f568b90a27 | [
"MIT"
] | 37 | 2020-06-14T18:14:08.000Z | 2022-03-29T18:39:34.000Z | ExampleTemplate/ExampleTemplate.cpp | HEX17/BrotBoxEngine | 4f8bbe220be022423b94e3b594a3695b87705a70 | [
"MIT"
] | 2 | 2021-04-05T15:34:18.000Z | 2021-05-28T00:04:56.000Z | ExampleTemplate/ExampleTemplate.cpp | HEX17/BrotBoxEngine | 4f8bbe220be022423b94e3b594a3695b87705a70 | [
"MIT"
] | 10 | 2020-06-25T17:07:03.000Z | 2022-03-08T20:31:17.000Z | #include "BBE/BrotBoxEngine.h"
#include <iostream>
class MyGame : public bbe::Game
{
virtual void onStart() override
{
}
virtual void update(float timeSinceLastFrame) override
{
}
virtual void draw3D(bbe::PrimitiveBrush3D & brush) override
{
}
virtual void draw2D(bbe::PrimitiveBrush2D & brush) override
{
}
virtual void onEnd() override
{
}
};
int main()
{
MyGame *mg = new MyGame();
mg->start(1280, 720, "Template!");
return 0;
}
| 14.741935 | 60 | 0.682713 | siretty |
39e64f1ecc077a97d5a64894fa9edc174bd0f1cd | 120,568 | cc | C++ | lib/ArgParseConvert/test/argument_map_test.cc | JasperBraun/PasteAlignments | 5186f674e51571319af3f328c661aaa62dbd0ca9 | [
"MIT"
] | null | null | null | lib/ArgParseConvert/test/argument_map_test.cc | JasperBraun/PasteAlignments | 5186f674e51571319af3f328c661aaa62dbd0ca9 | [
"MIT"
] | null | null | null | lib/ArgParseConvert/test/argument_map_test.cc | JasperBraun/PasteAlignments | 5186f674e51571319af3f328c661aaa62dbd0ca9 | [
"MIT"
] | null | null | null | // Copyright (c) 2020 Jasper Braun
//
// 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 "argument_map.h"
#define CATCH_CONFIG_MAIN
#define CATCH_CONFIG_COLOUR_NONE
#include "catch.h"
#include "string_conversions.h" // include after catch.h
// Test correctness for:
// * ArgumentMap(ParameterMap)
// * SetDefaultArguments
// * AddArgument
// * GetUnfilledParameters
// * HasArgument
// * ArgumentsOf
// * GetValue
// * GetAllValues
// * IsSet
//
// Test invariants for:
// * ArgumentMap(ParameterMap)
//
// Test exceptions for:
// * AddArgument
// * HasArgument
// * ArgumentsOf
// * GetValue
// * GetAllValues
// * IsSet
namespace arg_parse_convert {
namespace test {
struct TestType {
int data;
TestType() = default;
TestType(int d) : data{d} {}
inline bool operator==(const TestType& other) const {
return (data == other.data);
}
};
inline TestType StringToTestType(const std::string& s) {
TestType result;
result.data = std::stoi(s);
return result;
}
namespace {
// NoMin, YesMin, NoMax, YesMax indicate whether minimum and maximum arguments
// are set.
// * NoArgs: no arguments
// * UnderfullArgs: some arguments, but less than its minimum
// * MinArgs: exactly as many arguments as its minimum
// * ManyArgs: more arguments than its minimum but less than its maximum
// * FullArgs: as many arguments as its maximum
//
Parameter<std::string> kNoMinNoMaxNoArgs{Parameter<std::string>::Positional(
converters::StringIdentity, "kNoMinNoMaxNoArgs", 0)};
Parameter<std::string> kNoMinYesMaxNoArgs{Parameter<std::string>::Keyword(
converters::StringIdentity, {"kNoMinYesMaxNoArgs",
"alt_kNoMinYesMaxNoArgs"})
.MaxArgs(8)};
Parameter<int> kNoMinYesMaxManyArgs{Parameter<int>::Positional(
converters::stoi, "kNoMinYesMaxManyArgs", 1)
.MaxArgs(8)};
Parameter<int> kNoMinYesMaxFullArgs{Parameter<int>::Keyword(
converters::stoi, {"kNoMinYesMaxFullArgs", "alt_kNoMinYesMaxFullArgs"})
.MaxArgs(8)};
Parameter<TestType> kYesMinNoMaxNoArgs{Parameter<TestType>::Positional(
StringToTestType, "kYesMinNoMaxNoArgs", 2)
.MinArgs(4)};
Parameter<TestType> kYesMinNoMaxUnderfullArgs{Parameter<TestType>::Keyword(
StringToTestType, {"kYesMinNoMaxUnderfullArgs",
"alt_kYesMinNoMaxUnderfullArgs"})
.MinArgs(4)};
Parameter<long> kYesMinNoMaxMinArgs{Parameter<long>::Positional(
converters::stol, "kYesMinNoMaxMinArgs", 3)
.MinArgs(4)};
Parameter<long> kYesMinYesMaxNoArgs{Parameter<long>::Keyword(
converters::stol, {"kYesMinYesMaxNoArgs", "alt_kYesMinYesMaxNoArgs"})
.MaxArgs(8).MinArgs(4)};
Parameter<float> kYesMinYesMaxUnderfullArgs{Parameter<float>::Positional(
converters::stof, "kYesMinYesMaxUnderfullArgs", 4)
.MaxArgs(8).MinArgs(4)};
Parameter<float> kYesMinYesMaxMinArgs{Parameter<float>::Keyword(
converters::stof, {"kYesMinYesMaxMinArgs", "alt_kYesMinYesMaxMinArgs"})
.MaxArgs(8).MinArgs(4)};
Parameter<double> kYesMinYesMaxManyArgs{Parameter<double>::Positional(
converters::stod, "kYesMinYesMaxManyArgs", 5)
.MaxArgs(8).MinArgs(4)};
Parameter<double> kYesMinYesMaxFullArgs{Parameter<double>::Keyword(
converters::stod, {"kYesMinYesMaxFullArgs", "alt_kYesMinYesMaxFullArgs"})
.MaxArgs(8).MinArgs(4)};
std::vector<std::string> kArgs{"1.0", "2.0", "2.0", "4.0", "5.0", "6.0", "7.0",
"8.0", "9.0", "10.0"};
std::vector<std::string> kDefaultArgs{"10.0", "20.0", "20.0", "40.0", "50.0",
"60.0", "70.0", "80.0", "90.0", "100.0"};
Parameter<bool> kSetFlag{Parameter<bool>::Flag({"kSetFlag", "alt_kSetFlag"})};
Parameter<bool> kUnsetFlag{Parameter<bool>::Flag({"kUnsetFlag",
"alt_kUnsetFlag"})};
Parameter<bool> kMultipleSetFlag{Parameter<bool>::Flag(
{"kMultipleSetFlag", "alt_kMultipleSetFlag"})};
Parameter<TestType> kNoConverterPositional{Parameter<TestType>::Positional(
nullptr, "kNoConverterPositional", 6)};
Parameter<TestType> kNoConverterKeyword{Parameter<TestType>::Keyword(
nullptr, {"kNoConverterKeyword", "alt_kNoConverterKeyword"})};
std::vector<std::string> kNames{
"kNoMinNoMaxNoArgs", "kNoMinYesMaxNoArgs", "alt_kNoMinYesMaxNoArgs",
"kNoMinYesMaxManyArgs", "kNoMinYesMaxFullArgs", "alt_kNoMinYesMaxFullArgs",
"kYesMinNoMaxNoArgs", "kYesMinNoMaxUnderfullArgs",
"alt_kYesMinNoMaxUnderfullArgs", "kYesMinNoMaxMinArgs",
"kYesMinYesMaxNoArgs", "alt_kYesMinYesMaxNoArgs",
"kYesMinYesMaxUnderfullArgs", "kYesMinYesMaxMinArgs",
"alt_kYesMinYesMaxMinArgs", "kYesMinYesMaxManyArgs",
"kYesMinYesMaxFullArgs", "alt_kYesMinYesMaxFullArgs",
"kSetFlag", "alt_kSetFlag", "kUnsetFlag", "alt_kUnsetFlag",
"kMultipleSetFlag", "alt_kMultipleSetFlag", "kNoConverterPositional",
"kNoConverterKeyword", "alt_kNoConverterKeyword"};
SCENARIO("Test correctness of ArgumentMap::ArgumentMap(ParameterMap).",
"[ArgumentMap][ArgumentMap(ParameterMap)][correctness]") {
GIVEN("A `ParameterMap` object containing various parameters.") {
ParameterMap parameter_map, reference;
parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs)
(kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs)
(kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs)
(kYesMinNoMaxMinArgs)
(kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs)
(kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs)
(kYesMinYesMaxFullArgs)
(kSetFlag)(kUnsetFlag)(kMultipleSetFlag)
(kNoConverterPositional)(kNoConverterKeyword);
reference = parameter_map;
WHEN("Constructed from the parameters.") {
ArgumentMap argument_map(std::move(parameter_map));
THEN("The `ParameterMap` becomes a member of the `ArgumentMap`.") {
for (const std::string& name : kNames) {
CHECK(argument_map.Parameters().GetConfiguration(name)
== reference.GetConfiguration(name));
CHECK(argument_map.Parameters().required_parameters()
== reference.required_parameters());
CHECK(argument_map.Parameters().positional_parameters()
== reference.positional_parameters());
CHECK(argument_map.Parameters().keyword_parameters()
== reference.keyword_parameters());
CHECK(argument_map.Parameters().flags() == reference.flags());
}
}
THEN("All argument lists begin empty.") {
for (const std::string& name : kNames) {
CHECK(argument_map.ArgumentsOf(name).empty());
}
}
}
}
}
SCENARIO("Test invariant preservation by"
" ArgumentMap::ArgumentMap(ParameterMap).",
"[ArgumentMap][ArgumentMap(ParameterMap)][invariants]") {
GIVEN("A `ParameterMap` object containing various parameters.") {
int size = GENERATE(range(0, 21, 4));
ParameterMap parameter_map, reference;
for (int i = 0; i < size; i += 4) {
parameter_map(Parameter<bool>::Flag({kNames.at(i)}))
(Parameter<int>::Keyword(
converters::stoi, {kNames.at(i+1),
kNames.at(i+2)}))
(Parameter<std::string>::Positional(
converters::StringIdentity, kNames.at(i+3), i));
}
reference = parameter_map;
WHEN("Constructed from the parameters.") {
ArgumentMap argument_map(std::move(parameter_map));
THEN("The object's size is the same as the number of parameters.") {
CHECK(argument_map.size() == reference.size());
CHECK(argument_map.Arguments().size() == reference.size());
CHECK(argument_map.Values().size() == reference.size());
}
}
}
}
SCENARIO("Test correctness of ArgumentMap::SetDefaultArguments.",
"[ArgumentMap][SetDefaultArguments][correctness]") {
GIVEN("Parameters without default arguments.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs)
(kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs)
(kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs)
(kYesMinNoMaxMinArgs)
(kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs)
(kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs)
(kYesMinYesMaxFullArgs)
(kSetFlag)(kUnsetFlag)(kMultipleSetFlag)
(kNoConverterPositional)(kNoConverterKeyword);
WHEN("Argument lists are empty.") {
ArgumentMap argument_map(std::move(parameter_map));
ArgumentMap reference{argument_map};
argument_map.SetDefaultArguments();
THEN("Argument lists remain unchanged.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs")
== reference.ArgumentsOf("kNoMinNoMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs")
== reference.ArgumentsOf("kNoMinYesMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
== reference.ArgumentsOf("kNoMinYesMaxManyArgs"));
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
== reference.ArgumentsOf("kNoMinYesMaxFullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs")
== reference.ArgumentsOf("kYesMinNoMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs")
== reference.ArgumentsOf("kYesMinNoMaxUnderfullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
== reference.ArgumentsOf("kYesMinNoMaxMinArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs")
== reference.ArgumentsOf("kYesMinYesMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs")
== reference.ArgumentsOf("kYesMinYesMaxUnderfullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
== reference.ArgumentsOf("kYesMinYesMaxMinArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
== reference.ArgumentsOf("kYesMinYesMaxManyArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
== reference.ArgumentsOf("kYesMinYesMaxFullArgs"));
CHECK(argument_map.ArgumentsOf("kSetFlag")
== reference.ArgumentsOf("kSetFlag"));
CHECK(argument_map.ArgumentsOf("kUnsetFlag")
== reference.ArgumentsOf("kUnsetFlag"));
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag")
== reference.ArgumentsOf("kMultipleSetFlag"));
CHECK(argument_map.ArgumentsOf("kNoConverterPositional")
== reference.ArgumentsOf("kNoConverterPositional"));
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword")
== reference.ArgumentsOf("kNoConverterKeyword"));
}
}
WHEN("Argument lists already contain some arguments.") {
ArgumentMap argument_map(std::move(parameter_map));
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
ArgumentMap reference{argument_map};
argument_map.SetDefaultArguments();
THEN("Argument lists remain unchanged.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs")
== reference.ArgumentsOf("kNoMinNoMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs")
== reference.ArgumentsOf("kNoMinYesMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
== reference.ArgumentsOf("kNoMinYesMaxManyArgs"));
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
== reference.ArgumentsOf("kNoMinYesMaxFullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs")
== reference.ArgumentsOf("kYesMinNoMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs")
== reference.ArgumentsOf("kYesMinNoMaxUnderfullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
== reference.ArgumentsOf("kYesMinNoMaxMinArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs")
== reference.ArgumentsOf("kYesMinYesMaxNoArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs")
== reference.ArgumentsOf("kYesMinYesMaxUnderfullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
== reference.ArgumentsOf("kYesMinYesMaxMinArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
== reference.ArgumentsOf("kYesMinYesMaxManyArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
== reference.ArgumentsOf("kYesMinYesMaxFullArgs"));
CHECK(argument_map.ArgumentsOf("kSetFlag")
== reference.ArgumentsOf("kSetFlag"));
CHECK(argument_map.ArgumentsOf("kUnsetFlag")
== reference.ArgumentsOf("kUnsetFlag"));
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag")
== reference.ArgumentsOf("kMultipleSetFlag"));
CHECK(argument_map.ArgumentsOf("kNoConverterPositional")
== reference.ArgumentsOf("kNoConverterPositional"));
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword")
== reference.ArgumentsOf("kNoConverterKeyword"));
}
}
}
GIVEN("Parameters with default arguments.") {
int count = GENERATE(range(1, 10));
ParameterMap parameter_map;
std::vector<std::string> default_args{kDefaultArgs.begin(),
kDefaultArgs.begin() + count};
parameter_map(kNoMinNoMaxNoArgs.SetDefault(default_args))
(kNoMinYesMaxNoArgs.SetDefault(default_args))
(kNoMinYesMaxManyArgs.SetDefault(default_args))
(kNoMinYesMaxFullArgs.SetDefault(default_args))
(kYesMinNoMaxNoArgs.SetDefault(default_args))
(kYesMinNoMaxUnderfullArgs.SetDefault(default_args))
(kYesMinNoMaxMinArgs.SetDefault(default_args))
(kYesMinYesMaxNoArgs.SetDefault(default_args))
(kYesMinYesMaxUnderfullArgs.SetDefault(default_args))
(kYesMinYesMaxMinArgs.SetDefault(default_args))
(kYesMinYesMaxManyArgs.SetDefault(default_args))
(kYesMinYesMaxFullArgs.SetDefault(default_args))
(kSetFlag.SetDefault(default_args))
(kUnsetFlag.SetDefault(default_args))
(kMultipleSetFlag.SetDefault(default_args))
(kNoConverterPositional.SetDefault(default_args))
(kNoConverterKeyword.SetDefault(default_args));
WHEN("Argument lists are empty.") {
ArgumentMap argument_map(std::move(parameter_map));
ArgumentMap reference{argument_map};
argument_map.SetDefaultArguments();
THEN("Argument lists are added to where appropriate up to maximum.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kSetFlag")
== reference.ArgumentsOf("kSetFlag"));
CHECK(argument_map.ArgumentsOf("kUnsetFlag")
== reference.ArgumentsOf("kUnsetFlag"));
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag")
== reference.ArgumentsOf("kMultipleSetFlag"));
CHECK(argument_map.ArgumentsOf("kNoConverterPositional")
== default_args);
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword")
== default_args);
}
}
WHEN("Argument lists already contain some arguments.") {
ArgumentMap argument_map(std::move(parameter_map));
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
ArgumentMap reference{argument_map};
argument_map.SetDefaultArguments();
THEN("Arguments are assigned only to non-empty, non-flag parameters.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
== reference.ArgumentsOf("kNoMinYesMaxManyArgs"));
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
== reference.ArgumentsOf("kNoMinYesMaxFullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs")
== reference.ArgumentsOf("kYesMinNoMaxUnderfullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
== reference.ArgumentsOf("kYesMinNoMaxMinArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs")
== default_args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs")
== reference.ArgumentsOf("kYesMinYesMaxUnderfullArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
== reference.ArgumentsOf("kYesMinYesMaxMinArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
== reference.ArgumentsOf("kYesMinYesMaxManyArgs"));
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
== reference.ArgumentsOf("kYesMinYesMaxFullArgs"));
CHECK(argument_map.ArgumentsOf("kSetFlag")
== reference.ArgumentsOf("kSetFlag"));
CHECK(argument_map.ArgumentsOf("kUnsetFlag")
== reference.ArgumentsOf("kUnsetFlag"));
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag")
== reference.ArgumentsOf("kMultipleSetFlag"));
CHECK(argument_map.ArgumentsOf("kNoConverterPositional")
== reference.ArgumentsOf("kNoConverterPositional"));
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword")
== reference.ArgumentsOf("kNoConverterKeyword"));
}
}
}
}
SCENARIO("Test correctness of ArgumentMap::AddArgument.",
"[ArgumentMap][AddArgument][correctness]") {
GIVEN("Parameters without default arguments.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs)
(kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs)
(kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs)
(kYesMinNoMaxMinArgs)
(kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs)
(kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs)
(kYesMinYesMaxFullArgs)
(kSetFlag)(kUnsetFlag)(kMultipleSetFlag)
(kNoConverterPositional)(kNoConverterKeyword);
WHEN("Argument lists are empty.") {
ArgumentMap argument_map(std::move(parameter_map));
std::vector<std::string> args{kArgs.begin(), kArgs.begin() + 8};
for (const std::string& arg : args) {
argument_map.AddArgument("kNoMinNoMaxNoArgs", arg);
argument_map.AddArgument("kNoMinYesMaxNoArgs", arg);
argument_map.AddArgument("kNoMinYesMaxManyArgs", arg);
argument_map.AddArgument("kNoMinYesMaxFullArgs", arg);
argument_map.AddArgument("kYesMinNoMaxNoArgs", arg);
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", arg);
argument_map.AddArgument("kYesMinNoMaxMinArgs", arg);
argument_map.AddArgument("kYesMinYesMaxNoArgs", arg);
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", arg);
argument_map.AddArgument("kYesMinYesMaxMinArgs", arg);
argument_map.AddArgument("kYesMinYesMaxManyArgs", arg);
argument_map.AddArgument("kYesMinYesMaxFullArgs", arg);
argument_map.AddArgument("kSetFlag", arg);
argument_map.AddArgument("kUnsetFlag", arg);
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("They are appended to the existing list of arguments.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == args);
CHECK(argument_map.ArgumentsOf("kSetFlag") == args);
CHECK(argument_map.ArgumentsOf("kUnsetFlag") == args);
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == args);
CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == args);
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == args);
}
THEN("More arguments are ignored by parameters with argument limits.") {
for (auto it = kArgs.begin() + 8; it != kArgs.end(); ++it) {
argument_map.AddArgument("kNoMinYesMaxNoArgs", *it);
argument_map.AddArgument("kNoMinYesMaxManyArgs", *it);
argument_map.AddArgument("kNoMinYesMaxFullArgs", *it);
argument_map.AddArgument("kYesMinYesMaxNoArgs", *it);
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", *it);
argument_map.AddArgument("kYesMinYesMaxMinArgs", *it);
argument_map.AddArgument("kYesMinYesMaxManyArgs", *it);
argument_map.AddArgument("kYesMinYesMaxFullArgs", *it);
}
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == args);
}
THEN("More arguments are added for parameters without argument limits.") {
for (auto it = kArgs.begin() + 8; it != kArgs.end(); ++it) {
argument_map.AddArgument("kNoMinNoMaxNoArgs", *it);
argument_map.AddArgument("kYesMinNoMaxNoArgs", *it);
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", *it);
argument_map.AddArgument("kYesMinNoMaxMinArgs", *it);
argument_map.AddArgument("kSetFlag", *it);
argument_map.AddArgument("kUnsetFlag", *it);
argument_map.AddArgument("kMultipleSetFlag", *it);
argument_map.AddArgument("kNoConverterPositional", *it);
argument_map.AddArgument("kNoConverterKeyword", *it);
}
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kSetFlag") == kArgs);
CHECK(argument_map.ArgumentsOf("kUnsetFlag") == kArgs);
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == kArgs);
CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == kArgs);
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kArgs);
}
}
WHEN("Argument lists already contain some arguments.") {
ArgumentMap argument_map(std::move(parameter_map));
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
std::vector<std::string> args{kArgs.begin(), kArgs.begin() + 8};
for (int i = 0; i < 10; ++i) {
argument_map.AddArgument("kNoMinNoMaxNoArgs", kArgs.at(i));
argument_map.AddArgument("kNoMinYesMaxNoArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinNoMaxNoArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxNoArgs", kArgs.at(i));
argument_map.AddArgument("kUnsetFlag", kArgs.at(i));
if (i >= 1) {
argument_map.AddArgument("kSetFlag", kArgs.at(i));
}
if (i >= 2) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
if (i >= 4) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
if (i >= 6) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
if (i >= 8) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
}
THEN("Arguments are added until argument limit is reached, if any.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == args);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == kArgs);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs") == args);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs") == args);
CHECK(argument_map.ArgumentsOf("kSetFlag") == kArgs);
CHECK(argument_map.ArgumentsOf("kUnsetFlag") == kArgs);
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == kArgs);
CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == kArgs);
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kArgs);
}
}
}
}
SCENARIO("Test exceptions thrown by ArgumentMap::AddArgument.",
"[ArgumentMap][AddArgument][exceptions]") {
GIVEN("Parameters without default arguments.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs)
(kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs)
(kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs)
(kYesMinNoMaxMinArgs)
(kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs)
(kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs)
(kYesMinYesMaxFullArgs)
(kSetFlag)(kUnsetFlag)(kMultipleSetFlag)
(kNoConverterPositional)(kNoConverterKeyword);
ArgumentMap argument_map(std::move(parameter_map));
THEN("Adding arguments to parameters of unknown names causes exception.") {
CHECK_THROWS_AS(argument_map.AddArgument("unknown_name", "arg"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.AddArgument("foo", "arg"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.AddArgument("b", "ARG"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.AddArgument("", "arg"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.AddArgument("bazinga", ""),
exceptions::ParameterAccessError);
}
THEN("Adding arguments to recognized parameters doesn't cause exception.") {
std::string name = GENERATE(from_range(kNames));
CHECK_NOTHROW(argument_map.AddArgument(name, "arg"));
}
}
}
SCENARIO("Test correctness of ArgumentMap::GetUnfilledParameters.",
"[ArgumentMap][GetUnfilledParameters][correctness]") {
GIVEN("Various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
WHEN("Argument lists are empty.") {
ArgumentMap argument_map(std::move(parameter_map));
std::vector<std::string> unfilled_parameters{
argument_map.GetUnfilledParameters()};
THEN("Parameters with minimum argument numbers are unfilled.") {
CHECK(unfilled_parameters == std::vector<std::string>{
"kYesMinNoMaxNoArgs", "kYesMinNoMaxUnderfullArgs",
"kYesMinNoMaxMinArgs", "kYesMinYesMaxNoArgs",
"kYesMinYesMaxUnderfullArgs", "kYesMinYesMaxMinArgs",
"kYesMinYesMaxManyArgs", "kYesMinYesMaxFullArgs"});
}
}
WHEN("Argument lists already contain some arguments.") {
ArgumentMap argument_map(std::move(parameter_map));
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
std::vector<std::string> unfilled_parameters{
argument_map.GetUnfilledParameters()};
THEN("Parameters with too few arguments are unfilled.") {
CHECK(unfilled_parameters == std::vector<std::string>{
"kYesMinNoMaxNoArgs", "kYesMinNoMaxUnderfullArgs",
"kYesMinYesMaxNoArgs", "kYesMinYesMaxUnderfullArgs"});
}
}
}
}
SCENARIO("Test correctness of ArgumentMap::HasArgument.",
"[ArgumentMap][HasArgument][correctness]") {
GIVEN("An ArgumentMap containing various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("None of them has arguments.") {
CHECK_FALSE(argument_map.HasArgument("kNoMinNoMaxNoArgs"));
CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxNoArgs"));
CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxManyArgs"));
CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxFullArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxNoArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxUnderfullArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxMinArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxNoArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxUnderfullArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxMinArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxManyArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxFullArgs"));
CHECK_FALSE(argument_map.HasArgument("kSetFlag"));
CHECK_FALSE(argument_map.HasArgument("kUnsetFlag"));
CHECK_FALSE(argument_map.HasArgument("kMultipleSetFlag"));
CHECK_FALSE(argument_map.HasArgument("kNoConverterPositional"));
CHECK_FALSE(argument_map.HasArgument("kNoConverterKeyword"));
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("All arguments with non-empty lists have arguments.") {
CHECK_FALSE(argument_map.HasArgument("kNoMinNoMaxNoArgs"));
CHECK_FALSE(argument_map.HasArgument("kNoMinYesMaxNoArgs"));
CHECK(argument_map.HasArgument("kNoMinYesMaxManyArgs"));
CHECK(argument_map.HasArgument("kNoMinYesMaxFullArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinNoMaxNoArgs"));
CHECK(argument_map.HasArgument("kYesMinNoMaxUnderfullArgs"));
CHECK(argument_map.HasArgument("kYesMinNoMaxMinArgs"));
CHECK_FALSE(argument_map.HasArgument("kYesMinYesMaxNoArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxUnderfullArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxMinArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxManyArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxFullArgs"));
CHECK(argument_map.HasArgument("kSetFlag"));
CHECK_FALSE(argument_map.HasArgument("kUnsetFlag"));
CHECK(argument_map.HasArgument("kMultipleSetFlag"));
CHECK(argument_map.HasArgument("kNoConverterPositional"));
CHECK(argument_map.HasArgument("kNoConverterKeyword"));
}
}
WHEN("Default arguments are set for all arguments.") {
argument_map.SetDefaultArguments();
THEN("All non-flag parameters have arguments.") {
CHECK(argument_map.HasArgument("kNoMinNoMaxNoArgs"));
CHECK(argument_map.HasArgument("kNoMinYesMaxNoArgs"));
CHECK(argument_map.HasArgument("kNoMinYesMaxManyArgs"));
CHECK(argument_map.HasArgument("kNoMinYesMaxFullArgs"));
CHECK(argument_map.HasArgument("kYesMinNoMaxNoArgs"));
CHECK(argument_map.HasArgument("kYesMinNoMaxUnderfullArgs"));
CHECK(argument_map.HasArgument("kYesMinNoMaxMinArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxNoArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxUnderfullArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxMinArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxManyArgs"));
CHECK(argument_map.HasArgument("kYesMinYesMaxFullArgs"));
CHECK_FALSE(argument_map.HasArgument("kSetFlag"));
CHECK_FALSE(argument_map.HasArgument("kUnsetFlag"));
CHECK_FALSE(argument_map.HasArgument("kMultipleSetFlag"));
CHECK(argument_map.HasArgument("kNoConverterPositional"));
CHECK(argument_map.HasArgument("kNoConverterKeyword"));
}
}
}
}
SCENARIO("Test exceptions thrown by ArgumentMap::HasArgument.",
"[ArgumentMap][HasArgument][exceptions]") {
GIVEN("Parameters without default arguments.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs)
(kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs)
(kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs)
(kYesMinNoMaxMinArgs)
(kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs)
(kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs)
(kYesMinYesMaxFullArgs)
(kSetFlag)(kUnsetFlag)(kMultipleSetFlag)
(kNoConverterPositional)(kNoConverterKeyword);
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("Testing arguments of parameters of unknown names causes exception.") {
CHECK_THROWS_AS(argument_map.HasArgument("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Testing arguments of recognized names doesn't cause exception.") {
std::string name = GENERATE(from_range(kNames));
CHECK_NOTHROW(argument_map.HasArgument(name));
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("Testing arguments of parameters of unknown names causes exception.") {
CHECK_THROWS_AS(argument_map.HasArgument("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.HasArgument("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Testing arguments of recognized names doesn't cause exception.") {
std::string name = GENERATE(from_range(kNames));
CHECK_NOTHROW(argument_map.HasArgument(name));
}
}
}
}
SCENARIO("Test correctness of ArgumentMap::ArgumentsOf.",
"[ArgumentMap][ArgumentsOf][correctness]") {
GIVEN("An ArgumentMap containing various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("None of them has arguments.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kSetFlag")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kUnsetFlag")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoConverterPositional")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword")
== std::vector<std::string>{});
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("Partial argument lists are returned.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 6});
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 8});
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 2});
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 4});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 2});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 4});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 6});
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 8});
CHECK(argument_map.ArgumentsOf("kSetFlag")
== std::vector<std::string>{kArgs.begin(), kArgs.begin() + 1});
CHECK(argument_map.ArgumentsOf("kUnsetFlag")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag") == kArgs);
CHECK(argument_map.ArgumentsOf("kNoConverterPositional") == kArgs);
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kArgs);
}
}
WHEN("Default arguments are set for all parameters.") {
argument_map.SetDefaultArguments();
THEN("All default arguments are returned for non-flag parameters.") {
CHECK(argument_map.ArgumentsOf("kNoMinNoMaxNoArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxNoArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxNoArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs")
== kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxUnderfullArgs")
== kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs") == kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
== kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
== kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kSetFlag")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kUnsetFlag")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kMultipleSetFlag")
== std::vector<std::string>{});
CHECK(argument_map.ArgumentsOf("kNoConverterPositional")
== kDefaultArgs);
CHECK(argument_map.ArgumentsOf("kNoConverterKeyword") == kDefaultArgs);
}
}
}
}
SCENARIO("Test exceptions thrown by ArgumentMap::ArgumentsOf.",
"[ArgumentMap][ArgumentsOf][exceptions]") {
GIVEN("Parameters without default arguments.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs)(kNoMinYesMaxNoArgs)
(kNoMinYesMaxManyArgs)(kNoMinYesMaxFullArgs)
(kYesMinNoMaxNoArgs)(kYesMinNoMaxUnderfullArgs)
(kYesMinNoMaxMinArgs)
(kYesMinYesMaxNoArgs)(kYesMinYesMaxUnderfullArgs)
(kYesMinYesMaxMinArgs)(kYesMinYesMaxManyArgs)
(kYesMinYesMaxFullArgs)
(kSetFlag)(kUnsetFlag)(kMultipleSetFlag)
(kNoConverterPositional)(kNoConverterKeyword);
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.ArgumentsOf("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Getting arguments of recognized names doesn't cause exception.") {
std::string name = GENERATE(from_range(kNames));
CHECK_NOTHROW(argument_map.ArgumentsOf(name));
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("Testing arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.ArgumentsOf("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.ArgumentsOf("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Testing arguments of recognized names doesn't cause exception.") {
std::string name = GENERATE(from_range(kNames));
CHECK_NOTHROW(argument_map.ArgumentsOf(name));
}
}
}
}
SCENARIO("Test correctness of ArgumentMap::GetValue.",
"[ArgumentMap][GetValue][correctness]") {
GIVEN("An ArgumentMap containing various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("Calling function without specifying position gets first value.") {
CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs") == 1);
CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs") == 1);
CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs")
== TestType{1});
CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs") == 1l);
CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs")
== Approx(1.0f));
CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs")
== Approx(1.0f));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs")
== Approx(1.0));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs")
== Approx(1.0));
}
THEN("Specifying valid position will return the requested value.") {
int i = GENERATE(range(0, 7));
if (i < 2) {
CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs", i)
== TestType{std::stoi(kArgs.at(i))});
CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs", i)
== Approx(std::stof(kArgs.at(i))));
}
if (i < 4) {
CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs", i)
== std::stol(kArgs.at(i)));
CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs", i)
== Approx(std::stof(kArgs.at(i))));
}
if (i < 6) {
CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs", i)
== std::stoi(kArgs.at(i)));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs", i)
== Approx(std::stod(kArgs.at(i))));
}
if (i < 8) {
CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs", i)
== std::stoi(kArgs.at(i)));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs", i)
== Approx(std::stod(kArgs.at(i))));
}
}
}
WHEN("Default arguments are set for all parameters.") {
argument_map.SetDefaultArguments();
THEN("Calling function without specifying position gets first value.") {
CHECK(argument_map.GetValue<std::string>("kNoMinNoMaxNoArgs")
== converters::StringIdentity(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<std::string>("kNoMinYesMaxNoArgs")
== converters::StringIdentity(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs")
== std::stoi(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs")
== std::stoi(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxNoArgs")
== StringToTestType(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs")
== StringToTestType(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs")
== std::stol(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<long>("kYesMinYesMaxNoArgs")
== std::stol(kDefaultArgs.at(0)));
CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs")
== Approx(std::stof(kDefaultArgs.at(0))));
CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs")
== Approx(std::stof(kDefaultArgs.at(0))));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs")
== Approx(std::stod(kDefaultArgs.at(0))));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs")
== Approx(std::stod(kDefaultArgs.at(0))));
}
THEN("Specifying valid position will return the requested value.") {
int i = GENERATE(range(0, 8));
if (i < 2) {
CHECK(argument_map.GetValue<TestType>("kYesMinNoMaxUnderfullArgs", i)
== TestType{std::stoi(kDefaultArgs.at(i))});
CHECK(argument_map.GetValue<float>("kYesMinYesMaxUnderfullArgs", i)
== Approx(std::stof(kDefaultArgs.at(i))));
}
if (i < 4) {
CHECK(argument_map.GetValue<long>("kYesMinNoMaxMinArgs", i)
== std::stol(kDefaultArgs.at(i)));
CHECK(argument_map.GetValue<float>("kYesMinYesMaxMinArgs", i)
== Approx(std::stof(kDefaultArgs.at(i))));
}
if (i < 6) {
CHECK(argument_map.GetValue<int>("kNoMinYesMaxManyArgs", i)
== std::stoi(kDefaultArgs.at(i)));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxManyArgs", i)
== Approx(std::stod(kDefaultArgs.at(i))));
}
if (i < 8) {
CHECK(argument_map.GetValue<int>("kNoMinYesMaxFullArgs", i)
== std::stoi(kDefaultArgs.at(i)));
CHECK(argument_map.GetValue<double>("kYesMinYesMaxFullArgs", i)
== Approx(std::stod(kDefaultArgs.at(i))));
}
}
}
}
}
SCENARIO("Test exceptions thrown by ArgumentMap::GetValue.",
"[ArgumentMap][GetValue][exceptions]") {
GIVEN("An ArgumentMap containing various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<std::string>("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinYesMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinYesMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
}
THEN("Parameters without conversion functions cause exception.") {
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterKeyword"),
exceptions::ValueAccessError);
}
THEN("Accessing value beyond argument list's range causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<std::string>("kNoMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxFullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>(
"kYesMinNoMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinNoMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>(
"kYesMinYesMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>("kYesMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>("kYesMinYesMaxFullArgs"),
exceptions::ValueAccessError);
}
THEN("Flags cause exception.") {
CHECK_THROWS_AS(argument_map.GetValue<bool>("kSetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<bool>("kUnsetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<bool>("kMultipleSetFlag"),
exceptions::ValueAccessError);
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<std::string>("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinYesMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinYesMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
}
THEN("Parameters without conversion functions cause exception.") {
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterKeyword"),
exceptions::ValueAccessError);
}
THEN("Accessing value beyond argument list's range causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<std::string>("kNoMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxNoArgs", 0),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxManyArgs", 6),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kNoMinYesMaxFullArgs", 8),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>(
"kYesMinNoMaxNoArgs", kArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>(
"kYesMinNoMaxUnderfullArgs", 2),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinNoMaxMinArgs", 4),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>("kYesMinYesMaxNoArgs", 1),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>(
"kYesMinYesMaxUnderfullArgs", kArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>(
"kYesMinYesMaxMinArgs", kArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>(
"kYesMinYesMaxManyArgs", kArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>(
"kYesMinYesMaxFullArgs", kArgs.size()),
exceptions::ValueAccessError);
}
THEN("Flags cause exception.") {
CHECK_THROWS_AS(argument_map.GetValue<bool>("kSetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<bool>("kUnsetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<bool>("kMultipleSetFlag"),
exceptions::ValueAccessError);
}
}
WHEN("Default arguments are set for all parameters.") {
argument_map.SetDefaultArguments();
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<std::string>("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>("kNoMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>("kYesMinNoMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinNoMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kYesMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinYesMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinYesMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>("kYesMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
}
THEN("Parameters without conversion functions cause exception.") {
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>("kNoConverterKeyword"),
exceptions::ValueAccessError);
}
THEN("Accessing value beyond argument list's range causes exception.") {
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinNoMaxNoArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<std::string>(
"kNoMinYesMaxNoArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>(
"kNoMinYesMaxManyArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<int>(
"kNoMinYesMaxFullArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>(
"kYesMinNoMaxNoArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<TestType>(
"kYesMinNoMaxUnderfullArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinNoMaxMinArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<long>(
"kYesMinYesMaxNoArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>(
"kYesMinYesMaxUnderfullArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<float>(
"kYesMinYesMaxMinArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>(
"kYesMinYesMaxManyArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<double>(
"kYesMinYesMaxFullArgs", kDefaultArgs.size()),
exceptions::ValueAccessError);
}
THEN("Flags cause exception.") {
CHECK_THROWS_AS(argument_map.GetValue<bool>("kSetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<bool>("kUnsetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetValue<bool>("kMultipleSetFlag"),
exceptions::ValueAccessError);
}
}
}
}
SCENARIO("Test correctness of ArgumentMap::GetAllValues.",
"[ArgumentMap][GetAllValues][correctness]") {
GIVEN("An ArgumentMap containing various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("Empty value lists are returned.") {
CHECK(argument_map.GetAllValues<std::string>("kNoMinNoMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.GetAllValues<std::string>("kNoMinYesMaxNoArgs")
== std::vector<std::string>{});
CHECK(argument_map.GetAllValues<int>("kNoMinYesMaxManyArgs")
== std::vector<int>{});
CHECK(argument_map.GetAllValues<int>("kNoMinYesMaxFullArgs")
== std::vector<int>{});
CHECK(argument_map.GetAllValues<TestType>("kYesMinNoMaxNoArgs")
== std::vector<TestType>{});
CHECK(argument_map.GetAllValues<TestType>("kYesMinNoMaxUnderfullArgs")
== std::vector<TestType>{});
CHECK(argument_map.GetAllValues<long>("kYesMinNoMaxMinArgs")
== std::vector<long>{});
CHECK(argument_map.GetAllValues<long>("kYesMinYesMaxNoArgs")
== std::vector<long>{});
CHECK(argument_map.GetAllValues<float>("kYesMinYesMaxUnderfullArgs")
== std::vector<float>{});
CHECK(argument_map.GetAllValues<float>("kYesMinYesMaxMinArgs")
== std::vector<float>{});
CHECK(argument_map.GetAllValues<double>("kYesMinYesMaxManyArgs")
== std::vector<double>{});
CHECK(argument_map.GetAllValues<double>("kYesMinYesMaxFullArgs")
== std::vector<double>{});
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
std::vector<std::string> kNoMinNoMaxNoArgs_vals{
argument_map.GetAllValues<std::string>("kNoMinNoMaxNoArgs")};
std::vector<std::string> kNoMinYesMaxNoArgs_vals{
argument_map.GetAllValues<std::string>("kNoMinYesMaxNoArgs")};
std::vector<int> kNoMinYesMaxManyArgs_vals{
argument_map.GetAllValues<int>("kNoMinYesMaxManyArgs")};
std::vector<int> kNoMinYesMaxFullArgs_vals{
argument_map.GetAllValues<int>("kNoMinYesMaxFullArgs")};
std::vector<TestType> kYesMinNoMaxNoArgs_vals{
argument_map.GetAllValues<TestType>("kYesMinNoMaxNoArgs")};
std::vector<TestType> kYesMinNoMaxUnderfullArgs_vals{
argument_map.GetAllValues<TestType>("kYesMinNoMaxUnderfullArgs")};
std::vector<long> kYesMinNoMaxMinArgs_vals{
argument_map.GetAllValues<long>("kYesMinNoMaxMinArgs")};
std::vector<long> kYesMinYesMaxNoArgs_vals{
argument_map.GetAllValues<long>("kYesMinYesMaxNoArgs")};
std::vector<float> kYesMinYesMaxUnderfullArgs_vals{
argument_map.GetAllValues<float>("kYesMinYesMaxUnderfullArgs")};
std::vector<float> kYesMinYesMaxMinArgs_vals{
argument_map.GetAllValues<float>("kYesMinYesMaxMinArgs")};
std::vector<double> kYesMinYesMaxManyArgs_vals{
argument_map.GetAllValues<double>("kYesMinYesMaxManyArgs")};
std::vector<double> kYesMinYesMaxFullArgs_vals{
argument_map.GetAllValues<double>("kYesMinYesMaxFullArgs")};
THEN("Values for all arguments are returned.") {
CHECK(kNoMinNoMaxNoArgs_vals == std::vector<std::string>{});
CHECK(kNoMinYesMaxNoArgs_vals == std::vector<std::string>{});
CHECK(kYesMinNoMaxNoArgs_vals == std::vector<TestType>{});
CHECK(kYesMinYesMaxNoArgs_vals == std::vector<long>{});
for (int i = 0; i < 2; ++i) {
CHECK(kYesMinNoMaxUnderfullArgs_vals.at(i)
== StringToTestType(
argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs").at(i)));
CHECK(kYesMinYesMaxUnderfullArgs_vals.at(i)
== std::stof(argument_map.ArgumentsOf(
"kYesMinYesMaxUnderfullArgs").at(i)));
}
for (int i = 0; i < 4; ++i) {
CHECK(kYesMinNoMaxMinArgs_vals.at(i)
== std::stol(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
.at(i)));
CHECK(kYesMinYesMaxMinArgs_vals.at(i)
== std::stof(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
.at(i)));
}
for (int i = 0; i < 6; ++i) {
CHECK(kNoMinYesMaxManyArgs_vals.at(i)
== std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
.at(i)));
CHECK(kYesMinYesMaxManyArgs_vals.at(i)
== std::stod(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
.at(i)));
}
for (int i = 0; i < 8; ++i) {
CHECK(kNoMinYesMaxFullArgs_vals.at(i)
== std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
.at(i)));
CHECK(kYesMinYesMaxFullArgs_vals.at(i)
== std::stod(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
.at(i)));
}
}
}
WHEN("Default arguments are set for all parameters.") {
argument_map.SetDefaultArguments();
std::vector<std::string> kNoMinNoMaxNoArgs_vals{
argument_map.GetAllValues<std::string>("kNoMinNoMaxNoArgs")};
std::vector<std::string> kNoMinYesMaxNoArgs_vals{
argument_map.GetAllValues<std::string>("kNoMinYesMaxNoArgs")};
std::vector<int> kNoMinYesMaxManyArgs_vals{
argument_map.GetAllValues<int>("kNoMinYesMaxManyArgs")};
std::vector<int> kNoMinYesMaxFullArgs_vals{
argument_map.GetAllValues<int>("kNoMinYesMaxFullArgs")};
std::vector<TestType> kYesMinNoMaxNoArgs_vals{
argument_map.GetAllValues<TestType>("kYesMinNoMaxNoArgs")};
std::vector<TestType> kYesMinNoMaxUnderfullArgs_vals{
argument_map.GetAllValues<TestType>("kYesMinNoMaxUnderfullArgs")};
std::vector<long> kYesMinNoMaxMinArgs_vals{
argument_map.GetAllValues<long>("kYesMinNoMaxMinArgs")};
std::vector<long> kYesMinYesMaxNoArgs_vals{
argument_map.GetAllValues<long>("kYesMinYesMaxNoArgs")};
std::vector<float> kYesMinYesMaxUnderfullArgs_vals{
argument_map.GetAllValues<float>("kYesMinYesMaxUnderfullArgs")};
std::vector<float> kYesMinYesMaxMinArgs_vals{
argument_map.GetAllValues<float>("kYesMinYesMaxMinArgs")};
std::vector<double> kYesMinYesMaxManyArgs_vals{
argument_map.GetAllValues<double>("kYesMinYesMaxManyArgs")};
std::vector<double> kYesMinYesMaxFullArgs_vals{
argument_map.GetAllValues<double>("kYesMinYesMaxFullArgs")};
THEN("Values for all arguments are returned.") {
for (int i = 0; i < static_cast<int>(kDefaultArgs.size()); ++i) {
CHECK(kNoMinNoMaxNoArgs_vals.at(i)
== converters::StringIdentity(
argument_map.ArgumentsOf("kNoMinNoMaxNoArgs").at(i)));
CHECK(kNoMinYesMaxNoArgs_vals.at(i)
== converters::StringIdentity(
argument_map.ArgumentsOf("kNoMinYesMaxNoArgs").at(i)));
CHECK(kNoMinYesMaxManyArgs_vals.at(i)
== std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxManyArgs")
.at(i)));
CHECK(kNoMinYesMaxFullArgs_vals.at(i)
== std::stoi(argument_map.ArgumentsOf("kNoMinYesMaxFullArgs")
.at(i)));
CHECK(kYesMinNoMaxNoArgs_vals.at(i)
== StringToTestType(
argument_map.ArgumentsOf("kYesMinNoMaxNoArgs").at(i)));
CHECK(kYesMinNoMaxUnderfullArgs_vals.at(i)
== StringToTestType(
argument_map.ArgumentsOf("kYesMinNoMaxUnderfullArgs").at(i)));
CHECK(kYesMinNoMaxMinArgs_vals.at(i)
== std::stol(argument_map.ArgumentsOf("kYesMinNoMaxMinArgs")
.at(i)));
CHECK(kYesMinYesMaxNoArgs_vals.at(i)
== std::stol(argument_map.ArgumentsOf("kYesMinYesMaxNoArgs")
.at(i)));
CHECK(kYesMinYesMaxUnderfullArgs_vals.at(i)
== std::stof(argument_map.ArgumentsOf(
"kYesMinYesMaxUnderfullArgs").at(i)));
CHECK(kYesMinYesMaxMinArgs_vals.at(i)
== std::stof(argument_map.ArgumentsOf("kYesMinYesMaxMinArgs")
.at(i)));
CHECK(kYesMinYesMaxManyArgs_vals.at(i)
== std::stod(argument_map.ArgumentsOf("kYesMinYesMaxManyArgs")
.at(i)));
CHECK(kYesMinYesMaxFullArgs_vals.at(i)
== std::stod(argument_map.ArgumentsOf("kYesMinYesMaxFullArgs")
.at(i)));
}
}
}
}
}
SCENARIO("Test exceptions thrown by ArgumentMap::GetAllValues.",
"[ArgumentMap][GetAllValues][exceptions]") {
GIVEN("An ArgumentMap containing various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>(
"kNoMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>(
"kNoMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>("kYesMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>(
"kYesMinNoMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kYesMinNoMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kYesMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(
"kYesMinYesMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(
"kYesMinYesMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>(
"kYesMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>(
"kYesMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
}
THEN("Parameters without conversion functions cause exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kNoConverterKeyword"),
exceptions::ValueAccessError);
}
THEN("Flags cause exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kSetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kUnsetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kMultipleSetFlag"),
exceptions::ValueAccessError);
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>(
"kNoMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>(
"kNoMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>("kYesMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>(
"kYesMinNoMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kYesMinNoMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kYesMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(
"kYesMinYesMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(
"kYesMinYesMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>(
"kYesMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>(
"kYesMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
}
THEN("Parameters without conversion functions cause exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kNoConverterKeyword"),
exceptions::ValueAccessError);
}
THEN("Flags cause exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kSetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kUnsetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kMultipleSetFlag"),
exceptions::ValueAccessError);
}
}
WHEN("Default arguments are set for all parameters.") {
argument_map.SetDefaultArguments();
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<double>("kNoMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>(
"kNoMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<std::string>(
"kNoMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>("kYesMinNoMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<int>(
"kYesMinNoMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kYesMinNoMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kYesMinYesMaxNoArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(
"kYesMinYesMaxUnderfullArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<long>(
"kYesMinYesMaxMinArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>(
"kYesMinYesMaxManyArgs"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<float>(
"kYesMinYesMaxFullArgs"),
exceptions::ParameterAccessError);
}
THEN("Parameters without conversion functions cause exception.") {
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<TestType>(
"kNoConverterKeyword"),
exceptions::ValueAccessError);
}
THEN("Flags cause exception if arguments are assigned.") {
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kSetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kUnsetFlag"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.GetAllValues<bool>("kMultipleSetFlag"),
exceptions::ValueAccessError);
}
}
}
}
SCENARIO("Test correctness of ArgumentMap::IsSet.",
"[ArgumentMap][IsSet][correctness]") {
GIVEN("An ArgumentMap containing various flags.") {
ParameterMap parameter_map;
parameter_map(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("Flags are not set.") {
CHECK_FALSE(argument_map.IsSet("kSetFlag"));
CHECK_FALSE(argument_map.IsSet("kUnsetFlag"));
CHECK_FALSE(argument_map.IsSet("kMultipleSetFlag"));
}
}
WHEN("Argument lists are partially filled.") {
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
}
THEN("Non-empty argument lists mean that flag is set.") {
CHECK(argument_map.IsSet("kSetFlag"));
CHECK_FALSE(argument_map.IsSet("kUnsetFlag"));
CHECK(argument_map.IsSet("kMultipleSetFlag"));
}
}
WHEN("Default arguments are set for all parameters.") {
argument_map.SetDefaultArguments();
THEN("Default arguments are never set for flags, so flags are not set.") {
CHECK_FALSE(argument_map.IsSet("kSetFlag"));
CHECK_FALSE(argument_map.IsSet("kUnsetFlag"));
CHECK_FALSE(argument_map.IsSet("kMultipleSetFlag"));
}
}
}
}
SCENARIO("Test exceptions thrown by ArgumentMap::IsSet.",
"[ArgumentMap][IsSet][exceptions]") {
GIVEN("An ArgumentMap containing various parameters.") {
ParameterMap parameter_map;
parameter_map(kNoMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kNoMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinNoMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxNoArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxUnderfullArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxMinArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxManyArgs.SetDefault(kDefaultArgs))
(kYesMinYesMaxFullArgs.SetDefault(kDefaultArgs))
(kSetFlag.SetDefault(kDefaultArgs))
(kUnsetFlag.SetDefault(kDefaultArgs))
(kMultipleSetFlag.SetDefault(kDefaultArgs))
(kNoConverterPositional.SetDefault(kDefaultArgs))
(kNoConverterKeyword.SetDefault(kDefaultArgs));
ArgumentMap argument_map(std::move(parameter_map));
WHEN("Argument lists are empty.") {
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.IsSet("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.IsSet("kNoMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxFullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxFullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoConverterKeyword"),
exceptions::ValueAccessError);
}
}
WHEN("Argument lists are partially filled.") {
for (int i = 0; i < 2; ++i) {
argument_map.AddArgument("kYesMinNoMaxUnderfullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxUnderfullArgs", kArgs.at(i));
}
for (int i = 0; i < 4; ++i) {
argument_map.AddArgument("kYesMinNoMaxMinArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxMinArgs", kArgs.at(i));
}
for (int i = 0; i < 6; ++i) {
argument_map.AddArgument("kNoMinYesMaxManyArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxManyArgs", kArgs.at(i));
}
for (int i = 0; i < 8; ++i) {
argument_map.AddArgument("kNoMinYesMaxFullArgs", kArgs.at(i));
argument_map.AddArgument("kYesMinYesMaxFullArgs", kArgs.at(i));
}
argument_map.AddArgument("kSetFlag", kArgs.at(0));
for (const std::string& arg : kArgs) {
argument_map.AddArgument("kMultipleSetFlag", arg);
argument_map.AddArgument("kNoConverterPositional", arg);
argument_map.AddArgument("kNoConverterKeyword", arg);
}
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.IsSet("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.IsSet("kNoMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxFullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxFullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoConverterKeyword"),
exceptions::ValueAccessError);
}
}
WHEN("Default arguments are set for all parameters.") {
argument_map.SetDefaultArguments();
THEN("Getting arguments of unknown parameters causes exception.") {
CHECK_THROWS_AS(argument_map.IsSet("unknown_name"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("foo"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("b"),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet(""),
exceptions::ParameterAccessError);
CHECK_THROWS_AS(argument_map.IsSet("bazinga"),
exceptions::ParameterAccessError);
}
THEN("Mismatching types causes exception.") {
CHECK_THROWS_AS(argument_map.IsSet("kNoMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoMinYesMaxFullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinNoMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxNoArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxUnderfullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxMinArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxManyArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kYesMinYesMaxFullArgs"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoConverterPositional"),
exceptions::ValueAccessError);
CHECK_THROWS_AS(argument_map.IsSet("kNoConverterKeyword"),
exceptions::ValueAccessError);
}
}
}
}
} // namespace
} // namespace test
} // namespace arg_parse_convert | 50.069767 | 82 | 0.639332 | JasperBraun |
39ee83e54d46b60df4100a62c6ceedca042acc2d | 5,627 | cpp | C++ | poker/src/DecisionMaker.cpp | JMassing/Pokerbot | 40b2e4756fc8ef1be4af4d649deb6035a9774bdc | [
"MIT"
] | 1 | 2021-12-10T06:27:47.000Z | 2021-12-10T06:27:47.000Z | poker/src/DecisionMaker.cpp | JMassing/Pokerbot | 40b2e4756fc8ef1be4af4d649deb6035a9774bdc | [
"MIT"
] | null | null | null | poker/src/DecisionMaker.cpp | JMassing/Pokerbot | 40b2e4756fc8ef1be4af4d649deb6035a9774bdc | [
"MIT"
] | null | null | null | #include "DecisionMaker.hpp"
#include <iostream>
namespace poker{
void DecisionMaker::decideBetsize()
{
int bet = 0;
double winning_probability = this->data_.probability.first + this->data_.probability.second;
if(this->data_.players.at(0).current_decision == CALL)
{
bet =
this->data_.highest_bet <= this->data_.players.at(0).money ?
(this->data_.highest_bet - this->data_.players.at(0).money_bet_in_phase)
: this->data_.players.at(0).money;
}
else if(this->data_.players.at(0).current_decision == RAISE)
{
if(winning_probability <= 80)
{
bet =
(static_cast<double>(this->data_.pot_size)/3.0 > 3 * this->big_blind_) ?
static_cast<int>(static_cast<double>(this->data_.pot_size)/3.0) : 3 * this->big_blind_;
}
else if(winning_probability > 80)
{
bet =
(2 * this->data_.highest_bet > 2 * this->data_.pot_size) ?
2 * this->data_.highest_bet : 2 * this->data_.pot_size;
}
else
{
//do nothing
}
// Check if robot went all in
bet = bet <= this->data_.players.at(0).money ? bet : this->data_.players.at(0).money;
this->data_.players.at(0).current_decision = HAS_RAISED;
}
else
{
//do nothing
}
// Other player went all in
if( this->data_.players.at(1).is_all_in &&
(this->data_.players.at(0).current_decision == CALL || this->data_.players.at(0).current_decision == RAISE || this->data_.players.at(0).current_decision == HAS_RAISED) )
{
// Check if robot has more money than player who went all in
if( this->data_.players.at(0).money >= this->data_.players.at(1).current_bet)
{
bet = this->data_.players.at(1).money_bet_in_phase - this->data_.players.at(0).money_bet_in_phase;
}
else
{
this->data_.players.at(0).money;
}
// set robot player decision to call
this->data_.players.at(0).current_decision = CALL;
}
this->data_.players.at(0).current_bet = bet;
if( bet + this->data_.players.at(0).money_bet_in_phase > this->data_.highest_bet)
{
this->data_.highest_bet = bet + this->data_.players.at(0).money_bet_in_phase;
}
this->data_.players.at(0).money -= this->data_.players.at(0).current_bet;
this->data_.players.at(0).money_bet_in_phase += this->data_.players.at(0).current_bet;
}
void DecisionMaker::decideMove()
{
double winning_probability = this->data_.probability.first + this->data_.probability.second;
if(winning_probability <= 40)
{
if(this->data_.highest_bet > this->data_.players.at(0).money_bet_in_phase)
{
// Oponent has raised
this->data_.players.at(0).current_decision = FOLD;
}
else
{
// Nobody has raised
this->data_.players.at(0).current_decision = CHECK;
}
}
else if(winning_probability > 40 && winning_probability <= 60)
{
if (this->data_.highest_bet > this->data_.players.at(0).money_bet_in_phase &&
this->data_.highest_bet >= static_cast<double>(this->data_.pot_size)/3.0 &&
this->data_.highest_bet >= 3*this->big_blind_ )
{
// Oponent has raised for too much money
this->data_.players.at(0).current_decision = FOLD;
}
else if(this->data_.highest_bet == this->data_.players.at(0).money_bet_in_phase)
{
// Nobody has raised
this->data_.players.at(0).current_decision = CHECK;
}
else
{
// Oponent has raised but not too much
this->data_.players.at(0).current_decision = CALL;
}
}
else if(winning_probability > 60 && winning_probability <= 80)
{
if (this->data_.highest_bet > this->data_.players.at(0).money_bet_in_phase &&
this->data_.highest_bet >= 1/3 * this->data_.pot_size &&
this->data_.highest_bet >= 3*this->big_blind_ )
{
// Only call if oponent raised for a high amount
this->data_.players.at(0).current_decision = CALL;
}
else
{
// raise
this->data_.players.at(0).current_decision = RAISE;
}
}
else if(winning_probability > 80)
{
this->data_.players.at(0).current_decision = RAISE;
}
else
{
}
//set decision to call if robot has to go all in an decided to raise
if(this->data_.highest_bet >= this->data_.players.at(0).money && this->data_.players.at(0).current_decision == RAISE)
{
this->data_.players.at(0).current_decision = CALL;
}
}
void DecisionMaker::makeDecision()
{
this->decideMove();
this->decideBetsize();
}
}// end namespace poker | 36.538961 | 182 | 0.513773 | JMassing |
39f60abaee0d398121d6905751915372ae22d6dc | 11,163 | cpp | C++ | CReader_bin.cpp | MechLabEngineering/SICKRPi-Scanner | 19d7603a7bee444c8cfbd646f9773178ecf2e188 | [
"MIT"
] | null | null | null | CReader_bin.cpp | MechLabEngineering/SICKRPi-Scanner | 19d7603a7bee444c8cfbd646f9773178ecf2e188 | [
"MIT"
] | null | null | null | CReader_bin.cpp | MechLabEngineering/SICKRPi-Scanner | 19d7603a7bee444c8cfbd646f9773178ecf2e188 | [
"MIT"
] | null | null | null | /*
* CReader.cpp
* save laser data to binary file
*
* Created on: 22.12.2014
* Author: Markus
*/
#include <iostream>
#include <string>
#include "CReader.h"
#include <sstream>
#include <fstream>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <math.h>
#include <list>
#include <octomap/octomap.h>
#include <octomap/OcTree.h>
#include <octomap/Pointcloud.h>
#include "time.h"
#include "ip_connection.h"
#include "brick_imu.h"
#include <boost/chrono/thread_clock.hpp>
using namespace boost::chrono;
//
#define PI 3.14159265
#define CONFIG "/media/usb0/config.cfg"
#define HOST "localhost"
#define PORT 4223
#define CB_AV_PERIOD 10
#define DEBUG 1
std::fstream logfile;
std::stringstream tmpstr;
boost::mutex mtx_da;
std::stringstream ss;
int data_av = 0;
bool is_cb_angular = false;
bool is_imu_connected;
using std::string;
using namespace octomap;
IPConnection ipcon;
IMU imu;
// trim a string
const std::string trim( const std::string& s)
{
std::string::size_type first = s.find_first_not_of( ' ');
if( first == std::string::npos) {
return std::string();
}
else {
std::string::size_type last = s.find_last_not_of( ' '); /// must succeed
return s.substr( first, last - first + 1);
}
}
void debugMessage(int level, string message)
{
if (level >= DEBUG)
std::cerr << message << std::endl;
return;
}
// constructor
CReader::CReader()
{
scancycles = 0;
is_imu_connected = false;
ip_adress = "192.168.0.1";
port = 12002;
convergence = 0;
laserscanner = NULL;
// set angle filter
angle_max = 0*PI/180; // scanner max 50
angle_min = -60*PI/180; // scanner min -60
maxmin = false;
duration = false;
writebt = false;
writecsv = false;
is_indoor = false;
if (readConfig())
debugMessage(2,"config successfully readed!");
else
debugMessage(2, "no config file!");
return;
}
// read config file
int CReader::readConfig()
{
std::ifstream fh;
std::string line;
size_t pos = 0;
std::string key, val;
fh.open(CONFIG, std::ios::in);
if (!fh.is_open()) {
fh.open("config.cfg", std::ios::in);
if (!fh.is_open()) {
return FALSE;
}
}
debugMessage(2, "read config...");
while (getline(fh,line)) {
pos = line.find("=");
key = trim(line.substr(0,pos));
val = trim(line.substr(pos+1));
try {
if (key.compare("ip") == 0) {
ip_adress = val;
} else if (key.compare("port") == 0) {
port = atoi(val.c_str());
} else if (key.compare("maxmin") == 0) {
if (val.compare("true") == 0)
maxmin = true;
else
maxmin = false;
} else if (key.compare("writebt") == 0) {
if (val.compare("true") == 0)
writebt = true;
} else if (key.compare("btpath") == 0) {
bt_path = val;
} else if (key.compare("convergence") == 0) {
convergence = atoi(val.c_str());
} else if (key.compare("location") == 0) {
if (val.compare("indoor") == 0) {
is_indoor = true;
}
} else if (key.compare("writecsv") == 0) {
if (val.compare("true") == 0) {
writecsv = true;
}
} else if (key.compare("minangle") == 0) {
angle_min = atoi(val.c_str())*PI/180.0;
} else if (key.compare("maxangle") == 0) {
angle_max = atoi(val.c_str())*PI/180.0;
}
} catch (...) {
tmpstr << "unknown parameter:" << key;
debugMessage(4, tmpstr.str());
}
}
fh.close();
return TRUE;
}
CReader::~CReader()
{
// release sensor
//if (laserscanner != NULL) {
// mtx_da.lock();
releaseSensor();
// mtx_da.unlock();
//}
usleep(200);
logfile.close();
//std::stringstream path;
//path << "/home/pi/SICKRPi-Scanner/" << ss.str();
pid_t pid;
if((pid = fork()) < 0) {
fprintf(stderr, "Fehler... %s\n", strerror(errno));
}
else if(pid == 0) {
//Kindprozess "/media/usb0/"
//execl("/usr/bin/sudo", "cp", "/bin/cp", path.str().c_str(), bt_path.c_str(), NULL);
execl("/usr/bin/sudo", "sh", "/bin/sh", "/home/pi/SICKRPi-Scanner/tools/cpy_bin.sh", ss.str().c_str(), bt_path.c_str(), NULL);
}
else {
// Elternprozess
if (is_imu_connected) {
// turn off imu leds
imu_leds_off(&imu);
// release ipcon
imu_set_quaternion_period(&imu, 0);
imu_set_angular_velocity_period(&imu, 0);
imu_destroy(&imu);
}
ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally
}
//ret = execl("/usr/bin/sudo", "rm", "/bin/rm", path.str().c_str(), NULL);
}
// TINKERFORGE
void cb_connected(uint8_t connect_reason, void *user_data)
{
// ...then trigger enumerate
if (is_imu_connected == false)
ipcon_enumerate(&ipcon);
}
void cb_angular_velocity(int16_t x, int16_t y, int16_t z, void *user_data)
{
mtx_da.lock();
is_cb_angular = true;
//std::cout << y << std::endl;
if (abs(x) > 50 || abs(y) > 50 || abs(z) > 50) {
//std::cout << "adjust" << std::endl;
//is_imu_adjustment = true;
imu_set_convergence_speed(&imu, 300);
usleep(1000000);
imu_set_convergence_speed(&imu, 0);
//is_imu_adjustment = false;
//std::cout << "adjust finished" << std::endl;
} else {
//std::cout << "b" << std::endl;
imu_set_convergence_speed(&imu, 0);
//is_imu_adjustment = false;
}
is_cb_angular = false;
mtx_da.unlock();
return;
}
// print incoming enumeration information
void cb_enumerate(const char *uid, const char *connected_uid,
char position, uint8_t hardware_version[3],
uint8_t firmware_version[3], uint16_t device_identifier,
uint8_t enumeration_type, void *user_data)
{
int is_indoor = *(int*)user_data;
if(enumeration_type == IPCON_ENUMERATION_TYPE_DISCONNECTED) {
printf("\n");
return;
}
// check if device is an imu
if(device_identifier == IMU_DEVICE_IDENTIFIER) {
tmpstr << "found IMU with UID:" << uid;
debugMessage(2, tmpstr.str());
if (is_imu_connected) {
debugMessage(2, "IMU already connected!");
return;
}
imu_create(&imu, uid, &ipcon);
imu_set_convergence_speed(&imu,60);
if (!is_indoor) {
imu_set_angular_velocity_period(&imu, CB_AV_PERIOD);
imu_register_callback(&imu,
IMU_CALLBACK_ANGULAR_VELOCITY,
(void *)cb_angular_velocity,
NULL);
}
imu_leds_off(&imu);
is_imu_connected = true;
}
}
int CReader::init()
{
// set bounding box filter
bb_x_max = 70.0;
bb_x_min = 0.0;
bb_y_max = 200.0;
bb_y_min = -200.0;
// activate both filter
filter_angle = true;
filter_bbox = true;
// init tinkerforge ------------------------------------------------
// create IP connection
ipcon_create(&ipcon);
// Connect to brickd
if(ipcon_connect(&ipcon, HOST, PORT) < 0) {
debugMessage(4, "could not connect to brickd!");
return false;
}
// Register connected callback to "cb_connected"
ipcon_register_callback(&ipcon,
IPCON_CALLBACK_CONNECTED,
(void *)cb_connected,
&ipcon);
// Register enumeration callback to "cb_enumerate"
ipcon_register_callback(&ipcon,
IPCON_CALLBACK_ENUMERATE,
(void*)cb_enumerate,
&is_indoor);
ipcon_enumerate(&ipcon);
// sleep
usleep(7000000);
// check if imu is connected
if (!is_imu_connected) {
debugMessage(4,"no IMU connected!");
return false;
}
// set convergence after initial stage
imu_set_convergence_speed(&imu,convergence);
usleep(50000);
// raw data file
time_t t;
struct tm *ts;
char buff[128];
// build filename
t = time(NULL);
ts = localtime(&t);
strftime(buff, 80, "rawdata_%Y_%m_%d-%H_%M_%S.bin", ts);
ss << "/home/pi/SICKRPi-Scanner/scans/" << buff;
logfile.open(ss.str().c_str(), std::ios::out | std::ios::trunc);
logfile.close();
logfile.open(ss.str().c_str(), std::ios::app | std::ios::binary | std::ios::out);
// init sensor
if(!initSensor()) {
debugMessage(4, "couldn't connect to laserscanner!");
return false;
}
imu_leds_on(&imu);
return true;
}
int CReader::initSensor()
{
if (!ibeo::ibeoLUX::IbeoLUX::getInstance()) {
ibeo::ibeoLUX::IbeoLUX::initInstance(this->ip_adress, this->port, 1);
debugMessage(4, "laserscanner searching...!");
laserscanner = ibeo::ibeoLUX::IbeoLUX::getInstance();
try {
laserscanner->connect();
laserscanner->startMeasuring();
} catch (...) {
debugMessage(4, "laserscanner not found!");
return false;
}
}
if (laserscanner->getConnectionStatus()) {
debugMessage(4, "laserscanner connected!");
} else {
return false;
}
if (!laserscanner->getMeasuringStatus())
return false;
laserscanner->ibeoLaserDataAvailable.connect(boost::bind(&CReader::newLaserData, this, _1));
return true;
}
float xAngle, yAngle, zAngle;
void CReader::storeImuData()
{
float x, y, z, w;
imu_get_quaternion(&imu, &x, &y, &z, &w);
// use octomath to calc quaternion
// y, z, x
octomath::Quaternion q(w,x,y,z);
octomath::Vector3 v(0.0,0.0,0.0);
octomath::Pose6D pp(v, q);
xAngle = pp.roll();
yAngle = pp.yaw();
zAngle = pp.pitch();
//xAngle = pp.roll();
//yAngle = pp.pitch();
//zAngle = pp.yaw()*-1; // invert to correct mirroring
return;
}
void CReader::newLaserData(ibeo::ibeoLaserDataAbstractSmartPtr dat)
{
if (is_cb_angular)
return;
mtx_da.lock();
unsigned int scanpoints = dat->getNumberOfScanpoints();
short int angleTicksPerRotation = dat->getAngleTicksPerRotation();
//thread_clock::time_point start = thread_clock::now();
// get IMU data
storeImuData();
logfile.write(reinterpret_cast<const char*>(&scanpoints), sizeof(scanpoints));
logfile.write(reinterpret_cast<const char*>(&xAngle), sizeof(xAngle));
logfile.write(reinterpret_cast<const char*>(&yAngle), sizeof(yAngle));
logfile.write(reinterpret_cast<const char*>(&zAngle), sizeof(zAngle));
logfile.write(reinterpret_cast<const char*>(&angleTicksPerRotation), sizeof(angleTicksPerRotation));
dat->writeAllScanPointsToBinFile(&logfile);
data_av = 1;
// calc delay
//thread_clock::time_point stop = thread_clock::now();
//printf("| Time elapsed: %ld ms \n", duration_cast<milliseconds>(stop - start).count());
mtx_da.unlock();
return;
}
// get octomap data for lds server
int CReader::getOctomap(char* buff)
{
return 0;
}
int CReader::writeDataBT()
{
return 0;
}
void CReader::releaseSensor()
{
// stop laserscanner
laserscanner->stopMeasuring();
usleep(50000);
laserscanner->releaseInstance();
return;
}
// get cpu load
int CReader::getCPULoad()
{
int fd = 0;
char buff[1024];
float load;
fd = open("/proc/loadavg", O_RDONLY);
if (fd < 0)
return -1;
read(fd,buff,sizeof(buff)-1);
sscanf(buff, "%f", &load);
close(fd);
return (int)(load*100);
}
// get ram load
int CReader::getRAMLoad(int* total, int* free)
{
FILE* fp = NULL;
char buff[256];
char name[100], unit[16];
if ((fp = fopen("/proc/meminfo","r")) == NULL) {
perror("no file meminfo!");
return 0;
}
fgets(buff, sizeof(buff), fp);
sscanf(buff, "%s %d %s\n", name, total, unit);
fgets(buff, sizeof(buff), fp);
sscanf(buff, "%s %d %s\n", name, free, unit);
//std::cout << "Total:" << *total << " Kb" << std::endl;
//std::cout << "Free:" << *free << " Kb" << std::endl;
//std::cout << "InUse:" << ((*total-*free)/1024) << " Mb" << std::endl;
fclose(fp);
return 1;
}
| 21.717899 | 128 | 0.636746 | MechLabEngineering |
39fb491fd6f308f2fc4e92febae3038da1953a38 | 11,209 | cpp | C++ | src/engine/job_system.cpp | nemerle/LumixEngine | 6cfee07c4268c15994c7171cb5625179b1f369e2 | [
"MIT"
] | null | null | null | src/engine/job_system.cpp | nemerle/LumixEngine | 6cfee07c4268c15994c7171cb5625179b1f369e2 | [
"MIT"
] | null | null | null | src/engine/job_system.cpp | nemerle/LumixEngine | 6cfee07c4268c15994c7171cb5625179b1f369e2 | [
"MIT"
] | null | null | null | #include "engine/atomic.h"
#include "engine/array.h"
#include "engine/engine.h"
#include "engine/fibers.h"
#include "engine/allocator.h"
#include "engine/log.h"
#include "engine/math.h"
#include "engine/os.h"
#include "engine/sync.h"
#include "engine/thread.h"
#include "engine/profiler.h"
#include "job_system.h"
namespace Lumix::jobs {
struct Job {
void (*task)(void*) = nullptr;
void* data = nullptr;
Signal* dec_on_finish;
u8 worker_index;
};
struct WorkerTask;
struct FiberDecl {
int idx;
Fiber::Handle fiber = Fiber::INVALID_FIBER;
Job current_job;
};
#ifdef _WIN32
static void __stdcall manage(void* data);
#else
static void manage(void* data);
#endif
struct System
{
System(IAllocator& allocator)
: m_allocator(allocator)
, m_workers(allocator)
, m_job_queue(allocator)
, m_ready_fibers(allocator)
, m_free_fibers(allocator)
, m_backup_workers(allocator)
{}
Lumix::Mutex m_sync;
Lumix::Mutex m_job_queue_sync;
Array<WorkerTask*> m_workers;
Array<WorkerTask*> m_backup_workers;
Array<Job> m_job_queue;
FiberDecl m_fiber_pool[512];
Array<FiberDecl*> m_free_fibers;
Array<FiberDecl*> m_ready_fibers;
IAllocator& m_allocator;
};
static Local<System> g_system;
static volatile i32 g_generation = 0;
static thread_local WorkerTask* g_worker = nullptr;
#pragma optimize( "", off )
WorkerTask* getWorker()
{
return g_worker;
}
#pragma optimize( "", on )
struct WorkerTask : Thread
{
WorkerTask(System& system, u8 worker_index)
: Thread(system.m_allocator)
, m_system(system)
, m_worker_index(worker_index)
, m_job_queue(system.m_allocator)
, m_ready_fibers(system.m_allocator)
{
}
int task() override
{
profiler::showInProfiler(true);
g_worker = this;
Fiber::initThread(start, &m_primary_fiber);
return 0;
}
#ifdef _WIN32
static void __stdcall start(void* data)
#else
static void start(void* data)
#endif
{
g_system->m_sync.enter();
FiberDecl* fiber = g_system->m_free_fibers.back();
g_system->m_free_fibers.pop();
if (!Fiber::isValid(fiber->fiber)) {
fiber->fiber = Fiber::create(64 * 1024, manage, fiber);
}
getWorker()->m_current_fiber = fiber;
Fiber::switchTo(&getWorker()->m_primary_fiber, fiber->fiber);
}
bool m_finished = false;
FiberDecl* m_current_fiber = nullptr;
Fiber::Handle m_primary_fiber;
System& m_system;
Array<Job> m_job_queue;
Array<FiberDecl*> m_ready_fibers;
u8 m_worker_index;
bool m_is_enabled = false;
bool m_is_backup = false;
};
struct Waitor {
Waitor* next;
FiberDecl* fiber;
};
template <bool ZERO>
LUMIX_FORCE_INLINE static bool trigger(Signal* signal)
{
Waitor* waitor;
{
Lumix::MutexGuard lock(g_system->m_sync);
if constexpr (ZERO) {
signal->counter = 0;
}
else {
--signal->counter;
ASSERT(signal->counter >= 0);
if (signal->counter > 0) return false;
}
waitor = signal->waitor;
signal->waitor = nullptr;
}
if (!waitor) return false;
bool wake_all = false;
{
Lumix::MutexGuard queue_lock(g_system->m_job_queue_sync);
while (waitor) {
Waitor* next = waitor->next;
const u8 worker = waitor->fiber->current_job.worker_index;
if (worker == ANY_WORKER) {
g_system->m_ready_fibers.push(waitor->fiber);
wake_all = true;
}
else {
WorkerTask* worker = g_system->m_workers[waitor->fiber->current_job.worker_index % g_system->m_workers.size()];
worker->m_ready_fibers.push(waitor->fiber);
if(!wake_all) worker->wakeup();
}
waitor = next;
}
}
if (wake_all) {
for (WorkerTask* worker : g_system->m_backup_workers) {
if (worker->m_is_enabled) worker->wakeup();
}
for (WorkerTask* worker : g_system->m_workers) {
worker->wakeup();
}
}
return true;
}
void enableBackupWorker(bool enable)
{
Lumix::MutexGuard lock(g_system->m_sync);
for (WorkerTask* task : g_system->m_backup_workers) {
if (task->m_is_enabled != enable) {
task->m_is_enabled = enable;
return;
}
}
ASSERT(enable);
WorkerTask* task = LUMIX_NEW(g_system->m_allocator, WorkerTask)(*g_system, 0xff);
if (task->create("Backup worker", false)) {
g_system->m_backup_workers.push(task);
task->m_is_enabled = true;
task->m_is_backup = true;
}
else {
logError("Job system backup worker failed to initialize.");
LUMIX_DELETE(g_system->m_allocator, task);
}
}
LUMIX_FORCE_INLINE static bool setRedEx(Signal* signal) {
ASSERT(signal);
ASSERT(signal->counter <= 1);
bool res = compareAndExchange(&signal->counter, 1, 0);
if (res) {
signal->generation = atomicIncrement(&g_generation);
}
return res;
}
void setRed(Signal* signal) {
setRedEx(signal);
}
void setGreen(Signal* signal) {
ASSERT(signal);
ASSERT(signal->counter <= 1);
const u32 gen = signal->generation;
if (trigger<true>(signal)){
profiler::signalTriggered(gen);
}
}
void run(void* data, void(*task)(void*), Signal* on_finished)
{
runEx(data, task, on_finished, ANY_WORKER);
}
void runEx(void* data, void(*task)(void*), Signal* on_finished, u8 worker_index)
{
Job job;
job.data = data;
job.task = task;
job.worker_index = worker_index != ANY_WORKER ? worker_index % getWorkersCount() : worker_index;
job.dec_on_finish = on_finished;
if (on_finished) {
Lumix::MutexGuard guard(g_system->m_sync);
++on_finished->counter;
if (on_finished->counter == 1) {
on_finished->generation = atomicIncrement(&g_generation);
}
}
if (worker_index != ANY_WORKER) {
WorkerTask* worker = g_system->m_workers[worker_index % g_system->m_workers.size()];
{
Lumix::MutexGuard lock(g_system->m_job_queue_sync);
worker->m_job_queue.push(job);
}
worker->wakeup();
return;
}
{
Lumix::MutexGuard lock(g_system->m_job_queue_sync);
g_system->m_job_queue.push(job);
}
for (WorkerTask* worker : g_system->m_workers) {
worker->wakeup();
}
for (WorkerTask* worker : g_system->m_backup_workers) {
if (worker->m_is_enabled) worker->wakeup();
}
}
#ifdef _WIN32
static void __stdcall manage(void* data)
#else
static void manage(void* data)
#endif
{
g_system->m_sync.exit();
FiberDecl* this_fiber = (FiberDecl*)data;
WorkerTask* worker = getWorker();
while (!worker->m_finished) {
if (worker->m_is_backup) {
Lumix::MutexGuard guard(g_system->m_sync);
while (!worker->m_is_enabled && !worker->m_finished) {
PROFILE_BLOCK("disabled");
profiler::blockColor(0xff, 0, 0xff);
worker->sleep(g_system->m_sync);
}
}
FiberDecl* fiber = nullptr;
Job job;
while (!worker->m_finished) {
Lumix::MutexGuard lock(g_system->m_job_queue_sync);
if (!worker->m_ready_fibers.empty()) {
fiber = worker->m_ready_fibers.back();
worker->m_ready_fibers.pop();
break;
}
if (!worker->m_job_queue.empty()) {
job = worker->m_job_queue.back();
worker->m_job_queue.pop();
break;
}
if (!g_system->m_ready_fibers.empty()) {
fiber = g_system->m_ready_fibers.back();
g_system->m_ready_fibers.pop();
break;
}
if(!g_system->m_job_queue.empty()) {
job = g_system->m_job_queue.back();
g_system->m_job_queue.pop();
break;
}
PROFILE_BLOCK("sleeping");
profiler::blockColor(0x30, 0x30, 0x30);
worker->sleep(g_system->m_job_queue_sync);
if (worker->m_is_backup) break;
}
if (worker->m_finished) break;
if (fiber) {
worker->m_current_fiber = fiber;
g_system->m_sync.enter();
g_system->m_free_fibers.push(this_fiber);
Fiber::switchTo(&this_fiber->fiber, fiber->fiber);
g_system->m_sync.exit();
worker = getWorker();
worker->m_current_fiber = this_fiber;
}
else {
if (!job.task) continue;
profiler::beginBlock("job");
profiler::blockColor(0x60, 0x60, 0x60);
if (job.dec_on_finish) {
profiler::pushJobInfo(job.dec_on_finish->generation);
}
this_fiber->current_job = job;
job.task(job.data);
this_fiber->current_job.task = nullptr;
if (job.dec_on_finish) {
trigger<false>(job.dec_on_finish);
}
worker = getWorker();
profiler::endBlock();
}
}
Fiber::switchTo(&this_fiber->fiber, getWorker()->m_primary_fiber);
}
bool init(u8 workers_count, IAllocator& allocator)
{
g_system.create(allocator);
g_system->m_free_fibers.reserve(lengthOf(g_system->m_fiber_pool));
for (FiberDecl& fiber : g_system->m_fiber_pool) {
g_system->m_free_fibers.push(&fiber);
}
const int fiber_num = lengthOf(g_system->m_fiber_pool);
for(int i = 0; i < fiber_num; ++i) {
FiberDecl& decl = g_system->m_fiber_pool[i];
decl.idx = i;
}
int count = maximum(1, int(workers_count));
for (int i = 0; i < count; ++i) {
WorkerTask* task = LUMIX_NEW(allocator, WorkerTask)(*g_system, i < 64 ? u64(1) << i : 0);
if (task->create("Worker", false)) {
task->m_is_enabled = true;
g_system->m_workers.push(task);
task->setAffinityMask((u64)1 << i);
}
else {
logError("Job system worker failed to initialize.");
LUMIX_DELETE(allocator, task);
}
}
return !g_system->m_workers.empty();
}
u8 getWorkersCount()
{
const int c = g_system->m_workers.size();
ASSERT(c <= 0xff);
return (u8)c;
}
IAllocator& getAllocator() {
return g_system->m_allocator;
}
void shutdown()
{
IAllocator& allocator = g_system->m_allocator;
for (Thread* task : g_system->m_workers)
{
WorkerTask* wt = (WorkerTask*)task;
wt->m_finished = true;
}
for (Thread* task : g_system->m_backup_workers) {
WorkerTask* wt = (WorkerTask*)task;
wt->m_finished = true;
wt->wakeup();
}
for (Thread* task : g_system->m_backup_workers)
{
while (!task->isFinished()) task->wakeup();
task->destroy();
LUMIX_DELETE(allocator, task);
}
for (WorkerTask* task : g_system->m_workers)
{
while (!task->isFinished()) task->wakeup();
task->destroy();
LUMIX_DELETE(allocator, task);
}
for (FiberDecl& fiber : g_system->m_fiber_pool)
{
if(Fiber::isValid(fiber.fiber)) {
Fiber::destroy(fiber.fiber);
}
}
g_system.destroy();
}
static void waitEx(Signal* signal, bool is_mutex)
{
ASSERT(signal);
if (signal->counter == 0) return;
g_system->m_sync.enter();
if (signal->counter == 0) {
g_system->m_sync.exit();
return;
}
if (!getWorker()) {
while (signal->counter > 0) {
g_system->m_sync.exit();
os::sleep(1);
g_system->m_sync.enter();
}
g_system->m_sync.exit();
return;
}
FiberDecl* this_fiber = getWorker()->m_current_fiber;
Waitor waitor;
waitor.fiber = this_fiber;
waitor.next = signal->waitor;
signal->waitor = &waitor;
const profiler::FiberSwitchData& switch_data = profiler::beginFiberWait(signal->generation, is_mutex);
FiberDecl* new_fiber = g_system->m_free_fibers.back();
g_system->m_free_fibers.pop();
if (!Fiber::isValid(new_fiber->fiber)) {
new_fiber->fiber = Fiber::create(64 * 1024, manage, new_fiber);
}
getWorker()->m_current_fiber = new_fiber;
Fiber::switchTo(&this_fiber->fiber, new_fiber->fiber);
getWorker()->m_current_fiber = this_fiber;
g_system->m_sync.exit();
profiler::endFiberWait(switch_data);
}
void enter(Mutex* mutex) {
ASSERT(getWorker());
for (;;) {
for (u32 i = 0; i < 400; ++i) {
if (setRedEx(&mutex->signal)) return;
}
waitEx(&mutex->signal, true);
}
}
void exit(Mutex* mutex) {
ASSERT(getWorker());
setGreen(&mutex->signal);
}
void wait(Signal* handle) {
waitEx(handle, false);
}
} // namespace Lumix::jobs
| 22.328685 | 115 | 0.686323 | nemerle |
39fc8b02a547193c70cf3a351b0c8f934e67566e | 2,434 | cpp | C++ | lib/WebServer/WebServer.cpp | sidoh/esp8266_pin_server | 31912034f660a9e174876aef7c3aa250f1674a9a | [
"MIT"
] | 2 | 2019-02-18T01:01:29.000Z | 2019-04-22T12:28:04.000Z | lib/WebServer/WebServer.cpp | sidoh/esp8266_pin_server | 31912034f660a9e174876aef7c3aa250f1674a9a | [
"MIT"
] | 1 | 2018-01-04T22:14:25.000Z | 2018-01-06T19:17:12.000Z | lib/WebServer/WebServer.cpp | sidoh/esp8266_pin_server | 31912034f660a9e174876aef7c3aa250f1674a9a | [
"MIT"
] | null | null | null | #include <PinHandler.h>
#include <Settings.h>
#include <WebServer.h>
#include <FS.h>
using namespace std::placeholders;
WebServer::WebServer(Settings& settings, PinHandler& pinHandler)
: settings(settings)
, authProvider(settings)
, server(80, authProvider)
, pinHandler(pinHandler)
{ }
void WebServer::begin() {
server
.buildHandler("/pin/:pin")
.on(HTTP_GET, std::bind(&WebServer::handleGetPin, this, _1))
.on(HTTP_PUT, std::bind(&WebServer::handlePutPin, this, _1));
server
.buildHandler("/settings")
.on(HTTP_GET, std::bind(&WebServer::handleGetSettings, this, _1))
.on(HTTP_PUT, std::bind(&WebServer::handlePutSettings, this, _1));
server
.buildHandler("/about")
.on(HTTP_GET, std::bind(&WebServer::handleAbout, this, _1));
server
.buildHandler("/firmware")
.handleOTA();
}
void WebServer::handleClient() {
server.handleClient();
}
void WebServer::handleAbout(RequestContext& request) {
// Measure before allocating buffers
uint32_t freeHeap = ESP.getFreeHeap();
JsonObject res = request.response.json.to<JsonObject>();
res["version"] = QUOTE(FIRMWARE_VERSION);
res["variant"] = QUOTE(FIRMWARE_VARIANT);
res["signal_strength"] = WiFi.RSSI();
res["free_heap"] = freeHeap;
res["sdk_version"] = ESP.getSdkVersion();
}
void WebServer::handleGetPin(RequestContext& request) {
uint8_t pinId = atoi(request.pathVariables.get("pin"));
JsonObject pin = request.response.json.createNestedObject("pin");
pin["value"] = digitalRead(pinId);
}
void WebServer::handlePutPin(RequestContext& request) {
JsonObject body = request.getJsonBody().as<JsonObject>();
uint8_t pin = atoi(request.pathVariables.get("pin"));
pinMode(pin, OUTPUT);
pinHandler.handle(pin, body);
handleGetPin(request);
}
void WebServer::handleGetSettings(RequestContext& request) {
const char* file = SETTINGS_FILE;
if (SPIFFS.exists(file)) {
File f = SPIFFS.open(file, "r");
server.streamFile(f, "application/json");
f.close();
} else {
request.response.json["error"] = F("Settings file not stored on SPIFFS. This is an unexpected error!");
request.response.setCode(500);
}
}
void WebServer::handlePutSettings(RequestContext& request) {
JsonObject newSettings = request.getJsonBody().as<JsonObject>();
settings.patch(newSettings);
settings.save();
// just re-serve settings file
handleGetSettings(request);
ESP.restart();
} | 26.747253 | 108 | 0.703369 | sidoh |
260b82ff984fb3982bf266d67275f4a12127f6ef | 7,821 | cc | C++ | DED/i3-old/test.cc | flipk/pfkutils | d8f6c22720b6fcc44a882927c745a822282d1f69 | [
"Unlicense"
] | 4 | 2015-06-12T05:08:56.000Z | 2017-11-13T11:34:27.000Z | DED/i3-old/test.cc | flipk/pfkutils | d8f6c22720b6fcc44a882927c745a822282d1f69 | [
"Unlicense"
] | null | null | null | DED/i3-old/test.cc | flipk/pfkutils | d8f6c22720b6fcc44a882927c745a822282d1f69 | [
"Unlicense"
] | 1 | 2021-10-20T02:04:53.000Z | 2021-10-20T02:04:53.000Z | /*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>
*/
#include "libprotossl.h"
#include "protossl_test-libprotossl_test_proto.pb.h"
#include "posix_fe.h"
#include <unistd.h>
using namespace ProtoSSL;
using namespace PFK::Test;
void
timeval_to_PingInfo(PingInfo &pi, const pxfe_timeval &tv)
{
pi.set_time_seconds(tv.tv_sec);
pi.set_time_useconds(tv.tv_usec);
}
void
PingInfo_to_timeval(pxfe_timeval &tv, const PingInfo &pi)
{
tv.tv_sec = pi.time_seconds();
tv.tv_usec = pi.time_useconds();
}
//
// server
//
class myConnServer : public ProtoSSLConn<ClientToServer, ServerToClient>
{
public:
myConnServer(void) {
printf("myConnServer::myConnServer\n");
}
~myConnServer(void) {
printf("myConnServer::~myConnServer\n");
}
void handleConnect(void) {
printf("myConnServer::handleConnect\n");
outMessage().set_type(STC_PROTO_VERSION);
outMessage().mutable_proto_version()->set_app_name("LIBPROTOSSL_TEST");
outMessage().mutable_proto_version()->set_version(PROTOCOL_VERSION_3);
sendMessage();
}
void handleDisconnect(void) {
printf("myConnClient::handleDisconnect\n");
}
bool messageHandler(const ClientToServer &inMsg) {
switch (inMsg.type())
{
case CTS_PROTO_VERSION:
printf("server got proto app %s version %d from client\n",
inMsg.proto_version().app_name().c_str(),
inMsg.proto_version().version());
break;
case CTS_PING:
{
pxfe_timeval ts;
uint32_t seq = inMsg.ping().seq();
PingInfo_to_timeval(ts, inMsg.ping());
outMessage().set_type(STC_PING_ACK);
outMessage().mutable_ping()->set_seq(seq);
timeval_to_PingInfo(*outMessage().mutable_ping(),ts);
sendMessage();
break;
}
default:
printf("server got unknown message %d\n",
inMsg.type());
}
return true;
}
};
class myFactoryServer : public ProtoSSLConnFactory
{
public:
myFactoryServer(void) { }
~myFactoryServer(void) { }
_ProtoSSLConn * newConnection(void) {
return new myConnServer;
}
};
//
// client
//
class myConnClient : public ProtoSSLConn<ServerToClient, ClientToServer>
{
public:
myConnClient(void) {
printf("myConnClient::myConnClient\n");
}
~myConnClient(void) {
printf("myConnClient::~myConnClient\n");
}
void handleConnect(void) {
printf("myConnClient::handleConnect\n");
outMessage().set_type(CTS_PROTO_VERSION);
outMessage().mutable_proto_version()->set_app_name("LIBPROTOSSL_TEST");
outMessage().mutable_proto_version()->set_version(PROTOCOL_VERSION_3);
sendMessage();
}
void handleDisconnect(void) {
printf("myConnClient::handleDisconnect\n");
}
bool messageHandler(const ServerToClient &inMsg) {
bool done = false;
switch (inMsg.type())
{
case STC_PROTO_VERSION:
{
pxfe_timeval now;
printf("client got proto app %s version %d from server\n",
inMsg.proto_version().app_name().c_str(),
inMsg.proto_version().version());
now.getNow();
outMessage().set_type(CTS_PING);
outMessage().mutable_ping()->set_seq(1);
timeval_to_PingInfo(*outMessage().mutable_ping(), now);
sendMessage();
break;
}
case STC_PING_ACK:
{
pxfe_timeval ts, now, diff;
uint32_t seq = inMsg.ping().seq();
now.getNow();
PingInfo_to_timeval(ts, inMsg.ping());
diff = now - ts;
printf("client got PING_ACK seq %d delay %u.%06u\n",
seq,
(unsigned int) diff.tv_sec,
(unsigned int) diff.tv_usec);
if (seq < 10)
{
outMessage().set_type(CTS_PING);
outMessage().mutable_ping()->set_seq(seq+1);
timeval_to_PingInfo(*outMessage().mutable_ping(), now);
sendMessage();
}
else
{
printf("successful test\n");
stopMsgs();
done = true;
}
break;
}
default:
printf("client got unknown message %d\n",
inMsg.type());
}
return !done;
}
};
class myFactoryClient : public ProtoSSLConnFactory
{
public:
myFactoryClient(void) { }
~myFactoryClient(void) { }
_ProtoSSLConn * newConnection(void) {
return new myConnClient;
}
};
//
// main
//
int
main(int argc, char ** argv)
{
std::string cert_ca = "file:keys/Root-CA.crt";
std::string cert_server = "file:keys/Server-Cert.crt";
std::string key_server = "file:keys/Server-Cert-encrypted.key";
std::string key_pwd_server = "0KZ7QMalU75s0IXoWnhm3BXEtswirfwrXwwNiF6c";
std::string commonname_server = "Server Cert";
std::string cert_client = "file:keys/Client-Cert.crt";
std::string key_client = "file:keys/Client-Cert-encrypted.key";
std::string key_pwd_client = "IgiLNFWx3fTMioJycI8qXCep8j091yfHOwsBbo6f";
std::string commonname_client = "Client Cert";
if (argc < 2)
{
return 1;
}
std::string argv1(argv[1]);
ProtoSSLMsgs msgs(/*debugFlag*/true);
if (argv1 == "s")
{
ProtoSSLCertParams certs(cert_ca,
cert_server,
key_server,
key_pwd_server,
commonname_client);
myFactoryServer fact;
if (msgs.loadCertificates(certs) == false)
return 1;
msgs.startServer(fact, 2005);
while (msgs.run())
;
}
else if (argv1 == "c")
{
if (argc != 3)
{
printf("specify ip address of server\n");
return 2;
}
ProtoSSLCertParams certs(cert_ca,
cert_client,
key_client,
key_pwd_client,
commonname_server);
myFactoryClient fact;
if (msgs.loadCertificates(certs) == false)
return 1;
msgs.startClient(fact, argv[2], 2005);
while (msgs.run())
;
}
else
{
return 2;
}
return 0;
}
| 29.513208 | 79 | 0.588927 | flipk |
260baed23247e7fdc04a28da812ef4d91946fa20 | 1,354 | hpp | C++ | app/src/main/cpp/graphics/resources/base.hpp | ktzevani/native-camera-vulkan | b9c03c956f8e9c2bda05ae31060d09518fd5790b | [
"Apache-2.0"
] | 10 | 2021-06-06T15:30:05.000Z | 2022-03-20T09:48:18.000Z | app/src/main/cpp/graphics/resources/base.hpp | ktzevani/native-camera-vulkan | b9c03c956f8e9c2bda05ae31060d09518fd5790b | [
"Apache-2.0"
] | 1 | 2021-09-23T08:44:50.000Z | 2021-09-23T08:44:50.000Z | app/src/main/cpp/graphics/resources/base.hpp | ktzevani/native-camera-vulkan | b9c03c956f8e9c2bda05ae31060d09518fd5790b | [
"Apache-2.0"
] | 2 | 2021-08-09T07:50:10.000Z | 2021-12-31T13:51:53.000Z | /*
* Copyright 2020 Konstantinos Tzevanidis
*
* 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 NCV_RESOURCES_BASE_HPP
#define NCV_RESOURCES_BASE_HPP
#include <vulkan_hpp/vulkan.hpp>
namespace graphics{ namespace resources{
class base
{
public:
enum class memory_location
{
device,
host,
external
};
base(const vk::PhysicalDevice& a_gpu, const vk::UniqueDevice& a_device);
size_t data_size() { return m_data_size; }
protected:
int get_memory_index(uint32_t a_memory_type_bits, memory_location a_location) noexcept;
vk::Device m_device = nullptr;
vk::PhysicalDeviceMemoryProperties m_mem_props;
size_t m_data_size = 0;
vk::DeviceSize m_size = 0;
};
}}
#endif //NCV_RESOURCES_BASE_HPP
| 25.54717 | 95 | 0.687592 | ktzevani |
260e6d3bdac5631718004f8e99dd6e4539deca0f | 2,655 | cpp | C++ | src/base64.cpp | Oberon00/jd | 0724e059cfa56615afb0a50c27ce9885faa54ed6 | [
"BSD-2-Clause"
] | 1 | 2015-10-10T14:05:56.000Z | 2015-10-10T14:05:56.000Z | src/base64.cpp | Oberon00/jd | 0724e059cfa56615afb0a50c27ce9885faa54ed6 | [
"BSD-2-Clause"
] | null | null | null | src/base64.cpp | Oberon00/jd | 0724e059cfa56615afb0a50c27ce9885faa54ed6 | [
"BSD-2-Clause"
] | null | null | null | // Part of the Jade Engine -- Copyright (c) Christian Neumüller 2012--2013
// This file is subject to the terms of the BSD 2-Clause License.
// See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause
#include "base64.hpp"
#include <array>
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
namespace {
static base64::byte charToByte(base64::byte c)
{
switch(c) {
case '+': return 62;
case '/': return 63;
case '=': return -1;
default:
if (c >= '0' && c <= '9')
return c - '0' + 52;
if (c >= 'A' && c <= 'Z')
return c - 'A';
if (c >= 'a' && c <= 'z')
return c - 'a' + 26;
throw base64::InvalidCharacter();
}
}
} // anonymous namespace
namespace base64 {
std::vector<byte> decode(char const* encoded)
{
return decode(encoded, std::strlen(encoded));
}
std::vector<byte> decode(std::vector<byte> const& encoded)
{
if (encoded.empty())
return std::vector<byte>();
return decode(&encoded[0], encoded.size());
}
std::vector<byte> decode(std::string const& encoded)
{
return decode(encoded.data(), encoded.size());
}
// Could be optimized: call transform once on encoded
std::vector<byte> decode(byte const* encoded, std::size_t byteCount)
{
std::vector<byte> result;
if (byteCount == 0)
return result;
assert(encoded);
if (byteCount % 4 != 0)
throw InvalidLength();
result.reserve(byteCount * 3 / 4 + 2);
for (std::size_t i = 0; i < byteCount; i += 4) {
std::array<byte, 4> inBytes;
std::transform(
encoded + i, encoded + i + 4,
inBytes.begin(),
charToByte);
std::array<byte, 3> outBytes;
outBytes[0] = static_cast<byte>(inBytes[0] << 2 | inBytes[1] >> 4);
outBytes[1] = static_cast<byte>(inBytes[1] << 4 | inBytes[2] >> 2);
outBytes[2] = static_cast<byte>(inBytes[2] << 6 | inBytes[3]);
if (i + 4 == byteCount) {
std::size_t discard = 0;
if (inBytes[2] == -1) {
++discard;
if (inBytes[1] == -1)
++discard;
} else if (inBytes[1] == -1) {
throw InvalidCharacter();
}
result.insert(result.end(), outBytes.begin(), outBytes.end() - discard);
} else if (inBytes[0] == -1 || inBytes[1] == -1) {
throw InvalidCharacter();
} else {
result.insert(result.end(), outBytes.begin(), outBytes.end());
}
}
return result;
}
} // namespace base64
| 26.818182 | 84 | 0.534087 | Oberon00 |
2611e2856e3ac8d7acd24edab7ee13f10e239bdc | 2,660 | cpp | C++ | src/data/SourceCodeLocationsModel.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/data/SourceCodeLocationsModel.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/data/SourceCodeLocationsModel.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | #include "SourceCodeLocationsModel.h"
#include "util/NetworkUtils.h"
SourceCodeLocationsModel::SourceCodeLocationsModel(QObject *parent)
: StandardItemModel(parent)
{
setupHeader();
}
SourceCodeLocationsModel::~SourceCodeLocationsModel() = default;
QString SourceCodeLocationsModel::getColumnName(const SourceCodeLocationsEnum::Columns eColumn)
{
switch (eColumn) {
case SourceCodeLocationsEnum::COLUMN_PROJECT_NAME:
return tr("Project");
case SourceCodeLocationsEnum::COLUMN_SOURCE_PATH:
return tr("Path");
case SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS:
return QLatin1String("");
}
}
void SourceCodeLocationsModel::setupHeader()
{
this->setColumnCount(SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS);
for (int nIndex = 0; nIndex < SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS; ++nIndex) {
this->setHeaderData(nIndex,
Qt::Horizontal,
getColumnName(static_cast<SourceCodeLocationsEnum::Columns>(nIndex)),
Qt::DisplayRole);
}
}
QVariant SourceCodeLocationsModel::data(const QModelIndex &index, int role) const
{
switch (role) {
case Qt::TextAlignmentRole:
if (index.column() == SourceCodeLocationsEnum::COLUMN_PROJECT_NAME) {
return Qt::AlignCenter;
} else {
static const QVariant myAlignCenterLeft(Qt::AlignVCenter | Qt::AlignLeft);
return myAlignCenterLeft;
}
// case Qt::BackgroundRole: {
// switch (static_cast<SourceCodeLocationsEnum::Columns>(index.column())) {
// case NetworkAddressesEnum::COLUMN_ADDRESS_NAME:
// break;
// case NetworkAddressesEnum::COLUMN_SERVER_IP:
// if (NetworkUtils::isIpV4Address(this->item(index.row(), NetworkAddressesEnum::COLUMN_SERVER_IP)->text()) == false) {
// return myBrushError;
// }
// break;
// case NetworkAddressesEnum::COLUMN_SERVER_PORT:
// if (NetworkUtils::isValidPort(this->item(index.row(), NetworkAddressesEnum::COLUMN_SERVER_PORT)->text()) == false) {
// return myBrushError;
// }
// break;
// case SourceCodeLocationsEnum::COUNT_TABLE_COLUMNS:
// break;
// }
// break;
// }
default:
return StandardItemModel::data(index, role);
}
return StandardItemModel::data(index, role);
}
| 32.048193 | 138 | 0.59812 | vitorjna |
2612601b86ac87bb1928207ed4b547cdeb80a239 | 3,461 | cc | C++ | base/io_buffer_test.cc | wuyongchn/trpc | ee492ce8c40ef6a156f298aa295ed4e1fe4b4545 | [
"BSD-2-Clause"
] | null | null | null | base/io_buffer_test.cc | wuyongchn/trpc | ee492ce8c40ef6a156f298aa295ed4e1fe4b4545 | [
"BSD-2-Clause"
] | null | null | null | base/io_buffer_test.cc | wuyongchn/trpc | ee492ce8c40ef6a156f298aa295ed4e1fe4b4545 | [
"BSD-2-Clause"
] | null | null | null | #include "base/io_buffer.h"
#include "base/scoped_refptr.h"
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <string.h>
namespace pbrpc {
namespace unittest {
TEST(IOBufferWithSizeTest, TestConstructor) {
const int kBufSize = 128;
auto buffer = MakeRefCounted<IOBufferWithSize>(kBufSize);
}
TEST(IOBufferWithSizeTest, TestSize) {
const int kBufSize = 128;
auto buffer = MakeRefCounted<IOBufferWithSize>(kBufSize);
CHECK_EQ(kBufSize, buffer->size());
}
TEST(StringIOBufferTest, TestConstructor) {
std::string data;
auto buffer = MakeRefCounted<StringIOBuffer>(data);
}
TEST(StringIOBufferTest, TestSize) {
std::string data("test");
auto buffer = MakeRefCounted<StringIOBuffer>(data);
CHECK_EQ(data.size(), buffer->size());
}
TEST(DrainableIOBufferTest, TestConstructor) {
const int kBufSize = 128;
auto base = MakeRefCounted<IOBuffer>(kBufSize);
auto buffer = MakeRefCounted<DrainableIOBuffer>(base, kBufSize);
}
TEST(DrainableIOBufferTest, TestDidConsume) {
const int kBufSize = 128;
auto base = MakeRefCounted<IOBuffer>(kBufSize);
auto buffer = MakeRefCounted<DrainableIOBuffer>(base, kBufSize);
const int kBatchSize = 32;
buffer->DidConsume(kBatchSize);
CHECK_EQ(kBatchSize, buffer->BytesConsumed());
CHECK_EQ(kBufSize - kBatchSize, buffer->BytesRemaining());
}
TEST(DrainableIOBufferTest, TestSetOffset) {
const int kBufSize = 128;
auto base = MakeRefCounted<IOBuffer>(kBufSize);
auto buffer = MakeRefCounted<DrainableIOBuffer>(base, kBufSize);
const int kBatchSize = 32;
buffer->SetOffset(kBatchSize);
CHECK_EQ(kBatchSize, buffer->BytesConsumed());
CHECK_EQ(kBufSize - kBatchSize, buffer->BytesRemaining());
}
TEST(DrainableIOBufferTest, TestSetOffset2) {
std::string data("this is test");
auto base = MakeRefCounted<StringIOBuffer>(data);
auto buffer = MakeRefCounted<DrainableIOBuffer>(base, data.size());
const int kBatchSize = 4;
buffer->SetOffset(kBatchSize);
std::string remaining(buffer->data(), data.size() - kBatchSize);
CHECK_EQ(data.substr(kBatchSize), remaining);
}
TEST(GrowableIOBufferTest, TestConstructor) {
auto buffer = MakeRefCounted<GrowableIOBuffer>();
CHECK_EQ(0, buffer->capacity());
CHECK_EQ(0, buffer->offset());
CHECK_EQ(0, buffer->RemainingCapacity());
}
TEST(GrowableIOBufferTest, TestSetCapacity) {
auto buffer = MakeRefCounted<GrowableIOBuffer>();
const int kCapacity = 128;
buffer->SetCapacity(kCapacity);
CHECK_EQ(kCapacity, buffer->capacity());
CHECK_EQ(0, buffer->offset());
CHECK_EQ(kCapacity, buffer->RemainingCapacity());
}
TEST(GrowableIOBufferTest, TestSetOffset) {
auto buffer = MakeRefCounted<GrowableIOBuffer>();
const int kCapacity = 128;
buffer->SetCapacity(kCapacity);
const int kBatchSize = 32;
buffer->set_offset(kBatchSize);
CHECK_EQ(kCapacity, buffer->capacity());
CHECK_EQ(kBatchSize, buffer->offset());
CHECK_EQ(kCapacity - kBatchSize, buffer->RemainingCapacity());
}
TEST(GrowableIOBufferTest, TestStartOfBuffer) {
auto buffer = MakeRefCounted<GrowableIOBuffer>();
buffer->SetCapacity(8);
std::string data("test");
memcpy(buffer->StartOfBuffer(), data.data(), data.size());
buffer->SetCapacity(32);
std::string buf(buffer->data(), data.size());
CHECK_EQ(buf, data);
}
} // namespace unittest
} // namespace pbrpc
int main(int argc, char* argv[]) {
::google::InitGoogleLogging(argv[0]);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 30.359649 | 69 | 0.737937 | wuyongchn |
2613c230b86e3ace3ee1dc68d5649ce109d96676 | 4,009 | cpp | C++ | SPOJ/SPOJ CERC07K - Key Task.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | 2 | 2020-04-23T17:47:27.000Z | 2020-04-25T19:40:50.000Z | SPOJ/SPOJ CERC07K - Key Task.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | null | null | null | SPOJ/SPOJ CERC07K - Key Task.cpp | bishoy-magdy/Competitive-Programming | 689daac9aeb475da3c28aba4a69df394c68a9a34 | [
"MIT"
] | 1 | 2020-06-14T20:52:39.000Z | 2020-06-14T20:52:39.000Z | #include<bits/stdc++.h>
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<list>
#include <algorithm>
#include<vector>
#include<set>
#include <cctype>
#include <cstring>
#include <cstdio>
#include<queue>
#include<stack>
#include<bitset>
#include<time.h>
#include<fstream>
/******************************************************/
using namespace std;
/********************define***************************/
#define ll long long
#define ld long double
#define all(v) ((v).begin()), ((v).end())
#define for_(vec) for(int i=0;i<(int)vec.size();i++)
#define lp(j,n) for(int i=j;i<(int)(n);i++)
#define rlp(j,n) for(int i=j;i>=(int)(n);i--)
#define clr(arr,x) memset(arr,x,sizeof(arr))
#define fillstl(arr,X) fill(arr.begin(),arr.end(),X)
#define pb push_back
#define mp make_pair
#define print_vector(X) for(int i=0;i<X.size();i++)
/********************************************************/
typedef vector<int> vi;
typedef vector<pair<int, int> > vii;
typedef vector<vector<int> > vvi;
typedef vector<ll> vl;
/***********************function************************/
void fast()
{
ios_base::sync_with_stdio(NULL);
cin.tie(0);
cout.tie(0);
}
void online_judge()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
}
const int flag_max=0x3f3f3f3f;
const ll OO=1e15+9 ;
const double EPS = (1e-7);
int dcmp(double x, double y)
{
return fabs(x-y) <= EPS ? 0 : x < y ? -1 : 1;
}
ll gcd(ll a, ll b)
{
return !b ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return (a / gcd(a, b)) * b;
}
ll Power(ll n,ll deg)
{
if(!deg)return 1;
else if(deg & 1) return Power(n,deg-1)*n;
else
{
ll half=Power(n,deg/2);
return half*half;
}
}
/***********************main_problem****************************/
int dx[4]= {1,-1,0,0};
int dy[4]= {0,0,-1,1};
char arr[100][100];
int visited[100][100][17];
int dis[100][100][17];
int n,m;
bool valid(int x,int y)
{
return x>=0 && x<n && y>=0 && y<m;
}
bool can(int x,int y,int mask)
{
// "&" compair bits 01
return ( (arr[x][y]=='R' && mask & 1) || (arr[x][y]=='G' && mask & 2 ) || (arr[x][y]=='B' && mask & 4)
|| (arr[x][y]=='Y' && mask & 8) || arr[x][y]=='*' || arr[x][y]=='X' || arr[x][y]=='.' || arr[x][y]=='r'
|| arr[x][y]=='g' || arr[x][y]=='y' || arr[x][y]=='b'
);
}
string BFS(int i,int j)
{
queue<pair<pair<int,int>,int> >q;
int mask=0,ans=-1;
q.push({{i,j},mask});
visited[i][j][mask]=1;
while(!q.empty())
{
pair<pair<int,int>,int> now=q.front();
q.pop();
mask=now.second;
int x=now.first.first,y=now.first.second;
if(arr[x][y]=='X')
{
ans=dis[x][y][mask];
break;
}
else if(arr[x][y]=='r')
mask|=1;
else if ( arr[x][y] == 'g')
mask|=2;
else if (arr[x][y]=='b')
mask|=4;
else if (arr[x][y]=='y')
mask|=8;
for(int k=0; k<4; k++)
{
int new_x=x+dx[k],new_y=y+dy[k];
if(!visited[new_x][new_y][mask] && valid(new_x,new_y) && can(new_x,new_y,mask) )
{
//"now.second" old mask mark it
visited[new_x][new_y][now.second]=1;
dis[new_x][new_y][mask]=dis[x][y][now.second]+1;
q.push({{new_x,new_y},mask});
}
}
}
return ans==-1 ?"The poor student is trapped!":"Escape possible in "+to_string(ans)+" steps.";
}
/***********𝓢𝓣𝓞𝓟 𝓦𝓗𝓔𝓝 𝓨𝓞𝓤 𝓡𝓔𝓐𝓒𝓗 𝓣𝓗𝓔 𝓒𝓞𝓝𝓒𝓔𝓟𝓣 𝓞𝓕 𝓓𝓞𝓝'𝓣 𝓢𝓣𝓞𝓟******************/
int main()
{
fast();
while( cin>>n>>m && n && m)
{
int x_star,y_star;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin>>arr[i][j];
if(arr[i][j]=='*')x_star=i,y_star=j;
}
}
clr(visited,0);
clr(dis,0);
cout<<BFS(x_star,y_star)<<'\n';
}
return 0;
}
| 20.880208 | 116 | 0.467199 | bishoy-magdy |
2617d234f36327f4a417092231cbeac3db3a699b | 1,687 | cpp | C++ | src/Arduino/ADXL345/example_grativity_to_tilt.cpp | smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries | 30795f46112ab5b56a8244b198f0193afb8755ba | [
"MIT"
] | null | null | null | src/Arduino/ADXL345/example_grativity_to_tilt.cpp | smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries | 30795f46112ab5b56a8244b198f0193afb8755ba | [
"MIT"
] | null | null | null | src/Arduino/ADXL345/example_grativity_to_tilt.cpp | smurilogs/EmbeddedSystems-ATmega328P-ArduinoPlatform-InterfacingLibraries | 30795f46112ab5b56a8244b198f0193afb8755ba | [
"MIT"
] | null | null | null |
#include <Arduino.h>
#include <stdint.h>
#include <Math.h>
#include "ADXL345.h"
#define OFFSETX 270
#define OFFSETY 270
ADXL345 accel;
void setup()
{
Serial.begin(9600);
Wire.begin();
accel.begin();
delay(1500);
}
void loop()
{
// Data acquisition from accelerometer
float x = (int16_t) accel.getXAccel();
float y = (int16_t) accel.getYAccel();
float z = (int16_t) accel.getZAccel();
// For around X axis...
// Turning gravital vector components into angle in RAD
float angRadX = atan2(z, y);
// Turning angle in RAD into DEGREE
float angDegX = angRadX * (180.0/PI);
// Scale transformation: [-180, +180] to [0, 360[
if(angDegX > -180 && angDegX < 0)
{
angDegX = angDegX * (-1);
angDegX = (180.0 - angDegX);
angDegX = angDegX + 180.0;
}
// Offset
if((angDegX + OFFSETX) >= 360.0)
angDegX = (angDegX + OFFSETX) - 360.0;
else
angDegX = angDegX + OFFSETX;
// For around Y axis...
// Turning gravital vector components int angle in RAD
float angRadY = atan2(z, x);
// Turning angle in RAD into DEGREE
float angDegY = angRadY * (180.0/PI);
// Scale transformation: [-180, +180] to [0, 360[
if(angDegY > -180 && angDegY < 0)
{
angDegY = angDegY * (-1);
angDegY = (180.0 - angDegY);
angDegY = angDegY + 180.0;
}
// Offset
if((angDegY + OFFSETY) >= 360.0)
angDegY = (angDegY + OFFSETY) - 360.0;
else
angDegY = angDegY + OFFSETY;
// For presentation...
Serial.println(angDegX);
Serial.println(angDegY);
Serial.println();
delay(500);
} | 22.197368 | 59 | 0.571429 | smurilogs |
26194c3bdf8b2234686f873fc6c989481ab274f2 | 15,419 | cpp | C++ | fuse_publishers/test/test_pose_2d_publisher.cpp | congleetea/fuse | 7a87a59915a213431434166c96d0705ba6aa00b2 | [
"BSD-3-Clause"
] | 383 | 2018-07-02T07:20:32.000Z | 2022-03-31T12:51:06.000Z | fuse_publishers/test/test_pose_2d_publisher.cpp | congleetea/fuse | 7a87a59915a213431434166c96d0705ba6aa00b2 | [
"BSD-3-Clause"
] | 117 | 2018-07-16T10:32:52.000Z | 2022-02-02T20:15:16.000Z | fuse_publishers/test/test_pose_2d_publisher.cpp | congleetea/fuse | 7a87a59915a213431434166c96d0705ba6aa00b2 | [
"BSD-3-Clause"
] | 74 | 2018-10-01T10:10:45.000Z | 2022-03-02T04:48:22.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2018, Locus Robotics
* 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 copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <fuse_constraints/absolute_pose_2d_stamped_constraint.h>
#include <fuse_core/eigen.h>
#include <fuse_core/transaction.h>
#include <fuse_core/uuid.h>
#include <fuse_graphs/hash_graph.h>
#include <fuse_publishers/pose_2d_publisher.h>
#include <fuse_variables/orientation_2d_stamped.h>
#include <fuse_variables/position_2d_stamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <ros/ros.h>
#include <tf2/utils.h>
#include <tf2_msgs/TFMessage.h>
#include <tf2_ros/static_transform_broadcaster.h>
#include <gtest/gtest.h>
#include <vector>
/**
* @brief Test fixture for the LatestStampedPose2DPublisher
*
* This test fixture provides a populated graph for testing the publish() function, and subscriber callbacks
* for each of the different possible output topics.
*/
class Pose2DPublisherTestFixture : public ::testing::Test
{
public:
Pose2DPublisherTestFixture() :
private_node_handle_("~"),
graph_(fuse_graphs::HashGraph::make_shared()),
transaction_(fuse_core::Transaction::make_shared()),
received_pose_msg_(false),
received_pose_with_covariance_msg_(false),
received_tf_msg_(false)
{
// Add a few pose variables
auto position1 = fuse_variables::Position2DStamped::make_shared(ros::Time(1234, 10));
position1->x() = 1.01;
position1->y() = 2.01;
auto orientation1 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1234, 10));
orientation1->yaw() = 3.01;
auto position2 = fuse_variables::Position2DStamped::make_shared(ros::Time(1235, 10));
position2->x() = 1.02;
position2->y() = 2.02;
auto orientation2 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1235, 10));
orientation2->yaw() = 3.02;
auto position3 = fuse_variables::Position2DStamped::make_shared(ros::Time(1235, 9));
position3->x() = 1.03;
position3->y() = 2.03;
auto orientation3 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1235, 9));
orientation3->yaw() = 3.03;
auto position4 = fuse_variables::Position2DStamped::make_shared(ros::Time(1235, 11),
fuse_core::uuid::generate("kitt"));
position4->x() = 1.04;
position4->y() = 2.04;
auto orientation4 = fuse_variables::Orientation2DStamped::make_shared(ros::Time(1235, 11),
fuse_core::uuid::generate("kitt"));
orientation4->yaw() = 3.04;
transaction_->addInvolvedStamp(position1->stamp());
transaction_->addInvolvedStamp(orientation1->stamp());
transaction_->addInvolvedStamp(position2->stamp());
transaction_->addInvolvedStamp(orientation2->stamp());
transaction_->addInvolvedStamp(position3->stamp());
transaction_->addInvolvedStamp(orientation3->stamp());
transaction_->addInvolvedStamp(position4->stamp());
transaction_->addInvolvedStamp(orientation4->stamp());
transaction_->addVariable(position1);
transaction_->addVariable(orientation1);
transaction_->addVariable(position2);
transaction_->addVariable(orientation2);
transaction_->addVariable(position3);
transaction_->addVariable(orientation3);
transaction_->addVariable(position4);
transaction_->addVariable(orientation4);
// Add some priors on the variables some we can optimize the graph
fuse_core::Vector3d mean1;
mean1 << 1.01, 2.01, 3.01;
fuse_core::Matrix3d cov1;
cov1 << 1.01, 0.0, 0.0, 0.0, 2.01, 0.0, 0.0, 0.0, 3.01;
auto constraint1 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared(
"test", *position1, *orientation1, mean1, cov1);
fuse_core::Vector3d mean2;
mean2 << 1.02, 2.02, 3.02;
fuse_core::Matrix3d cov2;
cov2 << 1.02, 0.0, 0.0, 0.0, 2.02, 0.0, 0.0, 0.0, 3.02;
auto constraint2 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared(
"test", *position2, *orientation2, mean2, cov2);
fuse_core::Vector3d mean3;
mean3 << 1.03, 2.03, 3.03;
fuse_core::Matrix3d cov3;
cov3 << 1.03, 0.0, 0.0, 0.0, 2.03, 0.0, 0.0, 0.0, 3.03;
auto constraint3 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared(
"test", *position3, *orientation3, mean3, cov3);
fuse_core::Vector3d mean4;
mean4 << 1.04, 2.04, 3.04;
fuse_core::Matrix3d cov4;
cov4 << 1.04, 0.0, 0.0, 0.0, 2.04, 0.0, 0.0, 0.0, 3.04;
auto constraint4 = fuse_constraints::AbsolutePose2DStampedConstraint::make_shared(
"test", *position4, *orientation4, mean4, cov4);
transaction_->addConstraint(constraint1);
transaction_->addConstraint(constraint2);
transaction_->addConstraint(constraint3);
transaction_->addConstraint(constraint4);
// Add the transaction to the graph
graph_->update(*transaction_);
// Optimize the graph
graph_->optimize();
// Publish a odom->base transform so tf lookups will succeed
geometry_msgs::TransformStamped odom_to_base;
odom_to_base.header.stamp = ros::Time(0, 0);
odom_to_base.header.frame_id = "test_odom";
odom_to_base.child_frame_id = "test_base";
odom_to_base.transform.translation.x = -0.10;
odom_to_base.transform.translation.y = -0.20;
odom_to_base.transform.translation.z = -0.30;
odom_to_base.transform.rotation.x = 0.0;
odom_to_base.transform.rotation.y = 0.0;
odom_to_base.transform.rotation.z = -0.1986693307950612164;
odom_to_base.transform.rotation.w = 0.98006657784124162625; // -0.4rad in yaw
static_broadcaster_.sendTransform(odom_to_base);
}
void poseCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
received_pose_msg_ = true;
pose_msg_ = *msg;
}
void poseWithCovarianceCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg)
{
received_pose_with_covariance_msg_ = true;
pose_with_covariance_msg_ = *msg;
}
void tfCallback(const tf2_msgs::TFMessage::ConstPtr& msg)
{
received_tf_msg_ = true;
tf_msg_ = *msg;
}
protected:
ros::NodeHandle node_handle_;
ros::NodeHandle private_node_handle_;
fuse_graphs::HashGraph::SharedPtr graph_;
fuse_core::Transaction::SharedPtr transaction_;
bool received_pose_msg_;
geometry_msgs::PoseStamped pose_msg_;
bool received_pose_with_covariance_msg_;
geometry_msgs::PoseWithCovarianceStamped pose_with_covariance_msg_;
bool received_tf_msg_;
tf2_msgs::TFMessage tf_msg_;
tf2_ros::StaticTransformBroadcaster static_broadcaster_;
};
TEST_F(Pose2DPublisherTestFixture, PublishPose)
{
// Test that the expected PoseStamped message is published
// Create a publisher and send it the graph
private_node_handle_.setParam("test_publisher/map_frame", "test_map");
private_node_handle_.setParam("test_publisher/odom_frame", "test_odom");
private_node_handle_.setParam("test_publisher/base_frame", "test_base");
private_node_handle_.setParam("test_publisher/publish_to_tf", false);
fuse_publishers::Pose2DPublisher publisher;
publisher.initialize("test_publisher");
publisher.start();
// Subscribe to the "pose" topic
ros::Subscriber subscriber = private_node_handle_.subscribe(
"test_publisher/pose",
1,
&Pose2DPublisherTestFixture::poseCallback,
reinterpret_cast<Pose2DPublisherTestFixture*>(this));
// Send the graph to the Publisher to trigger message publishing
publisher.notify(transaction_, graph_);
// Verify the subscriber received the expected pose
ros::Time timeout = ros::Time::now() + ros::Duration(10.0);
while ((!received_pose_msg_) && (ros::Time::now() < timeout))
{
ros::Duration(0.10).sleep();
}
ASSERT_TRUE(received_pose_msg_);
EXPECT_EQ(ros::Time(1235, 10), pose_msg_.header.stamp);
EXPECT_EQ("test_map", pose_msg_.header.frame_id);
EXPECT_NEAR(1.02, pose_msg_.pose.position.x, 1.0e-9);
EXPECT_NEAR(2.02, pose_msg_.pose.position.y, 1.0e-9);
EXPECT_NEAR(0.00, pose_msg_.pose.position.z, 1.0e-9);
EXPECT_NEAR(3.02, tf2::getYaw(pose_msg_.pose.orientation), 1.0e-9);
}
TEST_F(Pose2DPublisherTestFixture, PublishPoseWithCovariance)
{
// Test that the expected PoseWithCovarianceStamped message is published
// Create a publisher and send it the graph
private_node_handle_.setParam("test_publisher/map_frame", "test_map");
private_node_handle_.setParam("test_publisher/odom_frame", "test_odom");
private_node_handle_.setParam("test_publisher/base_frame", "test_base");
private_node_handle_.setParam("test_publisher/publish_to_tf", false);
fuse_publishers::Pose2DPublisher publisher;
publisher.initialize("test_publisher");
publisher.start();
// Subscribe to the "pose_with_covariance" topic
ros::Subscriber subscriber = private_node_handle_.subscribe(
"test_publisher/pose_with_covariance",
1,
&Pose2DPublisherTestFixture::poseWithCovarianceCallback,
reinterpret_cast<Pose2DPublisherTestFixture*>(this));
// Send the graph to the Publisher to trigger message publishing
publisher.notify(transaction_, graph_);
// Verify the subscriber received the expected pose
ros::Time timeout = ros::Time::now() + ros::Duration(10.0);
while ((!received_pose_with_covariance_msg_) && (ros::Time::now() < timeout))
{
ros::Duration(0.10).sleep();
}
ASSERT_TRUE(received_pose_with_covariance_msg_);
EXPECT_EQ(ros::Time(1235, 10), pose_with_covariance_msg_.header.stamp);
EXPECT_EQ("test_map", pose_with_covariance_msg_.header.frame_id);
EXPECT_NEAR(1.02, pose_with_covariance_msg_.pose.pose.position.x, 1.0e-9);
EXPECT_NEAR(2.02, pose_with_covariance_msg_.pose.pose.position.y, 1.0e-9);
EXPECT_NEAR(0.00, pose_with_covariance_msg_.pose.pose.position.z, 1.0e-9);
EXPECT_NEAR(3.02, tf2::getYaw(pose_with_covariance_msg_.pose.pose.orientation), 1.0e-9);
std::vector<double> expected_covariance =
{
1.02, 0.00, 0.00, 0.00, 0.00, 0.00,
0.00, 2.02, 0.00, 0.00, 0.00, 0.00,
0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
0.00, 0.00, 0.00, 0.00, 0.00, 3.02
};
for (size_t i = 0; i < 36; ++i)
{
EXPECT_NEAR(expected_covariance[i], pose_with_covariance_msg_.pose.covariance[i], 1.0e-9);
}
}
TEST_F(Pose2DPublisherTestFixture, PublishTfWithoutOdom)
{
// Test that the expected TFMessage is published
// Create a publisher and send it the graph
private_node_handle_.setParam("test_publisher/map_frame", "test_map");
private_node_handle_.setParam("test_publisher/odom_frame", "test_base");
private_node_handle_.setParam("test_publisher/base_frame", "test_base");
private_node_handle_.setParam("test_publisher/publish_to_tf", true);
fuse_publishers::Pose2DPublisher publisher;
publisher.initialize("test_publisher");
publisher.start();
// Subscribe to the "pose" topic
ros::Subscriber subscriber = private_node_handle_.subscribe(
"/tf",
1,
&Pose2DPublisherTestFixture::tfCallback,
reinterpret_cast<Pose2DPublisherTestFixture*>(this));
// Send the graph to the Publisher to trigger message publishing
publisher.notify(transaction_, graph_);
// Verify the subscriber received the expected pose
ros::Time timeout = ros::Time::now() + ros::Duration(10.0);
while ((!received_tf_msg_) && (ros::Time::now() < timeout))
{
ros::Duration(0.10).sleep();
}
ASSERT_TRUE(received_tf_msg_);
ASSERT_EQ(1ul, tf_msg_.transforms.size());
EXPECT_EQ("test_map", tf_msg_.transforms[0].header.frame_id);
EXPECT_EQ("test_base", tf_msg_.transforms[0].child_frame_id);
EXPECT_NEAR(1.02, tf_msg_.transforms[0].transform.translation.x, 1.0e-9);
EXPECT_NEAR(2.02, tf_msg_.transforms[0].transform.translation.y, 1.0e-9);
EXPECT_NEAR(0.00, tf_msg_.transforms[0].transform.translation.z, 1.0e-9);
EXPECT_NEAR(3.02, tf2::getYaw(tf_msg_.transforms[0].transform.rotation), 1.0e-9);
}
TEST_F(Pose2DPublisherTestFixture, PublishTfWithOdom)
{
// Test that the expected TFMessage is published
// Create a publisher and send it the graph
private_node_handle_.setParam("test_publisher/map_frame", "test_map");
private_node_handle_.setParam("test_publisher/odom_frame", "test_odom");
private_node_handle_.setParam("test_publisher/base_frame", "test_base");
private_node_handle_.setParam("test_publisher/publish_to_tf", true);
fuse_publishers::Pose2DPublisher publisher;
publisher.initialize("test_publisher");
publisher.start();
// Subscribe to the "pose" topic
ros::Subscriber subscriber = private_node_handle_.subscribe(
"/tf",
1,
&Pose2DPublisherTestFixture::tfCallback,
reinterpret_cast<Pose2DPublisherTestFixture*>(this));
// Send the graph to the Publisher to trigger message publishing
publisher.notify(transaction_, graph_);
// Verify the subscriber received the expected pose
ros::Time timeout = ros::Time::now() + ros::Duration(10.0);
while ((!received_tf_msg_) && (ros::Time::now() < timeout))
{
ros::Duration(0.10).sleep();
}
ASSERT_TRUE(received_tf_msg_);
ASSERT_EQ(1ul, tf_msg_.transforms.size());
EXPECT_EQ("test_map", tf_msg_.transforms[0].header.frame_id);
EXPECT_EQ("test_odom", tf_msg_.transforms[0].child_frame_id);
EXPECT_NEAR(0.9788154983, tf_msg_.transforms[0].transform.translation.x, 1.0e-9);
EXPECT_NEAR(1.8002186614, tf_msg_.transforms[0].transform.translation.y, 1.0e-9);
EXPECT_NEAR(0.3000000000, tf_msg_.transforms[0].transform.translation.z, 1.0e-9);
EXPECT_NEAR(-2.8631853072, tf2::getYaw(tf_msg_.transforms[0].transform.rotation), 1.0e-9);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "test_pose_2d_publisher");
ros::AsyncSpinner spinner(1);
spinner.start();
int ret = RUN_ALL_TESTS();
spinner.stop();
ros::shutdown();
return ret;
}
| 41.117333 | 109 | 0.728841 | congleetea |
261c3a982176fb59cb4adb48f6970cbe839b934c | 7,690 | cpp | C++ | src/downloads/downloadfilehelper.cpp | bubapl/QupZilla | 3555a92eaf864fb00cce0c325c4afef582bd2024 | [
"BSD-3-Clause"
] | 1 | 2017-05-21T15:31:02.000Z | 2017-05-21T15:31:02.000Z | src/downloads/downloadfilehelper.cpp | bubapl/QupZilla | 3555a92eaf864fb00cce0c325c4afef582bd2024 | [
"BSD-3-Clause"
] | null | null | null | src/downloads/downloadfilehelper.cpp | bubapl/QupZilla | 3555a92eaf864fb00cce0c325c4afef582bd2024 | [
"BSD-3-Clause"
] | null | null | null | /* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2010-2012 David Rosca <nowrep@gmail.com>
*
* 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 "downloadfilehelper.h"
#include "webpage.h"
#include "webview.h"
#include "downloadoptionsdialog.h"
#include "mainapplication.h"
#include "qupzilla.h"
#include "downloaditem.h"
#include "downloadmanager.h"
#include "globalfunctions.h"
#include "settings.h"
DownloadFileHelper::DownloadFileHelper(const QString &lastDownloadPath, const QString &downloadPath, bool useNativeDialog, WebPage* page)
: QObject()
, m_lastDownloadOption(DownloadManager::SaveFile)
, m_lastDownloadPath(lastDownloadPath)
, m_downloadPath(downloadPath)
, m_useNativeDialog(useNativeDialog)
, m_timer(0)
, m_reply(0)
, m_openFileChoosed(false)
, m_listWidget(0)
, m_iconProvider(new QFileIconProvider)
, m_manager(0)
, m_webPage(page)
{
}
//////////////////////////////////////////////////////
//// Getting where to download requested file
//// in 3 functions, as we are using non blocking
//// dialogs ( this is important to make secure downloading
//// on Windows working properly )
//////////////////////////////////////////////////////
void DownloadFileHelper::handleUnsupportedContent(QNetworkReply* reply, bool askWhatToDo)
{
m_timer = new QTime();
m_timer->start();
m_h_fileName = getFileName(reply);
m_reply = reply;
QFileInfo info(reply->url().toString());
QTemporaryFile tempFile("XXXXXX." + info.suffix());
tempFile.open();
QFileInfo tempInfo(tempFile.fileName());
m_fileIcon = m_iconProvider->icon(tempInfo).pixmap(30, 30);
QString mimeType = m_iconProvider->type(tempInfo);
// Close Empty Tab
if (m_webPage) {
if (!m_webPage->mainFrame()->url().isEmpty() && m_webPage->mainFrame()->url().toString() != "about:blank") {
m_downloadPage = m_webPage->mainFrame()->url();
}
else if (m_webPage->history()->canGoBack()) {
m_downloadPage = m_webPage->history()->backItem().url();
}
else if (m_webPage->history()->count() == 0) {
m_webPage->getView()->closeTab();
}
}
if (askWhatToDo) {
DownloadOptionsDialog* dialog = new DownloadOptionsDialog(m_h_fileName, m_fileIcon, mimeType, reply->url(), mApp->activeWindow());
dialog->setLastDownloadOption(m_lastDownloadOption);
dialog->show();
connect(dialog, SIGNAL(dialogFinished(int)), this, SLOT(optionsDialogAccepted(int)));
}
else {
optionsDialogAccepted(2);
}
}
void DownloadFileHelper::optionsDialogAccepted(int finish)
{
m_openFileChoosed = false;
switch (finish) {
case 0: //Cancelled
if (m_timer) {
delete m_timer;
}
return;
break;
case 1: //Open
m_openFileChoosed = true;
m_lastDownloadOption = DownloadManager::OpenFile;
break;
case 2: //Save
m_lastDownloadOption = DownloadManager::SaveFile;
break;
}
m_manager->setLastDownloadOption(m_lastDownloadOption);
if (!m_openFileChoosed) {
if (m_downloadPath.isEmpty()) {
if (m_useNativeDialog) {
fileNameChoosed(QFileDialog::getSaveFileName(mApp->getWindow(), tr("Save file as..."), m_lastDownloadPath + m_h_fileName));
}
else {
QFileDialog* dialog = new QFileDialog(mApp->getWindow());
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setWindowTitle(tr("Save file as..."));
dialog->setDirectory(m_lastDownloadPath);
dialog->selectFile(m_h_fileName);
dialog->show();
connect(dialog, SIGNAL(fileSelected(QString)), this, SLOT(fileNameChoosed(QString)));
}
}
else {
fileNameChoosed(m_downloadPath + m_h_fileName, true);
}
}
else {
fileNameChoosed(QDir::tempPath() + "/" + m_h_fileName, true);
}
}
void DownloadFileHelper::fileNameChoosed(const QString &name, bool fileNameAutoGenerated)
{
m_userFileName = name;
if (m_userFileName.isEmpty()) {
m_reply->abort();
if (m_timer) {
delete m_timer;
}
return;
}
int pos = m_userFileName.lastIndexOf("/");
if (pos != -1) {
int size = m_userFileName.size();
m_path = m_userFileName.left(pos + 1);
m_fileName = m_userFileName.right(size - pos - 1);
}
if (fileNameAutoGenerated && QFile::exists(m_userFileName)) {
QString _tmpFileName = m_fileName;
int i = 1;
while (QFile::exists(m_path + "/" + _tmpFileName)) {
_tmpFileName = m_fileName;
int index = _tmpFileName.lastIndexOf(".");
if (index == -1) {
_tmpFileName.append("(" + QString::number(i) + ")");
}
else {
_tmpFileName = _tmpFileName.mid(0, index) + "(" + QString::number(i) + ")" + _tmpFileName.mid(index);
}
i++;
}
m_fileName = _tmpFileName;
}
if (!m_path.contains(QDir::tempPath())) {
m_lastDownloadPath = m_path;
}
Settings settings;
settings.beginGroup("DownloadManager");
settings.setValue("lastDownloadPath", m_lastDownloadPath);
settings.endGroup();
m_manager->setLastDownloadPath(m_lastDownloadPath);
QListWidgetItem* item = new QListWidgetItem(m_listWidget);
DownloadItem* downItem = new DownloadItem(item, m_reply, m_path, m_fileName, m_fileIcon, m_timer, m_openFileChoosed, m_downloadPage, m_manager);
emit itemCreated(item, downItem);
}
//////////////////////////////////////////////////////
//// End here
//////////////////////////////////////////////////////
QString DownloadFileHelper::getFileName(QNetworkReply* reply)
{
QString path;
if (reply->hasRawHeader("Content-Disposition")) {
QString value = QString::fromLatin1(reply->rawHeader("Content-Disposition"));
int pos = value.indexOf("filename=");
if (pos != -1) {
QString name = value.mid(pos + 9);
if (name.startsWith('"') && name.endsWith('"')) {
name = name.mid(1, name.size() - 2);
}
path = name;
}
}
if (path.isEmpty()) {
path = reply->url().path();
}
QFileInfo info(path);
QString baseName = info.completeBaseName();
QString endName = info.suffix();
if (baseName.isEmpty()) {
baseName = tr("NoNameDownload");
}
if (!endName.isEmpty()) {
endName = "." + endName;
}
QString name = baseName + endName;
if (name.startsWith("\"")) {
name = name.mid(1);
}
if (name.endsWith("\";")) {
name.remove("\";");
}
name = qz_filterCharsFromFilename(name);
return name;
}
DownloadFileHelper::~DownloadFileHelper()
{
delete m_iconProvider;
}
| 32.041667 | 148 | 0.597529 | bubapl |
1c7a16b52d0a2598419413ef6684c2331805539d | 10,204 | cpp | C++ | homework/AvilovaEM/05/BI.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 12 | 2018-02-20T15:25:12.000Z | 2022-02-15T03:31:55.000Z | homework/AvilovaEM/05/BI.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 1 | 2018-02-26T12:40:47.000Z | 2018-02-26T12:40:47.000Z | homework/AvilovaEM/05/BI.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 33 | 2018-02-20T15:25:11.000Z | 2019-02-13T22:33:36.000Z | #include <cstdlib>
#include <cstring>
#include <stdint.h>
#include <utility>
#include <ostream>
#include <iostream>
#include <algorithm>
#include <memory>
class BigInt
{
public:
BigInt()
: sign(0)
, length(0)
, dataSize(0)
, data(nullptr) {}
BigInt(const long long &x)
{
if (x == 0)
{
resize(1);
data[0] = 0;
sign = 0;
length = 1;
}
else
{
sign = (x < 0 ? -1 : 1);
resize(1);
length = 0;
long long y = std::abs(x);
while (y > 0)
{
if (length == dataSize)
resize(dataSize * 2);
data[length] = y % 10;
y /= 10;
++length;
}
}
}
BigInt(const BigInt& other)
{
sign = other.sign;
length = other.length;
dataSize = other.dataSize;
data.reset(new int8_t[dataSize]);
memset(data.get(), 0, sizeof(int8_t) * dataSize);
memcpy(data.get(), other.data.get(), length);
}
BigInt(BigInt&& other)
: sign(std::move(other.sign))
, length(std::move(other.length))
, dataSize(std::move(other.dataSize))
, data(std::move(other.data)) {}
BigInt abs(const BigInt& x) const
{
BigInt answer(x);
if (answer.sign < 0)
answer.sign = 1;
return answer;
}
BigInt& operator=(const BigInt& other)
{
sign = other.sign;
length = other.length;
dataSize = other.dataSize;
data.reset(new int8_t[dataSize]);
memset(data.get(), 0, sizeof(int8_t) * dataSize);
memcpy(data.get(), other.data.get(), length);
return *this;
}
BigInt& operator=(BigInt&& other)
{
sign = std::move(other.sign);
length = std::move(other.length);
dataSize = std::move(other.dataSize);
data = std::move(other.data);
return *this;
}
bool operator!=(const BigInt& other) const
{
if (sign != other.sign)
return true;
if (length != other.length)
return true;
for (uint32_t i = 0; i < length; ++i)
if (data[i] != other.data[i])
return true;
return false;
}
bool operator==(const BigInt& other) const
{
return !operator!=(other);
}
bool operator<=(const BigInt& other) const
{
if (sign < other.sign)
return true;
if (sign > other.sign)
return false;
if (length < other.length)
return true;
if (length > other.length)
return false;
for (uint32_t i = length; i > 0; --i)
{
if (data[i - 1] * sign < other.data[i - 1] * other.sign)
return true;
if (data[i - 1] * sign > other.data[i - 1] * other.sign)
return false;
}
return true;
}
bool operator>=(const BigInt& other) const
{
if (sign < other.sign)
return false;
if (sign > other.sign)
return true;
if (length < other.length)
return false;
if (length > other.length)
return true;
for (uint32_t i = length; i > 0; --i)
{
if (data[i - 1] * sign < other.data[i - 1] * other.sign)
return false;
if (data[i - 1] * sign > other.data[i - 1] * other.sign)
return true;
}
return true;
}
bool operator<(const BigInt& other) const
{
return !operator>=(other);
}
bool operator>(const BigInt& other) const
{
return !operator<=(other);
}
BigInt operator-() const
{
BigInt answer(*this);
answer.sign *= -1;
return answer;
}
BigInt operator+(const BigInt& other) const
{
if (sign == 0)
{
BigInt answer(other);
return answer;
}
if (other.sign == 0)
{
BigInt answer(*this);
return answer;
}
if (sign == other.sign)
{
BigInt answer(*this), second(other);
sum(answer, second);
return answer;
}
else
{
BigInt a(abs(*this));
BigInt b(abs(other));
if (a >= b)
{
minus(a, b);
if (a.sign != 0)
a.sign = sign;
return a;
}
else
{
minus(b, a);
if (b.sign != 0)
b.sign = other.sign;
return b;
}
}
}
BigInt operator-(const BigInt& other) const
{
return operator+(-other);
}
BigInt operator*(const BigInt& other) const
{
BigInt answer(0);
if ((*this) == 0 || other == 0)
return answer;
answer.sign = sign * other.sign;
answer.resize(length + other.length);
answer.length = length + other.length - 1;
for (uint32_t i = 0; i < length; ++i)
{
int t = 0;
for (uint32_t j = 0; j < other.length; ++j)
{
t += answer.data[i + j] + data[i] * other.data[j];
answer.data[i + j] = t % 10;
t /= 10;
}
uint32_t j = i + other.length;
while (t > 0)
{
if (answer.length <= j)
{
if (answer.length == answer.dataSize)
answer.resize(answer.dataSize * 2);
++answer.length;
}
t += answer.data[j];
answer.data[j] = t % 10;
t /= 10;
++j;
}
}
return answer;
}
BigInt operator/(const BigInt& other) const
{
if (abs(*this) < abs(other))
{
BigInt answer(0);
return answer;
}
if (other == 0)
return 0;
BigInt a(*this), b, c;
a.sign = 1;
b.sign = 1;
b.length = length;
b.dataSize = dataSize;
b.data.reset(new int8_t[length]);
memset(b.data.get(), 0, sizeof(int8_t) * length);
memcpy(b.data.get() + length - other.length, other.data.get(), other.length);
c.sign = sign * other.sign;
c.length = length - other.length + 1;
c.dataSize = c.length;
c.data.reset(new int8_t[c.length]);
memset(c.data.get(), 0, sizeof(int8_t) * c.length);
for (uint32_t i = 0; i < c.length; ++i)
{
while (a >= b)
{
BigInt d(a - b);
a = d;
++c.data[c.length - i - 1];
}
for (uint32_t j = 1; j < b.length; ++j)
b.data[j - 1] = b.data[j];
--b.length;
}
while (c.length > 1 && c.data[c.length - 1] == 0)
--c.length;
if (c.length == 1 && c.data[0] == 0)
c.sign = 0;
if (c.length * 2 <= c.dataSize)
c.resize(c.dataSize);
return c;
}
BigInt operator%(const BigInt& other) const
{
return ((*this) - ((*this) / other) * other);
}
private:
int32_t sign;
uint32_t length = 0;
uint32_t dataSize = 0;
std::unique_ptr<int8_t[]> data;
void resize(uint32_t newSize)
{
int8_t* newData = new int8_t[newSize];
memset(newData, 0, sizeof(int8_t) * newSize);
if (data != nullptr)
memcpy(newData, data.get(), std::min(length, newSize));
dataSize = newSize;
data.reset(newData);
}
void sum(BigInt& a, BigInt& b) const
{
if (b.dataSize > a.dataSize)
a.resize(b.dataSize);
a.length = std::max(a.length, b.length);
a.resize(a.length);
b.resize(a.length);
int8_t t = 0;
for (uint32_t i = 0; i < a.length; ++i)
{
t += a.data[i] + b.data[i];
a.data[i] = t % 10;
t /= 10;
}
if (t > 0)
{
if (a.dataSize == a.length)
{
a.resize(a.dataSize * 2);
a.data[a.length] = t;
++a.length;
}
}
}
void minus(BigInt& a, BigInt& b) const
{
a.length = std::max(a.length, b.length);
a.resize(a.length);
b.resize(a.length);
int8_t t = 0;
for (uint32_t i = 0; i < a.length; ++i)
{
t += a.data[i] - b.data[i];
if (t < 0)
{
t += 10;
a.data[i] = t;
t = -1;
}
else
{
a.data[i] = t;
t = 0;
}
}
while (a.length > 1 && a.data[a.length - 1] == 0)
--a.length;
if (a.length == 1 && a.data[0] == 0)
a.sign = 0;
uint32_t s = a.dataSize;
while (a.length * 2 <= s)
s /= 2;
if (a.dataSize != s)
a.resize(s);
a.resize(s);
}
friend std::ostream& operator<<(std::ostream& out, const BigInt& value);
};
std::ostream& operator<<(std::ostream& out, const BigInt& value)
{
if (value.sign == 0)
out << 0;
else
{
if (value.sign < 0)
out << "-";
for (uint32_t i = value.length; i > 0; --i)
out << static_cast<int>(value.data[i - 1]);
}
return out;
}
| 24.353222 | 85 | 0.409643 | nkotelevskii |
1c7b3fe3cf86dba04992823ab919c18ad59f7092 | 367 | hpp | C++ | glib/include/triangle.hpp | cesarus777/kt_glib | 96b4740f660535c3481645c4b45a3fd89a08c9e2 | [
"BSD-3-Clause"
] | 2 | 2020-09-22T13:44:47.000Z | 2021-12-10T07:46:24.000Z | glib/include/triangle.hpp | cesarus777/kt_glib | 96b4740f660535c3481645c4b45a3fd89a08c9e2 | [
"BSD-3-Clause"
] | null | null | null | glib/include/triangle.hpp | cesarus777/kt_glib | 96b4740f660535c3481645c4b45a3fd89a08c9e2 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <base.hpp>
namespace mygeo
{
class Triangle : public Polygon
{
public:
Triangle(Point p1, Point p2, Point p3) : Polygon({ p1, p2, p3 }, TRIANGLE) {}
Triangle(std::vector<Point> v) : Polygon(v, TRIANGLE)
{
if(v.size() != 3)
throw std::invalid_argument("Invalid Triangle : wrong number of points");
}
};
}
| 19.315789 | 81 | 0.613079 | cesarus777 |
1c7d2a3d01ed78eabca75cff56475777866f1206 | 1,470 | hpp | C++ | include/proton/_mapped_type.hpp | calmdan/libproton | 229f2a963771049523c8a58dfa25d79b4b2417e0 | [
"BSD-2-Clause"
] | 1 | 2020-07-12T13:43:40.000Z | 2020-07-12T13:43:40.000Z | include/proton/_mapped_type.hpp | calmdan/libproton | 229f2a963771049523c8a58dfa25d79b4b2417e0 | [
"BSD-2-Clause"
] | null | null | null | include/proton/_mapped_type.hpp | calmdan/libproton | 229f2a963771049523c8a58dfa25d79b4b2417e0 | [
"BSD-2-Clause"
] | null | null | null | #ifndef PROTON_MAPPED_TYPE_HEADER
#define PROTON_MAPPED_TYPE_HEADER
namespace proton{
template <typename mapT, typename K>
typename mapT::mapped_type get(const mapT& x, K&& key)
{
auto it=x.find(key);
PROTON_THROW_IF(it==x.end(), "can't find the key in a map");
return it->second;
}
template <typename mapT, typename K, typename V>
typename mapT::mapped_type get(const mapT& x, K&& key, V&& dft)
{
auto it=x.find(key);
if(it==x.end())
return dft;
return it->second;
}
template <typename mapT, typename K>
bool test_get(typename mapT::mapped_type& v, const mapT& x, K&& key)
{
auto it=x.find(key);
if(it==x.end())
return false;
v=it->second;
return true;
}
template <typename mapT, typename K, typename V>
bool test_insert(mapT& x, K&& k, V&& v)
{
return x.insert({k,v}).second;
}
template <typename mapT, typename K, typename V>
bool test_insert_or_get(mapT& x, K&& k, V& v)
{
auto p=x.insert({k,v});
if(p.second)
return true;
v=p.first->second;
return false;
}
template <typename mapT, typename K, typename ...argT>
typename mapT::mapped_type& get_or_create(bool& hit, mapT& x, K&& k, argT&& ... v)
{
auto p=x.find(k);
if(p!=x.end()){
hit= true;
return p->second;
}
hit=false;
#if 0
p=x.emplace(k, v...);
#else
p=x.insert({k,typename mapT::mapped_type(v...)}).first;
#endif
return p->second;
}
}
#endif // PROTON_MAPPED_TYPE_HEADER
| 21.304348 | 82 | 0.631293 | calmdan |
1c80b6327bfbc8e4e1b6903e5ffc1e73575f323b | 2,387 | cpp | C++ | source/std.groupboxbuttonscontrol.cpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | source/std.groupboxbuttonscontrol.cpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | source/std.groupboxbuttonscontrol.cpp | wilsonsouza/stdx.frame.x86 | c9e0cc4c748f161367531990e5795a700f40e5ec | [
"Apache-2.0"
] | null | null | null | //-----------------------------------------------------------------------------------------------//
// dedaluslib.lib for Windows
//
// Created by Wilson.Souza 2012, 2013
// For Libbs Farma
//
// Dedalus Prime
// (c) 2012, 2013
//-----------------------------------------------------------------------------------------------//
#pragma once
#include <std.groupboxbuttonscontrol.hpp>
//-----------------------------------------------------------------------------------------------//
using namespace std;
//-----------------------------------------------------------------------------------------------//
GroupBoxButtonsControl::GroupBoxButtonsControl(std::ustring const & szCaption,
int const & nCols,
int const & nOffset):
GroupBoxImpl<VerticalBox>(szCaption, szCaption)
{
SetCols(nCols);
SetOffset(nOffset);
SetName(szCaption);
SetFontSize(0xc);
SetFontStyle(QFont::Bold);
SetButtonSize(shared_ptr<QPoint>(new QPoint{ 0xc, 0xc }));
}
//-----------------------------------------------------------------------------------------------//
GroupBoxButtonsControl::~GroupBoxButtonsControl()
{
for(auto i = m_Queue->begin(); i != m_Queue->end(); i++)
i.operator->()->second->disconnect();
}
//-----------------------------------------------------------------------------------------------//
Button * GroupBoxButtonsControl::GetButton(int const nId)
{
auto p = m_Queue->find(nId);
if(p != m_Queue->end())
return p.operator->()->second;
return nullptr;
}
//-----------------------------------------------------------------------------------------------//
GroupBoxButtonsControl * GroupBoxButtonsControl::Create()
{
for(int i = 0; i <= m_Offset; ++i)
{
WidgetImpl<> * w = new WidgetImpl<>();
for(int n = 0; n < m_Cols; ++n, ++i)
{
Button * b = new Button
{
std::ustring(), QIcon(), std::ustring().sprintf("%d", i), true
};
QFont f = b->font();
{
b->setFixedSize(m_ButtonSize->x(), m_ButtonSize->y());
f.setPixelSize(m_FontSize);
f.setStyle(QFont::Style(m_FontStyle));
}
w->addWidget(b);
}
addWidget(w);
}
return this;
}
//-----------------------------------------------------------------------------------------------//
| 34.1 | 100 | 0.385002 | wilsonsouza |
1c85325531a36596e3ceaa4b65f7076b2f8050e4 | 181 | hpp | C++ | include/FrogJump.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | include/FrogJump.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | include/FrogJump.hpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #ifndef FROG_JUMP_HPP_
#define FROG_JUMP_HPP_
#include <vector>
using namespace std;
class FrogJump {
public:
bool canCross(vector<int> &stones);
};
#endif // FROG_JUMP_HPP_ | 13.923077 | 39 | 0.745856 | yanzhe-chen |
1c8c19d674c1611e12874901794e29cc4ed89d85 | 10,093 | cpp | C++ | tests/http/http_fields/main.cpp | Stiffstream/arataga | b6e1720dd2df055949847425f12bb1af56edbe83 | [
"MIT",
"Newsletr",
"BSL-1.0",
"BSD-3-Clause"
] | 14 | 2021-01-08T15:43:37.000Z | 2021-11-06T19:30:15.000Z | tests/http/http_fields/main.cpp | Stiffstream/arataga | b6e1720dd2df055949847425f12bb1af56edbe83 | [
"MIT",
"Newsletr",
"BSL-1.0",
"BSD-3-Clause"
] | 5 | 2021-03-07T06:51:33.000Z | 2021-07-01T09:54:30.000Z | tests/http/http_fields/main.cpp | Stiffstream/arataga | b6e1720dd2df055949847425f12bb1af56edbe83 | [
"MIT",
"Newsletr",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>
#include <arataga/acl_handler/buffers.hpp>
#include <restinio/helpers/string_algo.hpp>
#include <tests/connection_handler_simulator/pub.hpp>
#include <asio.hpp>
using namespace std::string_view_literals;
using namespace std::chrono_literals;
namespace chs = connection_handler_simulator;
TEST_CASE("headers without the body") {
asio::ip::tcp::endpoint proxy_endpoint{
asio::ip::make_address_v4( "127.0.0.1" ),
2444
};
chs::handler_config_values_t config_values;
config_values.m_http_headers_complete_timeout = 2s;
chs::simulator_t simulator{
proxy_endpoint,
config_values
};
asio::io_context ctx;
asio::ip::tcp::socket connection{ ctx };
REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) );
asio::ip::tcp::no_delay no_delay_opt{ true };
connection.set_option( no_delay_opt );
{
std::string_view outgoing_request{
"GET http://localhost:8080/ HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n"
"Accept: */*\r\n"
};
REQUIRE_NOTHROW( asio::write(connection,
asio::buffer(outgoing_request)) );
}
// A negative response is expected.
{
std::array< char, 512 > data;
std::size_t bytes_read;
REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) );
std::string_view response{ &data[ 0 ], bytes_read };
REQUIRE( restinio::string_algo::starts_with(
response, "HTTP/1.1 408 Request Timeout\r\n"sv ) );
}
// The connection has to be closed on the other side.
{
std::array< std::uint8_t, 20 > data;
asio::error_code ec;
REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) );
REQUIRE( asio::error::eof == ec );
}
chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() );
}
TEST_CASE("severals Host headers") {
asio::ip::tcp::endpoint proxy_endpoint{
asio::ip::make_address_v4( "127.0.0.1" ),
2444
};
chs::handler_config_values_t config_values;
config_values.m_http_headers_complete_timeout = 2s;
chs::simulator_t simulator{
proxy_endpoint,
config_values
};
asio::io_context ctx;
asio::ip::tcp::socket connection{ ctx };
REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) );
asio::ip::tcp::no_delay no_delay_opt{ true };
connection.set_option( no_delay_opt );
{
std::string_view outgoing_request{
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n"
"Host: localhost:8080\r\n"
"Accept: */*\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
REQUIRE_NOTHROW( asio::write(connection,
asio::buffer(outgoing_request)) );
}
// A negative response is expected.
{
std::array< char, 512 > data;
std::size_t bytes_read;
REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) );
std::string_view response{ &data[ 0 ], bytes_read };
REQUIRE( restinio::string_algo::starts_with(
response, "HTTP/1.1 400 Bad Request\r\n"sv ) );
}
// The connection has to be closed on the other side.
{
std::array< std::uint8_t, 20 > data;
asio::error_code ec;
REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) );
REQUIRE( asio::error::eof == ec );
}
chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() );
}
TEST_CASE("request-target too long") {
asio::ip::tcp::endpoint proxy_endpoint{
asio::ip::make_address_v4( "127.0.0.1" ),
2444
};
chs::handler_config_values_t config_values;
config_values.m_http_message_limits.m_max_request_target_length = 100u;
chs::simulator_t simulator{
proxy_endpoint,
config_values
};
asio::io_context ctx;
asio::ip::tcp::socket connection{ ctx };
REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) );
asio::ip::tcp::no_delay no_delay_opt{ true };
connection.set_option( no_delay_opt );
{
std::string_view outgoing_request{
"GET /123456789/123456789/123456789/123456789/123456789/123456789/"
"123456789/123456789/123456789/123456789/123456789/123456789 "
"HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n"
"Host: localhost:8080\r\n"
"Accept: */*\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
REQUIRE_NOTHROW( asio::write(connection,
asio::buffer(outgoing_request)) );
}
// A negative response is expected.
{
std::array< char, 512 > data;
std::size_t bytes_read;
REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) );
std::string_view response{ &data[ 0 ], bytes_read };
REQUIRE( restinio::string_algo::starts_with(
response, "HTTP/1.1 400 Bad Request\r\n"sv ) );
}
// The connection has to be closed on the other side.
{
std::array< std::uint8_t, 20 > data;
asio::error_code ec;
REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) );
REQUIRE( asio::error::eof == ec );
}
chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() );
}
TEST_CASE("HTTP-field name too long") {
asio::ip::tcp::endpoint proxy_endpoint{
asio::ip::make_address_v4( "127.0.0.1" ),
2444
};
chs::handler_config_values_t config_values;
config_values.m_http_message_limits.m_max_field_name_length = 100u;
chs::simulator_t simulator{
proxy_endpoint,
config_values
};
asio::io_context ctx;
asio::ip::tcp::socket connection{ ctx };
REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) );
asio::ip::tcp::no_delay no_delay_opt{ true };
connection.set_option( no_delay_opt );
{
std::string_view outgoing_request{
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n"
"Host: localhost:8080\r\n"
"Header-With-Very-Very-Long-Name-123456789"
"-123456789-123456789-123456789-123456789-123456789"
"-123456789-123456789-123456789-123456789-123456789: Boo!\r\n"
"Accept: */*\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
REQUIRE_NOTHROW( asio::write(connection,
asio::buffer(outgoing_request)) );
}
// A negative response is expected.
{
std::array< char, 512 > data;
std::size_t bytes_read;
REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) );
std::string_view response{ &data[ 0 ], bytes_read };
REQUIRE( restinio::string_algo::starts_with(
response, "HTTP/1.1 400 Bad Request\r\n"sv ) );
}
// The connection has to be closed on the other side.
{
std::array< std::uint8_t, 20 > data;
asio::error_code ec;
REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) );
REQUIRE( asio::error::eof == ec );
}
chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() );
}
TEST_CASE("HTTP-field value too long") {
asio::ip::tcp::endpoint proxy_endpoint{
asio::ip::make_address_v4( "127.0.0.1" ),
2444
};
chs::handler_config_values_t config_values;
config_values.m_http_message_limits.m_max_field_value_length = 100u;
chs::simulator_t simulator{
proxy_endpoint,
config_values
};
asio::io_context ctx;
asio::ip::tcp::socket connection{ ctx };
REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) );
asio::ip::tcp::no_delay no_delay_opt{ true };
connection.set_option( no_delay_opt );
{
std::string_view outgoing_request{
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n"
"Host: localhost:8080\r\n"
"Header-With-Very-Very-Long-Value: 123456789"
"-123456789-123456789-123456789-123456789-123456789"
"-123456789-123456789-123456789-123456789-123456789 Boo!\r\n"
"Accept: */*\r\n"
"Content-Length: 0\r\n"
"\r\n"
};
REQUIRE_NOTHROW( asio::write(connection,
asio::buffer(outgoing_request)) );
}
// A negative response is expected.
{
std::array< char, 512 > data;
std::size_t bytes_read;
REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) );
std::string_view response{ &data[ 0 ], bytes_read };
REQUIRE( restinio::string_algo::starts_with(
response, "HTTP/1.1 400 Bad Request\r\n"sv ) );
}
// The connection has to be closed on the other side.
{
std::array< std::uint8_t, 20 > data;
asio::error_code ec;
REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) );
REQUIRE( asio::error::eof == ec );
}
chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() );
}
TEST_CASE("total http-fields size too big") {
asio::ip::tcp::endpoint proxy_endpoint{
asio::ip::make_address_v4( "127.0.0.1" ),
2444
};
chs::handler_config_values_t config_values;
config_values.m_http_message_limits.m_max_total_headers_size = 100u;
chs::simulator_t simulator{
proxy_endpoint,
config_values
};
asio::io_context ctx;
asio::ip::tcp::socket connection{ ctx };
REQUIRE_NOTHROW( connection.connect( proxy_endpoint ) );
asio::ip::tcp::no_delay no_delay_opt{ true };
connection.set_option( no_delay_opt );
{
std::string_view outgoing_request{
"GET / HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: Keep-Alive\r\n"
"Cache-Control: no-cache\r\n"
"Host: localhost:8080\r\n"
"Accept: */*\r\n"
"Content-Length: 0\r\n"
"Dummy-Header-1: 01234567890123456789\r\n"
"Dummy-Header-2: 01234567890123456789\r\n"
"Dummy-Header-3: 01234567890123456789\r\n"
"Dummy-Header-4: 01234567890123456789\r\n"
"Dummy-Header-5: 01234567890123456789\r\n"
"Dummy-Header-6: 01234567890123456789\r\n"
"\r\n"
};
REQUIRE_NOTHROW( asio::write(connection,
asio::buffer(outgoing_request)) );
}
// A negative response is expected.
{
std::array< char, 512 > data;
std::size_t bytes_read;
REQUIRE_NOTHROW( bytes_read = connection.read_some(asio::buffer(data)) );
std::string_view response{ &data[ 0 ], bytes_read };
REQUIRE( restinio::string_algo::starts_with(
response, "HTTP/1.1 400 Bad Request\r\n"sv ) );
}
// The connection has to be closed on the other side.
{
std::array< std::uint8_t, 20 > data;
asio::error_code ec;
REQUIRE_NOTHROW( connection.read_some( asio::buffer(data), ec ) );
REQUIRE( asio::error::eof == ec );
}
chs::dump_trace( (std::cout << "-----\n"), simulator.get_trace() );
}
| 26.012887 | 75 | 0.688497 | Stiffstream |
1c97d0af2d6e76bd95eb25c247ed0c479bf1420e | 1,306 | hpp | C++ | includes/text_analysis.hpp | JaredsAlgorithms/CS-131-Project-6 | e911ef84ed3cdc89251ead24eb5cf21da7282272 | [
"MIT"
] | null | null | null | includes/text_analysis.hpp | JaredsAlgorithms/CS-131-Project-6 | e911ef84ed3cdc89251ead24eb5cf21da7282272 | [
"MIT"
] | null | null | null | includes/text_analysis.hpp | JaredsAlgorithms/CS-131-Project-6 | e911ef84ed3cdc89251ead24eb5cf21da7282272 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm> /* std::transform */
#include <iostream>
#include <list>
#include <set>
#include <string> /* not needed for Mac OSX */
#include <unordered_map>
#include <vector>
class TextAnalysis {
public:
TextAnalysis() = default;
void add_word(const std::string&, size_t); // IMPLEMENT BELOW
size_t countWord(const std::string&); // IMPLEMENT BELOW
size_t countTwoWords(const std::string&,
const std::string&); // IMPLEMENT BELOW
void read_text(std::istream&, const std::string&); // ALREADY DONE
private:
std::unordered_map<std::string, std::vector<size_t> >
wordtable; // hash table with key=word and value=vector of page numbers
};
// ALREADY DONE: BREAK A LINE INTO A LIST OF WORDS
// Courtesy of Martin Broadhurst --
// http://www.martinbroadhurst.com/how-to-split-a-string-in-c.html
template <class Container>
void split(const std::string& str, Container& cont,
const std::string& delims = " ") {
std::size_t curr, prev = 0;
curr = str.find_first_of(delims);
while (curr != std::string::npos) { // largest possible unsigned number
cont.push_back(str.substr(prev, curr - prev));
prev = curr + 1;
curr = str.find_first_of(delims, prev);
}
cont.push_back(str.substr(prev, curr - prev));
}
| 31.095238 | 78 | 0.671516 | JaredsAlgorithms |
1c98609ac81992193bbb7728945e00c6f3bfbee2 | 5,232 | cpp | C++ | VkMaterialSystem/os_input.cpp | khalladay/VkMaterialSystem | b8f83ed0ff0a4810d7f19868267d8e62f061e3c3 | [
"MIT"
] | 26 | 2017-12-04T17:51:22.000Z | 2022-02-17T16:50:54.000Z | VkMaterialSystem/os_input.cpp | khalladay/VkMaterialSystem | b8f83ed0ff0a4810d7f19868267d8e62f061e3c3 | [
"MIT"
] | 1 | 2019-07-08T12:48:30.000Z | 2019-08-09T11:51:08.000Z | VkMaterialSystem/os_input.cpp | khalladay/VkMaterialSystem | b8f83ed0ff0a4810d7f19868267d8e62f061e3c3 | [
"MIT"
] | 4 | 2018-06-14T18:31:07.000Z | 2022-02-28T12:16:00.000Z | #pragma once
#include "stdafx.h"
#include "os_input.h"
#include "os_support.h"
#define checkhf(expr, format, ...) if (FAILED(expr)) \
{ \
fprintf(stdout, "CHECK FAILED: %s:%d:%s " format "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__); \
CString dbgstr; \
dbgstr.Format(("%s"), format); \
MessageBox(NULL,dbgstr, "FATAL ERROR", MB_OK); \
}
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
struct InputState
{
int screenWidth;
int screenHeight;
int mouseX;
int mouseY;
int mouseDX;
int mouseDY;
unsigned char keyStates[256];
DIMOUSESTATE mouseState;
IDirectInput8* diDevice;
IDirectInputDevice8* diKeyboard;
IDirectInputDevice8* diMouse;
};
InputState GInputState;
void os_initializeInput()
{
HRESULT result;
GInputState.screenHeight = GAppInfo.curH;
GInputState.screenWidth = GAppInfo.curH;
GInputState.mouseX = 0;
GInputState.mouseY = 0;
// Initialize the main direct input interface.
result = DirectInput8Create(GAppInfo.instance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&GInputState.diDevice, NULL);
checkhf(result, "Failed to create DirectInput device");
// Initialize the direct input interface for the keyboard.
result = GInputState.diDevice->CreateDevice(GUID_SysKeyboard, &GInputState.diKeyboard, NULL);
checkhf(result, "Failed to create DirectInput keyboard");
// Set the data format. In this case since it is a keyboard we can use the predefined data format.
result = GInputState.diKeyboard->SetDataFormat(&c_dfDIKeyboard);
checkhf(result, "Failed to set data format for DirectInput kayboard");
// Set the cooperative level of the keyboard to not share with other programs.
result = GInputState.diKeyboard->SetCooperativeLevel(GAppInfo.wndHdl, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
checkhf(result, "Failed to set keyboard to foreground exclusive");
// Now acquire the keyboard.
result = GInputState.diKeyboard->Acquire();
checkhf(result, "Failed to acquire DI Keyboard");
// Initialize the direct input interface for the mouse.
result = GInputState.diDevice->CreateDevice(GUID_SysMouse, &GInputState.diMouse, NULL);
checkhf(result, "Failed ot create DirectInput keyboard");
// Set the data format for the mouse using the pre-defined mouse data format.
result = GInputState.diMouse->SetDataFormat(&c_dfDIMouse);
checkhf(result, "Failed to set data format for DirectInput mouse");
//result = GInputState.diMouse->SetCooperativeLevel(wndHdl, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
//checkhf(result, "Failed to get exclusive access to DirectInput mouse");
// Acquire the mouse.
result = GInputState.diMouse->Acquire();
checkhf(result, "Failed to acquire DirectInput mouse");
}
void os_pollInput()
{
HRESULT result;
// Read the keyboard device.
result = GInputState.diKeyboard->GetDeviceState(sizeof(GInputState.keyStates), (LPVOID)&GInputState.keyStates);
if (FAILED(result))
{
// If the keyboard lost focus or was not acquired then try to get control back.
if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED))
{
GInputState.diKeyboard->Acquire();
}
else
{
checkf(0, "Error polling keyboard");
}
}
// Read the mouse device.
result = GInputState.diMouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&GInputState.mouseState);
if (FAILED(result))
{
// If the mouse lost focus or was not acquired then try to get control back.
if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED))
{
GInputState.diMouse->Acquire();
}
else
{
checkf(0, "Error polling mouse");
}
}
// Update the location of the mouse cursor based on the change of the mouse location during the frame.
GInputState.mouseX += GInputState.mouseState.lX;
GInputState.mouseY += GInputState.mouseState.lY;
GInputState.mouseDX = GInputState.mouseState.lX;
GInputState.mouseDY = GInputState.mouseState.lY;
// Ensure the mouse location doesn't exceed the screen width or height.
if (GInputState.mouseX < 0) { GInputState.mouseX = 0; }
if (GInputState.mouseY < 0) { GInputState.mouseY = 0; }
if (GInputState.mouseX > GInputState.screenWidth) { GInputState.mouseX = GInputState.screenWidth; }
if (GInputState.mouseY > GInputState.screenHeight) { GInputState.mouseY = GInputState.screenHeight; }
}
void os_shutdownInput()
{
if (GInputState.diMouse)
{
GInputState.diMouse->Unacquire();
GInputState.diMouse->Release();
GInputState.diMouse = 0;
}
// Release the keyboard.
if (GInputState.diKeyboard)
{
GInputState.diKeyboard->Unacquire();
GInputState.diKeyboard->Release();
GInputState.diKeyboard = 0;
}
// Release the main interface to direct input.
if (GInputState.diDevice)
{
GInputState.diDevice->Release();
GInputState.diDevice = 0;
}
}
bool getKey(KeyCode key)
{
return GInputState.keyStates[key] > 0;
}
int getMouseDX()
{
return GInputState.mouseDX;
}
int getMouseDY()
{
return GInputState.mouseDY;
}
int getMouseX()
{
return GInputState.mouseX;
}
int getMouseY()
{
return GInputState.mouseY;
}
int getMouseLeftButton()
{
return GInputState.mouseState.rgbButtons[0] > 0;
}
int getMouseRightButton()
{
return GInputState.mouseState.rgbButtons[2] > 0;
} | 27.536842 | 125 | 0.728402 | khalladay |
1c9a2ee7e7d53924ad0bc7a2663238d2aeb48c86 | 1,222 | cpp | C++ | 0639-Word Abbreviation/0639-Word Abbreviation.cpp | akekho/LintCode | 2d31f1ec092d89e70d5059c7fb2df2ee03da5981 | [
"MIT"
] | 77 | 2017-12-30T13:33:37.000Z | 2022-01-16T23:47:08.000Z | 0601-0700/0639-Word Abbreviation/0639-Word Abbreviation.cpp | jxhangithub/LintCode-1 | a8aecc65c47a944e9debad1971a7bc6b8776e48b | [
"MIT"
] | 1 | 2018-05-14T14:15:40.000Z | 2018-05-14T14:15:40.000Z | 0601-0700/0639-Word Abbreviation/0639-Word Abbreviation.cpp | jxhangithub/LintCode-1 | a8aecc65c47a944e9debad1971a7bc6b8776e48b | [
"MIT"
] | 39 | 2017-12-07T14:36:25.000Z | 2022-03-10T23:05:37.000Z | class Solution {
public:
/**
* @param dict: an array of n distinct non-empty strings
* @return: an array of minimal possible abbreviations for every word
*/
vector<string> wordsAbbreviation(vector<string> &dict) {
// write your code here
int n = dict.size();
unordered_map<string, int> table;
vector<int> prefix(n, 1);
vector<string> result(n);
for (int i = 0; i < n; ++i) {
string s = getAbbr(dict[i], prefix[i]);
result[i] = s;
++table[s];
}
bool unique = true;
do {
unique = true;
for (int i = 0; i < n; ++i) {
if (table[result[i]] > 1) {
string s = getAbbr(dict[i], ++prefix[i]);
result[i] = s;
++table[s];
unique = false;
}
}
} while (!unique);
return result;
}
private:
string getAbbr(string& s, int prefix) {
if (prefix >= int(s.size()) - 2) {
return s;
}
return s.substr(0, prefix) + to_string(s.size() - 1 - prefix) + s.back();
}
};
| 27.772727 | 82 | 0.438625 | akekho |
1ca2a7117330734b01c768bfca8c047ff7a1daa8 | 5,469 | cpp | C++ | src/obj_reg.cpp | robinzhoucmu/MLab_TrackingMocap | e9bd71ea546c545dfb1f4f406e72fe2822992046 | [
"BSD-2-Clause"
] | null | null | null | src/obj_reg.cpp | robinzhoucmu/MLab_TrackingMocap | e9bd71ea546c545dfb1f4f406e72fe2822992046 | [
"BSD-2-Clause"
] | null | null | null | src/obj_reg.cpp | robinzhoucmu/MLab_TrackingMocap | e9bd71ea546c545dfb1f4f406e72fe2822992046 | [
"BSD-2-Clause"
] | null | null | null | #include "obj_reg.h"
ObjectReg::ObjectReg() {
}
void ObjectReg::Serialize(std::ostream & fout) {
// First 3 lines of cali marker positions.
for (int i = 0; i < 3; ++i) {
const Vec& p = cali_markers_pos[i];
for (int j = 0; j < 3; ++j ) {
fout << p[j] << " ";
}
fout << std::endl;
}
// Serialize relevant homogenious transformations.
SerializeHomog(fout, tf_robot_mctractable);
SerializeHomog(fout, tf_robot_calimarkers);
SerializeHomog(fout, tf_mctractable_obj);
}
void ObjectReg::Deserialize(std::istream& fin) {
// Deserialize vector of cali marker positions.
cali_markers_pos.clear();
for (int i = 0; i < 3; ++i) {
Vec p(3);
for (int j = 0; j < 3; ++j) {
fin >> p[j];
}
cali_markers_pos.push_back(p);
}
DeserializeHomog(fin, &tf_robot_mctractable);
DeserializeHomog(fin, &tf_robot_calimarkers);
DeserializeHomog(fin, &tf_mctractable_obj);
}
void ObjectReg::DeserializeHomog(std::istream& fin, HomogTransf* tf) {
double tf_mat[4][4];
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
fin >> tf_mat[i][j];
}
}
*tf = HomogTransf(tf_mat);
}
void ObjectReg::SerializeHomog(std::ostream& fout, const HomogTransf& tf) {
assert(tf.nn == 4 && tf.mm == 4);
for (int i = 0; i < tf.nn; ++i) {
for (int j = 0; j < tf.mm; ++j) {
fout << tf[i][j]<< " ";
}
fout << std::endl;
}
}
void ObjectReg::ReadCaliMarkersFromMocap(MocapComm& mocap_comm) {
cali_markers_pos.clear();
Mocap::mocap_frame mocap_msg;
mocap_comm.GetMocapFrame(&mocap_msg);
// Extract cali markers(which NatNet will treat as unidenfied markers).
int num_markers = mocap_msg.uid_markers.markers.size();
// Check for size.
assert(num_markers == 3);
for (int i = 0; i < num_markers; ++i) {
const geometry_msgs::Point& pt_mocap = mocap_msg.uid_markers.markers[i];
Vec pt(3);
pt[0] = pt_mocap.x;
pt[1] = pt_mocap.y;
pt[2] = pt_mocap.z;
cali_markers_pos.push_back(pt);
}
FormCaliMarkerCoordinateFrame();
}
void ObjectReg::FormCaliMarkerCoordinateFrame() {
int num_markers = cali_markers_pos.size();
assert(num_markers == 3);
int id_origin = -1;
const double eps_dot_product = 0.1;
Vec axis_x;
Vec axis_y;
for (int i = 0; i < num_markers; ++i) {
// Determine the ith point can be set as the origin.
// Check the angle between axis is close to right angle or not.
axis_x = cali_markers_pos[(i+1) % num_markers] - cali_markers_pos[i];
axis_y = cali_markers_pos[(i+2) % num_markers] - cali_markers_pos[i];
const double norm_axis_x = sqrt(axis_x * axis_x);
const double norm_axis_y = sqrt(axis_y * axis_y);
// Use the longer axis as the y axis.
if (norm_axis_x > norm_axis_y) {
Vec tmp = axis_x;
axis_x = axis_y;
axis_y = tmp;
}
// Check dot product.
double dot_product =
(axis_x * axis_y) / (sqrt(axis_x * axis_x) * sqrt(axis_y * axis_y));
if (dot_product < eps_dot_product) {
id_origin = i;
break;
}
}
double z[3] = {0, 0, 1};
Vec axis_z(z,3);
// axis_x and axis_y may not be perfectly perpendicular, we reset axis_x as
// the cross-product of axis_z and axis_y.
// Todo(Jiaji): Find the nearest rotation matrix by projection.
axis_x = axis_y ^ axis_z;
// Form the RefFrame.
RotMat rot_mat(axis_x, axis_y, axis_z);
// Form the Translation.
Vec trans(cali_markers_pos[id_origin]);
// Update the homogenious transformation.
tf_robot_calimarkers.setRotation(rot_mat);
tf_robot_calimarkers.setTranslation(trans);
}
void ObjectReg::ReadTractablePoseFromMocap(MocapComm& mocap_comm) {
Mocap::mocap_frame mocap_msg;
mocap_comm.GetMocapFrame(&mocap_msg);
// We are assuming during registration process, there is only one tractable in view.
assert(mocap_msg.body_poses.poses.size() == 1);
// Extract pose from mocap output.
double tractable_pose[7];
geometry_msgs::Pose pose = mocap_msg.body_poses.poses[0];
tractable_pose[0] = pose.position.x;
tractable_pose[1] = pose.position.y;
tractable_pose[2] = pose.position.z;
tractable_pose[3] = pose.orientation.x;
tractable_pose[4] = pose.orientation.y;
tractable_pose[5] = pose.orientation.z;
tractable_pose[6] = pose.orientation.w;
// Update the tf.
tf_robot_mctractable.setPose(tractable_pose);
}
void ObjectReg::ComputeTransformation() {
tf_mctractable_obj = tf_robot_mctractable.inv() * tf_robot_calimarkers;
}
int main(int argc, char* argv[]) {
ros::init(argc, argv, "ObjectRegistration");
ros::NodeHandle np;
MocapComm mocap_comm(&np);
ObjectReg obj_reg;
// Shell based interactive process.
std::cout << "Object Registration Process Starts. Remeber to calibrate mocap frame to robot base frame first." << std::endl;
std::cout << "Place JUST the paper cali markers on the table." << std::endl;
std::cout << "Input Object Name" << std::endl;
std::string name;
std::cin >> name;
obj_reg.SetObjName(name);
std::cout << "Setting Up Cali Marker Frame" << std::endl;
//std::cout << "Enter any key to start acquiring" << std::endl;
system("Pause");
obj_reg.ReadCaliMarkersFromMocap(mocap_comm);
std::cout << "Now put the object on the paper." << std::endl;
system("Pause");
obj_reg.ReadTractablePoseFromMocap(mocap_comm);
std::cout << "Computing transformation." << std::endl;
obj_reg.ComputeTransformation();
std::cout << obj_reg.GetTransformation() << std::endl;
return 0;
}
| 31.796512 | 126 | 0.669592 | robinzhoucmu |
1caab0212a24f6b421caa406dfc7099da758fd9c | 2,749 | cc | C++ | autolign.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | autolign.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | autolign.cc | jdb19937/makemore | 61297dd322b3a9bb6cdfdd15e8886383cb490534 | [
"MIT"
] | null | null | null | #include "project.hh"
#include "topology.hh"
#include "random.hh"
#include "cudamem.hh"
#include "project.hh"
#include "ppm.hh"
#include "warp.hh"
#include "partrait.hh"
#include "encgen.hh"
#include "autoposer.hh"
#include "imgutils.hh"
#include <math.h>
#include <map>
using namespace makemore;
int main(int argc, char **argv) {
seedrand();
Autoposer autoposer("bestposer.proj");
Autoposer autoposer2("newposer.proj");
Encgen egd("bigsham.proj", 1);
Partrait par;
Pose curpose;
bool first = 1;
while (par.read_ppm(stdin)) {
if (first) {
curpose = Pose::STANDARD;
curpose.scale = 64;
curpose.center.x = (double)par.w / 2.0;
curpose.center.y = (double)par.h / 2.0;
par.set_pose(curpose);
}
first = 0;
Pose lastpose = par.get_pose();
double cdrift = 0.2;
double sdrift = 0.5;
double drift = 0.5;
curpose.center.x = (1.0 - cdrift) * lastpose.center.x + cdrift * (par.w / 2.0);
curpose.center.y = (1.0 - cdrift) * lastpose.center.y + cdrift * (par.h / 2.0);
curpose.scale = (1.0 - sdrift) * lastpose.scale + sdrift * 64.0;
curpose.angle = (1.0 - drift) * lastpose.angle;
curpose.stretch = (1.0 - drift) * lastpose.stretch + 1.0 * drift;
curpose.skew = (1.0 - drift) * lastpose.skew;
if (curpose.center.x < 0) curpose.center.x = 0;
if (curpose.center.x >= par.w) curpose.center.x = par.w - 1;
if (curpose.center.y < 0) curpose.center.y = 0;
if (curpose.center.y >= par.h) curpose.center.y = par.h - 1;
if (curpose.skew > 0.1) curpose.skew = 0.1;
if (curpose.skew < -0.1) curpose.skew = -0.1;
if (curpose.scale > 128.0) curpose.scale = 128.0;
if (curpose.scale < 32.0) curpose.scale = 32.0;
if (curpose.angle > 1.0) curpose.angle = 1.0;
if (curpose.angle < -1.0) curpose.angle = -1.0;
if (curpose.stretch > 1.2) curpose.stretch = 1.2;
if (curpose.stretch < 0.8) curpose.stretch = 0.8;
par.set_pose(curpose);
autoposer.autopose(&par);
autoposer2.autopose(&par);
autoposer2.autopose(&par);
Partrait stdpar(256, 256);
stdpar.set_pose(Pose::STANDARD);
par.warp(&stdpar);
memset(egd.ctxbuf, 0, egd.ctxlay->n * sizeof(double));
stdpar.make_sketch(egd.ctxbuf);
Hashbag hb;
hb.add("white");
hb.add("male");
memcpy(egd.ctxbuf + 192, hb.vec, sizeof(double) * 64);
egd.ctxbuf[256] = par.get_tag("angle", 0.0);
egd.ctxbuf[257] = par.get_tag("stretch", 1.0);
egd.ctxbuf[258] = par.get_tag("skew", 0.0);
assert(egd.tgtlay->n == stdpar.w * stdpar.h * 3);
rgblab(stdpar.rgb, egd.tgtlay->n, egd.tgtbuf);
egd.encode();
egd.generate();
labrgb(egd.tgtbuf, egd.tgtlay->n, stdpar.rgb);
stdpar.warpover(&par);
par.write_ppm(stdout);
}
return 0;
}
| 26.432692 | 83 | 0.624227 | jdb19937 |
1cb37e2cd6062198c9923ef3446250367fbe4e49 | 802 | hpp | C++ | include/pipes/override.hpp | LouisCharlesC/pipes | 1100066894ceca3aebfc3e2fa12287600ab3a0f6 | [
"MIT"
] | null | null | null | include/pipes/override.hpp | LouisCharlesC/pipes | 1100066894ceca3aebfc3e2fa12287600ab3a0f6 | [
"MIT"
] | null | null | null | include/pipes/override.hpp | LouisCharlesC/pipes | 1100066894ceca3aebfc3e2fa12287600ab3a0f6 | [
"MIT"
] | null | null | null | #ifndef BEGIN_HPP
#define BEGIN_HPP
#include "pipes/operator.hpp"
#include "pipes/base.hpp"
#include <iterator>
#include <utility>
namespace pipes
{
template<typename Iterator>
class override_pipeline : public pipeline_base<override_pipeline<Iterator>>
{
public:
template<typename T>
void onReceive(T&& value)
{
*iterator_ = FWD(value);
++iterator_;
}
explicit override_pipeline(Iterator iterator) : iterator_(iterator) {}
private:
Iterator iterator_;
};
template<typename Container>
auto override(Container& container)
{
using std::begin;
return override_pipeline<decltype(begin(std::declval<Container&>()))>{begin(container)};
}
}
#endif /* BEGIN_HPP */
| 21.675676 | 96 | 0.630923 | LouisCharlesC |
1cbb247d98e296b1933ce7cc4988b8bd682a6119 | 743 | hpp | C++ | SDK/ARKSurvivalEvolved_DmgType_Trike_Reflected_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_DmgType_Trike_Reflected_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_DmgType_Trike_Reflected_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DmgType_Trike_Reflected_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass DmgType_Trike_Reflected.DmgType_Trike_Reflected_C
// 0x0000 (0x0131 - 0x0131)
class UDmgType_Trike_Reflected_C : public UDmgType_Instant_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass DmgType_Trike_Reflected.DmgType_Trike_Reflected_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 20.081081 | 116 | 0.621803 | 2bite |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.