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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f3e67bcc99af3578c85899010489b651df0ac53b
| 2,162
|
hpp
|
C++
|
include/networkit/distance/DynSSSP.hpp
|
clintg6/networkit
|
b4cba9a82436cd7ebc139c1a612f593fca9892c6
|
[
"MIT"
] | null | null | null |
include/networkit/distance/DynSSSP.hpp
|
clintg6/networkit
|
b4cba9a82436cd7ebc139c1a612f593fca9892c6
|
[
"MIT"
] | null | null | null |
include/networkit/distance/DynSSSP.hpp
|
clintg6/networkit
|
b4cba9a82436cd7ebc139c1a612f593fca9892c6
|
[
"MIT"
] | null | null | null |
/*
* DynSSSP.h
*
* Created on: 17.07.2014
* Author: cls, ebergamini
*/
#ifndef DYNSSSP_H_
#define DYNSSSP_H_
#include <set>
#include "../graph/Graph.hpp"
#include "../dynamics/GraphEvent.hpp"
#include "../base/DynAlgorithm.hpp"
#include "SSSP.hpp"
namespace NetworKit {
/**
* @ingroup distance
* Interface for dynamic single-source shortest path algorithms.
*/
class DynSSSP: public SSSP, public DynAlgorithm {
friend class DynApproxBetweenness;
public:
/**
* The algorithm computes a dynamic SSSP starting from the specified
* source vertex.
*
* @param graph input graph.
* @param source source vertex.
* @param storePredecessors keep track of the lists of predecessors?
*/
DynSSSP(const Graph& G, node source, bool storePredecessors = true, node target = none);
virtual ~DynSSSP() = default;
/**
* Returns true or false depending on whether the node previoulsy specified
* with setTargetNode has been modified by the udate or not.
*
* @param batch The batch of edge insertions.
*/
bool modified();
/**
* Set a target node to be `observed` during the update. If a node t is set as
* target before the update, the function modified() will return true or false
* depending on whether node t has been modified by the update.
*
* @param t Node to be `observed`.
*/
void setTargetNode(const node t = 0);
/**
* Returns the predecessor nodes of @a t on all shortest paths from source to @a t.
* @param t Target node.
* @return The predecessors of @a t on all shortest paths from source to @a t.
*/
std::vector<node> getPredecessors(node t) const;
protected:
bool storePreds = true;
bool mod = false;
node target;
};
inline bool DynSSSP::modified() {
return mod;
}
inline void DynSSSP::setTargetNode(const node t) {
target = t;
}
inline std::vector<node> DynSSSP::getPredecessors(node t) const {
if (! storePreds) {
throw std::runtime_error("predecessors have not been stored");
}
return previous[t];
}
} /* namespace NetworKit */
#endif /* DYNSSSP_H_ */
| 24.568182
| 92
| 0.659574
|
clintg6
|
f3e67c82fb3151c54498b26c631c0785084c8503
| 3,446
|
cpp
|
C++
|
Tools/Buffer.cpp
|
triplewz/MP-SPDZ
|
a858e5b440902ec25dbb97c555eef35e12fbf69c
|
[
"BSD-2-Clause"
] | null | null | null |
Tools/Buffer.cpp
|
triplewz/MP-SPDZ
|
a858e5b440902ec25dbb97c555eef35e12fbf69c
|
[
"BSD-2-Clause"
] | null | null | null |
Tools/Buffer.cpp
|
triplewz/MP-SPDZ
|
a858e5b440902ec25dbb97c555eef35e12fbf69c
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Buffer.cpp
*
*/
#include "Tools/Buffer.h"
#include "Processor/BaseMachine.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
bool BufferBase::rewind = false;
void BufferBase::setup(ifstream* f, int length, const string& filename,
const char* type, const string& field)
{
file = f;
tuple_length = length;
data_type = type;
field_type = field;
this->filename = filename;
}
bool BufferBase::is_pipe()
{
struct stat buf;
if (stat(filename.c_str(), &buf) == 0)
return S_ISFIFO(buf.st_mode);
else
return false;
}
void BufferBase::seekg(int pos)
{
assert(not is_pipe());
#ifdef DEBUG_BUFFER
if (pos != 0)
printf("seek %d %s thread %d\n", pos, filename.c_str(),
BaseMachine::thread_num);
#endif
if (not file)
{
if (pos == 0)
return;
else
file = open();
}
file->seekg(header_length + pos * tuple_length);
if (file->eof() || file->fail())
{
// let it go in case we don't need it anyway
if (pos != 0)
try_rewind();
}
#ifdef DEBUG_BUFFER
printf("seek %d %d thread %d\n", pos, int(file->tellg()),
BaseMachine::thread_num);
#endif
next = BUFFER_SIZE;
}
void BufferBase::try_rewind()
{
assert(not is_pipe());
#ifndef INSECURE
string type;
if (field_type.size() and data_type.size())
type = (string)" of " + field_type + " " + data_type;
throw not_enough_to_buffer(type, filename);
#endif
file->clear(); // unset EOF flag
file->seekg(header_length);
if (file->peek() == ifstream::traits_type::eof())
throw runtime_error("empty file: " + filename);
if (!rewind)
cerr << "REWINDING - ONLY FOR BENCHMARKING" << endl;
rewind = true;
eof = true;
}
void BufferBase::prune()
{
// only prune in secure mode
#ifdef INSECURE
return;
#endif
if (is_pipe())
return;
if (file and (not file->good() or file->peek() == EOF))
purge();
else if (file and file->tellg() != header_length)
{
#ifdef VERBOSE
cerr << "Pruning " << filename << endl;
#endif
string tmp_name = filename + ".new";
ofstream tmp(tmp_name.c_str());
size_t start = file->tellg();
char buf[header_length];
file->seekg(0);
file->read(buf, header_length);
tmp.write(buf, header_length);
file->seekg(start);
tmp << file->rdbuf();
if (tmp.fail())
throw runtime_error(
"problem writing to " + tmp_name + " from "
+ to_string(start) + " of " + filename);
tmp.close();
file->close();
rename(tmp_name.c_str(), filename.c_str());
file->open(filename.c_str(), ios::in | ios::binary);
}
#ifdef VERBOSE
else
{
cerr << "Not pruning " << filename << " because it's ";
if (file)
cerr << "closed";
else
cerr << "unused";
cerr << endl;
}
#endif
}
void BufferBase::purge()
{
if (file and not is_pipe())
{
#ifdef VERBOSE
cerr << "Removing " << filename << endl;
#endif
unlink(filename.c_str());
file->close();
file = 0;
}
}
void BufferBase::check_tuple_length(int tuple_length)
{
if (tuple_length != this->tuple_length)
throw Processor_Error("inconsistent tuple length");
}
| 22.671053
| 71
| 0.557748
|
triplewz
|
f3e88d6ebc212dd0b9f2d59a2012d18bcc6122ef
| 4,034
|
hpp
|
C++
|
include/universal/native/nonconstexpr/msvc_long_double.hpp
|
Afonso-2403/universal
|
bddd1489de6476ee60bd45e473b918b6c7a4bce6
|
[
"MIT"
] | null | null | null |
include/universal/native/nonconstexpr/msvc_long_double.hpp
|
Afonso-2403/universal
|
bddd1489de6476ee60bd45e473b918b6c7a4bce6
|
[
"MIT"
] | null | null | null |
include/universal/native/nonconstexpr/msvc_long_double.hpp
|
Afonso-2403/universal
|
bddd1489de6476ee60bd45e473b918b6c7a4bce6
|
[
"MIT"
] | null | null | null |
#pragma once
// msvc_long_double.hpp: nonconstexpr implementation of IEEE-754 long double manipulators
//
// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#if defined(_MSC_VER)
/* Microsoft Visual Studio. --------------------------------- */
// Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER will be 15002070601
namespace sw::universal {
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// compiler specific long double IEEE floating point
// Visual C++ does not support long double, it is just an alias for double
/*
union long_double_decoder {
long double ld;
struct {
uint64_t fraction : 52;
uint64_t exponent : 11;
uint64_t sign : 1;
} parts;
};
*/
// generate a binary string for a native long double precision IEEE floating point
inline std::string to_hex(long double number) {
return to_hex(double(number));
}
// generate a binary string for a native long double precision IEEE floating point
inline std::string to_binary(long double number, bool bNibbleMarker = false) {
return to_binary(double(number), bNibbleMarker);
}
// return in triple form (+, scale, fraction)
inline std::string to_triple(long double number) {
return to_triple(double(number));
}
// generate a color coded binary string for a native long double precision IEEE floating point
inline std::string color_print(long double number) {
return color_print(double(number));
}
// floating point component extractions
inline void extract_fp_components(float fp, bool& _sign, int& _exponent, float& _fr, uint32_t& _fraction) {
static_assert(sizeof(float) == 4, "This function only works when float is 32 bit.");
_sign = fp < 0.0 ? true : false;
_fr = frexpf(fp, &_exponent);
_fraction = uint32_t(0x007FFFFFul) & reinterpret_cast<uint32_t&>(_fr);
}
inline void extract_fp_components(double fp, bool& _sign, int& _exponent, double& _fr, uint64_t& _fraction) {
static_assert(sizeof(double) == 8, "This function only works when double is 64 bit.");
_sign = fp < 0.0 ? true : false;
_fr = frexp(fp, &_exponent);
_fraction = uint64_t(0x000FFFFFFFFFFFFFull) & reinterpret_cast<uint64_t&>(_fr);
}
#ifdef CPLUSPLUS_17
inline void extract_fp_components(long double fp, bool& _sign, int& _exponent, long double& _fr, uint64_t& _fraction) {
static_assert(std::numeric_limits<long double>::digits <= 64, "This function only works when long double significant is <= 64 bit.");
if (sizeof(long double) == 8) { // it is just a double
_sign = fp < 0.0 ? true : false;
_fr = frexp(double(fp), &_exponent);
_fraction = uint64_t(0x000FFFFFFFFFFFFFull) & reinterpret_cast<uint64_t&>(_fr);
}
else if (sizeof(long double) == 16 && std::numeric_limits<long double>::digits <= 64) {
_sign = fp < 0.0 ? true : false;
_fr = frexpl(fp, &_exponent);
_fraction = uint64_t(0x7FFFFFFFFFFFFFFFull) & reinterpret_cast<uint64_t&>(_fr); // 80bit extended format only has 63bits of fraction
}
}
#else
#ifdef _MSC_VER
#pragma warning(disable : 4127) // warning C4127: conditional expression is constant
#endif
inline void extract_fp_components(long double fp, bool& _sign, int& _exponent, long double& _fr, uint64_t& _fraction) {
static_assert(std::numeric_limits<long double>::digits <= 64, "This function only works when long double significant is <= 64 bit.");
if (sizeof(long double) == 8) { // check if (long double) is aliased to be just a double
_sign = fp < 0.0 ? true : false;
_fr = frexp(double(fp), &_exponent);
_fraction = uint64_t(0x000FFFFFFFFFFFFFull) & reinterpret_cast<uint64_t&>(_fr);
}
else if (sizeof(long double) == 16 && std::numeric_limits<long double>::digits <= 64) {
_sign = fp < 0.0 ? true : false;
_fr = frexpl(fp, &_exponent);
_fraction = uint64_t(0x7FFFFFFFFFFFFFFFull) & reinterpret_cast<uint64_t&>(_fr); // 80bit extended format only has 63bits of fraction
}
}
#endif
} // namespace sw::universal
#endif // MSVC
| 39.940594
| 134
| 0.705007
|
Afonso-2403
|
f3e97ec15f36d087a6cd0887de847d2fbd78d8c8
| 5,183
|
cpp
|
C++
|
test/tst_buffer_io.cpp
|
demonatic/Rinx
|
6e89150ea1ee22a90534c682e32923a30ed044e8
|
[
"MIT"
] | 3
|
2020-05-21T09:23:59.000Z
|
2021-03-17T09:17:55.000Z
|
test/tst_buffer_io.cpp
|
demonatic/Rinx
|
6e89150ea1ee22a90534c682e32923a30ed044e8
|
[
"MIT"
] | null | null | null |
test/tst_buffer_io.cpp
|
demonatic/Rinx
|
6e89150ea1ee22a90534c682e32923a30ed044e8
|
[
"MIT"
] | null | null | null |
#ifndef TST_BUFFER_TEST_H
#define TST_BUFFER_TEST_H
#include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>
#include <fstream>
#include "Rinx/Network/Buffer.h"
#include <sys/fcntl.h>
using namespace testing;
using namespace Rinx;
TEST(sock_rw_test, testset)
{
std::unique_ptr<ChainBuffer> buf=ChainBuffer::create_chain_buffer();
RxReadRc read_res;
ssize_t read_bytes=buf->read_from_fd(RxFD{RxFDType::FD_REGULAR_FILE,STDIN_FILENO},read_res);
EXPECT_EQ(read_res, RxReadRc::OK);
std::cout<<"begin-end distance="<<buf->end()-buf->begin()<<std::endl;
EXPECT_EQ(read_bytes,buf->end()-buf->begin());
EXPECT_EQ(read_bytes-read_bytes/2,buf->end()-(buf->begin()+read_bytes/2));
for(int i=0;i<read_bytes;i++){
auto it=buf->begin()+i;
EXPECT_EQ(it-buf->begin(),i);
}
std::cout<<"buf ref num="<<buf->buf_slice_num()<<std::endl;
std::cout<<"[print ++]"<<std::endl;
std::vector<int> read_plus_plus,read_plus_equal,read_reverse_minus_minus,read_reverse_minus_equal;
for(auto it=buf->begin();it!=buf->end();++it){
read_plus_plus.push_back(*it);
std::cout<<*it;
}
std::cout<<"[print +=1]"<<std::endl;
for(auto it=buf->begin();it!=buf->end();it+=1){
read_plus_equal.push_back(*it);
std::cout<<*it;
}
std::cout<<std::endl<<"[print --]"<<std::endl;
for(auto it=--buf->end();;--it){
read_reverse_minus_minus.push_back(*it);
std::cout<<*it;
if(it==buf->begin()){
break;
}
}
std::cout<<std::endl<<"[print -=1]"<<std::endl;
for(auto it=--buf->end();;){
read_reverse_minus_equal.push_back(*it);
std::cout<<*it;
if(it==buf->begin()){
break;
}
it-=1;
}
EXPECT_EQ(read_plus_plus,read_plus_equal);
std::reverse(read_reverse_minus_minus.begin(),read_reverse_minus_minus.end());
std::reverse(read_reverse_minus_equal.begin(),read_reverse_minus_equal.end());
EXPECT_EQ(read_plus_equal,read_reverse_minus_minus);
EXPECT_EQ(read_reverse_minus_minus,read_reverse_minus_equal);
RxWriteRc write_res;
std::cout<<std::endl<<"about to write fd------"<<std::endl;
ssize_t write_bytes=buf->write_to_fd(RxFD{RxFDType::FD_REGULAR_FILE,STDOUT_FILENO},write_res);
std::cout<<"has written fd------"<<std::endl;
std::cout<<"read "<<read_bytes<<" write "<<write_bytes<<std::endl;
EXPECT_EQ(write_res, RxWriteRc::OK);
EXPECT_EQ(read_bytes,write_bytes);
}
TEST(file_rw_test,testset){
std::ofstream source_file("./test.txt");
std::string source_str="!!!I love C plus plus\n";
source_file<<source_str;
source_file.close();
std::unique_ptr<ChainBuffer> buf=ChainBuffer::create_chain_buffer();
std::string prepend="An apple a day keep the doctor away\n";
std::string append="Now there is no turning back cause mine's dropped off me\n";
*buf<<prepend;
EXPECT_EQ(prepend.size(),buf->readable_size());
RxFD file_read;
FDHelper::RegFile::open("./test.txt",file_read);
long file_length=FDHelper::RegFile::get_file_length(file_read);
std::cout<<"read file length="<<file_length<<std::endl;
int offset=3;
bool res=buf->read_from_regular_file(file_read,file_length,offset);
EXPECT_EQ(prepend.size()+file_length-offset,buf->readable_size());
*buf<<append;
EXPECT_EQ(res,true);
std::string join_str=prepend+source_str.substr(offset)+append;
size_t i=0;
EXPECT_EQ(buf->readable_size(),join_str.size());
for(auto it=buf->begin();it!=buf->end();++it){
std::cout<<*it;
EXPECT_EQ(*it,join_str[i++]);
}
// RxFD file_write;
// file_write.raw=::open("./write_file.txt",O_RDWR|O_CREAT,0777);
// file_write.type=RxFDType::FD_REGULAR_FILE;
// RxWriteRc rc;
// buf->write_to_fd(file_write,rc);
// EXPECT_EQ(rc,RxWriteRc::OK);
// FDHelper::close(file_write);
// RxFD file_write_check;
// EXPECT_EQ(FDHelper::RegFile::open("./write_file.txt",file_write_check),true);
// buf->read_from_regular_file(file_write_check,FDHelper::RegFile::get_file_length(file_write_check));
// size_t j=0;
// for(auto it=buf->begin();it!=buf->end();++it){
// std::cout<<*it;
// EXPECT_EQ(*it,join_str[j++]);
// }
}
TEST(write_data_test,testset){
std::unique_ptr<ChainBuffer> buf=ChainBuffer::create_chain_buffer();
std::string str="std::string";
const char *p=new char(10);
int i=65;
float d=888;
p="c_str_ptr";
char array[]="c_array";
*buf<<"string_literal"<<"|"<<str<<"|"<<array<<"|"<<p<<"|"<<i<<"|"<<d;
RxWriteRc write_res;
buf->write_to_fd(RxFD{RxFDType::FD_REGULAR_FILE,STDOUT_FILENO},write_res);
}
TEST(slice_test,testset){
ChainBuffer buf;
std::string content="0123456789abcdefg";
buf<<content;
size_t offset=3;
ChainBuffer sliced=buf.slice(buf.begin()+offset,buf.begin()+offset+8);
std::cout<<"-----sliced content print:-------"<<std::endl;
for(auto it=sliced.begin();it!=sliced.end();++it){
EXPECT_EQ(content[it-sliced.begin()+offset],*it);
std::cout<<*it;
}
std::cout<<std::endl;
}
#endif // TST_BUFFER_TEST_H
| 33.224359
| 105
| 0.648466
|
demonatic
|
f3eb9944fbb633dfa3824ff4a26aadc5fab77b58
| 340
|
cpp
|
C++
|
lib/ds/segtree/mergesort-tree/test_merge.cpp
|
howdepressingitistoloveyou/lib
|
42e515ef15914ba6e7c253cdce124944a72bf258
|
[
"MIT"
] | null | null | null |
lib/ds/segtree/mergesort-tree/test_merge.cpp
|
howdepressingitistoloveyou/lib
|
42e515ef15914ba6e7c253cdce124944a72bf258
|
[
"MIT"
] | null | null | null |
lib/ds/segtree/mergesort-tree/test_merge.cpp
|
howdepressingitistoloveyou/lib
|
42e515ef15914ba6e7c253cdce124944a72bf258
|
[
"MIT"
] | 1
|
2021-09-03T16:52:21.000Z
|
2021-09-03T16:52:21.000Z
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define pb push_back
using namespace std;
signed main() {
vector<int> a, b, c;
a.pb(1);
b.pb(1), b.pb(2);
// c.resize(3); // this must be added if you don't use back_inserter.
merge(all(a), all(b), back_inserter(c));
for(auto x : c) cout << x << ' '; cout << '\n';
}
| 24.285714
| 70
| 0.582353
|
howdepressingitistoloveyou
|
f3ec49d4b0e4fa3e55eaa4b268809f9449af3c18
| 551
|
hpp
|
C++
|
src/node_factory.hpp
|
ognjen-petrovic/php-dom-ext
|
05bbe6b7a9bf68ca8193db7b314c0c542013e5da
|
[
"MIT"
] | null | null | null |
src/node_factory.hpp
|
ognjen-petrovic/php-dom-ext
|
05bbe6b7a9bf68ca8193db7b314c0c542013e5da
|
[
"MIT"
] | null | null | null |
src/node_factory.hpp
|
ognjen-petrovic/php-dom-ext
|
05bbe6b7a9bf68ca8193db7b314c0c542013e5da
|
[
"MIT"
] | null | null | null |
#include <phpcpp.h>
#include "pugixml.hpp"
//#include "pugixml.cpp"
#ifndef NODE_FACTORY
#define NODE_FACTORY
bool strequal(const pugi::char_t* src, const pugi::char_t* dst)
{
#ifdef PUGIXML_WCHAR_MODE
return wcscmp(src, dst) == 0;
#else
return strcmp(src, dst) == 0;
#endif
}
Php::Value node_factory(pugi::xml_node node)
{
if (strequal("form", node.name()))
return Php::Object("ogpe\\HTMLFormElement", new DOMNode(node));
else
return Php::Object("ogpe\\DOMNode", new DOMNode(node));
}
#endif
| 22.958333
| 73
| 0.647913
|
ognjen-petrovic
|
f3ece83b18ff39229de524cae9fb2cace09dabef
| 986
|
cc
|
C++
|
below2.1/zyxab.cc
|
danzel-py/Kattis-Problem-Archive
|
bce1929d654b1bceb104f96d68c74349273dd1ff
|
[
"Apache-2.0"
] | null | null | null |
below2.1/zyxab.cc
|
danzel-py/Kattis-Problem-Archive
|
bce1929d654b1bceb104f96d68c74349273dd1ff
|
[
"Apache-2.0"
] | null | null | null |
below2.1/zyxab.cc
|
danzel-py/Kattis-Problem-Archive
|
bce1929d654b1bceb104f96d68c74349273dd1ff
|
[
"Apache-2.0"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool bsort(string &s1, string &s2){
if(s1.length() == s2.length()){
return s1>s2;
}
else{
return s1.length()<s2.length();
}
}
int main(){
vector<string> v;
int n;
cin>>n;
string candidate;
for (int i = 0; i < n; i++)
{
cin>>candidate;
if(candidate.length()<5){
continue;
}
string candidatekw = candidate;
sort(candidatekw.begin(),candidatekw.end());
bool dupe = false;
for (int j = 1; j < candidatekw.length(); j++)
{
if(candidatekw[j] == candidatekw[j-1]){
dupe = true;
break;
}
}
if(dupe){
continue;
}
v.push_back(candidate);
}
if(v.empty()){
cout<<"neibb!";
return 0;
}
sort(v.begin(),v.end(),bsort);
cout<<v.front();
return 0;
}
| 20.541667
| 54
| 0.471602
|
danzel-py
|
f3ede1ed5b999e6ae408fe157e70f55f248fcfd7
| 7,268
|
cpp
|
C++
|
src/serac/numerics/functional/tests/functional_nonlinear.cpp
|
btalamini/serac
|
f7a1628d05393a3f5efce4d1808a0c3fde9bf188
|
[
"BSD-3-Clause"
] | null | null | null |
src/serac/numerics/functional/tests/functional_nonlinear.cpp
|
btalamini/serac
|
f7a1628d05393a3f5efce4d1808a0c3fde9bf188
|
[
"BSD-3-Clause"
] | null | null | null |
src/serac/numerics/functional/tests/functional_nonlinear.cpp
|
btalamini/serac
|
f7a1628d05393a3f5efce4d1808a0c3fde9bf188
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2019-2022, Lawrence Livermore National Security, LLC and
// other Serac Project Developers. See the top-level LICENSE file for
// details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
#include <fstream>
#include <iostream>
#include "mfem.hpp"
#include "axom/slic/core/SimpleLogger.hpp"
#include "serac/infrastructure/input.hpp"
#include "serac/serac_config.hpp"
#include "serac/mesh/mesh_utils_base.hpp"
#include "serac/numerics/expr_template_ops.hpp"
#include "serac/numerics/stdfunction_operator.hpp"
#include "serac/numerics/functional/functional.hpp"
#include "serac/numerics/functional/tensor.hpp"
#include "serac/infrastructure/profiling.hpp"
#include <gtest/gtest.h>
using namespace serac;
using namespace serac::profiling;
int num_procs, myid;
std::unique_ptr<mfem::ParMesh> mesh2D;
std::unique_ptr<mfem::ParMesh> mesh3D;
static constexpr double a = 1.7;
static constexpr double b = 2.1;
template <int dim>
struct hcurl_qfunction {
template <typename x_t, typename vector_potential_t>
SERAC_HOST_DEVICE auto operator()(x_t x, vector_potential_t vector_potential) const
{
auto [A, curl_A] = vector_potential;
auto J_term = a * A - tensor<double, dim>{10 * x[0] * x[1], -5 * (x[0] - x[1]) * x[1]};
auto H_term = b * curl_A;
return serac::tuple{J_term, H_term};
}
};
template <typename T>
void check_gradient(Functional<T>& f, mfem::Vector& U)
{
int seed = 42;
mfem::Vector dU(U.Size());
dU.Randomize(seed);
double epsilon = 1.0e-8;
auto U_plus = U;
U_plus.Add(epsilon, dU);
auto U_minus = U;
U_minus.Add(-epsilon, dU);
mfem::Vector df1 = f(U_plus);
df1 -= f(U_minus);
df1 /= (2 * epsilon);
auto [value, dfdU] = f(differentiate_wrt(U));
mfem::Vector df2 = dfdU(dU);
std::unique_ptr<mfem::HypreParMatrix> dfdU_matrix = assemble(dfdU);
mfem::Vector df3 = (*dfdU_matrix) * dU;
double relative_error1 = df1.DistanceTo(df2) / df1.Norml2();
double relative_error2 = df1.DistanceTo(df3) / df1.Norml2();
EXPECT_NEAR(0., relative_error1, 5.e-6);
EXPECT_NEAR(0., relative_error2, 5.e-6);
std::cout << relative_error1 << " " << relative_error2 << std::endl;
}
// this test sets up a toy "thermal" problem where the residual includes contributions
// from a temperature-dependent source term and a temperature-gradient-dependent flux
//
// the same problem is expressed with mfem and functional, and their residuals and gradient action
// are compared to ensure the implementations are in agreement.
template <int p, int dim>
void functional_test(mfem::ParMesh& mesh, H1<p> test, H1<p> trial, Dimension<dim>)
{
std::string postfix = concat("_H1<", p, ">");
serac::profiling::initialize();
// Create standard MFEM bilinear and linear forms on H1
auto fec = mfem::H1_FECollection(p, dim);
mfem::ParFiniteElementSpace fespace(&mesh, &fec);
// Set a random state to evaluate the residual
mfem::Vector U(fespace.TrueVSize());
U.Randomize();
// Define the types for the test and trial spaces using the function arguments
using test_space = decltype(test);
using trial_space = decltype(trial);
// Construct the new functional object using the known test and trial spaces
Functional<test_space(trial_space)> residual(&fespace, {&fespace});
// Add the total domain residual term to the functional
residual.AddDomainIntegral(
Dimension<dim>{},
[=](auto x, auto temperature) {
auto [u, du_dx] = temperature;
auto source = a * u * u - (100 * x[0] * x[1]);
auto flux = b * du_dx;
return serac::tuple{source, flux};
},
mesh);
residual.AddBoundaryIntegral(
Dimension<dim - 1>{},
[=](auto x, auto /*n*/, auto temperature) {
auto u = get<0>(temperature);
return x[0] + x[1] - cos(u);
},
mesh);
check_gradient(residual, U);
serac::profiling::finalize();
}
template <int p, int dim>
void functional_test(mfem::ParMesh& mesh, H1<p, dim> test, H1<p, dim> trial, Dimension<dim>)
{
std::string postfix = concat("_H1<", p, ",", dim, ">");
serac::profiling::initialize();
// Create standard MFEM bilinear and linear forms on H1
auto fec = mfem::H1_FECollection(p, dim);
mfem::ParFiniteElementSpace fespace(&mesh, &fec, dim);
// Set a random state to evaluate the residual
mfem::Vector U(fespace.TrueVSize());
U.Randomize();
// Define the types for the test and trial spaces using the function arguments
using test_space = decltype(test);
using trial_space = decltype(trial);
// Construct the new functional object using the known test and trial spaces
Functional<test_space(trial_space)> residual(&fespace, {&fespace});
// Add the total domain residual term to the functional
residual.AddDomainIntegral(
Dimension<dim>{},
[=](auto /*x*/, auto displacement) {
// get the value and the gradient from the input tuple
auto [u, du_dx] = displacement;
auto source = a * u * u[0];
auto flux = b * du_dx;
return serac::tuple{source, flux};
},
mesh);
residual.AddBoundaryIntegral(
Dimension<dim - 1>{},
[=](auto x, auto n, auto displacement) {
auto u = get<0>(displacement);
return (x[0] + x[1] - cos(u[0])) * n;
},
mesh);
check_gradient(residual, U);
serac::profiling::finalize();
}
TEST(thermal, 2D_linear) { functional_test(*mesh2D, H1<1>{}, H1<1>{}, Dimension<2>{}); }
TEST(thermal, 2D_quadratic) { functional_test(*mesh2D, H1<2>{}, H1<2>{}, Dimension<2>{}); }
TEST(thermal, 2D_cubic) { functional_test(*mesh2D, H1<3>{}, H1<3>{}, Dimension<2>{}); }
TEST(thermal, 3D_linear) { functional_test(*mesh3D, H1<1>{}, H1<1>{}, Dimension<3>{}); }
TEST(thermal, 3D_quadratic) { functional_test(*mesh3D, H1<2>{}, H1<2>{}, Dimension<3>{}); }
TEST(thermal, 3D_cubic) { functional_test(*mesh3D, H1<3>{}, H1<3>{}, Dimension<3>{}); }
TEST(elasticity, 2D_linear) { functional_test(*mesh2D, H1<1, 2>{}, H1<1, 2>{}, Dimension<2>{}); }
TEST(elasticity, 2D_quadratic) { functional_test(*mesh2D, H1<2, 2>{}, H1<2, 2>{}, Dimension<2>{}); }
TEST(elasticity, 2D_cubic) { functional_test(*mesh2D, H1<3, 2>{}, H1<3, 2>{}, Dimension<2>{}); }
TEST(elasticity, 3D_linear) { functional_test(*mesh3D, H1<1, 3>{}, H1<1, 3>{}, Dimension<3>{}); }
TEST(elasticity, 3D_quadratic) { functional_test(*mesh3D, H1<2, 3>{}, H1<2, 3>{}, Dimension<3>{}); }
TEST(elasticity, 3D_cubic) { functional_test(*mesh3D, H1<3, 3>{}, H1<3, 3>{}, Dimension<3>{}); }
int main(int argc, char* argv[])
{
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
axom::slic::SimpleLogger logger;
int serial_refinement = 0;
int parallel_refinement = 0;
std::string meshfile2D = SERAC_REPO_DIR "/data/meshes/star.mesh";
mesh2D = mesh::refineAndDistribute(buildMeshFromFile(meshfile2D), serial_refinement, parallel_refinement);
std::string meshfile3D = SERAC_REPO_DIR "/data/meshes/beam-hex.mesh";
mesh3D = mesh::refineAndDistribute(buildMeshFromFile(meshfile3D), serial_refinement, parallel_refinement);
int result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
| 33.493088
| 108
| 0.670748
|
btalamini
|
f3eef3469ce58ce780b152041761496e9ece5d99
| 4,988
|
cpp
|
C++
|
packages/monte_carlo/core/test/tstBremsstrahlungAngularDistributionType.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 10
|
2019-11-14T19:58:30.000Z
|
2021-04-04T17:44:09.000Z
|
packages/monte_carlo/core/test/tstBremsstrahlungAngularDistributionType.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 43
|
2020-03-03T19:59:20.000Z
|
2021-09-08T03:36:08.000Z
|
packages/monte_carlo/core/test/tstBremsstrahlungAngularDistributionType.cpp
|
bam241/FRENSIE
|
e1760cd792928699c84f2bdce70ff54228e88094
|
[
"BSD-3-Clause"
] | 6
|
2020-02-12T17:37:07.000Z
|
2020-09-08T18:59:51.000Z
|
//---------------------------------------------------------------------------//
//!
//! \file tstBremsstrahlungAngularDistributionType.cpp
//! \author Luke Kersting
//! \brief Bremsstrahlung angular distribution type helper unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <sstream>
// FRENSIE Includes
#include "MonteCarlo_BremsstrahlungAngularDistributionType.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
#include "ArchiveTestHelpers.hpp"
//---------------------------------------------------------------------------//
// Testing Types
//---------------------------------------------------------------------------//
typedef TestArchiveHelper::TestArchives TestArchives;
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that the bremsstrahlung angular distribution types can be converted to int
FRENSIE_UNIT_TEST( BremsstrahlungAngularDistributionType, convert_to_int )
{
FRENSIE_CHECK_EQUAL( (unsigned)MonteCarlo::DIPOLE_DISTRIBUTION, 1 );
FRENSIE_CHECK_EQUAL( (unsigned)MonteCarlo::TABULAR_DISTRIBUTION, 2 );
FRENSIE_CHECK_EQUAL( (unsigned)MonteCarlo::TWOBS_DISTRIBUTION, 3 );
}
//---------------------------------------------------------------------------//
// Check that a bremsstrahlung angular distribution type can be converted to a string
FRENSIE_UNIT_TEST( BremsstrahlungAngularDistributionType, toString )
{
std::string type_string =
Utility::toString( MonteCarlo::DIPOLE_DISTRIBUTION );
FRENSIE_CHECK_EQUAL( type_string, "Dipole Distribution" );
type_string =
Utility::toString( MonteCarlo::TABULAR_DISTRIBUTION );
FRENSIE_CHECK_EQUAL( type_string, "Tabular Distribution" );
type_string =
Utility::toString( MonteCarlo::TWOBS_DISTRIBUTION );
FRENSIE_CHECK_EQUAL( type_string, "2BS Distribution" );
}
//---------------------------------------------------------------------------//
// Check that a bremsstrahlung angular distribution type can be sent to a stream
FRENSIE_UNIT_TEST( BremsstrahlungAngularDistributionType, stream_operator )
{
std::stringstream ss;
ss << MonteCarlo::DIPOLE_DISTRIBUTION;
FRENSIE_CHECK_EQUAL( ss.str(), "Dipole Distribution" );
ss.str( "" );
ss << MonteCarlo::TABULAR_DISTRIBUTION;
FRENSIE_CHECK_EQUAL( ss.str(), "Tabular Distribution" );
ss.str( "" );
ss << MonteCarlo::TWOBS_DISTRIBUTION;
FRENSIE_CHECK_EQUAL( ss.str(), "2BS Distribution" );
}
//---------------------------------------------------------------------------//
// Check that an elastic electron distribution type can be archived
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( BremsstrahlungAngularDistributionType,
archive,
TestArchives )
{
FETCH_TEMPLATE_PARAM( 0, RawOArchive );
FETCH_TEMPLATE_PARAM( 1, RawIArchive );
typedef typename std::remove_pointer<RawOArchive>::type OArchive;
typedef typename std::remove_pointer<RawIArchive>::type IArchive;
std::string archive_base_name( "test_bremss_angular_dist_type" );
std::ostringstream archive_ostream;
{
std::unique_ptr<OArchive> oarchive;
createOArchive( archive_base_name, archive_ostream, oarchive );
MonteCarlo::BremsstrahlungAngularDistributionType type_1 =
MonteCarlo::DIPOLE_DISTRIBUTION;
MonteCarlo::BremsstrahlungAngularDistributionType type_2 =
MonteCarlo::TABULAR_DISTRIBUTION;
MonteCarlo::BremsstrahlungAngularDistributionType type_3 =
MonteCarlo::TWOBS_DISTRIBUTION;
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_1 ) );
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_2 ) );
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_3 ) );
}
// Copy the archive ostream to an istream
std::istringstream archive_istream( archive_ostream.str() );
// Load the archived distributions
std::unique_ptr<IArchive> iarchive;
createIArchive( archive_istream, iarchive );
MonteCarlo::BremsstrahlungAngularDistributionType type_1;
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_1 ) );
FRENSIE_CHECK_EQUAL( type_1, MonteCarlo::DIPOLE_DISTRIBUTION );
MonteCarlo::BremsstrahlungAngularDistributionType type_2;
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_2 ) );
FRENSIE_CHECK_EQUAL( type_2, MonteCarlo::TABULAR_DISTRIBUTION );
MonteCarlo::BremsstrahlungAngularDistributionType type_3;
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_3 ) );
FRENSIE_CHECK_EQUAL( type_3, MonteCarlo::TWOBS_DISTRIBUTION );
}
//---------------------------------------------------------------------------//
// end tstBremsstrahlungAngularDistributionType.cpp
//---------------------------------------------------------------------------//
| 36.144928
| 85
| 0.630914
|
bam241
|
f3ef1c968b13df9f7ddc6c0bf75a5aa51cd703a9
| 582
|
cc
|
C++
|
test/aoc15_d08_unittest.cc
|
dombalaz/aoc15
|
ea7e9f1ae18d9d32a43064e53bf6addbf8ef5fb2
|
[
"MIT"
] | 1
|
2020-05-15T08:08:52.000Z
|
2020-05-15T08:08:52.000Z
|
test/aoc15_d08_unittest.cc
|
dombalaz/aoc15
|
ea7e9f1ae18d9d32a43064e53bf6addbf8ef5fb2
|
[
"MIT"
] | null | null | null |
test/aoc15_d08_unittest.cc
|
dombalaz/aoc15
|
ea7e9f1ae18d9d32a43064e53bf6addbf8ef5fb2
|
[
"MIT"
] | null | null | null |
#include <aoc15/d08.h>
#include <gtest/gtest.h>
TEST(Day08_Part1_Test, CountCharacters)
{
EXPECT_EQ(countCharacters(R"("")"), 0);
EXPECT_EQ(countCharacters(R"("abc")"), 3);
EXPECT_EQ(countCharacters(R"("aaa\"aaa")"), 7);
EXPECT_EQ(countCharacters(R"("\x27")"), 1);
}
TEST(Day08_Part2_Test, CountEncodedChars)
{
EXPECT_EQ(countEncodedChars(R"("")"), 6);
EXPECT_EQ(countEncodedChars(R"("abc")"), 9);
EXPECT_EQ(countEncodedChars(R"("aaa\"aaa")"), 16);
EXPECT_EQ(countEncodedChars(R"("\x27")"), 11);
EXPECT_EQ(countEncodedChars(R"("\\")"), 10);
}
| 27.714286
| 54
| 0.647766
|
dombalaz
|
f3fbf56366e9266d5991803876625d605fce1d7c
| 6,499
|
hpp
|
C++
|
include/ironbeepp/memory_manager.hpp
|
b1v1r/ironbee
|
97b453afd9c3dc70342c6183a875bde22c9c4a76
|
[
"Apache-2.0"
] | 148
|
2015-01-10T01:53:39.000Z
|
2022-03-20T20:48:12.000Z
|
include/ironbeepp/memory_manager.hpp
|
ErikHendriks/ironbee
|
97b453afd9c3dc70342c6183a875bde22c9c4a76
|
[
"Apache-2.0"
] | 8
|
2015-03-09T15:50:36.000Z
|
2020-10-10T19:23:06.000Z
|
include/ironbeepp/memory_manager.hpp
|
ErikHendriks/ironbee
|
97b453afd9c3dc70342c6183a875bde22c9c4a76
|
[
"Apache-2.0"
] | 46
|
2015-03-08T22:45:42.000Z
|
2022-01-15T13:47:59.000Z
|
/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You 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.
****************************************************************************/
/**
* @file
* @brief IronBee++ --- Memory Manager
*
* This file defines MemoryManager, a wrapper for ib_mm_t.
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#ifndef __IBPP__MEMORY_MANAGER__
#define __IBPP__MEMORY_MANAGER__
#include <ironbeepp/abi_compatibility.hpp>
#include <ironbee/mm.h>
#include <ironbee/mm_mpool.h>
#include <ironbee/mm_mpool_lite.h>
#include <boost/function.hpp>
#include <ostream>
namespace IronBee {
class MemoryPool;
class ScopedMemoryPool;
class MemoryPoolLite;
class ScopedMemoryPoolLite;
/**
* Memory Manager; equivalent to a *value* of @ref ib_mm_t.
*
* Note: As a by-value, MemoryManager does not provide common semantics.
*
* A MemoryManager is a simple interface to memory management systems. It
* requires implementation of allocation and cleanup function registration.
*
* @sa ironbeepp
* @sa ib_mm_t
* @nosubgrouping
**/
class MemoryManager
{
public:
//! C Type.
typedef ib_mm_t ib_type;
/**
* @name Construction.
* Methods to access construct MemoryManagers.
**/
///@{
//! Default constructor. Singular. Wraps @ref IB_MM_NULL.
MemoryManager();
//! Construct from C type.
explicit
MemoryManager(ib_type ib);
//! Allocation function.
typedef boost::function<void*(size_t)> alloc_t;
//! Cleanup function.
typedef boost::function<void()> cleanup_t;
//! Cleanup registration function.
typedef boost::function<void(cleanup_t)> register_cleanup_t;
//! Constructor from functionals.
MemoryManager(alloc_t alloc, register_cleanup_t register_cleanup);
//! Conversion from MemoryPool. Implicit.
MemoryManager(MemoryPool memory_pool);
//! Conversion from MemoryPoolLite. Implicit.
MemoryManager(MemoryPoolLite memory_pool_lite);
//! Conversion from ScopedMemoryPool. Implicit.
MemoryManager(ScopedMemoryPool& memory_pool);
//! Conversion from ScopedMemoryPoolLite. Implicit.
MemoryManager(ScopedMemoryPoolLite& memory_pool_lite);
///@}
/**
* @name C Interoperability
* Methods to access underlying C types.
**/
///@{
//! @ref ib_mm_t accessor. Note copy-out.
ib_mm_t ib() const
{
return m_ib;
}
///@}
/**
* @name Allocation
* Routines to allocate memory.
**/
//@{
/**
* Allocate sufficient memory for a @a number @a Ts
*
* Note: This does not construct any Ts, simply allocates memory. You
* will need to use placement new to construct the T.
*
* @tparam T Type to allocate memory for.
* @param[in] number Number of Ts.
* @returns Pointer to allocated memory.
* @throw ealloc on failure to allocate.
**/
template <typename T>
T* allocate(size_t number = 1) const;
/**
* Allocate @a size bytes of memory.
*
* @param[in] size Number of bytes to allocate.
* @returns Pointer to allocated memory.
* @throw ealloc on failure to allocate.
**/
void* alloc(size_t size) const;
/**
* Allocate @a count * @a size bytes of memory and sets to 0.
*
* @param[in] count Number of elements to allocate memory for.
* @param[in] size Size of each element.
* @returns Pointer to allocated memory.
* @throw ealloc on failure to allocate.
**/
void* calloc(size_t count, size_t size) const;
/**
* Allocate @a size bytes and set to 0.
* @param[in] size Size of each element.
* @returns Pointer to allocated memory.
* @throw ealloc on failure to allocate.
**/
void* calloc(size_t size) const;
/**
* Duplicate a C string.
* @param[in] cstr C string to duplicate.
* @returns Pointer to copy of @a cstr.
* @throw ealloc on failure to allocate.
**/
char* strdup(const char* cstr) const;
/**
* Duplicate a region of memory.
* @param[in] data Data to duplicate.
* @param[in] size Size of @a data.
* @throw ealloc on failure to allocate.
**/
void* memdup(const void* data, size_t size) const;
/**
* Duplicate a region to memory, adding a NUL at the end.
* @param[in] data Data to duplicate.
* @param[in] size Size of @a data.
* @throw ealloc on failure to allocate.
**/
char* memdup_to_str(const void* data, size_t size) const;
//@}
/**
* Register a function to be called at memory destruction.
*
* Cleanup functions are called in reverse order of registration and
* before memory is released.
*
* @param[in] cleanup Function to register.
* @throw ealloc on Allocation failure.
**/
void register_cleanup(cleanup_t cleanup) const;
///@cond Internal
typedef void (*unspecified_bool_type)(MemoryManager***);
///@endcond
/**
* Test singularity.
*
* Evaluates as truthy if ! ib_mm_is_null(this->ib()). Does so in a way
* that prevents implicit conversion to integral types.
*
* @returns truthy iff ! ib_mm_is_null(this->ib()).
**/
operator unspecified_bool_type() const;
private:
//! Used for unspecified_bool_type.
static void unspecified_bool(MemoryManager***) {};
//! Underlying @ref ib_mm_t.
ib_mm_t m_ib;
};
//! Ostream output for MemoryPool.
std::ostream& operator<<(
std::ostream& o,
const MemoryManager& memory_manager
);
// Template Definition
template <typename T>
T* MemoryManager::allocate(size_t number) const
{
return static_cast<T*>(alloc(number * sizeof(T)));
}
} // IronBee
#endif
| 27.538136
| 78
| 0.646099
|
b1v1r
|
f3fc312ad3cc270061698b8eb6ae6ee69113b0aa
| 36,812
|
cpp
|
C++
|
source/timemory/variadic/bundle.cpp
|
pwm1234-sri/timemory
|
b804c8ab242baaa9546f3e74a568438896233d71
|
[
"MIT"
] | 1
|
2021-04-21T13:08:27.000Z
|
2021-04-21T13:08:27.000Z
|
source/timemory/variadic/bundle.cpp
|
hewhocannotbetamed/timemory
|
d84ccb79cb452f710917d3fa8c17a5ecf3a07406
|
[
"MIT"
] | 1
|
2020-10-30T03:44:18.000Z
|
2020-11-05T22:07:19.000Z
|
source/timemory/variadic/bundle.cpp
|
hewhocannotbetamed/timemory
|
d84ccb79cb452f710917d3fa8c17a5ecf3a07406
|
[
"MIT"
] | null | null | null |
// MIT License
//
// Copyright (c) 2020, The Regents of the University of California,
// through Lawrence Berkeley National Laboratory (subject to receipt of any
// required approvals from the U.S. Dept. of Energy). All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef TIMEMORY_VARIADIC_BUNDLE_CPP_
#define TIMEMORY_VARIADIC_BUNDLE_CPP_
#include "timemory/variadic/bundle.hpp"
#include "timemory/backends/dmp.hpp"
#include "timemory/mpl/filters.hpp"
#include "timemory/operations/types/set.hpp"
#include "timemory/settings/declaration.hpp"
#include "timemory/tpls/cereal/cereal.hpp"
#include "timemory/utility/macros.hpp"
#include "timemory/variadic/bundle_execute.hpp"
#include "timemory/variadic/functional.hpp"
#include "timemory/variadic/types.hpp"
namespace tim
{
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::initializer_type&
bundle<Tag, BundleT, TupleT>::get_initializer()
{
static initializer_type _instance = [](this_type&) {};
return _instance;
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle()
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, get_initializer());
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... T>
bundle<Tag, BundleT, TupleT>::bundle(const string_t& _key, quirk::config<T...> _config,
transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _key, true_type{}, _config))
, m_data(invoke::construct<data_type, Tag>(_key, _config))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle, T...>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func),
_config);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... T>
bundle<Tag, BundleT, TupleT>::bundle(const captured_location_t& _loc,
quirk::config<T...> _config,
transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _loc, true_type{}, _config))
, m_data(invoke::construct<data_type, Tag>(_loc, _config))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle, T...>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func),
_config);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... T>
bundle<Tag, BundleT, TupleT>::bundle(const string_t& _key, bool _store,
quirk::config<T...> _config,
transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _key, _store, _config))
, m_data(invoke::construct<data_type, Tag>(_key, _config))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle, T...>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func),
_config);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... T>
bundle<Tag, BundleT, TupleT>::bundle(const captured_location_t& _loc, bool _store,
quirk::config<T...> _config,
transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _loc, _store, _config))
, m_data(invoke::construct<data_type, Tag>(_loc, _config))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle, T...>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func),
_config);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle(size_t _hash, bool _store, scope::config _scope,
transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _hash, _store, _scope))
, m_data(invoke::construct<data_type, Tag>(_hash, m_scope))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func));
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle(const string_t& _key, bool _store,
scope::config _scope, transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _key, _store, _scope))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func));
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle(const captured_location_t& _loc, bool _store,
scope::config _scope, transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _loc, _store, _scope))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func));
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle(size_t _hash, scope::config _scope,
transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _hash, true_type{}, _scope))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func));
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle(const string_t& _key, scope::config _scope,
transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _key, true_type{}, _scope))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func));
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle(const captured_location_t& _loc,
scope::config _scope, transient_func_t _init_func)
: bundle_type(bundle_type::handle(type_list_type{}, _loc, true_type{}, _scope))
{
update_last_instance(&get_this_type(), get_last_instance(),
quirk_config<quirk::stop_last_bundle>::value);
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
bundle_type::init(type_list_type{}, get_this_type(), m_data, std::move(_init_func));
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::~bundle()
{
if(get_last_instance() == &get_this_type())
update_last_instance(nullptr, get_last_instance(), false);
IF_CONSTEXPR(!quirk_config<quirk::explicit_stop>::value)
{
if(m_is_active())
stop();
}
IF_CONSTEXPR(optional_count() > 0)
{
#if defined(DEBUG) && !defined(NDEBUG)
if(tim::settings::debug() && tim::settings::verbose() > 4)
{
PRINT_HERE("%s", "deleting components");
}
#endif
invoke::destroy<Tag>(m_data);
}
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>::bundle(const bundle& rhs)
: bundle_type(rhs)
{
using copy_oper_t = convert_each_t<operation::copy, remove_pointers_t<data_type>>;
IF_CONSTEXPR(optional_count() > 0) { apply_v::set_value(m_data, nullptr); }
apply_v::access2<copy_oper_t>(m_data, rhs.m_data);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>&
bundle<Tag, BundleT, TupleT>::operator=(const bundle& rhs)
{
if(this != &rhs)
{
bundle_type::operator=(rhs);
invoke::destroy<Tag>(m_data);
invoke::invoke_impl::invoke_data<operation::copy, Tag>(m_data, rhs.m_data);
// apply_v::access<operation_t<operation::copy>>(m_data);
}
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// this_type operators
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::operator-=(const this_type& rhs)
{
bundle_type::operator-=(static_cast<const bundle_type&>(rhs));
invoke::invoke_impl::invoke_data<operation::minus, Tag>(m_data, rhs.m_data);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::operator+=(const this_type& rhs)
{
bundle_type::operator+=(static_cast<const bundle_type&>(rhs));
invoke::invoke_impl::invoke_data<operation::plus, Tag>(m_data, rhs.m_data);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
bundle<Tag, BundleT, TupleT>
bundle<Tag, BundleT, TupleT>::clone(bool _store, scope::config _scope)
{
bundle tmp(*this);
tmp.m_store(_store);
tmp.m_scope = _scope;
return tmp;
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
void
bundle<Tag, BundleT, TupleT>::init_storage()
{
static thread_local bool _once = []() {
apply_v::type_access<operation::init_storage, mpl::non_quirk_t<reference_type>>();
return true;
}();
consume_parameters(_once);
}
//--------------------------------------------------------------------------------------//
// insert into graph
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::push()
{
if(!m_enabled())
return get_this_type();
if(!m_is_pushed())
{
// reset the data
invoke::reset<Tag>(m_data);
// avoid pushing/popping when already pushed/popped
m_is_pushed(true);
// insert node or find existing node
invoke::push<Tag>(m_data, m_scope, m_hash);
}
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// insert into graph
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Tp>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::push(mpl::piecewise_select<Tp...>)
{
if(!m_enabled())
return get_this_type();
using pw_type = convert_t<mpl::implemented_t<Tp...>, mpl::piecewise_select<>>;
// reset the data
invoke::invoke<operation::reset, Tag>(pw_type{}, m_data);
// insert node or find existing node
invoke::invoke<operation::push_node, Tag>(pw_type{}, m_data, m_scope, m_hash);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// insert into graph
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Tp>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::push(mpl::piecewise_select<Tp...>, scope::config _scope)
{
if(!m_enabled())
return get_this_type();
using pw_type = convert_t<mpl::implemented_t<Tp...>, mpl::piecewise_select<>>;
// reset the data
invoke::invoke<operation::reset, Tag>(pw_type{}, m_data);
// insert node or find existing node
invoke::invoke<operation::push_node, Tag>(pw_type{}, m_data, _scope, m_hash);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// pop out of graph
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::pop()
{
if(!m_enabled())
return get_this_type();
if(m_is_pushed())
{
// set the current node to the parent node
invoke::pop<Tag>(m_data);
// avoid pushing/popping when already pushed/popped
m_is_pushed(false);
}
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// pop out of graph
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Tp>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::pop(mpl::piecewise_select<Tp...>)
{
if(!m_enabled())
return get_this_type();
using pw_type = convert_t<mpl::implemented_t<Tp...>, mpl::piecewise_select<>>;
// set the current node to the parent node
invoke::invoke<operation::pop_node, Tag>(pw_type{}, m_data);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// measure functions
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::measure(Args&&... args)
{
return invoke<operation::measure>(std::forward<Args>(args)...);
}
//--------------------------------------------------------------------------------------//
// sample functions
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::sample(Args&&... args)
{
return invoke<operation::sample>(std::forward<Args>(args)...);
}
//--------------------------------------------------------------------------------------//
// start/stop functions with no push/pop or assemble/derive
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::start(mpl::lightweight, Args&&... args)
{
if(!m_enabled())
return get_this_type();
assemble(*this);
invoke::start<Tag>(m_data, std::forward<Args>(args)...);
m_is_active(true);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::stop(mpl::lightweight, Args&&... args)
{
if(!m_enabled())
return get_this_type();
invoke::stop<Tag>(m_data, std::forward<Args>(args)...);
if(m_is_active())
++m_laps;
derive(*this);
m_is_active(false);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// start/stop functions with no push/pop or assemble/derive
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Tp, typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::start(mpl::piecewise_select<Tp...>, Args&&... args)
{
if(!m_enabled())
return get_this_type();
using select_tuple_t = mpl::sort<trait::start_priority, std::tuple<Tp...>>;
TIMEMORY_FOLD_EXPRESSION(
operation::reset<Tp>(std::get<index_of<Tp, data_type>::value>(m_data)));
IF_CONSTEXPR(!quirk_config<quirk::explicit_push>::value &&
!quirk_config<quirk::no_store>::value)
{
if(m_store() && !bundle_type::m_explicit_push())
{
TIMEMORY_FOLD_EXPRESSION(operation::push_node<Tp>(
std::get<index_of<Tp, data_type>::value>(m_data), m_scope, m_hash));
}
}
// start components
auto&& _data = mpl::get_reference_tuple<select_tuple_t>(m_data);
invoke::invoke<operation::standard_start, Tag>(_data, std::forward<Args>(args)...);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Tp, typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::stop(mpl::piecewise_select<Tp...>, Args&&... args)
{
if(!m_enabled())
return get_this_type();
using select_tuple_t = mpl::sort<trait::stop_priority, std::tuple<Tp...>>;
// stop components
auto&& _data = mpl::get_reference_tuple<select_tuple_t>(m_data);
invoke::invoke<operation::standard_start, Tag>(_data, std::forward<Args>(args)...);
IF_CONSTEXPR(!quirk_config<quirk::explicit_pop>::value &&
!quirk_config<quirk::no_store>::value)
{
if(m_store() && !bundle_type::m_explicit_pop())
{
TIMEMORY_FOLD_EXPRESSION(operation::pop_node<Tp>(
std::get<index_of<Tp, data_type>::value>(m_data)));
}
}
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// start/stop functions
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::start(Args&&... args)
{
if(!m_enabled())
return get_this_type();
// push components into the call-stack
IF_CONSTEXPR(!quirk_config<quirk::explicit_push>::value &&
!quirk_config<quirk::no_store>::value)
{
if(m_store() && !bundle_type::m_explicit_push())
push();
}
// start components
start(mpl::lightweight{}, std::forward<Args>(args)...);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::stop(Args&&... args)
{
if(!m_enabled())
return get_this_type();
// stop components
stop(mpl::lightweight{}, std::forward<Args>(args)...);
// pop components off of the call-stack stack
IF_CONSTEXPR(!quirk_config<quirk::explicit_pop>::value &&
!quirk_config<quirk::no_store>::value)
{
if(m_store() && !bundle_type::m_explicit_pop())
pop();
}
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// recording
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::record(Args&&... args)
{
if(!m_enabled())
return get_this_type();
++m_laps;
return invoke<operation::record>(std::forward<Args>(args)...);
}
//--------------------------------------------------------------------------------------//
// reset data
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::reset(Args&&... args)
{
m_laps = 0;
return invoke<operation::reset>(std::forward<Args>(args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
uint64_t
bundle<Tag, BundleT, TupleT>::count()
{
uint64_t _count = 0;
invoke::invoke<operation::generic_counter>(m_data, std::ref(_count));
return _count;
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::construct(Args&&... _args)
{
// using construct_t = operation_t<operation::construct>;
// apply_v::access<construct_t>(m_data, std::forward<Args>(_args)...);
return invoke<operation::construct>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::assemble(Args&&... _args)
{
return invoke<operation::assemble>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::derive(Args&&... _args)
{
return invoke<operation::derive>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::mark(Args&&... _args)
{
return invoke<operation::mark>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::mark_begin(Args&&... _args)
{
return invoke<operation::mark_begin>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::mark_end(Args&&... _args)
{
return invoke<operation::mark_end>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::store(Args&&... _args)
{
if(!m_enabled())
return get_this_type();
m_is_active(true);
invoke<operation::store>(std::forward<Args>(_args)...);
m_is_active(false);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::audit(Args&&... _args)
{
return invoke<operation::audit>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::add_secondary(Args&&... _args)
{
return invoke<operation::add_secondary>(std::forward<Args>(_args)...);
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <template <typename> class OpT, typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::invoke(Args&&... _args)
{
if(!m_enabled())
return get_this_type();
invoke::invoke<OpT, Tag>(m_data, std::forward<Args>(_args)...);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <template <typename> class OpT, typename... Tp, typename... Args>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::invoke(mpl::piecewise_select<Tp...>, Args&&... _args)
{
if(!m_enabled())
return get_this_type();
TIMEMORY_FOLD_EXPRESSION(operation::generic_operator<Tp, OpT<Tp>, Tag>(
this->get<Tp>(), std::forward<Args>(_args)...));
return get_this_type();
}
//--------------------------------------------------------------------------------------//
// get data
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
auto
bundle<Tag, BundleT, TupleT>::get(Args&&... args) const
{
return invoke::get<Tag>(m_data, std::forward<Args>(args)...);
}
//--------------------------------------------------------------------------------------//
// get labeled data
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Args>
auto
bundle<Tag, BundleT, TupleT>::get_labeled(Args&&... args) const
{
return invoke::get_labeled<Tag>(m_data, std::forward<Args>(args)...);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::data_type&
bundle<Tag, BundleT, TupleT>::data()
{
return m_data;
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
const typename bundle<Tag, BundleT, TupleT>::data_type&
bundle<Tag, BundleT, TupleT>::data() const
{
return m_data;
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::get(void*& ptr, size_t _hash) const
{
if(!m_enabled())
return get_this_type();
tim::variadic::impl::get<Tag>(m_data, ptr, _hash);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... Tail>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::disable()
{
TIMEMORY_FOLD_EXPRESSION(operation::generic_deleter<remove_pointer_t<Tail>>{
this->get_reference<Tail>() });
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename... T, typename... Args>
std::array<bool, sizeof...(T)>
bundle<Tag, BundleT, TupleT>::initialize(Args&&... args)
{
if(!m_enabled())
return std::array<bool, sizeof...(T)>{};
constexpr auto N = sizeof...(T);
return TIMEMORY_FOLD_EXPANSION(bool, N, init<T>(std::forward<Args>(args)...));
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename T, typename Func, typename... Args,
enable_if_t<trait::is_available<T>::value, int>>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::type_apply(Func&& _func, Args&&... _args)
{
if(!m_enabled())
return get_this_type();
auto* _obj = get<T>();
if(_obj)
((*_obj).*(_func))(std::forward<Args>(_args)...);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename T, typename Func, typename... Args,
enable_if_t<!trait::is_available<T>::value, int>>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::type_apply(Func&&, Args&&...)
{
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
void
bundle<Tag, BundleT, TupleT>::set_prefix(const string_t& _key) const
{
if(!m_enabled())
return;
invoke::set_prefix<Tag>(m_data, m_hash, _key);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::set_prefix(size_t _hash) const
{
if(!m_enabled())
return get_this_type();
auto itr = get_hash_ids()->find(_hash);
if(itr != get_hash_ids()->end())
invoke::set_prefix<Tag>(m_data, _hash, itr->second);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::set_prefix(captured_location_t _loc) const
{
return set_prefix(_loc.get_hash());
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::set_scope(scope::config val)
{
if(!m_enabled())
return get_this_type();
m_scope = val;
invoke::set_scope<Tag>(m_data, m_scope);
return get_this_type();
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
scope::transient_destructor
bundle<Tag, BundleT, TupleT>::get_scope_destructor()
{
return scope::transient_destructor{ [&]() { this->stop(); } };
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
scope::transient_destructor
bundle<Tag, BundleT, TupleT>::get_scope_destructor(
utility::transient_function<void(this_type&)> _func)
{
return scope::transient_destructor{ [&, _func]() { _func(get_this_type()); } };
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename T>
void
bundle<Tag, BundleT, TupleT>::set_prefix(T* obj, internal_tag) const
{
if(!m_enabled())
return;
using PrefixOpT = operation::generic_operator<T, operation::set_prefix<T>, Tag>;
auto _key = get_hash_identifier_fast(m_hash);
PrefixOpT(obj, m_hash, _key);
}
//--------------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename T>
void
bundle<Tag, BundleT, TupleT>::set_scope(T* obj, internal_tag) const
{
if(!m_enabled())
return;
using PrefixOpT = operation::generic_operator<T, operation::set_scope<T>, Tag>;
PrefixOpT(obj, m_scope);
}
//----------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <bool PrintPrefix, bool PrintLaps>
typename bundle<Tag, BundleT, TupleT>::this_type&
bundle<Tag, BundleT, TupleT>::print(std::ostream& os, bool _endl) const
{
using printer_t = typename bundle_type::print_type;
if(size() == 0 || m_hash == 0)
return get_this_type();
std::stringstream ss_data;
apply_v::access_with_indices<printer_t>(m_data, std::ref(ss_data), false);
if(PrintPrefix)
{
bundle_type::update_width();
std::stringstream ss_prefix;
std::stringstream ss_id;
ss_id << get_prefix() << " " << std::left << key();
ss_prefix << std::setw(bundle_type::output_width()) << std::left << ss_id.str()
<< " : ";
os << ss_prefix.str();
}
os << ss_data.str();
if(m_laps > 0 && PrintLaps)
os << " [laps: " << m_laps << "]";
if(_endl)
os << '\n';
return get_this_type();
}
//----------------------------------------------------------------------------------//
//
template <typename Tag, typename BundleT, typename TupleT>
template <typename Archive>
void
bundle<Tag, BundleT, TupleT>::serialize(Archive& ar, const unsigned int)
{
std::string _key = {};
auto keyitr = get_hash_ids()->find(m_hash);
if(keyitr != get_hash_ids()->end())
_key = keyitr->second;
ar(cereal::make_nvp("hash", m_hash), cereal::make_nvp("key", _key),
cereal::make_nvp("laps", m_laps));
if(keyitr == get_hash_ids()->end())
{
auto _hash = add_hash_id(_key);
if(_hash != m_hash)
{
PRINT_HERE("Warning! Hash for '%s' (%llu) != %llu", _key.c_str(),
(unsigned long long) _hash, (unsigned long long) m_hash);
}
}
ar(cereal::make_nvp("data", m_data));
}
//--------------------------------------------------------------------------------------//
} // namespace tim
#endif
| 36.196657
| 90
| 0.565984
|
pwm1234-sri
|
f3fe2b4b5fd7e95a5d7b392eaa77f58de2c7ba18
| 3,592
|
cpp
|
C++
|
source/converters/KSampleRateConverter.cpp
|
grae22/WavConverter
|
6f4f244cc5a12a215bf673f68572217012871ac1
|
[
"MIT"
] | null | null | null |
source/converters/KSampleRateConverter.cpp
|
grae22/WavConverter
|
6f4f244cc5a12a215bf673f68572217012871ac1
|
[
"MIT"
] | null | null | null |
source/converters/KSampleRateConverter.cpp
|
grae22/WavConverter
|
6f4f244cc5a12a215bf673f68572217012871ac1
|
[
"MIT"
] | null | null | null |
#include "KSampleRateConverter.h"
#include "../KWav.h"
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
//-----------------------------------------------------------------------------
using namespace std;
using namespace boost;
//-----------------------------------------------------------------------------
bool KSampleRateConverter::Convert( const KWav& source,
KWav*& destination,
std::map< std::string, std::string > options,
std::string& errorDescription )
{
// Get the new sample rate from the options.
uint32_t newRate = 0;
if( options.find( "-r" ) == options.end() )
{
errorDescription = "Sample rate (-r) option not specified.";
return false;
}
try
{
newRate = lexical_cast< uint32_t >( options[ "-r" ].c_str() );
}
catch( bad_lexical_cast )
{
errorDescription = "Non-numeric sample rate option specified.";
return false;
}
if( newRate == 0 )
{
errorDescription = "Sample rate cannot be zero.";
return false;
}
else if( newRate > 96000 )
{
errorDescription = "Sample rate cannot exceed 96000.";
return false;
}
// Get the method to use.
Method method = LINEAR;
if( options.find( "-m" ) != options.end() )
{
string m = options[ "-m" ];
to_upper< string >( m );
if( m.length() == 0 )
{
errorDescription = "No re-sampling method (-m) specified.";
return false;
}
switch( m[ 0 ] )
{
case 'L':
method = LINEAR;
break;
case 'C':
method = CUBIC;
break;
default:
errorDescription = "Invalid re-sampling method (-m) specified.";
return false;
}
}
// Already at specified rate?
if( source.GetSampleRate() == newRate )
{
return true;
}
// Get the wav data.
const uint64_t dataSize = source.GetDataSize();
const int8_t* data = source.GetData();
// Choose conversion type.
int8_t* newData = nullptr;
uint64_t newDataSize = 0;
switch( method )
{
case LINEAR:
if( source.GetSampleRate() < newRate )
{
newData =
UpsampleLinear( source,
newRate,
newDataSize );
}
break;
case CUBIC:
break;
default:
errorDescription = "Unknown re-sampling method.";
return false;
}
// Create destination wav object.
destination =
new KWav(
source.GetChannelCount(),
newRate,
source.GetBitsPerSample(),
newData,
newDataSize );
return true;
}
//-----------------------------------------------------------------------------
int8_t* KSampleRateConverter::UpsampleLinear( const KWav& input,
const uint32_t newSampleRate,
uint64_t& newDataSize )
{
// Calculate new buffer size.
if( input.GetBytesPerSample() == 0 ||
input.GetChannelCount() == 0 )
{
return nullptr;
}
newDataSize = newSampleRate / input.GetBytesPerSample() / input.GetChannelCount();
// Allocate the buffer.
int8_t* buffer = new int8_t[ newDataSize ];
fill( buffer, buffer + newDataSize, 0 );
// Calculate the ratio between sample rates.
const float ratio = static_cast< float >( input.GetSampleRate() ) / newSampleRate;
//
for( uint64_t i = 0; i < input.GetDataSize(); i++ )
{
}
return buffer;
}
//-----------------------------------------------------------------------------
| 23.025641
| 84
| 0.518653
|
grae22
|
6d03f8eb5f1b093fbc45d7a4bfb14ea93cb945ee
| 971
|
cpp
|
C++
|
graph-source-code/218-C/2025530.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/218-C/2025530.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/218-C/2025530.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: GNU C++
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<string>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
int n;
int g[101][101];
int cx[101][2];
int vis[101];
void dfs(int node) {
if (vis[node]) {
return;
}
vis[node] = 1;
for (int i = 0; i < n; i++) {
if (g[node][i]) {
dfs(i);
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d %d", &cx[i][0], &cx[i][1]);
}
memset(g, 0, sizeof(int) * 101 * 101);
for (int i = 0; i < n; i++) {
int x = cx[i][0];
int y = cx[i][1];
for (int j = i + 1; j < n; j++) {
if (cx[j][0] == x || cx[j][1] == y) {
g[i][j] = g[j][i] = 1;
}
}
}
memset(vis, 0, sizeof(int) * 101);
int ans = 0;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
ans++;
dfs(i);
}
}
printf ("%d\n", ans - 1);
return 0;
}
| 16.741379
| 44
| 0.421215
|
AmrARaouf
|
6d0646f2186224ae7de4b51b96e199a0f056c0cd
| 676
|
cpp
|
C++
|
spoj/ACODE.cpp
|
amitdu6ey/Online-Judge-Submissions
|
9585aec29228211454bca5cf1d5738f49fb0aa8f
|
[
"MIT"
] | 5
|
2020-06-30T12:44:25.000Z
|
2021-07-14T06:35:57.000Z
|
spoj/ACODE.cpp
|
amitdu6ey/Online-Judge-Submissions
|
9585aec29228211454bca5cf1d5738f49fb0aa8f
|
[
"MIT"
] | null | null | null |
spoj/ACODE.cpp
|
amitdu6ey/Online-Judge-Submissions
|
9585aec29228211454bca5cf1d5738f49fb0aa8f
|
[
"MIT"
] | null | null | null |
// [amitdu6ey]
// g++ -std=c++11 -o2 -Wall filename.cpp -o filename
#include <bits/stdc++.h>
#define ll long long
using namespace std;
void solve(string a){
ll n = a.length();
vector<ll> dp(n,0);
dp[0]=1;
ll num = (a[0]-'0')*10 + (a[1]-'0');
if(num<=26) dp[1]=2;
else dp[1]=1;
for(int i=2;i<n;i++){
ll y = (a[i-1]-'0')*10 + (a[i]-'0');
if(y<=26){
dp[i]=dp[i-1]+dp[i-2];
}
else{
dp[i]=dp[i-1];
}
}
cout<<dp[n-1]<<"\n";
return;
}
int main(){
while(true){
string x;
cin>>x;
if(x=="0") break;
solve(x);
}
return 0;
}
| 17.333333
| 52
| 0.412722
|
amitdu6ey
|
6d06aceaae3b230b1decc93386971c1e41640ef5
| 6,903
|
cpp
|
C++
|
taichi/analysis/value_diff.cpp
|
Robslhc/taichi
|
a4279bd8e1aa6b7d0d269ff909773d333fab5daa
|
[
"MIT"
] | 1
|
2022-01-12T18:40:59.000Z
|
2022-01-12T18:40:59.000Z
|
taichi/analysis/value_diff.cpp
|
isuyu/taichi
|
e5f439b916b2c9f41e4d096072811e06a85237e6
|
[
"MIT"
] | null | null | null |
taichi/analysis/value_diff.cpp
|
isuyu/taichi
|
e5f439b916b2c9f41e4d096072811e06a85237e6
|
[
"MIT"
] | null | null | null |
// This pass analyzes compile-time known offsets for two values.
#include "taichi/ir/ir.h"
#include "taichi/ir/analysis.h"
#include "taichi/ir/statements.h"
#include "taichi/ir/visitors.h"
namespace taichi {
namespace lang {
DiffRange operator+(const DiffRange &a, const DiffRange &b) {
return DiffRange(a.related_() && b.related_(), a.coeff + b.coeff,
a.low + b.low, a.high + b.high - 1);
}
DiffRange operator-(const DiffRange &a, const DiffRange &b) {
return DiffRange(a.related_() && b.related_(), a.coeff - b.coeff,
a.low - b.high + 1, a.high - b.low);
}
DiffRange operator*(const DiffRange &a, const DiffRange &b) {
return DiffRange(
a.related_() && b.related_() && a.coeff * b.coeff == 0,
fmax(a.low * b.coeff, a.coeff * b.low),
fmin(a.low * b.low,
fmin(a.low * (b.high - 1),
fmin(b.low * (a.high - 1), (a.high - 1) * (b.high - 1)))),
fmax(a.low * b.low,
fmax(a.low * (b.high - 1),
fmax(b.low * (a.high - 1), (a.high - 1) * (b.high - 1)))) +
1);
}
namespace {
class ValueDiffLoopIndex : public IRVisitor {
public:
// first: related, second: offset
using ret_type = DiffRange;
int lane; // Note: lane may change when visiting ElementShuffle
Stmt *input_stmt, *loop;
int loop_index;
std::map<int, ret_type> results;
ValueDiffLoopIndex(Stmt *stmt, int lane, Stmt *loop, int loop_index)
: lane(lane), input_stmt(stmt), loop(loop), loop_index(loop_index) {
allow_undefined_visitor = true;
invoke_default_visitor = true;
}
void visit(Stmt *stmt) override {
results[stmt->instance_id] = DiffRange();
}
void visit(GlobalLoadStmt *stmt) override {
results[stmt->instance_id] = DiffRange();
}
void visit(LoopIndexStmt *stmt) override {
results[stmt->instance_id] = DiffRange();
if (stmt->loop == loop && stmt->index == loop_index) {
results[stmt->instance_id] =
DiffRange(/*related=*/true, /*coeff=*/1, /*low=*/0);
} else if (auto range_for = stmt->loop->cast<RangeForStmt>()) {
if (range_for->begin->is<ConstStmt>() &&
range_for->end->is<ConstStmt>()) {
auto begin_val = range_for->begin->as<ConstStmt>()->val[0].val_int();
auto end_val = range_for->end->as<ConstStmt>()->val[0].val_int();
// We have begin_val <= end_val even when range_for->reversed is true:
// in that case, the loop is iterated from end_val - 1 to begin_val.
results[stmt->instance_id] = DiffRange(
/*related=*/true, /*coeff=*/0, /*low=*/begin_val, /*high=*/end_val);
}
}
}
void visit(ElementShuffleStmt *stmt) override {
int old_lane = lane;
TI_ASSERT(stmt->width() == 1);
auto src = stmt->elements[lane].stmt;
lane = stmt->elements[lane].index;
src->accept(this);
results[stmt->instance_id] = results[src->instance_id];
lane = old_lane;
}
void visit(ConstStmt *stmt) override {
if (stmt->val[lane].dt->is_primitive(PrimitiveTypeID::i32)) {
results[stmt->instance_id] = DiffRange(true, 0, stmt->val[lane].val_i32);
} else {
results[stmt->instance_id] = DiffRange();
}
}
void visit(RangeAssumptionStmt *stmt) override {
stmt->base->accept(this);
results[stmt->instance_id] = results[stmt->base->instance_id] +
DiffRange(true, 0, stmt->low, stmt->high);
}
void visit(BinaryOpStmt *stmt) override {
if (stmt->op_type == BinaryOpType::add ||
stmt->op_type == BinaryOpType::sub ||
stmt->op_type == BinaryOpType::mul) {
stmt->lhs->accept(this);
stmt->rhs->accept(this);
auto ret1 = results[stmt->lhs->instance_id];
auto ret2 = results[stmt->rhs->instance_id];
if (ret1.related_() && ret2.related_()) {
if (stmt->op_type == BinaryOpType::add) {
results[stmt->instance_id] = ret1 + ret2;
} else if (stmt->op_type == BinaryOpType::sub) {
results[stmt->instance_id] = ret1 - ret2;
} else {
results[stmt->instance_id] = ret1 * ret2;
}
return;
}
}
results[stmt->instance_id] = {false, 0};
}
ret_type run() {
input_stmt->accept(this);
return results[input_stmt->instance_id];
}
};
class FindDirectValueBaseAndOffset : public IRVisitor {
public:
// In the return value, <first> is true if this class finds that the input
// statement has value equal to <second> + <third> (base + offset), or
// <first> is false if this class can't find the decomposition.
using ret_type = std::tuple<bool, Stmt *, int>;
ret_type result;
FindDirectValueBaseAndOffset() : result(false, nullptr, 0) {
allow_undefined_visitor = true;
invoke_default_visitor = true;
}
void visit(Stmt *stmt) override {
result = std::make_tuple(false, nullptr, 0);
}
void visit(ConstStmt *stmt) override {
TI_ASSERT(stmt->width() == 1);
if (stmt->val[0].dt->is_primitive(PrimitiveTypeID::i32)) {
result = std::make_tuple(true, nullptr, stmt->val[0].val_i32);
}
}
void visit(BinaryOpStmt *stmt) override {
if (stmt->rhs->is<ConstStmt>())
stmt->rhs->accept(this);
if (!std::get<0>(result) || std::get<1>(result) != nullptr ||
(stmt->op_type != BinaryOpType::add &&
stmt->op_type != BinaryOpType::sub)) {
result = std::make_tuple(false, nullptr, 0);
return;
}
if (stmt->op_type == BinaryOpType::sub)
std::get<2>(result) = -std::get<2>(result);
std::get<1>(result) = stmt->lhs;
}
static ret_type run(Stmt *val) {
FindDirectValueBaseAndOffset instance;
val->accept(&instance);
return instance.result;
}
};
} // namespace
namespace irpass {
namespace analysis {
DiffRange value_diff_loop_index(Stmt *stmt, Stmt *loop, int index_id) {
TI_ASSERT(loop->is<StructForStmt>() || loop->is<OffloadedStmt>());
if (loop->is<OffloadedStmt>()) {
TI_ASSERT(loop->as<OffloadedStmt>()->task_type ==
OffloadedStmt::TaskType::struct_for);
}
if (auto loop_index = stmt->cast<LoopIndexStmt>(); loop_index) {
if (loop_index->loop == loop && loop_index->index == index_id) {
return DiffRange(true, 1, 0);
}
}
TI_ASSERT(stmt->width() == 1);
auto diff = ValueDiffLoopIndex(stmt, 0, loop, index_id);
return diff.run();
}
DiffPtrResult value_diff_ptr_index(Stmt *val1, Stmt *val2) {
if (val1 == val2) {
return DiffPtrResult::make_certain(0);
}
auto v1 = FindDirectValueBaseAndOffset::run(val1);
auto v2 = FindDirectValueBaseAndOffset::run(val2);
if (!std::get<0>(v1) || !std::get<0>(v2) ||
std::get<1>(v1) != std::get<1>(v2)) {
return DiffPtrResult::make_uncertain();
}
return DiffPtrResult::make_certain(std::get<2>(v1) - std::get<2>(v2));
}
} // namespace analysis
} // namespace irpass
} // namespace lang
} // namespace taichi
| 32.71564
| 80
| 0.619151
|
Robslhc
|
6d0ac3633bd5c1cb058c75634d40e5333fa56d80
| 529
|
cpp
|
C++
|
example/src/block-array-test.cpp
|
dangleptr/autotest
|
512e8f3bb0b38c64c55587e5f632e3fee5517dcb
|
[
"MIT"
] | null | null | null |
example/src/block-array-test.cpp
|
dangleptr/autotest
|
512e8f3bb0b38c64c55587e5f632e3fee5517dcb
|
[
"MIT"
] | null | null | null |
example/src/block-array-test.cpp
|
dangleptr/autotest
|
512e8f3bb0b38c64c55587e5f632e3fee5517dcb
|
[
"MIT"
] | null | null | null |
#include "autotest/autotest.hpp"
#include "block-array.hpp"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
auto not_empty = [](auto const& self) { return self.size() > 0; };
AutoTest::Interface<block_array<int>>(data, size)
.AUTOTEST_FUN(emplace_back, AutoTest::Args::integral<int>)
.AUTOTEST_FUN(pop_back).If(not_empty)
.AUTOTEST_FUN(back).If(not_empty)
.AUTOTEST_CONST_FUN(back).If(not_empty)
.AUTOTEST_CONST_FUN(size)
.execute();
return 0;
}
| 35.266667
| 73
| 0.676749
|
dangleptr
|
6d16e60d7d5b02cc25995ed0b62b0b5d4622a4ed
| 5,951
|
cpp
|
C++
|
rts-master/Chapter16/Example 16.1/GroupAI.cpp
|
ericrrichards/rts
|
88efe082518434cad97264d9ebd3538004c98cc3
|
[
"MIT"
] | 4
|
2015-08-09T17:59:49.000Z
|
2019-09-19T10:38:21.000Z
|
rts-master/Chapter16/Example 16.1/GroupAI.cpp
|
ericrrichards/rts
|
88efe082518434cad97264d9ebd3538004c98cc3
|
[
"MIT"
] | null | null | null |
rts-master/Chapter16/Example 16.1/GroupAI.cpp
|
ericrrichards/rts
|
88efe082518434cad97264d9ebd3538004c98cc3
|
[
"MIT"
] | null | null | null |
#include "groupAI.h"
#include "masterAI.h"
#include "strategyMap.h"
GROUPAI::GROUPAI(MASTERAI *_master)
{
m_pMaster = _master;
m_task = TASK_NONE;
m_state = GROUP_STATE_IDLE;
}
GROUPAI::~GROUPAI()
{
//Reset group pointer for all group members
for(int i=0;i<(int)m_members.size();i++)
m_members[i]->m_pGroup = NULL;
}
void GROUPAI::AddMember(MAPOBJECT *newMember)
{
if(Find(m_members, newMember) < 0)
{
newMember->m_pGroup = this;
m_members.push_back(newMember);
}
}
void GROUPAI::RemoveMember(MAPOBJECT *oldMember)
{
int place = Find(m_members, oldMember);
if(place >= 0)
{
oldMember->m_pGroup = NULL;
m_members.erase(m_members.begin() + place);
}
}
void GROUPAI::DisbandGroup()
{
while(!m_members.empty())
{
RemoveMember(m_members[0]);
}
m_members.clear();
m_visibleEnemies.clear();
}
void GROUPAI::EnemiesSpotted(std::vector<MAPOBJECT*> &manyEnemies)
{
if(m_visibleEnemies.size() > 30)return;
for(int i=0;i<(int)manyEnemies.size();i++)
if(Find(m_visibleEnemies, manyEnemies[i]) < 0)
m_visibleEnemies.push_back(manyEnemies[i]);
}
void GROUPAI::SetTask(int newTask, RECT *area)
{
m_task = newTask;
if(area == NULL)
m_task = TASK_NONE;
else m_mapArea = *area;
}
GROUPAI* GROUPAI::SplitGroup(std::vector<int> units)
{
if(units.empty() || m_members.empty())return NULL;
GROUPAI *newGroup = new GROUPAI(m_pMaster);
try
{
bool done = false;
while(!done)
{
//Transfer member
for(int i=0;i<(int)m_members.size();i++)
if(!m_members[i]->m_isBuilding && m_members[i]->m_type == units[0])
{
MAPOBJECT* unit = m_members[i];
RemoveMember(unit);
newGroup->AddMember(unit);
break;
}
units.erase(units.begin());
done = units.empty() || m_members.empty();
}
if(newGroup->isDead())
{
delete newGroup;
newGroup = NULL;
}
}
catch(...)
{
debug.Print("Error in GROUPAI::SplitGroup()");
}
return newGroup;
}
void GROUPAI::Goto(RECT mArea)
{
if(m_members.empty())return;
try
{
for(int i=0;i<(int)m_members.size();i++)
if(m_members[i] != NULL && !m_members[i]->m_isBuilding && !m_members[i]->m_dead)
{
UNIT *unit = (UNIT*)m_members[i];
if(unit->m_state != STATE_ATTACK)
{
INTPOINT p(rand()%(mArea.right - mArea.left) + mArea.left,
rand()%(mArea.bottom - mArea.top) + mArea.top);
p = unit->m_pTerrain->GetClosestFreeTile(p, unit->m_mappos);
unit->m_pTarget = NULL;
unit->Goto(p, false, true, STATE_MOVING);
}
}
}
catch(...){}
}
void GROUPAI::Attack(std::vector<MAPOBJECT*> &enemies)
{
for(int i=0;i<(int)m_members.size();i++)
if(!m_members[i]->m_isBuilding && !m_members[i]->m_dead)
{
UNIT *unit = (UNIT*)m_members[i];
if(unit->m_state == STATE_IDLE || unit->m_state == STATE_MOVING)
unit->Attack(unit->BestTargetToAttack(enemies));
}
}
void GROUPAI::RetreatTo(RECT ma)
{
if(m_members.empty())return;
for(int i=0;i<(int)m_members.size();i++)
if(!m_members[i]->m_isBuilding && !m_members[i]->m_dead)
{
UNIT *unit = (UNIT*)m_members[i];
if(!unit->m_mappos.inRect(ma))
{
INTPOINT p(rand()%(ma.right - ma.left) + ma.left,
rand()%(ma.bottom - ma.top) + ma.top);
p = unit->m_pTerrain->GetClosestFreeTile(p, unit->m_mappos);
unit->m_pTarget = NULL;
unit->Goto(p, false, true, STATE_RETREAT);
}
}
m_mapArea = ma;
}
void GROUPAI::Shuffle()
{
if(m_members.empty())return;
for(int i=0;i<(int)m_members.size();i++)
if(!m_members[i]->m_isBuilding && !m_members[i]->m_dead && rand()%40 == 0)
{
UNIT *unit = (UNIT*)m_members[i];
INTPOINT p(rand()%(m_mapArea.right - m_mapArea.left) + m_mapArea.left,
rand()%(m_mapArea.bottom - m_mapArea.top) + m_mapArea.top);
p = unit->m_pTerrain->GetClosestFreeTile(p, unit->m_mappos);
unit->m_pTarget = NULL;
unit->Goto(p, false, true, STATE_MOVING);
}
}
void GROUPAI::GroupAI()
{
if(m_members.empty() || m_pMaster == NULL)return;
int memberStates[] = {0, 0, 0};
m_state = GROUP_STATE_IDLE;
std::vector<MAPOBJECT*>::iterator i;
for(i = m_members.begin();i != m_members.end();)
{
if((*i) == NULL || (*i)->m_dead)
{
//Remove dead Group m_members
RemoveMember(*i);
}
else
{
(*i)->m_pGroup = this;
//determine group m_state
if(!(*i)->m_isBuilding)
{
UNIT *unit = (UNIT*)(*i);
if(unit->m_state == STATE_ATTACK)
memberStates[GROUP_STATE_BATTLE]++;
else if(unit->m_moving)
memberStates[GROUP_STATE_MOVING]++;
else memberStates[GROUP_STATE_IDLE]++;
}
i++;
}
}
//Set group state
if(memberStates[GROUP_STATE_BATTLE] >= m_members.size() * 0.2f)
m_state = GROUP_STATE_BATTLE;
else if(memberStates[GROUP_STATE_MOVING] >= m_members.size() * 0.4f)
m_state = GROUP_STATE_MOVING;
else m_state = GROUP_STATE_IDLE;
//Group state machine
switch(m_state)
{
case GROUP_STATE_IDLE:
{
if(m_task == TASK_SCOUT)
{
AREA *area = m_pMaster->m_pStrategyMap->GetScoutArea(GetCenter());
if(area != NULL)Goto(area->m_mapArea);
}
else if(m_task == TASK_ATTACK_LOCATION)
{
AREA *area = m_pMaster->m_pStrategyMap->GetAttackArea(GetCenter());
if(area != NULL)Goto(area->m_mapArea);
}
else if(m_task == TASK_NONE || m_task == TASK_DEFEND_LOCATION)
{
Shuffle();
}
break;
}
case GROUP_STATE_MOVING:
{
Attack(m_visibleEnemies);
break;
}
case GROUP_STATE_BATTLE:
{
Attack(m_visibleEnemies);
if(m_task == TASK_DEFEND_LOCATION)
RetreatTo(m_mapArea);
break;
}
}
//Report enemies to Master AI
m_pMaster->EnemiesSpotted(m_visibleEnemies);
m_visibleEnemies.clear();
}
bool GROUPAI::isDead()
{
return m_members.empty();
}
INTPOINT GROUPAI::GetCenter()
{
INTPOINT p;
try
{
if(m_members.size() <= 0)return p;
for(int i=0;i<(int)m_members.size();i++)
p += m_members[i]->m_mappos;
p /= m_members.size();
}
catch(...)
{
debug.Print("Error in GROUPAI::GetCenter()");
}
return p;
}
| 20.172881
| 83
| 0.641909
|
ericrrichards
|
6d178b2f8e06b4ac5e86ffec9d4234ff02d079d9
| 1,307
|
hpp
|
C++
|
d_mk66f18/sys_pitmgr_port.hpp
|
beforelight/HITSIC_Module
|
5066d6eeed70b36564b52d2da7c5acd752589996
|
[
"Apache-2.0"
] | null | null | null |
d_mk66f18/sys_pitmgr_port.hpp
|
beforelight/HITSIC_Module
|
5066d6eeed70b36564b52d2da7c5acd752589996
|
[
"Apache-2.0"
] | null | null | null |
d_mk66f18/sys_pitmgr_port.hpp
|
beforelight/HITSIC_Module
|
5066d6eeed70b36564b52d2da7c5acd752589996
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright 2018 - 2020 HITSIC
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* sys_pitmgr_port.hpp
*
* Created on: 2019年12月5日
* Author: CkovMk
*/
#ifndef D_MK66F18_SYS_PITMGR_PORT_HPP_
#define D_MK66F18_SYS_PITMGR_PORT_HPP_
#include "hitsic_common.h"
#if defined(HITSIC_USE_PITMGR) && (HITSIC_USE_PITMGR > 0)
#define HITSIC_PITMGR_CNTFREQ 60000000
#define HITSIC_PITMGR_INITLIZE (1U)
#if defined(HITSIC_PITMGR_INITLIZE) && (HITSIC_PITMGR_INITLIZE > 0)
inline void PITMGR_PlatformInit(void)
{
NVIC_SetPriority(LPTMR0_IRQn, 4);
EnableIRQ(LPTMR0_IRQn);
LPTMR_StartTimer(LPTMR0);
}
#endif // ! HITSIC_PITMGR_INITLIZE
#define HITSIC_PITMGR_DEFAULT_IRQ (1U)
#endif // ! HITSIC_USE_PITMGR
#endif // ! D_MK66F18_SYS_PITMGR_PORT_HPP_
| 26.14
| 75
| 0.750574
|
beforelight
|
6d19bab8ce7599902baa33d7fccc019277b2e1df
| 7,420
|
cpp
|
C++
|
plugins/datatools/src/AbstractVolumeManipulator.cpp
|
masrice/megamol
|
d48fc4889f500528609053a5445202a9c0f6e5fb
|
[
"BSD-3-Clause"
] | 49
|
2017-08-23T13:24:24.000Z
|
2022-03-16T09:10:58.000Z
|
plugins/datatools/src/AbstractVolumeManipulator.cpp
|
masrice/megamol
|
d48fc4889f500528609053a5445202a9c0f6e5fb
|
[
"BSD-3-Clause"
] | 200
|
2018-07-20T15:18:26.000Z
|
2022-03-31T11:01:44.000Z
|
plugins/datatools/src/AbstractVolumeManipulator.cpp
|
masrice/megamol
|
d48fc4889f500528609053a5445202a9c0f6e5fb
|
[
"BSD-3-Clause"
] | 31
|
2017-07-31T16:19:29.000Z
|
2022-02-14T23:41:03.000Z
|
/*
* AbstractParticleManipulator.cpp
*
* Copyright (C) 2014 by S. Grottel
* Alle Rechte vorbehalten.
*/
#include "datatools/AbstractVolumeManipulator.h"
#include "datatools/AbstractParticleManipulator.h"
#include "stdafx.h"
using namespace megamol;
/*
* datatools::AbstractVolumeManipulator::AbstractVolumeManipulator
*/
datatools::AbstractVolumeManipulator::AbstractVolumeManipulator(const char* outSlotName, const char* inSlotName)
: megamol::core::Module()
, outDataSlot(outSlotName, "providing access to the manipulated data")
, inDataSlot(inSlotName, "accessing the original data") {
this->outDataSlot.SetCallback(megamol::geocalls::VolumetricDataCall::ClassName(),
geocalls::VolumetricDataCall::FunctionName(geocalls::VolumetricDataCall::IDX_GET_DATA),
&AbstractVolumeManipulator::getDataCallback);
this->outDataSlot.SetCallback(megamol::geocalls::VolumetricDataCall::ClassName(),
geocalls::VolumetricDataCall::FunctionName(geocalls::VolumetricDataCall::IDX_GET_EXTENTS),
&AbstractVolumeManipulator::getExtentCallback);
this->outDataSlot.SetCallback(megamol::geocalls::VolumetricDataCall::ClassName(),
geocalls::VolumetricDataCall::FunctionName(geocalls::VolumetricDataCall::IDX_GET_METADATA),
&AbstractVolumeManipulator::getMetaDataCallback);
this->outDataSlot.SetCallback(megamol::geocalls::VolumetricDataCall::ClassName(),
geocalls::VolumetricDataCall::FunctionName(geocalls::VolumetricDataCall::IDX_START_ASYNC),
&AbstractVolumeManipulator::startAsyncCallback);
this->outDataSlot.SetCallback(megamol::geocalls::VolumetricDataCall::ClassName(),
geocalls::VolumetricDataCall::FunctionName(geocalls::VolumetricDataCall::IDX_STOP_ASYNC),
&AbstractVolumeManipulator::stopAsyncCallback);
this->outDataSlot.SetCallback(megamol::geocalls::VolumetricDataCall::ClassName(),
geocalls::VolumetricDataCall::FunctionName(geocalls::VolumetricDataCall::IDX_TRY_GET_DATA),
&AbstractVolumeManipulator::tryGetDataCallback);
this->MakeSlotAvailable(&this->outDataSlot);
this->inDataSlot.SetCompatibleCall<geocalls::VolumetricDataCallDescription>();
this->MakeSlotAvailable(&this->inDataSlot);
}
/*
* datatools::AbstractVolumeManipulator::~AbstractVolumeManipulator
*/
datatools::AbstractVolumeManipulator::~AbstractVolumeManipulator(void) {}
/*
* datatools::AbstractVolumeManipulator::create
*/
bool datatools::AbstractVolumeManipulator::create(void) {
return true;
}
/*
* datatools::AbstractVolumeManipulator::release
*/
void datatools::AbstractVolumeManipulator::release(void) {}
/*
* datatools::AbstractVolumeManipulator::manipulateData
*/
bool datatools::AbstractVolumeManipulator::manipulateData(
megamol::geocalls::VolumetricDataCall& outData, megamol::geocalls::VolumetricDataCall& inData) {
outData = inData;
inData.SetUnlocker(nullptr, false);
return true;
}
/*
* datatools::AbstractVolumeManipulator::manipulateExtent
*/
bool datatools::AbstractVolumeManipulator::manipulateExtent(
megamol::geocalls::VolumetricDataCall& outData, megamol::geocalls::VolumetricDataCall& inData) {
outData = inData;
inData.SetUnlocker(nullptr, false);
return true;
}
/*
* datatools::AbstractVolumeManipulator::manipulateMetaData
*/
bool datatools::AbstractVolumeManipulator::manipulateMetaData(
class geocalls::VolumetricDataCall& outData, class geocalls::VolumetricDataCall& inData) {
outData = inData;
inData.SetUnlocker(nullptr, false);
return true;
}
/*
* datatools::AbstractVolumeManipulator::getDataCallback
*/
bool datatools::AbstractVolumeManipulator::getDataCallback(megamol::core::Call& c) {
using megamol::geocalls::VolumetricDataCall;
auto* outVdc = dynamic_cast<VolumetricDataCall*>(&c);
if (outVdc == nullptr)
return false;
auto* inVdc = this->inDataSlot.CallAs<VolumetricDataCall>();
if (inVdc == nullptr)
return false;
*inVdc = *outVdc; // to get the correct request time
if (!(*inVdc)(VolumetricDataCall::IDX_GET_DATA)) {
megamol::core::utility::log::Log::DefaultLog.WriteInfo("AbstractVolumeManipulator: No data available.\n");
return false;
}
if (!this->manipulateData(*outVdc, *inVdc)) {
inVdc->Unlock();
return false;
}
inVdc->Unlock();
return true;
}
/*
* datatools::AbstractVolumeManipulator::getExtentCallback
*/
bool datatools::AbstractVolumeManipulator::getExtentCallback(megamol::core::Call& c) {
using megamol::geocalls::VolumetricDataCall;
auto* outVdc = dynamic_cast<VolumetricDataCall*>(&c);
if (outVdc == nullptr)
return false;
auto* inVdc = this->inDataSlot.CallAs<VolumetricDataCall>();
if (inVdc == nullptr)
return false;
*inVdc = *outVdc; // to get the correct request time
if (!(*inVdc)(VolumetricDataCall::IDX_GET_EXTENTS))
return false;
if (!this->manipulateExtent(*outVdc, *inVdc)) {
inVdc->Unlock();
return false;
}
inVdc->Unlock();
return true;
}
bool datatools::AbstractVolumeManipulator::getMetaDataCallback(megamol::core::Call& c) {
using megamol::geocalls::VolumetricDataCall;
auto* outVdc = dynamic_cast<VolumetricDataCall*>(&c);
if (outVdc == nullptr)
return false;
auto* inVdc = this->inDataSlot.CallAs<VolumetricDataCall>();
if (inVdc == nullptr)
return false;
*inVdc = *outVdc; // to get the correct request time
if (!(*inVdc)(VolumetricDataCall::IDX_GET_METADATA))
return false;
if (!this->manipulateMetaData(*outVdc, *inVdc)) {
inVdc->Unlock();
return false;
}
inVdc->Unlock();
return true;
}
bool datatools::AbstractVolumeManipulator::startAsyncCallback(megamol::core::Call& c) {
using megamol::geocalls::VolumetricDataCall;
auto* outVdc = dynamic_cast<VolumetricDataCall*>(&c);
if (outVdc == nullptr)
return false;
auto* inVdc = this->inDataSlot.CallAs<VolumetricDataCall>();
if (inVdc == nullptr)
return false;
*inVdc = *outVdc; // to get the correct request time
if (!(*inVdc)(VolumetricDataCall::IDX_START_ASYNC))
return false;
inVdc->Unlock();
return true;
}
bool datatools::AbstractVolumeManipulator::stopAsyncCallback(megamol::core::Call& c) {
using megamol::geocalls::VolumetricDataCall;
auto* outVdc = dynamic_cast<VolumetricDataCall*>(&c);
if (outVdc == nullptr)
return false;
auto* inVdc = this->inDataSlot.CallAs<VolumetricDataCall>();
if (inVdc == nullptr)
return false;
*inVdc = *outVdc; // to get the correct request time
if (!(*inVdc)(VolumetricDataCall::IDX_STOP_ASYNC))
return false;
inVdc->Unlock();
return true;
}
bool datatools::AbstractVolumeManipulator::tryGetDataCallback(megamol::core::Call& c) {
using megamol::geocalls::VolumetricDataCall;
auto* outVdc = dynamic_cast<VolumetricDataCall*>(&c);
if (outVdc == nullptr)
return false;
auto* inVdc = this->inDataSlot.CallAs<VolumetricDataCall>();
if (inVdc == nullptr)
return false;
*inVdc = *outVdc; // to get the correct request time
if (!(*inVdc)(VolumetricDataCall::IDX_TRY_GET_DATA))
return false;
// TODO BUG HAZARD: if data, manipulate.
inVdc->Unlock();
return true;
}
| 30.409836
| 114
| 0.710916
|
masrice
|
6d1c3753827761215725e5f7eb256faaede4c48b
| 2,648
|
hpp
|
C++
|
externals/boost/boost/mp11/integer_sequence.hpp
|
YuukiTsuchida/v8_embeded
|
c6e18f4e91fcc50607f8e3edc745a3afa30b2871
|
[
"MIT"
] | 32
|
2019-02-27T06:57:07.000Z
|
2021-08-29T10:56:19.000Z
|
jeff/common/include/boost/mp11/integer_sequence.hpp
|
jeffphi/advent-of-code-2018
|
8e54bd23ebfe42fcbede315f0ab85db903551532
|
[
"MIT"
] | 1
|
2019-04-04T18:00:00.000Z
|
2019-04-04T18:00:00.000Z
|
jeff/common/include/boost/mp11/integer_sequence.hpp
|
jeffphi/advent-of-code-2018
|
8e54bd23ebfe42fcbede315f0ab85db903551532
|
[
"MIT"
] | 5
|
2019-08-20T13:45:04.000Z
|
2022-03-01T18:23:49.000Z
|
#ifndef BOOST_MP11_INTEGER_SEQUENCE_HPP_INCLUDED
#define BOOST_MP11_INTEGER_SEQUENCE_HPP_INCLUDED
// Copyright 2015, 2017 Peter Dimov.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <cstddef>
namespace boost
{
namespace mp11
{
// integer_sequence
template<class T, T... I> struct integer_sequence
{
};
// detail::make_integer_sequence_impl
namespace detail
{
// iseq_if_c
template<bool C, class T, class E> struct iseq_if_c_impl;
template<class T, class E> struct iseq_if_c_impl<true, T, E>
{
using type = T;
};
template<class T, class E> struct iseq_if_c_impl<false, T, E>
{
using type = E;
};
template<bool C, class T, class E> using iseq_if_c = typename iseq_if_c_impl<C, T, E>::type;
// iseq_identity
template<class T> struct iseq_identity
{
using type = T;
};
template<class S1, class S2> struct append_integer_sequence;
template<class T, T... I, T... J> struct append_integer_sequence<integer_sequence<T, I...>, integer_sequence<T, J...>>
{
using type = integer_sequence< T, I..., ( J + sizeof...(I) )... >;
};
template<class T, T N> struct make_integer_sequence_impl;
template<class T, T N> struct make_integer_sequence_impl_
{
private:
static_assert( N >= 0, "make_integer_sequence<T, N>: N must not be negative" );
static T const M = N / 2;
static T const R = N % 2;
using S1 = typename make_integer_sequence_impl<T, M>::type;
using S2 = typename append_integer_sequence<S1, S1>::type;
using S3 = typename make_integer_sequence_impl<T, R>::type;
using S4 = typename append_integer_sequence<S2, S3>::type;
public:
using type = S4;
};
template<class T, T N> struct make_integer_sequence_impl: iseq_if_c<N == 0, iseq_identity<integer_sequence<T>>, iseq_if_c<N == 1, iseq_identity<integer_sequence<T, 0>>, make_integer_sequence_impl_<T, N> > >
{
};
} // namespace detail
// make_integer_sequence
template<class T, T N> using make_integer_sequence = typename detail::make_integer_sequence_impl<T, N>::type;
// index_sequence
template<std::size_t... I> using index_sequence = integer_sequence<std::size_t, I...>;
// make_index_sequence
template<std::size_t N> using make_index_sequence = make_integer_sequence<std::size_t, N>;
// index_sequence_for
template<class... T> using index_sequence_for = make_integer_sequence<std::size_t, sizeof...(T)>;
} // namespace mp11
} // namespace boost
#endif // #ifndef BOOST_MP11_INTEGER_SEQUENCE_HPP_INCLUDED
| 27.020408
| 207
| 0.700529
|
YuukiTsuchida
|
6d20302abcf543bd467f31bb85dd72192c36da0b
| 1,634
|
cpp
|
C++
|
src/database/query.cpp
|
Natureshadow/biboumi
|
b70136b96e579e8d38a30a298f885899cb80514c
|
[
"Zlib"
] | null | null | null |
src/database/query.cpp
|
Natureshadow/biboumi
|
b70136b96e579e8d38a30a298f885899cb80514c
|
[
"Zlib"
] | null | null | null |
src/database/query.cpp
|
Natureshadow/biboumi
|
b70136b96e579e8d38a30a298f885899cb80514c
|
[
"Zlib"
] | null | null | null |
#include <database/query.hpp>
#include <database/column.hpp>
void actual_bind(Statement& statement, const std::string& value, int index)
{
statement.bind_text(index, value);
}
void actual_bind(Statement& statement, const std::int64_t& value, int index)
{
statement.bind_int64(index, value);
}
void actual_bind(Statement& statement, const OptionalBool& value, int index)
{
if (!value.is_set)
statement.bind_int64(index, 0);
else if (value.value)
statement.bind_int64(index, 1);
else
statement.bind_int64(index, -1);
}
void actual_bind(Statement& statement, const DateTime& value, int index)
{
const auto epoch = value.epoch().count();
const auto result = std::to_string(static_cast<long double>(epoch) / std::chrono::system_clock::period::den);
statement.bind_text(index, result);
}
void actual_add_param(Query& query, const std::string& val)
{
query.params.push_back(val);
}
void actual_add_param(Query& query, const OptionalBool& val)
{
if (!val.is_set)
query.params.push_back("0");
else if (val.value)
query.params.push_back("1");
else
query.params.push_back("-1");
}
Query& operator<<(Query& query, const char* str)
{
query.body += str;
return query;
}
Query& operator<<(Query& query, const std::string& str)
{
query.body += "$" + std::to_string(query.current_param);
query.current_param++;
actual_add_param(query, str);
return query;
}
Query& operator<<(Query& query, const DatetimeWriter& datetime_writer)
{
query.body += datetime_writer.escape_param_number(query.current_param++);
actual_add_param(query, datetime_writer.get_value());
return query;
}
| 24.029412
| 111
| 0.717258
|
Natureshadow
|
6d207c8c722c994b0bc81c92cda7fdf4da90ff86
| 35,776
|
hpp
|
C++
|
hpx/runtime/parcelset/parcelport_impl.hpp
|
alexmyczko/hpx
|
fd68e000ead9a03a6b5bad49cf4905df1c0b78c4
|
[
"BSL-1.0"
] | null | null | null |
hpx/runtime/parcelset/parcelport_impl.hpp
|
alexmyczko/hpx
|
fd68e000ead9a03a6b5bad49cf4905df1c0b78c4
|
[
"BSL-1.0"
] | null | null | null |
hpx/runtime/parcelset/parcelport_impl.hpp
|
alexmyczko/hpx
|
fd68e000ead9a03a6b5bad49cf4905df1c0b78c4
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2014 Thomas Heller
// Copyright (c) 2007-2017 Hartmut Kaiser
// Copyright (c) 2007 Richard D Guidry Jr
// Copyright (c) 2011 Bryce Lelbach
// Copyright (c) 2011 Katelyn Kufahl
//
// 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 HPX_PARCELSET_PARCELPORT_IMPL_HPP
#define HPX_PARCELSET_PARCELPORT_IMPL_HPP
#include <hpx/config.hpp>
#include <hpx/error_code.hpp>
#include <hpx/runtime/config_entry.hpp>
#include <hpx/runtime/parcelset/detail/call_for_each.hpp>
#include <hpx/runtime/parcelset/detail/parcel_await.hpp>
#include <hpx/runtime/parcelset/encode_parcels.hpp>
#include <hpx/runtime/parcelset/parcelport.hpp>
#include <hpx/runtime/threads/thread.hpp>
#include <hpx/throw_exception.hpp>
#include <hpx/util/assert.hpp>
#include <hpx/util/atomic_count.hpp>
#include <hpx/util/bind_front.hpp>
#include <hpx/util/connection_cache.hpp>
#include <hpx/util/deferred_call.hpp>
#include <hpx/util/detail/yield_k.hpp>
#include <hpx/util/io_service_pool.hpp>
#include <hpx/util/runtime_configuration.hpp>
#include <hpx/util/safe_lexical_cast.hpp>
#include <boost/predef/other/endian.h>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <mutex>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace parcelset
{
///////////////////////////////////////////////////////////////////////////
template <typename ConnectionHandler>
struct connection_handler_traits;
template <typename ConnectionHandler>
class HPX_EXPORT parcelport_impl
: public parcelport
{
typedef
typename connection_handler_traits<ConnectionHandler>::connection_type
connection;
public:
static const char * connection_handler_type()
{
return connection_handler_traits<ConnectionHandler>::type();
}
static std::size_t thread_pool_size(util::runtime_configuration const& ini)
{
std::string key("hpx.parcel.");
key += connection_handler_type();
return hpx::util::get_entry_as<std::size_t>(
ini, key + ".io_pool_size", "2");
}
static const char *pool_name()
{
return connection_handler_traits<ConnectionHandler>::pool_name();
}
static const char *pool_name_postfix()
{
return connection_handler_traits<ConnectionHandler>::pool_name_postfix();
}
static std::size_t max_connections(util::runtime_configuration const& ini)
{
std::string key("hpx.parcel.");
key += connection_handler_type();
return hpx::util::get_entry_as<std::size_t>(
ini, key + ".max_connections", HPX_PARCEL_MAX_CONNECTIONS);
}
static
std::size_t max_connections_per_loc(util::runtime_configuration const& ini)
{
std::string key("hpx.parcel.");
key += connection_handler_type();
return hpx::util::get_entry_as<std::size_t>(
ini, key + ".max_connections_per_locality",
HPX_PARCEL_MAX_CONNECTIONS_PER_LOCALITY);
}
public:
/// Construct the parcelport on the given locality.
parcelport_impl(util::runtime_configuration const& ini,
locality const& here,
util::function_nonser<void(std::size_t, char const*)> const&
on_start_thread,
util::function_nonser<void(std::size_t, char const*)> const&
on_stop_thread)
: parcelport(ini, here, connection_handler_type())
, io_service_pool_(thread_pool_size(ini), on_start_thread,
on_stop_thread, pool_name(), pool_name_postfix())
, connection_cache_(
max_connections(ini), max_connections_per_loc(ini))
, archive_flags_(0)
, operations_in_flight_(0)
, num_thread_(0)
, max_background_thread_(hpx::util::safe_lexical_cast<std::size_t>(
hpx::get_config_entry("hpx.max_background_threads",
(std::numeric_limits<std::size_t>::max)())))
{
#if BOOST_ENDIAN_BIG_BYTE
std::string endian_out = get_config_entry("hpx.parcel.endian_out", "big");
#else
std::string endian_out = get_config_entry("hpx.parcel.endian_out", "little");
#endif
if (endian_out == "little")
archive_flags_ |= serialization::endian_little;
else if (endian_out == "big")
archive_flags_ |= serialization::endian_big;
else {
HPX_ASSERT(endian_out =="little" || endian_out == "big");
}
if (!this->allow_array_optimizations()) {
archive_flags_ |= serialization::disable_array_optimization;
archive_flags_ |= serialization::disable_data_chunking;
}
else {
if (!this->allow_zero_copy_optimizations())
archive_flags_ |= serialization::disable_data_chunking;
}
}
~parcelport_impl() override
{
connection_cache_.clear();
}
bool can_bootstrap() const override
{
return
connection_handler_traits<
ConnectionHandler
>::send_early_parcel::value;
}
bool run(bool blocking = true) override
{
io_service_pool_.run(false); // start pool
bool success = connection_handler().do_run();
if (blocking)
io_service_pool_.join();
return success;
}
void flush_parcels() override
{
// We suspend our thread, which will make progress on the network
if(threads::get_self_ptr())
{
hpx::this_thread::suspend(hpx::threads::pending_boost,
"parcelport_impl::flush_parcels");
}
// make sure no more work is pending, wait for service pool to get
// empty
while(operations_in_flight_ != 0 || get_pending_parcels_count(false) != 0)
{
if(threads::get_self_ptr())
{
hpx::this_thread::suspend(hpx::threads::pending_boost,
"parcelport_impl::flush_parcels");
}
}
}
void stop(bool blocking = true) override
{
flush_parcels();
if (blocking) {
connection_cache_.shutdown();
connection_handler().do_stop();
io_service_pool_.wait();
io_service_pool_.stop();
io_service_pool_.join();
connection_cache_.clear();
io_service_pool_.clear();
}
else
{
io_service_pool_.stop();
}
}
public:
void put_parcel(
locality const& dest, parcel p, write_handler_type f) override
{
HPX_ASSERT(dest.type() == type());
// We create a shared pointer of the parcels_await object since it
// needs to be kept alive as long as there are futures not ready
// or GIDs to be split. This is necessary to preserve the identity
// of the this pointer.
detail::parcel_await_apply(std::move(p), std::move(f),
archive_flags_, [this, dest](parcel&& p, write_handler_type&& f)
{
if (connection_handler_traits<ConnectionHandler>::
send_immediate_parcels::value &&
can_send_immediate_impl<ConnectionHandler>())
{
send_immediate_impl<ConnectionHandler>(
*this, dest, &f, &p, 1);
}
else
{
// enqueue the outgoing parcel ...
enqueue_parcel(dest, std::move(p), std::move(f));
get_connection_and_send_parcels(dest);
}
});
}
void put_parcels(locality const& dest, std::vector<parcel> parcels,
std::vector<write_handler_type> handlers) override
{
if (parcels.size() != handlers.size())
{
HPX_THROW_EXCEPTION(bad_parameter, "parcelport::put_parcels",
"mismatched number of parcels and handlers");
return;
}
#if defined(HPX_DEBUG)
// make sure all parcels go to the same locality
HPX_ASSERT(dest.type() == type());
for (std::size_t i = 1; i != parcels.size(); ++i)
{
HPX_ASSERT(parcels[0].destination_locality() ==
parcels[i].destination_locality());
}
#endif
// We create a shared pointer of the parcels_await object since it
// needs to be kept alive as long as there are futures not ready
// or GIDs to be split. This is necessary to preserve the identity
// of the this pointer.
detail::parcels_await_apply(std::move(parcels),
std::move(handlers), archive_flags_,
[this, dest](std::vector<parcel>&& parcels,
std::vector<write_handler_type>&& handlers)
{
if (connection_handler_traits<ConnectionHandler>::
send_immediate_parcels::value &&
can_send_immediate_impl<ConnectionHandler>())
{
send_immediate_impl<ConnectionHandler>(
*this, dest, handlers.data(), parcels.data(),
parcels.size());
}
else
{
enqueue_parcels(
dest, std::move(parcels), std::move(handlers));
get_connection_and_send_parcels(dest);
}
});
}
void send_early_parcel(locality const & dest, parcel p) override
{
send_early_parcel_impl<ConnectionHandler>(dest, std::move(p));
}
util::io_service_pool* get_thread_pool(char const* name) override
{
if (0 == std::strcmp(name, io_service_pool_.get_name()))
return &io_service_pool_;
return nullptr;
}
bool do_background_work(
std::size_t num_thread, parcelport_background_mode mode) override
{
trigger_pending_work();
return do_background_work_impl<ConnectionHandler>(num_thread, mode);
}
/// support enable_shared_from_this
std::shared_ptr<parcelport_impl> shared_from_this()
{
return std::static_pointer_cast<parcelport_impl>(
parcelset::parcelport::shared_from_this());
}
std::shared_ptr<parcelport_impl const> shared_from_this() const
{
return std::static_pointer_cast<parcelport_impl const>(
parcelset::parcelport::shared_from_this());
}
/// Cache specific functionality
void remove_from_connection_cache_delayed(locality const& loc)
{
if (operations_in_flight_ != 0)
{
error_code ec(lightweight);
hpx::applier::register_thread_nullary(
util::deferred_call(
&parcelport_impl::remove_from_connection_cache,
this, loc),
"remove_from_connection_cache_delayed",
threads::pending, true, threads::thread_priority_normal,
threads::thread_schedule_hint(
static_cast<std::int16_t>(get_next_num_thread())),
threads::thread_stacksize_default,
ec);
if (!ec) return;
}
connection_cache_.clear(loc);
}
void remove_from_connection_cache(locality const& loc) override
{
error_code ec(lightweight);
threads::thread_id_type id =
hpx::applier::register_thread_nullary(
util::deferred_call(
&parcelport_impl::remove_from_connection_cache_delayed,
this, loc),
"remove_from_connection_cache",
threads::suspended, true, threads::thread_priority_normal,
threads::thread_schedule_hint(
static_cast<std::int16_t>(get_next_num_thread())),
threads::thread_stacksize_default,
ec);
if (ec) return;
threads::set_thread_state(id, std::chrono::milliseconds(100),
threads::pending, threads::wait_signaled,
threads::thread_priority_boost, true, ec);
}
/// Return the name of this locality
std::string get_locality_name() const override
{
return connection_handler().get_locality_name();
}
////////////////////////////////////////////////////////////////////////
// Return the given connection cache statistic
std::int64_t get_connection_cache_statistics(
connection_cache_statistics_type t, bool reset) override
{
switch (t) {
case connection_cache_insertions:
return connection_cache_.get_cache_insertions(reset);
case connection_cache_evictions:
return connection_cache_.get_cache_evictions(reset);
case connection_cache_hits:
return connection_cache_.get_cache_hits(reset);
case connection_cache_misses:
return connection_cache_.get_cache_misses(reset);
case connection_cache_reclaims:
return connection_cache_.get_cache_reclaims(reset);
default:
break;
}
HPX_THROW_EXCEPTION(bad_parameter,
"parcelport_impl::get_connection_cache_statistics",
"invalid connection cache statistics type");
return 0;
}
private:
ConnectionHandler & connection_handler()
{
return static_cast<ConnectionHandler &>(*this);
}
ConnectionHandler const & connection_handler() const
{
return static_cast<ConnectionHandler const &>(*this);
}
template <typename ConnectionHandler_>
typename std::enable_if<
connection_handler_traits<
ConnectionHandler_
>::send_early_parcel::value
>::type
send_early_parcel_impl(locality const & dest, parcel p)
{
put_parcel(
dest
, std::move(p)
, [=](boost::system::error_code const& ec, parcel const & p) -> void {
return early_pending_parcel_handler(ec, p);
}
);
}
template <typename ConnectionHandler_>
typename std::enable_if<
!connection_handler_traits<
ConnectionHandler_
>::send_early_parcel::value
>::type
send_early_parcel_impl(locality const & dest, parcel p)
{
HPX_THROW_EXCEPTION(network_error, "send_early_parcel",
"This parcelport does not support sending early parcels");
}
template <typename ConnectionHandler_>
typename std::enable_if<
connection_handler_traits<
ConnectionHandler_
>::do_background_work::value,
bool
>::type
do_background_work_impl(std::size_t num_thread,
parcelport_background_mode mode)
{
return connection_handler().background_work(num_thread, mode);
}
template <typename ConnectionHandler_>
typename std::enable_if<
!connection_handler_traits<
ConnectionHandler_
>::do_background_work::value,
bool
>::type
do_background_work_impl(std::size_t, parcelport_background_mode)
{
return false;
}
template <typename ConnectionHandler_>
typename std::enable_if<
connection_handler_traits<
ConnectionHandler_
>::send_immediate_parcels::value,
bool
>::type
can_send_immediate_impl()
{
return connection_handler().can_send_immediate();
}
template <typename ConnectionHandler_>
typename std::enable_if<
!connection_handler_traits<
ConnectionHandler_
>::send_immediate_parcels::value,
bool
>::type
can_send_immediate_impl()
{
return false;
}
protected:
template <typename ConnectionHandler_>
typename std::enable_if<
connection_handler_traits<
ConnectionHandler_
>::send_immediate_parcels::value,
void
>::type
send_immediate_impl(
parcelport_impl &this_, locality const&dest_,
write_handler_type *fs, parcel *ps, std::size_t num_parcels)
{
std::uint64_t addr;
error_code ec;
// First try to get a connection ...
connection *sender = this_.connection_handler().get_connection(dest_, addr);
// If we couldn't get one ... enqueue the parcel and move on
std::size_t encoded_parcels = 0;
std::vector<parcel> parcels;
std::vector<write_handler_type> handlers;
if (sender != nullptr)
{
if (fs == nullptr)
{
HPX_ASSERT(ps == nullptr);
HPX_ASSERT(num_parcels == 0u);
if(!dequeue_parcels(dest_, parcels, handlers))
{
// Give this connection back to the connection handler as
// we couldn't dequeue parcels.
this_.connection_handler().reclaim_connection(sender);
return;
}
ps = parcels.data();
fs = handlers.data();
num_parcels = parcels.size();
HPX_ASSERT(parcels.size() == handlers.size());
}
auto encoded_buffer = sender->get_new_buffer();
// encode the parcels
encoded_parcels = encode_parcels(this_, ps, num_parcels,
encoded_buffer,
this_.archive_flags_,
this_.get_max_outbound_message_size());
typedef detail::call_for_each handler_type;
if (sender->parcelport_->async_write(
handler_type(
handler_type::handlers_type(
std::make_move_iterator(fs),
std::make_move_iterator(fs + encoded_parcels)),
handler_type::parcels_type(
std::make_move_iterator(ps),
std::make_move_iterator(ps + encoded_parcels))
),
sender, addr,
encoded_buffer))
{
// we don't propagate errors for now
}
}
if (num_parcels != encoded_parcels && fs != nullptr)
{
std::vector<parcel> overflow_parcels(
std::make_move_iterator(ps + encoded_parcels),
std::make_move_iterator(ps + num_parcels));
std::vector<write_handler_type> overflow_handlers(
std::make_move_iterator(fs + encoded_parcels),
std::make_move_iterator(fs + num_parcels));
enqueue_parcels(dest_, std::move(overflow_parcels),
std::move(overflow_handlers));
}
}
template <typename ConnectionHandler_>
typename std::enable_if<
!connection_handler_traits<
ConnectionHandler_
>::send_immediate_parcels::value,
void
>::type
send_immediate_impl(
parcelport_impl &this_, locality const&dest_,
write_handler_type *fs, parcel *ps, std::size_t num_parcels)
{
HPX_ASSERT(false);
}
private:
///////////////////////////////////////////////////////////////////////
std::shared_ptr<connection> get_connection(
locality const& l, bool force, error_code& ec)
{
// Request new connection from connection cache.
std::shared_ptr<connection> sender_connection;
if (connection_handler_traits<ConnectionHandler>::
send_immediate_parcels::value)
{
std::terminate();
}
else {
// Get a connection or reserve space for a new connection.
if (!connection_cache_.get_or_reserve(l, sender_connection))
{
// If no slot is available it's not a problem as the parcel
// will be sent out whenever the next connection is returned
// to the cache.
if (&ec != &throws)
ec = make_success_code();
return sender_connection;
}
}
// Check if we need to create the new connection.
if (!sender_connection)
return connection_handler().create_connection(l, ec);
if (&ec != &throws)
ec = make_success_code();
return sender_connection;
}
///////////////////////////////////////////////////////////////////////
void enqueue_parcel(locality const& locality_id,
parcel&& p, write_handler_type&& f)
{
typedef pending_parcels_map::mapped_type mapped_type;
std::unique_lock<lcos::local::spinlock> l(mtx_);
// We ignore the lock here. It might happen that while enqueuing,
// we need to acquire a lock. This should not cause any problems
// (famous last words)
util::ignore_while_checking<
std::unique_lock<lcos::local::spinlock>
> il(&l);
mapped_type& e = pending_parcels_[locality_id];
util::get<0>(e).push_back(std::move(p));
util::get<1>(e).push_back(std::move(f));
parcel_destinations_.insert(locality_id);
++num_parcel_destinations_;
}
void enqueue_parcels(locality const& locality_id,
std::vector<parcel>&& parcels,
std::vector<write_handler_type>&& handlers)
{
typedef pending_parcels_map::mapped_type mapped_type;
std::unique_lock<lcos::local::spinlock> l(mtx_);
// We ignore the lock here. It might happen that while enqueuing,
// we need to acquire a lock. This should not cause any problems
// (famous last words)
util::ignore_while_checking<
std::unique_lock<lcos::local::spinlock>
> il(&l);
HPX_ASSERT(parcels.size() == handlers.size());
mapped_type& e = pending_parcels_[locality_id];
if (util::get<0>(e).empty())
{
HPX_ASSERT(util::get<1>(e).empty());
std::swap(util::get<0>(e), parcels);
std::swap(util::get<1>(e), handlers);
}
else
{
HPX_ASSERT(util::get<0>(e).size() == util::get<1>(e).size());
std::size_t new_size = util::get<0>(e).size() + parcels.size();
util::get<0>(e).reserve(new_size);
std::move(parcels.begin(), parcels.end(),
std::back_inserter(util::get<0>(e)));
util::get<1>(e).reserve(new_size);
std::move(handlers.begin(), handlers.end(),
std::back_inserter(util::get<1>(e)));
}
parcel_destinations_.insert(locality_id);
++num_parcel_destinations_;
}
bool dequeue_parcels(locality const& locality_id,
std::vector<parcel>& parcels,
std::vector<write_handler_type>& handlers)
{
typedef pending_parcels_map::iterator iterator;
{
std::unique_lock<lcos::local::spinlock> l(mtx_, std::try_to_lock);
if (!l) return false;
iterator it = pending_parcels_.find(locality_id);
// do nothing if parcels have already been picked up by
// another thread
if (it != pending_parcels_.end() && !util::get<0>(it->second).empty())
{
HPX_ASSERT(it->first == locality_id);
HPX_ASSERT(handlers.size() == 0);
HPX_ASSERT(handlers.size() == parcels.size());
std::swap(parcels, util::get<0>(it->second));
HPX_ASSERT(util::get<0>(it->second).size() == 0);
std::swap(handlers, util::get<1>(it->second));
HPX_ASSERT(handlers.size() == parcels.size());
HPX_ASSERT(!handlers.empty());
}
else
{
HPX_ASSERT(util::get<1>(it->second).empty());
return false;
}
parcel_destinations_.erase(locality_id);
HPX_ASSERT(0 != num_parcel_destinations_.load());
--num_parcel_destinations_;
return true;
}
}
protected:
bool dequeue_parcel(locality& dest, parcel& p, write_handler_type& handler)
{
{
std::unique_lock<lcos::local::spinlock> l(mtx_, std::try_to_lock);
if (!l) return false;
for (auto &pending: pending_parcels_)
{
auto &parcels = util::get<0>(pending.second);
if (!parcels.empty())
{
auto& handlers = util::get<1>(pending.second);
dest = pending.first;
p = std::move(parcels.back());
parcels.pop_back();
handler = std::move(handlers.back());
handlers.pop_back();
if (parcels.empty())
{
pending_parcels_.erase(dest);
}
return true;
}
}
}
return false;
}
bool trigger_pending_work()
{
if (0 == num_parcel_destinations_.load(std::memory_order_relaxed))
return true;
std::vector<locality> destinations;
{
std::unique_lock<lcos::local::spinlock> l(mtx_, std::try_to_lock);
if(l.owns_lock())
{
if (parcel_destinations_.empty())
return true;
destinations.reserve(parcel_destinations_.size());
for (locality const& loc : parcel_destinations_)
{
destinations.push_back(loc);
}
}
}
// Create new HPX threads which send the parcels that are still
// pending.
for (locality const& loc : destinations)
{
get_connection_and_send_parcels(loc);
}
return true;
}
private:
///////////////////////////////////////////////////////////////////////
void get_connection_and_send_parcels(
locality const& locality_id, bool background = false)
{
if (connection_handler_traits<ConnectionHandler>::
send_immediate_parcels::value)
{
this->send_immediate_impl<ConnectionHandler>(
*this, locality_id, nullptr, nullptr, 0);
return;
}
// If one of the sending threads are in suspended state, we
// need to force a new connection to avoid deadlocks.
bool force_connection = true;
error_code ec;
std::shared_ptr<connection> sender_connection =
get_connection(locality_id, force_connection, ec);
if (!sender_connection)
{
// We can safely return if no connection is available
// at this point. As soon as a connection becomes
// available it checks for pending parcels and sends
// those out.
return;
}
// repeat until no more parcels are to be sent
std::vector<parcel> parcels;
std::vector<write_handler_type> handlers;
if(!dequeue_parcels(locality_id, parcels, handlers))
{
// Give this connection back to the cache as we couldn't dequeue
// parcels.
connection_cache_.reclaim(locality_id, sender_connection);
return;
}
// send parcels if they didn't get sent by another connection
send_pending_parcels(
locality_id,
sender_connection, std::move(parcels),
std::move(handlers));
// We yield here for a short amount of time to give another
// HPX thread the chance to put a subsequent parcel which
// leads to a more effective parcel buffering
// if (hpx::threads::get_self_ptr())
// hpx::this_thread::yield();
}
void send_pending_parcels_trampoline(
boost::system::error_code const& ec,
locality const& locality_id,
std::shared_ptr<connection> sender_connection)
{
HPX_ASSERT(operations_in_flight_ != 0);
--operations_in_flight_;
#if defined(HPX_TRACK_STATE_OF_OUTGOING_TCP_CONNECTION)
sender_connection->set_state(connection::state_scheduled_thread);
#endif
if (!ec)
{
// Give this connection back to the cache as it's not
// needed anymore.
connection_cache_.reclaim(locality_id, sender_connection);
}
else
{
// remove this connection from cache
connection_cache_.clear(locality_id, sender_connection);
}
{
std::lock_guard<lcos::local::spinlock> l(mtx_);
// HPX_ASSERT(locality_id == sender_connection->destination());
pending_parcels_map::iterator it = pending_parcels_.find(locality_id);
if (it == pending_parcels_.end() || util::get<0>(it->second).empty())
return;
}
// Create a new HPX thread which sends parcels that are still
// pending.
get_connection_and_send_parcels(locality_id);
}
void send_pending_parcels(
parcelset::locality const & parcel_locality_id,
std::shared_ptr<connection> sender_connection,
std::vector<parcel>&& parcels,
std::vector<write_handler_type>&& handlers)
{
#if defined(HPX_TRACK_STATE_OF_OUTGOING_TCP_CONNECTION)
sender_connection->set_state(connection::state_send_pending);
#endif
#if defined(HPX_DEBUG)
// verify the connection points to the right destination
// HPX_ASSERT(parcel_locality_id == sender_connection->destination());
sender_connection->verify_(parcel_locality_id);
#endif
// encode the parcels
std::size_t num_parcels = encode_parcels(*this, &parcels[0],
parcels.size(), sender_connection->buffer_,
archive_flags_,
this->get_max_outbound_message_size());
using hpx::parcelset::detail::call_for_each;
if (num_parcels == parcels.size())
{
++operations_in_flight_;
// send all of the parcels
sender_connection->async_write(
call_for_each(std::move(handlers), std::move(parcels)),
util::bind_front(&parcelport_impl::send_pending_parcels_trampoline,
this));
}
else
{
++operations_in_flight_;
HPX_ASSERT(num_parcels < parcels.size());
std::vector<write_handler_type> handled_handlers;
handled_handlers.reserve(num_parcels);
std::move(handlers.begin(), handlers.begin()+num_parcels,
std::back_inserter(handled_handlers));
std::vector<parcel> handled_parcels;
handled_parcels.reserve(num_parcels);
std::move(parcels.begin(), parcels.begin()+num_parcels,
std::back_inserter(handled_parcels));
// send only part of the parcels
sender_connection->async_write(
call_for_each(
std::move(handled_handlers), std::move(handled_parcels)),
util::bind_front(&parcelport_impl::send_pending_parcels_trampoline,
this));
// give back unhandled parcels
parcels.erase(parcels.begin(), parcels.begin()+num_parcels);
handlers.erase(handlers.begin(), handlers.begin()+num_parcels);
enqueue_parcels(parcel_locality_id, std::move(parcels),
std::move(handlers));
}
if(threads::get_self_ptr())
{
// We suspend our thread, which will make progress on the network
hpx::this_thread::suspend(hpx::threads::pending_boost,
"parcelport_impl::send_pending_parcels");
}
}
public:
std::size_t get_next_num_thread()
{
return ++num_thread_ % max_background_thread_;
}
protected:
/// The pool of io_service objects used to perform asynchronous operations.
util::io_service_pool io_service_pool_;
/// The connection cache for sending connections
util::connection_cache<connection, locality> connection_cache_;
typedef hpx::lcos::local::spinlock mutex_type;
int archive_flags_;
hpx::util::atomic_count operations_in_flight_;
std::atomic<std::size_t> num_thread_;
std::size_t const max_background_thread_;
};
}}
#endif
| 36.618219
| 89
| 0.533654
|
alexmyczko
|
6d2465d0efe5b9113ec836f5c9e53fcc61452b23
| 264
|
hpp
|
C++
|
PP/get_reference.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | 3
|
2019-07-12T23:12:24.000Z
|
2019-09-05T07:57:45.000Z
|
PP/get_reference.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | null | null | null |
PP/get_reference.hpp
|
Petkr/PP
|
646cc156603a6a9461e74d8f54786c0d5a9c32d2
|
[
"MIT"
] | null | null | null |
#pragma once
#include <PP/compose.hpp>
#include <PP/decompose_reference.hpp>
#include <PP/partial_.hpp>
#include <PP/tuple/get.hpp>
#include <PP/value_t.hpp>
namespace PP
{
PP_CIA get_reference_value_t =
compose(tuple::get_ * value_1, decompose_reference);
}
| 20.307692
| 56
| 0.753788
|
Petkr
|
6d2a001de6472f9134ae5cbebca6307c4c9ba458
| 3,490
|
hh
|
C++
|
src/kafka/producer/sender.hh
|
avelanarius/seastar
|
d56ec0b618d42b4b9c9dc4839fbd369ae845a94c
|
[
"Apache-2.0"
] | null | null | null |
src/kafka/producer/sender.hh
|
avelanarius/seastar
|
d56ec0b618d42b4b9c9dc4839fbd369ae845a94c
|
[
"Apache-2.0"
] | 7
|
2019-11-19T14:43:39.000Z
|
2019-12-14T19:00:49.000Z
|
src/kafka/producer/sender.hh
|
avelanarius/seastar
|
d56ec0b618d42b4b9c9dc4839fbd369ae845a94c
|
[
"Apache-2.0"
] | null | null | null |
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2019 ScyllaDB Ltd.
*/
#pragma once
#include <string>
#include <vector>
#include <map>
#include <seastar/core/future.hh>
#include "../protocol/metadata_response.hh"
#include "../protocol/produce_response.hh"
#include "../connection/connection_manager.hh"
#include "metadata_manager.hh"
namespace seastar {
namespace kafka {
struct send_exception : public std::runtime_error {
public:
send_exception(const std::string& message) : runtime_error(message) {}
};
struct sender_message {
std::string _key;
std::string _value;
std::string _topic;
int32_t _partition_index;
kafka_error_code_t _error_code;
promise<> _promise;
sender_message() :
_partition_index(0),
_error_code(error::kafka_error_code::UNKNOWN_SERVER_ERROR) {}
sender_message(sender_message&& s) = default;
sender_message& operator=(sender_message&& s) = default;
sender_message(sender_message& s) = delete;
};
class sender {
public:
using connection_id = std::pair<std::string, uint16_t>;
using topic_partition = std::pair<std::string, int32_t>;
private:
lw_shared_ptr<connection_manager> _connection_manager;
lw_shared_ptr<metadata_manager> _metadata_manager;
std::vector<sender_message> _messages;
std::map<connection_id, std::map<std::string, std::map<int32_t, std::vector<sender_message*>>>> _messages_split_by_broker_topic_partition;
std::map<topic_partition, std::vector<sender_message*>> _messages_split_by_topic_partition;
std::vector<future<std::pair<connection_id, produce_response>>> _responses;
uint32_t _connection_timeout;
std::optional<connection_id> broker_for_topic_partition(const std::string& topic, int32_t partition_index);
connection_id broker_for_id(int32_t id);
void set_error_code_for_broker(const connection_id& broker, const error::kafka_error_code& error_code);
void set_error_code_for_topic_partition(const std::string& topic, int32_t partition_index,
const error::kafka_error_code& error_code);
void set_success_for_topic_partition(const std::string& topic, int32_t partition_index);
void split_messages();
void queue_requests();
void set_error_codes_for_responses(std::vector<future<std::pair<connection_id, produce_response>>>& responses);
void filter_messages();
future<> process_messages_errors();
public:
sender(lw_shared_ptr<connection_manager> connection_manager, lw_shared_ptr<metadata_manager> metadata_manager, uint32_t connection_timeout);
void move_messages(std::vector<sender_message>& messages);
size_t messages_size() const;
bool messages_empty() const;
void send_requests();
future<> receive_responses();
void close();
};
}
}
| 32.616822
| 144
| 0.747564
|
avelanarius
|
6d2a0d2b2454d2367f2147651a84a89fc5b9cee8
| 1,073
|
cpp
|
C++
|
aws-cpp-sdk-chime-sdk-identity/source/model/AppInstanceAdminSummary.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-chime-sdk-identity/source/model/AppInstanceAdminSummary.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-chime-sdk-identity/source/model/AppInstanceAdminSummary.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/chime-sdk-identity/model/AppInstanceAdminSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ChimeSDKIdentity
{
namespace Model
{
AppInstanceAdminSummary::AppInstanceAdminSummary() :
m_adminHasBeenSet(false)
{
}
AppInstanceAdminSummary::AppInstanceAdminSummary(JsonView jsonValue) :
m_adminHasBeenSet(false)
{
*this = jsonValue;
}
AppInstanceAdminSummary& AppInstanceAdminSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Admin"))
{
m_admin = jsonValue.GetObject("Admin");
m_adminHasBeenSet = true;
}
return *this;
}
JsonValue AppInstanceAdminSummary::Jsonize() const
{
JsonValue payload;
if(m_adminHasBeenSet)
{
payload.WithObject("Admin", m_admin.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace ChimeSDKIdentity
} // namespace Aws
| 17.883333
| 80
| 0.738117
|
perfectrecall
|
6d3107231683ec5f6d062acf9605124fe7fd3a90
| 3,682
|
cpp
|
C++
|
source/QtWidgets/QDockWidgetSlots.cpp
|
orangesocks/Qt5xHb
|
03aa383d9ae86cdadf7289d846018f8a3382a0e4
|
[
"MIT"
] | 11
|
2017-01-30T14:19:11.000Z
|
2020-05-30T13:39:16.000Z
|
source/QtWidgets/QDockWidgetSlots.cpp
|
orangesocks/Qt5xHb
|
03aa383d9ae86cdadf7289d846018f8a3382a0e4
|
[
"MIT"
] | 1
|
2017-02-24T20:57:32.000Z
|
2018-05-29T13:43:05.000Z
|
source/QtWidgets/QDockWidgetSlots.cpp
|
orangesocks/Qt5xHb
|
03aa383d9ae86cdadf7289d846018f8a3382a0e4
|
[
"MIT"
] | 5
|
2017-01-30T14:19:12.000Z
|
2020-03-28T08:54:56.000Z
|
/*
Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QDockWidgetSlots.h"
QDockWidgetSlots::QDockWidgetSlots( QObject *parent ) : QObject( parent )
{
}
QDockWidgetSlots::~QDockWidgetSlots()
{
}
void QDockWidgetSlots::allowedAreasChanged( Qt::DockWidgetAreas allowedAreas )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "allowedAreasChanged(Qt::DockWidgetAreas)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QDOCKWIDGET" );
PHB_ITEM pallowedAreas = hb_itemPutNI( NULL, (int) allowedAreas );
hb_vmEvalBlockV( cb, 2, psender, pallowedAreas );
hb_itemRelease( psender );
hb_itemRelease( pallowedAreas );
}
}
void QDockWidgetSlots::dockLocationChanged( Qt::DockWidgetArea area )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "dockLocationChanged(Qt::DockWidgetArea)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QDOCKWIDGET" );
PHB_ITEM parea = hb_itemPutNI( NULL, (int) area );
hb_vmEvalBlockV( cb, 2, psender, parea );
hb_itemRelease( psender );
hb_itemRelease( parea );
}
}
void QDockWidgetSlots::featuresChanged( QDockWidget::DockWidgetFeatures features )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "featuresChanged(QDockWidget::DockWidgetFeatures)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QDOCKWIDGET" );
PHB_ITEM pfeatures = hb_itemPutNI( NULL, (int) features );
hb_vmEvalBlockV( cb, 2, psender, pfeatures );
hb_itemRelease( psender );
hb_itemRelease( pfeatures );
}
}
void QDockWidgetSlots::topLevelChanged( bool topLevel )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "topLevelChanged(bool)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QDOCKWIDGET" );
PHB_ITEM ptopLevel = hb_itemPutL( NULL, topLevel );
hb_vmEvalBlockV( cb, 2, psender, ptopLevel );
hb_itemRelease( psender );
hb_itemRelease( ptopLevel );
}
}
void QDockWidgetSlots::visibilityChanged( bool visible )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "visibilityChanged(bool)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QDOCKWIDGET" );
PHB_ITEM pvisible = hb_itemPutL( NULL, visible );
hb_vmEvalBlockV( cb, 2, psender, pvisible );
hb_itemRelease( psender );
hb_itemRelease( pvisible );
}
}
void QDockWidgetSlots_connect_signal( const QString & signal, const QString & slot )
{
QDockWidget * obj = (QDockWidget *) Qt5xHb::itemGetPtrStackSelfItem();
if( obj )
{
QDockWidgetSlots * s = QCoreApplication::instance()->findChild<QDockWidgetSlots *>();
if( s == NULL )
{
s = new QDockWidgetSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt5xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
| 27.274074
| 112
| 0.675177
|
orangesocks
|
6d34945156d4bd4e8bd74aada0659eea2f18e525
| 667
|
cpp
|
C++
|
GFG/C++ BASIC/2 - Flow Control, Function & Loops/greatest_of_three_numbers.cpp
|
IamBikramPurkait/My-CP-Journey
|
bbb7fc533b8bcf79367e3f38f4a04de075b43d64
|
[
"MIT"
] | 1
|
2021-04-24T03:39:50.000Z
|
2021-04-24T03:39:50.000Z
|
GFG/C++ BASIC/2 - Flow Control, Function & Loops/greatest_of_three_numbers.cpp
|
IamBikramPurkait/My-CP-Journey
|
bbb7fc533b8bcf79367e3f38f4a04de075b43d64
|
[
"MIT"
] | null | null | null |
GFG/C++ BASIC/2 - Flow Control, Function & Loops/greatest_of_three_numbers.cpp
|
IamBikramPurkait/My-CP-Journey
|
bbb7fc533b8bcf79367e3f38f4a04de075b43d64
|
[
"MIT"
] | null | null | null |
// { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution
{
public:
int greatestOfThree(int A, int B, int C)
{
// code here
if (A >= B && A >= C)
return A;
else if (B >= C && B >= A)
return B;
else if (C >= A && C >= B)
return C;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int A, B, C;
cin >> A >> B >> C;
Solution ob;
cout << ob.greatestOfThree(A, B, C) << "\n";
}
}
// } Driver Code Ends
| 17.552632
| 52
| 0.461769
|
IamBikramPurkait
|
6d360634015d5508c9e38ee1038f858c75995d50
| 15,342
|
cpp
|
C++
|
plugins/Soccer.cpp
|
cgrebeld/opensteerpy
|
25adfc50bed808d516ab30656d4a86634f70c532
|
[
"MIT"
] | 3
|
2015-02-22T02:27:53.000Z
|
2019-06-25T21:05:31.000Z
|
plugins/Soccer.cpp
|
onedayitwillmake/OpenSteerMirror
|
51a614bb5c62ff7e02514e55a7148cd4d67c67a1
|
[
"Unlicense",
"MIT"
] | null | null | null |
plugins/Soccer.cpp
|
onedayitwillmake/OpenSteerMirror
|
51a614bb5c62ff7e02514e55a7148cd4d67c67a1
|
[
"Unlicense",
"MIT"
] | null | null | null |
// ----------------------------------------------------------------------------
//
//
// 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.
//
//
// ----------------------------------------------------------------------------
//
// Simple soccer game by Michael Holm, IO Interactive A/S
//
// I made this to learn opensteer, and it took me four hours. The players will
// hunt the ball with no team spirit, each player acts on his own accord.
//
// I challenge the reader to change the behavour of one of the teams, to beat my
// team. It should not be too hard. If you make a better team, please share the
// source code so others get the chance to create a team that'll beat yours :)
//
// You are free to use this code for whatever you please.
//
// (contributed on July 9, 2003)
//
// ----------------------------------------------------------------------------
#include <iomanip>
#include <sstream>
#include "OpenSteer/SimpleVehicle.h"
#include "OpenSteer/OpenSteerDemo.h"
#include "OpenSteer/Draw.h"
#include "OpenSteer/Color.h"
#include "OpenSteer/UnusedParameter.h"
namespace {
using namespace OpenSteer;
Vec3 playerPosition[9] = {
Vec3(4,0,0),
Vec3(7,0,-5),
Vec3(7,0,5),
Vec3(10,0,-3),
Vec3(10,0,3),
Vec3(15,0, -8),
Vec3(15,0,0),
Vec3(15,0,8),
Vec3(4,0,0)
};
// ----------------------------------------------------------------------------
// a box object for the field and the goals.
class AABBox{
public:
AABBox(Vec3 &min, Vec3& max): m_min(min), m_max(max){}
AABBox(Vec3 min, Vec3 max): m_min(min), m_max(max){}
bool InsideX(const Vec3 p){if(p.x < m_min.x || p.x > m_max.x) return false;return true;}
bool InsideZ(const Vec3 p){if(p.z < m_min.z || p.z > m_max.z) return false;return true;}
void draw(){
Vec3 b,c;
b = Vec3(m_min.x, 0, m_max.z);
c = Vec3(m_max.x, 0, m_min.z);
Color color(1.0f,1.0f,0.0f);
drawLineAlpha(m_min, b, color, 1.0f);
drawLineAlpha(b, m_max, color, 1.0f);
drawLineAlpha(m_max, c, color, 1.0f);
drawLineAlpha(c,m_min, color, 1.0f);
}
private:
Vec3 m_min;
Vec3 m_max;
};
// The ball object
class Ball : public SimpleVehicle{
public:
Ball(AABBox *bbox) : m_bbox(bbox) {reset();}
// reset state
void reset (void)
{
SimpleVehicle::reset (); // reset the vehicle
setSpeed (0.0f); // speed along Forward direction.
setMaxForce (9.0f); // steering force is clipped to this magnitude
setMaxSpeed (9.0f); // velocity is clipped to this magnitude
setPosition(0,0,0);
clearTrailHistory (); // prevent long streaks due to teleportation
setTrailParameters (100, 6000);
}
// per frame simulation update
void update (const float currentTime, const float elapsedTime)
{
applyBrakingForce(1.5f, elapsedTime);
applySteeringForce(velocity(), elapsedTime);
// are we now outside the field?
if(!m_bbox->InsideX(position()))
{
Vec3 d = velocity();
regenerateOrthonormalBasis(Vec3(-d.x, d.y, d.z));
applySteeringForce(velocity(), elapsedTime);
}
if(!m_bbox->InsideZ(position()))
{
Vec3 d = velocity();
regenerateOrthonormalBasis(Vec3(d.x, d.y, -d.z));
applySteeringForce(velocity(), elapsedTime);
}
recordTrailVertex (currentTime, position());
}
void kick(Vec3 dir, const float elapsedTime){
OPENSTEER_UNUSED_PARAMETER(elapsedTime);
setSpeed(dir.length());
regenerateOrthonormalBasis(dir);
}
// draw this character/vehicle into the scene
void draw (void)
{
drawBasic2dCircularVehicle (*this, Color(0.0f,1.0f,0.0f));
drawTrail ();
}
AABBox *m_bbox;
};
class Player : public SimpleVehicle
{
public:
// constructor
Player (std::vector<Player*> others, std::vector<Player*> allplayers, Ball* ball, bool isTeamA, int id) : m_others(others), m_AllPlayers(allplayers), m_Ball(ball), b_ImTeamA(isTeamA), m_MyID(id) {reset ();}
// reset state
void reset (void)
{
SimpleVehicle::reset (); // reset the vehicle
setSpeed (0.0f); // speed along Forward direction.
setMaxForce (3000.7f); // steering force is clipped to this magnitude
setMaxSpeed (10); // velocity is clipped to this magnitude
// Place me on my part of the field, looking at oponnents goal
setPosition(b_ImTeamA ? frandom01()*20 : -frandom01()*20, 0, (frandom01()-0.5f)*20);
if(m_MyID < 9)
{
if(b_ImTeamA)
setPosition(playerPosition[m_MyID]);
else
setPosition(Vec3(-playerPosition[m_MyID].x, playerPosition[m_MyID].y, playerPosition[m_MyID].z));
}
m_home = position();
clearTrailHistory (); // prevent long streaks due to teleportation
setTrailParameters (10, 60);
}
// per frame simulation update
// (parameter names commented out to prevent compiler warning from "-W")
void update (const float /*currentTime*/, const float elapsedTime)
{
// if I hit the ball, kick it.
const float distToBall = Vec3::distance (position(), m_Ball->position());
const float sumOfRadii = radius() + m_Ball->radius();
if (distToBall < sumOfRadii)
m_Ball->kick((m_Ball->position()-position())*50, elapsedTime);
// otherwise consider avoiding collisions with others
Vec3 collisionAvoidance = steerToAvoidNeighbors(1, (AVGroup&)m_AllPlayers);
if(collisionAvoidance != Vec3::zero)
applySteeringForce (collisionAvoidance, elapsedTime);
else
{
float distHomeToBall = Vec3::distance (m_home, m_Ball->position());
if( distHomeToBall < 12.0f)
{
// go for ball if I'm on the 'right' side of the ball
if( b_ImTeamA ? position().x > m_Ball->position().x : position().x < m_Ball->position().x)
{
Vec3 seekTarget = xxxsteerForSeek(m_Ball->position());
applySteeringForce (seekTarget, elapsedTime);
}
else
{
if( distHomeToBall < 12.0f)
{
float Z = m_Ball->position().z - position().z > 0 ? -1.0f : 1.0f;
Vec3 behindBall = m_Ball->position() + (b_ImTeamA ? Vec3(2.0f,0.0f,Z) : Vec3(-2.0f,0.0f,Z));
Vec3 behindBallForce = xxxsteerForSeek(behindBall);
annotationLine (position(), behindBall , Color(0.0f,1.0f,0.0f));
Vec3 evadeTarget = xxxsteerForFlee(m_Ball->position());
applySteeringForce (behindBallForce*10.0f + evadeTarget, elapsedTime);
}
}
}
else // Go home
{
Vec3 seekTarget = xxxsteerForSeek(m_home);
Vec3 seekHome = xxxsteerForSeek(m_home);
applySteeringForce (seekTarget+seekHome, elapsedTime);
}
}
}
// draw this character/vehicle into the scene
void draw (void)
{
drawBasic2dCircularVehicle (*this, b_ImTeamA ? Color(1.0f,0.0f,0.0f):Color(0.0f,0.0f,1.0f));
drawTrail ();
}
// per-instance reference to its group
const std::vector<Player*> m_others;
const std::vector<Player*> m_AllPlayers;
Ball* m_Ball;
bool b_ImTeamA;
int m_MyID;
Vec3 m_home;
};
// ----------------------------------------------------------------------------
// PlugIn for OpenSteerDemo
class MicTestPlugIn : public PlugIn
{
public:
const char* name (void) {return "Michael's Simple Soccer";}
// float selectionOrderSortKey (void) {return 0.06f;}
// bool requestInitialSelection() { return true;}
// be more "nice" to avoid a compiler warning
virtual ~MicTestPlugIn() {}
void open (void)
{
// Make a field
m_bbox = new AABBox(Vec3(-20,0,-10), Vec3(20,0,10));
// Red goal
m_TeamAGoal = new AABBox(Vec3(-21,0,-7), Vec3(-19,0,7));
// Blue Goal
m_TeamBGoal = new AABBox(Vec3(19,0,-7), Vec3(21,0,7));
// Make a ball
m_Ball = new Ball(m_bbox);
// Build team A
m_PlayerCountA = 8;
for(unsigned int i=0; i < m_PlayerCountA ; i++)
{
Player *pMicTest = new Player(TeamA, m_AllPlayers, m_Ball, true, i);
OpenSteerDemo::selectedVehicle = pMicTest;
TeamA.push_back (pMicTest);
m_AllPlayers.push_back(pMicTest);
}
// Build Team B
m_PlayerCountB = 8;
for(unsigned int i=0; i < m_PlayerCountB ; i++)
{
Player *pMicTest = new Player(TeamB, m_AllPlayers, m_Ball, false, i);
OpenSteerDemo::selectedVehicle = pMicTest;
TeamB.push_back (pMicTest);
m_AllPlayers.push_back(pMicTest);
}
// initialize camera
OpenSteerDemo::init2dCamera (*m_Ball);
OpenSteerDemo::camera.setPosition (10, OpenSteerDemo::camera2dElevation, 10);
OpenSteerDemo::camera.fixedPosition.set (40, 40, 40);
OpenSteerDemo::camera.mode = Camera::cmFixed;
m_redScore = 0;
m_blueScore = 0;
}
void update (const float currentTime, const float elapsedTime)
{
// update simulation of test vehicle
for(unsigned int i=0; i < m_PlayerCountA ; i++)
TeamA[i]->update (currentTime, elapsedTime);
for(unsigned int i=0; i < m_PlayerCountB ; i++)
TeamB[i]->update (currentTime, elapsedTime);
m_Ball->update(currentTime, elapsedTime);
if(m_TeamAGoal->InsideX(m_Ball->position()) && m_TeamAGoal->InsideZ(m_Ball->position()))
{
m_Ball->reset(); // Ball in blue teams goal, red scores
m_redScore++;
}
if(m_TeamBGoal->InsideX(m_Ball->position()) && m_TeamBGoal->InsideZ(m_Ball->position()))
{
m_Ball->reset(); // Ball in red teams goal, blue scores
m_blueScore++;
}
}
void redraw (const float currentTime, const float elapsedTime)
{
// draw test vehicle
for(unsigned int i=0; i < m_PlayerCountA ; i++)
TeamA[i]->draw ();
for(unsigned int i=0; i < m_PlayerCountB ; i++)
TeamB[i]->draw ();
m_Ball->draw();
m_bbox->draw();
m_TeamAGoal->draw();
m_TeamBGoal->draw();
{
std::ostringstream annote;
annote << "Red: "<< m_redScore;
draw2dTextAt3dLocation (annote, Vec3(23,0,0), Color(1.0f,0.7f,0.7f), drawGetWindowWidth(), drawGetWindowHeight());
}
{
std::ostringstream annote;
annote << "Blue: "<< m_blueScore;
draw2dTextAt3dLocation (annote, Vec3(-23,0,0), Color(0.7f,0.7f,1.0f), drawGetWindowWidth(), drawGetWindowHeight());
}
// textual annotation (following the test vehicle's screen position)
if(0)
for(unsigned int i=0; i < m_PlayerCountA ; i++)
{
std::ostringstream annote;
annote << std::setprecision (2) << std::setiosflags (std::ios::fixed);
annote << " speed: " << TeamA[i]->speed() << "ID:" << i << std::ends;
draw2dTextAt3dLocation (annote, TeamA[i]->position(), gRed, drawGetWindowWidth(), drawGetWindowHeight());
draw2dTextAt3dLocation (*"start", Vec3::zero, gGreen, drawGetWindowWidth(), drawGetWindowHeight());
}
// update camera, tracking test vehicle
OpenSteerDemo::updateCamera (currentTime, elapsedTime, *OpenSteerDemo::selectedVehicle);
// draw "ground plane"
OpenSteerDemo::gridUtility (Vec3(0,0,0));
}
void close (void)
{
for(unsigned int i=0; i < m_PlayerCountA ; i++)
delete TeamA[i];
TeamA.clear ();
for(unsigned int i=0; i < m_PlayerCountB ; i++)
delete TeamB[i];
TeamB.clear ();
m_AllPlayers.clear();
}
void reset (void)
{
// reset vehicle
for(unsigned int i=0; i < m_PlayerCountA ; i++)
TeamA[i]->reset ();
for(unsigned int i=0; i < m_PlayerCountB ; i++)
TeamB[i]->reset ();
m_Ball->reset();
}
const AVGroup& allVehicles (void) {return (const AVGroup&) TeamA;}
unsigned int m_PlayerCountA;
unsigned int m_PlayerCountB;
std::vector<Player*> TeamA;
std::vector<Player*> TeamB;
std::vector<Player*> m_AllPlayers;
Ball *m_Ball;
AABBox *m_bbox;
AABBox *m_TeamAGoal;
AABBox *m_TeamBGoal;
int junk;
int m_redScore;
int m_blueScore;
};
MicTestPlugIn pMicTestPlugIn;
// ----------------------------------------------------------------------------
} // anonymous namespace
| 38.069479
| 214
| 0.529396
|
cgrebeld
|
6d36bdd4bf9a0f2e4ee14702f044fb82b7d4506e
| 2,977
|
cpp
|
C++
|
dev/sample/async_handling_with_sobjectizer/main.cpp
|
Lord-Kamina/restinio
|
00133ac4154626ec094697370d2dbe4ce01727f8
|
[
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
dev/sample/async_handling_with_sobjectizer/main.cpp
|
Lord-Kamina/restinio
|
00133ac4154626ec094697370d2dbe4ce01727f8
|
[
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
dev/sample/async_handling_with_sobjectizer/main.cpp
|
Lord-Kamina/restinio
|
00133ac4154626ec094697370d2dbe4ce01727f8
|
[
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
#include <type_traits>
#include <iostream>
#include <chrono>
#include <args.hxx>
#include <restinio/all.hpp>
#include <restinio/so5/so_timer_manager.hpp>
// Application agents.
#include "app.hpp"
//
// app_args_t
//
struct app_args_t
{
bool m_help{ false };
std::uint16_t m_port{ 8080 };
app_args_t( int argc, const char * argv[] )
{
args::ArgumentParser parser( "RESTinio with SObjectizer sample", "" );
args::HelpFlag help( parser, "Help", "Usage example", { 'h', "help" } );
args::ValueFlag< std::uint16_t > server_port(
parser, "port", "tcp port to run server on (default: 8080)",
{ 'p', "port" } );
try
{
parser.ParseCLI( argc, argv );
}
catch( const args::Help & )
{
m_help = true;
std::cout << parser;
}
if( server_port )
m_port = args::get( server_port );
}
};
//
// a_http_server_t
//
// Agent that starts/stops a server.
template < typename TRAITS >
class a_http_server_t : public so_5::agent_t
{
public:
a_http_server_t(
context_t ctx,
restinio::server_settings_t< TRAITS > settings )
: so_5::agent_t{ std::move( ctx ) }
, m_server{
restinio::own_io_context(),
std::move( settings ) }
{}
virtual void so_evt_start() override
{
m_server_thread = std::thread{ [&] {
m_server.open_async(
[]{ /* Ok. */ },
[]( auto ex ) { std::rethrow_exception( ex ); } );
m_server.io_context().run();
} };
}
virtual void so_evt_finish() override
{
m_server.close_async(
[&]{ m_server.io_context().stop(); },
[]( auto ex ) { std::rethrow_exception( ex ); } );
m_server_thread.join();
}
private:
restinio::http_server_t< TRAITS > m_server;
std::thread m_server_thread;
};
void create_main_coop(
const app_args_t & args,
so_5::coop_t & coop )
{
using traits_t =
restinio::traits_t<
restinio::so5::so_timer_manager_t,
restinio::single_threaded_ostream_logger_t >;
restinio::server_settings_t< traits_t > settings{};
settings
.port( args.m_port )
.address( "localhost" )
.timer_manager(
coop.environment(),
coop.make_agent< restinio::so5::a_timeout_handler_t >()->so_direct_mbox() )
.request_handler(
create_request_handler(
// Add application agent to cooperation.
coop.make_agent< a_main_handler_t >()->so_direct_mbox() ) );
coop.make_agent< a_http_server_t< traits_t > >( std::move( settings ) );
}
int main( int argc, char const *argv[] )
{
try
{
const app_args_t args{ argc, argv };
if( args.m_help )
return 0;
so_5::wrapped_env_t sobj{ [&]( auto & env )
{
env.introduce_coop(
[ & ]( so_5::coop_t & coop ) {
create_main_coop( args, coop );
} );
} };
std::string cmd;
do
{
// Wait for quit command.
std::cout << "Type \"quit\" or \"q\" to quit." << std::endl;
std::cin >> cmd;
} while( cmd != "quit" && cmd != "q" );
}
catch( const std::exception & ex )
{
std::cerr << "Error: " << ex.what() << std::endl;
return 1;
}
return 0;
}
| 20.531034
| 78
| 0.62479
|
Lord-Kamina
|
6d37688c8db2a51bbb0af460475a4f8ff2466522
| 67,948
|
cpp
|
C++
|
src/xalanc/XMLSupport/FormatterToHTML.cpp
|
rherardi/xml-xalan-c-src_1_10_0
|
24e6653a617a244e4def60d67b57e70a192a5d4d
|
[
"Apache-2.0"
] | null | null | null |
src/xalanc/XMLSupport/FormatterToHTML.cpp
|
rherardi/xml-xalan-c-src_1_10_0
|
24e6653a617a244e4def60d67b57e70a192a5d4d
|
[
"Apache-2.0"
] | null | null | null |
src/xalanc/XMLSupport/FormatterToHTML.cpp
|
rherardi/xml-xalan-c-src_1_10_0
|
24e6653a617a244e4def60d67b57e70a192a5d4d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 1999-2004 The Apache Software 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.
*/
/**
* @author David N. Bertoni <david_n_bertoni@lotus.com>
*/
// Class header file.
#include "FormatterToHTML.hpp"
#include <cassert>
#include <xercesc/sax/AttributeList.hpp>
#include <xalanc/Include/XalanMemMgrAutoPtr.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/PrefixResolver.hpp>
#include <xalanc/PlatformSupport/Writer.hpp>
#include <xalanc/PlatformSupport/XalanTranscodingServices.hpp>
#include <xalanc/PlatformSupport/XalanUnicode.hpp>
#include <xalanc/PlatformSupport/XalanXMLChar.hpp>
#include <xalanc/DOMSupport/DOMServices.hpp>
XALAN_CPP_NAMESPACE_BEGIN
const XalanDOMString FormatterToHTML::s_emptyString(XalanMemMgrs::getDummyMemMgr());
FormatterToHTML::FormatterToHTML(
Writer& writer,
const XalanDOMString& encoding,
const XalanDOMString& mediaType,
const XalanDOMString& doctypeSystem,
const XalanDOMString& doctypePublic,
bool doIndent,
int indent,
bool escapeURLs,
bool omitMetaTag,
MemoryManagerType& theManager) :
FormatterToXML(
writer,
s_emptyString,
doIndent,
indent,
encoding,
mediaType,
doctypeSystem,
doctypePublic,
false,
s_emptyString,
OUTPUT_METHOD_HTML,
true,
theManager),
m_currentElementName(theManager),
m_inBlockElem(false),
m_isRawStack(theManager),
m_isScriptOrStyleElem(false),
m_inScriptElemStack(theManager),
m_escapeURLs(escapeURLs),
m_isFirstElement(false),
m_isUTF8(XalanTranscodingServices::encodingIsUTF8(m_encoding)),
m_elementLevel(0),
m_hasNamespaceStack(theManager),
m_omitMetaTag(omitMetaTag),
m_elementPropertiesStack(theManager)
{
initCharsMap();
// FormatterToXML may have enabled this property, based on
// the encoding, so we should force it off.
m_shouldWriteXMLHeader = false;
}
FormatterToHTML*
FormatterToHTML::create(
MemoryManagerType& theManager,
Writer& writer,
const XalanDOMString& encoding,
const XalanDOMString& mediaType,
const XalanDOMString& doctypeSystem,
const XalanDOMString& doctypePublic,
bool doIndent,
int indent,
bool escapeURLs,
bool omitMetaTag)
{
typedef FormatterToHTML ThisType;
XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));
ThisType* theResult = theGuard.get();
new (theResult) ThisType(
writer,
encoding,
mediaType,
doctypeSystem,
doctypePublic,
doIndent,
indent,
escapeURLs,
omitMetaTag,
theManager);
theGuard.release();
return theResult;
}
FormatterToHTML::~FormatterToHTML()
{
}
void
FormatterToHTML::initAttrCharsMap()
{
FormatterToXML::initAttrCharsMap();
m_attrCharsMap[XalanUnicode::charLF] = 'S';
// These should _not_ be escaped...
m_attrCharsMap[XalanUnicode::charHTab] = 0;
m_attrCharsMap[XalanUnicode::charLessThanSign] = 0;
m_attrCharsMap[XalanUnicode::charGreaterThanSign] = 0;
for(XalanDOMString::size_type i = 160; i < SPECIALSSIZE; i++)
{
m_attrCharsMap[i] = 'S';
}
}
void
FormatterToHTML::initCharsMap()
{
initAttrCharsMap();
#if defined(XALAN_STRICT_ANSI_HEADERS)
std::memset(m_charsMap, 0, sizeof(m_charsMap));
#else
memset(m_charsMap, 0, sizeof(m_charsMap));
#endif
m_charsMap[XalanUnicode::charLF] = 'S';
m_charsMap[XalanUnicode::charLessThanSign] = 'S';
m_charsMap[XalanUnicode::charGreaterThanSign] = 'S';
m_charsMap[XalanUnicode::charAmpersand] = 'S';
#if defined(XALAN_STRICT_ANSI_HEADERS)
std::memset(m_charsMap, 'S', 10);
#else
memset(m_charsMap, 'S', 10);
#endif
m_charsMap[0x0A] = 'S';
m_charsMap[0x0D] = 'S';
for(int i = 160; i < SPECIALSSIZE; ++i)
{
m_charsMap[i] = 'S';
}
for(int j = m_maxCharacter; j < SPECIALSSIZE; ++j)
{
m_charsMap[j] = 'S';
}
}
void
FormatterToHTML::startDocument()
{
// Clear the buffer, just in case...
clear(m_stringBuffer);
// Reset this, just in case...
m_elementLevel = 0;
m_isFirstElement = true;
m_startNewLine = false;
m_shouldWriteXMLHeader = false;
m_isScriptOrStyleElem = false;
m_isRawStack.clear();
m_inScriptElemStack.push_back(false);
m_hasNamespaceStack.clear();
m_elementPropertiesStack.clear();
const bool isEmptySystem = isEmpty(m_doctypeSystem);
const bool isEmptyPublic = isEmpty(m_doctypePublic);
// Output the header if either the System or Public attributes are
// specified
if(isEmptySystem == false || isEmptyPublic == false)
{
accumContent(s_doctypeHeaderStartString, 0, s_doctypeHeaderStartStringLength);
if(isEmptyPublic == false)
{
accumContent(s_doctypeHeaderPublicString, 0, s_doctypeHeaderPublicStringLength);
accumContent(m_doctypePublic);
accumContent(XalanUnicode::charQuoteMark);
}
if(isEmptySystem == false)
{
if(isEmptyPublic == true)
{
accumContent(s_doctypeHeaderSystemString, 0, s_doctypeHeaderSystemStringLength);
}
accumContent(XalanUnicode::charSpace);
accumContent(XalanUnicode::charQuoteMark);
accumContent(m_doctypeSystem);
accumContent(XalanUnicode::charQuoteMark);
}
accumContent(XalanUnicode::charGreaterThanSign);
outputLineSep();
}
m_needToOutputDocTypeDecl = false;
}
void
FormatterToHTML::endDocument()
{
assert(m_elementLevel == 0);
m_inScriptElemStack.pop_back();
FormatterToXML::endDocument();
}
void
FormatterToHTML::startElement(
const XMLCh* const name,
AttributeListType& attrs)
{
if (pushHasNamespace(name) == true)
{
FormatterToXML::startElement(name, attrs);
}
else
{
writeParentTagEnd();
const XalanHTMLElementsProperties::ElementProperties& elemProperties =
XalanHTMLElementsProperties::find(name);
assert(elemProperties.null() == false);
// Push a copy onto the stack for endElement(). Don't worry --
// the copy is cheap!
m_elementPropertiesStack.push_back(elemProperties);
const bool isBlockElement = elemProperties.is(XalanHTMLElementsProperties::BLOCK);
if (elemProperties.is(XalanHTMLElementsProperties::SCRIPTELEM) == true)
{
m_isScriptOrStyleElem = true;
m_inScriptElemStack.push_back(true);
}
else
{
if (elemProperties.is(XalanHTMLElementsProperties::STYLEELEM) == true)
{
m_isScriptOrStyleElem = true;
}
m_inScriptElemStack.push_back(m_inScriptElemStack.back());
}
// Increment the level...
++m_elementLevel;
if(m_ispreserve == true)
{
m_ispreserve = false;
}
else if(m_doIndent &&
m_elementLevel > 0 && m_isFirstElement == false &&
(m_inBlockElem == false || isBlockElement == true))
{
m_startNewLine = true;
indent(m_currentIndent);
}
m_inBlockElem = !isBlockElement;
m_isRawStack.push_back(elemProperties.is(XalanHTMLElementsProperties::RAW));
accumContent(XalanUnicode::charLessThanSign);
accumName(name);
const unsigned int nAttrs = attrs.getLength();
for (unsigned int i = 0; i < nAttrs ; i++)
{
processAttribute(attrs.getName(i), attrs.getValue(i), elemProperties);
}
// Flag the current element as not yet having any children.
openElementForChildren();
m_currentIndent += m_indent;
m_isprevtext = false;
if (elemProperties.is(XalanHTMLElementsProperties::HEADELEM) == true)
{
writeParentTagEnd();
if (m_omitMetaTag == false)
{
if (m_doIndent)
{
indent(m_currentIndent);
}
accumContent(s_metaString, 0, s_metaStringLength);
accumContent(getEncoding());
accumContent(XalanUnicode::charQuoteMark);
accumContent(XalanUnicode::charGreaterThanSign);
}
}
// We've written the first element, so turn off the flag...
if (m_isFirstElement == true)
{
m_isFirstElement = false;
}
assert(m_elementLevel > 0);
}
}
void
FormatterToHTML::endElement(const XMLCh* const name)
{
if (popHasNamespace() == true)
{
FormatterToXML::endElement(name);
}
else
{
m_currentIndent -= m_indent;
const bool hasChildNodes = childNodesWereAdded();
assert(m_isRawStack.empty() == false);
assert(m_inScriptElemStack.empty() == false);
assert(m_elementPropertiesStack.empty() == false);
m_isRawStack.pop_back();
m_inScriptElemStack.pop_back();
const XalanHTMLElementsProperties::ElementProperties elemProperties =
m_elementPropertiesStack.back();
assert(elemProperties.null() == false);
m_elementPropertiesStack.pop_back();
const bool isBlockElement = elemProperties.is(XalanHTMLElementsProperties::BLOCK);
bool shouldIndent = false;
if(m_ispreserve == true)
{
m_ispreserve = false;
}
else if(m_doIndent == true && (m_inBlockElem == false || isBlockElement == true))
{
m_startNewLine = true;
shouldIndent = true;
}
m_inBlockElem = !isBlockElement;
if (hasChildNodes)
{
if (shouldIndent == true)
{
indent(m_currentIndent);
}
if(elemProperties.is(XalanHTMLElementsProperties::EMPTY) == false)
{
accumContent(XalanUnicode::charLessThanSign);
accumContent(XalanUnicode::charSolidus);
accumName(name);
accumContent(XalanUnicode::charGreaterThanSign);
}
}
else
{
if(elemProperties.is(XalanHTMLElementsProperties::EMPTY) == false)
{
accumContent(XalanUnicode::charGreaterThanSign);
accumContent(XalanUnicode::charLessThanSign);
accumContent(XalanUnicode::charSolidus);
accumName(name);
accumContent(XalanUnicode::charGreaterThanSign);
}
else
{
accumContent(XalanUnicode::charGreaterThanSign);
}
}
if (elemProperties.is(XalanHTMLElementsProperties::WHITESPACESENSITIVE) == true)
{
m_ispreserve = true;
}
if (hasChildNodes == true)
{
if (m_preserves.empty() == false)
{
m_preserves.pop_back();
}
}
m_isprevtext = false;
// Decrement the level...
--m_elementLevel;
}
}
void
FormatterToHTML::characters(
const XMLCh* const chars,
const unsigned int length)
{
if(length != 0)
{
if(m_inCData == true)
{
cdata(chars, length);
}
else if(m_nextIsRaw)
{
m_nextIsRaw = false;
charactersRaw(chars, length);
}
else if (m_inScriptElemStack.back() == true)
{
charactersRaw(chars, length);
}
else if (m_isRawStack.empty() == false &&
m_isRawStack.back() == true)
{
writeParentTagEnd();
m_ispreserve = true;
if (shouldIndent() == true)
{
indent(m_currentIndent);
}
writeNormalizedChars(chars, 0, length, false);
}
else
{
writeParentTagEnd();
m_ispreserve = true;
writeCharacters(chars, length);
}
}
if (m_isprevtext == false)
{
m_isprevtext = true;
}
}
bool
FormatterToHTML::accumDefaultEntity(
XalanDOMChar ch,
bool escLF)
{
assert(ch != 0);
if(FormatterToXML::accumDefaultEntity(ch, escLF) == true)
{
return true;
}
else
{
// Find the entity, if any...
const Entity* theFirst = s_entities;
const Entity* theLast = s_lastEntity;
while(theFirst <= theLast)
{
const Entity* const theCurrent = theFirst + (theLast - theFirst) / 2;
assert(theCurrent->m_char != 0);
if (ch < theCurrent->m_char)
{
theLast = theCurrent - 1;
}
else if (ch > theCurrent->m_char)
{
theFirst = theCurrent + 1;
}
else
{
assert(length(theCurrent->m_string) == theCurrent->m_length);
copyEntityIntoBuffer(theCurrent->m_string, theCurrent->m_length);
return true;
}
}
return false;
}
}
void
FormatterToHTML::entityReference(const XMLCh* const name)
{
accumContent(XalanUnicode::charAmpersand);
accumName(name);
accumContent(XalanUnicode::charSemicolon);
}
void
FormatterToHTML::cdata(
const XMLCh* const ch,
const unsigned int length)
{
if(m_isScriptOrStyleElem == true)
{
writeParentTagEnd();
m_ispreserve = true;
if (shouldIndent() == true)
{
indent(m_currentIndent);
}
writeNormalizedChars(ch, 0, length, true);
}
else if(m_stripCData == true)
{
writeParentTagEnd();
m_ispreserve = true;
if (shouldIndent() == true)
{
indent(m_currentIndent);
}
accumContent(ch, 0, length);
}
else
{
FormatterToXML::cdata(ch, length);
}
}
void
FormatterToHTML::processingInstruction(
const XMLCh* const target,
const XMLCh* const data)
{
const XalanDOMString::size_type dataLength = length(data);
// Use a fairly nasty hack to tell if the next node is supposed to be
// unescaped text.
if(equals(target, length(target), s_piTarget, s_piTargetLength) == true &&
equals(data, dataLength, s_piData, s_piDataLength) == true)
{
m_nextIsRaw = true;
}
else
{
writeParentTagEnd();
if (shouldIndent() == true)
{
indent(m_currentIndent);
}
accumContent(XalanUnicode::charLessThanSign);
accumContent(XalanUnicode::charQuestionMark);
accumName(target);
if (length(data) > 0)
{
if(isXMLWhitespace(data[0]) == false)
{
accumContent(XalanUnicode::charSpace);
}
writeCharacters(data, dataLength);
}
accumContent(XalanUnicode::charGreaterThanSign); // different from XML
// If outside of an element, then put in a new line. This whitespace
// is not significant.
if (m_elementLevel == 0)
{
outputLineSep();
}
m_startNewLine = true;
}
}
void
FormatterToHTML::writeCharacters(const XalanDOMString& theString)
{
writeCharacters(toCharArray(theString), length(theString));
}
void
FormatterToHTML::writeCharacters(
const XalanDOMChar* theString,
XalanDOMString::size_type theLength)
{
assert(theString != 0);
XalanDOMString::size_type i = 0;
XalanDOMString::size_type firstIndex = 0;
while(i < theLength)
{
const XalanDOMChar ch = theString[i];
if(ch < SPECIALSSIZE && m_charsMap[ch] != 'S')
{
++i;
}
else if (XalanUnicode::charLF == ch) // sta this can be removed?
{
accumContent(theString, firstIndex, i - firstIndex);
outputLineSep();
++i;
firstIndex = i;
}
else
{
accumContent(theString, firstIndex, i - firstIndex);
if (accumDefaultEntity(ch, true) == false)
{
if (m_isUTF8 == true && 0xd800 <= ch && ch < 0xdc00)
{
// UTF-16 surrogate
XalanDOMChar next = 0;
if (i + 1 >= theLength)
{
throwInvalidUTF16SurrogateException(ch, getMemoryManager());
}
else
{
next = theString[++i];
if (!(0xdc00 <= next && next < 0xe000))
{
throwInvalidUTF16SurrogateException(ch, next, getMemoryManager());
}
next = XalanDOMChar(((ch - 0xd800) << 10) + next - 0xdc00 + 0x00010000);
}
writeNumberedEntityReference(next);
}
else if(ch >= 0x007Fu && ch <= m_maxCharacter)
{
// Hope this is right...
accumContent(ch);
}
else
{
writeNumberedEntityReference(ch);
}
}
++i;
firstIndex = i;
}
}
accumContent(theString, firstIndex, theLength - firstIndex);
}
void
FormatterToHTML::writeAttrString(
const XalanDOMChar* theString,
XalanDOMString::size_type theStringLength)
{
assert(theString != 0);
XalanDOMString::size_type i = 0;
XalanDOMString::size_type firstIndex = 0;
while(i < theStringLength)
{
const XalanDOMChar ch = theString[i];
if(ch < SPECIALSSIZE && m_attrCharsMap[ch] != 'S')
{
++i;
}
else if(XalanUnicode::charAmpersand == ch &&
i + 1 < theStringLength &&
XalanUnicode::charLeftCurlyBracket == theString[i + 1])
{
++i;
}
else
{
accumContent(theString, firstIndex, i - firstIndex);
if (accumDefaultEntity(ch, true) == false)
{
if (0xd800 <= ch && ch < 0xdc00)
{
// UTF-16 surrogate
XalanDOMChar next = 0;
if (i + 1 >= theStringLength)
{
throwInvalidUTF16SurrogateException(ch, getMemoryManager());
}
else
{
next = theString[++i];
if (!(0xdc00 <= next && next < 0xe000))
{
throwInvalidUTF16SurrogateException(ch, next, getMemoryManager());
}
next = XalanDOMChar(((ch - 0xd800) << 10) + next -0xdc00 + 0x00010000);
}
accumContent(XalanUnicode::charAmpersand);
accumContent(XalanUnicode::charNumberSign);
accumContent(UnsignedLongToDOMString(next, m_stringBuffer));
clear(m_stringBuffer);
accumContent(XalanUnicode::charSemicolon);
}
else
{
writeNumberedEntityReference(ch);
}
}
++i;
firstIndex = i;
}
}
accumContent(theString, firstIndex, theStringLength - firstIndex);
}
void
FormatterToHTML::accumCommentData(const XalanDOMChar* data)
{
accumName(data);
}
void
FormatterToHTML::copyEntityIntoBuffer(
const XalanDOMChar* s,
XalanDOMString::size_type theLength)
{
assert(s != 0);
accumName(XalanUnicode::charAmpersand);
accumName(s, 0, theLength);
accumName(XalanUnicode::charSemicolon);
}
void
FormatterToHTML::copyEntityIntoBuffer(const XalanDOMString& s)
{
accumName(XalanUnicode::charAmpersand);
accumName(s);
accumName(XalanUnicode::charSemicolon);
}
void
FormatterToHTML::processAttribute(
const XalanDOMChar* name,
const XalanDOMChar* value,
const XalanHTMLElementsProperties::ElementProperties& elemProperties)
{
const XalanDOMString::size_type nameLength = length(name);
accumContent(XalanUnicode::charSpace);
const XalanDOMString::size_type valueLength = length(value);
if((valueLength == 0 || equalsIgnoreCaseASCII(name, nameLength, value, valueLength)) &&
elemProperties.isAttribute(name, XalanHTMLElementsProperties::ATTREMPTY) == true)
{
accumName(name);
}
else
{
accumName(name, 0, nameLength);
accumContent(XalanUnicode::charEqualsSign);
accumContent(XalanUnicode::charQuoteMark);
if(elemProperties.isAttribute(name, XalanHTMLElementsProperties::ATTRURL) == true)
{
writeAttrURI(value, valueLength);
}
else
{
writeAttrString(value, valueLength);
}
accumContent(XalanUnicode::charQuoteMark);
}
}
void
FormatterToHTML::writeAttrURI(
const XalanDOMChar* theString,
XalanDOMString::size_type theStringLength)
{
assert(theString != 0);
// http://www.ietf.org/rfc/rfc2396.txt says:
// A URI is always in an "escaped" form, since escaping or unescaping a
// completed URI might change its semantics. Normally, the only time
// escape encodings can safely be made is when the URI is being created
// from its component parts; each component may have its own set of
// characters that are reserved, so only the mechanism responsible for
// generating or interpreting that component can determine whether or
// not escaping a character will change its semantics. Likewise, a URI
// must be separated into its components before the escaped characters
// within those components can be safely decoded.
//
// ...So we do our best to do limited escaping of the URL, without
// causing damage. If the URL is already properly escaped, in theory, this
// function should not change the string value.
for (XalanDOMString::size_type i = 0; i < theStringLength; ++i)
{
const XalanDOMChar ch = theString[i];
if (ch < 33 || ch > 126)
{
if (m_escapeURLs == true)
{
// For the gory details of encoding these characters as
// UTF-8 hex, see:
//
// Unicode, A Primer, by Tony Graham, p. 92.
//
if (ch == XalanUnicode::charSpace)
{
accumContent(ch);
}
else if(ch <= 0x7F)
{
accumHexNumber(ch);
}
else if(ch <= 0x7FF)
{
const XalanDOMChar highByte = XalanDOMChar((ch >> 6) | 0xC0);
const XalanDOMChar lowByte = XalanDOMChar((ch & 0x3F) | 0x80);
accumHexNumber(highByte);
accumHexNumber(lowByte);
}
else if(isUTF16Surrogate(ch) == true) // high surrogate
{
// I'm sure this can be done in 3 instructions, but I choose
// to try and do it exactly like it is done in the book, at least
// until we are sure this is totally clean. I don't think performance
// is a big issue with this particular function, though I could be
// wrong. Also, the stuff below clearly does more masking than
// it needs to do.
// Clear high 6 bits.
const XalanDOMChar highSurrogate = XalanDOMChar(ch & 0x03FF);
// Middle 4 bits (wwww) + 1
// "Note that the value of wwww from the high surrogate bit pattern
// is incremented to make the uuuuu bit pattern in the scalar value
// so the surrogate pair don't address the BMP."
const XalanDOMChar wwww = XalanDOMChar((highSurrogate & 0x03C0) >> 6);
const XalanDOMChar uuuuu = XalanDOMChar(wwww + 1);
// next 4 bits
const XalanDOMChar zzzz = XalanDOMChar((highSurrogate & 0x003C) >> 2);
// low 2 bits
const XalanDOMChar temp = XalanDOMChar(((highSurrogate & 0x0003) << 4) & 0x30);
// Get low surrogate character.
const XalanDOMChar nextChar = theString[++i];
// Clear high 6 bits.
const XalanDOMChar lowSurrogate = XalanDOMChar(nextChar & 0x03FF);
// put the middle 4 bits into the bottom of yyyyyy (byte 3)
const XalanDOMChar yyyyyy = XalanDOMChar(temp | ((lowSurrogate & 0x03C0) >> 6));
// bottom 6 bits.
const XalanDOMChar xxxxxx = XalanDOMChar(lowSurrogate & 0x003F);
const XalanDOMChar byte1 = XalanDOMChar(0xF0 | (uuuuu >> 2)); // top 3 bits of uuuuu
const XalanDOMChar byte2 = XalanDOMChar(0x80 | (((uuuuu & 0x03) << 4) & 0x30) | zzzz);
const XalanDOMChar byte3 = XalanDOMChar(0x80 | yyyyyy);
const XalanDOMChar byte4 = XalanDOMChar(0x80 | xxxxxx);
accumHexNumber(byte1);
accumHexNumber(byte2);
accumHexNumber(byte3);
accumHexNumber(byte4);
}
else
{
const XalanDOMChar highByte = XalanDOMChar((ch >> 12) | 0xE0);
const XalanDOMChar middleByte = XalanDOMChar(((ch & 0x0FC0) >> 6) | 0x80);
const XalanDOMChar lowByte = XalanDOMChar((ch & 0x3F) | 0x80);
accumHexNumber(highByte);
accumHexNumber(middleByte);
accumHexNumber(lowByte);
}
}
else if (ch < m_maxCharacter)
{
accumContent(ch);
}
else
{
accumContent(XalanUnicode::charAmpersand);
accumContent(XalanUnicode::charNumberSign);
accumContent(UnsignedLongToDOMString(ch, m_stringBuffer));
clear(m_stringBuffer);
accumContent(XalanUnicode::charSemicolon);
}
}
// Since http://www.ietf.org/rfc/rfc2396.txt refers to the URI grammar as
// not allowing quotes in the URI proper syntax, nor in the fragment
// identifier, we believe that double quotes should be escaped.
else if (ch == XalanUnicode::charQuoteMark)
{
if (m_escapeURLs == true)
{
accumContent(XalanUnicode::charPercentSign);
accumContent(XalanUnicode::charDigit_2);
accumContent(XalanUnicode::charDigit_2);
}
else
{
accumDefaultEntity(ch, true);
}
}
else if (ch == XalanUnicode::charAmpersand)
{
accumDefaultEntity(ch, true);
}
else
{
accumContent(ch);
}
}
}
void
FormatterToHTML::accumHexNumber(XalanDOMChar theChar)
{
accumContent(XalanUnicode::charPercentSign);
assert(length(m_stringBuffer) == 0);
UnsignedLongToHexDOMString(theChar, m_stringBuffer);
if (length(m_stringBuffer) == 1)
{
accumContent(XalanUnicode::charDigit_0);
}
accumContent(m_stringBuffer);
clear(m_stringBuffer);
}
bool
FormatterToHTML::popHasNamespace()
{
if (m_hasNamespaceStack.empty() == true)
{
return false;
}
else
{
const bool theValue = m_hasNamespaceStack.back();
m_hasNamespaceStack.pop_back();
return theValue;
}
}
bool
FormatterToHTML::pushHasNamespace(const XalanDOMChar* theElementName)
{
bool fHasNamespace = false;
if (m_prefixResolver != 0)
{
const XalanDOMString::size_type theLength = length(theElementName);
const XalanDOMString::size_type theColonIndex = indexOf(theElementName, XalanUnicode::charColon);
const XalanDOMString* thePrefix = &s_emptyString;
if (theColonIndex < theLength)
{
substring(theElementName, m_stringBuffer, 0, theColonIndex);
thePrefix = &m_stringBuffer;
}
assert(thePrefix != 0);
// Check for the namespace...
const XalanDOMString* const theNamespace =
m_prefixResolver->getNamespaceForPrefix(*thePrefix);
if (theNamespace != 0 && length(*theNamespace) != 0)
{
m_hasNamespaceStack.push_back(true);
fHasNamespace = true;
}
clear(m_stringBuffer);
}
return fHasNamespace;
}
// Some of these are now commented out to match Xalan-J, which claims that Netscape cannot handle many of these entities.
const FormatterToHTML::Entity FormatterToHTML::s_entities[] =
{
// These must always be in order by the character.
// Otherwise, the binary search for them will fail.
{ 160, 4, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_b, XalanUnicode::charLetter_s, XalanUnicode::charLetter_p, 0 } },
{ 161, 5, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_e, XalanUnicode::charLetter_x, XalanUnicode::charLetter_c, XalanUnicode::charLetter_l, 0 } },
{ 162, 4, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_e, XalanUnicode::charLetter_n, XalanUnicode::charLetter_t, 0 } },
{ 163, 5, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_o, XalanUnicode::charLetter_u, XalanUnicode::charLetter_n, XalanUnicode::charLetter_d, 0 } },
{ 164, 6, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, XalanUnicode::charLetter_e, XalanUnicode::charLetter_n, 0 } },
{ 165, 3, { XalanUnicode::charLetter_y, XalanUnicode::charLetter_e, XalanUnicode::charLetter_n, 0 } },
{ 166, 6, { XalanUnicode::charLetter_b, XalanUnicode::charLetter_r, XalanUnicode::charLetter_v, XalanUnicode::charLetter_b, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, 0 } },
{ 167, 4, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_e, XalanUnicode::charLetter_c, XalanUnicode::charLetter_t, 0 } },
{ 168, 3, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 169, 4, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_o, XalanUnicode::charLetter_p, XalanUnicode::charLetter_y, 0 } },
{ 170, 4, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_d, XalanUnicode::charLetter_f, 0 } },
{ 171, 5, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_a, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 172, 3, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, 0 } },
{ 173, 3, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_h, XalanUnicode::charLetter_y, 0 } },
{ 174, 3, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_e, XalanUnicode::charLetter_g, 0 } },
{ 175, 4, { XalanUnicode::charLetter_m, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_r, 0 } },
{ 176, 3, { XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, XalanUnicode::charLetter_g, 0 } },
{ 177, 6, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_l, XalanUnicode::charLetter_u, XalanUnicode::charLetter_s, XalanUnicode::charLetter_m, XalanUnicode::charLetter_n, 0 } },
{ 178, 4, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, XalanUnicode::charDigit_2, 0 } },
{ 179, 4, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, XalanUnicode::charDigit_3, 0 } },
{ 180, 5, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 181, 5, { XalanUnicode::charLetter_m, XalanUnicode::charLetter_i, XalanUnicode::charLetter_c, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, 0 } },
{ 182, 4, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, 0 } },
{ 183, 6, { XalanUnicode::charLetter_m, XalanUnicode::charLetter_i, XalanUnicode::charLetter_d, XalanUnicode::charLetter_d, XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, 0 } },
{ 184, 5, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_e, XalanUnicode::charLetter_d, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, 0 } },
{ 185, 4, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, XalanUnicode::charDigit_1, 0 } },
{ 186, 4, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_d, XalanUnicode::charLetter_m, 0 } },
{ 187, 5, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 188, 6, { XalanUnicode::charLetter_f, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charDigit_1, XalanUnicode::charDigit_4, 0 } },
{ 189, 6, { XalanUnicode::charLetter_f, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charDigit_1, XalanUnicode::charDigit_2, 0 } },
{ 190, 6, { XalanUnicode::charLetter_f, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charDigit_3, XalanUnicode::charDigit_4, 0 } },
{ 191, 6, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, XalanUnicode::charLetter_t, 0 } },
{ 192, 6, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 193, 6, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 194, 5, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 195, 6, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 196, 4, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 197, 5, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_r, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, XalanUnicode::charLetter_g, 0 } },
{ 198, 5, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_E, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, 0 } },
{ 199, 6, { XalanUnicode::charLetter_C, XalanUnicode::charLetter_c, XalanUnicode::charLetter_e, XalanUnicode::charLetter_d, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, 0 } },
{ 200, 6, { XalanUnicode::charLetter_E, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 201, 6, { XalanUnicode::charLetter_E, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 202, 5, { XalanUnicode::charLetter_E, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 203, 4, { XalanUnicode::charLetter_E, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 204, 6, { XalanUnicode::charLetter_I, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 205, 6, { XalanUnicode::charLetter_I, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 206, 5, { XalanUnicode::charLetter_I, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 207, 4, { XalanUnicode::charLetter_I, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 208, 3, { XalanUnicode::charLetter_E, XalanUnicode::charLetter_T, XalanUnicode::charLetter_H, 0 } },
{ 209, 6, { XalanUnicode::charLetter_N, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 210, 6, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 211, 6, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 212, 5, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 213, 6, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 214, 4, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 215, 5, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, 0 } },
{ 216, 6, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_s, XalanUnicode::charLetter_l, XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_h, 0 } },
{ 217, 6, { XalanUnicode::charLetter_U, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 218, 6, { XalanUnicode::charLetter_U, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 219, 5, { XalanUnicode::charLetter_U, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 220, 4, { XalanUnicode::charLetter_U, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 221, 6, { XalanUnicode::charLetter_Y, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 222, 5, { XalanUnicode::charLetter_T, XalanUnicode::charLetter_H, XalanUnicode::charLetter_O, XalanUnicode::charLetter_R, XalanUnicode::charLetter_N, 0 } },
{ 223, 5, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_z, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, 0 } },
{ 224, 6, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 225, 6, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 226, 5, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 227, 6, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 228, 4, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 229, 5, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, XalanUnicode::charLetter_g, 0 } },
{ 230, 5, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_e, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, 0 } },
{ 231, 6, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_c, XalanUnicode::charLetter_e, XalanUnicode::charLetter_d, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, 0 } },
{ 232, 6, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 233, 6, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 234, 5, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 235, 4, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 236, 6, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 237, 6, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 238, 5, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 239, 4, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 240, 3, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_h, 0 } },
{ 241, 6, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 242, 6, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 243, 6, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 244, 5, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 245, 6, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 246, 4, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 247, 6, { XalanUnicode::charLetter_d, XalanUnicode::charLetter_i, XalanUnicode::charLetter_v, XalanUnicode::charLetter_i, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 248, 6, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_s, XalanUnicode::charLetter_l, XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_h, 0 } },
{ 249, 6, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_g, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_v, XalanUnicode::charLetter_e, 0 } },
{ 250, 6, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 251, 5, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 252, 4, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 253, 6, { XalanUnicode::charLetter_y, XalanUnicode::charLetter_a, XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, 0 } },
{ 254, 5, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_h, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_n, 0 } },
{ 255, 4, { XalanUnicode::charLetter_y, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
{ 338, 5, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_E, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, 0 } },
{ 339, 5, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_e, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, 0 } },
{ 352, 6, { XalanUnicode::charLetter_S, XalanUnicode::charLetter_c, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 353, 6, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_c, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 376, 4, { XalanUnicode::charLetter_Y, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, XalanUnicode::charLetter_l, 0 } },
#if 0
{ 402, 4, { XalanUnicode::charLetter_f, XalanUnicode::charLetter_n, XalanUnicode::charLetter_o, XalanUnicode::charLetter_f, 0 } },
#endif
{ 710, 4, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_i, XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, 0 } },
{ 732, 5, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
#if 0
{ 913, 5, { XalanUnicode::charLetter_A, XalanUnicode::charLetter_l, XalanUnicode::charLetter_p, XalanUnicode::charLetter_h, XalanUnicode::charLetter_a, 0 } },
{ 914, 4, { XalanUnicode::charLetter_B, XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 915, 5, { XalanUnicode::charLetter_G, XalanUnicode::charLetter_a, XalanUnicode::charLetter_m, XalanUnicode::charLetter_m, XalanUnicode::charLetter_a, 0 } },
{ 916, 5, { XalanUnicode::charLetter_D, XalanUnicode::charLetter_e, XalanUnicode::charLetter_l, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 917, 7, { XalanUnicode::charLetter_E, XalanUnicode::charLetter_p, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 918, 4, { XalanUnicode::charLetter_Z, XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 919, 3, { XalanUnicode::charLetter_E, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 920, 5, { XalanUnicode::charLetter_T, XalanUnicode::charLetter_h, XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 921, 4, { XalanUnicode::charLetter_I, XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 922, 5, { XalanUnicode::charLetter_K, XalanUnicode::charLetter_a, XalanUnicode::charLetter_p, XalanUnicode::charLetter_p, XalanUnicode::charLetter_a, 0 } },
{ 923, 6, { XalanUnicode::charLetter_L, XalanUnicode::charLetter_a, XalanUnicode::charLetter_m, XalanUnicode::charLetter_b, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, 0 } },
{ 924, 2, { XalanUnicode::charLetter_M, XalanUnicode::charLetter_u, 0 } },
{ 925, 2, { XalanUnicode::charLetter_N, XalanUnicode::charLetter_u, 0 } },
{ 926, 2, { XalanUnicode::charLetter_X, XalanUnicode::charLetter_i, 0 } },
{ 927, 7, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_m, XalanUnicode::charLetter_i, XalanUnicode::charLetter_c, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 928, 2, { XalanUnicode::charLetter_P, XalanUnicode::charLetter_i, 0 } },
{ 929, 3, { XalanUnicode::charLetter_R, XalanUnicode::charLetter_h, XalanUnicode::charLetter_o, 0 } },
{ 931, 5, { XalanUnicode::charLetter_S, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, XalanUnicode::charLetter_m, XalanUnicode::charLetter_a, 0 } },
{ 932, 3, { XalanUnicode::charLetter_T, XalanUnicode::charLetter_a, XalanUnicode::charLetter_u, 0 } },
{ 933, 7, { XalanUnicode::charLetter_U, XalanUnicode::charLetter_p, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 934, 3, { XalanUnicode::charLetter_P, XalanUnicode::charLetter_h, XalanUnicode::charLetter_i, 0 } },
{ 935, 3, { XalanUnicode::charLetter_C, XalanUnicode::charLetter_h, XalanUnicode::charLetter_i, 0 } },
{ 936, 3, { XalanUnicode::charLetter_P, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, 0 } },
{ 937, 5, { XalanUnicode::charLetter_O, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, XalanUnicode::charLetter_g, XalanUnicode::charLetter_a, 0 } },
{ 945, 5, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_l, XalanUnicode::charLetter_p, XalanUnicode::charLetter_h, XalanUnicode::charLetter_a, 0 } },
{ 946, 4, { XalanUnicode::charLetter_b, XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 947, 5, { XalanUnicode::charLetter_g, XalanUnicode::charLetter_a, XalanUnicode::charLetter_m, XalanUnicode::charLetter_m, XalanUnicode::charLetter_a, 0 } },
{ 948, 5, { XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, XalanUnicode::charLetter_l, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 949, 7, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_p, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 950, 4, { XalanUnicode::charLetter_z, XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 951, 3, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 952, 5, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_h, XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 953, 4, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, 0 } },
{ 954, 5, { XalanUnicode::charLetter_k, XalanUnicode::charLetter_a, XalanUnicode::charLetter_p, XalanUnicode::charLetter_p, XalanUnicode::charLetter_a, 0 } },
{ 955, 6, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_a, XalanUnicode::charLetter_m, XalanUnicode::charLetter_b, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, 0 } },
{ 956, 2, { XalanUnicode::charLetter_m, XalanUnicode::charLetter_u, 0 } },
{ 957, 2, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_u, 0 } },
{ 958, 2, { XalanUnicode::charLetter_x, XalanUnicode::charLetter_i, 0 } },
{ 959, 7, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_m, XalanUnicode::charLetter_i, XalanUnicode::charLetter_c, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 960, 2, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_i, 0 } },
{ 961, 3, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_h, XalanUnicode::charLetter_o, 0 } },
{ 962, 6, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, XalanUnicode::charLetter_m, XalanUnicode::charLetter_a, XalanUnicode::charLetter_f, 0 } },
{ 963, 5, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_g, XalanUnicode::charLetter_m, XalanUnicode::charLetter_a, 0 } },
{ 964, 3, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, XalanUnicode::charLetter_u, 0 } },
{ 965, 7, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, 0 } },
{ 966, 3, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_h, XalanUnicode::charLetter_i, 0 } },
{ 967, 3, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_h, XalanUnicode::charLetter_i, 0 } },
{ 968, 3, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, 0 } },
{ 969, 5, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, XalanUnicode::charLetter_g, XalanUnicode::charLetter_a, 0 } },
{ 977, 8, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_h, XalanUnicode::charLetter_e, XalanUnicode::charLetter_t, XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_y, XalanUnicode::charLetter_m, 0 } },
{ 978, 5, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_h, 0 } },
{ 982, 3, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_i, XalanUnicode::charLetter_v, 0 } },
#endif
{ 8194, 4, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_n, XalanUnicode::charLetter_s, XalanUnicode::charLetter_p, 0 } },
{ 8195, 4, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_m, XalanUnicode::charLetter_s, XalanUnicode::charLetter_p, 0 } },
{ 8201, 6, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_h, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, XalanUnicode::charLetter_s, XalanUnicode::charLetter_p, 0 } },
{ 8204, 4, { XalanUnicode::charLetter_z, XalanUnicode::charLetter_w, XalanUnicode::charLetter_n, XalanUnicode::charLetter_j, 0 } },
{ 8205, 3, { XalanUnicode::charLetter_z, XalanUnicode::charLetter_w, XalanUnicode::charLetter_j, 0 } },
{ 8206, 3, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_r, XalanUnicode::charLetter_m, 0 } },
{ 8207, 3, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_l, XalanUnicode::charLetter_m, 0 } },
{ 8211, 5, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_h, 0 } },
{ 8212, 5, { XalanUnicode::charLetter_m, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_h, 0 } },
{ 8216, 5, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_s, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8217, 5, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_s, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8218, 5, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_b, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8220, 5, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_d, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8221, 5, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_d, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8222, 5, { XalanUnicode::charLetter_b, XalanUnicode::charLetter_d, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8224, 6, { XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_g, XalanUnicode::charLetter_g, XalanUnicode::charLetter_e, XalanUnicode::charLetter_r, 0 } },
{ 8225, 6, { XalanUnicode::charLetter_D, XalanUnicode::charLetter_a, XalanUnicode::charLetter_g, XalanUnicode::charLetter_g, XalanUnicode::charLetter_e, XalanUnicode::charLetter_r, 0 } },
{ 8226, 4, { XalanUnicode::charLetter_b, XalanUnicode::charLetter_u, XalanUnicode::charLetter_l, XalanUnicode::charLetter_l, 0 } },
{ 8230, 6, { XalanUnicode::charLetter_h, XalanUnicode::charLetter_e, XalanUnicode::charLetter_l, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_p, 0 } },
{ 8240, 6, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_e, XalanUnicode::charLetter_r, XalanUnicode::charLetter_m, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, 0 } },
{ 8242, 5, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_r, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, 0 } },
{ 8243, 5, { XalanUnicode::charLetter_P, XalanUnicode::charLetter_r, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, 0 } },
{ 8249, 6, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_s, XalanUnicode::charLetter_a, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8250, 6, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_s, XalanUnicode::charLetter_a, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_o, 0 } },
{ 8254, 5, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_l, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, XalanUnicode::charLetter_e, 0 } },
{ 8260, 5, { XalanUnicode::charLetter_f, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_l, 0 } },
{ 8364, 4, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_u, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, 0 } },
{ 8465, 5, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_a, XalanUnicode::charLetter_g, XalanUnicode::charLetter_e, 0 } },
{ 8472, 6, { XalanUnicode::charLetter_w, XalanUnicode::charLetter_e, XalanUnicode::charLetter_i, XalanUnicode::charLetter_e, XalanUnicode::charLetter_r, XalanUnicode::charLetter_p, 0 } },
{ 8476, 4, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_e, XalanUnicode::charLetter_a, XalanUnicode::charLetter_l, 0 } },
{ 8482, 5, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, 0 } },
{ 8501, 7, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_l, XalanUnicode::charLetter_e, XalanUnicode::charLetter_f, XalanUnicode::charLetter_s, XalanUnicode::charLetter_y, XalanUnicode::charLetter_m, 0 } },
{ 8592, 4, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8593, 4, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8594, 4, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8595, 4, { XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8596, 4, { XalanUnicode::charLetter_h, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8629, 5, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8656, 4, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_A, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8657, 4, { XalanUnicode::charLetter_u, XalanUnicode::charLetter_A, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8658, 4, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_A, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8659, 4, { XalanUnicode::charLetter_d, XalanUnicode::charLetter_A, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8660, 4, { XalanUnicode::charLetter_h, XalanUnicode::charLetter_A, XalanUnicode::charLetter_r, XalanUnicode::charLetter_r, 0 } },
{ 8704, 6, { XalanUnicode::charLetter_f, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_l, XalanUnicode::charLetter_l, 0 } },
{ 8706, 4, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_t, 0 } },
{ 8707, 5, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_x, XalanUnicode::charLetter_i, XalanUnicode::charLetter_s, XalanUnicode::charLetter_t, 0 } },
{ 8709, 5, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_m, XalanUnicode::charLetter_p, XalanUnicode::charLetter_t, XalanUnicode::charLetter_y, 0 } },
{ 8711, 5, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_a, XalanUnicode::charLetter_b, XalanUnicode::charLetter_l, XalanUnicode::charLetter_a, 0 } },
{ 8712, 4, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, 0 } },
{ 8713, 5, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, 0 } },
{ 8715, 2, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_i, 0 } },
{ 8719, 4, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, XalanUnicode::charLetter_d, 0 } },
{ 8721, 3, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_m, 0 } },
{ 8722, 5, { XalanUnicode::charLetter_m, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, XalanUnicode::charLetter_u, XalanUnicode::charLetter_s, 0 } },
{ 8727, 6, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_w, XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_t, 0 } },
{ 8730, 5, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_d, XalanUnicode::charLetter_i, XalanUnicode::charLetter_c, 0 } },
{ 8733, 4, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_r, XalanUnicode::charLetter_o, XalanUnicode::charLetter_p, 0 } },
{ 8734, 5, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, XalanUnicode::charLetter_f, XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, 0 } },
{ 8736, 3, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_n, XalanUnicode::charLetter_g, 0 } },
{ 8743, 3, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_n, XalanUnicode::charLetter_d, 0 } },
{ 8744, 2, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, 0 } },
{ 8745, 3, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_a, XalanUnicode::charLetter_p, 0 } },
{ 8746, 3, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, 0 } },
{ 8747, 3, { XalanUnicode::charLetter_i, XalanUnicode::charLetter_n, XalanUnicode::charLetter_t, 0 } },
{ 8756, 6, { XalanUnicode::charLetter_t, XalanUnicode::charLetter_h, XalanUnicode::charLetter_e, XalanUnicode::charLetter_r, XalanUnicode::charLetter_e, XalanUnicode::charDigit_4, 0 } },
{ 8764, 3, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, 0 } },
{ 8773, 4, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_o, XalanUnicode::charLetter_n, XalanUnicode::charLetter_g, 0 } },
{ 8776, 5, { XalanUnicode::charLetter_a, XalanUnicode::charLetter_s, XalanUnicode::charLetter_y, XalanUnicode::charLetter_m, XalanUnicode::charLetter_p, 0 } },
{ 8800, 2, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_e, 0 } },
{ 8801, 5, { XalanUnicode::charLetter_e, XalanUnicode::charLetter_q, XalanUnicode::charLetter_u, XalanUnicode::charLetter_i, XalanUnicode::charLetter_v, 0 } },
{ 8804, 2, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_e, 0 } },
{ 8805, 2, { XalanUnicode::charLetter_g, XalanUnicode::charLetter_e, 0 } },
{ 8834, 3, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_b, 0 } },
{ 8835, 3, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, 0 } },
{ 8836, 4, { XalanUnicode::charLetter_n, XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_b, 0 } },
{ 8838, 4, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_b, XalanUnicode::charLetter_e, 0 } },
{ 8839, 4, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_u, XalanUnicode::charLetter_p, XalanUnicode::charLetter_e, 0 } },
{ 8853, 5, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_p, XalanUnicode::charLetter_l, XalanUnicode::charLetter_u, XalanUnicode::charLetter_s, 0 } },
{ 8855, 6, { XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, 0 } },
{ 8869, 4, { XalanUnicode::charLetter_p, XalanUnicode::charLetter_e, XalanUnicode::charLetter_r, XalanUnicode::charLetter_p, 0 } },
{ 8901, 4, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_d, XalanUnicode::charLetter_o, XalanUnicode::charLetter_t, 0 } },
{ 8968, 5, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_c, XalanUnicode::charLetter_e, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, 0 } },
{ 8969, 5, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_c, XalanUnicode::charLetter_e, XalanUnicode::charLetter_i, XalanUnicode::charLetter_l, 0 } },
{ 8970, 6, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_f, XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, 0 } },
{ 8971, 6, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_f, XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, 0 } },
{ 9001, 4, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_a, XalanUnicode::charLetter_n, XalanUnicode::charLetter_g, 0 } },
{ 9002, 4, { XalanUnicode::charLetter_r, XalanUnicode::charLetter_a, XalanUnicode::charLetter_n, XalanUnicode::charLetter_g, 0 } },
{ 9674, 3, { XalanUnicode::charLetter_l, XalanUnicode::charLetter_o, XalanUnicode::charLetter_z, 0 } },
{ 9824, 6, { XalanUnicode::charLetter_s, XalanUnicode::charLetter_p, XalanUnicode::charLetter_a, XalanUnicode::charLetter_d, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, 0 } },
{ 9827, 5, { XalanUnicode::charLetter_c, XalanUnicode::charLetter_l, XalanUnicode::charLetter_u, XalanUnicode::charLetter_b, XalanUnicode::charLetter_s, 0 } },
{ 9829, 6, { XalanUnicode::charLetter_h, XalanUnicode::charLetter_e, XalanUnicode::charLetter_a, XalanUnicode::charLetter_r, XalanUnicode::charLetter_t, XalanUnicode::charLetter_s, 0 } },
{ 9830, 5, { XalanUnicode::charLetter_d, XalanUnicode::charLetter_i, XalanUnicode::charLetter_a, XalanUnicode::charLetter_m, XalanUnicode::charLetter_s, 0 } }
};
const FormatterToHTML::Entity* const FormatterToHTML::s_lastEntity =
FormatterToHTML::s_entities + (sizeof(s_entities) / sizeof (s_entities[0])) - 1;
#define FHTML_SIZE(str) ((sizeof(str) / sizeof(str[0]) - 1))
const XalanDOMChar FormatterToHTML::s_doctypeHeaderStartString[] =
{
XalanUnicode::charLessThanSign,
XalanUnicode::charExclamationMark,
XalanUnicode::charLetter_D,
XalanUnicode::charLetter_O,
XalanUnicode::charLetter_C,
XalanUnicode::charLetter_T,
XalanUnicode::charLetter_Y,
XalanUnicode::charLetter_P,
XalanUnicode::charLetter_E,
XalanUnicode::charSpace,
XalanUnicode::charLetter_H,
XalanUnicode::charLetter_T,
XalanUnicode::charLetter_M,
XalanUnicode::charLetter_L,
0
};
const FormatterToHTML::size_type FormatterToHTML::s_doctypeHeaderStartStringLength =
FHTML_SIZE(s_doctypeHeaderStartString);
const XalanDOMChar FormatterToHTML::s_doctypeHeaderPublicString[] =
{
XalanUnicode::charSpace,
XalanUnicode::charLetter_P,
XalanUnicode::charLetter_U,
XalanUnicode::charLetter_B,
XalanUnicode::charLetter_L,
XalanUnicode::charLetter_I,
XalanUnicode::charLetter_C,
XalanUnicode::charSpace,
XalanUnicode::charQuoteMark,
0
};
const FormatterToHTML::size_type FormatterToHTML::s_doctypeHeaderPublicStringLength =
FHTML_SIZE(s_doctypeHeaderPublicString);
const XalanDOMChar FormatterToHTML::s_doctypeHeaderSystemString[] =
{
XalanUnicode::charSpace,
XalanUnicode::charLetter_S,
XalanUnicode::charLetter_Y,
XalanUnicode::charLetter_S,
XalanUnicode::charLetter_T,
XalanUnicode::charLetter_E,
XalanUnicode::charLetter_M,
0
};
const FormatterToHTML::size_type FormatterToHTML::s_doctypeHeaderSystemStringLength =
FHTML_SIZE(s_doctypeHeaderSystemString);
const XalanDOMChar FormatterToHTML::s_metaString[] =
{
XalanUnicode::charLessThanSign,
XalanUnicode::charLetter_M,
XalanUnicode::charLetter_E,
XalanUnicode::charLetter_T,
XalanUnicode::charLetter_A,
XalanUnicode::charSpace,
XalanUnicode::charLetter_h,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_p,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_q,
XalanUnicode::charLetter_u,
XalanUnicode::charLetter_i,
XalanUnicode::charLetter_v,
XalanUnicode::charEqualsSign,
XalanUnicode::charQuoteMark,
XalanUnicode::charLetter_C,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
XalanUnicode::charHyphenMinus,
XalanUnicode::charLetter_T,
XalanUnicode::charLetter_y,
XalanUnicode::charLetter_p,
XalanUnicode::charLetter_e,
XalanUnicode::charQuoteMark,
XalanUnicode::charSpace,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_o,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_n,
XalanUnicode::charLetter_t,
XalanUnicode::charEqualsSign,
XalanUnicode::charQuoteMark,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_x,
XalanUnicode::charLetter_t,
XalanUnicode::charSolidus,
XalanUnicode::charLetter_h,
XalanUnicode::charLetter_t,
XalanUnicode::charLetter_m,
XalanUnicode::charLetter_l,
XalanUnicode::charSemicolon,
XalanUnicode::charSpace,
XalanUnicode::charLetter_c,
XalanUnicode::charLetter_h,
XalanUnicode::charLetter_a,
XalanUnicode::charLetter_r,
XalanUnicode::charLetter_s,
XalanUnicode::charLetter_e,
XalanUnicode::charLetter_t,
XalanUnicode::charEqualsSign,
0
};
const FormatterToHTML::size_type FormatterToHTML::s_metaStringLength =
FHTML_SIZE(s_metaString);
XALAN_CPP_NAMESPACE_END
| 43.809155
| 244
| 0.726188
|
rherardi
|
6d3b60c12bc2326a95a50dde0243f199138ddbb1
| 2,443
|
hpp
|
C++
|
modules/boost/simd/base/include/boost/simd/operator/functions/is_greater.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | null | null | null |
modules/boost/simd/base/include/boost/simd/operator/functions/is_greater.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | null | null | null |
modules/boost/simd/base/include/boost/simd/operator/functions/is_greater.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | null | null | null |
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_OPERATOR_FUNCTIONS_IS_GREATER_HPP_INCLUDED
#define BOOST_SIMD_OPERATOR_FUNCTIONS_IS_GREATER_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
namespace boost { namespace simd
{
namespace tag
{
/*!
@brief is_greater generic tag
Represents the is_greater function in generic contexts.
@par Models:
Hierarchy
**/
struct is_greater_ : ext::elementwise_<is_greater_>
{
/// @brief Parent hierarchy
typedef ext::elementwise_<is_greater_> parent;
template<class... Args>
static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
BOOST_AUTO_DECLTYPE_BODY( dispatching_is_greater_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
};
}
namespace ext
{
template<class Site, class... Ts>
BOOST_FORCEINLINE generic_dispatcher<tag::is_greater_, Site> dispatching_is_greater_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
{
return generic_dispatcher<tag::is_greater_, Site>();
}
template<class... Args>
struct impl_is_greater_;
}
/*!
Returns True or False according a0 is greater than a1 or not.
Infix notation can be used with operator '>'.
@par Semantic:
For every parameters of types respectively T0, T1:
@code
as_logical<T0> r = is_greater(a0,a1);
@endcode
is similar to:
@code
as_logical<T0> r = a0 > a1;
@endcode
@par Alias:
@c gt, @c is_gt
@see @funcref{is_greater_equal}, @funcref{is_gtz}, @funcref{is_nle}, @funcref{is_nlez}
@param a0
@param a1
@return a logical value
**/
BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::is_greater_, is_greater , 2 )
BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::is_greater_, gt , 2 )
BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::is_greater_, is_gt , 2 )
} }
#include <boost/simd/operator/specific/common.hpp>
#endif
| 30.160494
| 178
| 0.635694
|
psiha
|
6d3cb8363b08e7cbf9a8818f7808855beb034a8a
| 1,983
|
cpp
|
C++
|
examples/wifi-echo/server/esp32/main/Ble.cpp
|
balducci-apple/connectedhomeip
|
d5cbe865ee53557330941a3c4c243f40c3c7b400
|
[
"Apache-2.0"
] | null | null | null |
examples/wifi-echo/server/esp32/main/Ble.cpp
|
balducci-apple/connectedhomeip
|
d5cbe865ee53557330941a3c4c243f40c3c7b400
|
[
"Apache-2.0"
] | null | null | null |
examples/wifi-echo/server/esp32/main/Ble.cpp
|
balducci-apple/connectedhomeip
|
d5cbe865ee53557330941a3c4c243f40c3c7b400
|
[
"Apache-2.0"
] | null | null | null |
/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* 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 "Display.h"
#include "BluetoothWidget.h"
#include <platform/CHIPDeviceLayer.h>
#include <support/ErrorStr.h>
#include <support/logging/CHIPLogging.h>
#include <system/SystemPacketBuffer.h>
#if CONFIG_HAVE_DISPLAY
extern BluetoothWidget bluetoothLED;
#endif // CONFIG_HAVE_DISPLAY
using namespace ::chip;
using namespace ::chip::Ble;
void HandleBleMessageReceived(BLEEndPoint * endPoint, PacketBuffer * buffer)
{
const size_t bufferLen = buffer->DataLength();
char msg[bufferLen];
msg[bufferLen] = 0;
memcpy(msg, buffer->Start(), bufferLen);
ChipLogProgress(Ble, "BLEEndPoint: Receive message: %s", msg);
endPoint->Send(buffer);
}
void HandleBleConnectionClosed(BLEEndPoint * endPoint, BLE_ERROR err)
{
ChipLogProgress(Ble, "BLEEndPoint: Connection closed (%s)", ErrorStr(err));
#if CONFIG_HAVE_DISPLAY
bluetoothLED.Set(false);
#endif // CONFIG_HAVE_DISPLAY
}
void HandleBleNewConnection(BLEEndPoint * endPoint)
{
ChipLogProgress(Ble, "BLEEndPoint: Connection opened");
endPoint->OnMessageReceived = HandleBleMessageReceived;
endPoint->OnConnectionClosed = HandleBleConnectionClosed;
#if CONFIG_HAVE_DISPLAY
bluetoothLED.Set(true);
#endif // CONFIG_HAVE_DISPLAY
}
void startBle()
{
DeviceLayer::ConnectivityMgr().AddCHIPoBLEConnectionHandler(HandleBleNewConnection);
}
| 28.73913
| 88
| 0.741301
|
balducci-apple
|
6d3f519baf12a7be77605eccd3aea5fb1c13ef70
| 196
|
hpp
|
C++
|
src/geodesy.hpp
|
xanthospap/ngpt
|
fa445c5c21e657dda8c47bbbe0a6f1bf1aa45867
|
[
"WTFPL"
] | null | null | null |
src/geodesy.hpp
|
xanthospap/ngpt
|
fa445c5c21e657dda8c47bbbe0a6f1bf1aa45867
|
[
"WTFPL"
] | 2
|
2016-01-19T13:42:14.000Z
|
2016-01-29T19:00:05.000Z
|
src/geodesy.hpp
|
xanthospap/ngpt
|
fa445c5c21e657dda8c47bbbe0a6f1bf1aa45867
|
[
"WTFPL"
] | 3
|
2019-06-01T03:53:41.000Z
|
2020-09-21T10:48:08.000Z
|
#ifndef __GEODESY__
#define __GEODESY__
#include "geoconst.hpp"
namespace ngpt {
void
top2daz(double, double, double,
double&, double&, double&);
} // end namespace geodesy
#endif
| 13.066667
| 35
| 0.693878
|
xanthospap
|
6d3f9821022fc55e86145ed1fd3bb71e0e9165f0
| 3,616
|
cpp
|
C++
|
src/Coal/System/Task.cpp
|
janitochvvll2311/Coal
|
6ed6ba6b058e35c66cbef41552e3106589535b92
|
[
"Unlicense"
] | 3
|
2021-12-26T21:41:33.000Z
|
2022-03-29T22:33:04.000Z
|
src/Coal/System/Task.cpp
|
janitochvvll2311/Coal
|
6ed6ba6b058e35c66cbef41552e3106589535b92
|
[
"Unlicense"
] | 21
|
2022-03-29T02:51:39.000Z
|
2022-03-31T03:38:25.000Z
|
src/Coal/System/Task.cpp
|
janitochvvll2311/Coal
|
6ed6ba6b058e35c66cbef41552e3106589535b92
|
[
"Unlicense"
] | null | null | null |
/**
* @file Task.cpp
* @author Juan Jesus Chavez Villa (janitochvvll2311@gmail.com)
* @brief Implementation of Task
* @version 0.1.0
* @date 2022-04-20
*
* @copyright Copyright (c) 2022
*
*/
// Headers
#include <iostream> // To include std::cerr
#include <Coal/System/Task.hpp> // Main header
namespace co
{
namespace impl
{
void Task::main()
{
int state;
int type;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &state);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
try
{
execute();
m_core->control.lock();
m_core->state = TaskDone;
m_core->control.unlock();
}
catch (std::exception ex)
{
m_core->control.lock();
m_core->state = TaskException;
m_core->control.unlock();
std::cerr << ex.what() << '\n';
}
catch (...)
{
m_core->control.lock();
m_core->state = TaskException;
m_core->control.unlock();
std::cerr << "Unknowed exception\n";
}
pthread_setcancelstate(state, &state);
pthread_setcanceltype(type, &type);
}
////////////////////////////////////////////////////////////////
TaskState Task::state() const
{
return m_core->state;
}
cptrt<void> Task::canceltoken() const
{
return m_canceltoken;
}
void Task::run()
{
m_core->control.lock();
if (m_core->state == TaskReady)
{
m_core->state = TaskRunning;
m_core->thread = std::thread(main, this);
m_core->handle = m_core->thread.native_handle();
}
m_core->control.unlock();
}
void Task::wait() const
{
if (m_core->state == TaskRunning)
{
m_core->waiter.lock();
if (m_core->thread.joinable())
m_core->thread.join();
m_core->waiter.unlock();
}
}
void Task::cancel()
{
m_core->control.lock();
if (m_core->state == TaskRunning)
{
pthread_cancel(m_core->handle);
m_core->handle = 0;
m_core->state = TaskCanceled;
}
m_core->control.unlock();
}
/////////////////////////////////////////////////////////////////////////////
Task &Task::operator=(Task &&tmp)
{
cancel();
m_core.release();
m_canceltoken = nullptr;
//
m_core.swap(tmp.m_core);
std::swap(m_canceltoken, tmp.m_canceltoken);
return *this;
}
Task::Task(Task &&tmp)
: m_core(std::move(tmp.m_core)),
m_canceltoken(nullptr)
{
std::swap(m_canceltoken, tmp.m_canceltoken);
}
/////////////////////////////////////////////////////////////////////////////
Task::Task(TaskState state, cptrt<void> canceltoken)
: m_core(new TaskCore()),
m_canceltoken(canceltoken)
{
m_core->state = state;
}
Task::~Task()
{
cancel();
if (m_core->thread.joinable())
m_core->thread.detach();
}
}
}
| 26.202899
| 85
| 0.423119
|
janitochvvll2311
|
6d3fc078a65aa3e76cff89adf66bb7fe48da9e19
| 128
|
hxx
|
C++
|
src/Providers/UNIXProviders/ConcreteComponent/UNIX_ConcreteComponent_ZOS.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | 1
|
2020-10-12T09:00:09.000Z
|
2020-10-12T09:00:09.000Z
|
src/Providers/UNIXProviders/ConcreteComponent/UNIX_ConcreteComponent_ZOS.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
src/Providers/UNIXProviders/ConcreteComponent/UNIX_ConcreteComponent_ZOS.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
#ifdef PEGASUS_OS_ZOS
#ifndef __UNIX_CONCRETECOMPONENT_PRIVATE_H
#define __UNIX_CONCRETECOMPONENT_PRIVATE_H
#endif
#endif
| 10.666667
| 42
| 0.851563
|
brunolauze
|
6d3ff64edc97c8bd05e8ad5a464a1c5e8271698f
| 1,046
|
cc
|
C++
|
Array_List/907.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
Array_List/907.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
Array_List/907.cc
|
guohaoqiang/leetcode
|
802447c029c36892e8dd7391c825bcfc7ac0fd0b
|
[
"MIT"
] | null | null | null |
//https://leetcode.com/problems/sum-of-subarray-minimums/discuss/170750/JavaC%2B%2BPython-Stack-Solution
class Solution {
public:
int mod = 1e9+7;
int sumSubarrayMins(vector<int>& arr) {
int n = arr.size();
stack<pair<int,int>> left,right;
vector<int> l(n),r(n);
int count;
for (int i=0; i<n; ++i){
count = 1;
while (!left.empty() && left.top().first>arr[i]){
count += left.top().second;
left.pop();
}
left.push({arr[i],count});
l[i] = count;
}
for (int i=n-1; i>=0; --i){
count = 1;
while (!right.empty() && right.top().first>=arr[i]){
count += right.top().second;
right.pop();
}
right.push({arr[i],count});
r[i] = count;
}
int ans = 0;
for (int i=0; i<n; ++i){
ans = (ans + (long)arr[i]*l[i]*r[i])%mod;
}
return ans;
}
};
| 28.27027
| 104
| 0.427342
|
guohaoqiang
|
6d43584669ca23af0ba9c0ef635f617278e4d18e
| 29,210
|
cpp
|
C++
|
sh1106.cpp
|
insightmachineslab/IndustrialAlarmClock
|
65210b7e2c4e6ae328c9792c153de06b9ba379bd
|
[
"Apache-2.0"
] | null | null | null |
sh1106.cpp
|
insightmachineslab/IndustrialAlarmClock
|
65210b7e2c4e6ae328c9792c153de06b9ba379bd
|
[
"Apache-2.0"
] | null | null | null |
sh1106.cpp
|
insightmachineslab/IndustrialAlarmClock
|
65210b7e2c4e6ae328c9792c153de06b9ba379bd
|
[
"Apache-2.0"
] | null | null | null |
/**
******************************************************************************
* @file sh1106.c
* @author Waveshare Team
* @version
* @date 21-June-2017
* @brief This file includes the OLED driver for SH1106 display moudle
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, WAVESHARE SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
******************************************************************************
*/
#include <SPI.h>
#include <Wire.h>
#include <stdio.h>
#include "sh1106.h"
const uint8_t Font1206[95][12] PROGMEM = {
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*" ",0*/
{0x00,0x00,0x00,0x00,0x3F,0x40,0x00,0x00,0x00,0x00,0x00,0x00},/*"!",1*/
{0x00,0x00,0x30,0x00,0x40,0x00,0x30,0x00,0x40,0x00,0x00,0x00},/*""",2*/
{0x09,0x00,0x0B,0xC0,0x3D,0x00,0x0B,0xC0,0x3D,0x00,0x09,0x00},/*"#",3*/
{0x18,0xC0,0x24,0x40,0x7F,0xE0,0x22,0x40,0x31,0x80,0x00,0x00},/*"$",4*/
{0x18,0x00,0x24,0xC0,0x1B,0x00,0x0D,0x80,0x32,0x40,0x01,0x80},/*"%",5*/
{0x03,0x80,0x1C,0x40,0x27,0x40,0x1C,0x80,0x07,0x40,0x00,0x40},/*"&",6*/
{0x10,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"'",7*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0x80,0x20,0x40,0x40,0x20},/*"(",8*/
{0x00,0x00,0x40,0x20,0x20,0x40,0x1F,0x80,0x00,0x00,0x00,0x00},/*")",9*/
{0x09,0x00,0x06,0x00,0x1F,0x80,0x06,0x00,0x09,0x00,0x00,0x00},/*"*",10*/
{0x04,0x00,0x04,0x00,0x3F,0x80,0x04,0x00,0x04,0x00,0x00,0x00},/*"+",11*/
{0x00,0x10,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*",",12*/
{0x04,0x00,0x04,0x00,0x04,0x00,0x04,0x00,0x04,0x00,0x00,0x00},/*"-",13*/
{0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*".",14*/
{0x00,0x20,0x01,0xC0,0x06,0x00,0x38,0x00,0x40,0x00,0x00,0x00},/*"/",15*/
{0x1F,0x80,0x20,0x40,0x20,0x40,0x20,0x40,0x1F,0x80,0x00,0x00},/*"0",16*/
{0x00,0x00,0x10,0x40,0x3F,0xC0,0x00,0x40,0x00,0x00,0x00,0x00},/*"1",17*/
{0x18,0xC0,0x21,0x40,0x22,0x40,0x24,0x40,0x18,0x40,0x00,0x00},/*"2",18*/
{0x10,0x80,0x20,0x40,0x24,0x40,0x24,0x40,0x1B,0x80,0x00,0x00},/*"3",19*/
{0x02,0x00,0x0D,0x00,0x11,0x00,0x3F,0xC0,0x01,0x40,0x00,0x00},/*"4",20*/
{0x3C,0x80,0x24,0x40,0x24,0x40,0x24,0x40,0x23,0x80,0x00,0x00},/*"5",21*/
{0x1F,0x80,0x24,0x40,0x24,0x40,0x34,0x40,0x03,0x80,0x00,0x00},/*"6",22*/
{0x30,0x00,0x20,0x00,0x27,0xC0,0x38,0x00,0x20,0x00,0x00,0x00},/*"7",23*/
{0x1B,0x80,0x24,0x40,0x24,0x40,0x24,0x40,0x1B,0x80,0x00,0x00},/*"8",24*/
{0x1C,0x00,0x22,0xC0,0x22,0x40,0x22,0x40,0x1F,0x80,0x00,0x00},/*"9",25*/
{0x00,0x00,0x00,0x00,0x08,0x40,0x00,0x00,0x00,0x00,0x00,0x00},/*":",26*/
{0x00,0x00,0x00,0x00,0x04,0x60,0x00,0x00,0x00,0x00,0x00,0x00},/*";",27*/
{0x00,0x00,0x04,0x00,0x0A,0x00,0x11,0x00,0x20,0x80,0x40,0x40},/*"<",28*/
{0x09,0x00,0x09,0x00,0x09,0x00,0x09,0x00,0x09,0x00,0x00,0x00},/*"=",29*/
{0x00,0x00,0x40,0x40,0x20,0x80,0x11,0x00,0x0A,0x00,0x04,0x00},/*">",30*/
{0x18,0x00,0x20,0x00,0x23,0x40,0x24,0x00,0x18,0x00,0x00,0x00},/*"?",31*/
{0x1F,0x80,0x20,0x40,0x27,0x40,0x29,0x40,0x1F,0x40,0x00,0x00},/*"@",32*/
{0x00,0x40,0x07,0xC0,0x39,0x00,0x0F,0x00,0x01,0xC0,0x00,0x40},/*"A",33*/
{0x20,0x40,0x3F,0xC0,0x24,0x40,0x24,0x40,0x1B,0x80,0x00,0x00},/*"B",34*/
{0x1F,0x80,0x20,0x40,0x20,0x40,0x20,0x40,0x30,0x80,0x00,0x00},/*"C",35*/
{0x20,0x40,0x3F,0xC0,0x20,0x40,0x20,0x40,0x1F,0x80,0x00,0x00},/*"D",36*/
{0x20,0x40,0x3F,0xC0,0x24,0x40,0x2E,0x40,0x30,0xC0,0x00,0x00},/*"E",37*/
{0x20,0x40,0x3F,0xC0,0x24,0x40,0x2E,0x00,0x30,0x00,0x00,0x00},/*"F",38*/
{0x0F,0x00,0x10,0x80,0x20,0x40,0x22,0x40,0x33,0x80,0x02,0x00},/*"G",39*/
{0x20,0x40,0x3F,0xC0,0x04,0x00,0x04,0x00,0x3F,0xC0,0x20,0x40},/*"H",40*/
{0x20,0x40,0x20,0x40,0x3F,0xC0,0x20,0x40,0x20,0x40,0x00,0x00},/*"I",41*/
{0x00,0x60,0x20,0x20,0x20,0x20,0x3F,0xC0,0x20,0x00,0x20,0x00},/*"J",42*/
{0x20,0x40,0x3F,0xC0,0x24,0x40,0x0B,0x00,0x30,0xC0,0x20,0x40},/*"K",43*/
{0x20,0x40,0x3F,0xC0,0x20,0x40,0x00,0x40,0x00,0x40,0x00,0xC0},/*"L",44*/
{0x3F,0xC0,0x3C,0x00,0x03,0xC0,0x3C,0x00,0x3F,0xC0,0x00,0x00},/*"M",45*/
{0x20,0x40,0x3F,0xC0,0x0C,0x40,0x23,0x00,0x3F,0xC0,0x20,0x00},/*"N",46*/
{0x1F,0x80,0x20,0x40,0x20,0x40,0x20,0x40,0x1F,0x80,0x00,0x00},/*"O",47*/
{0x20,0x40,0x3F,0xC0,0x24,0x40,0x24,0x00,0x18,0x00,0x00,0x00},/*"P",48*/
{0x1F,0x80,0x21,0x40,0x21,0x40,0x20,0xE0,0x1F,0xA0,0x00,0x00},/*"Q",49*/
{0x20,0x40,0x3F,0xC0,0x24,0x40,0x26,0x00,0x19,0xC0,0x00,0x40},/*"R",50*/
{0x18,0xC0,0x24,0x40,0x24,0x40,0x22,0x40,0x31,0x80,0x00,0x00},/*"S",51*/
{0x30,0x00,0x20,0x40,0x3F,0xC0,0x20,0x40,0x30,0x00,0x00,0x00},/*"T",52*/
{0x20,0x00,0x3F,0x80,0x00,0x40,0x00,0x40,0x3F,0x80,0x20,0x00},/*"U",53*/
{0x20,0x00,0x3E,0x00,0x01,0xC0,0x07,0x00,0x38,0x00,0x20,0x00},/*"V",54*/
{0x38,0x00,0x07,0xC0,0x3C,0x00,0x07,0xC0,0x38,0x00,0x00,0x00},/*"W",55*/
{0x20,0x40,0x39,0xC0,0x06,0x00,0x39,0xC0,0x20,0x40,0x00,0x00},/*"X",56*/
{0x20,0x00,0x38,0x40,0x07,0xC0,0x38,0x40,0x20,0x00,0x00,0x00},/*"Y",57*/
{0x30,0x40,0x21,0xC0,0x26,0x40,0x38,0x40,0x20,0xC0,0x00,0x00},/*"Z",58*/
{0x00,0x00,0x00,0x00,0x7F,0xE0,0x40,0x20,0x40,0x20,0x00,0x00},/*"[",59*/
{0x00,0x00,0x70,0x00,0x0C,0x00,0x03,0x80,0x00,0x40,0x00,0x00},/*"\",60*/
{0x00,0x00,0x40,0x20,0x40,0x20,0x7F,0xE0,0x00,0x00,0x00,0x00},/*"]",61*/
{0x00,0x00,0x20,0x00,0x40,0x00,0x20,0x00,0x00,0x00,0x00,0x00},/*"^",62*/
{0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10},/*"_",63*/
{0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"`",64*/
{0x00,0x00,0x02,0x80,0x05,0x40,0x05,0x40,0x03,0xC0,0x00,0x40},/*"a",65*/
{0x20,0x00,0x3F,0xC0,0x04,0x40,0x04,0x40,0x03,0x80,0x00,0x00},/*"b",66*/
{0x00,0x00,0x03,0x80,0x04,0x40,0x04,0x40,0x06,0x40,0x00,0x00},/*"c",67*/
{0x00,0x00,0x03,0x80,0x04,0x40,0x24,0x40,0x3F,0xC0,0x00,0x40},/*"d",68*/
{0x00,0x00,0x03,0x80,0x05,0x40,0x05,0x40,0x03,0x40,0x00,0x00},/*"e",69*/
{0x00,0x00,0x04,0x40,0x1F,0xC0,0x24,0x40,0x24,0x40,0x20,0x00},/*"f",70*/
{0x00,0x00,0x02,0xE0,0x05,0x50,0x05,0x50,0x06,0x50,0x04,0x20},/*"g",71*/
{0x20,0x40,0x3F,0xC0,0x04,0x40,0x04,0x00,0x03,0xC0,0x00,0x40},/*"h",72*/
{0x00,0x00,0x04,0x40,0x27,0xC0,0x00,0x40,0x00,0x00,0x00,0x00},/*"i",73*/
{0x00,0x10,0x00,0x10,0x04,0x10,0x27,0xE0,0x00,0x00,0x00,0x00},/*"j",74*/
{0x20,0x40,0x3F,0xC0,0x01,0x40,0x07,0x00,0x04,0xC0,0x04,0x40},/*"k",75*/
{0x20,0x40,0x20,0x40,0x3F,0xC0,0x00,0x40,0x00,0x40,0x00,0x00},/*"l",76*/
{0x07,0xC0,0x04,0x00,0x07,0xC0,0x04,0x00,0x03,0xC0,0x00,0x00},/*"m",77*/
{0x04,0x40,0x07,0xC0,0x04,0x40,0x04,0x00,0x03,0xC0,0x00,0x40},/*"n",78*/
{0x00,0x00,0x03,0x80,0x04,0x40,0x04,0x40,0x03,0x80,0x00,0x00},/*"o",79*/
{0x04,0x10,0x07,0xF0,0x04,0x50,0x04,0x40,0x03,0x80,0x00,0x00},/*"p",80*/
{0x00,0x00,0x03,0x80,0x04,0x40,0x04,0x50,0x07,0xF0,0x00,0x10},/*"q",81*/
{0x04,0x40,0x07,0xC0,0x02,0x40,0x04,0x00,0x04,0x00,0x00,0x00},/*"r",82*/
{0x00,0x00,0x06,0x40,0x05,0x40,0x05,0x40,0x04,0xC0,0x00,0x00},/*"s",83*/
{0x00,0x00,0x04,0x00,0x1F,0x80,0x04,0x40,0x00,0x40,0x00,0x00},/*"t",84*/
{0x04,0x00,0x07,0x80,0x00,0x40,0x04,0x40,0x07,0xC0,0x00,0x40},/*"u",85*/
{0x04,0x00,0x07,0x00,0x04,0xC0,0x01,0x80,0x06,0x00,0x04,0x00},/*"v",86*/
{0x06,0x00,0x01,0xC0,0x07,0x00,0x01,0xC0,0x06,0x00,0x00,0x00},/*"w",87*/
{0x04,0x40,0x06,0xC0,0x01,0x00,0x06,0xC0,0x04,0x40,0x00,0x00},/*"x",88*/
{0x04,0x10,0x07,0x10,0x04,0xE0,0x01,0x80,0x06,0x00,0x04,0x00},/*"y",89*/
{0x00,0x00,0x04,0x40,0x05,0xC0,0x06,0x40,0x04,0x40,0x00,0x00},/*"z",90*/
{0x00,0x00,0x00,0x00,0x04,0x00,0x7B,0xE0,0x40,0x20,0x00,0x00},/*"{",91*/
{0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xF0,0x00,0x00,0x00,0x00},/*"|",92*/
{0x00,0x00,0x40,0x20,0x7B,0xE0,0x04,0x00,0x00,0x00,0x00,0x00},/*"}",93*/
{0x40,0x00,0x80,0x00,0x40,0x00,0x20,0x00,0x20,0x00,0x40,0x00},/*"~",94*/
};
const uint8_t Font1612[11][32] PROGMEM =
{
{0x00,0x00,0x3F,0xFC,0x3F,0xFC,0x30,0x0C,0x30,0x0C,0x30,0x0C,0x30,0x0C,0x30,0x0C,
0x30,0x0C,0x30,0x0C,0x30,0x0C,0x30,0x0C,0x30,0x0C,0x3F,0xFC,0x3F,0xFC,0x00,0x00},/*"0",0*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x00,
0x30,0x00,0x3F,0xFC,0x3F,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"1",1*/
{0x00,0x00,0x39,0xFC,0x39,0xFC,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,
0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x3F,0x8C,0x3F,0x8C,0x00,0x00},/*"2",2*/
{0x00,0x00,0x38,0x1C,0x38,0x1C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,
0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x3F,0xFC,0x3F,0xFC,0x00,0x00},/*"3",3*/
{0x00,0x00,0x3F,0x80,0x3F,0x80,0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80,
0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80,0x01,0x80,0x3F,0xFC,0x3F,0xFC,0x00,0x00},/*"4",4*/
{0x00,0x00,0x3F,0x8C,0x3F,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,
0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0xFC,0x31,0xFC,0x00,0x00},/*"5",5*/
{0x00,0x00,0x3F,0xFC,0x3F,0xFC,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,
0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0xFC,0x31,0xFC,0x00,0x00},/*"6",6*/
{0x00,0x00,0x38,0x00,0x38,0x00,0x30,0x00,0x30,0x00,0x30,0x00,0x30,0x00,0x30,0x00,
0x30,0x00,0x30,0x00,0x30,0x00,0x30,0x00,0x30,0x00,0x3F,0xFC,0x3F,0xFC,0x00,0x00},/*"7",7*/
{0x00,0x00,0x3F,0xFC,0x3F,0xFC,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,
0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x3F,0xFC,0x3F,0xFC,0x00,0x00},/*"8",8*/
{0x00,0x00,0x3F,0x9C,0x3F,0x9C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,
0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x31,0x8C,0x3F,0xFC,0x3F,0xFC,0x00,0x00},/*"9",9*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x30,
0x18,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*":",10*/
};
const uint8_t Font1608[95][16] PROGMEM = {
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*" ",0*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0xCC,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00},/*"!",1*/
{0x00,0x00,0x08,0x00,0x30,0x00,0x60,0x00,0x08,0x00,0x30,0x00,0x60,0x00,0x00,0x00},/*""",2*/
{0x02,0x20,0x03,0xFC,0x1E,0x20,0x02,0x20,0x03,0xFC,0x1E,0x20,0x02,0x20,0x00,0x00},/*"#",3*/
{0x00,0x00,0x0E,0x18,0x11,0x04,0x3F,0xFF,0x10,0x84,0x0C,0x78,0x00,0x00,0x00,0x00},/*"$",4*/
{0x0F,0x00,0x10,0x84,0x0F,0x38,0x00,0xC0,0x07,0x78,0x18,0x84,0x00,0x78,0x00,0x00},/*"%",5*/
{0x00,0x78,0x0F,0x84,0x10,0xC4,0x11,0x24,0x0E,0x98,0x00,0xE4,0x00,0x84,0x00,0x08},/*"&",6*/
{0x08,0x00,0x68,0x00,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"'",7*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x07,0xE0,0x18,0x18,0x20,0x04,0x40,0x02,0x00,0x00},/*"(",8*/
{0x00,0x00,0x40,0x02,0x20,0x04,0x18,0x18,0x07,0xE0,0x00,0x00,0x00,0x00,0x00,0x00},/*")",9*/
{0x02,0x40,0x02,0x40,0x01,0x80,0x0F,0xF0,0x01,0x80,0x02,0x40,0x02,0x40,0x00,0x00},/*"*",10*/
{0x00,0x80,0x00,0x80,0x00,0x80,0x0F,0xF8,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x00},/*"+",11*/
{0x00,0x01,0x00,0x0D,0x00,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*",",12*/
{0x00,0x00,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80},/*"-",13*/
{0x00,0x00,0x00,0x0C,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*".",14*/
{0x00,0x00,0x00,0x06,0x00,0x18,0x00,0x60,0x01,0x80,0x06,0x00,0x18,0x00,0x20,0x00},/*"/",15*/
{0x00,0x00,0x07,0xF0,0x08,0x08,0x10,0x04,0x10,0x04,0x08,0x08,0x07,0xF0,0x00,0x00},/*"0",16*/
{0x00,0x00,0x08,0x04,0x08,0x04,0x1F,0xFC,0x00,0x04,0x00,0x04,0x00,0x00,0x00,0x00},/*"1",17*/
{0x00,0x00,0x0E,0x0C,0x10,0x14,0x10,0x24,0x10,0x44,0x11,0x84,0x0E,0x0C,0x00,0x00},/*"2",18*/
{0x00,0x00,0x0C,0x18,0x10,0x04,0x11,0x04,0x11,0x04,0x12,0x88,0x0C,0x70,0x00,0x00},/*"3",19*/
{0x00,0x00,0x00,0xE0,0x03,0x20,0x04,0x24,0x08,0x24,0x1F,0xFC,0x00,0x24,0x00,0x00},/*"4",20*/
{0x00,0x00,0x1F,0x98,0x10,0x84,0x11,0x04,0x11,0x04,0x10,0x88,0x10,0x70,0x00,0x00},/*"5",21*/
{0x00,0x00,0x07,0xF0,0x08,0x88,0x11,0x04,0x11,0x04,0x18,0x88,0x00,0x70,0x00,0x00},/*"6",22*/
{0x00,0x00,0x1C,0x00,0x10,0x00,0x10,0xFC,0x13,0x00,0x1C,0x00,0x10,0x00,0x00,0x00},/*"7",23*/
{0x00,0x00,0x0E,0x38,0x11,0x44,0x10,0x84,0x10,0x84,0x11,0x44,0x0E,0x38,0x00,0x00},/*"8",24*/
{0x00,0x00,0x07,0x00,0x08,0x8C,0x10,0x44,0x10,0x44,0x08,0x88,0x07,0xF0,0x00,0x00},/*"9",25*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x0C,0x03,0x0C,0x00,0x00,0x00,0x00,0x00,0x00},/*":",26*/
{0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*";",27*/
{0x00,0x00,0x00,0x80,0x01,0x40,0x02,0x20,0x04,0x10,0x08,0x08,0x10,0x04,0x00,0x00},/*"<",28*/
{0x02,0x20,0x02,0x20,0x02,0x20,0x02,0x20,0x02,0x20,0x02,0x20,0x02,0x20,0x00,0x00},/*"=",29*/
{0x00,0x00,0x10,0x04,0x08,0x08,0x04,0x10,0x02,0x20,0x01,0x40,0x00,0x80,0x00,0x00},/*">",30*/
{0x00,0x00,0x0E,0x00,0x12,0x00,0x10,0x0C,0x10,0x6C,0x10,0x80,0x0F,0x00,0x00,0x00},/*"?",31*/
{0x03,0xE0,0x0C,0x18,0x13,0xE4,0x14,0x24,0x17,0xC4,0x08,0x28,0x07,0xD0,0x00,0x00},/*"@",32*/
{0x00,0x04,0x00,0x3C,0x03,0xC4,0x1C,0x40,0x07,0x40,0x00,0xE4,0x00,0x1C,0x00,0x04},/*"A",33*/
{0x10,0x04,0x1F,0xFC,0x11,0x04,0x11,0x04,0x11,0x04,0x0E,0x88,0x00,0x70,0x00,0x00},/*"B",34*/
{0x03,0xE0,0x0C,0x18,0x10,0x04,0x10,0x04,0x10,0x04,0x10,0x08,0x1C,0x10,0x00,0x00},/*"C",35*/
{0x10,0x04,0x1F,0xFC,0x10,0x04,0x10,0x04,0x10,0x04,0x08,0x08,0x07,0xF0,0x00,0x00},/*"D",36*/
{0x10,0x04,0x1F,0xFC,0x11,0x04,0x11,0x04,0x17,0xC4,0x10,0x04,0x08,0x18,0x00,0x00},/*"E",37*/
{0x10,0x04,0x1F,0xFC,0x11,0x04,0x11,0x00,0x17,0xC0,0x10,0x00,0x08,0x00,0x00,0x00},/*"F",38*/
{0x03,0xE0,0x0C,0x18,0x10,0x04,0x10,0x04,0x10,0x44,0x1C,0x78,0x00,0x40,0x00,0x00},/*"G",39*/
{0x10,0x04,0x1F,0xFC,0x10,0x84,0x00,0x80,0x00,0x80,0x10,0x84,0x1F,0xFC,0x10,0x04},/*"H",40*/
{0x00,0x00,0x10,0x04,0x10,0x04,0x1F,0xFC,0x10,0x04,0x10,0x04,0x00,0x00,0x00,0x00},/*"I",41*/
{0x00,0x03,0x00,0x01,0x10,0x01,0x10,0x01,0x1F,0xFE,0x10,0x00,0x10,0x00,0x00,0x00},/*"J",42*/
{0x10,0x04,0x1F,0xFC,0x11,0x04,0x03,0x80,0x14,0x64,0x18,0x1C,0x10,0x04,0x00,0x00},/*"K",43*/
{0x10,0x04,0x1F,0xFC,0x10,0x04,0x00,0x04,0x00,0x04,0x00,0x04,0x00,0x0C,0x00,0x00},/*"L",44*/
{0x10,0x04,0x1F,0xFC,0x1F,0x00,0x00,0xFC,0x1F,0x00,0x1F,0xFC,0x10,0x04,0x00,0x00},/*"M",45*/
{0x10,0x04,0x1F,0xFC,0x0C,0x04,0x03,0x00,0x00,0xE0,0x10,0x18,0x1F,0xFC,0x10,0x00},/*"N",46*/
{0x07,0xF0,0x08,0x08,0x10,0x04,0x10,0x04,0x10,0x04,0x08,0x08,0x07,0xF0,0x00,0x00},/*"O",47*/
{0x10,0x04,0x1F,0xFC,0x10,0x84,0x10,0x80,0x10,0x80,0x10,0x80,0x0F,0x00,0x00,0x00},/*"P",48*/
{0x07,0xF0,0x08,0x18,0x10,0x24,0x10,0x24,0x10,0x1C,0x08,0x0A,0x07,0xF2,0x00,0x00},/*"Q",49*/
{0x10,0x04,0x1F,0xFC,0x11,0x04,0x11,0x00,0x11,0xC0,0x11,0x30,0x0E,0x0C,0x00,0x04},/*"R",50*/
{0x00,0x00,0x0E,0x1C,0x11,0x04,0x10,0x84,0x10,0x84,0x10,0x44,0x1C,0x38,0x00,0x00},/*"S",51*/
{0x18,0x00,0x10,0x00,0x10,0x04,0x1F,0xFC,0x10,0x04,0x10,0x00,0x18,0x00,0x00,0x00},/*"T",52*/
{0x10,0x00,0x1F,0xF8,0x10,0x04,0x00,0x04,0x00,0x04,0x10,0x04,0x1F,0xF8,0x10,0x00},/*"U",53*/
{0x10,0x00,0x1E,0x00,0x11,0xE0,0x00,0x1C,0x00,0x70,0x13,0x80,0x1C,0x00,0x10,0x00},/*"V",54*/
{0x1F,0xC0,0x10,0x3C,0x00,0xE0,0x1F,0x00,0x00,0xE0,0x10,0x3C,0x1F,0xC0,0x00,0x00},/*"W",55*/
{0x10,0x04,0x18,0x0C,0x16,0x34,0x01,0xC0,0x01,0xC0,0x16,0x34,0x18,0x0C,0x10,0x04},/*"X",56*/
{0x10,0x00,0x1C,0x00,0x13,0x04,0x00,0xFC,0x13,0x04,0x1C,0x00,0x10,0x00,0x00,0x00},/*"Y",57*/
{0x08,0x04,0x10,0x1C,0x10,0x64,0x10,0x84,0x13,0x04,0x1C,0x04,0x10,0x18,0x00,0x00},/*"Z",58*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFE,0x40,0x02,0x40,0x02,0x40,0x02,0x00,0x00},/*"[",59*/
{0x00,0x00,0x30,0x00,0x0C,0x00,0x03,0x80,0x00,0x60,0x00,0x1C,0x00,0x03,0x00,0x00},/*"\",60*/
{0x00,0x00,0x40,0x02,0x40,0x02,0x40,0x02,0x7F,0xFE,0x00,0x00,0x00,0x00,0x00,0x00},/*"]",61*/
{0x00,0x00,0x00,0x00,0x20,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x20,0x00,0x00,0x00},/*"^",62*/
{0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01},/*"_",63*/
{0x00,0x00,0x40,0x00,0x40,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"`",64*/
{0x00,0x00,0x00,0x98,0x01,0x24,0x01,0x44,0x01,0x44,0x01,0x44,0x00,0xFC,0x00,0x04},/*"a",65*/
{0x10,0x00,0x1F,0xFC,0x00,0x88,0x01,0x04,0x01,0x04,0x00,0x88,0x00,0x70,0x00,0x00},/*"b",66*/
{0x00,0x00,0x00,0x70,0x00,0x88,0x01,0x04,0x01,0x04,0x01,0x04,0x00,0x88,0x00,0x00},/*"c",67*/
{0x00,0x00,0x00,0x70,0x00,0x88,0x01,0x04,0x01,0x04,0x11,0x08,0x1F,0xFC,0x00,0x04},/*"d",68*/
{0x00,0x00,0x00,0xF8,0x01,0x44,0x01,0x44,0x01,0x44,0x01,0x44,0x00,0xC8,0x00,0x00},/*"e",69*/
{0x00,0x00,0x01,0x04,0x01,0x04,0x0F,0xFC,0x11,0x04,0x11,0x04,0x11,0x00,0x18,0x00},/*"f",70*/
{0x00,0x00,0x00,0xD6,0x01,0x29,0x01,0x29,0x01,0x29,0x01,0xC9,0x01,0x06,0x00,0x00},/*"g",71*/
{0x10,0x04,0x1F,0xFC,0x00,0x84,0x01,0x00,0x01,0x00,0x01,0x04,0x00,0xFC,0x00,0x04},/*"h",72*/
{0x00,0x00,0x01,0x04,0x19,0x04,0x19,0xFC,0x00,0x04,0x00,0x04,0x00,0x00,0x00,0x00},/*"i",73*/
{0x00,0x00,0x00,0x03,0x00,0x01,0x01,0x01,0x19,0x01,0x19,0xFE,0x00,0x00,0x00,0x00},/*"j",74*/
{0x10,0x04,0x1F,0xFC,0x00,0x24,0x00,0x40,0x01,0xB4,0x01,0x0C,0x01,0x04,0x00,0x00},/*"k",75*/
{0x00,0x00,0x10,0x04,0x10,0x04,0x1F,0xFC,0x00,0x04,0x00,0x04,0x00,0x00,0x00,0x00},/*"l",76*/
{0x01,0x04,0x01,0xFC,0x01,0x04,0x01,0x00,0x01,0xFC,0x01,0x04,0x01,0x00,0x00,0xFC},/*"m",77*/
{0x01,0x04,0x01,0xFC,0x00,0x84,0x01,0x00,0x01,0x00,0x01,0x04,0x00,0xFC,0x00,0x04},/*"n",78*/
{0x00,0x00,0x00,0xF8,0x01,0x04,0x01,0x04,0x01,0x04,0x01,0x04,0x00,0xF8,0x00,0x00},/*"o",79*/
{0x01,0x01,0x01,0xFF,0x00,0x85,0x01,0x04,0x01,0x04,0x00,0x88,0x00,0x70,0x00,0x00},/*"p",80*/
{0x00,0x00,0x00,0x70,0x00,0x88,0x01,0x04,0x01,0x04,0x01,0x05,0x01,0xFF,0x00,0x01},/*"q",81*/
{0x01,0x04,0x01,0x04,0x01,0xFC,0x00,0x84,0x01,0x04,0x01,0x00,0x01,0x80,0x00,0x00},/*"r",82*/
{0x00,0x00,0x00,0xCC,0x01,0x24,0x01,0x24,0x01,0x24,0x01,0x24,0x01,0x98,0x00,0x00},/*"s",83*/
{0x00,0x00,0x01,0x00,0x01,0x00,0x07,0xF8,0x01,0x04,0x01,0x04,0x00,0x00,0x00,0x00},/*"t",84*/
{0x01,0x00,0x01,0xF8,0x00,0x04,0x00,0x04,0x00,0x04,0x01,0x08,0x01,0xFC,0x00,0x04},/*"u",85*/
{0x01,0x00,0x01,0x80,0x01,0x70,0x00,0x0C,0x00,0x10,0x01,0x60,0x01,0x80,0x01,0x00},/*"v",86*/
{0x01,0xF0,0x01,0x0C,0x00,0x30,0x01,0xC0,0x00,0x30,0x01,0x0C,0x01,0xF0,0x01,0x00},/*"w",87*/
{0x00,0x00,0x01,0x04,0x01,0x8C,0x00,0x74,0x01,0x70,0x01,0x8C,0x01,0x04,0x00,0x00},/*"x",88*/
{0x01,0x01,0x01,0x81,0x01,0x71,0x00,0x0E,0x00,0x18,0x01,0x60,0x01,0x80,0x01,0x00},/*"y",89*/
{0x00,0x00,0x01,0x84,0x01,0x0C,0x01,0x34,0x01,0x44,0x01,0x84,0x01,0x0C,0x00,0x00},/*"z",90*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x3E,0xFC,0x40,0x02,0x40,0x02},/*"{",91*/
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00},/*"|",92*/
{0x00,0x00,0x40,0x02,0x40,0x02,0x3E,0xFC,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"}",93*/
{0x00,0x00,0x60,0x00,0x80,0x00,0x80,0x00,0x40,0x00,0x40,0x00,0x20,0x00,0x20,0x00},/*"~",94*/
};
const uint8_t Font3216[11][64] PROGMEM =
{
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC, /*"0",0*/
0x30,0x00,0x00,0x0C,0x30,0x00,0x00,0x0C,0x30,0x00,0x00,0x0C,0x30,0x00,0x00,0x0C,
0x30,0x00,0x00,0x0C,0x30,0x00,0x00,0x0C,0x30,0x00,0x00,0x0C,0x30,0x00,0x00,0x0C,
0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*"1",1*/
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x01,0xFF,0xFC,0x3C,0x01,0xFF,0xFC, /*"2",2*/
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x3F,0xFF,0x80,0x0C,0x3F,0xFF,0x80,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x00,0x3C,0x38,0x00,0x00,0x3C, /*"3",3*/
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0xFF,0x80,0x00,0x3F,0xFF,0x80,0x00, /*"4",4*/
0x00,0x01,0x80,0x00,0x00,0x01,0x80,0x00,0x00,0x01,0x80,0x00,0x00,0x01,0x80,0x00,
0x00,0x01,0x80,0x00,0x00,0x01,0x80,0x00,0x00,0x01,0x80,0x00,0x00,0x01,0x80,0x00,
0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0xFF,0x80,0x3C,0x3F,0xFF,0x80,0x3C, /*"5",5*/
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x30,0x01,0xFF,0xFC,0x30,0x01,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC, /*"6",6*/
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x3C,0x01,0xFF,0xFC,0x3C,0x01,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x3C,0x00,0x00,0x00, /*"7",7*/
0x30,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
0x30,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x30,0x00,0x00,0x00,
0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC, /*"8",8*/
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F,0xFF,0x80,0x3C,0x3F,0xFF,0x80,0x3C, /*"9",9*/
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,0x30,0x01,0x80,0x0C,
0x3F,0xFF,0xFF,0xFC,0x3F,0xFF,0xFF,0xFC,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /*":",10*/
0x00,0x00,0x00,0x00,0x0F,0xF0,0x0F,0xF0,0x0F,0xF0,0x0F,0xF0,0x0C,0x00,0x00,0x30,
0x0C,0x00,0x00,0x30,0x0F,0xF0,0x0F,0xF0,0x0F,0xF0,0x0F,0xF0,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}
};
void command(uint8_t cmd){
digitalWrite(OLED_DC, LOW);
SPIWrite(&cmd, 1);
}
void SPIWrite(uint8_t *buffer, int bufferLength) {
int i;
for (i = 0; i < bufferLength; i++) {
SPI.transfer(buffer[i]);
}
}
void SH1106_begin()
{
pinMode(OLED_RST, OUTPUT);
pinMode(OLED_DC, OUTPUT);
pinMode(OLED_CS, OUTPUT);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV128);
digitalWrite(OLED_CS, LOW);
digitalWrite(OLED_RST, HIGH);
delay(10);
digitalWrite(OLED_RST, LOW);
delay(10);
digitalWrite(OLED_RST, HIGH);
command(0xAE);//--turn off oled panel
command(0x02);//---set low column address
command(0x10);//---set high column address
command(0x40);//--set start line address Set Mapping RAM Display Start Line (0x00~0x3F)
command(0x81);//--set contrast control register
command(0xA0);//--Set SEG/Column Mapping
command(0xC0);//Set COM/Row Scan Direction
command(0xA6);//--set normal display
command(0xA8);//--set multiplex ratio(1 to 64)
command(0x3F);//--1/64 duty
command(0xD3);//-set display offset Shift Mapping RAM Counter (0x00~0x3F)
command(0x00);//-not offset
command(0xd5);//--set display clock divide ratio/oscillator frequency
command(0x80);//--set divide ratio, Set Clock as 100 Frames/Sec
command(0xD9);//--set pre-charge period
command(0xF1);//Set Pre-Charge as 15 Clocks & Discharge as 1 Clock
command(0xDA);//--set com pins hardware configuration
command(0x12);
command(0xDB);//--set vcomh
command(0x40);//Set VCOM Deselect Level
command(0x20);//-Set Page Addressing Mode (0x00/0x01/0x02)
command(0x02);//
command(0xA4);// Disable Entire Display On (0xa4/0xa5)
command(0xA6);// Disable Inverse Display On (0xa6/a7)
command(0xAF);//--turn on oled panel
}
void SH1106_clear(uint8_t* buffer)
{
int i;
for(i = 0;i < WIDTH * HEIGHT / 8;i++)
{
buffer[i] = 0;
}
}
void SH1106_invert(uint8_t* buffer)
{
int i;
for(i = 0;i < WIDTH * HEIGHT / 8;i++)
{
buffer[i] = ~buffer[i];
}
}
void SH1106_pixel(int x, int y, char color, uint8_t* buffer)
{
if(x > WIDTH || y > HEIGHT)return ;
if(color)
buffer[x+(y/8)*WIDTH] |= 1<<(y%8);
else
buffer[x+(y/8)*WIDTH] &= ~(1<<(y%8));
}
void SH1106_char1616(uint8_t x, uint8_t y, uint8_t chChar, uint8_t* buffer)
{
uint8_t i, j;
uint8_t chTemp = 0, y0 = y, chMode = 0;
for (i = 0; i < 32; i ++) {
chTemp = pgm_read_byte(&Font1612[chChar - 0x30][i]);
for (j = 0; j < 8; j ++) {
chMode = chTemp & 0x80? 1 : 0;
SH1106_pixel(x, y, chMode, buffer);
chTemp <<= 1;
y ++;
if ((y - y0) == 16) {
y = y0;
x ++;
break;
}
}
}
}
void SH1106_char(uint8_t x, uint8_t y, uint8_t acsii, uint8_t size, uint8_t mode, uint8_t* buffer)
{
uint8_t i, j, y0=y;
char temp;
uint8_t ch = acsii - ' ';
for(i = 0;i<size;i++) {
if(size == 12)
{
if(mode)temp = pgm_read_byte(&Font1206[ch][i]);
else temp = ~pgm_read_byte(&Font1206[ch][i]);
}
else
{
if(mode)temp = pgm_read_byte(&Font1608[ch][i]);
else temp = ~pgm_read_byte(&Font1608[ch][i]);
}
for(j =0;j<8;j++)
{
if(temp & 0x80) SH1106_pixel(x, y, 1, buffer);
else SH1106_pixel(x, y, 0, buffer);
temp <<= 1;
y++;
if((y-y0) == size)
{
y = y0;
x++;
break;
}
}
}
}
void SH1106_string(uint8_t x, uint8_t y, const char *pString, uint8_t Size, uint8_t Mode, uint8_t* buffer)
{
while (*pString != '\0') {
if (x > (WIDTH - Size / 2)) {
x = 0;
y += Size;
if (y > (HEIGHT - Size)) {
y = x = 0;
}
}
SH1106_char(x, y, *pString, Size, Mode, buffer);
x += Size / 2;
pString++;
}
}
void SH1106_char3216(uint8_t x, uint8_t y, uint8_t chChar, uint8_t* buffer)
{
uint8_t i, j;
uint8_t chTemp = 0, y0 = y, chMode = 0;
for (i = 0; i < 64; i++) {
chTemp = pgm_read_byte(&Font3216[chChar - 0x30][i]);
for (j = 0; j < 8; j++) {
chMode = chTemp & 0x80? 1 : 0;
SH1106_pixel(x, y, chMode, buffer);
chTemp <<= 1;
y++;
if ((y - y0) == 32) {
y = y0;
x++;
break;
}
}
}
}
void SH1106_bitmap(uint8_t x, uint8_t y, const uint8_t *pBmp, uint8_t chWidth, uint8_t chHeight, uint8_t* buffer)
{
uint8_t i,j,byteWidth = (chWidth + 7)/8;
for(j = 0;j < chHeight;j++){
for(i = 0;i <chWidth;i ++){
if(pgm_read_byte(pBmp +j*byteWidth+i/8) & (128 >> (i & 7))){
SH1106_pixel(x+i,y+j,1,buffer);
}
}
}
}
void SH1106_display(uint8_t* buffer)
{
uint8_t page;
uint8_t *pBuf = buffer;
for (page = 0; page < 8; page++) {
/* set page address */
command(0xB0 + page);
/* set low column address */
command(0x02);
/* set high column address */
command(0x10);
/* write data */
digitalWrite(OLED_DC, HIGH);
SPIWrite(pBuf, WIDTH);
pBuf += WIDTH;
}
}
void SH1106_setContrast(char contrast) {
command(0x81);
command(contrast);
}
| 56.718447
| 113
| 0.649127
|
insightmachineslab
|
6d463322ab6406de9710253ff10e0f8bdc90c5d8
| 675
|
cpp
|
C++
|
DAY-2/ModularMultiplicativeInverse.cpp
|
varshitha1707/DailyCoding
|
d8a974cf5742cc1a77d638eb188012bb32f31d5f
|
[
"MIT"
] | 5
|
2021-02-09T08:03:25.000Z
|
2021-06-27T15:29:11.000Z
|
DAY-2/ModularMultiplicativeInverse.cpp
|
varshitha1707/DailyCoding
|
d8a974cf5742cc1a77d638eb188012bb32f31d5f
|
[
"MIT"
] | null | null | null |
DAY-2/ModularMultiplicativeInverse.cpp
|
varshitha1707/DailyCoding
|
d8a974cf5742cc1a77d638eb188012bb32f31d5f
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int gcd(int a, int m)
{
if (a == 0)
return m;
if (m == 0)
return a;
if (a == m)
return a;
if (a > m)
return gcd(a-m, m);
return gcd(a, m-a);
}
void mulinv(int x, int a, int m )
{
for(int x=1; x<m;x++)
{
int c= a*x;
if(c%m == 1)
{
cout<<x;
break;
}
}
}
int main()
{
int x,a,m;
cout<<"Enter a:\n";
cin>>a;
cout<<"Enter m:\n";
cin>>m;
if(gcd(a,m)==1)
{
cout<<"The modular multiplicative inverse of "<<a<<" and "<<m<<" is: ";
mulinv( x, a, m);
}
return 0;
}
| 12.735849
| 78
| 0.402963
|
varshitha1707
|
6d47c266848604e7ceed273a72119895cf29648d
| 523
|
cpp
|
C++
|
Ejercicios/Ejercicio6 - Calculadora/calculadora.cpp
|
YerlinSarabia/cpp
|
8bd4ab4eb04f7891878d324e45b1b4d76851db12
|
[
"MIT"
] | null | null | null |
Ejercicios/Ejercicio6 - Calculadora/calculadora.cpp
|
YerlinSarabia/cpp
|
8bd4ab4eb04f7891878d324e45b1b4d76851db12
|
[
"MIT"
] | null | null | null |
Ejercicios/Ejercicio6 - Calculadora/calculadora.cpp
|
YerlinSarabia/cpp
|
8bd4ab4eb04f7891878d324e45b1b4d76851db12
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int a=0, b=0;
int suma, multiplicacion, resta, division;
cout << "Ingrese el valor de a: "<<endl;
cin >> a;
cout << "Ingrese el valor de b: "<<endl;
cin >>b;
suma = a+b;
resta = a-b;
multiplicacion = a*b;
division = a/b;
cout << "La suma es: "<< suma <<endl;
cout << "La resta es: "<< resta <<endl;
cout << "La multiplicacion es: "<< multiplicacion <<endl;
cout << "La division es: "<< division <<endl;
return 0;
}
| 19.37037
| 58
| 0.590822
|
YerlinSarabia
|
6d47fe5bd0305973800416890dbed87618429372
| 565
|
hpp
|
C++
|
include/crocoddyl/multibody/costs/frame-force.hpp
|
iit-DLSLab/crocoddyl
|
2b8b731fae036916ff9b4ce3969e2c96c009593c
|
[
"BSD-3-Clause"
] | 1
|
2019-12-21T12:11:15.000Z
|
2019-12-21T12:11:15.000Z
|
include/crocoddyl/multibody/costs/frame-force.hpp
|
iit-DLSLab/crocoddyl
|
2b8b731fae036916ff9b4ce3969e2c96c009593c
|
[
"BSD-3-Clause"
] | null | null | null |
include/crocoddyl/multibody/costs/frame-force.hpp
|
iit-DLSLab/crocoddyl
|
2b8b731fae036916ff9b4ce3969e2c96c009593c
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2018-2019, LAAS-CNRS
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#ifndef CROCODDYL_MULTIBODY_COSTS_FRAME_FORCE_HPP_
#define CROCODDYL_MULTIBODY_COSTS_FRAME_FORCE_HPP_
// TODO: CostModelForce CostDataFor
// TODO: CostModelForceLinearCost CostDataForceCone
#endif // CROCODDYL_MULTIBODY_COSTS_FRAME_FORCE_HPP_
| 35.3125
| 79
| 0.589381
|
iit-DLSLab
|
6d4892181db2d59362f48d488d95d100aeee3bcc
| 7,777
|
cc
|
C++
|
test/libponyc/codegen.cc
|
rtpax/ponyc
|
5af6626fcc894ef201bebfac712c454e6c8b14c9
|
[
"BSD-2-Clause"
] | 4,304
|
2016-02-01T14:46:51.000Z
|
2022-03-29T15:17:15.000Z
|
test/libponyc/codegen.cc
|
rtpax/ponyc
|
5af6626fcc894ef201bebfac712c454e6c8b14c9
|
[
"BSD-2-Clause"
] | 2,889
|
2016-02-01T11:11:07.000Z
|
2022-03-31T20:59:39.000Z
|
test/libponyc/codegen.cc
|
rtpax/ponyc
|
5af6626fcc894ef201bebfac712c454e6c8b14c9
|
[
"BSD-2-Clause"
] | 534
|
2016-02-01T12:42:45.000Z
|
2022-03-22T16:45:45.000Z
|
#include <gtest/gtest.h>
#include <platform.h>
#include <codegen/gentype.h>
#include <../libponyrt/mem/pool.h>
#include "util.h"
#include "llvm_config_begin.h"
#include <llvm/IR/Constants.h>
#include <llvm/IR/Module.h>
#include "llvm_config_end.h"
#define TEST_COMPILE(src) DO(test_compile(src, "ir"))
class CodegenTest : public PassTest
{
};
TEST_F(CodegenTest, PackedStructIsPacked)
{
const char* src =
"struct \\packed\\ Foo\n"
" var a: U8 = 0\n"
" var b: U32 = 0\n"
"actor Main\n"
" new create(env: Env) =>\n"
" Foo";
TEST_COMPILE(src);
reach_t* reach = compile->reach;
reach_type_t* foo = reach_type_name(reach, "Foo");
ASSERT_TRUE(foo != NULL);
LLVMTypeRef type = ((compile_type_t*)foo->c_type)->structure;
ASSERT_TRUE(LLVMIsPackedStruct(type));
}
TEST_F(CodegenTest, NonPackedStructIsntPacked)
{
const char* src =
"struct Foo\n"
" var a: U8 = 0\n"
" var b: U32 = 0\n"
"actor Main\n"
" new create(env: Env) =>\n"
" Foo";
TEST_COMPILE(src);
reach_t* reach = compile->reach;
reach_type_t* foo = reach_type_name(reach, "Foo");
ASSERT_TRUE(foo != NULL);
LLVMTypeRef type = ((compile_type_t*)foo->c_type)->structure;
ASSERT_TRUE(!LLVMIsPackedStruct(type));
}
TEST_F(CodegenTest, BoxBoolAsUnionIntoTuple)
{
// From #2191
const char* src =
"type U is (Bool | C)\n"
"class C\n"
" fun apply(): (I32, U) =>\n"
" (0, false)\n"
"actor Main\n"
" new create(env: Env) =>\n"
" C()";
TEST_COMPILE(src);
ASSERT_TRUE(compile != NULL);
}
TEST_F(CodegenTest, UnionOfTuplesToTuple)
{
const char* src =
"actor Main\n"
" new create(env: Env) =>\n"
" let a: ((Main, Env) | (Env, Main)) = (this, env)\n"
" let b: ((Main | Env), (Main | Env)) = a";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, ViewpointAdaptedFieldReach)
{
// From issue #2238
const char* src =
"class A\n"
"class B\n"
" var f: (A | None) = None\n"
"actor Main\n"
" new create(env: Env) =>\n"
" let l = B\n"
" l.f = A";
TEST_COMPILE(src);
}
extern "C"
{
EXPORT_SYMBOL void* test_custom_serialisation_get_object()
{
uint64_t* i = POOL_ALLOC(uint64_t);
*i = 0xDEADBEEF10ADBEE5;
return i;
}
EXPORT_SYMBOL void test_custom_serialisation_free_object(uint64_t* p)
{
POOL_FREE(uint64_t, p);
}
EXPORT_SYMBOL void test_custom_serialisation_serialise(uint64_t* p,
unsigned char* bytes)
{
*(uint64_t*)(bytes) = *p;
}
EXPORT_SYMBOL void* test_custom_serialisation_deserialise(unsigned char* bytes)
{
uint64_t* p = POOL_ALLOC(uint64_t);
*p = *(uint64_t*)(bytes);
return p;
}
EXPORT_SYMBOL char test_custom_serialisation_compare(uint64_t* p1, uint64_t* p2)
{
return *p1 == *p2;
}
}
TEST_F(CodegenTest, DoNotOptimiseApplyPrimitive)
{
const char* src =
"actor Main\n"
" new create(env: Env) =>\n"
" DoNotOptimise[I64](0)";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, DescTable)
{
const char* src =
"class C1\n"
"class C2\n"
"class C3\n"
"actor A1\n"
"actor A2\n"
"actor A3\n"
"primitive P1\n"
"primitive P2\n"
"primitive P3\n"
"actor Main\n"
" new create(env: Env) =>\n"
// Reach various types.
" (C1, A1, P1)\n"
" (C2, A2, P2)\n"
" (C3, A3, P3)\n"
" (C1, I8)\n"
" (C2, I16)\n"
" (C3, I32)";
TEST_COMPILE(src);
auto module = llvm::unwrap(compile->module);
auto table_glob = module->getNamedGlobal("__DescTable");
ASSERT_NE(table_glob, nullptr);
ASSERT_TRUE(table_glob->hasInitializer());
auto desc_table = llvm::dyn_cast_or_null<llvm::ConstantArray>(
table_glob->getInitializer());
ASSERT_NE(desc_table, nullptr);
for(unsigned int i = 0; i < desc_table->getNumOperands(); i++)
{
// Check that for each element of the table, `desc_table[i]->id == i`.
auto table_element = desc_table->getOperand(i);
ASSERT_EQ(table_element->getType(), llvm::unwrap(compile->descriptor_ptr));
if(table_element->isNullValue())
continue;
auto elt_bitcast = llvm::dyn_cast_or_null<llvm::ConstantExpr>(
table_element);
ASSERT_NE(elt_bitcast, nullptr);
ASSERT_EQ(elt_bitcast->getOpcode(), llvm::Instruction::BitCast);
auto desc_ptr = llvm::dyn_cast_or_null<llvm::GlobalVariable>(
elt_bitcast->getOperand(0));
ASSERT_NE(desc_ptr, nullptr);
ASSERT_TRUE(desc_ptr->hasInitializer());
auto desc = llvm::dyn_cast_or_null<llvm::ConstantStruct>(
desc_ptr->getInitializer());
ASSERT_NE(desc, nullptr);
auto type_id = llvm::dyn_cast_or_null<llvm::ConstantInt>(
desc->getOperand(0));
ASSERT_NE(type_id, nullptr);
ASSERT_EQ(type_id->getBitWidth(), 32);
ASSERT_EQ(type_id->getZExtValue(), i);
}
}
TEST_F(CodegenTest, RecoverCast)
{
// From issue #2639
const char* src =
"class A\n"
" new create() => None\n"
"actor Main\n"
" new create(env: Env) =>\n"
" let x: ((None, None) | (A iso, None)) =\n"
" if false then\n"
" (None, None)\n"
" else\n"
" recover (A, None) end\n"
" end";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, VariableDeclNestedTuple)
{
// From issue #2662
const char* src =
"actor Main\n"
" new create(env: Env) =>\n"
" let array = Array[((U8, U8), U8)]\n"
" for ((a, b), c) in array.values() do\n"
" None\n"
" end";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, TupleRemoveUnreachableBlockInLoop)
{
// From issue #2760
const char* src =
"actor Main\n"
" new create(env: Env) =>\n"
" var token = U8(1)\n"
" repeat\n"
" (token, let source) = (U8(1), U8(2))\n"
" until token == 2 end";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, TupleRemoveUnreachableBlock)
{
// From issue #2735
const char* src =
"actor Main\n"
" new create(env: Env) =>\n"
" if true then\n"
" (let f, let g) = (U8(2), U8(3))\n"
" end";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, RedundantUnionInForLoopIteratorValueType)
{
// From issue #2736
const char* src =
"type T is (U8 | U8)\n"
"actor Main\n"
" new create(env: Env) =>\n"
" let i = I\n"
" for m in i do\n"
" None\n"
" end\n"
"class ref I is Iterator[T]\n"
" new create() => None\n"
" fun ref has_next(): Bool => false\n"
" fun ref next(): T ? => error";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, WhileLoopBreakOnlyValueNeeded)
{
// From issue #2788
const char* src =
"actor Main\n"
"new create(env: Env) =>\n"
"let x = while true do break true else false end\n"
"if x then None end";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, WhileLoopBreakOnlyInBranches)
{
// From issue #2788
const char* src =
"actor Main\n"
"new create(env: Env) =>\n"
"while true do\n"
"if true then\n"
"break None\n"
"else\n"
"break\n"
"end\n"
"else\n"
"return\n"
"end";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, RepeatLoopBreakOnlyValueNeeded)
{
// From issue #2788
const char* src =
"actor Main\n"
"new create(env: Env) =>\n"
"let x = repeat break true until false else false end\n"
"if x then None end";
TEST_COMPILE(src);
}
TEST_F(CodegenTest, RepeatLoopBreakOnlyInBranches)
{
// From issue #2788
const char* src =
"actor Main\n"
"new create(env: Env) =>\n"
"repeat\n"
"if true then\n"
"break None\n"
"else\n"
"break\n"
"end\n"
"until\n"
"false\n"
"else\n"
"return\n"
"end";
TEST_COMPILE(src);
}
| 20.738667
| 80
| 0.593545
|
rtpax
|
6d4925357d9def9813dcafdcaf6fcfed4bf66cf6
| 4,635
|
cc
|
C++
|
modules/image/plugin/PiiImageUnwarpOperation.cc
|
topiolli/into
|
f0a47736f5c93dd32e89e7aad34152ae1afc5583
|
[
"BSD-3-Clause"
] | 14
|
2015-01-19T22:14:18.000Z
|
2020-04-13T23:27:20.000Z
|
modules/image/plugin/PiiImageUnwarpOperation.cc
|
topiolli/into
|
f0a47736f5c93dd32e89e7aad34152ae1afc5583
|
[
"BSD-3-Clause"
] | null | null | null |
modules/image/plugin/PiiImageUnwarpOperation.cc
|
topiolli/into
|
f0a47736f5c93dd32e89e7aad34152ae1afc5583
|
[
"BSD-3-Clause"
] | 14
|
2015-01-16T05:43:15.000Z
|
2019-01-29T07:57:11.000Z
|
/* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#include "PiiImageUnwarpOperation.h"
#include "PiiImageDistortions.h"
#include <PiiYdinTypes.h>
PiiImageUnwarpOperation::Data::Data() :
dFocalLength(1e100),
dCameraDistance(1),
dRadius(0),
dMaxSectorAngle(0),
dCenter(NAN),
bRadiusConnected(false),
bDistanceConnected(false),
bCenterConnected(false)
{
}
PiiImageUnwarpOperation::PiiImageUnwarpOperation() :
PiiDefaultOperation(new Data)
{
setThreadCount(1);
PII_D;
addSocket(d->pImageInput = new PiiInputSocket("image"));
addSocket(d->pRadiusInput = new PiiInputSocket("radius"));
addSocket(d->pDistanceInput = new PiiInputSocket("distance"));
addSocket(d->pCenterInput = new PiiInputSocket("center"));
d->pRadiusInput->setOptional(true);
d->pDistanceInput->setOptional(true);
d->pCenterInput->setOptional(true);
addSocket(d->pImageOutput = new PiiOutputSocket("image"));
addSocket(d->pRadiusOutput = new PiiOutputSocket("radius"));
addSocket(d->pDistanceOutput = new PiiOutputSocket("distance"));
addSocket(d->pAngleOutput = new PiiOutputSocket("start angle"));
addSocket(d->pSectorOutput = new PiiOutputSocket("sector"));
addSocket(d->pScaleOutput = new PiiOutputSocket("scale"));
}
void PiiImageUnwarpOperation::check(bool reset)
{
PII_D;
PiiDefaultOperation::check(reset);
d->bRadiusConnected = d->pRadiusInput->isConnected();
d->bDistanceConnected = d->pDistanceInput->isConnected();
d->bCenterConnected = d->pCenterInput->isConnected();
}
void PiiImageUnwarpOperation::process()
{
PII_D;
PiiVariant obj = readInput();
switch (obj.type())
{
PII_ALL_IMAGE_CASES(unwarp, obj);
default:
PII_THROW_UNKNOWN_TYPE(d->lstInputs[0]);
}
}
template <class T> void PiiImageUnwarpOperation::unwarp(const PiiVariant& obj)
{
PII_D;
const PiiMatrix<T> image = obj.valueAs<PiiMatrix<T> >();
double
dRadius = d->dRadius,
dDistance = d->dCameraDistance,
dSector = d->dMaxSectorAngle / 180 * M_PI,
dStartAngle = 0,
dCenter = d->dCenter;
if (d->bRadiusConnected)
dRadius = PiiYdin::primitiveAs<double>(d->pRadiusInput);
if (d->bCenterConnected)
dCenter = PiiYdin::primitiveAs<double>(d->pCenterInput);
if (d->bDistanceConnected)
dDistance = PiiYdin::primitiveAs<double>(d->pDistanceInput);
PiiMatrix<T> matResult(PiiImage::unwarpCylinder(image,
d->dFocalLength,
dCenter,
&dDistance,
&dRadius,
&dSector,
&dStartAngle));
d->pImageOutput->emitObject(matResult);
d->pScaleOutput->emitObject(PiiMatrix<double>(1,2,
dSector / matResult.columns(),
(dDistance - dRadius) / d->dFocalLength));
d->pDistanceOutput->emitObject(dDistance);
d->pRadiusOutput->emitObject(dRadius);
d->pAngleOutput->emitObject(dStartAngle);
d->pSectorOutput->emitObject(dSector);
}
void PiiImageUnwarpOperation::setFocalLength(double focalLength) { _d()->dFocalLength = focalLength; }
double PiiImageUnwarpOperation::focalLength() const { return _d()->dFocalLength; }
void PiiImageUnwarpOperation::setCameraDistance(double cameraDistance) { _d()->dCameraDistance = cameraDistance; }
double PiiImageUnwarpOperation::cameraDistance() const { return _d()->dCameraDistance; }
void PiiImageUnwarpOperation::setRadius(double radius) { _d()->dRadius = radius; }
double PiiImageUnwarpOperation::radius() const { return _d()->dRadius; }
void PiiImageUnwarpOperation::setMaxSectorAngle(double maxSectorAngle) { _d()->dMaxSectorAngle = maxSectorAngle; }
double PiiImageUnwarpOperation::maxSectorAngle() const { return _d()->dMaxSectorAngle; }
void PiiImageUnwarpOperation::setCenter(double center) { _d()->dCenter = center; }
double PiiImageUnwarpOperation::center() const { return _d()->dCenter; }
| 37.682927
| 114
| 0.681122
|
topiolli
|
6d5370dd199822da8fadcae3abb189f104d0662a
| 17,003
|
cpp
|
C++
|
GameJam_v3.2/GameEngineBase/gameObject.cpp
|
aditgoyal19/Tropical-Go-Kart-Bananas
|
ed3c0489402f8a559c77b56545bd8ebc79c4c563
|
[
"MIT"
] | null | null | null |
GameJam_v3.2/GameEngineBase/gameObject.cpp
|
aditgoyal19/Tropical-Go-Kart-Bananas
|
ed3c0489402f8a559c77b56545bd8ebc79c4c563
|
[
"MIT"
] | null | null | null |
GameJam_v3.2/GameEngineBase/gameObject.cpp
|
aditgoyal19/Tropical-Go-Kart-Bananas
|
ed3c0489402f8a559c77b56545bd8ebc79c4c563
|
[
"MIT"
] | null | null | null |
#include "GameObject.h"
#include "softBodyComp.h"
#include "mediator.h"
#include "global.h"
#include <Physics2012\Vehicle\DriverInput\Default\hkpVehicleDefaultAnalogDriverInput.h>
// Initial value of the first GameObject ID
// (i.e. the unique IDs of the objects will start at this number)
// Note that using an unsigned int, and assuming that it's 32 bits
// means that it may potentially wrap around at some point.
// (but you'd have to create 4 billion objects, first)
static const unsigned int FIRSTGAMEOBJECTID = 1000;
unsigned int GameObject::m_nextID = FIRSTGAMEOBJECTID;
// Called by the constructors
void GameObject::m_Init(void)
{
// Assign ID here
this->m_ID = this->m_nextID;
this->m_nextID++; // Increment
this->name = "no name";
this->plyFileName = "";
this->specularShininess = 1.0f; // "Meh" shiny
this->specularStrength = 1.0f; // Not shiny
this->isWireFrame = false;
this->isSkyMap = false;
this->hasAlphaMap = false;
this->isBlend = false;
this->isDiscard = false;
this->isTextureMix = false;
this->isPlayer = false;
playerId = -1; //Not a player
this->textureMixval = 0.0f;
this->BlendVal = 1.0f;
isActive = true;
inputY = 0.0f; //Accelerate
inputX = 0.0f; //Steer
motionState = 0;
return;
}
GameObject::GameObject()
{
this->m_Init();
Vcounter = 0;
return;
}
GameObject::~GameObject()
{
//delete data;
return;
}
void GameObject::Update( float deltaTime )
{
// Insert behaviour code in here
int sexyBreakpoint = 0;
physicsComp->UpdatePhysics(deltaTime);
return;
}
unsigned int GameObject::getID(void)
{
return this->m_ID;
}
float GameObject::getMaxExtent()
{
return data->getMaxExtent();
}
void GameObject::attachModelData(ModelData* value)
{
data = value;
this->MDataVector.push_back(value);
}
ModelData* GameObject::getModelData(int index)
{
return MDataVector[index];
}
std::string GameObject::getName()
{
return name;
}
std::wstring GameObject::getPlyFileName()
{
return data->getFileName();
}
void GameObject::setName(std::string value)
{
name = value;
}
void GameObject::setPlyFileName(std::string value)
{
plyFileName = value;
}
// Specular component (Shininess)
void GameObject::setSpecularShininess(float value)
{
specularShininess = value;
}
void GameObject::setSpecularStrength(float value)
{
specularStrength = value;
}
std::vector<BoundingBox> GameObject :: getBoundingBoxes()
{
std::vector<BoundingBox> resized = data->boundingboxes;
/* for (int i = 0; i < resized.size(); i++)
{
resized[i].setminX(resized[i].getminX() + position.x);
resized[i].setmaxX(resized[i].getmaxX() + position.x);
resized[i].setminY(resized[i].getminY() + position.y);
resized[i].setmaxY(resized[i].getmaxY() + position.y);
resized[i].setminZ(resized[i].getminZ() + position.z);
resized[i].setmaxZ(resized[i].getmaxZ() + position.z);
}*/
return resized;
}
void GameObject::setwireframe(bool value)
{
isWireFrame = value;
}
//Added for matrix stack
bool GameObject::hasChildObjects()
{
if (childObjects.size() > 0)
return true;
else
return false;
}
void GameObject::attachChildObject(GameObject* obj)
{
childObjects.push_back(obj);
}
std::vector<GameObject*> GameObject::getChildObjects()
{
return childObjects;
}
std::vector<BoundingBox> GameObject::getBoundingBoxesById(int id)
{
std::vector<int> copyIndex = data->boundingBoxgrp[id];
std::vector<BoundingBox> resized ;
for(int i = 0 ; i < copyIndex.size() ; i++)
{
BoundingBox b = data->boundingboxes[copyIndex[i]];
/* b.setminX(b.getminX() + position.x);
b.setmaxX(b.getmaxX() + position.x);
b.setminY(b.getminY() + position.y);
b.setmaxY(b.getmaxY() + position.y);
b.setminZ(b.getminZ() + position.z);
b.setmaxZ(b.getmaxZ() + position.z);*/
resized.push_back(b);
}
return resized;
}
void GameObject::setIsSkyMap(bool value)
{
isSkyMap = value;
}
void GameObject::setIsBlend(bool value)
{
isBlend = value;
}
void GameObject::setIsDiscard(bool value)
{
isDiscard = value;
}
void GameObject::setIsTextureMix(bool value)
{
isTextureMix = value;
}
void GameObject::setTextureMix(float value)
{
textureMixval = value;
}
void GameObject::setBlendVal(float value)
{
BlendVal = value;
}
void GameObject::setHasAlphaMap(bool value)
{
hasAlphaMap = value;
}
void GameObject::reCalculateBounds(glm::mat4 worldMatrix)
{
data->reCalculateBounds(worldMatrix);
}
void GameObject::attachPhysics(IPhysicsComp* value)
{
physicsComp = value;
this->physicsCompVector.push_back(value);
}
void GameObject::render(glm::mat4& matWorld,glm::mat4& matView, Shader* shaderData, int pass , glm::mat4& depthP, glm::mat4& depthV )
{
if(isActive)
{
//Pack data to be sent to shader /////////////////////////////////////////////////////////////
std::map<std::string , UniformData> uniformData;
if(pass == 1)
{
if (isWireFrame)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);//GL_FILL
}
int offset = 0;
if(name == "Vehicle")
offset = 1;
//Loops through all vectors
for(int i = 0 ; i < MDataVector.size() - offset; i++)
{
UniformData data;
matWorld = glm::mat4(1.0);
MDataVector[i]->activateTextures(uniformData);
//physicsComp->SetModelMatrix(mat);
physicsCompVector[i]->SetModelMatrix(matWorld);
data.mat4Data = matWorld;
uniformData["WorldMatrix"] = data;
data.mat4Data = matView;
uniformData["ViewMatrix"] = data;
if(shaderName == "simple")
{
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
glm::mat4 depthMVP = depthP * depthV * matWorld;
glm::mat4 depthBiasMVP = biasMatrix * depthMVP;
data.mat4Data = depthBiasMVP;
uniformData["depthMVP"] = data;
}
shaderData->setUniformVariablesInBulk(uniformData);
MDataVector[i]->render();
if(this->name.substr(0,4) == "Soft")
{
CVertex_fXYZW* verts = MDataVector[i]->beginMapping();
unsigned int numVerts = MDataVector[i]->GetNumberOfVerticies();
for (unsigned int idxVert = 0; idxVert < numVerts; idxVert++)
{
((SoftBodyPhyComp*)physicsCompVector[i])->GetPosition(idxVert, verts[idxVert]);
}
MDataVector[i]->endMapping();
}
}
}
else if(pass == 2) //Final Pass
{
//Render only quad here
//Pack data to be sent to shader /////////////////////////////////////////////////////////////
std::map<std::string , UniformData> uniformData;
UniformData data;
//Pass 1 for depth texture
//Loops through all vectors
for(int i = 0 ; i < MDataVector.size(); i++)
{
//MDataVector[i]->activateTextures(uniformData);
physicsCompVector[i]->SetModelMatrix(matWorld);
UniformData data;
data.mat4Data = matWorld;
uniformData["WorldMatrix"] = data;
data.mat4Data = matView;
uniformData["ViewMatrix"] = data;
//shaderData[vec_pRenderedObjects[index]->shaderName]->setUniformVariablesInBulk(uniformData);
myGlobalShader->setUniformVariablesInBulk(uniformData, true);
MDataVector[i]->render();
}
}
else if(pass == 3)
{
//Pack data to be sent to shader /////////////////////////////////////////////////////////////
std::map<std::string , UniformData> uniformData;
for(int i = 0 ; i < MDataVector.size(); i++)
{
//MDataVector[i]->activateTextures(uniformData);
physicsCompVector[i]->SetModelMatrix(matWorld);
UniformData data;
glm::mat4 depthMVP = depthP * depthV * matWorld;
data.mat4Data = depthMVP;
::myGlobalShader->setUniformVariable("depthMVP",data, false);
//shaderData[vec_pRenderedObjects[index]->shaderName]->setUniformVariablesInBulk(uniformData);
//myGlobalShader->setUniformVariablesInBulk(uniformData);
MDataVector[i]->render();
}
}else if(pass == 4)
{
if (isWireFrame)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);//GL_FILL
}
if(name == "Vehicle")
{
//Loops through all vectors
for(int i = MDataVector.size() - 2 ; i < MDataVector.size() - 1; i++)
{
UniformData data;
matWorld = glm::mat4(1.0);
MDataVector[i+1]->activateTextures(uniformData);
//physicsComp->SetModelMatrix(mat);
physicsCompVector[i]->SetModelMatrix(matWorld);
data.mat4Data = matWorld;
uniformData["WorldMatrix"] = data;
data.mat4Data = matView;
uniformData["ViewMatrix"] = data;
if(shaderName == "simple")
{
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
glm::mat4 depthMVP = depthP * depthV * matWorld;
glm::mat4 depthBiasMVP = biasMatrix * depthMVP;
data.mat4Data = depthBiasMVP;
uniformData["depthMVP"] = data;
}
shaderData->setUniformVariablesInBulk(uniformData);
MDataVector[i+1]->render();
if(this->name.substr(0,4) == "Soft")
{
CVertex_fXYZW* verts = MDataVector[i]->beginMapping();
unsigned int numVerts = MDataVector[i]->GetNumberOfVerticies();
for (unsigned int idxVert = 0; idxVert < numVerts; idxVert++)
{
((SoftBodyPhyComp*)physicsCompVector[i])->GetPosition(idxVert, verts[idxVert]);
}
MDataVector[i]->endMapping();
}
}
}
else
{
//Loops through all vectors
for(int i = 0 ; i < MDataVector.size(); i++)
{
UniformData data;
matWorld = glm::mat4(1.0);
MDataVector[i]->activateTextures(uniformData);
//physicsComp->SetModelMatrix(mat);
physicsCompVector[i]->SetModelMatrix(matWorld);
data.mat4Data = matWorld;
uniformData["WorldMatrix"] = data;
data.mat4Data = matView;
uniformData["ViewMatrix"] = data;
if(shaderName == "simple")
{
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
glm::mat4 depthMVP = depthP * depthV * matWorld;
glm::mat4 depthBiasMVP = biasMatrix * depthMVP;
data.mat4Data = depthBiasMVP;
uniformData["depthMVP"] = data;
}
shaderData->setUniformVariablesInBulk(uniformData);
MDataVector[i]->render();
if(this->name.substr(0,4) == "Soft")
{
CVertex_fXYZW* verts = MDataVector[i]->beginMapping();
unsigned int numVerts = MDataVector[i]->GetNumberOfVerticies();
for (unsigned int idxVert = 0; idxVert < numVerts; idxVert++)
{
((SoftBodyPhyComp*)physicsCompVector[i])->GetPosition(idxVert, verts[idxVert]);
}
MDataVector[i]->endMapping();
}
}
}
}
}
}
void GameObject::updatePhysicAttribute(std::string type , Vector3D value)
{
//if(name == "Vehicle")
//{
// if(type=="ACCELERATION")
// {
// m_vehicleInstance->getChassis()->activate();
// std::cout<<"Speed "<<m_vehicleInstance->calcKMPH()<<std::endl;
// hkReal deltaX = 0.0f;
// hkReal deltaY = 0.0f;
// const hkReal steerSpeed = 10.0f;
// hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_vehicleInstance->m_deviceStatus;
// if(value.z < 0.0)
// {
// //Accelerate
// std::cout<<"Accelerate"<<std::endl;
// deltaY = 0.5f;
// //if(m_vehicleInstance->m_torque < 20.0f)
// //m_vehicleInstance->m_torque += 0.5f;
// }
// else if(value.x < 0.0)
// {
// //Turn Left
// std::cout<<"Turn Left"<<std::endl;
// deltaX -= steerSpeed;
// deviceStatus->m_positionX += hkMath::clamp( deltaX, hkReal(-5.0f), hkReal(5.0f));
// }
// else if(value.x > 0.0)
// {
// //Turn right
// std::cout<<"Turn Right"<<std::endl;
// deltaX += steerSpeed;
// }
// else
// {
// //Brakes
// std::cout<<"Brakes !!"<<std::endl;
// deltaY = -0.5f;
// //if(m_vehicleInstance->m_torque > 0.0f)
// //m_vehicleInstance->m_torque -= 0.5f;
// }
// deviceStatus->m_positionY += deltaY;//hkMath::clamp( deltaY, hkReal(-1.0f), hkReal(1.0f));
// deviceStatus->m_positionX += deltaX;//hkMath::clamp( deltaX, hkReal(-1.0f), hkReal(1.0f));
// std::cout<<"Turning "<<deviceStatus->m_positionX<<std::endl;
// std::cout<<"Acceleration "<<deviceStatus->m_positionY<<std::endl;
// }
//}
//else
//{
// physicsComp->UpdatePhysicsAttrib(type, value);
//}
}
Vector3D GameObject::getPhysicAttribute(std::string type)
{
//return physicsComp->GetPhysicsAttrib(type);
return physicsCompVector[0]->GetPhysicsAttrib(type);
}
void GameObject::attachMediator(IMediator* p_med)
{
med = p_med;
}
void GameObject::setAsPlayer()
{
this->isPlayer = true;
}
bool GameObject::getPlayer()
{
return this->isPlayer;
}
IPhysicsComp* GameObject::getPhyComp()
{
return physicsComp;
}
//For Havok Vehicle ------>
void buildVehicle()
{
}
void GameObject::setWheelPosition(IPhysicsComp* physicsComp, int wheelIndex)
{
if(m_vehicleInstance != NULL)
{
hkVector4 pos;
hkQuaternion rot;
m_vehicleInstance->calcCurrentPositionAndRotation(m_vehicleInstance->getChassis(),m_vehicleInstance->m_suspension,wheelIndex,pos,rot);
glm::quat rotation;
rotation.x = rot.getComponent<0>();
rotation.y = rot.getComponent<1>();
rotation.z = rot.getComponent<2>();
rotation.w = rot.getComponent<3>();
// std::cout<<"Position of wheel "<<wheelIndex<<" x : "<<pos.getComponent(0)<<" y "<<pos.getComponent(1)<<" z "<<pos.getComponent(2)<<std::endl;
// std::cout<<"Rotation of wheel "<<wheelIndex<<" x : "<<rot.m_vec.getComponent(0)<<" y "<<rot.m_vec.getComponent(1)<<" z "<<rot.m_vec.getComponent(2)<<std::endl;
//Vector3D(rot.m_vec.getComponent(0),rot.m_vec.getComponent(1),rot.m_vec.getComponent(2))
physicsComp->RegisterPhyAttributes(Vector3D(pos.getComponent(0),pos.getComponent(1),pos.getComponent(2)), rotation, 1.0);
}
}
void GameObject::updateWheels(std::vector<Vector3D> &tracks)
{
//hkpTyremarksInfo* info = this->m_vehicleInstance->m_tyreMarks;
for(int i = 0 ; i < physicsCompVector.size() - 2; i++)
{
if(physicsCompVector[i]->getType() == "BASE")
{
this->setWheelPosition(physicsCompVector[i],i-1);
/*hkVector4* tireOrigin = new hkVector4();
info->getWheelTyremarksStrips(this->m_vehicleInstance, i-1,tireOrigin);
tracks.push_back(Vector3D(tireOrigin->getComponent(0),tireOrigin->getComponent(1),tireOrigin->getComponent(2)));*/
}
}
glm::quat rot;
Vector3D pos = physicsCompVector[0]->GetPhysicsAttrib("POSITION", rot);
pos.y += 0.05f;
physicsCompVector[physicsCompVector.size()-2]->RegisterPhyAttributes(pos, rot, 1.0);
}
void GameObject::processUserInput(ButtonPressed input)
{
//
// Update controller "position" within range [-1, 1] for both X, Y directions.
//
hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_vehicleInstance->m_deviceStatus;
const hkReal steerSpeed = 2.0f;// * 0.1f;
const hkReal backSteerSpeed = 10.0f * 0.1f;
hkReal deltaY = -inputY * 0.2f;
hkReal deltaX = -inputX * backSteerSpeed;
if ( (input == ACCELERATE)) // Add HKG_PAD_BUTTON_0 to restore pre-Havok 5.5 control
{
// Accelerate.
deltaY = -0.1f;// Acceleration down to this value from 0.1
inputY = hkMath::clamp( inputY+deltaY, hkReal(-0.4f), hkReal(0.3f));
deviceStatus->m_positionY = inputY;
}
else if (input == BRAKES )
{
// Brake/reverse.
deltaY = 0.1f;
inputY = hkMath::clamp( inputY+deltaY, hkReal(-0.4f), hkReal(0.3f));
deviceStatus->m_positionY = inputY;// it should halt the car (Acceleration becomes zero)
}
if ( input == RIGHT)
{
// Turn left.
if ( inputX >= 0.0f){ deltaX = 0.0f; }
deltaX += steerSpeed;
inputX = hkMath::clamp( inputX+deltaX, hkReal(-0.3f), hkReal(0.3f));
deviceStatus->m_positionX = inputX;
}
else if (input ==LEFT )
{
// Turn right.
if ( inputX <= 0.0f){ deltaX = 0.0f; }
deltaX -= steerSpeed;
inputX = hkMath::clamp( inputX+deltaX, hkReal(-0.3f), hkReal(0.3f));
deviceStatus->m_positionX = inputX;
}
else if (input == HANDBRAKES)
{
deviceStatus->m_positionY = 0;
deviceStatus->m_positionX = 0;
}
else if (input == DIRECTIONRESET)
{
deviceStatus->m_positionX = 0;
}
//// add analog controls
//{
// deltaY -= .2f * pad->getStickPosY(0);
// hkReal x = pad->getStickPosX(1);
// //if ( x < 0 && inputXPosition <= 0.0f){ deltaX = 0.0f; }
// //if ( x > 0 && inputXPosition >= 0.0f){ deltaX = 0.0f; }
// deltaX += x * backSteerSpeed;
//}
// Now -1 <= m_inputXPosition <= 1 and
// -1 <= m_inputYPosition <= 1
//std::cout<<"input Y "<<deviceStatus->m_positionY<<std::endl;
//std::cout<<"torque "<<m_vehicleInstance->m_torque<<std::endl;
// AutoReverse
deviceStatus->m_reverseButtonPressed = ( input == REVERSE) != 0;
// Handbrake.
//hkprintf( "%f %f\n", *inputXPosition, *inputYPosition);
deviceStatus->m_handbrakeButtonPressed = (input == HANDBRAKES) != 0;
///[CODE steerCode]>
}
| 20.760684
| 164
| 0.646651
|
aditgoyal19
|
6d597710504dec39fcaed7e950a718051844f5a1
| 1,473
|
cpp
|
C++
|
EU4toV2/Source/Mappers/RegionProvinces/RegionProvinceMapper.cpp
|
AquosPoke206/EU4toVic2
|
1aa8dc815f118dce231d09f050464c75d6925f02
|
[
"MIT"
] | 1
|
2020-10-03T16:01:28.000Z
|
2020-10-03T16:01:28.000Z
|
EU4toV2/Source/Mappers/RegionProvinces/RegionProvinceMapper.cpp
|
AquosPoke206/EU4toVic2
|
1aa8dc815f118dce231d09f050464c75d6925f02
|
[
"MIT"
] | null | null | null |
EU4toV2/Source/Mappers/RegionProvinces/RegionProvinceMapper.cpp
|
AquosPoke206/EU4toVic2
|
1aa8dc815f118dce231d09f050464c75d6925f02
|
[
"MIT"
] | null | null | null |
#include "RegionProvinceMapper.h"
#include "../../Configuration.h"
#include "OSCompatibilityLayer.h"
#include "ParserHelpers.h"
mappers::RegionProvinceMapper::RegionProvinceMapper()
{
registerKeys();
if (commonItems::DoesFileExist("./blankMod/output/map/region.txt"))
{
parseFile("./blankMod/output/map/region.txt");
}
else
{
parseFile(theConfiguration.getVic2Path() + "/map/region.txt");
}
clearRegisteredKeywords();
}
mappers::RegionProvinceMapper::RegionProvinceMapper(std::istream& theStream)
{
registerKeys();
parseStream(theStream);
clearRegisteredKeywords();
}
void mappers::RegionProvinceMapper::registerKeys()
{
registerRegex("\\w\\w\\w_\\d+", [this](const std::string& regionName, std::istream& theStream)
{
const commonItems::intList provinceList(theStream);
auto provinceVector = provinceList.getInts();
std::set<int> provinces(provinceVector.begin(), provinceVector.end());
theRegions.insert(make_pair(regionName, provinces));
});
}
bool mappers::RegionProvinceMapper::provinceIsInRegion(int province, const std::string& region) const
{
const auto provinces = theRegions.find(region);
if (provinces != theRegions.end()) return provinces->second.count(province) > 0;
return false;
}
std::set<int> mappers::RegionProvinceMapper::getProvincesInRegion(const std::string& region) const
{
const auto provinces = theRegions.find(region);
if (provinces != theRegions.end()) return provinces->second;
return std::set<int>();
}
| 29.46
| 101
| 0.746096
|
AquosPoke206
|
6d59f3426564f9a5a2b072fb47e02138c5597634
| 1,743
|
hpp
|
C++
|
src/impl/operators/crossover/vector_based/one_point_crossover.hpp
|
dominiksisejkovic/OpenECL
|
de3356cb9bfbe3b6545cc9eeaccc04705330eaf7
|
[
"MIT"
] | null | null | null |
src/impl/operators/crossover/vector_based/one_point_crossover.hpp
|
dominiksisejkovic/OpenECL
|
de3356cb9bfbe3b6545cc9eeaccc04705330eaf7
|
[
"MIT"
] | null | null | null |
src/impl/operators/crossover/vector_based/one_point_crossover.hpp
|
dominiksisejkovic/OpenECL
|
de3356cb9bfbe3b6545cc9eeaccc04705330eaf7
|
[
"MIT"
] | null | null | null |
// (c) 2020 Dominik Šišejković
// This code is licensed under the MIT license (see LICENSE.txt for details)
#ifndef OPEN_ECL_ONE_POINT_CROSSOVER_HPP
#define OPEN_ECL_ONE_POINT_CROSSOVER_HPP
#include "../../../../utils/random_utils.hpp"
#include "../../../../model/operators/i_crossover.hpp"
#include "solutions/vector_based/bit_string_solution.hpp"
class OnePointCrossover : public ICrossover {
public:
~OnePointCrossover() {}
std::vector<std::shared_ptr<ISolution>> execute(std::vector<std::shared_ptr<ISolution>> &parents) override {
if (parents.size() != 2) {
throw std::runtime_error("NPointCrossover expects exactly 2 parent solutions");
}
// Get parents
auto parent_1 = std::dynamic_pointer_cast<BitStringSolution>(parents[0]);
auto parent_2 = std::dynamic_pointer_cast<BitStringSolution>(parents[1]);
auto solution_size = parent_1->getSize();
// Prepare children
auto child_1 = std::make_shared<BitStringSolution>(solution_size);
auto child_2 = std::make_shared<BitStringSolution>(solution_size);
// Get two unique indexes
auto index = RandomUtils::getInstance().randomIntInRange(0, solution_size - 1);
// Copy parent genes
for (int i = 0; i < index; i++) {
child_1->setValueOnIndex(i, parent_1->getValueOnIndex(i));
child_2->setValueOnIndex(i, parent_2->getValueOnIndex(i));
}
for (int i = index; i < solution_size; i++) {
child_1->setValueOnIndex(i, parent_2->getValueOnIndex(i));
child_2->setValueOnIndex(i, parent_1->getValueOnIndex(i));
}
return {child_1, child_2};
}
};
#endif //OPEN_ECL_ONE_POINT_CROSSOVER_HPP
| 37.085106
| 112
| 0.667814
|
dominiksisejkovic
|
6d59fa899d15e722a2844e4b7656b2c2494a76ef
| 20,336
|
cpp
|
C++
|
tracking/src/tracking_lib/ukf.cpp
|
hywel1994/SARosPerceptionKitti
|
82c307facb5b39e47c510fbdb132962cebf09d2e
|
[
"MIT"
] | null | null | null |
tracking/src/tracking_lib/ukf.cpp
|
hywel1994/SARosPerceptionKitti
|
82c307facb5b39e47c510fbdb132962cebf09d2e
|
[
"MIT"
] | null | null | null |
tracking/src/tracking_lib/ukf.cpp
|
hywel1994/SARosPerceptionKitti
|
82c307facb5b39e47c510fbdb132962cebf09d2e
|
[
"MIT"
] | null | null | null |
/******************************************************************************
*
* Author: Simon Appel (simonappel62@gmail.com)
* Date: 25/04/2018
*
*/
#include <tracking_lib/ukf.h>
namespace tracking{
/******************************************************************************/
UnscentedKF::UnscentedKF(ros::NodeHandle nh, ros::NodeHandle private_nh):
nh_(nh),
private_nh_(private_nh)
{
// Define parameters
private_nh_.param("data_association/ped/dist/position",
params_.da_ped_dist_pos, params_.da_ped_dist_pos);
private_nh_.param("data_association/ped/dist/form",
params_.da_ped_dist_form, params_.da_ped_dist_form);
private_nh_.param("data_association/car/dist/position",
params_.da_car_dist_pos, params_.da_car_dist_pos);
private_nh_.param("data_association/car/dist/form",
params_.da_car_dist_form, params_.da_car_dist_form);
private_nh_.param("tracking/dim/z", params_.tra_dim_z,
params_.tra_dim_z);
private_nh_.param("tracking/dim/x", params_.tra_dim_x,
params_.tra_dim_x);
private_nh_.param("tracking/dim/x_aug", params_.tra_dim_x_aug,
params_.tra_dim_x_aug);
private_nh_.param("tracking/std/lidar/x", params_.tra_std_lidar_x,
params_.tra_std_lidar_x);
private_nh_.param("tracking/std/lidar/y", params_.tra_std_lidar_y,
params_.tra_std_lidar_y);
private_nh_.param("tracking/std/acc", params_.tra_std_acc,
params_.tra_std_acc);
private_nh_.param("tracking/std/yaw_rate", params_.tra_std_yaw_rate,
params_.tra_std_yaw_rate);
private_nh_.param("tracking/lambda", params_.tra_lambda,
params_.tra_lambda);
private_nh_.param("tracking/aging/bad", params_.tra_aging_bad,
params_.tra_aging_bad);
private_nh_.param("tracking/occlusion_factor", params_.tra_occ_factor,
params_.tra_occ_factor);
private_nh_.param("track/P_init/x", params_.p_init_x,
params_.p_init_x);
private_nh_.param("track/P_init/y", params_.p_init_y,
params_.p_init_y);
private_nh_.param("track/P_init/v", params_.p_init_v,
params_.p_init_v);
private_nh_.param("track/P_init/yaw", params_.p_init_yaw,
params_.p_init_yaw);
private_nh_.param("track/P_init/yaw_rate", params_.p_init_yaw_rate,
params_.p_init_yaw_rate);
// Print parameters
ROS_INFO_STREAM("da_ped_dist_pos " << params_.da_ped_dist_pos);
ROS_INFO_STREAM("da_ped_dist_form " << params_.da_ped_dist_form);
ROS_INFO_STREAM("da_car_dist_pos " << params_.da_car_dist_pos);
ROS_INFO_STREAM("da_car_dist_form " << params_.da_car_dist_form);
ROS_INFO_STREAM("tra_dim_z " << params_.tra_dim_z);
ROS_INFO_STREAM("tra_dim_x " << params_.tra_dim_x);
ROS_INFO_STREAM("tra_dim_x_aug " << params_.tra_dim_x_aug);
ROS_INFO_STREAM("tra_std_lidar_x " << params_.tra_std_lidar_x);
ROS_INFO_STREAM("tra_std_lidar_y " << params_.tra_std_lidar_y);
ROS_INFO_STREAM("tra_std_acc " << params_.tra_std_acc);
ROS_INFO_STREAM("tra_std_yaw_rate " << params_.tra_std_yaw_rate);
ROS_INFO_STREAM("tra_lambda " << params_.tra_lambda);
ROS_INFO_STREAM("tra_aging_bad " << params_.tra_aging_bad);
ROS_INFO_STREAM("tra_occ_factor " << params_.tra_occ_factor);
ROS_INFO_STREAM("p_init_x " << params_.p_init_x);
ROS_INFO_STREAM("p_init_y " << params_.p_init_y);
ROS_INFO_STREAM("p_init_v " << params_.p_init_v);
ROS_INFO_STREAM("p_init_yaw " << params_.p_init_yaw);
ROS_INFO_STREAM("p_init_yaw_rate " << params_.p_init_yaw_rate);
// Set initialized to false at the beginning
is_initialized_ = false;
// Measurement covariance
R_laser_ = MatrixXd(params_.tra_dim_z, params_.tra_dim_z);
R_laser_ << params_.tra_std_lidar_x * params_.tra_std_lidar_x, 0,
0, params_.tra_std_lidar_y * params_.tra_std_lidar_y;
// Define weights for UKF
weights_ = VectorXd(2 * params_.tra_dim_x_aug + 1);
weights_(0) = params_.tra_lambda /
(params_.tra_lambda + params_.tra_dim_x_aug);
for (int i = 1; i < 2 * params_.tra_dim_x_aug + 1; i++) {
weights_(i) = 0.5 / (params_.tra_dim_x_aug + params_.tra_lambda);
}
// Start ids for track with 0
track_id_counter_ = 0;
// Define Subscriber
list_detected_objects_sub_ = nh.subscribe("/detection/objects", 2,
&UnscentedKF::process, this);
// Define Publisher
list_tracked_objects_pub_ = nh_.advertise<ObjectArray>(
"/tracking/objects", 2);
// Random color for track
rng_(2345);
// Init counter for publishing
time_frame_ = 0;
}
UnscentedKF::~UnscentedKF(){
}
void UnscentedKF::process(const ObjectArrayConstPtr & detected_objects){
// Read current time
double time_stamp = detected_objects->header.stamp.toSec();
// All other frames
if(is_initialized_){
// Calculate time difference between frames
double delta_t = time_stamp - last_time_stamp_;
// Prediction
Prediction(delta_t);
// Data association
GlobalNearestNeighbor(detected_objects);
// Update
Update(detected_objects);
// Track management
TrackManagement(detected_objects);
}
// First frame
else{
// Initialize tracks
for(int i = 0; i < detected_objects->list.size(); ++i){
initTrack(detected_objects->list[i]);
}
// Set initialized to true
is_initialized_ = true;
}
// Store time stamp for next frame
last_time_stamp_ = time_stamp;
// Print Tracks
printTracks();
// Publish and print
publishTracks(detected_objects->header);
// Increment time frame
time_frame_++;
}
void UnscentedKF::Prediction(const double delta_t){
// Buffer variables
VectorXd x_aug = VectorXd(params_.tra_dim_x_aug);
MatrixXd P_aug = MatrixXd(params_.tra_dim_x_aug, params_.tra_dim_x_aug);
MatrixXd Xsig_aug =
MatrixXd(params_.tra_dim_x_aug, 2 * params_.tra_dim_x_aug + 1);
// Loop through all tracks
for(int i = 0; i < tracks_.size(); ++i){
// Grab track
Track & track = tracks_[i];
/******************************************************************************
* 1. Generate augmented sigma points
*/
// Fill augmented mean state
x_aug.head(5) = track.sta.x;
x_aug(5) = 0;
x_aug(6) = 0;
// Fill augmented covariance matrix
P_aug.fill(0.0);
P_aug.topLeftCorner(5,5) = track.sta.P;
P_aug(5,5) = params_.tra_std_acc * params_.tra_std_acc;
P_aug(6,6) = params_.tra_std_yaw_rate * params_.tra_std_yaw_rate;
// Create square root matrix
MatrixXd L = P_aug.llt().matrixL();
// Create augmented sigma points
Xsig_aug.col(0) = x_aug;
for(int j = 0; j < params_.tra_dim_x_aug; j++){
Xsig_aug.col(j + 1) = x_aug +
sqrt(params_.tra_lambda + params_.tra_dim_x_aug) * L.col(j);
Xsig_aug.col(j + 1 + params_.tra_dim_x_aug) = x_aug -
sqrt(params_.tra_lambda + params_.tra_dim_x_aug) * L.col(j);
}
/******************************************************************************
* 2. Predict sigma points
*/
for(int j = 0; j < 2 * params_.tra_dim_x_aug + 1; j++){
// Grab values for better readability
double p_x = Xsig_aug(0,j);
double p_y = Xsig_aug(1,j);
double v = Xsig_aug(2,j);
double yaw = Xsig_aug(3,j);
double yawd = Xsig_aug(4,j);
double nu_a = Xsig_aug(5,j);
double nu_yawdd = Xsig_aug(6,j);
// Predicted state values
double px_p, py_p;
// Avoid division by zero
if(fabs(yawd) > 0.001){
px_p = p_x + v/yawd * ( sin (yaw + yawd * delta_t) - sin(yaw));
py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw + yawd * delta_t) );
}
else {
px_p = p_x + v * delta_t * cos(yaw);
py_p = p_y + v * delta_t * sin(yaw);
}
double v_p = v;
double yaw_p = yaw + yawd * delta_t;
double yawd_p = yawd;
// Add noise
px_p = px_p + 0.5 * nu_a * delta_t * delta_t * cos(yaw);
py_p = py_p + 0.5 * nu_a * delta_t * delta_t * sin(yaw);
v_p = v_p + nu_a * delta_t;
yaw_p = yaw_p + 0.5 * nu_yawdd * delta_t * delta_t;
yawd_p = yawd_p + nu_yawdd * delta_t;
// Write predicted sigma point into right column
track.sta.Xsig_pred(0,j) = px_p;
track.sta.Xsig_pred(1,j) = py_p;
track.sta.Xsig_pred(2,j) = v_p;
track.sta.Xsig_pred(3,j) = yaw_p;
track.sta.Xsig_pred(4,j) = yawd_p;
}
/******************************************************************************
* 3. Predict state vector and state covariance
*/
// Predicted state mean
track.sta.x.fill(0.0);
for(int j = 0; j < 2 * params_.tra_dim_x_aug + 1; j++) {
track.sta.x = track.sta.x + weights_(j) *
track.sta.Xsig_pred.col(j);
}
// Predicted state covariance matrix
track.sta.P.fill(0.0);
// Iterate over sigma points
for(int j = 0; j < 2 * params_.tra_dim_x_aug + 1; j++) {
// State difference
VectorXd x_diff = track.sta.Xsig_pred.col(j) - track.sta.x;
// Angle normalization
while (x_diff(3) > M_PI) x_diff(3) -= 2. * M_PI;
while (x_diff(3) < -M_PI) x_diff(3) += 2. * M_PI;
track.sta.P = track.sta.P + weights_(j) * x_diff *
x_diff.transpose() ;
}
/*
// Print prediction
ROS_INFO("Pred of T[%d] xp=[%f,%f,%f,%f,%f], Pp=[%f,%f,%f,%f,%f]",
track.id, track.sta.x(0), track.sta.x(1), track.sta.x(2),
track.sta.x(3), track.sta.x(4), track.sta.P(0), track.sta.P(6),
track.sta.P(12), track.sta.P(18), track.sta.P(24)
);
*/
}
}
void UnscentedKF::GlobalNearestNeighbor(
const ObjectArrayConstPtr & detected_objects){
// Define assoication vectors
da_tracks = std::vector<int>(tracks_.size(),-1);
da_objects = std::vector<int>(detected_objects->list.size(),-1);
// Loop through tracks
for(int i = 0; i < tracks_.size(); ++i){
// Buffer variables
std::vector<float> distances;
std::vector<int> matches;
// Set data association parameters depending on if
// the track is a car or a pedestrian
float gate;
float box_gate;
// Pedestrian
if(tracks_[i].sem.id == 11){
gate = params_.da_ped_dist_pos;
box_gate = params_.da_ped_dist_form;
}
// Car
else if(tracks_[i].sem.id == 13){
gate = params_.da_car_dist_pos;
box_gate = params_.da_car_dist_form;
}
else{
ROS_WARN("Wrong semantic for track [%d]", tracks_[i].id);
}
// Loop through detected objects
for(int j = 0; j < detected_objects->list.size(); ++j){
// Calculate distance between track and detected object
if(tracks_[i].sem.id == detected_objects->list[j].semantic_id){
float dist = CalculateDistance(tracks_[i],
detected_objects->list[j]);
if(dist < gate){
distances.push_back(dist);
matches.push_back(j);
}
}
}
// If track exactly finds one match assign it
if(matches.size() == 1){
float box_dist = CalculateEuclideanAndBoxOffset(tracks_[i],
detected_objects->list[matches[0]]);
if(box_dist < box_gate){
da_tracks[i] = matches[0];
da_objects[matches[0]] = i;
}
}
// If found more then take best match and block other measurements
else if(matches.size() > 1){
// Block other measurements to NOT be initialized
ROS_WARN("Multiple associations for track [%d]", tracks_[i].id);
// Calculate all box distances and find minimum
float min_box_dist = box_gate;
int min_box_index = -1;
for(int k = 0; k < matches.size(); ++k){
float box_dist = CalculateEuclideanAndBoxOffset(tracks_[i],
detected_objects->list[matches[k]]);
if(box_dist < min_box_dist){
min_box_index = k;
min_box_dist = box_dist;
}
}
for(int k = 0; k < matches.size(); ++k){
if(k == min_box_index){
da_objects[matches[k]] = i;
da_tracks[i] = matches[k];
}
else{
da_objects[matches[k]] = -2;
}
}
}
else{
ROS_WARN("No measurement found for track [%d]", tracks_[i].id);
}
}
}
float UnscentedKF::CalculateDistance(const Track & track,
const Object & object){
// Calculate euclidean distance in x,y,z coordinates of track and object
return abs(track.sta.x(0) - object.world_pose.point.x) +
abs(track.sta.x(1) - object.world_pose.point.y) +
abs(track.sta.z - object.world_pose.point.z);
}
float UnscentedKF::CalculateBoxMismatch(const Track & track,
const Object & object){
// Calculate mismatch of both tracked cube and detected cube
float box_wl_switched = abs(track.geo.width - object.length) +
abs(track.geo.length - object.width);
float box_wl_ordered = abs(track.geo.width - object.width) +
abs(track.geo.length - object.length);
float box_mismatch = (box_wl_switched < box_wl_ordered) ?
box_wl_switched : box_wl_ordered;
box_mismatch += abs(track.geo.height - object.height);
return box_mismatch;
}
float UnscentedKF::CalculateEuclideanAndBoxOffset(const Track & track,
const Object & object){
// Sum of euclidean offset and box mismatch
return CalculateDistance(track, object) +
CalculateBoxMismatch(track, object);
}
void UnscentedKF::Update(const ObjectArrayConstPtr & detected_objects){
// Buffer variables
VectorXd z = VectorXd(params_.tra_dim_z);
MatrixXd Zsig;
VectorXd z_pred = VectorXd(params_.tra_dim_z);
MatrixXd S = MatrixXd(params_.tra_dim_z, params_.tra_dim_z);
MatrixXd Tc = MatrixXd(params_.tra_dim_x, params_.tra_dim_z);
// Loop through all tracks
for(int i = 0; i < tracks_.size(); ++i){
// Grab track
Track & track = tracks_[i];
// If track has not found any measurement
if(da_tracks[i] == -1){
// Increment bad aging
track.hist.bad_age++;
}
// If track has found a measurement update it
else{
// Grab measurement
z << detected_objects->list[ da_tracks[i] ].world_pose.point.x,
detected_objects->list[ da_tracks[i] ].world_pose.point.y;
/******************************************************************************
* 1. Predict measurement
*/
// Init measurement sigma points
Zsig = track.sta.Xsig_pred.topLeftCorner(params_.tra_dim_z,
2 * params_.tra_dim_x_aug + 1);
// Mean predicted measurement
z_pred.fill(0.0);
for(int j = 0; j < 2 * params_.tra_dim_x_aug + 1; j++) {
z_pred = z_pred + weights_(j) * Zsig.col(j);
}
S.fill(0.0);
Tc.fill(0.0);
for(int j = 0; j < 2 * params_.tra_dim_x_aug + 1; j++) {
// Residual
VectorXd z_sig_diff = Zsig.col(j) - z_pred;
S = S + weights_(j) * z_sig_diff * z_sig_diff.transpose();
// State difference
VectorXd x_diff = track.sta.Xsig_pred.col(j) - track.sta.x;
// Angle normalization
while(x_diff(3) > M_PI) x_diff(3) -= 2. * M_PI;
while(x_diff(3) < -M_PI) x_diff(3) += 2. * M_PI;
Tc = Tc + weights_(j) * x_diff * z_sig_diff.transpose();
}
// Add measurement noise covariance matrix
S = S + R_laser_;
/******************************************************************************
* 2. Update state vector and covariance matrix
*/
// Kalman gain K;
MatrixXd K = Tc * S.inverse();
// Residual
VectorXd z_diff = z - z_pred;
// Update state mean and covariance matrix
track.sta.x = track.sta.x + K * z_diff;
track.sta.P = track.sta.P - K * S * K.transpose();
// Update History
track.hist.good_age++;
track.hist.bad_age = 0;
/******************************************************************************
* 3. Update geometric information of track
*/
// Calculate area of detection and track
float det_area =
detected_objects->list[ da_tracks[i] ].length *
detected_objects->list[ da_tracks[i] ].width;
float tra_area = track.geo.length * track.geo.width;
// If track became strongly smaller keep the shape
if(params_.tra_occ_factor * det_area < tra_area){
ROS_WARN("Track [%d] probably occluded because of dropping size"
" from [%f] to [%f]", track.id, tra_area, det_area);
}
// Update the form of the track with measurement
track.geo.length =
detected_objects->list[ da_tracks[i] ].length;
track.geo.width =
detected_objects->list[ da_tracks[i] ].width;
// Update orientation and ground level
track.geo.orientation =
detected_objects->list[ da_tracks[i] ].orientation;
track.sta.z =
detected_objects->list[ da_tracks[i] ].world_pose.point.z;
/*
// Print Update
ROS_INFO("Update of T[%d] A[%d] z=[%f,%f] x=[%f,%f,%f,%f,%f],"
" P=[%f,%f,%f,%f,%f]", track.id, track.hist.good_age,
z_diff[0], z_diff[1],
track.sta.x(0), track.sta.x(1), track.sta.x(2),
track.sta.x(3), track.sta.x(4),
track.sta.P(0), track.sta.P(6), track.sta.P(12),
track.sta.P(18), track.sta.P(24)
);
*/
}
}
}
void UnscentedKF::TrackManagement(const ObjectArrayConstPtr & detected_objects){
// Delete spuriors tracks
for(int i = 0; i < tracks_.size() ; ++i){
// Deletion condition
if(tracks_[i].hist.bad_age >= params_.tra_aging_bad){
// Print
ROS_INFO("Deletion of T [%d]", tracks_[i].id);
// Swap track with end of vector and pop back
std::swap(tracks_[i],tracks_.back());
tracks_.pop_back();
}
}
// Create new ones out of untracked new detected object hypothesis
// Initialize tracks
for(int i = 0; i < detected_objects->list.size(); ++i){
// Unassigned object condition
if(da_objects[i] == -1){
// Init new track
initTrack(detected_objects->list[i]);
}
}
}
void UnscentedKF::initTrack(const Object & obj){
// Only if object can be a track
if(! obj.is_new_track)
return;
// Create new track
Track tr = Track();
// Add id and increment
tr.id = track_id_counter_;
track_id_counter_++;
// Add state information
tr.sta.x = VectorXd::Zero(params_.tra_dim_x);
tr.sta.x[0] = obj.world_pose.point.x;
tr.sta.x[1] = obj.world_pose.point.y;
tr.sta.z = obj.world_pose.point.z;
tr.sta.P = MatrixXd::Zero(params_.tra_dim_x, params_.tra_dim_x);
tr.sta.P << params_.p_init_x, 0, 0, 0, 0,
0, params_.p_init_y, 0, 0, 0,
0, 0, params_.p_init_v, 0, 0,
0, 0, 0,params_.p_init_yaw, 0,
0, 0, 0, 0, params_.p_init_yaw_rate;
tr.sta.Xsig_pred = MatrixXd::Zero(params_.tra_dim_x,
2 * params_.tra_dim_x_aug + 1);
// Add geometric information
tr.geo.width = obj.width;
tr.geo.length = obj.length;
if(obj.semantic_id == 13)
tr.geo.height = 1.4f;
else
tr.geo.height = obj.height;
tr.geo.orientation = obj.orientation;
// Add semantic information
tr.sem.name = obj.semantic_name;
tr.sem.id = obj.semantic_id;
tr.sem.confidence = obj.semantic_confidence;
// Add unique color
tr.r = rng_.uniform(0, 255);
tr.g = rng_.uniform(0, 255);
tr.b = rng_.uniform(0, 255);
tr.prob_existence = 0.6f;
// Push back to track list
tracks_.push_back(tr);
}
void UnscentedKF::publishTracks(const std_msgs::Header & header){
// Create track message
ObjectArray track_list;
track_list.header = header;
// Loop over all tracks
for(int i = 0; i < tracks_.size(); ++i){
// Grab track
Track & track = tracks_[i];
// Create new message and fill it
Object track_msg;
track_msg.id = track.id;
track_msg.world_pose.header.frame_id = "world";
track_msg.world_pose.point.x = track.sta.x[0];
track_msg.world_pose.point.y = track.sta.x[1];
track_msg.world_pose.point.z = track.sta.z;
try{
listener_.transformPoint("camera_color_left",
track_msg.world_pose,
track_msg.cam_pose);
listener_.transformPoint("velo_link",
track_msg.world_pose,
track_msg.velo_pose);
}
catch(tf::TransformException& ex){
ROS_ERROR("Received an exception trying to transform a point from"
"\"velo_link\" to \"world\": %s", ex.what());
}
track_msg.heading = track.sta.x[3];
track_msg.velocity = track.sta.x[2];
track_msg.width = track.geo.width;
track_msg.length = track.geo.length;
track_msg.height = track.geo.height;
track_msg.orientation = track.geo.orientation;
track_msg.semantic_name = track.sem.name;
track_msg.semantic_id = track.sem.id;
track_msg.semantic_confidence = track.sem.confidence;
track_msg.r = track.r;
track_msg.g = track.g;
track_msg.b = track.b;
track_msg.a = track.prob_existence;
// Push back track message
track_list.list.push_back(track_msg);
}
// Print
ROS_INFO("Publishing Tracking [%d]: # Tracks [%d]", time_frame_,
int(tracks_.size()));
// Publish
list_tracked_objects_pub_.publish(track_list);
}
void UnscentedKF::printTrack(const Track & tr){
ROS_INFO("Track [%d] x=[%f,%f,%f,%f,%f], z=[%f]"
" P=[%f,%f,%f,%f,%f] is [%s, %f] A[%d, %d] [w,l,h,o] [%f,%f,%f,%f]",
tr.id,
tr.sta.x(0), tr.sta.x(1), tr.sta.x(2), tr.sta.x(3), tr.sta.x(4),
tr.sta.z,
tr.sta.P(0), tr.sta.P(6), tr.sta.P(12), tr.sta.P(18), tr.sta.P(24),
tr.sem.name.c_str(), tr.sem.confidence,
tr.hist.good_age, tr.hist.bad_age,
tr.geo.width, tr.geo.length,
tr.geo.height, tr.geo.orientation
);
}
void UnscentedKF::printTracks(){
for(int i = 0; i < tracks_.size(); ++i){
printTrack(tracks_[i]);
}
}
} // namespace tracking
| 29.009986
| 80
| 0.660061
|
hywel1994
|
6d5aab7110fbf30c386a7e463e7b94ca92dc8b78
| 4,109
|
cpp
|
C++
|
export/release/macos/obj/src/__ASSET__OPENFL__assets_fonts_lanapixel_ttf.cpp
|
BushsHaxs/DOKIDOKI-MAC
|
22729124a0b7b637d56ff3b18acb555ec05934f1
|
[
"Apache-2.0"
] | null | null | null |
export/release/macos/obj/src/__ASSET__OPENFL__assets_fonts_lanapixel_ttf.cpp
|
BushsHaxs/DOKIDOKI-MAC
|
22729124a0b7b637d56ff3b18acb555ec05934f1
|
[
"Apache-2.0"
] | null | null | null |
export/release/macos/obj/src/__ASSET__OPENFL__assets_fonts_lanapixel_ttf.cpp
|
BushsHaxs/DOKIDOKI-MAC
|
22729124a0b7b637d56ff3b18acb555ec05934f1
|
[
"Apache-2.0"
] | 1
|
2021-12-11T09:19:29.000Z
|
2021-12-11T09:19:29.000Z
|
#include <hxcpp.h>
#ifndef INCLUDED___ASSET__OPENFL__assets_fonts_lanapixel_ttf
#include <__ASSET__OPENFL__assets_fonts_lanapixel_ttf.h>
#endif
#ifndef INCLUDED___ASSET__assets_fonts_lanapixel_ttf
#include <__ASSET__assets_fonts_lanapixel_ttf.h>
#endif
#ifndef INCLUDED_lime_text_Font
#include <lime/text/Font.h>
#endif
#ifndef INCLUDED_openfl_text_Font
#include <openfl/text/Font.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_6b79878e76d5f559_1197_new,"__ASSET__OPENFL__assets_fonts_lanapixel_ttf","new",0x8cfb2900,"__ASSET__OPENFL__assets_fonts_lanapixel_ttf.new","ManifestResources.hx",1197,0xf77aa668)
void __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__construct(){
HX_GC_STACKFRAME(&_hx_pos_6b79878e76d5f559_1197_new)
HXDLIN(1197) this->_hx___fromLimeFont( ::__ASSET__assets_fonts_lanapixel_ttf_obj::__alloc( HX_CTX ));
HXDLIN(1197) super::__construct(null());
}
Dynamic __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__CreateEmpty() { return new __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj; }
void *__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::_hx_vtable = 0;
Dynamic __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj > _hx_result = new __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj();
_hx_result->__construct();
return _hx_result;
}
bool __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x12d0aa2c) {
if (inClassId<=(int)0x09932e4e) {
return inClassId==(int)0x00000001 || inClassId==(int)0x09932e4e;
} else {
return inClassId==(int)0x12d0aa2c;
}
} else {
return inClassId==(int)0x40cee131;
}
}
::hx::ObjectPtr< __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj > __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__new() {
::hx::ObjectPtr< __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj > __this = new __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj();
__this->__construct();
return __this;
}
::hx::ObjectPtr< __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj > __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__alloc(::hx::Ctx *_hx_ctx) {
__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj *__this = (__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj), true, "__ASSET__OPENFL__assets_fonts_lanapixel_ttf"));
*(void **)__this = __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::_hx_vtable;
__this->__construct();
return __this;
}
__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj()
{
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj_sStaticStorageInfo = 0;
#endif
::hx::Class __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__mClass;
void __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::__register()
{
__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj _hx_dummy;
__ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("__ASSET__OPENFL__assets_fonts_lanapixel_ttf",0e,e9,7a,3c);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = __ASSET__OPENFL__assets_fonts_lanapixel_ttf_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
| 43.252632
| 247
| 0.825505
|
BushsHaxs
|
6d5af2453075178087a9c27942794943e02d534a
| 735
|
cpp
|
C++
|
022-generate-parentheses/generate-parentheses.cpp
|
nagestx/MyLeetCode
|
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
|
[
"MIT"
] | 3
|
2018-12-15T14:07:12.000Z
|
2020-07-19T23:18:09.000Z
|
022-generate-parentheses/generate-parentheses.cpp
|
yangyangu/MyLeetCode
|
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
|
[
"MIT"
] | null | null | null |
022-generate-parentheses/generate-parentheses.cpp
|
yangyangu/MyLeetCode
|
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
|
[
"MIT"
] | null | null | null |
//
// Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
//
//
//
// For example, given n = 3, a solution set is:
//
//
// [
// "((()))",
// "(()())",
// "(())()",
// "()(())",
// "()()()"
// ]
//
class Solution {
private:
void get(vector<string>&v, string s,int open, int close, int max){
if(s.size() == max*2){
v.push_back(s);
return;
}
if(open < max){
get(v,s+'(',open+1, close, max);
}
if(close<open){
get(v,s+')',open, close+1, max);
}
}
public:
vector<string> generateParenthesis(int n) {
vector<string> v;
if(n==0) return v;
get(v,"",0,0,n);
return v;
}
};
| 17.5
| 107
| 0.473469
|
nagestx
|
6d62814ef1a88b6978ba995bc51011887cb8d7c0
| 2,419
|
hpp
|
C++
|
nutation.hpp
|
komasaru/calc_greenwich_time
|
af45776181c2a457a944cd472e1b5069589aa2d8
|
[
"MIT"
] | null | null | null |
nutation.hpp
|
komasaru/calc_greenwich_time
|
af45776181c2a457a944cd472e1b5069589aa2d8
|
[
"MIT"
] | null | null | null |
nutation.hpp
|
komasaru/calc_greenwich_time
|
af45776181c2a457a944cd472e1b5069589aa2d8
|
[
"MIT"
] | null | null | null |
#ifndef CALC_GREENWICH_NUTATION_HPP_
#define CALC_GREENWICH_NUTATION_HPP_
#include "file.hpp"
#include <cmath>
#include <iostream>
#include <vector>
namespace calc_greenwich {
class Nutation {
static std::vector<std::vector<double>> dat_ls; // data of lunisolar parameters
static std::vector<std::vector<double>> dat_pl; // data of planetary parameters
double t; // Julian Century Number for TT
public:
Nutation(double t); // コンストラクタ
bool calc_nutation(double&, double&); // 計算: nutation
private:
bool calc_lunisolar(double&, double&); // 計算: lunisolar
bool calc_planetary(double&, double&); // 計算: planetary
double calc_l_iers2003(); // Mean anomaly of the Moon (IERS 2003)
double calc_lp_mhb2000(); // Mean anomaly of the Sun (MHB2000)
double calc_f_iers2003(); // Mean longitude of the Moon minus that of the ascending node (IERS 2003)
double calc_d_mhb2000(); // Mean elongation of the Moon from the Sun (MHB2000)
double calc_om_iers2003(); // Mean longitude of the ascending node of the Moon (IERS 2003)
double calc_l_mhb2000(); // Mean anomaly of the Moon (MHB2000)
double calc_f_mhb2000(); // Mean longitude of the Moon minus that of the ascending node (MHB2000)
double calc_d_mhb2000_2(); // Mean elongation of the Moon from the Sun (MHB2000)
double calc_om_mhb2000(); // Mean longitude of the ascending node of the Moon (MHB2000)
double calc_pa_iers2003(); // General accumulated precession in longitude (IERS 2003)
double calc_lme_iers2003(); // Mercury longitudes (IERS 2003)
double calc_lve_iers2003(); // Venus longitudes (IERS 2003)
double calc_lea_iers2003(); // Earth longitudes (IERS 2003)
double calc_lma_iers2003(); // Mars longitudes (IERS 2003)
double calc_lju_iers2003(); // Jupiter longitudes (IERS 2003)
double calc_lsa_iers2003(); // Saturn longitudes (IERS 2003)
double calc_lur_iers2003(); // Uranus longitudes (IERS 2003)
double calc_lne_mhb2000(); // Neptune longitude (MHB2000)
double fmod_p(double, double); // 正剰余計算(std::fmod が非対応のため)
};
} // namespace calc_greenwich
#endif
| 49.367347
| 118
| 0.634973
|
komasaru
|
6d62a5e43d720e1421aff83f6510acc3a55179f8
| 5,486
|
cpp
|
C++
|
src/mac/osBundle.cpp
|
GPUOpen-Tools/common-src-AMDTOSWrappers
|
80f8902c78d52435ac04f66ac190d689e5badbc1
|
[
"MIT"
] | 2
|
2017-01-28T14:11:35.000Z
|
2018-02-01T08:22:03.000Z
|
src/mac/osBundle.cpp
|
GPUOpen-Tools/common-src-AMDTOSWrappers
|
80f8902c78d52435ac04f66ac190d689e5badbc1
|
[
"MIT"
] | null | null | null |
src/mac/osBundle.cpp
|
GPUOpen-Tools/common-src-AMDTOSWrappers
|
80f8902c78d52435ac04f66ac190d689e5badbc1
|
[
"MIT"
] | 2
|
2018-02-01T08:22:04.000Z
|
2019-11-01T23:00:21.000Z
|
//------------------------------ osBundle.cpp ------------------------------
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTBaseTools/Include/gtString.h>
#include <AMDTBaseTools/Include/AMDTDefinitions.h>
// Local:
#include <AMDTOSWrappers/Include/osDebugLog.h>
#include <AMDTOSWrappers/Include/osBundle.h>
#include <AMDTOSWrappers/Include/osOSDefinitions.h>
#ifdef _GR_IPHONE_BUILD
#include <dlfcn.h>
// CoreServices for iPhone:
#include <CFNetwork/CFNetwork.h>
#else
// Carbon:
#include <Carbon/Carbon.h>
#endif
// Will hold the OpenGL ES framework path if needed:
static gtString s_openglesFrameworkPathAsString;
// ---------------------------------------------------------------------------
// Name: osGetOpenGLFrameworkFunctionAddress
// Description: The MAC OS implementation for getProcAddress
// Arguments: const char* procName
// Return Val: osProcedureAddress
// Author: Sigal Algranaty
// Date: 8/12/2008
// ---------------------------------------------------------------------------
osProcedureAddress osGetOpenGLFrameworkFunctionAddress(const char* procName)
{
osProcedureAddress retVal = NULL;
#ifdef _GR_IPHONE_BUILD
gtString openglesModuleFilePath = osGetOpenGLESFrameworkPath();
openglesModuleFilePath.append(osFilePath::osPathSeparator).append(OS_OPENGL_ES_MODULE_NAME);
void* openGLESLibraryHandle = dlopen(openglesModuleFilePath.asCharArray(), RTLD_LAZY);
retVal = dlsym(openGLESLibraryHandle, procName);
#else
// Get the OS functions entry points:
CFBundleRef pBundleRefOpenGL = NULL;
bool rc = osGetSystemOpenGLFrameworkBundle(pBundleRefOpenGL);
GT_IF_WITH_ASSERT(rc)
{
// Get the function pointer from the bundle:
retVal = CFBundleGetFunctionPointerForName(pBundleRefOpenGL, CFStringCreateWithCStringNoCopy(NULL, procName, CFStringGetSystemEncoding(), NULL));
}
if (pBundleRefOpenGL != NULL)
{
// Release the bundle ref:
CFBundleUnloadExecutable(pBundleRefOpenGL);
CFRelease(pBundleRefOpenGL);
pBundleRefOpenGL = NULL;
}
#endif
return retVal;
}
// ---------------------------------------------------------------------------
// Name: osGetSystemOpenGLFrameworkBundle
// Description: Returns a reference to the system's OpenGL framework bundle.
// Arguments: refOpenGLFrameworkBundle - Will get a reference to the system's OpenGL
// framework bundle.
// Return Val: bool - Success / failure.
// Author: Yaki Tebeka
// Date: 28/12/2008
// ---------------------------------------------------------------------------
bool osGetSystemOpenGLFrameworkBundle(CFBundleRef& refOpenGLFrameworkBundle)
{
bool retVal = false;
#ifdef _GR_IPHONE_BUILD
// This function should not be called on the iPhone:
GT_ASSERT(false);
#else
// Get a reference to the System's frameworks folder:
FSRef frameworksFolderRef;
OSStatus err = FSFindFolder(kSystemDomain, kFrameworksFolderType, FALSE, &frameworksFolderRef);
GT_IF_WITH_ASSERT(err == noErr)
{
// Convert the reference to a URL:
CFURLRef baseURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault, &frameworksFolderRef);
GT_IF_WITH_ASSERT(baseURL != NULL)
{
// Build the OpenGL framework bundle URL (path):
CFURLRef bundleURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, baseURL, CFSTR("OpenGL.framework"), false);
if (bundleURL != NULL)
{
// Get a reference to the OpenGL framework bundle:
refOpenGLFrameworkBundle = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
if (refOpenGLFrameworkBundle != NULL)
{
// Load the OpenGL fremework bundle into this process address space:
Boolean rc1 = CFBundleLoadExecutable(refOpenGLFrameworkBundle);
GT_IF_WITH_ASSERT(rc1)
{
retVal = true;
}
else
{
// Failure clean up:
CFRelease(refOpenGLFrameworkBundle);
refOpenGLFrameworkBundle = NULL;
}
}
// Cleanup:
CFRelease(bundleURL);
}
// Cleanup:
CFRelease(baseURL);
}
}
#endif // _GR_IPHONE_BUILD
return retVal;
}
// ---------------------------------------------------------------------------
// Name: osSetOpenGLESFrameworkPath
// Description: Sets the OpenGL ES framework path
// Author: Uri Shomroni
// Date: 8/6/2009
// ---------------------------------------------------------------------------
void osSetOpenGLESFrameworkPath(const char* pFrameworkPath)
{
GT_IF_WITH_ASSERT(pFrameworkPath != NULL)
{
s_openglesFrameworkPathAsString = pFrameworkPath;
}
}
// ---------------------------------------------------------------------------
// Name: osGetOpenGLESFrameworkPath
// Description: Returns the previously set OpenGL ES framework path
// Return Val: const char*
// Author: Uri Shomroni
// Date: 8/6/2009
// ---------------------------------------------------------------------------
const char* osGetOpenGLESFrameworkPath()
{
return s_openglesFrameworkPathAsString.asCharArray();
}
| 35.393548
| 153
| 0.58148
|
GPUOpen-Tools
|
6d66c915284f566e78338b4f34d4fc78e6500818
| 1,444
|
cpp
|
C++
|
SimpleDB/src/core/sql/statement_delete.cpp
|
caivao/SimpleDB
|
ff90245c5ffc96ea84cf046596d690866c1c8cb6
|
[
"MIT"
] | 1
|
2021-01-05T17:01:31.000Z
|
2021-01-05T17:01:31.000Z
|
SimpleDB/src/core/sql/statement_delete.cpp
|
caivao/SimpleDB
|
ff90245c5ffc96ea84cf046596d690866c1c8cb6
|
[
"MIT"
] | null | null | null |
SimpleDB/src/core/sql/statement_delete.cpp
|
caivao/SimpleDB
|
ff90245c5ffc96ea84cf046596d690866c1c8cb6
|
[
"MIT"
] | null | null | null |
//
// statement_delete.cpp
// SimpleDB
//
// Created by lifeng on 2019/6/6.
// Copyright © 2019 feng. All rights reserved.
//
#include "statement_delete.hpp"
#include "expr.hpp"
#include "order.hpp"
namespace SDB {
namespace STMT {
Delete &Delete::delete_from(const std::string &table)
{
_description.append("DELETE FROM " + table);
return *this;
}
Delete &Delete::where(const Expr &where)
{
if (!where.empty()) {
_description.append(" WHERE " + where.description());
}
return *this;
}
Delete &Delete::limit(const Expr &from, const Expr &to)
{
if (!from.empty()) {
_description.append(" LIMIT " + from.description());
if (!to.empty()) {
_description.append("," + to.description());
}
}
return *this;
}
Delete &Delete::limit(const Expr &limit)
{
if (!limit.empty()) {
_description.append(" LIMIT " + limit.description());
}
return *this;
}
Delete &Delete::offset(const Expr &offset)
{
if (!offset.empty()) {
_description.append(" OFFSET " + offset.description());
}
return *this;
}
}
}
| 24.896552
| 71
| 0.463989
|
caivao
|
6d67b08081359a9fb9cecfc572a4d1a4d0b2e925
| 9,379
|
cc
|
C++
|
tensorflow_text/core/kernels/mst_solver_test.cc
|
aprasad16/text
|
c1607c98c70534abc3c75eb231830ce6d87be645
|
[
"Apache-2.0"
] | 975
|
2019-05-29T22:10:37.000Z
|
2022-03-30T03:43:21.000Z
|
tensorflow_text/core/kernels/mst_solver_test.cc
|
aprasad16/text
|
c1607c98c70534abc3c75eb231830ce6d87be645
|
[
"Apache-2.0"
] | 276
|
2019-06-07T23:12:52.000Z
|
2022-03-31T17:38:05.000Z
|
tensorflow_text/core/kernels/mst_solver_test.cc
|
aprasad16/text
|
c1607c98c70534abc3c75eb231830ce6d87be645
|
[
"Apache-2.0"
] | 192
|
2019-06-04T03:36:42.000Z
|
2022-03-31T23:49:17.000Z
|
// Copyright 2021 TF.Text Authors.
//
// 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 "tensorflow_text/core/kernels/mst_solver.h"
#include <limits>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/core/lib/core/status_test_util.h"
namespace tensorflow {
namespace text {
// Testing rig.
//
// Template args:
// Solver: An instantiation of the MstSolver<> template.
template <class Solver>
class MstSolverTest : public ::testing::Test {
protected:
using Index = typename Solver::IndexType;
using Score = typename Solver::ScoreType;
// Adds directed arcs for all |num_nodes| nodes to the |solver_| with the
// |score|.
void AddAllArcs(Index num_nodes, Score score) {
for (Index source = 0; source < num_nodes; ++source) {
for (Index target = 0; target < num_nodes; ++target) {
if (source == target) continue;
solver_.AddArc(source, target, score);
}
}
}
// Adds root selections for all |num_nodes| nodes to the |solver_| with the
// |score|.
void AddAllRoots(Index num_nodes, Score score) {
for (Index root = 0; root < num_nodes; ++root) {
solver_.AddRoot(root, score);
}
}
// Runs the |solver_| using an argmax array of size |argmax_array_size| and
// expects it to fail with an error message that matches |error_substr|.
void SolveAndExpectError(int argmax_array_size,
const std::string &error_message_substr) {
std::vector<Index> argmax(argmax_array_size);
EXPECT_TRUE(absl::StrContains(solver_.Solve(&argmax).error_message(),
error_message_substr));
}
// As above, but expects success. Does not assert anything about the solution
// produced by the solver.
void SolveAndExpectOk(int argmax_array_size) {
std::vector<Index> argmax(argmax_array_size);
TF_EXPECT_OK(solver_.Solve(&argmax));
}
// As above, but expects the solution to be |expected_argmax| and infers the
// argmax array size.
void SolveAndExpectArgmax(const std::vector<Index> &expected_argmax) {
std::vector<Index> actual_argmax(expected_argmax.size());
TF_ASSERT_OK(solver_.Solve(&actual_argmax));
EXPECT_EQ(expected_argmax, actual_argmax);
}
// MstSolver<> instance used by the test. Reused across all MST problems in
// each test to exercise reuse.
Solver solver_;
};
using Solvers =
::testing::Types<MstSolver<uint8, int16>, MstSolver<uint16, int32>,
MstSolver<uint32, int64>, MstSolver<uint16, float>,
MstSolver<uint32, double>>;
TYPED_TEST_SUITE(MstSolverTest, Solvers);
TYPED_TEST(MstSolverTest, FailIfNoNodes) {
for (const bool forest : {false, true}) {
EXPECT_TRUE(absl::StrContains(this->solver_.Init(forest, 0).error_message(),
"Non-positive number of nodes"));
}
}
TYPED_TEST(MstSolverTest, FailIfTooManyNodes) {
// Set to a value that would overflow when doubled.
const auto kNumNodes =
(std::numeric_limits<typename TypeParam::IndexType>::max() / 2) + 10;
for (const bool forest : {false, true}) {
EXPECT_TRUE(
absl::StrContains(this->solver_.Init(forest, kNumNodes).error_message(),
"Too many nodes"));
}
}
TYPED_TEST(MstSolverTest, InfeasibleIfNoRootsNoArcs) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->SolveAndExpectError(kNumNodes, "Infeasible digraph");
}
}
TYPED_TEST(MstSolverTest, InfeasibleIfNoRootsAllArcs) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllArcs(kNumNodes, 0);
this->SolveAndExpectError(kNumNodes, "Infeasible digraph");
}
}
TYPED_TEST(MstSolverTest, FeasibleForForestOnlyIfAllRootsNoArcs) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
if (forest) {
this->SolveAndExpectOk(kNumNodes); // all roots is a valid forest
} else {
this->SolveAndExpectError(kNumNodes, "Infeasible digraph");
}
}
}
TYPED_TEST(MstSolverTest, FeasibleIfAllRootsAllArcs) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
this->SolveAndExpectOk(kNumNodes);
}
}
TYPED_TEST(MstSolverTest, FailIfArgmaxArrayTooSmall) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
this->SolveAndExpectError(kNumNodes - 1, // too small
"Argmax array too small");
}
}
TYPED_TEST(MstSolverTest, OkIfArgmaxArrayTooLarge) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
this->SolveAndExpectOk(kNumNodes + 1); // too large
}
}
TYPED_TEST(MstSolverTest, SolveForAllRootsForestOnly) {
const int kNumNodes = 10;
const bool forest = true;
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 1); // favor all root selections
this->AddAllArcs(kNumNodes, 0);
this->SolveAndExpectArgmax({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
}
TYPED_TEST(MstSolverTest, SolveForLeftToRightChain) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
for (int target = 1; target < kNumNodes; ++target) {
this->solver_.AddArc(target - 1, target, 1); // favor left-to-right chain
}
this->SolveAndExpectArgmax({0, 0, 1, 2, 3, 4, 5, 6, 7, 8});
}
}
TYPED_TEST(MstSolverTest, SolveForRightToLeftChain) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
for (int source = 1; source < kNumNodes; ++source) {
this->solver_.AddArc(source, source - 1, 1); // favor right-to-left chain
}
this->SolveAndExpectArgmax({1, 2, 3, 4, 5, 6, 7, 8, 9, 9});
}
}
TYPED_TEST(MstSolverTest, SolveForAllFromFirstTree) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
for (int target = 1; target < kNumNodes; ++target) {
this->solver_.AddArc(0, target, 1); // favor first -> target
}
this->SolveAndExpectArgmax({0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
}
}
TYPED_TEST(MstSolverTest, SolveForAllFromLastTree) {
const int kNumNodes = 10;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
for (int target = 0; target + 1 < kNumNodes; ++target) {
this->solver_.AddArc(9, target, 1); // favor last -> target
}
this->SolveAndExpectArgmax({9, 9, 9, 9, 9, 9, 9, 9, 9, 9});
}
}
TYPED_TEST(MstSolverTest, SolveForBinaryTree) {
const int kNumNodes = 15;
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, kNumNodes));
this->AddAllRoots(kNumNodes, 0);
this->AddAllArcs(kNumNodes, 0);
for (int target = 1; target < kNumNodes; ++target) {
this->solver_.AddArc((target - 1) / 2, target, 1); // like a binary heap
}
// clang-format off
this->SolveAndExpectArgmax({0,
0, 0,
1, 1, 2, 2,
3, 3, 4, 4, 5, 5, 6, 6});
// clang-format on
}
}
TYPED_TEST(MstSolverTest, ScoreAccessors) {
for (const bool forest : {false, true}) {
TF_ASSERT_OK(this->solver_.Init(forest, 10));
this->solver_.AddArc(0, 1, 0);
this->solver_.AddArc(1, 4, 1);
this->solver_.AddArc(7, 6, 2);
this->solver_.AddArc(9, 2, 3);
this->solver_.AddRoot(0, 10);
this->solver_.AddRoot(2, 20);
this->solver_.AddRoot(8, 30);
EXPECT_EQ(this->solver_.ArcScore(0, 1), 0);
EXPECT_EQ(this->solver_.ArcScore(1, 4), 1);
EXPECT_EQ(this->solver_.ArcScore(7, 6), 2);
EXPECT_EQ(this->solver_.ArcScore(9, 2), 3);
EXPECT_EQ(this->solver_.RootScore(0), 10);
EXPECT_EQ(this->solver_.RootScore(2), 20);
EXPECT_EQ(this->solver_.RootScore(8), 30);
}
}
} // namespace text
} // namespace tensorflow
| 34.105455
| 80
| 0.662757
|
aprasad16
|
6d6947f8edc731c1ff4829331173608301564dc5
| 24,425
|
cpp
|
C++
|
src/parse/parser.cpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 14
|
2020-04-14T17:00:56.000Z
|
2021-08-30T08:29:26.000Z
|
src/parse/parser.cpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 27
|
2020-12-27T16:00:44.000Z
|
2021-08-01T13:12:14.000Z
|
src/parse/parser.cpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 1
|
2020-05-29T18:33:37.000Z
|
2020-05-29T18:33:37.000Z
|
#include "parse/parser.hpp"
#include "op_precedence.hpp"
#include "parse/error.hpp"
#include "parse/nodes.hpp"
#include "utilities.hpp"
#include <cassert>
#include <vector>
namespace {
// Maximum depth that expressions are allowed to be nested.
constexpr size_t g_maxRecursionDepth = 100;
auto isPossibleTypeToken(lex::Token token) -> bool {
switch (token.getKind()) {
case lex::TokenKind::Identifier:
case lex::TokenKind::Keyword:
case lex::TokenKind::StaticInt:
return true;
default:
return false;
}
}
} // namespace
namespace parse {
namespace internal {
ParserImpl::~ParserImpl() noexcept { assert(m_exprRecursionDepth == 0); }
auto ParserImpl::next() -> NodePtr { return nextStmt(); }
auto ParserImpl::nextStmt() -> NodePtr {
if (peekToken(0).isEnd()) {
return nullptr;
}
const auto kw = getKw(peekToken(0));
if (kw) {
switch (*kw) {
case lex::Keyword::Import:
return nextImport();
case lex::Keyword::Fun:
case lex::Keyword::Act:
return nextStmtFuncDecl();
case lex::Keyword::Struct:
return nextStmtStructDecl();
case lex::Keyword::Union:
return nextStmtUnionDecl();
case lex::Keyword::Enum:
return nextStmtEnumDecl();
default:
break;
}
}
if (peekToken(0).getKind() == lex::TokenKind::LineComment) {
return nextComment();
}
return nextStmtExec();
}
auto ParserImpl::nextExpr() -> NodePtr {
if (peekToken(0).isEnd()) {
return nullptr;
}
return nextExpr(0);
}
auto ParserImpl::nextComment() -> NodePtr { return commentNode(consumeToken()); }
auto ParserImpl::nextImport() -> NodePtr {
auto kw = consumeToken();
auto path = consumeToken();
if (getKw(kw) == lex::Keyword::Import && path.getKind() == lex::TokenKind::LitString) {
return importStmtNode(kw, std::move(path));
}
return errInvalidStmtImport(kw, std::move(path));
}
auto ParserImpl::nextStmtFuncDecl() -> NodePtr {
auto kwTok = consumeToken();
auto kw = getKw(kwTok);
auto modifiers = std::vector<lex::Token>{};
while (auto kw = getKw(peekToken(0))) {
switch (*kw) {
case lex::Keyword::Noinline:
case lex::Keyword::Implicit:
modifiers.push_back(consumeToken());
continue;
default:
break;
}
break; // Not supported modifier keyword.
}
auto id = consumeToken();
auto typeSubs = peekToken(0).getKind() == lex::TokenKind::SepOpenCurly
? std::optional<TypeSubstitutionList>{nextTypeSubstitutionList()}
: std::nullopt;
auto argList = nextArgDeclList();
auto retType = std::optional<RetTypeSpec>{};
if (peekToken(0).getKind() == lex::TokenKind::SepArrow) {
retType = nextRetTypeSpec();
}
auto body = nextExpr(0);
auto kwValid = kw == lex::Keyword::Fun || kw == lex::Keyword::Act;
auto typeSubsValid = !typeSubs || typeSubs->validate();
auto idValid =
id.getKind() == lex::TokenKind::Identifier || id.getCat() == lex::TokenCat::Operator;
auto retTypeValid = !retType || retType->validate();
if (kwValid && idValid && typeSubsValid && retTypeValid && argList.validate()) {
return funcDeclStmtNode(
kwTok,
std::move(modifiers),
std::move(id),
std::move(typeSubs),
std::move(argList),
std::move(retType),
std::move(body));
}
return errInvalidStmtFuncDecl(
kwTok,
std::move(modifiers),
std::move(id),
std::move(typeSubs),
std::move(argList),
std::move(retType),
std::move(body));
}
auto ParserImpl::nextStmtStructDecl() -> NodePtr {
auto kw = consumeToken();
auto id = consumeToken();
auto typeSubs = peekToken(0).getKind() == lex::TokenKind::SepOpenCurly
? std::optional<TypeSubstitutionList>{nextTypeSubstitutionList()}
: std::nullopt;
auto isEmpty = peekToken(0).getKind() != lex::TokenKind::OpEq;
auto eq = isEmpty ? std::nullopt : std::optional{consumeToken()};
auto fields = std::vector<StructDeclStmtNode::FieldSpec>{};
auto commas = std::vector<lex::Token>{};
if (!isEmpty) {
while (isPossibleTypeToken(peekToken(0)) || peekToken(0).getKind() == lex::TokenKind::Keyword) {
auto fieldType = nextType();
auto fieldId = consumeToken();
fields.emplace_back(std::move(fieldType), std::move(fieldId));
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else {
break;
}
}
}
auto isValid = getKw(kw) == lex::Keyword::Struct && id.getKind() == lex::TokenKind::Identifier;
if (typeSubs) {
isValid &= typeSubs->validate();
}
if (!isEmpty) {
isValid &= !fields.empty() &&
std::all_of(
fields.begin(),
fields.end(),
[](const auto& a) {
return a.getIdentifier().getKind() == lex::TokenKind::Identifier &&
a.getType().validate();
}) &&
(commas.size() == fields.size() - 1);
}
if (isValid) {
return structDeclStmtNode(
kw, std::move(id), std::move(typeSubs), eq, std::move(fields), std::move(commas));
}
return errInvalidStmtStructDecl(kw, id, std::move(typeSubs), eq, fields, std::move(commas));
}
auto ParserImpl::nextStmtUnionDecl() -> NodePtr {
auto kw = consumeToken();
auto id = consumeToken();
auto typeSubs = peekToken(0).getKind() == lex::TokenKind::SepOpenCurly
? std::optional<TypeSubstitutionList>{nextTypeSubstitutionList()}
: std::nullopt;
auto eq = consumeToken();
auto types = std::vector<Type>{};
auto commas = std::vector<lex::Token>{};
while (isPossibleTypeToken(peekToken(0)) || peekToken(0).getKind() == lex::TokenKind::Keyword) {
types.push_back(nextType());
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else {
break;
}
}
const auto kwValid = getKw(kw) == lex::Keyword::Union;
const auto idValid = id.getKind() == lex::TokenKind::Identifier;
const auto typeSubsValid = !typeSubs || typeSubs->validate();
const auto eqValid = eq.getKind() == lex::TokenKind::OpEq;
const auto typesValid =
std::all_of(types.begin(), types.end(), [](const auto& t) { return t.validate(); });
if (kwValid && idValid && typeSubsValid && eqValid && types.size() >= 2 && typesValid &&
commas.size() == types.size() - 1) {
return unionDeclStmtNode(
kw, std::move(id), std::move(typeSubs), eq, std::move(types), std::move(commas));
}
return errInvalidStmtUnionDecl(
kw, std::move(id), std::move(typeSubs), eq, types, std::move(commas));
}
auto ParserImpl::nextStmtEnumDecl() -> NodePtr {
auto kw = consumeToken();
auto id = consumeToken();
auto eq = consumeToken();
auto entries = std::vector<EnumDeclStmtNode::EntrySpec>{};
auto commas = std::vector<lex::Token>{};
while (peekToken(0).getKind() == lex::TokenKind::Identifier) {
auto entryId = consumeToken();
auto entryValue = std::optional<EnumDeclStmtNode::ValueSpec>{};
// Allow consume value specifiers that use '=' instead of ':', reason is that its common in
// other languages and this way we can provide a proper error message in that case.
if (peekToken(0).getKind() == lex::TokenKind::SepColon ||
peekToken(0).getKind() == lex::TokenKind::OpEq) {
auto colon = consumeToken();
auto minus = peekToken(0).getKind() == lex::TokenKind::OpMinus ? std::optional{consumeToken()}
: std::nullopt;
auto value = consumeToken();
entryValue = EnumDeclStmtNode::ValueSpec{colon, std::move(minus), std::move(value)};
}
entries.emplace_back(EnumDeclStmtNode::EntrySpec{std::move(entryId), std::move(entryValue)});
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else {
break;
}
}
const auto kwValid = getKw(kw) == lex::Keyword::Enum;
const auto idValid = id.getKind() == lex::TokenKind::Identifier;
const auto eqValid = eq.getKind() == lex::TokenKind::OpEq;
const auto entriesValid =
std::all_of(entries.begin(), entries.end(), [](const auto& e) { return e.validate(); });
const auto commasValid = commas.size() == entries.size() - 1;
if (kwValid && idValid && eqValid && !entries.empty() && entriesValid && commasValid) {
return enumDeclStmtNode(kw, std::move(id), eq, std::move(entries), std::move(commas));
}
return errInvalidStmtEnumDecl(kw, std::move(id), eq, entries, std::move(commas));
}
auto ParserImpl::nextStmtExec() -> NodePtr { return execStmtNode(nextExprCall(nextExprPrimary())); }
auto ParserImpl::nextExpr(const int minPrecedence, const int maxPrecedence) -> NodePtr {
if (++m_exprRecursionDepth >= g_maxRecursionDepth) {
--m_exprRecursionDepth;
return errMaxExprRecursionDepthReached(consumeToken());
}
auto lhs = nextExprLhs();
while (true) {
// Handle binary operators, precedence controls if we should keep recursing or let the next
// iteration handle them.
const auto& nextToken = peekToken(0);
const auto rhsPrecedence = getRhsOpPrecedence(nextToken);
const auto rightAssociative = isRightAssociative(nextToken);
if (rhsPrecedence == 0 || rhsPrecedence < minPrecedence ||
(!rightAssociative && rhsPrecedence == minPrecedence) || rhsPrecedence >= maxPrecedence) {
break;
}
switch (nextToken.getKind()) {
case lex::TokenKind::SepOpenParen:
case lex::TokenKind::OpParenParen:
lhs = nextExprCall(std::move(lhs));
break;
case lex::TokenKind::OpSemi:
lhs = nextExprGroup(std::move(lhs), rhsPrecedence);
break;
case lex::TokenKind::OpQMark:
lhs = nextExprConditional(std::move(lhs));
break;
case lex::TokenKind::OpDot:
lhs = nextExprField(std::move(lhs));
break;
case lex::TokenKind::SepOpenSquare:
lhs = nextExprIndex(std::move(lhs));
break;
case lex::TokenKind::Keyword:
if (getKw(nextToken) == lex::Keyword::Is || getKw(nextToken) == lex::Keyword::As) {
lhs = nextExprIs(std::move(lhs));
break;
}
[[fallthrough]];
default:
auto op = consumeToken();
auto rhs = nextExpr(rhsPrecedence);
lhs = binaryExprNode(std::move(lhs), op, std::move(rhs));
break;
}
}
--m_exprRecursionDepth;
return lhs;
}
auto ParserImpl::nextExprLhs() -> NodePtr {
const auto& nextToken = peekToken(0);
if (nextToken.getCat() == lex::TokenCat::Operator) {
const auto opToken = consumeToken();
const auto precedence = getLhsOpPrecedence(opToken);
if (precedence == 0) {
return errInvalidUnaryOp(opToken, nextExpr(precedence));
}
return unaryExprNode(opToken, nextExpr(precedence));
}
return nextExprPrimary();
}
auto ParserImpl::nextExprGroup(NodePtr firstExpr, const int precedence) -> NodePtr {
auto subExprs = std::vector<NodePtr>{};
auto semis = std::vector<lex::Token>{};
subExprs.push_back(std::move(firstExpr));
while (peekToken(0).getKind() == lex::TokenKind::OpSemi) {
semis.push_back(consumeToken());
subExprs.push_back(nextExpr(precedence));
}
return groupExprNode(std::move(subExprs), std::move(semis));
}
auto ParserImpl::nextExprPrimary() -> NodePtr {
auto nextTok = peekToken(0);
switch (nextTok.getCat()) {
case lex::TokenCat::Literal:
return litExprNode(consumeToken());
case lex::TokenCat::Identifier: {
auto id = consumeToken();
if (peekToken(0).getKind() == lex::TokenKind::OpEq) {
auto eq = consumeToken();
return constDeclExprNode(std::move(id), eq, nextExpr(assignmentPrecedence));
}
return nextExprId(std::move(id));
}
case lex::TokenCat::Keyword: {
switch (*getKw(nextTok)) {
case lex::Keyword::Intrinsic:
return nextExprIntrinsic();
case lex::Keyword::If:
return nextExprSwitch();
case lex::Keyword::Impure: {
auto modifiers = std::vector<lex::Token>{consumeToken()};
return nextExprAnonFunc(std::move(modifiers));
}
case lex::Keyword::Lambda:
return nextExprAnonFunc({});
case lex::Keyword::Fork:
case lex::Keyword::Lazy: {
auto modifiers = std::vector<lex::Token>{consumeToken()};
return nextExprCall(nextExpr(0, callPrecedence), std::move(modifiers));
}
case lex::Keyword::Self:
return nextExprId(consumeToken());
default:
return errInvalidPrimaryExpr(consumeToken());
}
}
default:
if (nextTok.getKind() == lex::TokenKind::SepOpenParen) {
return nextExprParen();
}
return errInvalidPrimaryExpr(consumeToken());
}
}
auto ParserImpl::nextExprId() -> NodePtr { return nextExprId(consumeToken()); }
auto ParserImpl::nextExprId(lex::Token idToken) -> NodePtr {
auto typeParams = peekToken(0).getKind() == lex::TokenKind::SepOpenCurly
? std::optional<TypeParamList>{nextTypeParamList()}
: std::nullopt;
auto validId =
idToken.getKind() == lex::TokenKind::Identifier || getKw(idToken) == lex::Keyword::Self;
if (validId && (!typeParams || typeParams->validate())) {
return idExprNode(std::move(idToken), std::move(typeParams));
}
return errInvalidIdExpr(std::move(idToken), std::move(typeParams));
}
auto ParserImpl::nextExprIntrinsic() -> NodePtr {
auto kw = consumeToken();
auto open = consumeToken();
auto intrinsic = consumeToken();
auto close = consumeToken();
auto typeParams = peekToken(0).getKind() == lex::TokenKind::SepOpenCurly
? std::optional<TypeParamList>{nextTypeParamList()}
: std::nullopt;
const auto validIntrinsic = intrinsic.getKind() == lex::TokenKind::Identifier;
const auto validTypeParams = !typeParams || typeParams->validate();
const auto validBraces = open.getKind() == lex::TokenKind::SepOpenCurly &&
close.getKind() == lex::TokenKind::SepCloseCurly;
if (getKw(kw) == lex::Keyword::Intrinsic && validIntrinsic && validTypeParams && validBraces) {
return intrinsicExprNode(
std::move(kw),
std::move(open),
std::move(intrinsic),
std::move(close),
std::move(typeParams));
}
return errInvalidIntrinsicExpr(
std::move(kw),
std::move(open),
std::move(intrinsic),
std::move(close),
std::move(typeParams));
}
auto ParserImpl::nextExprField(NodePtr lhs) -> NodePtr {
auto dot = consumeToken();
auto id = consumeToken();
if (dot.getKind() == lex::TokenKind::OpDot && id.getKind() == lex::TokenKind::Identifier) {
return fieldExprNode(std::move(lhs), std::move(dot), std::move(id));
}
return errInvalidFieldExpr(std::move(lhs), std::move(dot), std::move(id));
}
auto ParserImpl::nextExprIs(NodePtr lhs) -> NodePtr {
auto kwTok = consumeToken();
auto kw = getKw(kwTok);
auto type = nextType();
auto id = kw == lex::Keyword::As ? std::optional{consumeToken()} : std::nullopt;
const auto kwValid = kw == lex::Keyword::Is || kw == lex::Keyword::As;
const auto idValid = !id ||
(id->getKind() == lex::TokenKind::Identifier || id->getKind() == lex::TokenKind::Discard);
if (kwValid && type.validate() && idValid) {
return isExprNode(std::move(lhs), kwTok, std::move(type), std::move(id));
}
return errInvalidIsExpr(std::move(lhs), kwTok, type, std::move(id));
}
auto ParserImpl::nextExprCall(NodePtr lhs, std::vector<lex::Token> modifiers) -> NodePtr {
auto open = consumeToken();
auto empty = open.getKind() == lex::TokenKind::OpParenParen;
auto args = std::vector<NodePtr>{};
auto commas = std::vector<lex::Token>{};
auto missingComma = false;
if (!empty) {
while (peekToken(0).getKind() != lex::TokenKind::SepCloseParen && !peekToken(0).isEnd()) {
args.push_back(nextExpr(0));
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else if (peekToken(0).getKind() != lex::TokenKind::SepCloseParen) {
missingComma = true;
}
}
}
auto close = empty ? open : consumeToken();
auto commasValid = !missingComma && commas.size() == (args.empty() ? 0 : args.size() - 1);
if (validateParentheses(open, close) && commasValid) {
return callExprNode(
std::move(modifiers), std::move(lhs), open, std::move(args), std::move(commas), close);
}
return errInvalidCallExpr(
std::move(modifiers),
std::move(lhs),
open,
std::move(args),
std::move(commas),
close,
missingComma);
}
auto ParserImpl::nextExprIndex(NodePtr lhs) -> NodePtr {
auto open = consumeToken();
auto args = std::vector<NodePtr>{};
auto commas = std::vector<lex::Token>{};
auto missingComma = false;
while (peekToken(0).getKind() != lex::TokenKind::SepCloseSquare && !peekToken(0).isEnd()) {
args.push_back(nextExpr(0));
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else if (peekToken(0).getKind() != lex::TokenKind::SepCloseSquare) {
missingComma = true;
}
}
auto close = consumeToken();
const auto openValid = open.getKind() == lex::TokenKind::SepOpenSquare;
const auto closeValid = close.getKind() == lex::TokenKind::SepCloseSquare;
const auto commasValid = !missingComma && commas.size() == args.size() - 1;
if (openValid && closeValid && !args.empty() && commasValid) {
return indexExprNode(std::move(lhs), open, std::move(args), std::move(commas), close);
}
return errInvalidIndexExpr(std::move(lhs), open, std::move(args), std::move(commas), close);
}
auto ParserImpl::nextExprConditional(NodePtr condExpr) -> NodePtr {
auto qmark = consumeToken();
auto ifBranch = nextExpr(groupingPrecedence);
auto colon = consumeToken();
auto elseBranch = nextExpr(groupingPrecedence);
if (qmark.getKind() == lex::TokenKind::OpQMark && colon.getKind() == lex::TokenKind::SepColon) {
return conditionalExprNode(
std::move(condExpr), qmark, std::move(ifBranch), colon, std::move(elseBranch));
}
return errInvalidConditionalExpr(
std::move(condExpr), qmark, std::move(ifBranch), colon, std::move(elseBranch));
}
auto ParserImpl::nextExprParen() -> NodePtr {
auto open = consumeToken();
auto expr = nextExpr(0);
auto close = consumeToken();
if (open.getKind() == lex::TokenKind::SepOpenParen &&
close.getKind() == lex::TokenKind::SepCloseParen) {
return parenExprNode(open, std::move(expr), close);
}
return errInvalidParenExpr(open, std::move(expr), close);
}
auto ParserImpl::nextExprSwitch() -> NodePtr {
auto ifClauses = std::vector<NodePtr>{};
do {
ifClauses.push_back(nextExprSwitchIf());
} while (getKw(peekToken(0)) == lex::Keyword::If);
auto elseClause = getKw(peekToken(0)) == lex::Keyword::Else ? nextExprSwitchElse() : nullptr;
return switchExprNode(std::move(ifClauses), std::move(elseClause));
}
auto ParserImpl::nextExprSwitchIf() -> NodePtr {
auto kw = consumeToken();
auto cond = nextExpr(0);
auto arrow = consumeToken();
auto expr = nextExpr(0);
if (getKw(kw) == lex::Keyword::If && arrow.getKind() == lex::TokenKind::SepArrow) {
return switchExprIfNode(kw, std::move(cond), arrow, std::move(expr));
}
return errInvalidSwitchIf(kw, std::move(cond), arrow, std::move(expr));
}
auto ParserImpl::nextExprSwitchElse() -> NodePtr {
auto kw = consumeToken();
auto arrow = consumeToken();
auto expr = nextExpr(0);
if (getKw(kw) == lex::Keyword::Else && arrow.getKind() == lex::TokenKind::SepArrow) {
return switchExprElseNode(kw, arrow, std::move(expr));
}
return errInvalidSwitchElse(kw, arrow, std::move(expr));
}
auto ParserImpl::nextExprAnonFunc(std::vector<lex::Token> modifiers) -> NodePtr {
auto kw = consumeToken();
auto argList = nextArgDeclList();
auto retType = std::optional<RetTypeSpec>{};
if (peekToken(0).getKind() == lex::TokenKind::SepArrow) {
retType = nextRetTypeSpec();
}
auto body = nextExpr(0);
auto retTypeValid = !retType || retType->validate();
if (getKw(kw) == lex::Keyword::Lambda && argList.validate() && retTypeValid) {
return anonFuncExprNode(
std::move(modifiers), kw, std::move(argList), std::move(retType), std::move(body));
}
return errInvalidAnonFuncExpr(
std::move(modifiers), kw, std::move(argList), std::move(retType), std::move(body));
}
auto ParserImpl::nextType() -> Type {
auto id = consumeToken();
if (peekToken(0).getKind() == lex::TokenKind::SepOpenCurly) {
return Type{id, nextTypeParamList()};
}
return Type{id};
}
auto ParserImpl::nextTypeParamList() -> TypeParamList {
auto open = consumeToken();
auto params = std::vector<Type>{};
auto commas = std::vector<lex::Token>{};
auto missingComma = false;
while (peekToken(0).getKind() != lex::TokenKind::SepCloseCurly && !peekToken(0).isEnd()) {
params.push_back(nextType());
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else if (peekToken(0).getKind() != lex::TokenKind::SepCloseCurly) {
missingComma = true;
}
}
auto close = consumeToken();
return TypeParamList(open, std::move(params), std::move(commas), close, missingComma);
}
auto ParserImpl::nextTypeSubstitutionList() -> TypeSubstitutionList {
auto open = consumeToken();
auto params = std::vector<lex::Token>{};
auto commas = std::vector<lex::Token>{};
bool missingComma = false;
while (peekToken(0).getKind() != lex::TokenKind::SepCloseCurly && !peekToken(0).isEnd()) {
params.push_back(consumeToken());
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else if (peekToken(0).getKind() != lex::TokenKind::SepCloseCurly) {
missingComma = true;
}
}
auto close = consumeToken();
return TypeSubstitutionList(open, std::move(params), std::move(commas), close, missingComma);
}
auto ParserImpl::nextArgDeclList() -> ArgumentListDecl {
auto open = consumeToken();
auto empty = open.getKind() == lex::TokenKind::OpParenParen;
auto args = std::vector<ArgumentListDecl::ArgSpec>{};
auto commas = std::vector<lex::Token>{};
auto missingComma = false;
if (!empty) {
while (isPossibleTypeToken(peekToken(0)) ||
peekToken(0).getKind() == lex::TokenKind::SepComma) {
auto argType = nextType();
auto argId = consumeToken();
auto argInitializer = std::optional<ArgumentListDecl::ArgInitializer>{};
if (peekToken(0).getKind() == lex::TokenKind::OpEq) {
auto eq = consumeToken();
NodePtr initializerExpr = nullptr;
if (peekToken(0).getKind() != lex::TokenKind::SepComma &&
peekToken(0).getKind() != lex::TokenKind::SepCloseParen) {
initializerExpr = nextExpr(assignmentPrecedence);
}
argInitializer =
ArgumentListDecl::ArgInitializer{std::move(eq), std::move(initializerExpr)};
}
args.emplace_back(argType, argId, std::move(argInitializer));
if (peekToken(0).getKind() == lex::TokenKind::SepComma) {
commas.push_back(consumeToken());
} else if (
peekToken(0).getKind() == lex::TokenKind::Identifier ||
peekToken(0).getKind() == lex::TokenKind::Keyword) {
missingComma = true;
}
}
}
auto close = empty ? open : consumeToken();
return ArgumentListDecl(open, std::move(args), std::move(commas), close, missingComma);
}
auto ParserImpl::nextRetTypeSpec() -> RetTypeSpec {
auto arrow = consumeToken();
auto type = nextType();
return RetTypeSpec{arrow, std::move(type)};
}
auto ParserImpl::consumeToken() -> lex::Token {
if (!m_readBuffer.empty()) {
auto t = std::move(m_readBuffer.front());
m_readBuffer.pop_front();
return t;
}
return getFromInput();
}
auto ParserImpl::peekToken(const size_t ahead) -> lex::Token& {
for (auto i = m_readBuffer.size(); i <= ahead; i++) {
m_readBuffer.push_back(getFromInput());
}
return m_readBuffer[ahead];
}
} // namespace internal
// Explicit instantiations.
template class Parser<lex::Token*, lex::Token*>;
template class Parser<std::vector<lex::Token>::iterator, std::vector<lex::Token>::iterator>;
} // namespace parse
| 34.596317
| 100
| 0.642825
|
BastianBlokland
|
6d7440910ad179bb7651aff1c3d4f2c764bf8f2a
| 7,002
|
cpp
|
C++
|
Libraries/AP_Math_mdk5/AP_Math.cpp
|
SuWeipeng/xm_rc
|
7f5d9bcfc42dff7e9e72a3e096b195ea1a3076aa
|
[
"Apache-2.0"
] | 2
|
2020-03-10T03:00:38.000Z
|
2020-05-04T02:40:10.000Z
|
Libraries/AP_Math_mdk5/AP_Math.cpp
|
SuWeipeng/xm_rc
|
7f5d9bcfc42dff7e9e72a3e096b195ea1a3076aa
|
[
"Apache-2.0"
] | null | null | null |
Libraries/AP_Math_mdk5/AP_Math.cpp
|
SuWeipeng/xm_rc
|
7f5d9bcfc42dff7e9e72a3e096b195ea1a3076aa
|
[
"Apache-2.0"
] | 3
|
2020-03-10T03:00:48.000Z
|
2021-01-26T06:03:49.000Z
|
#include "AP_Math.h"
template <typename T>
float safe_asin(const T v)
{
const float f = static_cast<float>(v);
if (isnan(f)) {
return 0.0f;
}
if (f >= 1.0f) {
return static_cast<float>(M_PI_2);
}
if (f <= -1.0f) {
return static_cast<float>(-M_PI_2);
}
return asinf(f);
}
template float safe_asin<int>(const int v);
template float safe_asin<short>(const short v);
template float safe_asin<float>(const float v);
template float safe_asin<double>(const double v);
template <typename T>
float safe_sqrt(const T v)
{
float ret = sqrtf(static_cast<float>(v));
if (isnan(ret)) {
return 0;
}
return ret;
}
template float safe_sqrt<int>(const int v);
template float safe_sqrt<short>(const short v);
template float safe_sqrt<float>(const float v);
template float safe_sqrt<double>(const double v);
/*
* linear interpolation based on a variable in a range
*/
float linear_interpolate(float low_output, float high_output,
float var_value,
float var_low, float var_high)
{
if (var_value <= var_low) {
return low_output;
}
if (var_value >= var_high) {
return high_output;
}
float p = (var_value - var_low) / (var_high - var_low);
return low_output + p * (high_output - low_output);
}
/* cubic "expo" curve generator
* alpha range: [0,1] min to max expo
* input range: [-1,1]
*/
float expo_curve(float alpha, float x)
{
return (1.0f - alpha) * x + alpha * x * x * x;
}
/* throttle curve generator
* thr_mid: output at mid stick
* alpha: expo coefficient
* thr_in: [0-1]
*/
float throttle_curve(float thr_mid, float alpha, float thr_in)
{
float alpha2 = alpha + 1.25f * (1.0f - alpha) * (0.5f - thr_mid) / 0.5f;
alpha2 = constrain_float(alpha2, 0.0f, 1.0f);
float thr_out = 0.0f;
if (thr_in < 0.5f) {
float t = linear_interpolate(-1.0f, 0.0f, thr_in, 0.0f, 0.5f);
thr_out = linear_interpolate(0.0f, thr_mid, expo_curve(alpha, t), -1.0f, 0.0f);
} else {
float t = linear_interpolate(0.0f, 1.0f, thr_in, 0.5f, 1.0f);
thr_out = linear_interpolate(thr_mid, 1.0f, expo_curve(alpha2, t), 0.0f, 1.0f);
}
return thr_out;
}
//template <typename T>
//float wrap_180(const T angle, float unit_mod)
//{
// auto res = wrap_360(angle, unit_mod);
// if (res > 180.f * unit_mod) {
// res -= 360.f * unit_mod;
// }
// return res;
//}
//template float wrap_180<int>(const int angle, float unit_mod);
//template float wrap_180<short>(const short angle, float unit_mod);
//template float wrap_180<float>(const float angle, float unit_mod);
//template float wrap_180<double>(const double angle, float unit_mod);
//template <typename T>
//auto wrap_180_cd(const T angle) -> decltype(wrap_180(angle, 100.f))
//{
// return wrap_180(angle, 100.f);
//}
//template auto wrap_180_cd<float>(const float angle) -> decltype(wrap_180(angle, 100.f));
//template auto wrap_180_cd<int>(const int angle) -> decltype(wrap_180(angle, 100.f));
//template auto wrap_180_cd<long>(const long angle) -> decltype(wrap_180(angle, 100.f));
//template auto wrap_180_cd<short>(const short angle) -> decltype(wrap_180(angle, 100.f));
//template auto wrap_180_cd<double>(const double angle) -> decltype(wrap_360(angle, 100.f));
template <typename T>
float wrap_360(const T angle, float unit_mod)
{
const float ang_360 = 360.f * unit_mod;
float res = fmodf(static_cast<float>(angle), ang_360);
if (res < 0) {
res += ang_360;
}
return res;
}
template float wrap_360<int>(const int angle, float unit_mod);
template float wrap_360<short>(const short angle, float unit_mod);
template float wrap_360<long>(const long angle, float unit_mod);
template float wrap_360<float>(const float angle, float unit_mod);
template float wrap_360<double>(const double angle, float unit_mod);
//template <typename T>
//auto wrap_360_cd(const T angle) -> decltype(wrap_360(angle, 100.f))
//{
// return wrap_360(angle, 100.f);
//}
//template auto wrap_360_cd<float>(const float angle) -> decltype(wrap_360(angle, 100.f));
//template auto wrap_360_cd<int>(const int angle) -> decltype(wrap_360(angle, 100.f));
//template auto wrap_360_cd<long>(const long angle) -> decltype(wrap_360(angle, 100.f));
//template auto wrap_360_cd<short>(const short angle) -> decltype(wrap_360(angle, 100.f));
//template auto wrap_360_cd<double>(const double angle) -> decltype(wrap_360(angle, 100.f));
//template <typename T>
//float wrap_PI(const T radian)
//{
// auto res = wrap_2PI(radian);
// if (res > M_PI) {
// res -= M_2PI;
// }
// return res;
//}
//template float wrap_PI<int>(const int radian);
//template float wrap_PI<short>(const short radian);
//template float wrap_PI<float>(const float radian);
//template float wrap_PI<double>(const double radian);
template <typename T>
float wrap_2PI(const T radian)
{
float res = fmodf(static_cast<float>(radian), M_2PI);
if (res < 0) {
res += M_2PI;
}
return res;
}
template float wrap_2PI<int>(const int radian);
template float wrap_2PI<short>(const short radian);
template float wrap_2PI<float>(const float radian);
template float wrap_2PI<double>(const double radian);
template <typename T>
T constrain_value(const T amt, const T low, const T high)
{
// the check for NaN as a float prevents propagation of floating point
// errors through any function that uses constrain_value(). The normal
// float semantics already handle -Inf and +Inf
if (isnan(amt)) {
return (low + high) / 2;
}
if (amt < low) {
return low;
}
if (amt > high) {
return high;
}
return amt;
}
template int constrain_value<int>(const int amt, const int low, const int high);
template long constrain_value<long>(const long amt, const long low, const long high);
template long long constrain_value<long long>(const long long amt, const long long low, const long long high);
template short constrain_value<short>(const short amt, const short low, const short high);
template float constrain_value<float>(const float amt, const float low, const float high);
template double constrain_value<double>(const double amt, const double low, const double high);
/*
simple 16 bit random number generator
*/
uint16_t get_random16(void)
{
static uint32_t m_z = 1234;
static uint32_t m_w = 76542;
m_z = 36969 * (m_z & 0xFFFFu) + (m_z >> 16);
m_w = 18000 * (m_w & 0xFFFFu) + (m_w >> 16);
return ((m_z << 16) + m_w) & 0xFFFF;
}
bool is_valid_octal(uint16_t octal)
{
// treat "octal" as decimal and test if any decimal digit is > 7
if (octal > 7777) {
return false;
} else if (octal % 10 > 7) {
return false;
} else if ((octal % 100)/10 > 7) {
return false;
} else if ((octal % 1000)/100 > 7) {
return false;
} else if ((octal % 10000)/1000 > 7) {
return false;
}
return true;
}
| 30.710526
| 110
| 0.663239
|
SuWeipeng
|
6d7c57829826b74f9759251eb7ba039de1ce3b37
| 6,717
|
cpp
|
C++
|
testing/testing_zher2k.cpp
|
shengren/magma-1.6.1
|
1adfee30b763e9491a869403e0f320b3888923b6
|
[
"BSD-3-Clause"
] | 21
|
2017-10-06T05:05:05.000Z
|
2022-03-13T15:39:20.000Z
|
testing/testing_zher2k.cpp
|
shengren/magma-1.6.1
|
1adfee30b763e9491a869403e0f320b3888923b6
|
[
"BSD-3-Clause"
] | 1
|
2017-03-23T00:27:24.000Z
|
2017-03-23T00:27:24.000Z
|
testing/testing_zher2k.cpp
|
shengren/magma-1.6.1
|
1adfee30b763e9491a869403e0f320b3888923b6
|
[
"BSD-3-Clause"
] | 4
|
2018-01-09T15:49:58.000Z
|
2022-03-13T15:39:27.000Z
|
/*
-- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
@precisions normal z -> c d s
@author Chongxiao Cao
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "testings.h" // before magma.h, to include cublas_v2
#include "flops.h"
#include "magma.h"
#include "magma_lapack.h"
/* ////////////////////////////////////////////////////////////////////////////
-- Testing zher2k
*/
int main( int argc, char** argv)
{
TESTING_INIT();
real_Double_t gflops, cublas_perf, cublas_time, cpu_perf, cpu_time;
double cublas_error, Cnorm, work[1];
magma_int_t N, K;
magma_int_t Ak, An, Bk, Bn;
magma_int_t sizeA, sizeB, sizeC;
magma_int_t lda, ldb, ldc, ldda, lddb, lddc;
magma_int_t ione = 1;
magma_int_t ISEED[4] = {0,0,0,1};
magmaDoubleComplex *h_A, *h_B, *h_C, *h_Ccublas;
magmaDoubleComplex_ptr d_A, d_B, d_C;
magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
magmaDoubleComplex alpha = MAGMA_Z_MAKE( 0.29, -0.86 );
double beta = MAGMA_D_MAKE( -0.48, 0.38 );
magma_int_t status = 0;
magma_opts opts;
parse_opts( argc, argv, &opts );
opts.lapack |= opts.check; // check (-c) implies lapack (-l)
double tol = opts.tolerance * lapackf77_dlamch("E");
printf("If running lapack (option --lapack), CUBLAS error is computed\n"
"relative to CPU BLAS result.\n\n");
printf("uplo = %s, transA = %s\n",
lapack_uplo_const(opts.uplo), lapack_trans_const(opts.transA) );
printf(" N K CUBLAS Gflop/s (ms) CPU Gflop/s (ms) CUBLAS error\n");
printf("==================================================================\n");
for( int itest = 0; itest < opts.ntest; ++itest ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
N = opts.msize[itest];
K = opts.ksize[itest];
gflops = FLOPS_ZHER2K(K, N) / 1e9;
if ( opts.transA == MagmaNoTrans ) {
lda = An = N;
Ak = K;
ldb = Bn = N;
Bk = K;
} else {
lda = An = K;
Ak = N;
ldb = Bn = K;
Bk = N;
}
ldc = N;
ldda = ((lda+31)/32)*32;
lddb = ((ldb+31)/32)*32;
lddc = ((ldc+31)/32)*32;
sizeA = lda*Ak;
sizeB = ldb*Ak;
sizeC = ldc*N;
TESTING_MALLOC_CPU( h_A, magmaDoubleComplex, lda*Ak );
TESTING_MALLOC_CPU( h_B, magmaDoubleComplex, ldb*Bk );
TESTING_MALLOC_CPU( h_C, magmaDoubleComplex, ldc*N );
TESTING_MALLOC_CPU( h_Ccublas, magmaDoubleComplex, ldc*N );
TESTING_MALLOC_DEV( d_A, magmaDoubleComplex, ldda*Ak );
TESTING_MALLOC_DEV( d_B, magmaDoubleComplex, lddb*Bk );
TESTING_MALLOC_DEV( d_C, magmaDoubleComplex, lddc*N );
/* Initialize the matrices */
lapackf77_zlarnv( &ione, ISEED, &sizeA, h_A );
lapackf77_zlarnv( &ione, ISEED, &sizeB, h_B );
lapackf77_zlarnv( &ione, ISEED, &sizeC, h_C );
/* =====================================================================
Performs operation using CUBLAS
=================================================================== */
magma_zsetmatrix( An, Ak, h_A, lda, d_A, ldda );
magma_zsetmatrix( Bn, Bk, h_B, ldb, d_B, lddb );
magma_zsetmatrix( N, N, h_C, ldc, d_C, lddc );
cublas_time = magma_sync_wtime( NULL );
cublasZher2k( opts.handle, cublas_uplo_const(opts.uplo), cublas_trans_const(opts.transA), N, K,
&alpha, d_A, ldda,
d_B, lddb,
&beta, d_C, lddc );
cublas_time = magma_sync_wtime( NULL ) - cublas_time;
cublas_perf = gflops / cublas_time;
magma_zgetmatrix( N, N, d_C, lddc, h_Ccublas, ldc );
/* =====================================================================
Performs operation using CPU BLAS
=================================================================== */
if ( opts.lapack ) {
cpu_time = magma_wtime();
blasf77_zher2k( lapack_uplo_const(opts.uplo), lapack_trans_const(opts.transA), &N, &K,
&alpha, h_A, &lda,
h_B, &ldb,
&beta, h_C, &ldc );
cpu_time = magma_wtime() - cpu_time;
cpu_perf = gflops / cpu_time;
}
/* =====================================================================
Check the result
=================================================================== */
if ( opts.lapack ) {
// compute relative error for both magma & cublas, relative to lapack,
// |C_magma - C_lapack| / |C_lapack|
Cnorm = lapackf77_zlange( "M", &N, &N, h_C, &ldc, work );
blasf77_zaxpy( &sizeC, &c_neg_one, h_C, &ione, h_Ccublas, &ione );
cublas_error = lapackf77_zlange( "M", &N, &N, h_Ccublas, &ldc, work ) / Cnorm;
printf("%5d %5d %7.2f (%7.2f) %7.2f (%7.2f) %8.2e %s\n",
(int) N, (int) K,
cublas_perf, 1000.*cublas_time,
cpu_perf, 1000.*cpu_time,
cublas_error, (cublas_error < tol ? "ok" : "failed"));
status += ! (cublas_error < tol);
}
else {
printf("%5d %5d %7.2f (%7.2f) --- ( --- ) --- ---\n",
(int) N, (int) K,
cublas_perf, 1000.*cublas_time);
}
TESTING_FREE_CPU( h_A );
TESTING_FREE_CPU( h_B );
TESTING_FREE_CPU( h_C );
TESTING_FREE_CPU( h_Ccublas );
TESTING_FREE_DEV( d_A );
TESTING_FREE_DEV( d_B );
TESTING_FREE_DEV( d_C );
fflush( stdout );
}
if ( opts.niter > 1 ) {
printf( "\n" );
}
}
TESTING_FINALIZE();
return status;
}
| 38.82659
| 107
| 0.441566
|
shengren
|
6d7e79c566bf1865dac47afda7cad544b5755b0d
| 4,026
|
cpp
|
C++
|
src/cache/index/query_manager/emkde_query_manager.cpp
|
EmanuelHerrendorf/mapping-core
|
d28d85547e8ed08df37dad1da142594d3f07a366
|
[
"MIT"
] | null | null | null |
src/cache/index/query_manager/emkde_query_manager.cpp
|
EmanuelHerrendorf/mapping-core
|
d28d85547e8ed08df37dad1da142594d3f07a366
|
[
"MIT"
] | 10
|
2018-03-02T13:58:32.000Z
|
2020-06-05T11:12:42.000Z
|
src/cache/index/query_manager/emkde_query_manager.cpp
|
EmanuelHerrendorf/mapping-core
|
d28d85547e8ed08df37dad1da142594d3f07a366
|
[
"MIT"
] | 3
|
2018-02-26T14:01:43.000Z
|
2019-12-09T10:03:17.000Z
|
/*
* bema_query_manager.cpp
*
* Created on: 24.05.2016
* Author: koerberm
*/
#include "cache/index/query_manager/emkde_query_manager.h"
#include "util/log.h"
#include "util/exceptions.h"
const GDAL::CRSTransformer EMKDEQueryManager::TRANS_GEOSMSG(CrsId::from_epsg_code(0x9E05),
CrsId::from_epsg_code(4326));
const GDAL::CRSTransformer EMKDEQueryManager::TRANS_WEBMERCATOR(
CrsId::from_epsg_code(3857), CrsId::from_epsg_code(4326));
const uint32_t EMKDEQueryManager::MAX_Z = 0xFFFFFFFF;
const uint32_t EMKDEQueryManager::MASKS[] = { 0x55555555, 0x33333333,
0x0F0F0F0F, 0x00FF00FF };
const uint32_t EMKDEQueryManager::SHIFTS[] = { 1, 2, 4, 8 };
const uint16_t EMKDEQueryManager::SCALE_X = 0xFFFF / 360;
const uint16_t EMKDEQueryManager::SCALE_Y = 0xFFFF / 180;
EMKDEQueryManager::EMKDEQueryManager(
const std::map<uint32_t, std::shared_ptr<Node> >& nodes) :
SimpleQueryManager(nodes), alpha(0.3), bandwith(6) {
bins.fill(0);
}
std::unique_ptr<PendingQuery> EMKDEQueryManager::create_job(
const BaseRequest& req) {
check_nodes_changed();
uint32_t node = 0;
auto hv = get_hilbert_value(req.query);
for (auto &n : bounds) {
if (hv <= n.hilbert_bound) {
node = n.node_id;
break;
}
}
if (node == 0) {
Log::error("Bound: %u, Max: %u bounds: %s", hv, MAX_Z, bounds_to_string().c_str() );
throw MustNotHappenException("No node found to schedule job on!");
}
double fsum = update_bins(hv);
update_bounds(fsum);
return std::make_unique<SimpleJob>(req, node);
}
double EMKDEQueryManager::update_bins(uint32_t hv) {
uint32_t selected = hv / (MAX_Z / bins.size());
double fsum = 0;
for (uint32_t i = 0; i < bins.size(); i++) {
if (i >= (selected - bandwith / 2) && i <= (selected + bandwith / 2)) {
bins[i] = bins[i] * (1.0 - alpha) + alpha / (bandwith + 1);
} else
bins[i] *= (1.0 - alpha);
fsum += bins[i];
}
return fsum;
}
void EMKDEQueryManager::check_nodes_changed() {
if (nodes.size() != bounds.size()) {
bounds.clear();
for (auto &p : nodes) {
bounds.push_back(EMNode(p.first));
}
double sum = 0;
for (auto &f : bins)
sum += f;
update_bounds(sum);
}
}
std::string EMKDEQueryManager::bounds_to_string() const {
std::ostringstream ss;
ss << "Bounds: [";
for (auto &en : bounds) {
ss << en.node_id << ": " << en.hilbert_bound << ", ";
}
ss << "]";
return ss.str();
}
void EMKDEQueryManager::update_bounds(double fsum) {
if (fsum == 0) {
for (auto &n : bounds)
n.hilbert_bound = MAX_Z;
return;
}
double per_node = fsum / bounds.size();
double bin_width = MAX_Z / bins.size();
double f = bins[0];
double sum = 0;
double bound = 0;
double interp = 0;
size_t s = 0;
size_t i = 0;
while (i < bins.size()) {
if (sum + f <= per_node) {
sum += f;
f = bins[++i];
bin_width = MAX_Z / bins.size();
bound = bin_width * i;
} else {
interp = (per_node - sum) / f;
bound += interp * bin_width;
bounds[s++].hilbert_bound = bound;
f = f - (per_node - sum);
bin_width -= interp * bin_width;
sum = 0;
}
}
//TODO: Check this hack
bounds.back().hilbert_bound = MAX_Z;
Log::debug("%s", bounds_to_string().c_str());
}
uint32_t EMKDEQueryManager::get_hilbert_value(const QueryRectangle& rect) {
double ex = rect.x1 + (rect.x2 - rect.x1) / 2.0;
double ey = rect.y1 + (rect.y2 - rect.y1) / 2.0;
if (rect.crsId == CrsId::from_epsg_code(0x9E05)) {
EMKDEQueryManager::TRANS_GEOSMSG.transform(ex, ey);
} else if (rect.crsId == CrsId::from_epsg_code(3857)) {
EMKDEQueryManager::TRANS_WEBMERCATOR.transform(ex, ey);
}
// Translate and scale
uint32_t x = (ex + 180) * SCALE_X;
uint32_t y = (ey + 90) * SCALE_Y;
x = (x | (x << SHIFTS[3])) & MASKS[3];
x = (x | (x << SHIFTS[2])) & MASKS[2];
x = (x | (x << SHIFTS[1])) & MASKS[1];
x = (x | (x << SHIFTS[0])) & MASKS[0];
y = (y | (y << SHIFTS[3])) & MASKS[3];
y = (y | (y << SHIFTS[2])) & MASKS[2];
y = (y | (y << SHIFTS[1])) & MASKS[1];
y = (y | (y << SHIFTS[0])) & MASKS[0];
uint32_t result = x | (y << 1);
return result;
}
| 25.643312
| 90
| 0.633631
|
EmanuelHerrendorf
|
6d80a00cdeddab88508bb0c9b4028748643509e0
| 2,591
|
cc
|
C++
|
src/python/swig/pyevent.cc
|
cmlasu/smm_gem5
|
2865229999904d531f5510ca50552b396efeaea0
|
[
"BSD-3-Clause"
] | 31
|
2015-12-15T19:14:10.000Z
|
2021-12-31T17:40:21.000Z
|
src/python/swig/pyevent.cc
|
jcai19/smm_gem5
|
15e10bd32ef4a4d18e5d846b015d11317d319bcc
|
[
"BSD-3-Clause"
] | 5
|
2015-12-04T08:06:47.000Z
|
2020-08-09T21:49:46.000Z
|
src/python/swig/pyevent.cc
|
jcai19/smm_gem5
|
15e10bd32ef4a4d18e5d846b015d11317d319bcc
|
[
"BSD-3-Clause"
] | 21
|
2015-11-05T08:25:45.000Z
|
2021-06-19T02:24:50.000Z
|
/*
* Copyright (c) 2006 The Regents of The University of Michigan
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
*/
#include <Python.h>
#include "python/swig/pyevent.hh"
#include "sim/async.hh"
#include "sim/eventq.hh"
PythonEvent::PythonEvent(PyObject *obj, Priority priority)
: Event(priority), object(obj)
{
if (object == NULL)
panic("Passed in invalid object");
}
PythonEvent::~PythonEvent()
{
}
void
PythonEvent::process()
{
PyObject *args = PyTuple_New(0);
PyObject *result = PyObject_Call(object, args, NULL);
Py_DECREF(args);
if (result) {
// Nothing to do just decrement the reference count
Py_DECREF(result);
} else {
// Somethign should be done to signal back to the main interpreter
// that there's been an exception.
async_event = true;
async_exception = true;
/* Wake up some event queue to handle event */
getEventQueue(0)->wakeup();
}
// Since the object has been removed from the event queue, its
// reference count must be decremented.
Py_DECREF(object);
}
| 36.492958
| 74
| 0.727904
|
cmlasu
|
6d812d3d90981b8016e2fcbef0d0357e84227579
| 956
|
hpp
|
C++
|
include/lea/engine/ecs/typename.hpp
|
jfalcou/lea
|
85c3648af1b67aa70320df1c60fec457f82b5f81
|
[
"MIT"
] | 2
|
2019-08-12T22:54:48.000Z
|
2020-06-01T22:23:07.000Z
|
include/lea/engine/ecs/typename.hpp
|
jfalcou/lea
|
85c3648af1b67aa70320df1c60fec457f82b5f81
|
[
"MIT"
] | null | null | null |
include/lea/engine/ecs/typename.hpp
|
jfalcou/lea
|
85c3648af1b67aa70320df1c60fec457f82b5f81
|
[
"MIT"
] | null | null | null |
//==================================================================================================
/**
LEA - Little Engine Adventure
Copyright 2020 Joel FALCOU
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#pragma once
#include <string_view>
namespace lea
{
template<typename T> struct type_name_
{
static constexpr auto value() noexcept
{
#if defined(_MSC_VER )
std::string_view data(__FUNCSIG__);
auto i = data.find('<') + 1, j = data.find(">::value");
return data.substr(i, j - i);
#else
std::string_view data(__PRETTY_FUNCTION__);
auto i = data.find('=') + 2, j = data.find_last_of(']');
return data.substr(i, j - i);
#endif
}
};
template<typename T>
inline constexpr auto const typename_ = type_name_<T>::value();
}
| 27.314286
| 100
| 0.507322
|
jfalcou
|
6d8188019352ad083720c90e9ed84de2704a071f
| 1,868
|
cpp
|
C++
|
examples/accept.cpp
|
ksergey/NetBox
|
e9bc4fbd22561e841d16a2420be0df387cb8477d
|
[
"Unlicense"
] | 1
|
2019-10-25T03:15:04.000Z
|
2019-10-25T03:15:04.000Z
|
examples/accept.cpp
|
ksergey/NetBox
|
e9bc4fbd22561e841d16a2420be0df387cb8477d
|
[
"Unlicense"
] | null | null | null |
examples/accept.cpp
|
ksergey/NetBox
|
e9bc4fbd22561e841d16a2420be0df387cb8477d
|
[
"Unlicense"
] | null | null | null |
// ------------------------------------------------------------
// Copyright 2017-present Sergey Kovalevich <inndie@gmail.com>
// ------------------------------------------------------------
#include <cstdlib>
#include <iostream>
#include <netbox/socket_ops.h>
#include <netbox/socket_options.h>
using namespace netbox;
int main(int argc, char* argv[])
{
try {
if (argc < 2) {
std::cout << "Usage: Accept <port> [bind-ip]\n";
return EXIT_FAILURE;
}
auto port = std::atoi(argv[1]);
if (port <= 0 || port > 65536) {
throwEx< std::runtime_error >("Port out of range");
}
IPv4::Address address = (argc > 2)
? IPv4::addressFromString(argv[2])
: IPv4::Address::any();
std::cout << toString(address) << '\n';
IPv4::Endpoint endpoint{address, std::uint16_t(port)};
auto socket = Socket::create(AF_INET, SOCK_STREAM, 0);
if (auto result = setOption(socket, Options::Socket::ReuseAddr{true}); !result) {
std::cout << "Can't set option ReuseAddr (" << result.str() << ")\n";
}
if (auto result = bind(socket, endpoint); !result) {
std::cout << "Can't bind socket (" << result.str() << ")\n";
}
if (auto result = listen(socket); !result) {
std::cout << "Can't listen (" << result.str() << ")\n";
}
IPv4::Endpoint client;
auto result = accept(socket, client);
if (result) {
std::cout << "Connection accept (" << toString(client.address()) << ':' << client.port() << ")\n";
} else {
std::cout << "Error: " << result.str() << '\n';
}
} catch (const std::exception& e) {
std::cout << "ERROR: " << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 31.133333
| 110
| 0.485011
|
ksergey
|
6d8bb6c47300e8e64598acb61427848d0ace4ada
| 9,194
|
hpp
|
C++
|
lib/include/glow_dkg.hpp
|
fetchai/research-dvrf
|
943b335e1733bb9b2ef403e4f8237dfdc4f93952
|
[
"Apache-2.0"
] | 16
|
2020-02-08T00:04:58.000Z
|
2022-01-18T11:42:07.000Z
|
lib/include/glow_dkg.hpp
|
fetchai/research-dvrf
|
943b335e1733bb9b2ef403e4f8237dfdc4f93952
|
[
"Apache-2.0"
] | null | null | null |
lib/include/glow_dkg.hpp
|
fetchai/research-dvrf
|
943b335e1733bb9b2ef403e4f8237dfdc4f93952
|
[
"Apache-2.0"
] | 4
|
2021-07-20T08:56:08.000Z
|
2022-01-03T01:48:12.000Z
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2019-2020 Fetch.AI Limited
//
// 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 "base_dkg.hpp"
namespace fetch {
namespace consensus {
template<class CryptoType>
class GlowDkg : public BaseDkg<CryptoType, typename CryptoType::Signature> {
public:
using PrivateKey = typename CryptoType::PrivateKey;
using Signature = typename CryptoType::Signature;
using GroupPublicKey = typename CryptoType::GroupPublicKey;
using VerificationKey = typename CryptoType::Signature;
using Pairing = typename CryptoType::Pairing;
using MessagePayload = std::string;
GlowDkg(uint32_t committeeSize, uint32_t threshold) : BaseDkg<CryptoType, typename CryptoType::Signature>{
committeeSize, threshold} {
CryptoType::setGenerator(g2_);
a_i_.resize(this->polynomialDegree_ + 1);
B_i_.resize(this->committeeSize_);
}
virtual ~GlowDkg() = default;
/**
* Generate coefficients and secret shares to be broadcast and sent directly to each member,
* respectively
* @param rank Our index
* @return pair of broadcast and vector of direct messages to be sent
*/
std::pair<fetch::consensus::pb::Broadcast, std::vector<fetch::consensus::pb::PrivateShares>>
createCoefficientsAndShares(uint32_t rank) override {
std::vector<PrivateKey> b_i;
b_i.resize(this->polynomialDegree_ + 1);
for (size_t k = 0; k <= this->polynomialDegree_; k++) {
a_i_[k].random();
b_i[k].random();
}
return std::make_pair(createCoefficients(a_i_, b_i, rank), this->createShares(a_i_, b_i, rank));
}
/**
* Fill a coefficients message with our qual coefficients to be broadcasted
*
* @param coefs Coefficients message
* @param rank Our index
*/
void computeQualCoefficient(fetch::consensus::pb::Broadcast_Coefficients &coefs, uint32_t rank) override {
B_i_[rank].mult(g2_, a_i_[0]);
// Make first element in coefficients message B_i_
coefs.add_coefficients(B_i_[rank].toString());
// Now add later coefficients
for (size_t k = 0; k <= this->polynomialDegree_; k++) {
this->A_ik_[rank][k].mult(this->G, a_i_[k]);
coefs.add_coefficients(this->A_ik_[rank][k].toString());
}
}
/**
* Insert qual coefficients from other qualified members
*
* @param from Index of sender
* @param i Index in coefficients vector
* @param coef String value of the coefficient at i
* @return bool indicating whether value passes deserialisation
*/
bool setQualCoefficient(uint32_t from, uint32_t i, const std::string &coef) override {
if (i == 0 and B_i_[from].isZero()) {
return B_i_[from].assign(coef);
} else if (i > 0 and i <= this->polynomialDegree_ + 1 and this->A_ik_[from][i - 1].isZero()) {
return this->A_ik_[from][i - 1].assign(coef);
}
return false;
}
/**
* Checks qual coefficients received from qualified members
*
* @param rank Our index
* @param i Index in vector of coefficient
* @return Whether coefficient passed verification
*/
bool verifyQualCoefficient(uint32_t rank, uint32_t i) const override {
if (!this->A_ik_[i][0].isZero()) {
VerificationKey rhs, lhs;
lhs = this->g__s_ij_[i][rank];
rhs = this->computeRHS(rank, this->A_ik_[i]);
if (lhs == rhs) {
Pairing e1, e2;
e1.map(this->G, B_i_[i]);
e2.map(this->A_ik_[i][0], g2_);
return e1 == e2;
}
}
return false;
}
/**
* Verify whether a qual complaint was genuine from broadcasted secret shares
*
* @param nodeIndex Index of node being complained against
* @param fromIndex Index of complaint filer
* @param first First secret share as string
* @param second Second secret share as string
* @return Pair of bools whether the shares pass verification with respect to initial and
* qual coefficients, respectively
*/
std::pair<bool, bool> verifyQualComplaint(uint32_t nodeIndex, uint32_t fromIndex, const std::string &first,
const std::string &second) override {
std::pair<bool, bool> res{false, false};
VerificationKey lhs, rhs;
PrivateKey s, sprime;
if (s.assign(first) && sprime.assign(second)) {
lhs = this->computeLHS(this->G, this->H, s, sprime);
rhs = this->computeRHS(fromIndex, this->C_ik_[nodeIndex]);
res.first = lhs == rhs;
lhs.mult(this->G, s);
rhs = this->computeRHS(fromIndex, this->A_ik_[nodeIndex]);
Pairing e1, e2;
e1.map(this->G, B_i_[nodeIndex]);
e2.map(this->A_ik_[nodeIndex][0], g2_);
res.second = ((lhs == rhs) and (e1 == e2));
}
return res;
}
/**
* Run polynomial interpolation on the exposed secret shares of other cabinet members to
* recontruct their random polynomials
*
* @return Bool for whether reconstruction from shares was successful
*/
bool runReconstruction(const std::unordered_map<std::string, uint32_t> &nodesMap) override {
std::lock_guard<std::mutex> lock(this->mutex_);
assert(this->committeeSize_ == nodesMap.size());
std::vector<std::vector<PrivateKey>> a_ik;
this->init(a_ik, this->committeeSize_, this->polynomialDegree_ + 1);
for (const auto &in : this->reconstructionShares_) {
std::set<std::size_t> parties{in.second.first};
std::vector<PrivateKey> shares{in.second.second};
if (parties.size() <= this->polynomialDegree_) {
// Do not have enough good shares to be able to do reconstruction
return false;
}
auto iter = nodesMap.find(in.first);
assert(iter != nodesMap.end());
uint32_t victimIndex{iter->second};
std::vector<PrivateKey> points, shares_f;
for (const auto &index : parties) {
points.emplace_back(index + 1); // adjust index in computation
shares_f.push_back(shares[index]);
}
a_ik[victimIndex] = this->interpolatePolynom(points, shares_f);
for (size_t k = 0; k <= this->polynomialDegree_; k++) {
this->A_ik_[victimIndex][k].mult(this->G, a_ik[victimIndex][k]);
}
B_i_[victimIndex].mult(g2_, a_ik[victimIndex][0]);
}
return true;
}
/**
* Compute group public key and individual public key shares
*/
void
computePublicKeys(const std::set<std::string> &qual,
const std::unordered_map<std::string, uint32_t> &nodesMap) override {
std::lock_guard<std::mutex> lock(this->mutex_);
this->groupPublicKey_.setZero();
for (const auto &iq : qual) {
auto iter = nodesMap.find(iq);
assert(iter != nodesMap.end());
uint32_t it{iter->second};
this->groupPublicKey_.add(this->groupPublicKey_, B_i_[it]);
}
// Compute public verification keys
/*
for (const auto &jq : qual) {
auto iter_j = nodesMap.find(jq);
assert(iter_j != nodesMap.end());
uint32_t jt{iter_j->second};
for (const auto &iq : qual) {
auto iter_i = nodesMap.find(iq);
assert(iter_i != nodesMap.end());
uint32_t it{iter_i->second};
this->publicKeyShares_[jt].add(this->publicKeyShares_[jt], this->A_ik_[it][0]);
this->updateRHS(jt, this->publicKeyShares_[jt], this->A_ik_[it]);
}
}*/
std::vector<VerificationKey> vCoeff;
for (size_t k = 0; k <= this->polynomialDegree_; k++) {
VerificationKey tmpV;
tmpV.setZero();
for (const auto &jq : qual) {
auto iter_j = nodesMap.find(jq);
assert(iter_j != nodesMap.end());
uint32_t jt{iter_j->second};
tmpV.add(tmpV, this->A_ik_[jt][k]);
}
vCoeff.push_back(tmpV);
}
for (const auto &jq : qual) {
auto iter_j = nodesMap.find(jq);
assert(iter_j != nodesMap.end());
uint32_t jt{iter_j->second};
this->publicKeyShares_[jt].add(this->publicKeyShares_[jt], vCoeff[0]);
this->updateRHS(jt, this->publicKeyShares_[jt], vCoeff);
}
}
private:
GroupPublicKey g2_;
std::vector<PrivateKey> a_i_;
std::vector<GroupPublicKey> B_i_;
fetch::consensus::pb::Broadcast
createCoefficients(const std::vector<PrivateKey> &a_i, const std::vector<PrivateKey> &b_i, uint32_t rank) override {
fetch::consensus::pb::Broadcast broadcast;
auto *coefficients = broadcast.mutable_coefficients();
for (size_t k = 0; k <= this->polynomialDegree_; k++) {
this->C_ik_[rank][k] = this->computeLHS(this->G, this->H, a_i[k], b_i[k]);
coefficients->add_coefficients(this->C_ik_[rank][k].toString());
}
return broadcast;
}
};
}
}
| 35.498069
| 118
| 0.646291
|
fetchai
|
6d8c1efca1f229f75adacec1700215b822893a6f
| 6,069
|
hpp
|
C++
|
include/outcome/experimental/status_outcome.hpp
|
libbboze/outcome
|
248b05f75c723df56a5fa7988bb7de8b173a98ba
|
[
"Apache-2.0"
] | null | null | null |
include/outcome/experimental/status_outcome.hpp
|
libbboze/outcome
|
248b05f75c723df56a5fa7988bb7de8b173a98ba
|
[
"Apache-2.0"
] | null | null | null |
include/outcome/experimental/status_outcome.hpp
|
libbboze/outcome
|
248b05f75c723df56a5fa7988bb7de8b173a98ba
|
[
"Apache-2.0"
] | null | null | null |
/* A less simple result type
(C) 2018 Niall Douglas <http://www.nedproductions.biz/> (59 commits)
File Created: Apr 2018
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 in the accompanying file
Licence.txt or 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.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef OUTCOME_EXPERIMENTAL_STATUS_OUTCOME_HPP
#define OUTCOME_EXPERIMENTAL_STATUS_OUTCOME_HPP
#include "../basic_outcome.hpp"
#include "../detail/trait_std_exception.hpp"
#include "status_result.hpp"
// Boost.Outcome #include "boost/exception_ptr.hpp"
SYSTEM_ERROR2_NAMESPACE_BEGIN
template <class DomainType> inline std::exception_ptr basic_outcome_failure_exception_from_error(const status_code<DomainType> &sc)
{
(void) sc;
#ifdef __cpp_exceptions
try
{
sc.throw_exception();
}
catch(...)
{
return std::current_exception();
}
#endif
return {};
}
SYSTEM_ERROR2_NAMESPACE_END
OUTCOME_V2_NAMESPACE_EXPORT_BEGIN
//! Namespace for traits
namespace trait
{
namespace detail
{
// Shortcut this for lower build impact
template <class DomainType> struct _is_error_code_available<SYSTEM_ERROR2_NAMESPACE::status_code<DomainType>>
{
static constexpr bool value = true;
};
template <class DomainType> struct _is_error_code_available<SYSTEM_ERROR2_NAMESPACE::errored_status_code<DomainType>>
{
static constexpr bool value = true;
};
} // namespace detail
#if 0
template <class DomainType> struct is_error_type<SYSTEM_ERROR2_NAMESPACE::status_code<DomainType>>
{
static constexpr bool value = true;
};
template <> struct is_error_type<SYSTEM_ERROR2_NAMESPACE::errc>
{
static constexpr bool value = true;
};
template <class DomainType, class Enum> struct is_error_type_enum<SYSTEM_ERROR2_NAMESPACE::status_code<DomainType>, Enum>
{
static constexpr bool value = boost::system::is_error_condition_enum<Enum>::value;
};
#endif
} // namespace trait
//! Namespace for experimental features
namespace experimental
{
//! Namespace for policies
namespace policy
{
/*! Default policy selector.
*/
template <class T, class EC, class E>
using default_status_outcome_policy = std::conditional_t< //
std::is_void<EC>::value && std::is_void<E>::value, //
OUTCOME_V2_NAMESPACE::policy::terminate, //
std::conditional_t<(is_status_code<EC>::value || is_errored_status_code<EC>::value) && (std::is_void<E>::value || OUTCOME_V2_NAMESPACE::trait::is_exception_ptr_available<E>::value), //
status_code_throw<T, EC, E>, //
OUTCOME_V2_NAMESPACE::policy::fail_to_compile_observers //
>>;
} // namespace policy
/*! TODO
*/
template <class R, class S = system_code, class P = std::exception_ptr, class NoValuePolicy = policy::default_status_outcome_policy<R, S, P>> //
using status_outcome = basic_outcome<R, S, P, NoValuePolicy>;
//! Namespace for policies
namespace policy
{
/*!
*/
template <class T, class DomainType, class E> struct status_code_throw<T, status_code<DomainType>, E> : base
{
using _base = base;
/*! Performs a wide check of state, used in the value() functions.
\effects See description of class for effects.
*/
template <class Impl> static constexpr void wide_value_check(Impl &&self)
{
if(!base::_has_value(static_cast<Impl &&>(self)))
{
if(base::_has_exception(static_cast<Impl &&>(self)))
{
OUTCOME_V2_NAMESPACE::policy::detail::_rethrow_exception<trait::is_exception_ptr_available<E>::value>(base::_exception<T, status_code<DomainType>, E, status_code_throw>(static_cast<Impl &&>(self))); // NOLINT
}
if(base::_has_error(static_cast<Impl &&>(self)))
{
#ifdef __cpp_exceptions
base::_error(static_cast<Impl &&>(self)).throw_exception();
#else
OUTCOME_THROW_EXCEPTION("wide value check failed");
#endif
}
}
}
/*! Performs a wide check of state, used in the error() functions
\effects TODO
*/
template <class Impl> static constexpr void wide_error_check(Impl &&self) { _base::narrow_error_check(static_cast<Impl &&>(self)); }
/*! Performs a wide check of state, used in the exception() functions
\effects TODO
*/
template <class Impl> static constexpr void wide_exception_check(Impl &&self) { _base::narrow_exception_check(static_cast<Impl &&>(self)); }
};
template <class T, class DomainType, class E> struct status_code_throw<T, errored_status_code<DomainType>, E> : status_code_throw<T, status_code<DomainType>, E>
{
status_code_throw() = default;
using status_code_throw<T, status_code<DomainType>, E>::status_code_throw;
};
} // namespace policy
} // namespace experimental
OUTCOME_V2_NAMESPACE_END
#endif
| 37.93125
| 221
| 0.629923
|
libbboze
|
6d8c330307a161f0bec923bab70a54287abed99a
| 4,545
|
cpp
|
C++
|
src/cargame/TranslationManager.cpp
|
sppmacd/CarGame
|
c6b7351daa94b692ab209a5035c85084eafb8a67
|
[
"MIT"
] | 1
|
2020-05-13T18:19:17.000Z
|
2020-05-13T18:19:17.000Z
|
src/cargame/TranslationManager.cpp
|
sppmacd/CarGame
|
c6b7351daa94b692ab209a5035c85084eafb8a67
|
[
"MIT"
] | 5
|
2019-07-15T15:43:38.000Z
|
2020-04-18T17:46:24.000Z
|
src/cargame/TranslationManager.cpp
|
sppmacd/CarGame
|
c6b7351daa94b692ab209a5035c85084eafb8a67
|
[
"MIT"
] | null | null | null |
#include "TranslationManager.hpp"
#include "DebugLogger.hpp"
#include "ModuleManager.hpp"
#include <codecvt>
#include <cstring>
#include <fstream>
#include <iostream>
#include <locale>
#include <sstream>
// error codes
// 01 - not enough values given (too many variables in translation string)
// 02 - language file invalid (empty)
// 03 - cannot found translation
// 04 - language file not exist
TranslationEntry::TranslationEntry(String in)
{
size_t lastp = 0;
for(size_t i = 0; i < in.getSize(); i++)
{
if(in[i] == '%' && i != in.getSize() - 1 && isdigit(in[i+1]))
{
translation.push_back(in.substring(lastp, i - lastp));
translation.back().replace("%%", "%");
lastp = i + 2;
translation.push_back(String("%") + in[i+1]);
}
else if(i == in.getSize() - 1)
{
translation.push_back(in.substring(lastp, i - lastp + 1));
translation.back().replace("%%", "%");
}
else if(in[i] == '\\' && i != in.getSize() - 1)
{
in.erase(i);
switch(in[i])
{
case '\\': in[i] = '\\'; break;
case 'n': in[i] = '\n'; break;
case 't': in[i] = '\t'; break;
default: break;
}
}
}
}
String TranslationEntry::getValue(initializer_list<String> values)
{
basic_ostringstream<Uint32> stream;
vector<String> strings;
strings.insert(strings.begin(), values.begin(), values.end());
if(translation.empty())
return "";
for(String& str: translation)
{
if(str[0] == '%' && str.getSize() > 1)
{
size_t val = str[1] - '0';
if(val < strings.size())
stream << strings[val].toUtf32();
else
{
return "(translation err 01)";
}
}
else
{
stream << str.toUtf32();
}
}
return stream.str();
}
///////////////////////////////////////
TranslationManager::TranslationManager(TranslationManager* parent): parentTranslation(parent)
{
}
bool TranslationManager::loadFromFile(String code)
{
// Delete all translations.
for(auto it: translations)
delete it.second;
translations.clear();
languageCode = code;
std::vector<std::string> modules = {"api"};
ModuleManager::instance->getModuleNames(modules);
for(std::string& mod: modules)
{
DebugLogger::log("Loading translation: " + mod + ":" + code.toAnsiString(), "TranslationManager");
wifstream file("res/" + mod + "/lang/" + code + ".lang");
codecvt_utf8_utf16<wchar_t>* c = new codecvt_utf8_utf16<wchar_t>;
file.imbue(locale(file.getloc(), c));
if(!file.good())
{
DebugLogger::log("L04: Couldn't open language file: " + mod + ":" + code);
return false; //err:04
}
// parse
while(!file.eof())
{
wstring str;
getline(file, str);
String sfStr(str);
size_t pos = sfStr.find("=");
if(pos == String::InvalidPos || str[str.find_first_not_of(32)] == '#')
continue;
String code = sfStr.substring(0, pos);
String trs = sfStr.substring(pos + 1);
addTranslation(code, trs);
}
}
return true;
}
void TranslationManager::addTranslation(String unlocalized, String localized)
{
DebugLogger::logDbg("Adding translation: " + unlocalized + " --> " + localized, "TranslationManager");
TranslationEntry* entry = new TranslationEntry(localized);
translations.insert(make_pair(unlocalized, entry));
}
String TranslationManager::get(String unlocalized, initializer_list<String> values)
{
/*if(translations.empty())
return "(translation err 02: " + languageCode + ")";*/
auto it = translations.find(unlocalized);
if(it == translations.end())
{
if(parentTranslation)
return parentTranslation->get(unlocalized, values); // Try to search in parent.
else
return unlocalized; // No parent and no translation - return default string.
}
TranslationEntry* entry = it->second;
return entry->getValue(values);
}
void TranslationManager::setDisplay(String name, String country)
{
displayCountryName = country;
displayLangName = name;
}
void TranslationManager::setParent(TranslationManager* manager)
{
parentTranslation = manager;
}
| 28.40625
| 106
| 0.563256
|
sppmacd
|
6d96c4a7bcdbe8bfdabe459f2b2bb7b17446decf
| 1,526
|
hpp
|
C++
|
src/org/apache/poi/ss/usermodel/CellCopyPolicy_Builder.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/ss/usermodel/CellCopyPolicy_Builder.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/ss/usermodel/CellCopyPolicy_Builder.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /POI/java/org/apache/poi/ss/usermodel/CellCopyPolicy.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/ss/usermodel/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::ss::usermodel::CellCopyPolicy_Builder
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
bool copyCellValue { };
bool copyCellStyle { };
bool copyCellFormula { };
bool copyHyperlink_ { };
bool mergeHyperlink_ { };
bool copyRowHeight { };
bool condenseRows_ { };
bool copyMergedRegions { };
protected:
void ctor();
public:
virtual CellCopyPolicy_Builder* cellValue(bool copyCellValue);
virtual CellCopyPolicy_Builder* cellStyle(bool copyCellStyle);
virtual CellCopyPolicy_Builder* cellFormula(bool copyCellFormula);
virtual CellCopyPolicy_Builder* copyHyperlink(bool copyHyperlink);
virtual CellCopyPolicy_Builder* mergeHyperlink(bool mergeHyperlink);
virtual CellCopyPolicy_Builder* rowHeight(bool copyRowHeight);
virtual CellCopyPolicy_Builder* condenseRows(bool condenseRows);
virtual CellCopyPolicy_Builder* mergedRegions(bool copyMergedRegions);
virtual CellCopyPolicy* build();
// Generated
CellCopyPolicy_Builder();
protected:
CellCopyPolicy_Builder(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
void init();
virtual ::java::lang::Class* getClass0();
friend class CellCopyPolicy;
};
| 27.745455
| 75
| 0.733945
|
pebble2015
|
6d97682e69a124e2de807678fcc585f7364f8b0b
| 32,182
|
cc
|
C++
|
dcmtk-3.6.6/dcmdata/libsrc/dcpath.cc
|
happymanx/Weather_FFI
|
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
|
[
"MIT"
] | null | null | null |
dcmtk-3.6.6/dcmdata/libsrc/dcpath.cc
|
happymanx/Weather_FFI
|
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
|
[
"MIT"
] | null | null | null |
dcmtk-3.6.6/dcmdata/libsrc/dcpath.cc
|
happymanx/Weather_FFI
|
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
|
[
"MIT"
] | null | null | null |
/*
*
* Copyright (C) 2008-2020, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Michael Onken
*
* Purpose: Class definitions for accessing DICOM dataset structures (items,
* sequences and leaf elements via string-based path access.
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dcpath.h"
#include "dcmtk/dcmdata/dcsequen.h"
#define INCLUDE_CINTTYPES
#include "dcmtk/ofstd/ofstdinc.h"
/*******************************************************************/
/* Implementation of class DcmPath */
/*******************************************************************/
// Constructor
DcmPath::DcmPath()
: m_path()
{
}
// Construct from existing path (kind of copy constructor)
DcmPath::DcmPath(const OFList<DcmPathNode*>& currentPath)
: m_path()
{
OFListConstIterator(DcmPathNode*) it = currentPath.begin();
OFListConstIterator(DcmPathNode*) endOfPath = currentPath.end();
while (it != endOfPath)
{
m_path.push_back(new DcmPathNode((*it)->m_obj, (*it)->m_itemNo));
it++;
}
}
// Append a node to the path
void DcmPath::append(DcmPathNode* node)
{
if (node != NULL)
m_path.push_back(node); // do any validity checking?
}
// Deletes last node from the path and frees corresponding memory
void DcmPath::deleteBackNode()
{
DcmPathNode* node = m_path.back();
m_path.pop_back();
if (node)
{
delete node;
node = NULL;
}
}
// Returns iterator to first element of the path
OFListIterator(DcmPathNode*) DcmPath::begin()
{
return m_path.begin();
}
// Returns iterator to last element of the path
DcmPathNode* DcmPath::back()
{
return m_path.back();
}
// Returns iterator to the end of path, i.e. dummy after actual last element
OFListIterator(DcmPathNode*) DcmPath::end()
{
return m_path.end();
}
// Returns number of path nodes in the path
Uint32 DcmPath::size() const
{
return OFstatic_cast(Uint32, m_path.size());
}
// Returns true if path is empty, i.e. number of path nodes is zero
OFBool DcmPath::empty() const
{
return (m_path.size() == 0);
}
// Returns string representation of the path
OFString DcmPath::toString() const
{
OFListConstIterator(DcmPathNode*) it = m_path.begin();
OFListConstIterator(DcmPathNode*) endOfList = m_path.end();
OFString pathStr;
DcmEVR vr;
DcmObject* obj;
char buf[500];
while (it != endOfList)
{
if (((*it) == NULL) || ((*it)->m_obj == NULL))
return "Invalid search result";
obj = (*it)->m_obj;
vr = obj->ident();
if ((vr == EVR_SQ) || (obj->isLeaf()))
{
pathStr.append(OFconst_cast(DcmTag*, &obj->getTag())->getTagName());
it++;
}
else if ((vr == EVR_item) || (vr == EVR_dataset))
{
#ifdef PRIu32
sprintf(buf, "[%" PRIu32 "]", (*it)->m_itemNo);
#elif SIZEOF_LONG == 8
sprintf(buf, "[%u]", (*it)->m_itemNo);
#else
sprintf(buf, "[%lu]", (*it)->m_itemNo);
#endif
pathStr.append(buf);
it++;
if (it != endOfList)
pathStr.append(".");
}
else
{
pathStr.append("<UNKNOWN>");
it++;
}
}
return pathStr;
}
// Checks whether a specific group number is used in the path's path nodes
OFBool DcmPath::containsGroup(const Uint16 groupNo) const
{
OFListConstIterator(DcmPathNode*) it = m_path.begin();
OFListConstIterator(DcmPathNode*) endOfList = m_path.end();
while (it != endOfList)
{
DcmPathNode* node = *it;
if ((node == NULL) || (node->m_obj == NULL))
return OFFalse;
if (node->m_obj->getGTag() == groupNo)
return OFTrue;
it++;
}
return OFFalse;
}
// Helper function for findOrCreatePath(). Parses item no from start of string
OFCondition DcmPath::parseItemNoFromPath(OFString& path, // inout
Uint32& itemNo, // out
OFBool& wasWildcard) // out
{
wasWildcard = OFFalse;
itemNo = 0;
// check whether there is an item to parse
size_t closePos = path.find_first_of(']', 0);
if ((closePos != OFString_npos) && (path[0] == '['))
{
long int parsedNo;
// try parsing item number; parsing for %lu would cause overflows in case of negative numbers
int parsed = sscanf(path.c_str(), "[%ld]", &parsedNo);
if (parsed == 1)
{
if (parsedNo < 0)
{
OFString errMsg = "Negative item number (not permitted) at beginning of path: ";
errMsg += path;
return makeOFCondition(OFM_dcmdata, 25, OF_error, errMsg.c_str());
}
itemNo = OFstatic_cast(Uint32, parsedNo);
if (closePos + 1 < path.length()) // if end of path not reached, cut off "."
closePos++;
path.erase(0, closePos + 1); // remove item from path
return EC_Normal;
}
char aChar;
parsed = sscanf(path.c_str(), "[%c]", &aChar);
if ((parsed == 1) && (aChar == '*'))
{
wasWildcard = OFTrue;
if (closePos + 1 < path.length()) // if end of path not reached, cut off "."
closePos++;
path.erase(0, closePos + 1); // remove item from path
return EC_Normal;
}
}
OFString errMsg = "Unable to parse item number at beginning of path: ";
errMsg += path;
return makeOFCondition(OFM_dcmdata, 25, OF_error, errMsg.c_str());
}
// Function that parses a tag from the beginning of a path string.
OFCondition DcmPath::parseTagFromPath(OFString& path, // inout
DcmTag& tag) // out
{
OFCondition result;
size_t pos = OFString_npos;
// In case we have a tag "(gggg,xxxx)"
if (path[0] == '(')
{
pos = path.find_first_of(')', 0);
if (pos != OFString_npos)
result = DcmTag::findTagFromName(path.substr(1, pos - 1).c_str() /* "gggg,eeee" */, tag);
else
{
OFString errMsg("Unable to parse tag at beginning of path: ");
errMsg += path;
return makeOFCondition(OFM_dcmdata, 25, OF_error, errMsg.c_str());
}
pos++; // also cut off closing bracket
}
// otherwise we could have a dictionary name
else
{
// maybe an item follows
pos = path.find_first_of('[', 0);
if (pos == OFString_npos)
result = DcmTag::findTagFromName(path.c_str(), tag); // check full path
else
result = DcmTag::findTagFromName(path.substr(0, pos).c_str(), tag); // parse path up to "[" char
}
// construct error message if necessary and return
if (result.bad())
{
OFString errMsg("Unable to parse tag/dictionary name at beginning of path: ");
errMsg += path;
return makeOFCondition(OFM_dcmdata, 25, OF_error, errMsg.c_str());
}
// else remove parsed tag from path and return success
else
{
path.erase(0, pos);
}
return EC_Normal;
}
// Destructor, frees memory of path nodes (but not of underlying DICOM objects)
DcmPath::~DcmPath()
{
// free dynamically allocated memory
while (m_path.size() != 0)
{
DcmPathNode* node = m_path.front();
delete node;
node = NULL;
m_path.pop_front();
}
}
// Separate a string path into the different nodes
OFCondition DcmPath::separatePathNodes(const OFString& path, OFList<OFString>& result)
{
OFString pathStr(path);
OFCondition status = EC_Normal;
OFBool nextIsItem = OFTrue;
Uint32 itemNo = 0;
OFBool isWildcard = OFFalse;
// initialize parsing loop
if (!pathStr.empty())
{
if (pathStr[0] != '[')
nextIsItem = OFFalse;
}
char buf[100];
// parse node for node and only stop if error occurs or parsing completes
while (!pathStr.empty())
{
if (nextIsItem)
{
status = parseItemNoFromPath(pathStr, itemNo, isWildcard);
if (status.bad())
return status;
if (isWildcard)
result.push_back("[*]");
else
{
#ifdef PRIu32
if (sprintf(buf, "[%" PRIu32 "]", itemNo) < 2)
return EC_IllegalParameter;
#elif SIZEOF_LONG == 8
if (sprintf(buf, "[%u]", itemNo) < 2)
return EC_IllegalParameter;
#else
if (sprintf(buf, "[%lu]", itemNo) < 2)
return EC_IllegalParameter;
#endif
result.push_back(buf);
}
nextIsItem = OFFalse;
}
else
{
DcmTag tag;
status = parseTagFromPath(pathStr, tag);
if (status.bad())
return status;
if (sprintf(buf, "(%04X,%04X)", tag.getGroup(), tag.getElement()) != 11)
return EC_IllegalParameter;
result.push_back(buf);
nextIsItem = OFTrue;
}
}
return status;
}
/*******************************************************************/
/* Implementation of class DcmPathProcessor */
/*******************************************************************/
// Constructor, constructs an empty path processor
DcmPathProcessor::DcmPathProcessor()
: m_currentPath()
, m_results()
, m_createIfNecessary(OFFalse)
, m_checkPrivateReservations(OFTrue)
, m_itemWildcardsEnabled(OFTrue)
{
}
// enables (class default:enabled) or disables checking of private reservations
void DcmPathProcessor::checkPrivateReservations(const OFBool doChecking)
{
m_checkPrivateReservations = doChecking;
}
// enables (class default:enabled) or disables support for item wildcards
void DcmPathProcessor::setItemWildcardSupport(const OFBool supported)
{
m_itemWildcardsEnabled = supported;
}
// Permits finding and creating DICOM object hierarchies based on a path string
OFCondition DcmPathProcessor::findOrCreatePath(DcmObject* obj, const OFString& path, OFBool createIfNecessary)
{
// check input parameters
if ((obj == NULL) || path.empty())
return EC_IllegalParameter;
if (!m_itemWildcardsEnabled)
{
if (path.find('*') != OFString_npos)
{
return makeOFCondition(OFM_dcmdata, 25, OF_error, "Item wildcard '*' found in path but wildcards disabled");
}
}
clear();
m_createIfNecessary = createIfNecessary;
// do real work in private member functions
OFString pathCopy = path;
if ((obj->ident() == EVR_item) || (obj->ident() == EVR_dataset))
return findOrCreateItemPath(OFstatic_cast(DcmItem*, obj), pathCopy);
else if (obj->ident() == EVR_SQ)
return findOrCreateSequencePath(OFstatic_cast(DcmSequenceOfItems*, obj), pathCopy);
else
return EC_IllegalParameter;
}
// Permits deleting DICOM object hierarchies based on a path string
OFCondition DcmPathProcessor::findOrDeletePath(DcmObject* obj, const OFString& path, Uint32& numDeleted)
{
// check input parameters
if ((obj == NULL) || path.empty())
return EC_IllegalParameter;
numDeleted = 0;
if (!m_itemWildcardsEnabled)
{
if (path.find('*') != OFString_npos)
{
return makeOFCondition(OFM_dcmdata, 25, OF_error, "Item wildcard '*' found in path but wildcards disabled");
}
}
// search
m_createIfNecessary = OFFalse;
OFString pathCopy = path;
OFCondition result;
clear();
if ((obj->ident() == EVR_item) || (obj->ident() == EVR_dataset))
result = findOrCreateItemPath(OFstatic_cast(DcmItem*, obj), pathCopy);
else if (obj->ident() == EVR_SQ)
result = findOrCreateSequencePath(OFstatic_cast(DcmSequenceOfItems*, obj), pathCopy);
else
return EC_IllegalParameter;
if (result.bad())
return result;
// check results
OFList<DcmPath*> resultPaths;
Uint32 numPaths = getResults(resultPaths);
if (numPaths == 0)
return EC_IllegalCall; // should never happen at this point
OFListIterator(DcmPath*) pathIt = resultPaths.begin();
OFListIterator(DcmPath*) endIt = resultPaths.end();
while (pathIt != endIt)
{
// get last item/element from path which should be deleted
DcmPathNode* nodeToDelete = (*pathIt)->back();
if ((nodeToDelete == NULL) || (nodeToDelete->m_obj == NULL))
return EC_IllegalCall;
// if it's not an item, delete element from item.
// deletes DICOM content of node but not node itself (done later)
if (nodeToDelete->m_obj->ident() != EVR_item)
{
result = deleteLastElemFromPath(obj, *pathIt, nodeToDelete);
}
// otherwise we need to delete an item from a sequence
else
{
result = deleteLastItemFromPath(obj, *pathIt, nodeToDelete);
}
if (result.bad())
return result;
// if success, remove node from path and clear node memory
(*pathIt)->deleteBackNode();
numDeleted++;
pathIt++;
}
return result;
}
// Get results of a an operation started before (e.g. findOrCreatePath())
Uint32 DcmPathProcessor::getResults(OFList<DcmPath*>& searchResults)
{
if (m_results.size() > 0)
{
// explicitly copy (shallow)
OFListIterator(DcmPath*) it = m_results.begin();
while (it != m_results.end())
{
searchResults.push_back(*it);
it++;
}
}
return OFstatic_cast(Uint32, m_results.size());
}
// applies a string path (optionally with value) to a dataset
OFCondition DcmPathProcessor::applyPathWithValue(DcmDataset* dataset, const OFString& overrideKey)
{
if (dataset == NULL)
return EC_IllegalCall;
if (overrideKey.empty())
return EC_Normal;
OFString path = overrideKey;
OFString value;
size_t pos = path.find('=');
// separate tag from value if there is one
if (pos != OFString_npos)
{
value = path.substr(pos + 1); // value now contains value
path.erase(pos); // pure path without value
}
clear();
// create path
OFCondition result = findOrCreatePath(dataset, path, OFTrue /* create if necessary */);
if (result.bad())
return result;
// prepare for value insertion
OFListConstIterator(DcmPath*) it = m_results.begin();
OFListConstIterator(DcmPath*) endList = m_results.end();
DcmPathNode* last = (*it)->back();
if (last == NULL)
return EC_IllegalCall;
// if value is specified, be sure path does not end with item
if (!last->m_obj->isLeaf())
{
if (value.empty())
return EC_Normal;
else
return makeOFCondition(
OFM_dcmdata, 25, OF_error, "Cannot insert value into path ending with item or sequence");
}
// insert value into each element affected by path
while (it != endList)
{
last = (*it)->back();
if (last == NULL)
return EC_IllegalCall;
DcmElement* elem = OFstatic_cast(DcmElement*, last->m_obj);
if (elem == NULL)
return EC_IllegalCall;
result = elem->putString(value.c_str());
if (result.bad())
break;
it++;
}
return result;
}
// Resets status (including results) of DcmPathProcessor and frees corresponding memory
void DcmPathProcessor::clear()
{
while (m_results.size() != 0)
{
DcmPath* result = m_results.front();
if (result != NULL)
{
delete result;
result = NULL;
}
m_results.pop_front();
}
while (m_currentPath.size() != 0)
{
DcmPathNode* node = m_currentPath.front();
if (node != NULL)
{
delete node;
node = NULL;
}
m_currentPath.pop_front();
}
}
// Destructor, frees memory by calling clear()
DcmPathProcessor::~DcmPathProcessor()
{
clear();
}
/* protected helper functions */
// Helper function that deletes last DICOM element from a path from the DICOM hierarchy
OFCondition DcmPathProcessor::deleteLastElemFromPath(DcmObject* objSearchedIn, DcmPath* path, DcmPathNode* toDelete)
{
// item containing the element to delete
DcmItem* containingItem = NULL;
if (path->size() == 1)
{
// if we have only a single elem in path, given object must be cont. item
if ((objSearchedIn->ident() != EVR_item) && (objSearchedIn->ident() != EVR_dataset))
return makeOFCondition(OFM_dcmdata, 25, OF_error, "Cannot search leaf element in object being not an item");
containingItem = OFstatic_cast(DcmItem*, objSearchedIn);
}
else
{
// get containing item from path which is the penultimate in the path
OFListIterator(DcmPathNode*) temp = path->end();
temp--;
temp--;
if (*temp == NULL)
return EC_IllegalCall; // never happens here...
if ((*temp)->m_obj == NULL)
return EC_IllegalCall;
if ((*temp)->m_obj->ident() != EVR_item) // (no test for dataset needed)
return makeOFCondition(OFM_dcmdata, 25, OF_error, "Cannot search leaf element in object being not an item");
containingItem = OFstatic_cast(DcmItem*, (*temp)->m_obj);
}
if (containingItem == NULL)
return EC_IllegalCall;
OFCondition result = containingItem->findAndDeleteElement(toDelete->m_obj->getTag(), OFFalse, OFFalse);
return result;
}
// Helper function that deletes last DICOM item from a path from the DICOM hierarchy
OFCondition DcmPathProcessor::deleteLastItemFromPath(DcmObject* objSearchedIn, DcmPath* path, DcmPathNode* toDelete)
{
DcmSequenceOfItems* containingSeq = NULL;
if (path->size() == 1)
{
// if we have only a single elem in path, given object must be cont. item
if (objSearchedIn->ident() != EVR_SQ)
return makeOFCondition(OFM_dcmdata, 25, OF_error, "Cannot search item in object being not a sequence");
containingSeq = OFstatic_cast(DcmSequenceOfItems*, objSearchedIn);
}
else
{
// get containing item from path which is the penultimate in the path
OFListIterator(DcmPathNode*) temp = path->end();
temp--;
temp--;
if (*temp == NULL)
return EC_IllegalCall; // never happens here...
if ((*temp)->m_obj == NULL)
return EC_IllegalCall;
if ((*temp)->m_obj->ident() != EVR_SQ)
return makeOFCondition(OFM_dcmdata, 25, OF_error, "Cannot search item in object being not a sequence");
containingSeq = OFstatic_cast(DcmSequenceOfItems*, (*temp)->m_obj);
}
if (containingSeq == NULL)
return EC_IllegalCall;
DcmItem* item2BDeleted = containingSeq->remove(OFstatic_cast(DcmItem*, toDelete->m_obj));
if (item2BDeleted == NULL)
return EC_IllegalCall; // should not happen here...
delete item2BDeleted;
item2BDeleted = NULL;
return EC_Normal;
}
// Helper function that does work for findOrCreatePath()
OFCondition DcmPathProcessor::findOrCreateItemPath(DcmItem* item, OFString& path)
{
if (item == NULL)
return EC_IllegalParameter;
if (path.empty())
return EC_IllegalParameter;
OFString restPath(path);
OFCondition status = EC_Normal;
DcmTag tag;
OFString privCreator;
OFBool newlyCreated = OFFalse; // denotes whether an element was created
DcmElement* elem = NULL;
DcmPath* currentResult = NULL;
// parse tag
status = DcmPath::parseTagFromPath(restPath, tag);
if (status.bad())
return status;
// insert element or sequence
if (!(item->tagExists(tag))) // do not to overwrite existing tags
{
if (m_createIfNecessary)
{
// private tags needs special handling, e.g. checking reservation
if (tag.isPrivate())
{
if (!tag.isPrivateReservation())
{
// if this is no reservation, find the private creator and update tag
if (getPrivateCreator(item, tag, privCreator).good() && !privCreator.empty())
{
tag.setPrivateCreator(privCreator.c_str());
}
// now that private creator is hopefully set, lookup vr
tag.lookupVRinDictionary();
// check private reservation if desired
if (m_checkPrivateReservations)
{
status = checkPrivateTagReservation(item, tag.getXTag());
if (status.bad())
return status;
}
}
}
// create element for insertion
elem = DcmItem::newDicomElement(tag, privCreator.empty() ? NULL : privCreator.c_str());
if (elem == NULL)
return EC_IllegalCall;
status = item->insert(elem, OFTrue);
if (status.bad())
{
delete elem;
elem = NULL;
return status;
}
newlyCreated = OFTrue;
}
else
return EC_TagNotFound;
}
// get element
status = item->findAndGetElement(tag, elem);
if (status.bad())
return EC_CorruptedData; // should not happen
// start recursion if element was a sequence
if (tag.getEVR() == EVR_SQ)
{
DcmSequenceOfItems* seq = NULL;
seq = OFstatic_cast(DcmSequenceOfItems*, elem);
if (!seq)
status = EC_IllegalCall; // should not happen
else
{
// if sequence could be inserted and there is nothing more to do: add current path to results and return
// success
if (restPath.empty())
{
currentResult = new DcmPath(m_currentPath);
currentResult->append(new DcmPathNode(elem, 0));
m_results.push_back(currentResult);
return EC_Normal;
}
// start recursion if there is path left
DcmPathNode* node = new DcmPathNode(seq, 0);
m_currentPath.push_back(node);
status = findOrCreateSequencePath(seq, restPath);
m_currentPath.pop_back(); // avoid side effects
delete node;
}
}
else if (restPath.empty()) // we inserted a leaf element: path must be completed
{
// add element and add current path to overall results; then return success
currentResult = new DcmPath(m_currentPath);
currentResult->append(new DcmPathNode(elem, 0));
m_results.push_back(currentResult);
return EC_Normal;
}
else // we inserted a leaf element but there is path left -> error
status = makeOFCondition(
OFM_dcmdata, 25, OF_error, "Invalid Path: Non-sequence tag found with rest path following");
// in case of errors: delete result path copy and delete DICOM element if it was newly created
if (status.bad() && (elem != NULL))
{
m_results.remove(currentResult); // remove from search result
if (currentResult)
{
delete currentResult;
currentResult = NULL;
}
if (newlyCreated) // only delete from this dataset and memory if newly created ("undo")
{
if (item->findAndDeleteElement(tag).bad())
delete elem; // delete manually if not found in dataset
}
elem = NULL;
}
return status;
}
// Helper function that does work for findOrCreatePath()
OFCondition DcmPathProcessor::findOrCreateSequencePath(DcmSequenceOfItems* seq, OFString& path)
{
if (seq == NULL)
return EC_IllegalParameter;
// prepare variables
OFString restPath(path);
OFCondition status = EC_Normal;
DcmItem* resultItem = NULL;
Uint32 itemNo = 0;
Uint32 newlyCreated = 0; // number of items created (appended) (only non-wildcard mode)
Uint32 newPathsCreated = 0; // wildcard mode: number of paths found
// parse item number
OFBool isWildcard = OFFalse;
status = DcmPath::parseItemNoFromPath(restPath, itemNo, isWildcard);
if (status.bad())
return status;
// wildcard code: add result path for every matching item
if (isWildcard)
{
// if there are no items -> no results are found
Uint32 numItems = OFstatic_cast(Uint32, seq->card());
if (numItems == 0)
{
if (!m_createIfNecessary)
return EC_TagNotFound;
else
return makeOFCondition(
OFM_dcmdata, 25, OF_error, "Cannot insert unspecified number (wildcard) of items into sequence");
}
// copy every item to result
for (itemNo = 0; itemNo < numItems; itemNo++)
{
DcmItem* oneItem = seq->getItem(itemNo);
/* if we found an item that matches, copy current result path, then
add the item found and finally start recursive search for
that item.
*/
if (oneItem != NULL)
{
// if the item was the last thing to parse, add list to results and return
if (restPath.empty())
{
DcmPathNode* itemNode = new DcmPathNode(oneItem, itemNo);
DcmPath* currentResult = new DcmPath(m_currentPath);
currentResult->append(itemNode);
m_results.push_back(currentResult);
newPathsCreated++;
}
// else there is path left: continue searching in the new item
else
{
DcmPathNode* itemNode = new DcmPathNode(oneItem, itemNo);
m_currentPath.push_back(itemNode);
status = findOrCreateItemPath(oneItem, restPath);
m_currentPath.pop_back(); // avoid side effects
delete itemNode;
itemNode = NULL;
if (status.bad()) // we did not find the path in that item
{
if (status != EC_TagNotFound)
return status;
}
else
{
newPathsCreated++;
}
}
}
else // should be possible to get every item, however...
return EC_IllegalCall;
}
// if there was at least one result, success can be returned
if (newPathsCreated != 0)
{
return EC_Normal;
}
else
return EC_TagNotFound;
}
/* no wildcard, just select single item or create it if necessary */
// if item already exists, just grab a reference
if (itemNo < seq->card())
resultItem = seq->getItem(itemNo);
// if item does not exist, create new if desired
else if (m_createIfNecessary)
{
// create and insert items until desired item count is reached
while ((seq->card() <= itemNo) || (status.bad()))
{
resultItem = new DcmItem();
if (!resultItem)
return EC_MemoryExhausted;
status = seq->insert(resultItem);
if (status.bad())
delete resultItem;
else
newlyCreated++;
}
}
// item does not exist and should not be created newly, return "path not found"
else
return EC_TagNotFound;
// at this point, the item has been obtained and everything is fine so far
// finding/creating the path was successful. now check whether there is more to do
if (!restPath.empty())
{
// push new item to result path and continue
DcmPathNode* itemNode = new DcmPathNode(resultItem, itemNo);
m_currentPath.push_back(itemNode);
status = findOrCreateItemPath(resultItem, restPath);
m_currentPath.pop_back(); // avoid side effects to input parameter
delete itemNode;
itemNode = NULL;
// in case of no success, delete any items that were newly created and return error
if (status.bad())
{
for (Uint32 i = newlyCreated; i > 0; i--)
{
DcmItem* todelete = seq->remove(i - 1);
if (todelete != NULL)
{
delete todelete;
todelete = NULL;
}
}
return status;
}
}
else // finally everything was successful
{
DcmPathNode* itemNode = new DcmPathNode(resultItem, itemNo);
m_currentPath.push_back(itemNode);
m_results.push_back(new DcmPath(m_currentPath));
m_currentPath.pop_back(); // avoid side effects
delete itemNode;
itemNode = NULL;
status = EC_Normal;
}
return status;
}
DcmTagKey DcmPathProcessor::calcPrivateReservationTag(const DcmTagKey& privateKey)
{
DcmTagKey reservationTag(0xFFFF, 0xFFFF);
// if not a private key is given return "error"
if (!privateKey.isPrivate())
return reservationTag;
// if the private key given is already a reservation key, return it
if (privateKey.isPrivateReservation())
return privateKey;
// Calculate corresponding private creator element
Uint16 elemNo = privateKey.getElement();
// Get yz from given element number wxyz, groups stays the same
elemNo = OFstatic_cast(Uint16, elemNo >> 8);
reservationTag.setGroup(privateKey.getGroup());
reservationTag.setElement(elemNo);
return reservationTag;
}
OFCondition DcmPathProcessor::getPrivateCreator(DcmItem* item, const DcmTagKey& tagKey, OFString& privateCreator)
{
DcmTagKey reservationKey;
if (!tagKey.isPrivateReservation())
{
reservationKey = calcPrivateReservationTag(tagKey);
if (reservationKey == DCM_UndefinedTagKey)
{
OFString msg("Unable to compute private reservation for tag: ");
msg += tagKey.toString();
return makeOFCondition(OFM_dcmdata, 25, OF_error, msg.c_str());
}
if (!item->tagExists(reservationKey))
{
return EC_TagNotFound;
}
return item->findAndGetOFString(reservationKey, privateCreator);
}
else
return EC_IllegalCall;
}
OFCondition
DcmPathProcessor::checkPrivateTagReservation(DcmItem* item, const DcmTagKey& tagKey, const OFString& privateCreator)
{
OFString actualPrivateCreator;
OFCondition result = getPrivateCreator(item, tagKey, actualPrivateCreator);
if (result.bad() || actualPrivateCreator.empty())
{
OFString msg = "Invalid or empty private creator tag: ";
msg += calcPrivateReservationTag(tagKey).toString();
return makeOFCondition(OFM_dcmdata, 25, OF_error, msg.c_str());
}
else if (!privateCreator.empty())
{
// check whether private creator is correct
if (actualPrivateCreator != privateCreator)
{
OFString msg = "Private creator string (";
msg += actualPrivateCreator;
msg += ") other than expected ( ";
msg += privateCreator;
msg += privateCreator;
return makeOFCondition(OFM_dcmdata, 25, OF_error, msg.c_str());
}
}
return EC_Normal;
}
| 33.592902
| 120
| 0.584488
|
happymanx
|
6d9d5bb9c7b3915108d4dba53bd6054679b87b5b
| 2,524
|
cpp
|
C++
|
src/modules/osgVolume/generated_code/_osgVolume.main.cpp
|
cmbruns/osgpyplusplus
|
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
|
[
"BSD-3-Clause"
] | 3
|
2017-04-20T09:11:47.000Z
|
2021-04-29T19:24:03.000Z
|
src/modules/osgVolume/generated_code/_osgVolume.main.cpp
|
cmbruns/osgpyplusplus
|
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
|
[
"BSD-3-Clause"
] | null | null | null |
src/modules/osgVolume/generated_code/_osgVolume.main.cpp
|
cmbruns/osgpyplusplus
|
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
|
[
"BSD-3-Clause"
] | null | null | null |
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "__call_policies.pypp.hpp"
#include "__convenience.pypp.hpp"
#include "indexing_suite/container_suite.hpp"
#include "indexing_suite/vector.hpp"
#include "wrap_osgVolume.h"
#include "AlphaFuncProperty.pypp.hpp"
#include "CollectPropertiesVisitor.pypp.hpp"
#include "CompositeLayer.pypp.hpp"
#include "CompositeProperty.pypp.hpp"
#include "FixedFunctionTechnique.pypp.hpp"
#include "ImageDetails.pypp.hpp"
#include "ImageLayer.pypp.hpp"
#include "IsoSurfaceProperty.pypp.hpp"
#include "Layer.pypp.hpp"
#include "LightingProperty.pypp.hpp"
#include "Locator.pypp.hpp"
#include "LocatorCallbacks.pypp.hpp"
#include "MaximumIntensityProjectionProperty.pypp.hpp"
#include "Property.pypp.hpp"
#include "PropertyAdjustmentCallback.pypp.hpp"
#include "PropertyVisitor.pypp.hpp"
#include "RayTracedTechnique.pypp.hpp"
#include "SampleDensityProperty.pypp.hpp"
#include "SampleDensityWhenMovingProperty.pypp.hpp"
#include "ScalarProperty.pypp.hpp"
#include "SwitchProperty.pypp.hpp"
#include "TileID.pypp.hpp"
#include "TransferFunctionProperty.pypp.hpp"
#include "TransparencyProperty.pypp.hpp"
#include "Volume.pypp.hpp"
#include "VolumeTechnique.pypp.hpp"
#include "VolumeTile.pypp.hpp"
#include "_osgVolume_free_functions.pypp.hpp"
namespace bp = boost::python;
BOOST_PYTHON_MODULE(_osgVolume){
register_LocatorCallbacks_class();
register_Property_class();
register_ScalarProperty_class();
register_AlphaFuncProperty_class();
register_PropertyVisitor_class();
register_CollectPropertiesVisitor_class();
register_Layer_class();
register_CompositeLayer_class();
register_CompositeProperty_class();
register_VolumeTechnique_class();
register_FixedFunctionTechnique_class();
register_ImageDetails_class();
register_ImageLayer_class();
register_IsoSurfaceProperty_class();
register_LightingProperty_class();
register_Locator_class();
register_MaximumIntensityProjectionProperty_class();
register_PropertyAdjustmentCallback_class();
register_RayTracedTechnique_class();
register_SampleDensityProperty_class();
register_SampleDensityWhenMovingProperty_class();
register_SwitchProperty_class();
register_TileID_class();
register_TransferFunctionProperty_class();
register_TransparencyProperty_class();
register_Volume_class();
register_VolumeTile_class();
register_free_functions();
}
| 19.267176
| 56
| 0.7813
|
cmbruns
|
6da1b18743490e9d050c0442dc051c4ffc38b284
| 5,509
|
cpp
|
C++
|
DFS. Tarjan SCC/Source(9).cpp
|
AlexandraDediu/Fundamental-Algorithms
|
92cfc8f135fbe9681427d362634de3b9f049bfbd
|
[
"Apache-2.0"
] | null | null | null |
DFS. Tarjan SCC/Source(9).cpp
|
AlexandraDediu/Fundamental-Algorithms
|
92cfc8f135fbe9681427d362634de3b9f049bfbd
|
[
"Apache-2.0"
] | null | null | null |
DFS. Tarjan SCC/Source(9).cpp
|
AlexandraDediu/Fundamental-Algorithms
|
92cfc8f135fbe9681427d362634de3b9f049bfbd
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include "Profiler.h"
#define white 1
#define grey 2
#define black 3
#define tree 4
#define back 5
#define forward 6
#define cross 7
using namespace std;
Profiler profiler("BFS");
int op = 0;
bool topo = true;
int V = 100, component;
int sol[500], contor;
int e = 1000;
int myTime;
typedef struct
{
int vec[500];
int topOfStack = 0;
}Stack;
Stack s;
int pop(Stack &s)
{
return s.vec[--s.topOfStack];
}
void push(int val, Stack &s)
{
s.vec[s.topOfStack++] = val;
}
typedef struct AdjListNode {
int destination;
int edgeType;
struct AdjListNode*next;
}AdjListNode;
typedef struct AdjList {
int value;
int discoveryTime;
int finishTime;
int parent;
int color;
int comp;
int index;
struct AdjListNode *head; // pointer to head node of list
}AdjList;
typedef struct Graph {
int V; // number of vertices
struct AdjList *arrayOfAdjacencyLists;
}Graph;
struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->destination = dest;
newNode->next = NULL;
return newNode;
}
void addEdge(struct Graph* graph, int src, int dest)
{
// A new node is added to the adjacency list of src. The node is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->arrayOfAdjacencyLists[src].head;
graph->arrayOfAdjacencyLists[src].head = newNode;
}
Graph* createGraph(int V, int E) {
Graph *graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
// each vertex of the graph will have an adjacencylist
graph->arrayOfAdjacencyLists = (AdjList*)malloc((V + 1) * sizeof(AdjList));
for (int i = 1; i <= V; i++)
{
graph->arrayOfAdjacencyLists[i].value = i;
graph->arrayOfAdjacencyLists[i].head = NULL; // Initialize each adjacency list as empty by making head as NULL
}
bool matrix[100][100];
memset(matrix, 0, sizeof(matrix));
for (int i = 0; i < E; i++)
{
int dest, src;
do
{
dest = rand() % V + 1;
src = rand() % V + 1;
} while (dest == src || matrix[src][dest]==1);
addEdge(graph, src, dest);
matrix[src][dest] = 1;
}
return graph;
}
void dfs_visit(Graph *g ,int indice)
{
//cout << g->arrayOfAdjacencyLists[indice].value << " " ; //afisez valoarea nodului in care sunt cu dfs
AdjList *nod = &(g->arrayOfAdjacencyLists[indice]);
op += 2;
nod->color = grey;
nod->discoveryTime = myTime++;
//component++;
//nod->comp = component;
//nod->index = component;
AdjListNode *current = nod->head;
//push(nod->value, s);
while (current != NULL)
{
AdjList *myNext = &(g->arrayOfAdjacencyLists[current->destination]);//in nodurile din lista unui nod am un int destinatie. mie imi trebe nodul ca sa-i pun culoare si parinte. asa ca fac graph->adjList[destinatie]
op++;
if (myNext->color == white)
{
op++;
myNext->parent = nod->value;
dfs_visit(g, myNext->value);
//if (myNext.comp < nod->comp) nod->comp = myNext.comp;
}
else if (myNext->color == grey)
{
topo = false;
//if (myNext.index < nod->comp) nod->comp = myNext.index;
}
op++;
current = current->next;
}
op += 2;
nod->color = black;
nod->finishTime = myTime++;
sol[++contor] = nod->value;
/*if (nod->index == nod->comp)
{
int thisIndex;
do {
thisIndex = pop(s);
cout << thisIndex << " ";
} while (thisIndex != indice);
cout << "\n";
}*/
}
void dfs(Graph *g)
{
for (int i = 1; i <= g->V; i++)
{
op += 3;
g->arrayOfAdjacencyLists[i].color = white;
g->arrayOfAdjacencyLists[i].parent = NULL;
g->arrayOfAdjacencyLists[i].comp = 100000;
}
myTime = 0;
//component = 0;
topo = true;
contor = 0;
for (int i = 1; i <= g->V; i++)
{
if (g->arrayOfAdjacencyLists[i].color == white)
dfs_visit(g, i);
//dfs_visit(g, i);
}
}
void printGraph(Graph *G )
{
for (int i = 1; i <= G->V; i++)
{
cout << i << "->";
AdjListNode *current = G->arrayOfAdjacencyLists[i].head;
while (current != NULL)
{
cout << current->destination << " ";
current = current->next;
}
cout << "\n";
}
}
void prettyPrint(int indice, Graph *G, int space)
{
for (int i = 1; i <= space; i++) cout << " ";
cout << indice << "\n";
for (int i = 1; i <= G->V; i++)
{
if (G->arrayOfAdjacencyLists[i].parent == indice)
prettyPrint(i, G, space + 2);
}
}
void demoTopo()
{
int V = 6;
int E = 10;
Graph *G;
do {
G = createGraph(V, E);
dfs(G);
} while (topo == false);
printGraph(G);
for (int i = contor; i >0; i--)
{
cout << sol[i] << " ";
}
}
void demoTarjan()
{
int V = 6;
int E = 10;
Graph *G = createGraph(V, E);
printGraph(G);
dfs(G);
}
void demoDFS()
{
int V = 6;
int E = 10;
Graph *G = createGraph(V, E);
printGraph(G);
dfs(G);
for (int i = 1; i <= V; i++)
{
if (G->arrayOfAdjacencyLists[i].parent == NULL)
prettyPrint(i, G, 0);
}
}
void averageE()
{
int e = 9000;
Graph *g;
profiler.createGroup("Efix", "serie1");
for (int n = 100; n <= 200; n+=10)
{
op = 0;
g = createGraph(n, e);
dfs(g);
profiler.countOperation("serie1", n, op);
}
//profiler.showReport();
}
void averageV()
{
int n = 100;
Graph *g;
profiler.createGroup("Vfix", "serie2");
for (int e = 1000; e <= 5000; e+=100)
{
op = 0;
g = createGraph(n, e);
dfs(g);
profiler.countOperation("serie2", e, op);
}
//profiler.showReport();
}
int main()
{
srand(time(NULL));
//demoTopo();
//cout << '\n' << '\n';
//demoTarjan();
demoDFS();
//averageE();
//averageV();
//profiler.showReport();
getchar();
return 0;
}
| 18.181518
| 214
| 0.614994
|
AlexandraDediu
|
6da2f881175bcf938f2cfea7b373a00ba216e819
| 3,095
|
cpp
|
C++
|
OP2-Landlord/TileGroups.cpp
|
OutpostUniverse/op2-landlord
|
f4256b8bbe4d7d475a49a18ddf00d880e902c14e
|
[
"Unlicense"
] | null | null | null |
OP2-Landlord/TileGroups.cpp
|
OutpostUniverse/op2-landlord
|
f4256b8bbe4d7d475a49a18ddf00d880e902c14e
|
[
"Unlicense"
] | 19
|
2019-12-08T11:40:44.000Z
|
2020-02-20T10:32:19.000Z
|
OP2-Landlord/TileGroups.cpp
|
OutpostUniverse/op2-landlord
|
f4256b8bbe4d7d475a49a18ddf00d880e902c14e
|
[
"Unlicense"
] | 1
|
2019-12-19T03:50:20.000Z
|
2019-12-19T03:50:20.000Z
|
#include "TileGroups.h"
#include "Common.h"
using namespace NAS2D;
/**
* C'Tor
*/
TileGroups::TileGroups()
{
_init();
}
/**
* D'Tor
*/
TileGroups::~TileGroups()
{
mSlider.change().disconnect(this, &TileGroups::mSlider_Changed);
Utility<EventHandler>::get().keyDown().disconnect(this, &TileGroups::onKeyDown);
Utility<EventHandler>::get().mouseWheel().disconnect(this, &TileGroups::mouseWheel);
}
void TileGroups::_init()
{
text("Tile Groups");
mSlider.change().connect(this, &TileGroups::mSlider_Changed);
Utility<EventHandler>::get().keyDown().connect(this, &TileGroups::onKeyDown);
Utility<EventHandler>::get().mouseWheel().connect(this, &TileGroups::mouseWheel);
}
void TileGroups::map(MapFile* map)
{
if (!map)
{
throw std::runtime_error("TileGroups::map(): nullptr passed.");
}
Renderer& r = Utility<Renderer>::get();
mMap = map;
size((mMap->tileGroupExtents().x * TILE_SIZE) + 10, (mMap->tileGroupExtents().y * TILE_SIZE) + 10 + TILE_SIZE + 7);
position(r.size().x - width() - 5, r.size().y - height() - 5);
mSlider.font(font());
mSlider.position(positionX() + 5, positionY() + height() - 20);
mSlider.size(width() - 10, 15);
mSlider.length((double)mMap->tileGroupCount() - 1);
mSlider.displayPosition(true);
}
void TileGroups::mSlider_Changed(double pos)
{
mTileGroupIndex = static_cast<int>(pos);
}
/**
* Slider doesn't play nice with UIContainer so we need
* to update its position here or it misbehaves.
*
* \todo Fix slider so that this becomes unnecessary.
*/
void TileGroups::positionChanged(float dX, float dY)
{
mSlider.position(positionX() + 5, positionY() + height() - 20);
}
/**
* Draws the tile palette
*/
void TileGroups::draw()
{
Renderer& r = Utility<Renderer>::get();
mMap->tileGroup(mTileGroupIndex)->draw(rect().x + 5, rect().y + titleBarHeight() + 5);
r.drawText(font(), mMap->tileGroupName(mTileGroupIndex), {positionX() + 10, positionY() + titleBarHeight() + 10});
mSlider.update();
}
void TileGroups::mouseDown(EventHandler::MouseButton button, int x, int y)
{
if (!visible() || (button != EventHandler::MouseButton::Left)) { return; }
if (!(rect().contains(_mouseCoords())))
{
return;
}
mLeftButtonDown = true;
}
void TileGroups::mouseUp(EventHandler::MouseButton button, int x, int y)
{
mLeftButtonDown = false;
if (!visible() || (button != EventHandler::MouseButton::Left)) { return; }
if (!mLeftButtonDown && !dragging()) { return; }
}
void TileGroups::mouseWheel(int x, int y)
{
if (!visible()) { return; }
if (y < 0)
{
mSlider.changeThumbPosition(1.0);
}
else if (y > 0)
{
mSlider.changeThumbPosition(-1.0);
}
}
void TileGroups::onKeyDown(EventHandler::KeyCode key, EventHandler::KeyModifier mod, bool repeat)
{
if (!visible()) { return; }
switch (key)
{
case EventHandler::KeyCode::KEY_LEFT:
mSlider.changeThumbPosition(-1.0);
break;
case EventHandler::KeyCode::KEY_RIGHT:
mSlider.changeThumbPosition(1.0);
break;
default:
break;
}
}
/**
* Determine a pattern using two selected points.
*/
void TileGroups::reset()
{
mTileGroupIndex = 0;
}
| 20.097403
| 116
| 0.677221
|
OutpostUniverse
|
6da6f09af876f2a62a9fe9b006f6debb52f499aa
| 548
|
hpp
|
C++
|
module04/ex03/AMateria.hpp
|
M-Philippe/cpp_piscine
|
9584ebcb030c54ca522dbcf795bdcb13a0325f77
|
[
"MIT"
] | null | null | null |
module04/ex03/AMateria.hpp
|
M-Philippe/cpp_piscine
|
9584ebcb030c54ca522dbcf795bdcb13a0325f77
|
[
"MIT"
] | null | null | null |
module04/ex03/AMateria.hpp
|
M-Philippe/cpp_piscine
|
9584ebcb030c54ca522dbcf795bdcb13a0325f77
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream>
#include "ICharacter.hpp"
class ICharacter;
class AMateria
{
private:
unsigned int _xp;
std::string _type;
public:
AMateria();
AMateria(std::string const& type);
AMateria(const AMateria& org);
AMateria& operator=(const AMateria& org);
virtual ~AMateria();
std::string const& getType() const;
void setType(const std::string& type);
unsigned int getXP() const;
// tmp
void setXP(unsigned int n);
virtual AMateria* clone() const = 0;
virtual void use(ICharacter& target);
};
| 19.571429
| 43
| 0.684307
|
M-Philippe
|
6da6f89044475c2b8ead66ccb45021b977a83385
| 2,636
|
cpp
|
C++
|
Triangles.cpp
|
bjonke/Classes
|
c8b815ce41daa622bff7651d341fdc0322c0aa89
|
[
"MIT"
] | null | null | null |
Triangles.cpp
|
bjonke/Classes
|
c8b815ce41daa622bff7651d341fdc0322c0aa89
|
[
"MIT"
] | null | null | null |
Triangles.cpp
|
bjonke/Classes
|
c8b815ce41daa622bff7651d341fdc0322c0aa89
|
[
"MIT"
] | null | null | null |
#include "Triangles.h"
#include <SDL.h>
#include "game.h"
#include "ControlGfx.h"
// 1. this should go into every .cpp , after all header inclusions
#ifdef _WIN32
#ifdef _DEBUG
#include <crtdbg.h>
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new new( _NORMAL_BLOCK, __FILE__, __LINE__)
#define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif
ControlTriangles TriangleController;
const float CubeSpeed = 0.0001f;
SDL_Rect Triangle::UpdateCollisionBox(SDL_Rect Box)
{
CollisionBox = Box;
return CollisionBox;
}
void Triangle::Update()
{
xPos -= 0.0003f * gamestate.DeltaTime;
Destination.w = Width;
Destination.x = xPos;
Destination.y = yPos+rand()% 12;
PrevFrame = Frame++;
if( Frame >= TRIANGLE_MAX_FRAMES )
{
Frame = 0;
}
UpdateCollisionBox(Destination);
}
void Triangle::Draw()
{
#ifdef _DEBUG
//SDL_FillRect(Gfx.BackBuffer, &CollisionBox,0xffffff );
#endif
SDL_BlitSurface(
Gfx.GetSurface( SurfaceID ),
&Clips[ PrevFrame ],
Gfx.BackBuffer,
&GetDestination()
);
}
SDL_Rect Triangle::GetDestination()
{
return Destination;
}
Triangle::Triangle()
{
PrevFrame = 0;
Frame = 0;
Height = 64;
Width = 64;
for( int i = 0; i < 16; i++ )
{
Clips[ i ].x = i * Width;
Clips[ i ].y = 0;
Clips[ i ].h = Height;
Clips[ i ].w = Width;
}
}
void ControlTriangles::DrawTriangles()
{
if( TriangleArrayRef.size() < 1 )
return;
vector< Triangle >::iterator i;
i = TriangleArrayRef.begin();
while(i != TriangleArrayRef.end() )
{
i->Update();
i->Draw();
if( i->xPos <= 0.0f - SpriteWidth )
{
i = TriangleArrayRef.erase(i);
}
else
{
++i;
}
}
}
void ControlTriangles::CreateTriangles(int iProgress )
{
if( iProgress > TRIANGLE_MIN_PROGRESS && iProgress < TRIANGLE_MAX_PROGRESS )
{
if( TriangleArrayRef.size() < rand() % 5 )
{
TriangleArrayRef.push_back( CreateTriangleByReference( SDL_GetVideoSurface()->w, rand() % Gfx.BackBuffer->h , gamestate.m_srfTriangle ) );
}
}
else
{
cout << "Progress passed the target range... " << endl;
}
}
Triangle ControlTriangles::CreateTriangleByReference( int xPos, int yPos, int surface )
{
static int old_y_pos = 0;
while( yPos > old_y_pos && yPos < old_y_pos + 64 )
{
yPos = rand() % Gfx.BackBuffer->h - 64;
}
if( yPos < 64 )
yPos = 64;
Triangle temp;
temp.SurfaceID = surface;
temp.xPos = xPos;
temp.yPos = yPos;
return temp;
}
ControlTriangles::ControlTriangles()
{
cout << "Creating the Triangle Controller..." << endl;
}
ControlTriangles::~ControlTriangles()
{
cout << "Destroying the Triangle Controller..." << endl;
}
| 18.433566
| 141
| 0.66654
|
bjonke
|
6da853551a901af75ca3d7c68723df5043a676ed
| 979
|
cpp
|
C++
|
examples/edit_profile.cpp
|
Xeth/libbitprofile
|
49cd266ffa680c6eefaae205bc17c971c2d38b65
|
[
"MIT"
] | 1
|
2016-04-17T23:03:39.000Z
|
2016-04-17T23:03:39.000Z
|
examples/edit_profile.cpp
|
BitProfile/libbitprofile
|
49cd266ffa680c6eefaae205bc17c971c2d38b65
|
[
"MIT"
] | null | null | null |
examples/edit_profile.cpp
|
BitProfile/libbitprofile
|
49cd266ffa680c6eefaae205bc17c971c2d38b65
|
[
"MIT"
] | 1
|
2018-08-31T10:56:39.000Z
|
2018-08-31T10:56:39.000Z
|
#include <iostream>
#include "ethrpc/Provider.hpp"
#include "bitprofile/Resolver.hpp"
#include "utils/PromptPassword.hpp"
int main(int argc, char **argv)
{
if(argc<4)
{
std::cout<<"usage : edit_profile [uri] [key] [value]"<<std::endl;
return 1;
}
std::string password = PromptPassword();
Ethereum::Connector::Provider provider;
provider.connect(Ethereum::Connector::Test_Net);
BitProfile::Resolver resolver(provider, BitProfile::Test_Net);
BitProfile::Profile profile = resolver.lookupProfile(argv[1]);
if(profile.isNull())
{
std::cout<<"profile not found"<<std::endl;
}
else
{
std::cout<<"profile found : "<<profile.getAddress()<<std::endl;
std::cout<<"uri : "<<argv[1]<<std::endl;
std::cout<<"edit : "<<profile.set(argv[2], argv[3], "", password)<<std::endl;
std::cout<<"profile data["<<argv[2]<<"]="<<profile.get(argv[2])<<std::endl;
}
return 0;
}
| 23.309524
| 85
| 0.603677
|
Xeth
|
6dae529a2af96a0f12c8d36af2a25240f491d02d
| 671
|
cpp
|
C++
|
src/grammar/selections/selection_single.cpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 34
|
2020-08-14T14:32:51.000Z
|
2022-02-16T23:20:02.000Z
|
src/grammar/selections/selection_single.cpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 19
|
2020-08-20T20:04:39.000Z
|
2022-02-28T14:34:37.000Z
|
src/grammar/selections/selection_single.cpp
|
domoritz/xvega
|
3754dee3e7e38e79282ba267cd86c3885807a4cd
|
[
"BSD-3-Clause"
] | 7
|
2020-08-14T14:18:17.000Z
|
2022-02-01T10:59:24.000Z
|
// Copyright (c) 2020, QuantStack and XVega Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#include "xvega/grammar/selections/selection_single.hpp"
#include "../selections_private.hpp"
namespace xv
{
selection_single::selection_single()
{
name = "selector_single_" + random_string(5);
type = "single";
}
void to_json(nl::json& j, const selection_single& m)
{
private_to_json(m, j);
serialize(j, m.init(), "init");
serialize(j, m.bind(), "bind");
serialize(j, m.nearest(), "nearest");
}
}
| 25.807692
| 75
| 0.643815
|
domoritz
|
6db196ae53f40514ab2f24d72ec64e29a2bb09c6
| 3,445
|
hpp
|
C++
|
src/xpcc/architecture/peripheral/one_wire.hpp
|
walmis/xpcc
|
1d87c4434530c6aeac923f57d379aeaf32e11e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/xpcc/architecture/peripheral/one_wire.hpp
|
walmis/xpcc
|
1d87c4434530c6aeac923f57d379aeaf32e11e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/xpcc/architecture/peripheral/one_wire.hpp
|
walmis/xpcc
|
1d87c4434530c6aeac923f57d379aeaf32e11e1e
|
[
"BSD-3-Clause"
] | null | null | null |
// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2009, Roboterclub Aachen e.V.
* 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 Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*/
// ----------------------------------------------------------------------------
/**
* \ingroup connectivity
* \defgroup 1-wire 1-Wire
*
* 1-Wire is a device communications bus system designed by
* Dallas Semiconductor Corp. that provides low-speed data, signaling and
* power over a single signal.[1] 1-Wire is similar in concept to I²C, but
* with lower data rates and longer range. It is typically used to communicate
* with small inexpensive devices such as digital thermometers and
* weather instruments.
*
* One distinctive feature of the bus is the possibility to use only two
* wires: data and ground. To accomplish this, 1-wire devices include an
* 800 pF capacitor to store charge, and power the device during periods where
* the data line is used for data.
*/
#ifndef XPCC__ONE_WIRE_HPP
#define XPCC__ONE_WIRE_HPP
#include <xpcc/architecture/utils.hpp>
#include <xpcc/architecture/peripheral.hpp>
namespace xpcc
{
/**
* \ingroup 1-wire
*/
namespace one_wire
{
/**
* \brief ROM Commands
*
* After the bus master has detected a presence pulse, it can issue a
* ROM command. These commands operate on the unique 64-bit ROM codes
* of each slave device and allow the master to single out a specific
* device if many are present on the 1-Wire bus.
*
* These commands also allow the master to determine how many and what
* types of devices are present on the bus or if any device has
* experienced an alarm condition.
*
* There are five ROM commands, and each command is 8 bits long.
*
* \ingroup 1-wire
*/
enum RomCommand
{
SEARCH_ROM = 0xf0,
READ_ROM = 0x33,
MATCH_ROM = 0x55,
SKIP_ROM = 0xcc,
ALARM_SEARCH = 0xec
};
}
}
#endif // XPCC__ONE_WIRE_HPP
| 39.147727
| 79
| 0.695791
|
walmis
|
6db69d403803afc4fcbe18d071895da7619091ad
| 7,902
|
cp
|
C++
|
aa/2000's - DICE/-DICE10/Source/JSDom/ds_NotePlayer.cp
|
jht1900/DICE-AGE
|
5ecb810f21b7e1075430f71890fc7bb82ec09caf
|
[
"MIT"
] | null | null | null |
aa/2000's - DICE/-DICE10/Source/JSDom/ds_NotePlayer.cp
|
jht1900/DICE-AGE
|
5ecb810f21b7e1075430f71890fc7bb82ec09caf
|
[
"MIT"
] | null | null | null |
aa/2000's - DICE/-DICE10/Source/JSDom/ds_NotePlayer.cp
|
jht1900/DICE-AGE
|
5ecb810f21b7e1075430f71890fc7bb82ec09caf
|
[
"MIT"
] | null | null | null |
/*
JavaScript wrapper for note player
Copyright (c) 2003 John Henry Thompson. All rights reserved.
History:
2003.03.20 jht Created. Integrating JavaScript.
*/
#include "ds_NotePlayer.h"
#include "CNotePlayer.h"
#include "jscntxt.h"
#include "jslock.h"
#define DS_CLASS_NAME "NotePlayer"
// --------------------------------------------------------------------------------
static JSBool
ds_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
static JSBool
ds_setProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
static void
ds_finalize(JSContext *cx, JSObject *obj);
static JSBool
ds_play(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
static JSBool
ds_Task(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
static JSBool
ds_getController(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
static JSBool
ds_setController(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
// --------------------------------------------------------------------------------
static JSFunctionSpec ds_methods[] = {
{"play", ds_play, 2,0,0},
{"getController", ds_getController, 2,0,0},
{"setController", ds_setController, 2,0,0},
{"Task", ds_Task, 2,0,0},
{0,0,0,0,0}
};
enum ds_tinyid {
DS_PROP_instrument,
DS_PROP_npoly,
DS_XXX_PROP
};
// --------------------------------------------------------------------------------
static JSPropertySpec ds_props[] = {
{"instrument", DS_PROP_instrument, JSPROP_ENUMERATE|JSPROP_PERMANENT,0,0},
{"npoly", DS_PROP_npoly, JSPROP_ENUMERATE|JSPROP_PERMANENT,0,0},
{0,0,0,0,0}
};
static const char ds_NotePlayer_str[] = "NotePlayer";
// --------------------------------------------------------------------------------
static JSClass ds_Class = {
DS_CLASS_NAME,
JSCLASS_HAS_PRIVATE,
JS_PropertyStub, JS_PropertyStub, ds_getProperty, ds_setProperty,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, ds_finalize,
JSCLASS_NO_OPTIONAL_MEMBERS
};
// --------------------------------------------------------------------------------
static CNotePlayer *
ds_CNotePlayer_GetPrivate(JSContext *cx, JSObject *obj, jsval *argv)
{
return (CNotePlayer*) JS_GetInstancePrivate(cx, obj, &ds_Class, argv );
}
// --------------------------------------------------------------------------------
// method o.Task( )
static JSBool
ds_Task(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval * /*rval*/ )
{
CNotePlayer *ucontrol;
ucontrol = ds_CNotePlayer_GetPrivate(cx, obj, argv);
if (! ucontrol)
return JS_FALSE;
ucontrol->Task();
return JS_TRUE;
}
// --------------------------------------------------------------------------------
// method o.setController( controllerNum, value )
//
static JSBool
ds_setController(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval * /*rval*/ )
{
CNotePlayer *ucontrol;
int32 controllerNum = 1, newValue = 0x010;
JSBool ok = JS_FALSE;
ucontrol = ds_CNotePlayer_GetPrivate(cx, obj, argv);
if (! ucontrol)
goto exit;
ok = JS_ConvertArguments(cx, argc, argv, "/ii", &controllerNum, &newValue);
if (! ok)
goto exit;
ucontrol->SetController(controllerNum, newValue);
exit:;
return ok;
}
// --------------------------------------------------------------------------------
// method o.getController( controllerNum )
//
static JSBool
ds_getController(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval * rval)
{
CNotePlayer *ucontrol;
int32 controllerNum = 1, newValue = 0x010;
JSBool ok = JS_FALSE;
ucontrol = ds_CNotePlayer_GetPrivate(cx, obj, argv);
if (! ucontrol)
goto exit;
ok = JS_ConvertArguments(cx, argc, argv, "/i", &controllerNum );
if (! ok)
goto exit;
ucontrol->GetController(controllerNum);
ok = JS_NewNumberValue(cx, ucontrol->GetController(controllerNum), rval);
exit:;
return ok;
}
// --------------------------------------------------------------------------------
// method o.play( pitchNum, velocityNum )
static JSBool
ds_play(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval * /*rval*/ )
{
CNotePlayer *notePlayer;
int32 pitchNum = 70;
int32 velocityNum = 127;
JSBool ok = JS_FALSE;
notePlayer = ds_CNotePlayer_GetPrivate(cx, obj, argv);
if (!notePlayer)
return JS_FALSE;
ok = JS_ConvertArguments(cx, argc, argv, "ii", &pitchNum, &velocityNum);
if (! ok)
goto exit;
notePlayer->Play( pitchNum, velocityNum );
exit:;
return ok;
}
// --------------------------------------------------------------------------------
static JSBool
NotePlayer_constructor(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
CNotePlayer *notePlayer;
JSBool ok = JS_FALSE;
int32 instrumentNum = 1;
int32 polyphonyNum = 3;
/* NotePlayer called as function
If called with new, replace with new NotePlayer object
*/
if (!(cx->fp->flags & JSFRAME_CONSTRUCTING))
{
obj = js_NewObject(cx, &ds_Class, NULL, NULL);
if (!obj)
return JS_FALSE;
*rval = OBJECT_TO_JSVAL(obj);
}
ok = JS_ConvertArguments(cx, argc, argv, "/ii", &instrumentNum, &polyphonyNum);
if (! ok)
goto exit;
notePlayer = new CNotePlayer( instrumentNum, polyphonyNum, (double)polyphonyNum );
if (! notePlayer)
return JS_FALSE;
ok = JS_SetPrivate(cx, obj, notePlayer);
exit:;
return ok;
}
// --------------------------------------------------------------------------------
static void
ds_finalize(JSContext *cx, JSObject *obj)
{
CNotePlayer *notePlayer;
notePlayer = (CNotePlayer *) JS_GetPrivate(cx, obj);
if (!notePlayer)
return;
delete notePlayer;
}
// --------------------------------------------------------------------------------
static JSBool
ds_accessProperty(JSContext *cx, JSBool doSet, JSObject *obj, jsval id, jsval *vp)
{
JSBool ok = JS_FALSE;
jsint slot;
CNotePlayer *notePlayer;
int32 num;
// !!@ why return ok here??
if (!JSVAL_IS_INT(id))
return JS_TRUE;
slot = JSVAL_TO_INT(id);
JS_LOCK_OBJ(cx, obj);
notePlayer = (CNotePlayer*) JS_GetPrivate(cx, obj);
if (! notePlayer)
goto exit;
switch (slot)
{
case DS_PROP_instrument:
if (doSet)
{
if (!JS_ValueToInt32(cx, *vp, &num))
goto exit;
notePlayer->SetInstrument(num);
}
else
{
*vp = INT_TO_JSVAL(notePlayer->GetInstrument());
}
break;
case DS_PROP_npoly:
if (doSet)
{
if (!JS_ValueToInt32(cx, *vp, &num))
goto exit;
notePlayer->SetNPoly(num);
}
else
{
*vp = INT_TO_JSVAL(notePlayer->GetNPoly());
}
break;
}
ok = JS_TRUE;
exit:;
JS_UNLOCK_OBJ(cx, obj);
return ok;
}
// --------------------------------------------------------------------------------
static JSBool
ds_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
return ds_accessProperty( cx, FALSE/*doSet*/, obj, id, vp );
}
// --------------------------------------------------------------------------------
static JSBool
ds_setProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
return ds_accessProperty( cx, TRUE/*doSet*/, obj, id, vp );
}
// --------------------------------------------------------------------------------
JSObject *
ds_NotePlayer_InitClass(JSContext *cx, JSObject *obj)
{
JSObject *proto;
proto = JS_InitClass(cx, obj, NULL, &ds_Class, NotePlayer_constructor, 2,
ds_props, ds_methods,
NULL /* static_props*/, NULL /* static_method*/);
return proto;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
| 7,902
| 7,902
| 0.544546
|
jht1900
|
6db6bf97c68d3e0e821cca6cdf254fa338c4bf2c
| 1,939
|
cpp
|
C++
|
ComfyDxEngine/strconv.cpp
|
makuke1234/ComfyEditor
|
72054f1fb60b11df2c3158f3960cff9fcc5c1440
|
[
"MIT"
] | null | null | null |
ComfyDxEngine/strconv.cpp
|
makuke1234/ComfyEditor
|
72054f1fb60b11df2c3158f3960cff9fcc5c1440
|
[
"MIT"
] | null | null | null |
ComfyDxEngine/strconv.cpp
|
makuke1234/ComfyEditor
|
72054f1fb60b11df2c3158f3960cff9fcc5c1440
|
[
"MIT"
] | null | null | null |
#include "pch.hpp"
#include "strconv.hpp"
COMFYDX_API std::string ce::conv(std::wstring_view str)
{
int realSize = ::WideCharToMultiByte(
CP_UTF8,
0,
str.data(),
str.size() + 1,
nullptr,
0,
nullptr,
nullptr
);
std::string out;
out.resize(realSize - 1);
::WideCharToMultiByte(
CP_UTF8,
0,
str.data(),
str.size() + 1,
out.data(),
realSize,
nullptr,
nullptr
);
return out;
}
COMFYDX_API std::wstring ce::conv(std::string_view str)
{
int realSize = ::MultiByteToWideChar(
CP_UTF8,
MB_PRECOMPOSED,
str.data(),
str.size() + 1,
nullptr,
0
);
std::wstring out;
out.resize(realSize - 1);
::MultiByteToWideChar(
CP_UTF8,
MB_PRECOMPOSED,
str.data(),
str.size() + 1,
out.data(),
realSize
);
return out;
}
template<> COMFYDX_API float ce::stof<float>(std::string_view str, std::size_t * pos)
{
char * ptr;
auto val = std::strtof(str.data(), &ptr);
if (str.data() == ptr)
{
throw std::invalid_argument("stof<float>");
}
else if (errno == ERANGE)
{
throw std::out_of_range("stof<float>");
}
else if (pos != nullptr)
{
*pos = std::size_t(ptr - str.data());
}
return val;
}
template<> COMFYDX_API double ce::stof<double>(std::string_view str, std::size_t * pos)
{
char * ptr;
auto val = std::strtod(str.data(), &ptr);
if (str.data() == ptr)
{
throw std::invalid_argument("stof<double>");
}
else if (errno == ERANGE)
{
throw std::out_of_range("stof<double>");
}
else if (pos != nullptr)
{
*pos = std::size_t(ptr - str.data());
}
return val;
}
template<> COMFYDX_API long double ce::stof<long double>(std::string_view str, std::size_t * pos)
{
char * ptr;
auto val = std::strtold(str.data(), &ptr);
if (str.data() == ptr)
{
throw std::invalid_argument("stof<long double>");
}
else if (errno == ERANGE)
{
throw std::out_of_range("stof<long double>");
}
if (pos != nullptr)
{
*pos = std::size_t(ptr - str.data());
}
return val;
}
| 17.468468
| 97
| 0.62558
|
makuke1234
|
6dbfa094199e1b0f5185d7da84e03353a8708676
| 14,970
|
cpp
|
C++
|
spoki/libspoki/src/probe/udp_prober.cpp
|
inetrg/spoki
|
599a19366e4cea70e2391471de6f6b745935cddf
|
[
"MIT"
] | 1
|
2022-02-03T15:35:16.000Z
|
2022-02-03T15:35:16.000Z
|
spoki/libspoki/src/probe/udp_prober.cpp
|
inetrg/spoki
|
599a19366e4cea70e2391471de6f6b745935cddf
|
[
"MIT"
] | null | null | null |
spoki/libspoki/src/probe/udp_prober.cpp
|
inetrg/spoki
|
599a19366e4cea70e2391471de6f6b745935cddf
|
[
"MIT"
] | null | null | null |
/*
* This file is part of the CAF spoki driver.
*
* Copyright (C) 2018-2021
* Authors: Raphael Hiesgen
*
* All rights reserved.
*
* Report any bugs, questions or comments to raphael.hiesgen@haw-hamburg.de
*
*/
#include "spoki/probe/udp_prober.hpp"
#include <arpa/inet.h>
#include <fcntl.h>
#include <iomanip>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <caf/io/network/default_multiplexer.hpp>
#include <caf/io/network/interfaces.hpp>
#include <caf/io/network/ip_endpoint.hpp>
#include <caf/io/network/native_socket.hpp>
#include <caf/ipv4_address.hpp>
#ifdef SPOKI_KQUEUE_DECODER
# include <sys/event.h>
#else // SPOKI_POLL_DECODER
# include <poll.h>
#endif
#include "spoki/atoms.hpp"
#include "spoki/logger.hpp"
#include "spoki/task.hpp"
#include "spoki/scamper/ping.hpp"
namespace spoki::probe {
namespace {
void down_handler(caf::scheduled_actor* ptr, caf::down_msg& msg) {
if (msg.reason != caf::exit_reason::user_shutdown)
aout(ptr) << "shard died unexpectedly (" << to_string(msg.source)
<< "): " << to_string(msg.reason) << std::endl;
}
void poke(int sockfd) {
uint8_t tmp = 1;
::send(sockfd, &tmp, sizeof(tmp), 0);
}
struct pseudo_ip_hdr {
uint8_t ihl : 4, ver : 4;
uint8_t ecn : 2, tos : 6;
uint16_t len;
uint16_t idn;
uint16_t off; // off: 13, flg: 3; this doesn't work as I want it to
uint8_t ttl;
uint8_t pro;
uint16_t chk;
uint32_t src;
uint32_t dst;
};
struct pseudo_udp_hdr {
uint16_t src;
uint16_t dst;
uint16_t len;
uint16_t chk;
};
uint16_t checksum(const pseudo_ip_hdr* hdr) {
const uint16_t* begin = reinterpret_cast<const uint16_t*>(hdr);
const uint16_t* end = begin + sizeof(pseudo_ip_hdr) / 2;
uint32_t checksum = 0;
uint32_t first_half = 0;
uint32_t second_half = 0;
for (; begin != end; ++begin)
checksum += *begin;
first_half = static_cast<uint16_t>(checksum >> 16);
while (first_half != 0) {
second_half = static_cast<uint16_t>((checksum << 16) >> 16);
checksum = first_half + second_half;
first_half = static_cast<uint16_t>(checksum >> 16);
}
return static_cast<uint16_t>(~checksum);
}
} // namespace
udp_request::udp_request(caf::ipv4_address saddr, caf::ipv4_address daddr,
uint16_t sport, uint16_t dport, std::vector<char> pl)
: saddr{saddr},
daddr{daddr},
sport{sport},
dport{dport},
payload(std::move(pl)) {
// nop
}
udp_prober::udp_prober(int sockfd, payload_map payloads)
: reflect_{false},
default_payload_{'\x0A'},
// default_payload_{'\x0D', '\x0A', '\x0D', '\x0A'},
// default_payload_{'h', 'a', 'l', 'l', 'o', '\x0A'},
payloads_{std::move(payloads)},
done_{false},
writing_{false},
probe_out_fd_{sockfd} {
// nop
}
udp_prober::~udp_prober() {
// Close the open sockets.
close(notify_in_fd_);
close(notify_out_fd_);
close(probe_out_fd_);
}
udp_prober::udp_prober_ptr udp_prober::make(bool service_specific,
bool reflect) {
using namespace caf::io;
auto fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (fd == -1) {
std::cerr << "ERR: Failed to create raw socket: "
<< network::last_socket_error_as_string() << std::endl;
return nullptr;
}
// I think this is already enabled on IPPROTO_RAW.
int on = 1;
if (setsockopt(fd, IPPROTO_IP, IP_HDRINCL,
reinterpret_cast<network::setsockopt_ptr>(&on),
static_cast<network::socket_size_type>(sizeof(on)))) {
std::cerr << "ERR: Failed to set IP_HDRINCL: " << strerror(errno)
<< std::endl;
close(fd);
exit(0);
}
/*
int on = 1;
auto ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<network::setsockopt_ptr>(&on),
static_cast<network::socket_size_type>(sizeof(on)));
if (ret != 0) {
std::cerr << "ERR: Failed to set reuse address option." << std::endl;
close(sockfd);
return nullptr;
}
*/
// Create socket pair for notifcation of the mpx loop.
std::array<int, 2> notify_pair;
// Create socket pair for notification.
if (socketpair(AF_UNIX, SOCK_STREAM, 0, notify_pair.data()) != 0) {
std::cerr << "ERR: Failed to create pair for notification." << std::endl;
close(fd);
return nullptr;
}
// Set nonblocking.
if (!network::nonblocking(fd, true)
|| !network::nonblocking(notify_pair[0], true)
|| !network::nonblocking(notify_pair[1], true)) {
std::cerr << "ERR: Failed to set sockets to non-blocking." << std::endl;
close(fd);
close(notify_pair[0]);
close(notify_pair[1]);
return nullptr;
}
// Generate payload map.
payload_map payloads;
if (service_specific)
payloads = get_payloads();
// Nice, let's get this started.
auto ptr = caf::make_counted<udp_prober>(fd, std::move(payloads));
ptr->notify_in_fd_ = notify_pair[0];
ptr->notify_out_fd_ = notify_pair[1];
ptr->reflect_ = reflect;
ptr->start();
return ptr;
}
void udp_prober::start() {
// Set callbacks for socket event.
callbacks_.clear();
callbacks_[notify_in_fd_] = [&]() { handle_notify_read(); };
callbacks_[probe_out_fd_] = [&]() { handle_probe_write(); };
mpx_loop_ = std::thread(&udp_prober::run, this);
}
void udp_prober::add_request(caf::ipv4_address saddr, caf::ipv4_address daddr,
uint16_t sport, uint16_t dport,
std::vector<char>& pl) {
// This might be called from another thread.
std::lock_guard<std::mutex> guard(mtx_);
requests_.emplace_back(saddr, daddr, sport, dport, std::move(pl));
if (!writing_)
poke(notify_out_fd_);
}
void udp_prober::shutdown() {
// Not sure this will work ...
stop();
}
void udp_prober::stop() {
std::cout << "stop called" << std::endl;
done_ = true;
if (is_valid(notify_out_fd_)) {
poke(notify_out_fd_);
// TODO: This might be a bad idea?
if (mpx_loop_.joinable())
mpx_loop_.join();
}
mpx_loop_ = std::thread();
}
void udp_prober::handle_notify_read() {
std::array<uint8_t, 16> tmp;
auto res = ::recv(notify_in_fd_, tmp.data(), 16, 0);
if (res < 0)
std::cerr << "notify error: " << strerror(errno) << std::endl;
// TODO: Check queue size?
enable(probe_out_fd_, operation::write);
writing_ = true;
}
void udp_prober::handle_probe_write() {
using namespace caf::io::network;
std::lock_guard<std::mutex> guard(mtx_);
if (!requests_.empty()) {
auto& next = requests_.front();
// TODO: there is probably a better way to do this.
// The bits in the ipv4_address might already be in network byte order.
auto ip_dst = to_string(next.daddr);
auto ip_src = to_string(next.saddr);
auto len = sizeof(pseudo_ip_hdr) + sizeof(pseudo_udp_hdr);
auto& payload = default_payload_;
if (payloads_.count(next.dport) > 0)
payload = payloads_[next.dport];
else if (reflect_)
payload = next.payload;
len += payload.size();
send_buffer_.resize(len);
memset(send_buffer_.data(), 0, send_buffer_.size());
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = htons(next.dport);
sin.sin_addr.s_addr = inet_addr(ip_dst.c_str());
// Write IP header.
auto* ip = reinterpret_cast<pseudo_ip_hdr*>(send_buffer_.data());
ip->ver = 4;
ip->ihl = 5;
ip->tos = 0;
ip->ecn = 0;
ip->len = htons(len);
ip->idn = htons(1337);
ip->off = htons(0x4000); // Don't fragment.
ip->ttl = 64;
ip->pro = IPPROTO_UDP;
ip->src = inet_addr(ip_src.c_str());
ip->dst = sin.sin_addr.s_addr;
// Checksum at the end.
ip->chk = htons(checksum(ip));
// Write UDP header.
auto udp_len = static_cast<uint16_t>(sizeof(pseudo_udp_hdr)
+ payload.size());
auto* udp = reinterpret_cast<pseudo_udp_hdr*>(send_buffer_.data()
+ sizeof(pseudo_ip_hdr));
udp->src = htons(next.sport);
udp->dst = htons(next.dport);
udp->len = htons(udp_len);
udp->chk = 0;
// Attach payload.
std::copy(payload.begin(), payload.end(),
send_buffer_.data() + sizeof(pseudo_ip_hdr)
+ sizeof(pseudo_udp_hdr));
// And send it!
auto sres = ::sendto(probe_out_fd_,
reinterpret_cast<socket_send_ptr>(send_buffer_.data()),
send_buffer_.size(), 0,
reinterpret_cast<sockaddr*>(&sin), sizeof(sin));
if (is_error(sres, true))
std::cerr << "Failed to send to '" << ip_dst << ":" << next.sport
<< "': " << sres << std::endl;
requests_.pop_front();
}
// Remove us from write events if there is nothing to process.
if (requests_.empty()) {
disable(probe_out_fd_, operation::write);
writing_ = false;
}
}
void udp_prober::handle_probe_read() {
// nop, shouldn't happen.
}
bool udp_prober::is_valid(int sockfd) {
return fcntl(sockfd, F_GETFL) != -1 || errno != EBADF;
}
#ifdef SPOKI_KQUEUE_DECODER
void udp_prober::run() {
// Multiplexer ref.
caf::intrusive_ptr_add_ref(this);
// Create kqueue for multiplexing.
if ((kq_ = kqueue()) == -1) {
std::cerr << "failed to create kqueue\n";
return;
}
// Setup our initial socket events;
std::array<struct kevent, 2> initial_events;
EV_SET(&initial_events[0], static_cast<uint64_t>(notify_in_fd_), EVFILT_READ,
EV_ADD | EV_ENABLE, 0, 0, nullptr);
// We only want to enable this once we have data to write.
EV_SET(&initial_events[1], static_cast<uint64_t>(probe_out_fd_), EVFILT_WRITE,
EV_ADD | EV_DISABLE, 0, 0, nullptr);
if (kevent(kq_, initial_events.data(), 3, nullptr, 0, nullptr) == -1) {
std::cerr << "failed to setup initial kqueue events\n";
return;
}
// For our kqueue operation;
std::array<struct kevent, 32> events;
for (; !done_;) {
int cnt = kevent(kq_, nullptr, 0, events.data(), events.size(), nullptr);
if (cnt == -1) {
std::cerr << "kqueue failed: " << strerror(errno) << std::endl;
done_ = true;
continue;
}
for (size_t i = 0; i < static_cast<size_t>(cnt); ++i) {
if (events[i].flags & EV_EOF) {
std::cerr << "got eof\n";
done_ = true;
} else if (events[i].flags & EV_ERROR) {
std::cerr << "got error event with "
<< events[i].data << ": "
<< strerror(static_cast<int>(events[i].data)) << std::endl;
done_ = true;
} else if (callbacks_.count(static_cast<int>(events[i].ident)) > 0) {
callbacks_[static_cast<int>(events[i].ident)]();
} else {
std::cerr << "kqueue returned unexpected event\n";
}
}
}
// Remove all the events.
EV_SET(&initial_events[0], static_cast<uint64_t>(notify_in_fd_), EVFILT_READ,
EV_DELETE, 0, 0, nullptr);
EV_SET(&initial_events[1], static_cast<uint64_t>(probe_out_fd_), EVFILT_WRITE,
EV_DELETE, 0, 0, nullptr);
if (kevent(kq_, initial_events.data(), 3, nullptr, 0, nullptr) == -1) {
std::cerr << "failed to setup initial kqueue events\n";
return;
}
if (kq_)
close(kq_);
// Multiplexer ref.
caf::intrusive_ptr_release(this);
}
void udp_prober::enable(int sockfd, operation op) {
switch (op) {
case operation::read:
mod(static_cast<uint64_t>(sockfd), EVFILT_READ, EV_ENABLE);
break;
case operation::write:
mod(static_cast<uint64_t>(sockfd), EVFILT_WRITE, EV_ENABLE);
}
}
void udp_prober::disable(int sockfd, operation op) {
switch (op) {
case operation::read:
mod(static_cast<uint64_t>(sockfd), EVFILT_READ, EV_DISABLE);
break;
case operation::write:
mod(static_cast<uint64_t>(sockfd), EVFILT_WRITE, EV_DISABLE);
}
}
void udp_prober::mod(uint64_t sockfd, int16_t filter, uint16_t operation) {
struct kevent new_event;
EV_SET(&new_event, sockfd, filter, operation, 0, 0, nullptr);
if (kevent(kq_, &new_event, 1, nullptr, 0, nullptr) == -1) {
std::cerr << "failed to add event to kqueue\n";
done_ = true;
}
}
#else // SPOKI_POLL_DECODER
void udp_prober::run() {
// Multiplexer ref.
caf::intrusive_ptr_add_ref(this);
std::array<pollfd, 2> ufds;
// read event to notify queue changes
ufds[0].fd = notify_in_fd_;
ufds[0].events = POLLIN;
mods_[notify_in_fd_] = [&](short val) { ufds[0].events = val; };
// write to socket from queue
ufds[1].fd = probe_out_fd_;
ufds[1].events = 0;
mods_[probe_out_fd_] = [&](short val) { ufds[1].events = val; };
int rv = -1;
const auto cnt = ufds.size();
const auto mask = POLLIN | POLLOUT;
for (done_ = false; !done_;) {
rv = ::poll(ufds.data(), ufds.size(), -1);
if (rv == -1) {
std::cerr << "poll returned " << rv << std::endl;
done_ = true;
continue;
}
for (size_t i = 0; i < cnt; ++i) {
// There is either POLLIN or POLLOUT registered for a socket here.
if (ufds[i].revents & mask) {
if (callbacks_.count(static_cast<int>(ufds[i].fd)) > 0) {
callbacks_[static_cast<int>(ufds[i].fd)]();
} else {
//std::cerr << "no callback found" << std::endl;
std::cerr << "poll returned unexpected event\n";
}
}
}
}
// Multiplexer ref.
caf::intrusive_ptr_release(this);
}
void udp_prober::enable(int sockfd, operation op) {
switch (op) {
case operation::read:
mods_[sockfd](POLLIN);
break;
case operation::write:
mods_[sockfd](POLLOUT);
}
}
void udp_prober::disable(int sockfd, operation) {
mods_[sockfd](0);
}
#endif // SPOKI_POLL_DECODER
const char* upi_state::name = "udp_prober";
caf::behavior prober(caf::stateful_actor<upi_state>* self,
udp_prober::udp_prober_ptr backend) {
self->state.backend = backend;
self->set_down_handler(down_handler);
self->set_default_handler(caf::print_and_drop);
return {
[=](spoki::request_atom, packet& pkt) {
if (pkt.carries_udp()) {
auto& proto = pkt.protocol<net::udp>();
self->state.backend->add_request(pkt.daddr, pkt.saddr, proto.dport,
proto.sport, proto.payload);
} else {
std::cerr << "Not UDP, dropping " << to_string(pkt) << std::endl;
}
},
[=](spoki::request_atom, caf::ipv4_address& saddr, caf::ipv4_address& daddr,
uint16_t sport, uint16_t dport, std::vector<char> pl) {
aout(self) << "New target: " << to_string(daddr) << ":" << dport
<< std::endl;
self->state.backend->add_request(saddr, daddr, sport, dport, pl);
},
[=](spoki::done_atom) {
aout(self) << "Prober got done message" << std::endl;
self->state.backend->shutdown();
self->quit();
},
};
}
} // namespace spoki::probe
| 30.242424
| 80
| 0.620174
|
inetrg
|
6dc0c5910faebfa6e3655c91a5609e2b4d887e97
| 34,920
|
cpp
|
C++
|
PositionBasedDynamics/PositionBasedDynamics.cpp
|
aibel18/phasechange
|
30fa880fbd063b26b7e8187be4231fb40c668335
|
[
"MIT"
] | 2
|
2019-11-19T20:15:34.000Z
|
2021-11-27T05:08:30.000Z
|
PositionBasedDynamics/PositionBasedDynamics.cpp
|
aibel18/phasechange
|
30fa880fbd063b26b7e8187be4231fb40c668335
|
[
"MIT"
] | null | null | null |
PositionBasedDynamics/PositionBasedDynamics.cpp
|
aibel18/phasechange
|
30fa880fbd063b26b7e8187be4231fb40c668335
|
[
"MIT"
] | 1
|
2019-11-19T20:15:37.000Z
|
2019-11-19T20:15:37.000Z
|
#include "PositionBasedDynamics.h"
#include "MathFunctions.h"
#include <cfloat>
using namespace PBD;
const Real eps = 1e-6;
const Real compliance = 1e-9;
//////////////////////////////////////////////////////////////////////////
// XPositionBasedDynamics
//////////////////////////////////////////////////////////////////////////
bool PositionBasedDynamics::solve_DistanceConstraintX(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Real restLength,
const Real compressionStiffness,
const Real stretchStiffness,
Vector3r &corr0, Vector3r &corr1,
Real& lambda,
const Real dt)
{
Real wSum = invMass0 + invMass1;
if (wSum == 0.0)
return false;
Real factorCompliance = compliance / (dt * dt);
Real deltaLambda = 0.0f;
Vector3r n = p1 - p0;
Real d = n.norm();
//n.normalize();
Vector3r corr;
if (d < restLength) {
deltaLambda = ( (d - restLength) - factorCompliance * lambda ) / (wSum + factorCompliance);
corr = compressionStiffness * deltaLambda * n / ( d - eps );
lambda += deltaLambda;
}
else {
deltaLambda = ( (d - restLength) - factorCompliance * lambda) / (wSum + factorCompliance);
corr = stretchStiffness * deltaLambda * n / (d - eps);
lambda += deltaLambda;
}
corr0 = invMass0 * corr;
corr1 = -invMass1 * corr;
return true;
}
//////////////////////////////////////////////////////////////////////////
// PositionBasedDynamics
//////////////////////////////////////////////////////////////////////////
bool PositionBasedDynamics::solve_DistanceConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Real restLength,
const Real compressionStiffness,
const Real stretchStiffness,
Vector3r &corr0, Vector3r &corr1)
{
Real wSum = invMass0 + invMass1;
if (wSum == 0.0)
return false;
Vector3r n = p1 - p0;
Real d = n.norm();
n.normalize();
Vector3r corr;
if (d < restLength)
corr = compressionStiffness * n * (d - restLength) / wSum;
else
corr = stretchStiffness * n * (d - restLength) / wSum;
corr0 = invMass0 * corr;
corr1 = -invMass1 * corr;
return true;
}
bool PositionBasedDynamics::solve_DihedralConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Vector3r &p3, Real invMass3,
const Real restAngle,
const Real stiffness,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2, Vector3r &corr3)
{
// derivatives from Bridson, Simulation of Clothing with Folds and Wrinkles
// his modes correspond to the derivatives of the bending angle arccos(n1 dot n2) with correct scaling
if (invMass0 == 0.0 && invMass1 == 0.0)
return false;
Vector3r e = p3-p2;
Real elen = e.norm();
if (elen < eps)
return false;
Real invElen = 1.0 / elen;
Vector3r n1 = (p2-p0).cross(p3-p0); n1 /= n1.squaredNorm();
Vector3r n2 = (p3 - p1).cross(p2 - p1); n2 /= n2.squaredNorm();
Vector3r d0 = elen*n1;
Vector3r d1 = elen*n2;
Vector3r d2 = (p0-p3).dot(e) * invElen * n1 + (p1-p3).dot(e) * invElen * n2;
Vector3r d3 = (p2-p0).dot(e) * invElen * n1 + (p2-p1).dot(e) * invElen * n2;
n1.normalize();
n2.normalize();
Real dot = n1.dot(n2);
if (dot < -1.0) dot = -1.0;
if (dot > 1.0) dot = 1.0;
Real phi = acos(dot);
// Real phi = (-0.6981317 * dot * dot - 0.8726646) * dot + 1.570796; // fast approximation
Real lambda =
invMass0 * d0.squaredNorm() +
invMass1 * d1.squaredNorm() +
invMass2 * d2.squaredNorm() +
invMass3 * d3.squaredNorm();
if (lambda == 0.0)
return false;
// stability
// 1.5 is the largest magic number I found to be stable in all cases :-)
//if (stiffness > 0.5 && fabs(phi - b.restAngle) > 1.5)
// stiffness = 0.5;
lambda = (phi - restAngle) / lambda * stiffness;
if (n1.cross(n2).dot(e) > 0.0)
lambda = -lambda;
corr0 = - invMass0 * lambda * d0;
corr1 = - invMass1 * lambda * d1;
corr2 = - invMass2 * lambda * d2;
corr3 = - invMass3 * lambda * d3;
return true;
}
bool PositionBasedDynamics::solve_VolumeConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Vector3r &p3, Real invMass3,
const Real restVolume,
const Real negVolumeStiffness,
const Real posVolumeStiffness,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2, Vector3r &corr3)
{
Vector3r d1 = p1 - p0;
Vector3r d2 = p2 - p0;
Vector3r d3 = p3 - p0;
Real volume = 1.0 / 6.0 * (p1 - p0).cross(p2 - p0).dot(p3 - p0);
corr0.setZero(); corr1.setZero(); corr2.setZero(); corr3.setZero();
if (posVolumeStiffness == 0.0 && volume > 0.0)
return false;
if (negVolumeStiffness == 0.0 && volume < 0.0)
return false;
Vector3r grad0 = (p1 - p2).cross(p3 - p2);
Vector3r grad1 = (p2 - p0).cross(p3 - p0);
Vector3r grad2 = (p0 - p1).cross(p3 - p1);
Vector3r grad3 = (p1 - p0).cross(p2 - p0);
Real lambda =
invMass0 * grad0.squaredNorm() +
invMass1 * grad1.squaredNorm() +
invMass2 * grad2.squaredNorm() +
invMass3 * grad3.squaredNorm();
if (fabs(lambda) < eps)
return false;
if (volume < 0.0)
lambda = negVolumeStiffness * (volume - restVolume) / lambda;
else
lambda = posVolumeStiffness * (volume - restVolume) / lambda;
corr0 = -lambda * invMass0 * grad0;
corr1 = -lambda * invMass1 * grad1;
corr2 = -lambda * invMass2 * grad2;
corr3 = -lambda * invMass3 * grad3;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::init_IsometricBendingConstraint(
const Vector3r &p0,
const Vector3r &p1,
const Vector3r &p2,
const Vector3r &p3,
Matrix4r &Q)
{
// Compute matrix Q for quadratic bending
const Vector3r *x[4] = { &p2, &p3, &p0, &p1 };
const Vector3r e0 = *x[1] - *x[0];
const Vector3r e1 = *x[2] - *x[0];
const Vector3r e2 = *x[3] - *x[0];
const Vector3r e3 = *x[2] - *x[1];
const Vector3r e4 = *x[3] - *x[1];
const Real c01 = MathFunctions::cotTheta(e0, e1);
const Real c02 = MathFunctions::cotTheta(e0, e2);
const Real c03 = MathFunctions::cotTheta(-e0, e3);
const Real c04 = MathFunctions::cotTheta(-e0, e4);
const Real A0 = 0.5 * (e0.cross(e1)).norm();
const Real A1 = 0.5 * (e0.cross(e2)).norm();
const Real coef = -3.f / (2.f*(A0 + A1));
const Real K[4] = { c03 + c04, c01 + c02, -c01 - c03, -c02 - c04 };
const Real K2[4] = { coef*K[0], coef*K[1], coef*K[2], coef*K[3] };
for (unsigned char j = 0; j < 4; j++)
{
for (unsigned char k = 0; k < j; k++)
{
Q(j, k) = Q(k, j) = K[j] * K2[k];
}
Q(j, j) = K[j] * K2[j];
}
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_IsometricBendingConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Vector3r &p3, Real invMass3,
const Matrix4r &Q,
const Real stiffness,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2, Vector3r &corr3)
{
const Vector3r *x[4] = { &p2, &p3, &p0, &p1 };
Real invMass[4] = { invMass2, invMass3, invMass0, invMass1 };
Real energy = 0.0;
for (unsigned char k = 0; k < 4; k++)
for (unsigned char j = 0; j < 4; j++)
energy += Q(j, k)*(x[k]->dot(*x[j]));
energy *= 0.5;
Vector3r gradC[4];
gradC[0].setZero();
gradC[1].setZero();
gradC[2].setZero();
gradC[3].setZero();
for (unsigned char k = 0; k < 4; k++)
for (unsigned char j = 0; j < 4; j++)
gradC[j] += Q(j,k) * *x[k];
Real sum_normGradC = 0.0;
for (unsigned int j = 0; j < 4; j++)
{
// compute sum of squared gradient norms
if (invMass[j] != 0.0)
sum_normGradC += invMass[j] * gradC[j].squaredNorm();
}
// exit early if required
if (fabs(sum_normGradC) > eps)
{
// compute impulse-based scaling factor
const Real s = energy / sum_normGradC;
corr0 = -stiffness * (s*invMass[2]) * gradC[2];
corr1 = -stiffness * (s*invMass[3]) * gradC[3];
corr2 = -stiffness * (s*invMass[0]) * gradC[0];
corr3 = -stiffness * (s*invMass[1]) * gradC[1];
return true;
}
return false;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_EdgePointDistanceConstraint(
const Vector3r &p, Real invMass,
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Real restDist,
const Real compressionStiffness,
const Real stretchStiffness,
Vector3r &corr, Vector3r &corr0, Vector3r &corr1)
{
Vector3r d = p1 - p0;
Real t;
if ((p0-p1).squaredNorm() < eps * eps)
t = 0.5;
else {
Real d2 = d.dot(d);
t = d.dot(p - p1) / d2;
if (t < 0.0)
t = 0.0;
else if (t > 1.0)
t = 1.0;
}
Vector3r q = p0 + d*t; // closest point on edge
Vector3r n = p - q;
Real dist = n.norm();
n.normalize();
Real C = dist - restDist;
Real b0 = 1.0 - t;
Real b1 = t;
Vector3r grad = n;
Vector3r grad0 = -n * b0;
Vector3r grad1 = -n * b1;
Real s = invMass + invMass0 * b0 * b0 + invMass1 * b1 * b1;
if (s == 0.0)
return false;
s = C / s;
if (C < 0.0)
s *= compressionStiffness;
else
s *= stretchStiffness;
if (s == 0.0)
return false;
corr = -s * invMass * grad;
corr0 = -s * invMass0 * grad0;
corr1 = -s * invMass1 * grad1;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_TrianglePointDistanceConstraint(
const Vector3r &p, Real invMass,
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Real restDist,
const Real compressionStiffness,
const Real stretchStiffness,
Vector3r &corr, Vector3r &corr0, Vector3r &corr1, Vector3r &corr2)
{
// find barycentric coordinates of closest point on triangle
Real b0 = 1.0 / 3.0; // for singular case
Real b1 = b0;
Real b2 = b0;
Vector3r d1 = p1 - p0;
Vector3r d2 = p2 - p0;
Vector3r pp0 = p - p0;
Real a = d1.dot(d1);
Real b = d2.dot(d1);
Real c = pp0.dot(d1);
Real d = b;
Real e = d2.dot(d2);
Real f = pp0.dot(d2);
Real det = a*e - b*d;
if (det != 0.0) {
Real s = (c*e - b*f) / det;
Real t = (a*f - c*d) / det;
b0 = 1.0 - s - t; // inside triangle
b1 = s;
b2 = t;
if (b0 < 0.0) { // on edge 1-2
Vector3r d = p2 - p1;
Real d2 = d.dot(d);
Real t = (d2 == 0.0) ? 0.5 : d.dot(p - p1) / d2;
if (t < 0.0) t = 0.0; // on point 1
if (t > 1.0) t = 1.0; // on point 2
b0 = 0.0;
b1 = (1.0 - t);
b2 = t;
}
else if (b1 < 0.0) { // on edge 2-0
Vector3r d = p0 - p2;
Real d2 = d.dot(d);
Real t = (d2 == 0.0) ? 0.5 : d.dot(p - p2) / d2;
if (t < 0.0) t = 0.0; // on point 2
if (t > 1.0) t = 1.0; // on point 0
b1 = 0.0;
b2 = (1.0 - t);
b0 = t;
}
else if (b2 < 0.0) { // on edge 0-1
Vector3r d = p1 - p0;
Real d2 = d.dot(d);
Real t = (d2 == 0.0) ? 0.5 : d.dot(p - p0) / d2;
if (t < 0.0) t = 0.0; // on point 0
if (t > 1.0) t = 1.0; // on point 1
b2 = 0.0;
b0 = (1.0 - t);
b1 = t;
}
}
Vector3r q = p0 * b0 + p1 * b1 + p2 * b2;
Vector3r n = p - q;
Real dist = n.norm();
n.normalize();
Real C = dist - restDist;
Vector3r grad = n;
Vector3r grad0 = -n * b0;
Vector3r grad1 = -n * b1;
Vector3r grad2 = -n * b2;
Real s = invMass + invMass0 * b0*b0 + invMass1 * b1*b1 + invMass2 * b2*b2;
if (s == 0.0)
return false;
s = C / s;
if (C < 0.0)
s *= compressionStiffness;
else
s *= stretchStiffness;
if (s == 0.0)
return false;
corr = -s * invMass * grad;
corr0 = -s * invMass0 * grad0;
corr1 = -s * invMass1 * grad1;
corr2 = -s * invMass2 * grad2;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_EdgeEdgeDistanceConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Vector3r &p3, Real invMass3,
const Real restDist,
const Real compressionStiffness,
const Real stretchStiffness,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2, Vector3r &corr3)
{
Vector3r d0 = p1 - p0;
Vector3r d1 = p3 - p2;
Real a = d0.squaredNorm();
Real b = -d0.dot(d1);
Real c = d0.dot(d1);
Real d = -d1.squaredNorm();
Real e = (p2 - p0).dot(d0);
Real f = (p2 - p0).dot(d1);
Real det = a*d - b*c;
Real s, t;
if (det != 0.0) {
det = 1.0 / det;
s = (e*d - b*f) * det;
t = (a*f - e*c) * det;
}
else { // d0 and d1 parallel
Real s0 = p0.dot(d0);
Real s1 = p1.dot(d0);
Real t0 = p2.dot(d0);
Real t1 = p3.dot(d0);
bool flip0 = false;
bool flip1 = false;
if (s0 > s1) { Real f = s0; s0 = s1; s1 = f; flip0 = true; }
if (t0 > t1) { Real f = t0; t0 = t1; t1 = f; flip1 = true; }
if (s0 >= t1) {
s = !flip0 ? 0.0 : 1.0;
t = !flip1 ? 1.0 : 0.0;
}
else if (t0 >= s1) {
s = !flip0 ? 1.0 : 0.0;
t = !flip1 ? 0.0 : 1.0;
}
else { // overlap
Real mid = (s0 > t0) ? (s0 + t1) * 0.5 : (t0 + s1) * 0.5;
s = (s0 == s1) ? 0.5 : (mid - s0) / (s1 - s0);
t = (t0 == t1) ? 0.5 : (mid - t0) / (t1 - t0);
}
}
if (s < 0.0) s = 0.0;
if (s > 1.0) s = 1.0;
if (t < 0.0) t = 0.0;
if (t > 1.0) t = 1.0;
Real b0 = 1.0 - s;
Real b1 = s;
Real b2 = 1.0 - t;
Real b3 = t;
Vector3r q0 = p0 * b0 + p1 * b1;
Vector3r q1 = p2 * b2 + p3 * b3;
Vector3r n = q0 - q1;
Real dist = n.norm();
n.normalize();
Real C = dist - restDist;
Vector3r grad0 = n * b0;
Vector3r grad1 = n * b1;
Vector3r grad2 = -n * b2;
Vector3r grad3 = -n * b3;
s = invMass0 * b0*b0 + invMass1 * b1*b1 + invMass2 * b2*b2 + invMass3 * b3*b3;
if (s == 0.0)
return false;
s = C / s;
if (C < 0.0)
s *= compressionStiffness;
else
s *= stretchStiffness;
if (s == 0.0)
return false;
corr0 = -s * invMass0 * grad0;
corr1 = -s * invMass1 * grad1;
corr2 = -s * invMass2 * grad2;
corr3 = -s * invMass3 * grad3;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::init_ShapeMatchingConstraint(
const Vector3r x0[], const Real invMasses[], int numPoints,
Vector3r &restCm, Matrix3r &invRestMat)
{
invRestMat.setIdentity();
// center of mass
restCm.setZero();
Real wsum = 0.0;
for (int i = 0; i < numPoints; i++) {
Real wi = 1.0 / (invMasses[i] + eps);
restCm += x0[i] * wi;
wsum += wi;
}
if (wsum == 0.0)
return false;
restCm /= wsum;
// A
Matrix3r A;
A.setZero();
for (int i = 0; i < numPoints; i++) {
const Vector3r qi = x0[i] - restCm;
Real wi = 1.0 / (invMasses[i] + eps);
Real x2 = wi * qi[0] * qi[0];
Real y2 = wi * qi[1] * qi[1];
Real z2 = wi * qi[2] * qi[2];
Real xy = wi * qi[0] * qi[1];
Real xz = wi * qi[0] * qi[2];
Real yz = wi * qi[1] * qi[2];
A(0, 0) += x2; A(0, 1) += xy; A(0, 2) += xz;
A(1, 0) += xy; A(1, 1) += y2; A(1, 2) += yz;
A(2, 0) += xz; A(2, 1) += yz; A(2, 2) += z2;
}
Real det = A.determinant();
if (fabs(det) > eps)
{
invRestMat = A.inverse();
return true;
}
return false;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_ShapeMatchingConstraint(
const Vector3r x0[], const Vector3r x[], const Real invMasses[], int numPoints,
const Vector3r &restCm,
const Matrix3r &invRestMat,
const Real stiffness,
const bool allowStretch,
Vector3r corr[], Matrix3r *rot)
{
for (int i = 0; i < numPoints; i++)
corr[i].setZero();
// center of mass
Vector3r cm(0.0, 0.0, 0.0);
Real wsum = 0.0;
for (int i = 0; i < numPoints; i++)
{
Real wi = 1.0 / (invMasses[i] + eps);
cm += x[i] * wi;
wsum += wi;
}
if (wsum == 0.0)
return false;
cm /= wsum;
// A
Matrix3r mat;
mat.setZero();
for (int i = 0; i < numPoints; i++) {
Vector3r q = x0[i] - restCm;
Vector3r p = x[i] - cm;
Real w = 1.0 / (invMasses[i] + eps);
p *= w;
mat(0, 0) += p[0] * q[0]; mat(0, 1) += p[0] * q[1]; mat(0, 2) += p[0] * q[2];
mat(1, 0) += p[1] * q[0]; mat(1, 1) += p[1] * q[1]; mat(1, 2) += p[1] * q[2];
mat(2, 0) += p[2] * q[0]; mat(2, 1) += p[2] * q[1]; mat(2, 2) += p[2] * q[2];
}
mat = mat * invRestMat;
Matrix3r R, U, D;
R = mat;
if (allowStretch)
R = mat;
else
//MathFunctions::polarDecomposition(mat, R, U, D);
MathFunctions::polarDecompositionStable(mat, eps, R);
for (int i = 0; i < numPoints; i++) {
Vector3r goal = cm + R * (x0[i] - restCm);
corr[i] = (goal - x[i]) * stiffness;
}
if (rot)
*rot = R;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::init_StrainTriangleConstraint(
const Vector3r &p0,
const Vector3r &p1,
const Vector3r &p2,
Matrix2r &invRestMat)
{
Real a = p1[0] - p0[0]; Real b = p2[0] - p0[0];
Real c = p1[1] - p0[1]; Real d = p2[1] - p0[1];
// inverse
Real det = a*d - b*c;
if (fabs(det) < eps)
return false;
Real s = 1.0 / det;
invRestMat(0,0) = d*s; invRestMat(0,1) = -b*s;
invRestMat(1,0) = -c*s; invRestMat(1,1) = a*s;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_StrainTriangleConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Matrix2r &invRestMat,
const Real xxStiffness,
const Real yyStiffness,
const Real xyStiffness,
const bool normalizeStretch,
const bool normalizeShear,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2)
{
Vector3r c[2];
c[0] = Vector3r(invRestMat(0, 0), invRestMat(1, 0), 0.0);
c[1] = Vector3r(invRestMat(0, 1), invRestMat(1, 1), 0.0);
Vector3r r[3];
corr0.setZero();
corr1.setZero();
corr2.setZero();
for (int i = 0; i < 2; i++) {
for (int j = 0; j <= i; j++) {
// r[0] = Vector3r(p1[0] - p0[0], p2[0] - p0[0], 0.0); // Jacobi
// r[1] = Vector3r(p1[1] - p0[1], p2[1] - p0[1], 0.0);
// r[2] = Vector3r(p1[2] - p0[2], p2[2] - p0[2], 0.0);
r[0] = Vector3r((p1[0] + corr1[0]) - (p0[0] + corr0[0]), (p2[0] + corr2[0]) - (p0[0] + corr0[0]), 0.0); // Gauss - Seidel
r[1] = Vector3r((p1[1] + corr1[1]) - (p0[1] + corr0[1]), (p2[1] + corr2[1]) - (p0[1] + corr0[1]), 0.0);
r[2] = Vector3r((p1[2] + corr1[2]) - (p0[2] + corr0[2]), (p2[2] + corr2[2]) - (p0[2] + corr0[2]), 0.0);
Real Sij = 0.0;
for (int k = 0; k < 3; k++)
Sij += r[k].dot(c[i]) * r[k].dot(c[j]);
Vector3r d[3];
d[0] = Vector3r(0.0, 0.0, 0.0);
for (int k = 0; k < 2; k++) {
d[k+1] = Vector3r(r[0].dot(c[j]), r[1].dot(c[j]), r[2].dot(c[j])) * invRestMat(k, i);
d[k+1] += Vector3r(r[0].dot(c[i]), r[1].dot(c[i]), r[2].dot(c[i])) * invRestMat(k, j);
d[0] -= d[k+1];
}
if (i != j && normalizeShear) {
Real fi2 = 0.0;
Real fj2 = 0.0;
for (int k = 0; k < 3; k++) {
fi2 += r[k].dot(c[i]) * r[k].dot(c[i]);
fj2 += r[k].dot(c[j]) * r[k].dot(c[j]);
}
Real fi = sqrt(fi2);
Real fj = sqrt(fj2);
d[0] = Vector3r(0.0, 0.0, 0.0);
Real s = Sij / (fi2*fi*fj2*fj);
for (int k = 0; k < 2; k++) {
d[k+1] /= fi * fj;
d[k+1] -= fj*fj * Vector3r(r[0].dot(c[i]), r[1].dot(c[i]), r[2].dot(c[i])) * invRestMat(k, i) * s;
d[k+1] -= fi*fi * Vector3r(r[0].dot(c[j]), r[1].dot(c[j]), r[2].dot(c[j])) * invRestMat(k, j) * s;
d[0] -= d[k+1];
}
Sij = Sij / (fi * fj);
}
Real lambda =
invMass0 * d[0].squaredNorm() +
invMass1 * d[1].squaredNorm() +
invMass2 * d[2].squaredNorm();
if (lambda == 0.0)
continue;
if (i == 0 && j == 0) {
if (normalizeStretch) {
Real s = sqrt(Sij);
lambda = 2.0 * s * (s - 1.0) / lambda * xxStiffness;
}
else {
lambda = (Sij - 1.0) / lambda * xxStiffness;
}
}
else if (i == 1 && j == 1) {
if (normalizeStretch) {
Real s = sqrt(Sij);
lambda = 2.0 * s * (s - 1.0) / lambda * yyStiffness;
}
else {
lambda = (Sij - 1.0) / lambda * yyStiffness;
}
}
else {
lambda = Sij / lambda * xyStiffness;
}
corr0 -= lambda * invMass0 * d[0];
corr1 -= lambda * invMass1 * d[1];
corr2 -= lambda * invMass2 * d[2];
}
}
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::init_StrainTetraConstraint(
const Vector3r &p0,
const Vector3r &p1,
const Vector3r &p2,
const Vector3r &p3,
Matrix3r &invRestMat)
{
Matrix3r m;
m.col(0) = p1 - p0;
m.col(1) = p2 - p0;
m.col(2) = p3 - p0;
Real det = m.determinant();
if (fabs(det) > eps)
{
invRestMat = m.inverse();
return true;
}
return false;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_StrainTetraConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Vector3r &p3, Real invMass3,
const Matrix3r &invRestMat,
const Vector3r &stretchStiffness,
const Vector3r &shearStiffness,
const bool normalizeStretch,
const bool normalizeShear,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2, Vector3r &corr3)
{
corr0.setZero();
corr1.setZero();
corr2.setZero();
corr3.setZero();
Vector3r c[3];
c[0] = invRestMat.col(0);
c[1] = invRestMat.col(1);
c[2] = invRestMat.col(2);
for (int i = 0; i < 3; i++) {
for (int j = 0; j <= i; j++) {
Matrix3r P;
// P.col(0) = p1 - p0; // Jacobi
// P.col(1) = p2 - p0;
// P.col(2) = p3 - p0;
P.col(0) = (p1 + corr1) - (p0 + corr0); // Gauss - Seidel
P.col(1) = (p2 + corr2) - (p0 + corr0);
P.col(2) = (p3 + corr3) - (p0 + corr0);
Vector3r fi = P * c[i];
Vector3r fj = P * c[j];
Real Sij = fi.dot(fj);
Real wi,wj,s1,s3;
if (normalizeShear && i != j) {
wi = fi.norm();
wj = fj.norm();
s1 = 1.0 / (wi*wj);
s3 = s1 * s1 * s1;
}
Vector3r d[4];
d[0] = Vector3r(0.0, 0.0, 0.0);
for (int k = 0; k < 3; k++) {
d[k+1] = fj * invRestMat(k,i) + fi * invRestMat(k,j);
if (normalizeShear && i != j) {
d[k+1] = s1 * d[k+1] - Sij*s3 * (wj*wj * fi*invRestMat(k,i) + wi*wi * fj*invRestMat(k,j));
}
d[0] -= d[k+1];
}
if (normalizeShear && i != j)
Sij *= s1;
Real lambda =
invMass0 * d[0].squaredNorm() +
invMass1 * d[1].squaredNorm() +
invMass2 * d[2].squaredNorm() +
invMass3 * d[3].squaredNorm();
if (fabs(lambda) < eps) // foo: threshold should be scale dependent
continue;
if (i == j) { // diagonal, stretch
if (normalizeStretch) {
Real s = sqrt(Sij);
lambda = 2.0 * s * (s - 1.0) / lambda * stretchStiffness[i];
}
else {
lambda = (Sij - 1.0) / lambda * stretchStiffness[i];
}
}
else { // off diagonal, shear
lambda = Sij / lambda * shearStiffness[i + j - 1];
}
corr0 -= lambda * invMass0 * d[0];
corr1 -= lambda * invMass1 * d[1];
corr2 -= lambda * invMass2 * d[2];
corr3 -= lambda * invMass3 * d[3];
}
}
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::init_FEMTriangleConstraint(
const Vector3r &p0,
const Vector3r &p1,
const Vector3r &p2,
Real &area,
Matrix2r &invRestMat)
{
Vector3r normal0 = (p1 - p0).cross(p2 - p0);
area = normal0.norm() * 0.5;
Vector3r axis0_1 = p1 - p0;
axis0_1.normalize();
Vector3r axis0_2 = normal0.cross(axis0_1);
axis0_2.normalize();
Vector2r p[3];
p[0] = Vector2r(p0.dot(axis0_2), p0.dot(axis0_1));
p[1] = Vector2r(p1.dot(axis0_2), p1.dot(axis0_1));
p[2] = Vector2r(p2.dot(axis0_2), p2.dot(axis0_1));
Matrix2r P;
P(0, 0) = p[0][0] - p[2][0];
P(1, 0) = p[0][1] - p[2][1];
P(0, 1) = p[1][0] - p[2][0];
P(1, 1) = p[1][1] - p[2][1];
const Real det = P.determinant();
if (fabs(det) > eps)
{
invRestMat = P.inverse();
return true;
}
return false;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_FEMTriangleConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Real &area,
const Matrix2r &invRestMat,
const Real youngsModulusX,
const Real youngsModulusY,
const Real youngsModulusShear,
const Real poissonRatioXY,
const Real poissonRatioYX,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2)
{
// Orthotropic elasticity tensor
Matrix3r C;
C.setZero();
C(0, 0) = youngsModulusX / (1.0 - poissonRatioXY*poissonRatioYX);
C(0, 1) = youngsModulusX*poissonRatioYX / (1.0 - poissonRatioXY*poissonRatioYX);
C(1, 1) = youngsModulusY / (1.0 - poissonRatioXY*poissonRatioYX);
C(1, 0) = youngsModulusY*poissonRatioXY / (1.0 - poissonRatioXY*poissonRatioYX);
C(2, 2) = youngsModulusShear;
// Determine \partial x/\partial m_i
Eigen::Matrix<Real, 3, 2> F;
const Vector3r p13 = p0 - p2;
const Vector3r p23 = p1 - p2;
F(0,0) = p13[0] * invRestMat(0,0) + p23[0] * invRestMat(1,0);
F(0,1) = p13[0] * invRestMat(0,1) + p23[0] * invRestMat(1,1);
F(1,0) = p13[1] * invRestMat(0,0) + p23[1] * invRestMat(1,0);
F(1,1) = p13[1] * invRestMat(0,1) + p23[1] * invRestMat(1,1);
F(2,0) = p13[2] * invRestMat(0,0) + p23[2] * invRestMat(1,0);
F(2,1) = p13[2] * invRestMat(0,1) + p23[2] * invRestMat(1,1);
// epsilon = 0.5(F^T * F - I)
Matrix2r epsilon;
epsilon(0,0) = 0.5*(F(0,0) * F(0,0) + F(1,0) * F(1,0) + F(2,0) * F(2,0) - 1.0); // xx
epsilon(1,1) = 0.5*(F(0,1) * F(0,1) + F(1,1) * F(1,1) + F(2,1) * F(2,1) - 1.0); // yy
epsilon(0,1) = 0.5*(F(0,0) * F(0,1) + F(1,0) * F(1,1) + F(2,0) * F(2,1)); // xy
epsilon(1,0) = epsilon(0,1);
// P(F) = det(F) * C*E * F^-T => E = green strain
Matrix2r stress;
stress(0,0) = C(0,0) * epsilon(0,0) + C(0,1) * epsilon(1,1) + C(0,2) * epsilon(0,1);
stress(1,1) = C(1,0) * epsilon(0,0) + C(1,1) * epsilon(1,1) + C(1,2) * epsilon(0,1);
stress(0,1) = C(2,0) * epsilon(0,0) + C(2,1) * epsilon(1,1) + C(2,2) * epsilon(0,1);
stress(1,0) = stress(0,1);
const Eigen::Matrix<Real, 3, 2> piolaKirchhoffStres = F * stress;
Real psi = 0.0;
for (unsigned char j = 0; j < 2; j++)
for (unsigned char k = 0; k < 2; k++)
psi += epsilon(j,k) * stress(j,k);
psi = 0.5*psi;
Real energy = area*psi;
// compute gradient
Eigen::Matrix<Real, 3, 2> H = area * piolaKirchhoffStres * invRestMat.transpose();
Vector3r gradC[3];
for (unsigned char j = 0; j < 3; ++j)
{
gradC[0][j] = H(j,0);
gradC[1][j] = H(j,1);
}
gradC[2] = -gradC[0] - gradC[1];
Real sum_normGradC = invMass0 * gradC[0].squaredNorm();
sum_normGradC += invMass1 * gradC[1].squaredNorm();
sum_normGradC += invMass2 * gradC[2].squaredNorm();
// exit early if required
if (fabs(sum_normGradC) > eps)
{
// compute scaling factor
const Real s = energy / sum_normGradC;
// update positions
corr0 = -(s*invMass0) * gradC[0];
corr1 = -(s*invMass1) * gradC[1];
corr2 = -(s*invMass2) * gradC[2];
return true;
}
return false;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::init_FEMTetraConstraint( // compute only when rest shape changes
const Vector3r &p0,
const Vector3r &p1,
const Vector3r &p2,
const Vector3r &p3,
Real &volume,
Matrix3r &invRestMat)
{
volume = fabs((1.0 / 6.0) * (p3 - p0).dot((p2 - p0).cross(p1 - p0)));
Matrix3r m;
m.col(0) = p0 - p3;
m.col(1) = p1 - p3;
m.col(2) = p2 - p3;
Real det = m.determinant();
if (fabs(det) > eps)
{
invRestMat = m.inverse();
return true;
}
return false;
}
// ----------------------------------------------------------------------------------------------
void PositionBasedDynamics::computeGreenStrainAndPiolaStress(
const Vector3r &x1, const Vector3r &x2, const Vector3r &x3, const Vector3r &x4,
const Matrix3r &invRestMat,
const Real restVolume,
const Real mu, const Real lambda, Matrix3r &epsilon, Matrix3r &sigma, Real &energy)
{
// Determine \partial x/\partial m_i
Matrix3r F;
const Vector3r p14 = x1 - x4;
const Vector3r p24 = x2 - x4;
const Vector3r p34 = x3 - x4;
F(0, 0) = p14[0]*invRestMat(0, 0) + p24[0]*invRestMat(1, 0) + p34[0]*invRestMat(2, 0);
F(0, 1) = p14[0]*invRestMat(0, 1) + p24[0]*invRestMat(1, 1) + p34[0]*invRestMat(2, 1);
F(0, 2) = p14[0]*invRestMat(0, 2) + p24[0]*invRestMat(1, 2) + p34[0]*invRestMat(2, 2);
F(1, 0) = p14[1]*invRestMat(0, 0) + p24[1]*invRestMat(1, 0) + p34[1]*invRestMat(2, 0);
F(1, 1) = p14[1]*invRestMat(0, 1) + p24[1]*invRestMat(1, 1) + p34[1]*invRestMat(2, 1);
F(1, 2) = p14[1]*invRestMat(0, 2) + p24[1]*invRestMat(1, 2) + p34[1]*invRestMat(2, 2);
F(2, 0) = p14[2]*invRestMat(0, 0) + p24[2]*invRestMat(1, 0) + p34[2]*invRestMat(2, 0);
F(2, 1) = p14[2]*invRestMat(0, 1) + p24[2]*invRestMat(1, 1) + p34[2]*invRestMat(2, 1);
F(2, 2) = p14[2]*invRestMat(0, 2) + p24[2]*invRestMat(1, 2) + p34[2]*invRestMat(2, 2);
// epsilon = 1/2 F^T F - I
epsilon(0, 0) = 0.5*(F(0, 0) * F(0, 0) + F(1, 0) * F(1, 0) + F(2, 0) * F(2, 0) - 1.0); // xx
epsilon(1, 1) = 0.5*(F(0, 1) * F(0, 1) + F(1, 1) * F(1, 1) + F(2, 1) * F(2, 1) - 1.0); // yy
epsilon(2, 2) = 0.5*(F(0, 2) * F(0, 2) + F(1, 2) * F(1, 2) + F(2, 2) * F(2, 2) - 1.0); // zz
epsilon(0, 1) = 0.5*(F(0, 0) * F(0, 1) + F(1, 0) * F(1, 1) + F(2, 0) * F(2, 1)); // xy
epsilon(0, 2) = 0.5*(F(0, 0) * F(0, 2) + F(1, 0) * F(1, 2) + F(2, 0) * F(2, 2)); // xz
epsilon(1, 2) = 0.5*(F(0, 1) * F(0, 2) + F(1, 1) * F(1, 2) + F(2, 1) * F(2, 2)); // yz
epsilon(1, 0) = epsilon(0, 1);
epsilon(2, 0) = epsilon(0, 2);
epsilon(2, 1) = epsilon(1, 2);
// P(F) = F(2 mu E + lambda tr(E)I) => E = green strain
const Real trace = epsilon(0, 0) + epsilon(1, 1) + epsilon(2, 2);
const Real ltrace = lambda*trace;
sigma = epsilon * 2.0*mu;
sigma(0, 0) += ltrace;
sigma(1, 1) += ltrace;
sigma(2, 2) += ltrace;
sigma = F * sigma;
Real psi = 0.0;
for (unsigned char j = 0; j < 3; j++)
for (unsigned char k = 0; k < 3; k++)
psi += epsilon(j, k) * epsilon(j, k);
psi = mu*psi + 0.5*lambda * trace*trace;
energy = restVolume * psi;
}
// ----------------------------------------------------------------------------------------------
void PositionBasedDynamics::computeGradCGreen(Real restVolume, const Matrix3r &invRestMat, const Matrix3r &sigma, Vector3r *J)
{
Matrix3r H;
Matrix3r T;
T = invRestMat.transpose();
H = sigma * T * restVolume;
J[0][0] = H(0, 0);
J[1][0] = H(0, 1);
J[2][0] = H(0, 2);
J[0][1] = H(1, 0);
J[1][1] = H(1, 1);
J[2][1] = H(1, 2);
J[0][2] = H(2, 0);
J[1][2] = H(2, 1);
J[2][2] = H(2, 2);
J[3] = -J[0] - J[1] - J[2];
}
// ----------------------------------------------------------------------------------------------
void PositionBasedDynamics::computeGreenStrainAndPiolaStressInversion(
const Vector3r &x1, const Vector3r &x2, const Vector3r &x3, const Vector3r &x4,
const Matrix3r &invRestMat,
const Real restVolume,
const Real mu, const Real lambda, Matrix3r &epsilon, Matrix3r &sigma, Real &energy)
{
// Determine \partial x/\partial m_i
Matrix3r F;
const Vector3r p14 = x1 - x4;
const Vector3r p24 = x2 - x4;
const Vector3r p34 = x3 - x4;
F(0, 0) = p14[0]*invRestMat(0, 0) + p24[0]*invRestMat(1, 0) + p34[0]*invRestMat(2, 0);
F(0, 1) = p14[0]*invRestMat(0, 1) + p24[0]*invRestMat(1, 1) + p34[0]*invRestMat(2, 1);
F(0, 2) = p14[0]*invRestMat(0, 2) + p24[0]*invRestMat(1, 2) + p34[0]*invRestMat(2, 2);
F(1, 0) = p14[1]*invRestMat(0, 0) + p24[1]*invRestMat(1, 0) + p34[1]*invRestMat(2, 0);
F(1, 1) = p14[1]*invRestMat(0, 1) + p24[1]*invRestMat(1, 1) + p34[1]*invRestMat(2, 1);
F(1, 2) = p14[1]*invRestMat(0, 2) + p24[1]*invRestMat(1, 2) + p34[1]*invRestMat(2, 2);
F(2, 0) = p14[2]*invRestMat(0, 0) + p24[2]*invRestMat(1, 0) + p34[2]*invRestMat(2, 0);
F(2, 1) = p14[2]*invRestMat(0, 1) + p24[2]*invRestMat(1, 1) + p34[2]*invRestMat(2, 1);
F(2, 2) = p14[2]*invRestMat(0, 2) + p24[2]*invRestMat(1, 2) + p34[2]*invRestMat(2, 2);
Matrix3r U, VT;
Vector3r hatF;
MathFunctions::svdWithInversionHandling(F, hatF, U, VT);
// Clamp small singular values
const Real minXVal = 0.577;
for (unsigned char j = 0; j < 3; j++)
{
if (hatF[j] < minXVal)
hatF[j] = minXVal;
}
// epsilon for hatF
Vector3r epsilonHatF(0.5*(hatF[0]*hatF[0] - 1.0), 0.5*(hatF[1]*hatF[1] - 1.0), 0.5*(hatF[2]*hatF[2] - 1.0));
const Real trace = epsilonHatF[0] + epsilonHatF[1] + epsilonHatF[2];
const Real ltrace = lambda*trace;
Vector3r sigmaVec = epsilonHatF * 2.0*mu;
sigmaVec[0] += ltrace;
sigmaVec[1] += ltrace;
sigmaVec[2] += ltrace;
sigmaVec[0] = hatF[0] * sigmaVec[0];
sigmaVec[1] = hatF[1] * sigmaVec[1];
sigmaVec[2] = hatF[2] * sigmaVec[2];
Matrix3r sigmaDiag, epsDiag;
sigmaDiag.row(0) = Vector3r(sigmaVec[0], 0.0, 0.0);
sigmaDiag.row(1) = Vector3r(0.0, sigmaVec[1], 0.0);
sigmaDiag.row(2) = Vector3r(0.0, 0.0, sigmaVec[2]);
epsDiag.row(0) = Vector3r(epsilonHatF[0], 0.0, 0.0);
epsDiag.row(1) = Vector3r(0.0, epsilonHatF[1], 0.0);
epsDiag.row(2) = Vector3r(0.0, 0.0, epsilonHatF[2]);
epsilon = U*epsDiag*VT;
sigma = U*sigmaDiag*VT;
Real psi = 0.0;
for (unsigned char j = 0; j < 3; j++)
for (unsigned char k = 0; k < 3; k++)
psi += epsilon(j, k) * epsilon(j, k);
psi = mu*psi + 0.5*lambda * trace*trace;
energy = restVolume*psi;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedDynamics::solve_FEMTetraConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Vector3r &p3, Real invMass3,
const Real restVolume,
const Matrix3r &invRestMat,
const Real youngsModulus,
const Real poissonRatio,
const bool handleInversion,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2, Vector3r &corr3)
{
corr0.setZero();
corr1.setZero();
corr2.setZero();
corr3.setZero();
if (youngsModulus <= 0.0)
return true;
if (poissonRatio < 0.0 || poissonRatio > 0.49)
return false;
Real C = 0.0;
Vector3r gradC[4];
Matrix3r epsilon, sigma;
Real volume = (p1 - p0).cross(p2 - p0).dot(p3 - p0) / 6.0;
Real mu = youngsModulus / 2.0 / (1.0 + poissonRatio);
Real lambda = youngsModulus * poissonRatio / (1.0 + poissonRatio) / (1.0 - 2.0 * poissonRatio);
if (!handleInversion || volume > 0.0)
{
computeGreenStrainAndPiolaStress(p0, p1, p2, p3, invRestMat, restVolume, mu, lambda, epsilon, sigma, C);
computeGradCGreen(restVolume, invRestMat, sigma, gradC);
}
else
{
computeGreenStrainAndPiolaStressInversion(p0, p1, p2, p3, invRestMat, restVolume, mu, lambda, epsilon, sigma, C);
computeGradCGreen(restVolume, invRestMat, sigma, gradC);
}
Real sum_normGradC =
invMass0 * gradC[0].squaredNorm() +
invMass1 * gradC[1].squaredNorm() +
invMass2 * gradC[2].squaredNorm() +
invMass3 * gradC[3].squaredNorm();
if (sum_normGradC < eps)
return false;
// compute scaling factor
const Real s = C / sum_normGradC;
corr0 = -s * invMass0 * gradC[0];
corr1 = -s * invMass1 * gradC[1];
corr2 = -s * invMass2 * gradC[2];
corr3 = -s * invMass3 * gradC[3];
return true;
}
| 27.869114
| 126
| 0.557646
|
aibel18
|
6dc3b97fc98bac5991bc99ad8a0ec2f5fb49176b
| 7,083
|
cpp
|
C++
|
llvm/lib/Target/TargetMachine.cpp
|
zard49/kokkos-clang
|
c519a032853e6507075de1807c5730b8239ab936
|
[
"Unlicense"
] | 4
|
2015-10-21T05:51:05.000Z
|
2015-12-19T06:27:44.000Z
|
llvm/lib/Target/TargetMachine.cpp
|
losalamos/kokkos-clang
|
d68d9c63cea3dbaad33454e4ebc9df829bca24fe
|
[
"Unlicense"
] | null | null | null |
llvm/lib/Target/TargetMachine.cpp
|
losalamos/kokkos-clang
|
d68d9c63cea3dbaad33454e4ebc9df829bca24fe
|
[
"Unlicense"
] | 2
|
2019-11-16T19:03:05.000Z
|
2020-03-19T08:32:37.000Z
|
//===-- TargetMachine.cpp - General Target Information ---------------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the general parts of a Target machine.
//
//===----------------------------------------------------------------------===//
#include "llvm/Target/TargetMachine.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Mangler.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeGenInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
//---------------------------------------------------------------------------
// TargetMachine Class
//
TargetMachine::TargetMachine(const Target &T, StringRef DataLayoutString,
const Triple &TT, StringRef CPU, StringRef FS,
const TargetOptions &Options)
: TheTarget(T), DL(DataLayoutString), TargetTriple(TT), TargetCPU(CPU),
TargetFS(FS), CodeGenInfo(nullptr), AsmInfo(nullptr), MRI(nullptr),
MII(nullptr), STI(nullptr), RequireStructuredCFG(false),
Options(Options) {}
TargetMachine::~TargetMachine() {
delete CodeGenInfo;
delete AsmInfo;
delete MRI;
delete MII;
delete STI;
}
/// \brief Reset the target options based on the function's attributes.
// FIXME: This function needs to go away for a number of reasons:
// a) global state on the TargetMachine is terrible in general,
// b) there's no default state here to keep,
// c) these target options should be passed only on the function
// and not on the TargetMachine (via TargetOptions) at all.
void TargetMachine::resetTargetOptions(const Function &F) const {
#define RESET_OPTION(X, Y) \
do { \
if (F.hasFnAttribute(Y)) \
Options.X = (F.getFnAttribute(Y).getValueAsString() == "true"); \
} while (0)
RESET_OPTION(LessPreciseFPMADOption, "less-precise-fpmad");
RESET_OPTION(UnsafeFPMath, "unsafe-fp-math");
RESET_OPTION(NoInfsFPMath, "no-infs-fp-math");
RESET_OPTION(NoNaNsFPMath, "no-nans-fp-math");
}
/// getRelocationModel - Returns the code generation relocation model. The
/// choices are static, PIC, and dynamic-no-pic, and target default.
Reloc::Model TargetMachine::getRelocationModel() const {
if (!CodeGenInfo)
return Reloc::Default;
return CodeGenInfo->getRelocationModel();
}
/// getCodeModel - Returns the code model. The choices are small, kernel,
/// medium, large, and target default.
CodeModel::Model TargetMachine::getCodeModel() const {
if (!CodeGenInfo)
return CodeModel::Default;
return CodeGenInfo->getCodeModel();
}
/// Get the IR-specified TLS model for Var.
static TLSModel::Model getSelectedTLSModel(const GlobalValue *GV) {
switch (GV->getThreadLocalMode()) {
case GlobalVariable::NotThreadLocal:
llvm_unreachable("getSelectedTLSModel for non-TLS variable");
break;
case GlobalVariable::GeneralDynamicTLSModel:
return TLSModel::GeneralDynamic;
case GlobalVariable::LocalDynamicTLSModel:
return TLSModel::LocalDynamic;
case GlobalVariable::InitialExecTLSModel:
return TLSModel::InitialExec;
case GlobalVariable::LocalExecTLSModel:
return TLSModel::LocalExec;
}
llvm_unreachable("invalid TLS model");
}
TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
bool isLocal = GV->hasLocalLinkage();
bool isDeclaration = GV->isDeclaration();
bool isPIC = getRelocationModel() == Reloc::PIC_;
bool isPIE = Options.PositionIndependentExecutable;
// FIXME: what should we do for protected and internal visibility?
// For variables, is internal different from hidden?
bool isHidden = GV->hasHiddenVisibility();
TLSModel::Model Model;
if (isPIC && !isPIE) {
if (isLocal || isHidden)
Model = TLSModel::LocalDynamic;
else
Model = TLSModel::GeneralDynamic;
} else {
if (!isDeclaration || isHidden)
Model = TLSModel::LocalExec;
else
Model = TLSModel::InitialExec;
}
// If the user specified a more specific model, use that.
TLSModel::Model SelectedModel = getSelectedTLSModel(GV);
if (SelectedModel > Model)
return SelectedModel;
return Model;
}
/// getOptLevel - Returns the optimization level: None, Less,
/// Default, or Aggressive.
CodeGenOpt::Level TargetMachine::getOptLevel() const {
if (!CodeGenInfo)
return CodeGenOpt::Default;
return CodeGenInfo->getOptLevel();
}
void TargetMachine::setOptLevel(CodeGenOpt::Level Level) const {
if (CodeGenInfo)
CodeGenInfo->setOptLevel(Level);
}
TargetIRAnalysis TargetMachine::getTargetIRAnalysis() {
return TargetIRAnalysis([this](const Function &F) {
return TargetTransformInfo(F.getParent()->getDataLayout());
});
}
static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
const MCSection &Section) {
if (!AsmInfo.isSectionAtomizableBySymbols(Section))
return true;
// If it is not dead stripped, it is safe to use private labels.
const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
return true;
return false;
}
void TargetMachine::getNameWithPrefix(SmallVectorImpl<char> &Name,
const GlobalValue *GV, Mangler &Mang,
bool MayAlwaysUsePrivate) const {
if (MayAlwaysUsePrivate || !GV->hasPrivateLinkage()) {
// Simple case: If GV is not private, it is not important to find out if
// private labels are legal in this case or not.
Mang.getNameWithPrefix(Name, GV, false);
return;
}
SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, *this);
const TargetLoweringObjectFile *TLOF = getObjFileLowering();
const MCSection *TheSection = TLOF->SectionForGlobal(GV, GVKind, Mang, *this);
bool CannotUsePrivateLabel = !canUsePrivateLabel(*AsmInfo, *TheSection);
TLOF->getNameWithPrefix(Name, GV, CannotUsePrivateLabel, Mang, *this);
}
MCSymbol *TargetMachine::getSymbol(const GlobalValue *GV, Mangler &Mang) const {
SmallString<128> NameStr;
getNameWithPrefix(NameStr, GV, Mang);
const TargetLoweringObjectFile *TLOF = getObjFileLowering();
return TLOF->getContext().getOrCreateSymbol(NameStr);
}
| 36.699482
| 80
| 0.674855
|
zard49
|
6dc4ce01ed2ea3c35f40cd370fb3cc655894c600
| 579
|
hpp
|
C++
|
util/Qt/graph.hpp
|
hyjang/web10g-userland
|
a2e481e6c1513ceede34caf46cee5306c5495c3e
|
[
"MIT"
] | null | null | null |
util/Qt/graph.hpp
|
hyjang/web10g-userland
|
a2e481e6c1513ceede34caf46cee5306c5495c3e
|
[
"MIT"
] | null | null | null |
util/Qt/graph.hpp
|
hyjang/web10g-userland
|
a2e481e6c1513ceede34caf46cee5306c5495c3e
|
[
"MIT"
] | null | null | null |
#ifndef GRAPH_HPP
#define GRAPH_HPP
#include <QGraphicsItem>
#include <QSet>
class Graph : public QGraphicsItem
{
// Q_OBJECT
public:
explicit Graph(QRectF rectF, QGraphicsItem *parent=0);
QRectF boundingRect() const { return m_rectF; }
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option, QWidget *widget);
void clear();
void update_vars(qint32 var);
void update_vals();
protected:
QSet<int> vars;
QMap<quint32, QList<QVariant>> vals;
private:
void initialize();
QRectF m_rectF;
};
#endif // GRAPH_HPP
| 18.09375
| 65
| 0.690846
|
hyjang
|
6dd17cfb97d787d5d3d55c3c5bacb036538ad047
| 5,934
|
cpp
|
C++
|
tests/unit/queue/bounded_queue_fulness.cpp
|
simple555a/libcds
|
d05a0909402369d4a79eb82aed1742a7b227548b
|
[
"BSD-2-Clause"
] | null | null | null |
tests/unit/queue/bounded_queue_fulness.cpp
|
simple555a/libcds
|
d05a0909402369d4a79eb82aed1742a7b227548b
|
[
"BSD-2-Clause"
] | null | null | null |
tests/unit/queue/bounded_queue_fulness.cpp
|
simple555a/libcds
|
d05a0909402369d4a79eb82aed1742a7b227548b
|
[
"BSD-2-Clause"
] | 1
|
2020-02-01T15:18:59.000Z
|
2020-02-01T15:18:59.000Z
|
//$$CDS-header$$
#include "cppunit/thread.h"
#include "queue/queue_type.h"
#include "queue/queue_defs.h"
/*
Bounded queue test.
The test checks the behaviour of bounded queue when it is almost full.
Many algorithms says the queue is full when it is not, and vice versa.
*/
namespace queue {
#define TEST_BOUNDED( Q, V ) void Q() { test< Types<V>::Q >(); }
namespace ns_BoundedQueue_Fullness {
static size_t s_nThreadCount = 8;
static size_t s_nQueueSize = 1024;
static size_t s_nPassCount = 1000000;
}
using namespace ns_BoundedQueue_Fullness;
class VyukovMPMCCycleQueue_dyn_fair_ : public Types<size_t>::VyukovMPMCCycleQueue_dyn_ic
{
typedef Types<size_t>::VyukovMPMCCycleQueue_dyn_ic base_class;
public:
typedef base_class::value_type value_type;
VyukovMPMCCycleQueue_dyn_fair_()
: base_class()
{}
VyukovMPMCCycleQueue_dyn_fair_( size_t nCapacity )
: base_class( nCapacity )
{}
bool enqueue( value_type const& data )
{
bool ret;
do {
ret = base_class::enqueue( data );
} while ( !ret && size() != capacity() );
return ret;
}
bool push( value_type const& data )
{
return enqueue( data );
}
bool dequeue( value_type& dest )
{
bool ret;
do {
ret = base_class::dequeue( dest );
} while ( !ret && size() != capacity() );
return ret;
}
bool pop( value_type& dest )
{
return dequeue( dest );
}
size_t size() const { return base_class::size(); }
size_t capacity() const { return base_class::capacity(); }
};
class BoundedQueue_Fullness: public CppUnitMini::TestCase
{
template <class Queue>
class Thread: public CppUnitMini::TestThread
{
virtual TestThread * clone()
{
return new Thread( *this );
}
public:
Queue& m_Queue;
double m_fTime;
size_t m_nPushError;
size_t m_nPopError;
public:
Thread( CppUnitMini::ThreadPool& pool, Queue& q )
: CppUnitMini::TestThread( pool )
, m_Queue( q )
{}
Thread( Thread& src )
: CppUnitMini::TestThread( src )
, m_Queue( src.m_Queue )
{}
BoundedQueue_Fullness& getTest()
{
return reinterpret_cast<BoundedQueue_Fullness&>( m_Pool.m_Test );
}
virtual void init()
{
cds::threading::Manager::attachThread();
}
virtual void fini()
{
cds::threading::Manager::detachThread();
}
virtual void test()
{
m_fTime = m_Timer.duration();
m_nPushError = 0;
m_nPopError = 0;
for ( size_t i = 0; i < s_nPassCount; ++i ) {
if ( !m_Queue.push( i ))
++m_nPushError;
size_t item;
if ( !m_Queue.pop( item ))
++m_nPopError;
}
m_fTime = m_Timer.duration() - m_fTime;
}
};
protected:
template <class Queue>
void analyze( CppUnitMini::ThreadPool& pool, Queue& testQueue )
{
double fTime = 0;
size_t nPushError = 0;
size_t nPopError = 0;
for ( CppUnitMini::ThreadPool::iterator it = pool.begin(); it != pool.end(); ++it ) {
Thread<Queue> * pThread = reinterpret_cast<Thread<Queue> *>(*it);
fTime += pThread->m_fTime;
nPushError += pThread->m_nPushError;
nPopError += pThread->m_nPopError;
}
CPPUNIT_MSG( " Duration=" << (fTime / s_nThreadCount) );
CPPUNIT_MSG( " Errors: push=" << nPushError << ", pop=" << nPopError );
CPPUNIT_CHECK( !testQueue.empty());
CPPUNIT_CHECK( nPushError == 0 );
CPPUNIT_CHECK( nPopError == 0 );
}
template <class Queue>
void test()
{
Queue testQueue( s_nQueueSize );
CppUnitMini::ThreadPool pool( *this );
pool.add( new Thread<Queue>( pool, testQueue ), s_nThreadCount );
size_t nSize = testQueue.capacity() - s_nThreadCount;
for ( size_t i = 0; i < nSize; ++i )
testQueue.push( i );
CPPUNIT_MSG( " Thread count=" << s_nThreadCount << ", push/pop pairs=" << s_nPassCount
<< ", queue capacity=" << testQueue.capacity() << " ...");
pool.run();
analyze( pool, testQueue );
CPPUNIT_MSG( testQueue.statistics() );
}
void setUpParams( const CppUnitMini::TestCfg& cfg ) {
s_nThreadCount = cfg.getULong("ThreadCount", 8 );
s_nQueueSize = cfg.getULong("QueueSize", 1024 );
s_nPassCount = cfg.getULong( "PassCount", 1000000 );
}
protected:
CDSUNIT_DECLARE_TsigasCycleQueue( size_t )
CDSUNIT_DECLARE_VyukovMPMCCycleQueue( size_t )
void VyukovMPMCCycleQueue_dyn_fair()
{
test< VyukovMPMCCycleQueue_dyn_fair_ >();
}
CPPUNIT_TEST_SUITE( BoundedQueue_Fullness )
CDSUNIT_TEST_TsigasCycleQueue
CDSUNIT_TEST_VyukovMPMCCycleQueue
CPPUNIT_TEST( VyukovMPMCCycleQueue_dyn_fair_ ) \
CPPUNIT_TEST_SUITE_END();
};
} // namespace queue
CPPUNIT_TEST_SUITE_REGISTRATION(queue::BoundedQueue_Fullness );
| 31.231579
| 101
| 0.518874
|
simple555a
|
6de09fb1b04efbe15702b64c4ef720b0da7364d4
| 1,440
|
hh
|
C++
|
src/core/include/chase/representation/DataDeclaration.hh
|
chase-cps/chase
|
87db0754bf0eaa94beb10c355794b6d3c6d9e883
|
[
"BSD-3-Clause"
] | 4
|
2019-06-15T15:33:37.000Z
|
2022-02-10T19:10:50.000Z
|
src/core/include/chase/representation/DataDeclaration.hh
|
chase-cps/chase
|
87db0754bf0eaa94beb10c355794b6d3c6d9e883
|
[
"BSD-3-Clause"
] | null | null | null |
src/core/include/chase/representation/DataDeclaration.hh
|
chase-cps/chase
|
87db0754bf0eaa94beb10c355794b6d3c6d9e883
|
[
"BSD-3-Clause"
] | 3
|
2018-02-02T18:14:48.000Z
|
2021-01-31T12:18:25.000Z
|
/**
* @author <a href="mailto:michele.lora@univr.it">Michele Lora</a>
* @date 2019
* @copyright Copyright (c) 2019 by University of Verona.
* Copyright (c) 2019 by Singapore University of Technology and Design.
* All rights reserved.
* This project is released under the 3-Clause BSD License.
*
*/
#pragma once
#include "representation/Declaration.hh"
#include "representation/Type.hh"
namespace chase {
/// @brief Abstract class for all the object representing the declaration
/// of data. E.g., Variables and constants declarations.
class DataDeclaration : public Declaration
{
public:
/// @brief Constructor.
/// @param t Type of the declared object.
/// @param n Name of the declared object.
explicit DataDeclaration( Type * t = nullptr, Name * n = nullptr);
/// @brief Getter for the type.
/// @return The type of the declaration.
Type * getType();
/// @brief Setter for the type.
/// @param t The type of the declared object.
void setType( Type * t );
/// @brief Clone method.
/// @return Clone of the object.
DataDeclaration * clone() override = 0;
protected:
/// @brief The type of the object represented by the declaration.
Type * _type;
};
}
| 29.387755
| 84
| 0.577083
|
chase-cps
|
6de46b18834dae0b5f98af81a29cf82695c7f490
| 2,799
|
cpp
|
C++
|
ObjectIterator.cpp
|
deepdubey06/WMI
|
6cba31cf8ddc8fc3ad9767507690f6d11a9c3bb5
|
[
"MIT"
] | 49
|
2015-08-10T09:53:45.000Z
|
2021-05-31T23:12:56.000Z
|
ObjectIterator.cpp
|
deepdubey06/WMI
|
6cba31cf8ddc8fc3ad9767507690f6d11a9c3bb5
|
[
"MIT"
] | null | null | null |
ObjectIterator.cpp
|
deepdubey06/WMI
|
6cba31cf8ddc8fc3ad9767507690f6d11a9c3bb5
|
[
"MIT"
] | 22
|
2015-10-27T13:53:06.000Z
|
2021-12-01T07:36:03.000Z
|
////////////////////////////////////////////////////////////////////////////////
//! \file ObjectIterator.cpp
//! \brief The ObjectIterator class definition.
//! \author Chris Oldwood
#include "Common.hpp"
#include "ObjectIterator.hpp"
#include "Exception.hpp"
#include <Core/BadLogicException.hpp>
namespace WMI
{
////////////////////////////////////////////////////////////////////////////////
//! Constructor for the End iterator.
ObjectIterator::ObjectIterator()
: m_enumerator()
, m_connection()
, m_value()
{
}
////////////////////////////////////////////////////////////////////////////////
//! Constructor for the Begin iterator.
ObjectIterator::ObjectIterator(IEnumWbemClassObjectPtr enumerator, const Connection& connection)
: m_enumerator(enumerator)
, m_connection(connection)
, m_value()
{
increment();
}
////////////////////////////////////////////////////////////////////////////////
//! Destructor.
ObjectIterator::~ObjectIterator()
{
}
////////////////////////////////////////////////////////////////////////////////
//! Dereference operator.
const Object& ObjectIterator::operator*() const
{
if (m_value.get() == nullptr)
throw Core::BadLogicException(TXT("Attempted to dereference end iterator"));
return *m_value;
}
////////////////////////////////////////////////////////////////////////////////
//! Pointer-to-member operator.
const Object* ObjectIterator::operator->() const
{
if (m_value.get() == nullptr)
throw Core::BadLogicException(TXT("Attempted to dereference end iterator"));
return m_value.get();
}
////////////////////////////////////////////////////////////////////////////////
//! Compare to another iterator for equivalence.
bool ObjectIterator::equals(const ObjectIterator& rhs) const
{
// Comparing End iterators?
if (m_enumerator.get() == nullptr)
return (rhs.m_enumerator.get() == nullptr);
return (m_enumerator.get() == rhs.m_enumerator.get());
}
////////////////////////////////////////////////////////////////////////////////
//! Move the iterator forward.
void ObjectIterator::increment()
{
ASSERT(m_enumerator.get() != nullptr);
// Request the next item.
IWbemClassObjectPtr value;
ULONG avail = 0;
HRESULT result = m_enumerator->Next(WBEM_INFINITE, 1, AttachTo(value), &avail);
if (FAILED(result))
throw Exception(result, m_enumerator, TXT("Failed to advance the WMI object enumerator"));
// Continued enumeration?
if (avail != 0)
{
ASSERT(avail == 1);
m_value.reset(new Object(value, m_connection));
}
// End reached.
else
{
ASSERT(result == S_FALSE);
reset();
}
}
////////////////////////////////////////////////////////////////////////////////
//! Move the iterator to the End.
void ObjectIterator::reset()
{
m_value.reset();
m_enumerator.Release();
}
//namespace WMI
}
| 23.521008
| 96
| 0.526617
|
deepdubey06
|
6de6512a92705005368359d0102b3b8308562690
| 676
|
hpp
|
C++
|
CToC++/CToC++/Leetcode/LeetCodeSolution2.hpp
|
UCliwenbin/AlgorithmCPP
|
3cb4a6a9510682b5d4dc956826d263ab778a2a00
|
[
"MIT"
] | 1
|
2021-02-25T08:00:43.000Z
|
2021-02-25T08:00:43.000Z
|
CToC++/CToC++/Leetcode/LeetCodeSolution2.hpp
|
UCliwenbin/AlgorithmCPP
|
3cb4a6a9510682b5d4dc956826d263ab778a2a00
|
[
"MIT"
] | null | null | null |
CToC++/CToC++/Leetcode/LeetCodeSolution2.hpp
|
UCliwenbin/AlgorithmCPP
|
3cb4a6a9510682b5d4dc956826d263ab778a2a00
|
[
"MIT"
] | null | null | null |
//
// LeetCodeSolution2.hpp
// CToC++
//
// Created by mac on 2020/7/6.
// Copyright © 2020 lwb. All rights reserved.
//
#ifndef LeetCodeSolution2_hpp
#define LeetCodeSolution2_hpp
#include <stdio.h>
#include "ListNode.hpp"
/**
给出两个 非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
};
#endif /* LeetCodeSolution2_hpp */
| 19.314286
| 100
| 0.692308
|
UCliwenbin
|
6de770809fe62cf2b6799d2c699f1a31c2a75a49
| 660
|
cpp
|
C++
|
c++/day10/39.cpp
|
msoild/sword-to-offer
|
6c15c78ad773da0b66cb76c9e01292851aca45c5
|
[
"MIT"
] | null | null | null |
c++/day10/39.cpp
|
msoild/sword-to-offer
|
6c15c78ad773da0b66cb76c9e01292851aca45c5
|
[
"MIT"
] | null | null | null |
c++/day10/39.cpp
|
msoild/sword-to-offer
|
6c15c78ad773da0b66cb76c9e01292851aca45c5
|
[
"MIT"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//空树 也是对称的
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == nullptr) return true;
return dfs(root->right, root->left);
}
bool dfs(TreeNode* pR, TreeNode* pL)
{
if(pR ==nullptr && pL == nullptr) return true;
if(pR == nullptr || pL == nullptr) return false; //有一个为空指针
return (pR->val == pL->val) && dfs(pL->left, pR->right) && dfs(pL->right, pR->left);
}
};
| 24.444444
| 92
| 0.531818
|
msoild
|
6de958529b324b639289d323abbd81ce003610f6
| 29,040
|
cpp
|
C++
|
clicache/src/TypeRegistry.cpp
|
echobravopapa/geode-native
|
f35a0f89c3bb97d309b3c8f507af23d0f4fb2f19
|
[
"Apache-2.0"
] | null | null | null |
clicache/src/TypeRegistry.cpp
|
echobravopapa/geode-native
|
f35a0f89c3bb97d309b3c8f507af23d0f4fb2f19
|
[
"Apache-2.0"
] | null | null | null |
clicache/src/TypeRegistry.cpp
|
echobravopapa/geode-native
|
f35a0f89c3bb97d309b3c8f507af23d0f4fb2f19
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "begin_native.hpp"
#include <geode/Cache.hpp>
#include <geode/PoolManager.hpp>
#include "SerializationRegistry.hpp"
#include "CacheRegionHelper.hpp"
#include "end_native.hpp"
#include "TypeRegistry.hpp"
#include "impl/DelegateWrapper.hpp"
#include "DataOutput.hpp"
#include "DataInput.hpp"
#include "CacheableStringArray.hpp"
#include "CacheableBuiltins.hpp"
#include "impl/SafeConvert.hpp"
#include "CacheableHashTable.hpp"
#include "Struct.hpp"
#include "CacheableUndefined.hpp"
#include "CacheableObject.hpp"
#include "CacheableStack.hpp"
#include "CacheableObjectXml.hpp"
#include "CacheableHashSet.hpp"
#include "CacheableObjectArray.hpp"
#include "CacheableLinkedList.hpp"
#include "CacheableFileName.hpp"
#include "CacheableIdentityHashMap.hpp"
#include "IPdxSerializer.hpp"
#include "impl/DotNetTypes.hpp"
#include "CacheRegionHelper.hpp"
#include "Cache.hpp"
#include "Properties.hpp"
using namespace apache::geode::client;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
namespace Apache
{
namespace Geode
{
namespace Client
{
namespace native = apache::geode::client;
String^ TypeRegistry::GetPdxTypeName(String^ localTypeName)
{
if (pdxTypeMapper == nullptr)
{
return localTypeName;
}
String^ pdxTypeName;
if (localTypeNameToPdx->TryGetValue(localTypeName, pdxTypeName)) {
return pdxTypeName;
}
pdxTypeName = pdxTypeMapper->ToPdxTypeName(localTypeName);
if (pdxTypeName == nullptr)
{
throw gcnew IllegalStateException("PdxTypeName should not be null for local type " + localTypeName);
}
localTypeNameToPdx[localTypeName] = pdxTypeName;
pdxTypeNameToLocal[pdxTypeName] = localTypeName;
return pdxTypeName;
}
String^ TypeRegistry::GetLocalTypeName(String^ pdxTypeName)
{
if (pdxTypeMapper == nullptr)
{
return pdxTypeName;
}
String^ localTypeName;
if (pdxTypeNameToLocal->TryGetValue(pdxTypeName, localTypeName))
{
return localTypeName;
}
localTypeName = pdxTypeMapper->FromPdxTypeName(pdxTypeName);
if (localTypeName == nullptr)
{
throw gcnew IllegalStateException("LocalTypeName should not be null for pdx type " + pdxTypeName);
}
localTypeNameToPdx[localTypeName] = pdxTypeName;
pdxTypeNameToLocal[pdxTypeName] = localTypeName;
return localTypeName;
}
Type^ TypeRegistry::GetType(String^ className)
{
Type^ type = nullptr;
if (classNameVsType->TryGetValue(className, type)) {
return type;
}
auto referedAssembly = gcnew Dictionary<Assembly^, bool>();
auto MyDomain = AppDomain::CurrentDomain;
array<Assembly^>^ AssembliesLoaded = MyDomain->GetAssemblies();
for each(Assembly^ assembly in AssembliesLoaded)
{
type = GetTypeFromRefrencedAssemblies(className, referedAssembly, assembly);
if (type) {
classNameVsType[className] = type;
return type;
}
}
return type;
}
void TypeRegistry::RegisterPdxType(PdxTypeFactoryMethod^ creationMethod)
{
if (creationMethod == nullptr) {
throw gcnew IllegalArgumentException("Serializable.RegisterPdxType(): "
"null PdxTypeFactoryMethod delegate passed");
}
IPdxSerializable^ obj = creationMethod();
PdxDelegateMap[obj->GetType()->FullName] = creationMethod;
Log::Debug("RegisterPdxType: class registered: " + obj->GetType()->FullName);
}
IPdxSerializable^ TypeRegistry::GetPdxType(String^ className)
{
PdxTypeFactoryMethod^ retVal = nullptr;
if (!PdxDelegateMap->TryGetValue(className, retVal))
{
if (pdxSerializer != nullptr)
{
return gcnew PdxWrapper(className);
}
try
{
Object^ retObj = CreateObject(className);
IPdxSerializable^ retPdx = dynamic_cast<IPdxSerializable^>(retObj);
if (retPdx != nullptr)
{
return retPdx;
}
}
catch (System::Exception^ ex)
{
Log::Error("Unable to create object using reflection for class: " + className + " : " + ex->Message);
}
throw gcnew IllegalStateException("Pdx factory method (or PdxSerializer ) not registered (or don't have zero arg constructor)"
" to create default instance for class: " + className);
}
return retVal();
}
void TypeRegistry::RegisterType(TypeFactoryMethod^ creationMethod)
{
if (creationMethod == nullptr) {
throw gcnew IllegalArgumentException("Serializable.RegisterType(): "
"null TypeFactoryMethod delegate passed");
}
//--------------------------------------------------------------
int32_t classId;
//adding user type as well in global builtin hashmap
auto obj = creationMethod();
if (auto dataSerializable = dynamic_cast<IDataSerializable^>(obj))
{
classId = dataSerializable->ClassId;
} else
{
throw gcnew IllegalArgumentException("Unknown serialization type.");
}
if (!ManagedDelegatesGeneric->ContainsKey(classId))
{
ManagedDelegatesGeneric->Add(classId, creationMethod);
}
auto delegateObj = gcnew DelegateWrapperGeneric(creationMethod);
auto nativeDelegate = gcnew TypeFactoryNativeMethodGeneric(delegateObj,
&DelegateWrapperGeneric::NativeDelegateGeneric);
// this is avoid object being Gced
NativeDelegatesGeneric->Add(nativeDelegate);
// register the type in the DelegateMap, this is pure c# for create domain object
Log::Fine("Registering serializable class ID " + classId);
DelegateMapGeneric[classId] = creationMethod;
_GF_MG_EXCEPTION_TRY2
auto&& nativeTypeRegistry = CacheRegionHelper::getCacheImpl(m_cache->GetNative().get())->getSerializationRegistry();
auto nativeDelegateFunction = static_cast<std::shared_ptr<native::Serializable>(*)()>(
System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(nativeDelegate).ToPointer());
nativeTypeRegistry->addType(nativeDelegateFunction);
_GF_MG_EXCEPTION_CATCH_ALL2
}
void TypeRegistry::RegisterDataSerializablePrimitiveOverrideNativeDeserialization(
int8_t dsCode, TypeFactoryMethod^ creationMethod, Type^ managedType)
{
if (creationMethod == nullptr) {
throw gcnew IllegalArgumentException("Serializable.RegisterType(): ");
}
auto delegateObj = gcnew DelegateWrapperGeneric(creationMethod);
auto nativeDelegate = gcnew TypeFactoryNativeMethodGeneric(delegateObj,
&DelegateWrapperGeneric::NativeDelegateGeneric);
DsCodeToDataSerializablePrimitiveTypeFactoryMethod[dsCode] = creationMethod;
DsCodeToDataSerializablePrimitiveNativeDelegate[dsCode] = nativeDelegate;
if (managedType != nullptr)
{
ManagedTypeToDsCode[managedType] = dsCode;
}
_GF_MG_EXCEPTION_TRY2
auto&& serializationRegistry = CacheRegionHelper::getCacheImpl(m_cache->GetNative().get())->getSerializationRegistry();
auto nativeDelegateFunction = static_cast<std::shared_ptr<native::Serializable>(*)()>(
System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(nativeDelegate).ToPointer());
serializationRegistry->addType(dsCode, nativeDelegateFunction);
_GF_MG_EXCEPTION_CATCH_ALL2
}
void TypeRegistry::RegisterDataSerializableFixedIdTypeOverrideNativeDeserialization(
Int32 fixedId, TypeFactoryMethod^ creationMethod)
{
if (creationMethod == nullptr) {
throw gcnew IllegalArgumentException("Serializable.RegisterType(): ");
}
auto delegateObj = gcnew DelegateWrapperGeneric(creationMethod);
auto nativeDelegate = gcnew TypeFactoryNativeMethodGeneric(delegateObj,
&DelegateWrapperGeneric::NativeDelegateGeneric);
FixedIdToDataSerializableFixedIdTypeFactoryMethod[fixedId] = creationMethod;
FixedIdToDataSerializableFixedIdNativeDelegate[fixedId] = nativeDelegate;
Log::Finer("Registering serializable fixed ID " + fixedId);
_GF_MG_EXCEPTION_TRY2
auto&& serializationRegistry = CacheRegionHelper::getCacheImpl(m_cache->GetNative().get())->getSerializationRegistry();
auto nativeDelegateFunction = static_cast<std::shared_ptr<native::Serializable>(*)()>(
System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(nativeDelegate).ToPointer());
serializationRegistry->addType2(fixedId, nativeDelegateFunction);
_GF_MG_EXCEPTION_CATCH_ALL2
}
void TypeRegistry::UnregisterTypeGeneric(Byte typeId)
{
DsCodeToDataSerializablePrimitiveNativeDelegate->Remove(typeId);
_GF_MG_EXCEPTION_TRY2
CacheRegionHelper::getCacheImpl(m_cache->GetNative().get())->getSerializationRegistry()->removeType(typeId);
_GF_MG_EXCEPTION_CATCH_ALL2
}
void TypeRegistry::RegisterDataSerializablePrimitiveWrapper(
DataSerializablePrimitiveWrapperDelegate^ wrapperMethod,
int8_t dsCode, System::Type^ managedType)
{
DsCodeToDataSerializablePrimitiveWrapperDelegate[dsCode] = wrapperMethod;
}
void TypeRegistry::UnregisterNativesGeneric(Cache^ cache)
{
cache->TypeRegistry->DsCodeToDataSerializablePrimitiveNativeDelegate->Clear();
}
Type^ TypeRegistry::GetTypeFromRefrencedAssemblies(String^ className, Dictionary<Assembly^, bool>^ referedAssembly, Assembly^ currentAssembly)
{
auto type = currentAssembly->GetType(className);
if (type != nullptr)
{
return type;
}
if (referedAssembly->ContainsKey(currentAssembly))
return nullptr;
referedAssembly[currentAssembly] = true;
//get all refrenced assembly
array<AssemblyName^>^ ReferencedAssemblies = currentAssembly->GetReferencedAssemblies();
for each(AssemblyName^ assembly in ReferencedAssemblies)
{
try
{
Assembly^ loadedAssembly = Assembly::Load(assembly);
if (loadedAssembly != nullptr && (!referedAssembly->ContainsKey(loadedAssembly)))
{
type = GetTypeFromRefrencedAssemblies(className, referedAssembly, loadedAssembly);
if (!type) {
return type;
}
}
}
catch (System::Exception^){//ignore
}
}
return nullptr;
}
generic<class TValue>
TValue wrap(std::shared_ptr<native::DataSerializablePrimitive> dataSerializablePrimitive)
{
switch (dataSerializablePrimitive->getDsCode())
{
case native::GeodeTypeIds::CacheableDate:
{
auto ret = SafeGenericUMSerializableConvert<CacheableDate^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableBytes:
{
auto ret = SafeGenericUMSerializableConvert<CacheableBytes^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableDoubleArray:
{
auto ret = SafeGenericUMSerializableConvert<CacheableDoubleArray^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableFloatArray:
{
auto ret = SafeGenericUMSerializableConvert<CacheableFloatArray^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableInt16Array:
{
auto ret = SafeGenericUMSerializableConvert<CacheableInt16Array^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableInt32Array:
{
auto ret = SafeGenericUMSerializableConvert<CacheableInt32Array^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableInt64Array:
{
auto ret = SafeGenericUMSerializableConvert<CacheableInt64Array^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableStringArray:
{
auto ret = SafeGenericUMSerializableConvert<CacheableStringArray^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->GetValues());
}
case native::GeodeTypeIds::CacheableArrayList://Ilist generic
{
auto ret = SafeGenericUMSerializableConvert<CacheableArrayList^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableLinkedList://LinkedList generic
{
auto ret = SafeGenericUMSerializableConvert<CacheableLinkedList^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableHashTable://collection::hashtable
{
auto ret = SafeGenericUMSerializableConvert<CacheableHashTable^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableHashMap://generic dictionary
{
auto ret = SafeGenericUMSerializableConvert<CacheableHashMap^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableIdentityHashMap:
{
auto ret = SafeGenericUMSerializableConvert<CacheableIdentityHashMap^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableHashSet://no need of it, default case should work
{
auto ret = SafeGenericUMSerializableConvert<CacheableHashSet^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
case native::GeodeTypeIds::CacheableLinkedHashSet://no need of it, default case should work
{
auto ret = SafeGenericUMSerializableConvert<CacheableLinkedHashSet^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
case native::GeodeTypeIds::CacheableFileName:
{
auto ret = SafeGenericUMSerializableConvert<CacheableFileName^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
case native::GeodeTypeIds::CacheableObjectArray:
{
auto ret = SafeGenericUMSerializableConvert<CacheableObjectArray^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
case native::GeodeTypeIds::CacheableVector://collection::arraylist
{
auto ret = SafeGenericUMSerializableConvert<CacheableVector^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableUndefined:
{
auto ret = SafeGenericUMSerializableConvert<CacheableUndefined^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
case native::GeodeTypeIds::Struct:
{
return safe_cast<TValue>(Struct::Create(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableStack:
{
auto ret = SafeGenericUMSerializableConvert<CacheableStack^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CacheableManagedObject:
{
auto ret = SafeGenericUMSerializableConvert<CacheableObject^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
case native::GeodeTypeIds::CacheableManagedObjectXml:
{
auto ret = SafeGenericUMSerializableConvert<CacheableObjectXml^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
/*
case native::GeodeTypeIds::Properties: // TODO: replace with IDictionary<K, V>
{
auto ret = SafeGenericUMSerializableConvert<Properties<Object^, Object^>^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
*/
case native::GeodeTypeIds::BooleanArray:
{
auto ret = SafeGenericUMSerializableConvert<BooleanArray^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case native::GeodeTypeIds::CharArray:
{
auto ret = SafeGenericUMSerializableConvert<CharArray^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret->Value);
}
case 0://UserFunctionExecutionException unregistered
{
auto ret = SafeGenericUMSerializableConvert<UserFunctionExecutionException^>(dataSerializablePrimitive);
return safe_cast<TValue>(ret);
}
}
throw gcnew IllegalArgumentException("Unknown type");
}
generic<class TValue>
TValue TypeRegistry::GetManagedValueGeneric(std::shared_ptr<native::Serializable> val)
{
if (val == nullptr)
{
return TValue();
}
if (auto dataSerializablePrimitive = std::dynamic_pointer_cast<native::DataSerializablePrimitive>(val))
{
switch (dataSerializablePrimitive->getDsCode())
{
case native::GeodeTypeIds::CacheableByte:
{
return safe_cast<TValue>(Serializable::getByte(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableBoolean:
{
return safe_cast<TValue>(Serializable::getBoolean(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableCharacter:
{
return safe_cast<TValue>(Serializable::getChar(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableDouble:
{
return safe_cast<TValue>(Serializable::getDouble(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableASCIIString:
case native::GeodeTypeIds::CacheableASCIIStringHuge:
case native::GeodeTypeIds::CacheableString:
case native::GeodeTypeIds::CacheableStringHuge:
{
return safe_cast<TValue>(Serializable::getString(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableFloat:
{
return safe_cast<TValue>(Serializable::getFloat(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableInt16:
{
return safe_cast<TValue>(Serializable::getInt16(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableInt32:
{
return safe_cast<TValue>(Serializable::getInt32(dataSerializablePrimitive));
}
case native::GeodeTypeIds::CacheableInt64:
{
return safe_cast<TValue>(Serializable::getInt64(dataSerializablePrimitive));
}
default:
return wrap<TValue>(dataSerializablePrimitive);
}
}
else if (auto dataSerializableFixedId = std::dynamic_pointer_cast<native::DataSerializableFixedId>(val))
{
switch (dataSerializableFixedId->getDSFID())
{
case native::GeodeTypeIds::Struct:
{
return safe_cast<TValue>(Struct::Create(val));
}
case native::GeodeTypeIds::CacheableUndefined:
{
return safe_cast<TValue>(CacheableUndefined::Create());
}
default:
break;
}
}
else if (auto dataSerializable = std::dynamic_pointer_cast<native::DataSerializable>(val))
{
auto ret = SafeUMSerializableConvertGeneric(dataSerializable);
return safe_cast<TValue>(ret);
}
else if (auto pdxSerializable = std::dynamic_pointer_cast<native::PdxSerializable>(val))
{
auto ret = SafeUMSerializablePDXConvert(pdxSerializable);
if (auto pdxWrapper = dynamic_cast<PdxWrapper^>(ret))
{
return safe_cast<TValue>(pdxWrapper->GetObject());
}
return safe_cast<TValue>(ret);
}
else if (auto userFunctionExecutionException = std::dynamic_pointer_cast<native::UserFunctionExecutionException>(val))
{
return safe_cast<TValue>(gcnew UserFunctionExecutionException(userFunctionExecutionException));
}
else if (auto pdxManagedCacheableKey = std::dynamic_pointer_cast<native::PdxManagedCacheableKey>(val))
{
auto pdx = pdxManagedCacheableKey->ptr();
if (auto pdxWrapper = dynamic_cast<PdxWrapper^>(pdx))
{
return safe_cast<TValue>(pdxWrapper->GetObject());
}
return safe_cast<TValue>(pdx);
}
else
{
throw gcnew IllegalStateException("Unknown serialization type.");
}
throw gcnew System::Exception("not found typeid");
}
Object^ TypeRegistry::CreateObject(String^ className)
{
Object^ retVal = CreateObjectEx(className);
if (retVal == nullptr)
{
auto type = GetType(className);
if (type)
{
retVal = type->GetConstructor(Type::EmptyTypes)->Invoke(nullptr);
return retVal;
}
}
return retVal;
}
Object^ TypeRegistry::CreateObjectEx(String^ className)
{
CreateNewObjectDelegate^ del = nullptr;
Dictionary<String^, CreateNewObjectDelegate^>^ tmp = ClassNameVsCreateNewObjectDelegate;
tmp->TryGetValue(className, del);
if (del != nullptr)
{
return del();
}
auto type = GetType(className);
if (type)
{
msclr::lock lockInstance(ClassNameVsCreateNewObjectLockObj);
{
tmp = ClassNameVsCreateNewObjectDelegate;
tmp->TryGetValue(className, del);
if (del != nullptr)
return del();
del = CreateNewObjectDelegateF(type);
ClassNameVsCreateNewObjectDelegate[className] = del;
return del();
}
}
return nullptr;
}
Object^ TypeRegistry::GetArrayObject(String^ className, int length)
{
Object^ retArr = GetArrayObjectEx(className, length);
if (retArr == nullptr)
{
Type^ type = GetType(className);
if (type)
{
retArr = type->MakeArrayType()->GetConstructor(singleIntType)->Invoke(gcnew array<Object^>(1) { length });
return retArr;
}
}
return retArr;
}
Object^ TypeRegistry::GetArrayObjectEx(String^ className, int length)
{
CreateNewObjectArrayDelegate^ del = nullptr;
Dictionary<String^, CreateNewObjectArrayDelegate^>^ tmp = ClassNameVsCreateNewObjectArrayDelegate;
tmp->TryGetValue(className, del);
if (del != nullptr)
{
return del(length);
}
Type^ t = GetType(className);
if (t)
{
msclr::lock lockInstance(ClassNameVsCreateNewObjectLockObj);
{
tmp = ClassNameVsCreateNewObjectArrayDelegate;
tmp->TryGetValue(className, del);
if (del != nullptr)
return del(length);
del = CreateNewObjectArrayDelegateF(t);
tmp = gcnew Dictionary<String^, CreateNewObjectArrayDelegate^>(ClassNameVsCreateNewObjectArrayDelegate);
tmp[className] = del;
ClassNameVsCreateNewObjectArrayDelegate = tmp;
return del(length);
}
}
return nullptr;
}
//delegate Object^ CreateNewObject();
//static CreateNewObjectDelegate^ CreateNewObjectDelegateF(Type^ type);
TypeRegistry::CreateNewObjectDelegate^ TypeRegistry::CreateNewObjectDelegateF(Type^ type)
{
DynamicMethod^ dynam = gcnew DynamicMethod("", Internal::DotNetTypes::ObjectType, Type::EmptyTypes, type, true);
ILGenerator^ il = dynam->GetILGenerator();
ConstructorInfo^ ctorInfo = type->GetConstructor(Type::EmptyTypes);
if (ctorInfo == nullptr) {
Log::Error("Object missing public no arg constructor");
throw gcnew IllegalStateException("Object missing public no arg constructor");
}
il->Emit(OpCodes::Newobj, ctorInfo);
il->Emit(OpCodes::Ret);
return (TypeRegistry::CreateNewObjectDelegate^)dynam->CreateDelegate(createNewObjectDelegateType);
}
//delegate Object^ CreateNewObjectArray(int len);
TypeRegistry::CreateNewObjectArrayDelegate^ TypeRegistry::CreateNewObjectArrayDelegateF(Type^ type)
{
DynamicMethod^ dynam = gcnew DynamicMethod("", Internal::DotNetTypes::ObjectType, singleIntTypeA, type, true);
ILGenerator^ il = dynam->GetILGenerator();
il->Emit(OpCodes::Ldarg_0);
il->Emit(OpCodes::Newarr, type);
il->Emit(OpCodes::Ret);
return (TypeRegistry::CreateNewObjectArrayDelegate^)dynam->CreateDelegate(createNewObjectArrayDelegateType);
}
void TypeRegistry::RegisterDataSerializablePrimitivesWrapNativeDeserialization()
{
// Register wrappers for primitive types
// Does not intercept deserialization
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableByte::Create),
native::GeodeTypeIds::CacheableByte, Byte::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableBoolean::Create),
native::GeodeTypeIds::CacheableBoolean, Boolean::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableCharacter::Create),
native::GeodeTypeIds::CacheableCharacter, Char::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableDouble::Create),
native::GeodeTypeIds::CacheableDouble, Double::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableString::Create),
native::GeodeTypeIds::CacheableASCIIString, String::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableFloat::Create),
native::GeodeTypeIds::CacheableFloat, float::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableInt16::Create),
native::GeodeTypeIds::CacheableInt16, Int16::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableInt32::Create),
native::GeodeTypeIds::CacheableInt32, Int32::typeid);
RegisterDataSerializablePrimitiveWrapper(
gcnew DataSerializablePrimitiveWrapperDelegate(CacheableInt64::Create),
native::GeodeTypeIds::CacheableInt64, Int64::typeid);
}
} // namespace Client
} // namespace Geode
} // namespace Apache
| 38.927614
| 148
| 0.648106
|
echobravopapa
|
6df63845e16b4a91e576312b7a19ec96fd547c3f
| 14,774
|
cpp
|
C++
|
src/tdme/os/filesystem/ArchiveFileSystem.cpp
|
mahula/tdme2
|
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
|
[
"BSD-3-Clause"
] | null | null | null |
src/tdme/os/filesystem/ArchiveFileSystem.cpp
|
mahula/tdme2
|
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
|
[
"BSD-3-Clause"
] | null | null | null |
src/tdme/os/filesystem/ArchiveFileSystem.cpp
|
mahula/tdme2
|
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
|
[
"BSD-3-Clause"
] | null | null | null |
#include <tdme/os/filesystem/ArchiveFileSystem.h>
#include <string.h>
#include <algorithm>
#include <cassert>
#include <fstream>
#include <string>
#include <vector>
#include <ext/sha256/sha256.h>
#include <ext/zlib/zlib.h>
#include <tdme/math/Math.h>
#include <tdme/os/filesystem/FileNameFilter.h>
#include <tdme/os/threading/Mutex.h>
#include <tdme/utils/fwd-tdme.h>
#include <tdme/utils/StringUtils.h>
#include <tdme/utils/StringTokenizer.h>
#include <tdme/utils/Console.h>
#include <tdme/utils/Exception.h>
using std::ifstream;
using std::ios;
using std::sort;
using std::string;
using std::to_string;
using std::vector;
using tdme::math::Math;
using tdme::os::filesystem::ArchiveFileSystem;
using tdme::os::threading::Mutex;
using tdme::utils::StringUtils;
using tdme::utils::StringTokenizer;
using tdme::utils::Console;
using tdme::utils::Exception;
ArchiveFileSystem::ArchiveFileSystem(const string& fileName): fileName(fileName), ifsMutex("afs-ifs-mutex")
{
// open
ifs.open(fileName.c_str(), ifstream::binary);
if (ifs.is_open() == false) {
throw FileSystemException("Unable to open file for reading(" + to_string(errno) + "): " + fileName);
}
// read toc offset
uint64_t fileInformationOffset;
ifs.seekg(-static_cast<int64_t>(sizeof(fileInformationOffset)), ios::end);
ifs.read((char*)&fileInformationOffset, sizeof(fileInformationOffset));
ifs.seekg(fileInformationOffset, ios::beg);
// read toc
while (true == true) {
uint32_t nameSize;
ifs.read((char*)&nameSize, sizeof(nameSize));
if (nameSize == 0) break;
FileInformation fileInformation;
auto buffer = new char[nameSize];
ifs.read(buffer, nameSize);
fileInformation.name.append(buffer, nameSize);
delete [] buffer;
ifs.read((char*)&fileInformation.bytes, sizeof(fileInformation.bytes));
ifs.read((char*)&fileInformation.compressed, sizeof(fileInformation.compressed));
ifs.read((char*)&fileInformation.bytesCompressed, sizeof(fileInformation.bytesCompressed));
ifs.read((char*)&fileInformation.offset, sizeof(fileInformation.offset));
ifs.read((char*)&fileInformation.executable, sizeof(fileInformation.executable));
fileInformations[fileInformation.name] = fileInformation;
}
}
ArchiveFileSystem::~ArchiveFileSystem()
{
ifs.close();
}
const string& ArchiveFileSystem::getArchiveFileName() {
return fileName;
}
const string ArchiveFileSystem::getFileName(const string& pathName, const string& fileName) {
return pathName + "/" + fileName;
}
void ArchiveFileSystem::list(const string& pathName, vector<string>& files, FileNameFilter* filter, bool addDrives)
{
// TODO: this currently lists all files beginning from given path, also files in sub folders
auto _pathName = pathName;
if (_pathName.empty() == false && StringUtils::endsWith(pathName, "/") == false) _pathName+= "/";
for (auto& fileInformationIt: fileInformations) {
auto fileName = fileInformationIt.second.name;
if (StringUtils::startsWith(fileName, _pathName) == true) {
try {
if (filter != nullptr && filter->accept(
getPathName(fileName),
getFileName(fileName)
) == false) continue;
} catch (Exception& exception) {
Console::println("StandardFileSystem::list(): Filter::accept(): " + pathName + "/" + fileName + ": " + exception.what());
continue;
}
files.push_back(StringUtils::substring(fileName, pathName.size()));
}
}
sort(files.begin(), files.end());
}
bool ArchiveFileSystem::isPath(const string& pathName) {
return false;
}
bool ArchiveFileSystem::isDrive(const string& pathName) {
return false;
}
bool ArchiveFileSystem::fileExists(const string& fileName) {
// compose relative file name and remove ./
auto relativeFileName = fileName;
if (StringUtils::startsWith(relativeFileName, "./") == true) relativeFileName = StringUtils::substring(relativeFileName, 2);
//
return fileInformations.find(relativeFileName) != fileInformations.end();
}
bool ArchiveFileSystem::isExecutable(const string& pathName, const string& fileName) {
// compose relative file name and remove ./
auto relativeFileName = pathName + "/" + fileName;
if (StringUtils::startsWith(relativeFileName, "./") == true) relativeFileName = StringUtils::substring(relativeFileName, 2);
// determine file
auto fileInformationIt = fileInformations.find(relativeFileName);
if (fileInformationIt == fileInformations.end()) {
throw FileSystemException("Unable to open file for reading: " + relativeFileName + ": " + pathName + "/" + fileName);
}
auto& fileInformation = fileInformationIt->second;
//
return fileInformation.executable;
}
void ArchiveFileSystem::setExecutable(const string& pathName, const string& fileName) {
throw FileSystemException("ArchiveFileSystem::createPath(): Not implemented yet");
}
uint64_t ArchiveFileSystem::getFileSize(const string& pathName, const string& fileName) {
// compose relative file name and remove ./
auto relativeFileName = pathName + "/" + fileName;
if (StringUtils::startsWith(relativeFileName, "./") == true) relativeFileName = StringUtils::substring(relativeFileName, 2);
// determine file
auto fileInformationIt = fileInformations.find(relativeFileName);
if (fileInformationIt == fileInformations.end()) {
throw FileSystemException("Unable to open file for reading: " + relativeFileName + ": " + pathName + "/" + fileName);
}
auto& fileInformation = fileInformationIt->second;
//
return fileInformation.bytes;
}
void ArchiveFileSystem::decompress(vector<uint8_t>& inContent, vector<uint8_t>& outContent) {
// see: https://www.zlib.net/zpipe.c
#define CHUNK 16384
int ret;
size_t have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
// allocate inflate state
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK) {
throw FileSystemException("ArchiveFileSystem::decompress(): Error while decompressing: inflate init");
}
// decompress until deflate stream ends or end of file */
size_t outPosition = 0;
size_t inPosition = 0;
size_t inBytes = inContent.size();
do {
// see: https://www.zlib.net/zpipe.c
auto inStartPosition = inPosition;
for (size_t i = 0; i < CHUNK; i++) {
if (inPosition == inBytes) break;
in[i] = inContent[inPosition];
inPosition++;
}
strm.avail_in = inPosition - inStartPosition;
if (strm.avail_in == 0) break;
strm.next_in = in;
// run inflate() on input until output buffer not full
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); // state not clobbered
switch (ret) {
case Z_NEED_DICT:
throw FileSystemException("ArchiveFileSystem::decompress(): Error while decompressing: Z_NEED_DICT");
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
throw FileSystemException("ArchiveFileSystem::decompress(): Error while decompressing: Z_DATA_ERROR | Z_MEM_ERROR");
}
have = CHUNK - strm.avail_out;
for (size_t i = 0; i < have; i++) {
outContent[outPosition++] = out[i];
}
} while (strm.avail_out == 0);
// done when inflate() says it's done
} while (ret != Z_STREAM_END);
// clean up and return
(void) inflateEnd(&strm);
// check if eof
if (ret != Z_STREAM_END) {
throw FileSystemException("ArchiveFileSystem::decompress(): Error while decompressing: missing eof");
}
}
const string ArchiveFileSystem::getContentAsString(const string& pathName, const string& fileName) {
// compose relative file name and remove ./
auto relativeFileName = pathName + "/" + fileName;
if (StringUtils::startsWith(relativeFileName, "./") == true) relativeFileName = StringUtils::substring(relativeFileName, 2);
// determine file
auto fileInformationIt = fileInformations.find(relativeFileName);
if (fileInformationIt == fileInformations.end()) {
throw FileSystemException("Unable to open file for reading: " + relativeFileName + ": " + pathName + "/" + fileName);
}
auto& fileInformation = fileInformationIt->second;
//
ifsMutex.lock();
// seek
ifs.seekg(fileInformation.offset, ios::beg);
// result
string result;
if (fileInformation.compressed == 1) {
vector<uint8_t> compressedBuffer;
compressedBuffer.resize(fileInformation.bytesCompressed);
ifs.read((char*)compressedBuffer.data(), fileInformation.bytesCompressed);
ifsMutex.unlock();
vector<uint8_t> decompressedBuffer;
decompressedBuffer.resize(fileInformation.bytes);
decompress(compressedBuffer, decompressedBuffer);
result.append((char*)decompressedBuffer.data(), fileInformation.bytes);
} else {
vector<uint8_t> buffer;
buffer.resize(fileInformation.bytes);
ifs.read((char*)buffer.data(), fileInformation.bytes);
ifsMutex.unlock();
result.append((char*)buffer.data(), fileInformation.bytes);
}
// done
return result;
}
void ArchiveFileSystem::setContentFromString(const string& pathName, const string& fileName, const string& content) {
throw FileSystemException("ArchiveFileSystem::setContentFromString(): Not implemented yet");
}
void ArchiveFileSystem::getContent(const string& pathName, const string& fileName, vector<uint8_t>& content)
{
// compose relative file name and remove ./
auto relativeFileName = pathName + "/" + fileName;
if (StringUtils::startsWith(relativeFileName, "./") == true) relativeFileName = StringUtils::substring(relativeFileName, 2);
// determine file
auto fileInformationIt = fileInformations.find(relativeFileName);
if (fileInformationIt == fileInformations.end()) {
throw FileSystemException("Unable to open file for reading: " + relativeFileName + ": " + pathName + "/" + fileName);
}
auto& fileInformation = fileInformationIt->second;
//
ifsMutex.lock();
// seek
ifs.seekg(fileInformation.offset, ios::beg);
// result
if (fileInformation.compressed == 1) {
vector<uint8_t> compressedContent;
compressedContent.resize(fileInformation.bytesCompressed);
ifs.read((char*)compressedContent.data(), fileInformation.bytesCompressed);
ifsMutex.unlock();
content.resize(fileInformation.bytes);
decompress(compressedContent, content);
} else {
content.resize(fileInformation.bytes);
ifs.read((char*)content.data(), fileInformation.bytes);
ifsMutex.unlock();
}
}
void ArchiveFileSystem::setContent(const string& pathName, const string& fileName, const vector<uint8_t>& content) {
throw FileSystemException("ArchiveFileSystem::setContent(): Not implemented yet");
}
void ArchiveFileSystem::getContentAsStringArray(const string& pathName, const string& fileName, vector<string>& content)
{
auto contentAsString = getContentAsString(pathName, fileName);
contentAsString = StringUtils::replace(contentAsString, "\r", "");
StringTokenizer t;
t.tokenize(contentAsString, "\n");
while (t.hasMoreTokens() == true) {
content.push_back(t.nextToken());
}
}
void ArchiveFileSystem::setContentFromStringArray(const string& pathName, const string& fileName, const vector<string>& content)
{
throw FileSystemException("ArchiveFileSystem::setContentFromStringArray(): Not implemented yet");
}
const string ArchiveFileSystem::getCanonicalPath(const string& pathName, const string& fileName) {
string unixPathName = StringUtils::replace(pathName, "\\", "/");
string unixFileName = StringUtils::replace(fileName, "\\", "/");
auto pathString = getFileName(unixPathName, unixFileName);
// separate into path components
vector<string> pathComponents;
StringTokenizer t;
t.tokenize(pathString, "/");
while (t.hasMoreTokens()) {
pathComponents.push_back(t.nextToken());
}
// process path components
for (auto i = 0; i < pathComponents.size(); i++) {
auto pathComponent = pathComponents[i];
if (pathComponent == ".") {
pathComponents[i] = "";
} else
if (pathComponent == "..") {
pathComponents[i]= "";
int j = i - 1;
for (int pathComponentReplaced = 0; pathComponentReplaced < 1 && j >= 0; ) {
if (pathComponents[j] != "") {
pathComponents[j] = "";
pathComponentReplaced++;
}
j--;
}
}
}
// process path components
string canonicalPath = "";
bool slash = StringUtils::startsWith(pathString, "/");
for (auto i = 0; i < pathComponents.size(); i++) {
auto pathComponent = pathComponents[i];
if (pathComponent == "") {
// no op
} else {
canonicalPath = canonicalPath + (slash == true?"/":"") + pathComponent;
slash = true;
}
}
// add cwd if required
auto canonicalPathString = canonicalPath;
if (canonicalPathString.length() == 0 ||
(StringUtils::startsWith(canonicalPathString, "/") == false &&
StringUtils::regexMatch(canonicalPathString, "^[a-zA-Z]\\:.*$") == false)) {
canonicalPathString = getCurrentWorkingPathName() + "/" + canonicalPathString;
}
//
return canonicalPathString;
}
const string ArchiveFileSystem::getCurrentWorkingPathName() {
return ".";
}
const string ArchiveFileSystem::getPathName(const string& fileName) {
string unixFileName = StringUtils::replace(fileName, L'\\', L'/');
int32_t lastPathSeparator = StringUtils::lastIndexOf(unixFileName, L'/');
if (lastPathSeparator == -1) return ".";
return StringUtils::substring(unixFileName, 0, lastPathSeparator);
}
const string ArchiveFileSystem::getFileName(const string& fileName) {
string unixFileName = StringUtils::replace(fileName, L'\\', L'/');
int32_t lastPathSeparator = StringUtils::lastIndexOf(unixFileName, L'/');
if (lastPathSeparator == -1) return fileName;
return StringUtils::substring(unixFileName, lastPathSeparator + 1, unixFileName.length());
}
void ArchiveFileSystem::createPath(const string& pathName) {
throw FileSystemException("ArchiveFileSystem::createPath(): Not implemented yet");
}
void ArchiveFileSystem::removePath(const string& pathName, bool recursive) {
throw FileSystemException("ArchiveFileSystem::removePath(): Not implemented yet");
}
void ArchiveFileSystem::removeFile(const string& pathName, const string& fileName) {
throw FileSystemException("ArchiveFileSystem::removeFile(): Not implemented yet");
}
const string ArchiveFileSystem::computeSHA256Hash() {
ifs.seekg(0, ios::end);
auto bytesTotal = ifs.tellg();
ifs.seekg(0, ios::beg);
uint8_t input[16384];
unsigned char digest[SHA256::DIGEST_SIZE];
memset(digest, 0, SHA256::DIGEST_SIZE);
SHA256 ctx = SHA256();
ctx.init();
auto bytesRead = 0LL;
while (bytesRead < bytesTotal) {
auto bytesToRead = Math::min(static_cast<int64_t>(bytesTotal - bytesRead), sizeof(input));
ifs.read((char*)input, bytesToRead);
ctx.update((const uint8_t*)input, bytesToRead);
bytesRead+= bytesToRead;
}
ctx.final(digest);
char buf[2 * SHA256::DIGEST_SIZE + 1];
buf[2 * SHA256::DIGEST_SIZE] = 0;
for (int i = 0; i < SHA256::DIGEST_SIZE; i++) sprintf(buf + i * 2, "%02x", digest[i]);
return std::string(buf);
}
| 33.501134
| 128
| 0.727156
|
mahula
|
6df66952fbe162513712d1d5d58242fcb2073c3c
| 559
|
cpp
|
C++
|
LeetCode/ThousandOne/0049-group_anagram.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandOne/0049-group_anagram.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandOne/0049-group_anagram.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
#include "leetcode.hpp"
/* 49. 字母异位词分组
给定一个字符串数组,将字母异位词组合在一起。
字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
*/
vector<vector<string>> groupAnagrams(vector<string>& S)
{
vector<vector<string>> R;
unordered_map<string, vector<string>> M;
for (string s : S)
{
string t = s;
sort(t.begin(), t.end());
M[t].push_back(s);
}
size_t r = 0;
R.resize(M.size());
for (auto& kv : M)
R[r++].swap(kv.second);
return R;
}
int main()
{}
| 13
| 55
| 0.586762
|
Ginkgo-Biloba
|
6df9137ff2548bd4d6527f8a75816f024a948b97
| 6,618
|
cpp
|
C++
|
aws-cpp-sdk-ec2/source/model/AnalysisPacketHeader.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-ec2/source/model/AnalysisPacketHeader.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-ec2/source/model/AnalysisPacketHeader.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ec2/model/AnalysisPacketHeader.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
AnalysisPacketHeader::AnalysisPacketHeader() :
m_destinationAddressesHasBeenSet(false),
m_destinationPortRangesHasBeenSet(false),
m_protocolHasBeenSet(false),
m_sourceAddressesHasBeenSet(false),
m_sourcePortRangesHasBeenSet(false)
{
}
AnalysisPacketHeader::AnalysisPacketHeader(const XmlNode& xmlNode) :
m_destinationAddressesHasBeenSet(false),
m_destinationPortRangesHasBeenSet(false),
m_protocolHasBeenSet(false),
m_sourceAddressesHasBeenSet(false),
m_sourcePortRangesHasBeenSet(false)
{
*this = xmlNode;
}
AnalysisPacketHeader& AnalysisPacketHeader::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode destinationAddressesNode = resultNode.FirstChild("destinationAddressSet");
if(!destinationAddressesNode.IsNull())
{
XmlNode destinationAddressesMember = destinationAddressesNode.FirstChild("item");
while(!destinationAddressesMember.IsNull())
{
m_destinationAddresses.push_back(destinationAddressesMember.GetText());
destinationAddressesMember = destinationAddressesMember.NextNode("item");
}
m_destinationAddressesHasBeenSet = true;
}
XmlNode destinationPortRangesNode = resultNode.FirstChild("destinationPortRangeSet");
if(!destinationPortRangesNode.IsNull())
{
XmlNode destinationPortRangesMember = destinationPortRangesNode.FirstChild("item");
while(!destinationPortRangesMember.IsNull())
{
m_destinationPortRanges.push_back(destinationPortRangesMember);
destinationPortRangesMember = destinationPortRangesMember.NextNode("item");
}
m_destinationPortRangesHasBeenSet = true;
}
XmlNode protocolNode = resultNode.FirstChild("protocol");
if(!protocolNode.IsNull())
{
m_protocol = Aws::Utils::Xml::DecodeEscapedXmlText(protocolNode.GetText());
m_protocolHasBeenSet = true;
}
XmlNode sourceAddressesNode = resultNode.FirstChild("sourceAddressSet");
if(!sourceAddressesNode.IsNull())
{
XmlNode sourceAddressesMember = sourceAddressesNode.FirstChild("item");
while(!sourceAddressesMember.IsNull())
{
m_sourceAddresses.push_back(sourceAddressesMember.GetText());
sourceAddressesMember = sourceAddressesMember.NextNode("item");
}
m_sourceAddressesHasBeenSet = true;
}
XmlNode sourcePortRangesNode = resultNode.FirstChild("sourcePortRangeSet");
if(!sourcePortRangesNode.IsNull())
{
XmlNode sourcePortRangesMember = sourcePortRangesNode.FirstChild("item");
while(!sourcePortRangesMember.IsNull())
{
m_sourcePortRanges.push_back(sourcePortRangesMember);
sourcePortRangesMember = sourcePortRangesMember.NextNode("item");
}
m_sourcePortRangesHasBeenSet = true;
}
}
return *this;
}
void AnalysisPacketHeader::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_destinationAddressesHasBeenSet)
{
unsigned destinationAddressesIdx = 1;
for(auto& item : m_destinationAddresses)
{
oStream << location << index << locationValue << ".DestinationAddressSet." << destinationAddressesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&";
}
}
if(m_destinationPortRangesHasBeenSet)
{
unsigned destinationPortRangesIdx = 1;
for(auto& item : m_destinationPortRanges)
{
Aws::StringStream destinationPortRangesSs;
destinationPortRangesSs << location << index << locationValue << ".DestinationPortRangeSet." << destinationPortRangesIdx++;
item.OutputToStream(oStream, destinationPortRangesSs.str().c_str());
}
}
if(m_protocolHasBeenSet)
{
oStream << location << index << locationValue << ".Protocol=" << StringUtils::URLEncode(m_protocol.c_str()) << "&";
}
if(m_sourceAddressesHasBeenSet)
{
unsigned sourceAddressesIdx = 1;
for(auto& item : m_sourceAddresses)
{
oStream << location << index << locationValue << ".SourceAddressSet." << sourceAddressesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&";
}
}
if(m_sourcePortRangesHasBeenSet)
{
unsigned sourcePortRangesIdx = 1;
for(auto& item : m_sourcePortRanges)
{
Aws::StringStream sourcePortRangesSs;
sourcePortRangesSs << location << index << locationValue << ".SourcePortRangeSet." << sourcePortRangesIdx++;
item.OutputToStream(oStream, sourcePortRangesSs.str().c_str());
}
}
}
void AnalysisPacketHeader::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_destinationAddressesHasBeenSet)
{
unsigned destinationAddressesIdx = 1;
for(auto& item : m_destinationAddresses)
{
oStream << location << ".DestinationAddressSet." << destinationAddressesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&";
}
}
if(m_destinationPortRangesHasBeenSet)
{
unsigned destinationPortRangesIdx = 1;
for(auto& item : m_destinationPortRanges)
{
Aws::StringStream destinationPortRangesSs;
destinationPortRangesSs << location << ".DestinationPortRangeSet." << destinationPortRangesIdx++;
item.OutputToStream(oStream, destinationPortRangesSs.str().c_str());
}
}
if(m_protocolHasBeenSet)
{
oStream << location << ".Protocol=" << StringUtils::URLEncode(m_protocol.c_str()) << "&";
}
if(m_sourceAddressesHasBeenSet)
{
unsigned sourceAddressesIdx = 1;
for(auto& item : m_sourceAddresses)
{
oStream << location << ".SourceAddressSet." << sourceAddressesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&";
}
}
if(m_sourcePortRangesHasBeenSet)
{
unsigned sourcePortRangesIdx = 1;
for(auto& item : m_sourcePortRanges)
{
Aws::StringStream sourcePortRangesSs;
sourcePortRangesSs << location << ".SourcePortRangeSet." << sourcePortRangesIdx++;
item.OutputToStream(oStream, sourcePortRangesSs.str().c_str());
}
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
| 32.600985
| 166
| 0.700514
|
perfectrecall
|
6dfa216ab4d8db16a36b5aea8d3c1e7ead15774f
| 3,413
|
hpp
|
C++
|
src/types/inc/utils.hpp
|
hackecord/terminal
|
c0111a706db017719ea11c3219522f8f8e5542cc
|
[
"MIT"
] | 4
|
2019-05-09T12:47:49.000Z
|
2020-06-16T22:08:57.000Z
|
src/types/inc/utils.hpp
|
ironyman/terminal
|
1e2f203395424a0304efe16d955e5b14fd3a5e56
|
[
"MIT"
] | null | null | null |
src/types/inc/utils.hpp
|
ironyman/terminal
|
1e2f203395424a0304efe16d955e5b14fd3a5e56
|
[
"MIT"
] | 1
|
2020-05-13T09:07:40.000Z
|
2020-05-13T09:07:40.000Z
|
/*++
Copyright (c) Microsoft Corporation
Module Name:
- utils.hpp
Abstract:
- Helpful cross-lib utilities
Author(s):
- Mike Griese (migrie) 12-Jun-2018
--*/
// Inspired from RETURN_IF_WIN32_BOOL_FALSE
// WIL doesn't include a RETURN_BOOL_IF_FALSE, and RETURN_IF_WIN32_BOOL_FALSE
// will actually return the value of GLE.
#define RETURN_BOOL_IF_FALSE(b) \
do \
{ \
BOOL __boolRet = wil::verify_bool(b); \
if (!__boolRet) \
{ \
return __boolRet; \
} \
} while (0, 0)
namespace Microsoft::Console::Utils
{
bool IsValidHandle(const HANDLE handle) noexcept;
// Function Description:
// - Clamps a long in between `min` and `SHRT_MAX`
// Arguments:
// - value: the value to clamp
// - min: the minimum value to clamp to
// Return Value:
// - The clamped value as a short.
constexpr short ClampToShortMax(const long value, const short min) noexcept
{
return static_cast<short>(std::clamp(value,
static_cast<long>(min),
static_cast<long>(SHRT_MAX)));
}
std::wstring GuidToString(const GUID guid);
GUID GuidFromString(const std::wstring wstr);
GUID CreateGuid();
std::string ColorToHexString(const COLORREF color);
COLORREF ColorFromHexString(const std::string wstr);
void InitializeCampbellColorTable(const gsl::span<COLORREF> table);
void InitializeCampbellColorTableForConhost(const gsl::span<COLORREF> table);
void SwapANSIColorOrderForConhost(const gsl::span<COLORREF> table);
void Initialize256ColorTable(const gsl::span<COLORREF> table);
// Function Description:
// - Fill the alpha byte of the colors in a given color table with the given value.
// Arguments:
// - table: a color table
// - newAlpha: the new value to use as the alpha for all the entries in that table.
// Return Value:
// - <none>
constexpr void SetColorTableAlpha(const gsl::span<COLORREF> table, const BYTE newAlpha) noexcept
{
const auto shiftedAlpha = newAlpha << 24;
for (auto& color : table)
{
WI_UpdateFlagsInMask(color, 0xff000000, shiftedAlpha);
}
}
constexpr uint16_t EndianSwap(uint16_t value)
{
return (value & 0xFF00) >> 8 |
(value & 0x00FF) << 8;
}
constexpr uint32_t EndianSwap(uint32_t value)
{
return (value & 0xFF000000) >> 24 |
(value & 0x00FF0000) >> 8 |
(value & 0x0000FF00) << 8 |
(value & 0x000000FF) << 24;
}
constexpr unsigned long EndianSwap(unsigned long value)
{
return gsl::narrow_cast<unsigned long>(EndianSwap(gsl::narrow_cast<uint32_t>(value)));
}
constexpr GUID EndianSwap(GUID value)
{
value.Data1 = EndianSwap(value.Data1);
value.Data2 = EndianSwap(value.Data2);
value.Data3 = EndianSwap(value.Data3);
return value;
}
GUID CreateV5Uuid(const GUID& namespaceGuid, const gsl::span<const gsl::byte> name);
}
| 33.460784
| 101
| 0.572517
|
hackecord
|
6dfb5ea91cb70949e1ce0ee52a8b0bd7d293a7cc
| 5,134
|
cc
|
C++
|
src/node/old_version/activation_node.cc
|
huichengz0520/intellgraph
|
00173f4c24a6314c85b4a091b2475ae157a2d814
|
[
"Apache-2.0"
] | 1
|
2019-04-24T19:10:05.000Z
|
2019-04-24T19:10:05.000Z
|
src/node/old_version/activation_node.cc
|
huichengz0520/intellgraph
|
00173f4c24a6314c85b4a091b2475ae157a2d814
|
[
"Apache-2.0"
] | null | null | null |
src/node/old_version/activation_node.cc
|
huichengz0520/intellgraph
|
00173f4c24a6314c85b4a091b2475ae157a2d814
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2019 The IntellGraph Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributor(s):
Lingbo Zhang <lingboz2015@gmail.com>
==============================================================================*/
#include "node/activation_node.h"
namespace intellgraph {
template <class T>
ActivationNode<T>::ActivationNode(const NodeParameter<T>& node_param) {
node_param_.Clone(node_param);
size_t row = node_param.ref_dims()[0];
size_t col = node_param.ref_dims()[1];
activation_ptr_ = std::make_shared<MatXX<T>>(row, col);
delta_ptr_ = std::make_unique<MatXX<T>>(row, col);
bias_ptr_ = std::make_unique<VecX<T>>(row);
activation_ptr_->array() = 0.0;
delta_ptr_->array() = 0.0;
bias_ptr_->array() = 0.0;
current_act_state_ = kInit;
}
template <class T>
void ActivationNode<T>::PrintAct() const {
std::cout << "Node: " << node_param_.ref_id() << std::endl
<< " Activation Vector:" << std::endl
<< activation_ptr_->array() << std::endl;
}
template <class T>
void ActivationNode<T>::PrintDelta() const {
std::cout << "Node: " << node_param_.ref_id() << std::endl
<< " Delta Vector:" << std::endl
<< delta_ptr_->array() << std::endl;
}
template <class T>
void ActivationNode<T>::PrintBias() const {
std::cout << "Node: " << node_param_.ref_id() << std::endl
<< " Bias Vector:" << std::endl
<< bias_ptr_->array() << std::endl;
}
template <class T>
bool ActivationNode<T>::CallActFxn() {
if (!Transition(kAct)) {
LOG(ERROR) << "CallActFxn() for ActivationNode is failed.";
return false;
}
return true;
}
template <class T>
bool ActivationNode<T>::CalcActPrime() {
if (!Transition(kPrime)) {
LOG(ERROR) << "CalcActPrime() for ActivationNode is failed";
return false;
}
return true;
}
template <class T>
void ActivationNode<T>::InitializeAct(const std::function<T(T)>& functor) {
if (functor == nullptr) {
LOG(WARNING) << "functor passed to ApplyUnaryFunctor() is not defined."
<< "Initializes activation with standard normal distribution";
activation_ptr_->array() = activation_ptr_->array().unaryExpr( \
std::function<T(T)>(NormalFunctor<T>(0.0, 1.0)));
} else {
activation_ptr_->array() = activation_ptr_->array().unaryExpr(functor);
}
Transition(kInit);
}
template <class T>
void ActivationNode<T>::InitializeBias(const std::function<T(T)>& functor) {
if (functor == nullptr) {
LOG(WARNING) << "functor passed to InitializeBias() is not defined."
<< "Initializes bias with standard normal distribution";
bias_ptr_->array() = bias_ptr_->unaryExpr( \
std::function<T(T)>(NormalFunctor<T>(0.0, 1.0)));
} else {
bias_ptr_->array() = bias_ptr_->unaryExpr(functor);
}
Transition(kInit);
}
// Transitions from kInit state to kAct state.
template <class T>
void ActivationNode<T>::InitToAct() {
auto act_functor = node_param_.ref_act_functor();
if ( act_functor == nullptr) {
LOG(ERROR) << "InitToAct() for ActivationNode is failed."
<< "activation function is not defined.";
exit(1);
} else {
activation_ptr_->array() = activation_ptr_->array(). \
unaryExpr(act_functor);
}
current_act_state_ = kAct;
}
template <class T>
void ActivationNode<T>::ActToPrime() {
// Derivative equation:
// $df/dz=f(z)(1-f(z))$
auto act_prime_functor = node_param_.ref_act_prime_functor();
if (act_prime_functor == nullptr) {
LOG(ERROR) << "ActToPrime() for ActivationNode is failed."
<< "activation prime function is not defined.";
exit(1);
} else {
activation_ptr_->array() = activation_ptr_->array(). \
unaryExpr(act_prime_functor);
}
current_act_state_ = kPrime;
}
template <class T>
bool ActivationNode<T>::Transition(ActStates state) {
if (state == kInit) {
current_act_state_ = kInit;
return true;
}
if (current_act_state_ > state) {
LOG(ERROR) << "Transition() for ActivationNode is failed";
return false;
}
while (current_act_state_ < state) {
switch (current_act_state_) {
case kInit: {
InitToAct();
break;
}
case kAct: {
ActToPrime();
break;
}
default: {
LOG(ERROR) << "Transition() for ActivationNode is failed";
return false;
}
}
}
return true;
}
// Instantiate class, otherwise compilation will fail
template class ActivationNode<float>;
template class ActivationNode<double>;
} // namespace intellgraph
| 29.170455
| 80
| 0.639073
|
huichengz0520
|
6dfcb9da3604e0f4e74156704e3bfd2d799222b0
| 2,733
|
cpp
|
C++
|
src/options.cpp
|
jake-stewart/jmatrix
|
cf42ae4a3cd11500c071f451e783ee3ff16905a7
|
[
"MIT"
] | null | null | null |
src/options.cpp
|
jake-stewart/jmatrix
|
cf42ae4a3cd11500c071f451e783ee3ff16905a7
|
[
"MIT"
] | null | null | null |
src/options.cpp
|
jake-stewart/jmatrix
|
cf42ae4a3cd11500c071f451e783ee3ff16905a7
|
[
"MIT"
] | null | null | null |
#include "../include/options.hpp"
#include "../include/util.hpp"
#include <string.h>
#include <stdio.h>
bool read_options(int argc, char **argv, Options *options) {
for (int i = 1; i < argc; i++) {
char *arg = argv[i];
if (strcmp(arg, "--fg") == 0) {
if (++i == argc) {
printf("ERROR: --fg is missing a value\n");
return false;
}
if (!parse_color(argv[i], &options->fg)) {
return false;
}
}
else if (strcmp(arg, "--bg") == 0) {
if (++i == argc) {
printf("ERROR: --bg is missing a value\n");
return false;
}
if (!parse_color(argv[i], &options->bg)) {
return false;
}
}
else if (strcmp(arg, "--speed") == 0) {
if (++i == argc) {
printf("ERROR: --speed is missing a value\n");
return false;
}
if (!parse_int(argv[i], &options->speed)) {
return false;
}
}
else if (strcmp(arg, "--ascii") == 0) {
options->ascii = true;
}
else if (strcmp(arg, "--gap") == 0) {
if (++i == argc) {
printf("ERROR: --gap is missing a value\n");
return false;
}
if (!parse_int(argv[i], &options->gap)) {
return false;
}
}
else if (strcmp(arg, "--trail") == 0) {
if (++i == argc) {
printf("ERROR: --trail is missing a value\n");
return false;
}
if (!parse_int(argv[i], &options->trail)) {
return false;
}
}
else if (strcmp(arg, "--length") == 0) {
if (++i == argc) {
printf("ERROR: --length is missing a value\n");
return false;
}
if (!parse_int(argv[i], &options->length)) {
return false;
}
}
else if (strcmp(arg, "--rarity") == 0) {
if (++i == argc) {
printf("ERROR: --rarity is missing a value\n");
return false;
}
if (!parse_int(argv[i], &options->rarity)) {
return false;
}
}
else if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) {
options->view_help = true;
break;
}
else {
printf("Unknown option: '%s'\n", arg);
printf("See 'jmatrix --help' for usage information\n");
return false;
}
}
return true;
}
| 27.606061
| 72
| 0.394072
|
jake-stewart
|
6dfce865c2413be5e4fd7cef14edcd01f9dd0734
| 299
|
cpp
|
C++
|
Source/KInk/Private/Player/CustomPlayerState.cpp
|
DanySpin97/KInk
|
e9f65cfe20aab39a09467bf8e96e0cc06697a29f
|
[
"MIT"
] | 4
|
2016-11-30T04:39:51.000Z
|
2018-06-29T06:38:27.000Z
|
Source/KInk/Private/Player/CustomPlayerState.cpp
|
DanySpin97/KInk
|
e9f65cfe20aab39a09467bf8e96e0cc06697a29f
|
[
"MIT"
] | null | null | null |
Source/KInk/Private/Player/CustomPlayerState.cpp
|
DanySpin97/KInk
|
e9f65cfe20aab39a09467bf8e96e0cc06697a29f
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2016 WiseDragonStd
#include "KInk.h"
#include "CustomPlayerState.h"
void ACustomPlayerState::ResetNewGame()
{
CurrentHealth = MaxHealth;
FireRate = 1.f / (Rate / 50.f);
CurrentWeaponType = EWeapon::WFireGun;
CurrentScore = 0;
CurrentEnemyKilled = 0;
bBigKraken = false;
}
| 17.588235
| 39
| 0.722408
|
DanySpin97
|
6dfd1a203c5da15d62192d31099576cfa43dfa26
| 7,204
|
cxx
|
C++
|
src/util/GuideObject.cxx
|
rita0222/FK
|
bc5786a5da0dd732e2f411c1a953b331323ee432
|
[
"BSD-3-Clause"
] | 4
|
2020-05-15T03:43:53.000Z
|
2021-06-05T16:21:31.000Z
|
src/util/GuideObject.cxx
|
rita0222/FK
|
bc5786a5da0dd732e2f411c1a953b331323ee432
|
[
"BSD-3-Clause"
] | 1
|
2020-05-19T09:27:16.000Z
|
2020-05-21T02:12:54.000Z
|
src/util/GuideObject.cxx
|
rita0222/FK
|
bc5786a5da0dd732e2f411c1a953b331323ee432
|
[
"BSD-3-Clause"
] | null | null | null |
#include <FK/GuideObject.h>
#include <FK/Scene.h>
using namespace FK;
using namespace std;
namespace FK {
fk_Guide operator | (fk_Guide argL, fk_Guide argR) {
return static_cast<fk_Guide>(static_cast<unsigned int>(argL) |
static_cast<unsigned int>(argR));
}
fk_Guide operator & (fk_Guide argL, fk_Guide argR) {
return static_cast<fk_Guide>(static_cast<unsigned int>(argL) &
static_cast<unsigned int>(argR));
}
fk_Guide operator ^ (fk_Guide argL, fk_Guide argR) {
return static_cast<fk_Guide>(static_cast<unsigned int>(argL) ^
static_cast<unsigned int>(argR));
}
}
fk_GuideObject::Member::Member(void)
{
axis[0].pushLine(fk_Vector(0.0, 0.0, 0.0), fk_Vector(1.0, 0.0, 0.0));
axis[1].pushLine(fk_Vector(0.0, 0.0, 0.0), fk_Vector(0.0, 1.0, 0.0));
axis[2].pushLine(fk_Vector(0.0, 0.0, 0.0), fk_Vector(0.0, 0.0, 1.0));
axisModel[0].setLineColor(1.0, 0.0, 0.0);
axisModel[1].setLineColor(0.0, 1.0, 0.0);
axisModel[2].setLineColor(0.0, 0.0, 1.0);
for(int i = 0; i < 3; i++) {
axisModel[i].setShape(&axis[i]);
gridModel[i].setShape(&grid);
}
gridModel[1].glAngle(0.0, fk_Math::PI*0.5, 0.0);
gridModel[2].glAngle(0.0, 0.0, fk_Math::PI*0.5);
return;
}
fk_GuideObject::fk_GuideObject(void) : _m(make_unique<Member>())
{
setAxisWidth(4.0);
setGridWidth(1.0);
setScale(5.0);
setNum(20);
return;
}
fk_GuideObject::~fk_GuideObject(void)
{
return;
}
void fk_GuideObject::setAxisWidth(double argWidth)
{
for(int i = 0; i < 3; i++) {
_m->axisModel[i].setWidth(argWidth);
}
return;
}
void fk_GuideObject::setGridWidth(double argWidth)
{
for(int i = 0; i < 3; i++) {
_m->gridModel[i].setWidth(argWidth);
}
return;
}
void fk_GuideObject::setScale(double argScale)
{
if(argScale < fk_Math::EPS) return;
_m->scale = argScale;
for(int i = 0; i < 3; i++) {
if(_m->num >= 2) _m->axisModel[i].setScale(_m->scale*(double)(_m->num/2));
_m->gridModel[i].setScale(_m->scale);
}
return;
}
void fk_GuideObject::setNum(int argNum)
{
if(argNum <= 0) return;
_m->num = argNum;
_m->grid.allClear();
double hn = double(_m->num / 2);
for(int i = 0; i <= _m->num; i++) {
_m->grid.pushLine(fk_Vector(double(i) - hn, 0.0, hn), fk_Vector(double(i) - hn, 0.0, -hn));
_m->grid.pushLine(fk_Vector(-hn, 0.0, hn - double(i)), fk_Vector(hn, 0.0, hn - double(i)));
}
for(int i = 0; i < 3; i++) {
_m->axisModel[i].setScale(_m->scale*hn);
}
return;
}
void fk_GuideObject::setParent(fk_Model *argModel)
{
for(int i = 0; i < 3; i++) {
_m->axisModel[i].setParent(argModel, false);
_m->gridModel[i].setParent(argModel, false);
}
return;
}
void fk_GuideObject::entryScene(fk_Scene *argScene, fk_Guide argMode)
{
if((argMode & fk_Guide::AXIS_X) != fk_Guide::NO_GUIDE) {
argScene->entryModel(&_m->axisModel[0]);
}
if((argMode & fk_Guide::AXIS_Y) != fk_Guide::NO_GUIDE) {
argScene->entryModel(&_m->axisModel[1]);
}
if((argMode & fk_Guide::AXIS_Z) != fk_Guide::NO_GUIDE) {
argScene->entryModel(&_m->axisModel[2]);
}
if((argMode & fk_Guide::GRID_XZ) != fk_Guide::NO_GUIDE) {
argScene->entryModel(&_m->gridModel[0]);
}
if((argMode & fk_Guide::GRID_XY) != fk_Guide::NO_GUIDE) {
argScene->entryModel(&_m->gridModel[1]);
}
if((argMode & fk_Guide::GRID_YZ) != fk_Guide::NO_GUIDE) {
argScene->entryModel(&_m->gridModel[2]);
}
return;
}
void fk_GuideObject::removeScene(fk_Scene *argScene, fk_Guide argMode)
{
if((argMode & fk_Guide::AXIS_X) != fk_Guide::NO_GUIDE || argMode == fk_Guide::NO_GUIDE) {
argScene->removeModel(&_m->axisModel[0]);
}
if((argMode & fk_Guide::AXIS_Y) != fk_Guide::NO_GUIDE || argMode == fk_Guide::NO_GUIDE) {
argScene->removeModel(&_m->axisModel[1]);
}
if((argMode & fk_Guide::AXIS_Z) != fk_Guide::NO_GUIDE || argMode == fk_Guide::NO_GUIDE) {
argScene->removeModel(&_m->axisModel[2]);
}
if((argMode & fk_Guide::GRID_XZ) != fk_Guide::NO_GUIDE || argMode == fk_Guide::NO_GUIDE) {
argScene->removeModel(&_m->gridModel[0]);
}
if((argMode & fk_Guide::GRID_XY) != fk_Guide::NO_GUIDE || argMode == fk_Guide::NO_GUIDE) {
argScene->removeModel(&_m->gridModel[1]);
}
if((argMode & fk_Guide::GRID_YZ) != fk_Guide::NO_GUIDE || argMode == fk_Guide::NO_GUIDE) {
argScene->removeModel(&_m->gridModel[2]);
}
}
void fk_GuideObject::SetFinalizeMode(void)
{
for(int i = 0; i < 3; i++) {
_m->axisModel[i].SetTreeDelMode(false);
_m->gridModel[i].SetTreeDelMode(false);
}
}
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, 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 holders nor the names
* of its contributors may be used to endorse or promote
* products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved.
*
* 本ソフトウェアおよびソースコードのライセンスは、基本的に
* 「修正 BSD ライセンス」に従います。以下にその詳細を記します。
*
* ソースコード形式かバイナリ形式か、変更するかしないかを問わず、
* 以下の条件を満たす場合に限り、再頒布および使用が許可されます。
*
* - ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、
* および下記免責条項を含めること。
*
* - バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の
* 資料に、上記の著作権表示、本条件一覧、および下記免責条項を
* 含めること。
*
* - 書面による特別の許可なしに、本ソフトウェアから派生した製品の
* 宣伝または販売促進に、本ソフトウェアの著作権者の名前または
* コントリビューターの名前を使用してはならない。
*
* 本ソフトウェアは、著作権者およびコントリビューターによって「現
* 状のまま」提供されており、明示黙示を問わず、商業的な使用可能性、
* および特定の目的に対する適合性に関す暗黙の保証も含め、またそれ
* に限定されない、いかなる保証もないものとします。著作権者もコン
* トリビューターも、事由のいかんを問わず、損害発生の原因いかんを
* 問わず、かつ責任の根拠が契約であるか厳格責任であるか(過失その
* 他の)不法行為であるかを問わず、仮にそのような損害が発生する可
* 能性を知らされていたとしても、本ソフトウェアの使用によって発生
* した(代替品または代用サービスの調達、使用の喪失、データの喪失、
* 利益の喪失、業務の中断も含め、またそれに限定されない)直接損害、
* 間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害に
* ついて、一切責任を負わないものとします。
*
****************************************************************************/
| 29.284553
| 93
| 0.666297
|
rita0222
|
6dfd6f3caf884c8361b5cf78f2d3e7c0305fcc37
| 25,607
|
cpp
|
C++
|
src/integer_object.cpp
|
natalie-lang/natalie
|
5597f401a41128631c92378b99bf3e8b5393717b
|
[
"MIT"
] | 7
|
2022-03-08T08:47:54.000Z
|
2022-03-29T15:08:36.000Z
|
src/integer_object.cpp
|
natalie-lang/natalie
|
5597f401a41128631c92378b99bf3e8b5393717b
|
[
"MIT"
] | 12
|
2022-03-10T13:04:42.000Z
|
2022-03-24T01:40:23.000Z
|
src/integer_object.cpp
|
natalie-lang/natalie
|
5597f401a41128631c92378b99bf3e8b5393717b
|
[
"MIT"
] | 5
|
2022-03-13T17:46:16.000Z
|
2022-03-31T07:28:26.000Z
|
#include "natalie.hpp"
#include <math.h>
namespace Natalie {
Value IntegerObject::create(const Integer &integer) {
if (integer.is_bignum())
return new IntegerObject { integer };
return Value::integer(integer.to_nat_int_t());
}
Value IntegerObject::create(const char *string) {
return new IntegerObject { BigInt(string) };
};
Value IntegerObject::to_s(Env *env, Value base_value) {
if (m_integer == 0)
return new StringObject { "0" };
nat_int_t base = 10;
if (base_value) {
base = convert_to_nat_int_t(env, base_value);
if (base < 2 || base > 36) {
env->raise("ArgumentError", "invalid radix {}", base);
}
}
if (base == 10)
return new StringObject { m_integer.to_string() };
auto str = new StringObject {};
auto num = m_integer;
bool negative = false;
if (num < 0) {
negative = true;
num *= -1;
}
while (num > 0) {
auto digit = num % base;
char c;
if (digit >= 0 && digit <= 9)
c = digit.to_nat_int_t() + 48;
else
c = digit.to_nat_int_t() + 87;
str->prepend_char(env, c);
num /= base;
}
if (negative)
str->prepend_char(env, '-');
return str;
}
Value IntegerObject::to_i() {
return this;
}
Value IntegerObject::to_f() const {
return Value::floatingpoint(m_integer.to_double());
}
Value IntegerObject::add(Env *env, Value arg) {
if (arg.is_fast_integer())
return create(m_integer + arg.get_fast_integer());
if (arg.is_fast_float())
return Value::floatingpoint(m_integer + arg.get_fast_float());
arg.unguard();
if (arg->is_float()) {
return Value::floatingpoint(m_integer + arg->as_float()->to_double());
} else if (!arg->is_integer()) {
arg = Natalie::coerce(env, arg, this).second;
}
arg->assert_type(env, Object::Type::Integer, "Integer");
return create(m_integer + arg->as_integer()->integer());
}
Value IntegerObject::sub(Env *env, Value arg) {
if (arg.is_fast_integer())
return create(m_integer - arg.get_fast_integer());
if (arg.is_fast_float())
return Value::floatingpoint(m_integer - arg.get_fast_float());
arg.unguard();
if (arg->is_float()) {
double result = m_integer.to_double() - arg->as_float()->to_double();
return Value::floatingpoint(result);
} else if (!arg->is_integer()) {
arg = Natalie::coerce(env, arg, this).second;
}
arg->assert_type(env, Object::Type::Integer, "Integer");
return create(m_integer - arg->as_integer()->integer());
}
Value IntegerObject::mul(Env *env, Value arg) {
if (arg.is_fast_integer())
return create(m_integer * arg.get_fast_integer());
if (arg.is_fast_float())
return Value::floatingpoint(m_integer * arg.get_fast_float());
arg.unguard();
if (arg->is_float()) {
double result = m_integer.to_double() * arg->as_float()->to_double();
return new FloatObject { result };
} else if (!arg->is_integer()) {
arg = Natalie::coerce(env, arg, this).second;
}
arg->assert_type(env, Object::Type::Integer, "Integer");
if (m_integer == 0 || arg->as_integer()->integer() == 0)
return Value::integer(0);
return create(m_integer * arg->as_integer()->integer());
}
Value IntegerObject::div(Env *env, Value arg) {
if (arg.is_fast_integer() && arg.get_fast_integer() != 0)
return create(m_integer / arg.get_fast_integer());
if (arg.is_fast_float())
return Value::floatingpoint(m_integer / arg.get_fast_float());
arg.unguard();
if (arg->is_float()) {
double result = to_nat_int_t() / arg->as_float()->to_double();
if (isnan(result))
return FloatObject::nan();
return Value::floatingpoint(result);
} else if (arg->is_rational()) {
return RationalObject(this, new IntegerObject { 1 }).div(env, arg);
} else if (!arg->is_integer()) {
arg = Natalie::coerce(env, arg, this).second;
}
arg->assert_type(env, Object::Type::Integer, "Integer");
auto other = arg->as_integer()->integer();
if (other == 0)
env->raise("ZeroDivisionError", "divided by 0");
return create(m_integer / other);
}
Value IntegerObject::mod(Env *env, Value arg) {
Integer argument;
if (arg.is_fast_integer()) {
argument = arg.get_fast_integer();
} else if (arg.is_fast_float() || arg->is_float()) {
return FloatObject { m_integer.to_double() }.mod(env, arg);
} else if (arg->is_rational()) {
return RationalObject { this, new IntegerObject { 1 } }.send(env, "%"_s, { arg });
} else {
arg.unguard();
arg->assert_type(env, Object::Type::Integer, "Integer");
argument = arg->as_integer()->integer();
}
if (argument == 0)
env->raise("ZeroDivisionError", "divided by 0");
return create(m_integer % argument);
}
Value IntegerObject::pow(Env *env, Value arg) {
Integer arg_int;
if (arg.is_fast_integer()) {
arg_int = arg.get_fast_integer();
} else {
arg.unguard();
if (arg->is_float())
return FloatObject { m_integer.to_double() }.pow(env, arg);
if (arg->is_rational())
return RationalObject { this, new IntegerObject { 1 } }.pow(env, arg);
if (!arg->is_integer()) {
auto coerced = Natalie::coerce(env, arg, this);
arg = coerced.second;
if (!coerced.first->is_integer()) {
return coerced.first->send(env, "**"_s, { arg });
}
}
arg->assert_type(env, Object::Type::Integer, "Integer");
arg_int = arg->as_integer()->integer();
}
if (m_integer == 0 && arg_int < 0)
env->raise("ZeroDivisionError", "divided by 0");
// NATFIXME: If a negative number is passed we want to return a Rational
if (arg_int < 0) {
auto denominator = Natalie::pow(m_integer, -arg_int);
return new RationalObject { new IntegerObject { 1 }, new IntegerObject { denominator } };
}
if (arg_int == 0)
return Value::integer(1);
else if (arg_int == 1)
return create(m_integer);
if (m_integer == 0)
return Value::integer(0);
else if (m_integer == 1)
return Value::integer(1);
else if (m_integer == -1)
return Value::integer(arg_int % 2 ? 1 : -1);
// NATFIXME: Ruby has a really weird max bignum value that is calculated by the words needed to store a bignum
// The calculation that we do is pretty much guessed to be in the direction of ruby. However, we should do more research about this limit...
size_t length = m_integer.to_string().length();
constexpr const size_t BIGINT_LIMIT = 8 * 1024 * 1024;
if (length > BIGINT_LIMIT || length * arg_int > (nat_int_t)BIGINT_LIMIT) {
env->warn("in a**b, b may be too big");
return FloatObject { m_integer.to_double() }.pow(env, arg);
}
return create(Natalie::pow(m_integer, arg_int));
}
Value IntegerObject::powmod(Env *env, Value exponent, Value mod) {
if (exponent->is_integer() && exponent->as_integer()->to_nat_int_t() < 0 && mod)
env->raise("RangeError", "2nd argument not allowed when first argument is negative");
auto powd = pow(env, exponent);
if (!mod)
return powd;
if (!mod->is_integer())
env->raise("TypeError", "2nd argument not allowed unless all arguments are integers");
auto modi = mod->as_integer();
if (modi->to_nat_int_t() == 0)
env->raise("ZeroDivisionError", "cannot divide by zero");
auto powi = powd->as_integer();
if (powi->is_bignum())
return new IntegerObject { powi->to_bigint() % modi->to_bigint() };
if (powi->to_nat_int_t() < 0 || modi->to_nat_int_t() < 0)
return powi->mod(env, mod);
return Value::integer(powi->to_nat_int_t() % modi->to_nat_int_t());
}
Value IntegerObject::cmp(Env *env, Value arg) {
auto is_comparable_with = [](Value arg) -> bool {
return arg.is_fast_integer() || arg.is_fast_float() || arg->is_integer() || arg->is_float();
};
// Check if we might want to coerce the value
if (!is_comparable_with(arg))
arg = Natalie::coerce(env, arg, this, Natalie::CoerceInvalidReturnValueMode::Allow).second;
// Check if compareable
if (!is_comparable_with(arg))
return NilObject::the();
if (lt(env, arg)) {
return Value::integer(-1);
} else if (eq(env, arg)) {
return Value::integer(0);
} else {
return Value::integer(1);
}
}
bool IntegerObject::eq(Env *env, Value other) {
if (other.is_fast_integer())
return m_integer == other.get_fast_integer();
if (other.is_fast_float())
return m_integer == other.get_fast_float();
other.unguard();
if (other->is_float())
return m_integer.to_nat_int_t() == other->as_float()->to_double();
if (!other->is_integer())
other = Natalie::coerce(env, other, this).second;
if (other->is_integer())
return m_integer == other->as_integer()->integer();
return other->send(env, "=="_s, { this })->is_truthy();
}
bool IntegerObject::lt(Env *env, Value other) {
if (other.is_fast_integer())
return m_integer < other.get_fast_integer();
if (other.is_fast_float())
return m_integer < other.get_fast_float();
other.unguard();
if (other->is_float())
return m_integer < other->as_float()->to_double();
if (!other->is_integer())
other = Natalie::coerce(env, other, this).second;
if (other->is_integer())
return m_integer < other->as_integer()->integer();
env->raise("ArgumentError", "comparison of Integer with {} failed", other->inspect_str(env));
}
bool IntegerObject::lte(Env *env, Value other) {
if (other.is_fast_integer())
return m_integer <= other.get_fast_integer();
else if (other.is_fast_float())
return m_integer <= other.get_fast_float();
other.unguard();
if (other->is_float())
return m_integer <= other->as_float()->to_double();
if (!other->is_integer())
other = Natalie::coerce(env, other, this).second;
if (other->is_integer())
return m_integer <= other->as_integer()->integer();
env->raise("ArgumentError", "comparison of Integer with {} failed", other->inspect_str(env));
}
bool IntegerObject::gt(Env *env, Value other) {
if (other.is_fast_integer())
return m_integer > other.get_fast_integer();
if (other.is_fast_float())
return m_integer > other.get_fast_float();
other.unguard();
if (other->is_float())
return m_integer > other->as_float()->to_double();
if (!other->is_integer())
other = Natalie::coerce(env, other, this).second;
if (other->is_integer())
return m_integer > other->as_integer()->integer();
env->raise("ArgumentError", "comparison of Integer with {} failed", other->inspect_str(env));
}
bool IntegerObject::gte(Env *env, Value other) {
if (other.is_fast_integer())
return m_integer >= other.get_fast_integer();
if (other.is_fast_float())
return m_integer >= other.get_fast_float();
other.unguard();
if (other->is_float())
return m_integer >= other->as_float()->to_double();
if (!other->is_integer())
other = Natalie::coerce(env, other, this).second;
if (other->is_integer())
return m_integer >= other->as_integer()->integer();
env->raise("ArgumentError", "comparison of Integer with {} failed", other->inspect_str(env));
}
Value IntegerObject::times(Env *env, Block *block) {
if (!block) {
auto enumerator = send(env, "enum_for"_s, { "times"_s });
enumerator->ivar_set(env, "@size"_s, m_integer < 0 ? Value::integer(0) : this);
return enumerator;
}
if (m_integer <= 0)
return this;
for (Integer i = 0; i < m_integer; ++i) {
Value num = create(i);
Value args[] = { num };
NAT_RUN_BLOCK_AND_POSSIBLY_BREAK(env, block, 1, args, nullptr);
}
return this;
}
Value IntegerObject::bitwise_and(Env *env, Value arg) {
if (arg.is_fast_integer()) {
return create(m_integer & arg.get_fast_integer());
} else if (!arg->is_integer()) {
auto result = Natalie::coerce(env, arg, this);
result.second->assert_type(env, Object::Type::Integer, "Integer");
return result.first.send(env, "&"_s, { result.second });
}
arg.unguard();
arg->assert_type(env, Object::Type::Integer, "Integer");
return create(m_integer & arg->as_integer()->integer());
}
Value IntegerObject::bitwise_or(Env *env, Value arg) {
Integer argument;
if (arg.is_fast_integer()) {
argument = arg.get_fast_integer();
} else if (!arg->is_integer()) {
auto result = Natalie::coerce(env, arg, this);
result.second->assert_type(env, Object::Type::Integer, "Integer");
return result.first.send(env, "|"_s, { result.second });
} else {
arg.unguard();
arg->assert_type(env, Object::Type::Integer, "Integer");
argument = arg->as_integer()->integer();
}
return create(m_integer | argument);
}
Value IntegerObject::bitwise_xor(Env *env, Value arg) {
Integer argument;
if (arg.is_fast_integer()) {
argument = arg.get_fast_integer();
} else if (!arg->is_integer()) {
auto result = Natalie::coerce(env, arg, this);
result.second->assert_type(env, Object::Type::Integer, "Integer");
return result.first.send(env, "^"_s, { result.second });
} else {
arg.unguard();
arg->assert_type(env, Object::Type::Integer, "Integer");
argument = arg->as_integer()->integer();
}
return create(m_integer ^ argument);
}
Value IntegerObject::bit_length(Env *env) {
return create(m_integer.bit_length());
}
Value IntegerObject::left_shift(Env *env, Value arg) {
nat_int_t nat_int;
if (arg.is_fast_integer()) {
nat_int = arg.get_fast_integer();
} else {
auto integer = arg->to_int(env);
if (integer->is_bignum()) {
if (is_negative())
return Value::integer(-1);
else
return Value::integer(0);
}
nat_int = integer->integer().to_nat_int_t();
}
if (nat_int < 0)
return right_shift(env, Value::integer(-nat_int));
return create(m_integer << nat_int);
}
Value IntegerObject::right_shift(Env *env, Value arg) {
nat_int_t nat_int;
if (arg.is_fast_integer()) {
nat_int = arg.get_fast_integer();
} else {
auto integer = arg->to_int(env);
if (integer->is_bignum()) {
if (is_negative())
return Value::integer(-1);
else
return Value::integer(0);
}
nat_int = integer->integer().to_nat_int_t();
}
if (nat_int < 0)
return left_shift(env, Value::integer(-nat_int));
return create(m_integer >> nat_int);
}
Value IntegerObject::pred(Env *env) {
return sub(env, Value::integer(1));
}
Value IntegerObject::size(Env *env) {
// NATFIXME: add Bignum support.
return Value::integer(sizeof(nat_int_t));
}
Value IntegerObject::succ(Env *env) {
return add(env, Value::integer(1));
}
Value IntegerObject::coerce(Env *env, Value arg) {
ArrayObject *ary = new ArrayObject {};
switch (arg->type()) {
case Object::Type::Integer:
ary->push(arg);
ary->push(this);
break;
case Object::Type::String:
ary->push(send(env, "Float"_s, { arg }));
ary->push(send(env, "to_f"_s));
break;
default:
if (!arg->is_nil() && !arg->is_float() && arg->respond_to(env, "to_f"_s)) {
arg = arg.send(env, "to_f"_s);
}
if (arg->is_float()) {
ary->push(arg);
ary->push(send(env, "to_f"_s));
break;
}
env->raise("TypeError", "can't convert {} into Float", arg->inspect_str(env));
}
return ary;
}
Value IntegerObject::ceil(Env *env, Value arg) {
if (arg == nullptr)
return this;
arg->assert_type(env, Object::Type::Integer, "Integer");
auto precision = arg->as_integer()->integer().to_nat_int_t();
if (precision >= 0)
return this;
double f = ::pow(10, precision);
auto result = ::ceil(m_integer.to_nat_int_t() * f) / f;
return Value::integer(result);
}
Value IntegerObject::floor(Env *env, Value arg) {
if (arg == nullptr)
return this;
arg->assert_type(env, Object::Type::Integer, "Integer");
auto precision = arg->as_integer()->integer().to_nat_int_t();
if (precision >= 0)
return this;
double f = ::pow(10, precision);
auto result = ::floor(m_integer.to_nat_int_t() * f) / f;
return Value::integer(result);
}
Value IntegerObject::gcd(Env *env, Value divisor) {
if (divisor.is_fast_integer())
return create(Natalie::gcd(m_integer, divisor.get_fast_integer()));
divisor->assert_type(env, Object::Type::Integer, "Integer");
return create(Natalie::gcd(m_integer, divisor->as_integer()->integer()));
}
Value IntegerObject::abs(Env *env) {
if (m_integer.is_negative())
return create(-m_integer);
return this;
}
Value IntegerObject::chr(Env *env, Value encoding) const {
if (m_integer < 0 || m_integer > (nat_int_t)UINT_MAX)
env->raise("RangeError", "{} out of char range", m_integer.to_string());
else if (is_bignum())
env->raise("RangeError", "bignum out of char range");
if (encoding) {
if (!encoding->is_encoding()) {
encoding->assert_type(env, Type::String, "String");
encoding = EncodingObject::find(env, encoding);
}
} else if (m_integer < 256) {
Value Encoding = GlobalEnv::the()->Object()->const_fetch("Encoding"_s);
if (m_integer <= 127) {
NAT_NOT_YET_IMPLEMENTED();
} else {
encoding = Encoding->const_fetch("BINARY"_s);
}
} else if (EncodingObject::default_internal()) {
encoding = EncodingObject::default_internal();
} else {
env->raise("RangeError", "{} out of char range", m_integer.to_string());
}
auto encoding_obj = encoding->as_encoding();
if (!encoding_obj->in_encoding_codepoint_range(m_integer.to_nat_int_t()))
env->raise("RangeError", "{} out of char range", m_integer.to_string());
if (encoding_obj->invalid_codepoint(m_integer.to_nat_int_t()))
env->raise("RangeError", "invalid codepoint {} in {}", m_integer.to_nat_int_t(), encoding_obj->inspect_str(env));
char c = static_cast<char>(m_integer.to_nat_int_t());
Natalie::String string = " ";
string[0] = c;
return new StringObject { string, encoding_obj->num() };
}
bool IntegerObject::optimized_method(SymbolObject *method_name) {
if (s_optimized_methods.is_empty()) {
// NOTE: No method that ever returns 'this' can be an "optimized" method. Trust me!
s_optimized_methods.set("+"_s);
s_optimized_methods.set("-"_s);
s_optimized_methods.set("*"_s);
s_optimized_methods.set("/"_s);
s_optimized_methods.set("%"_s);
s_optimized_methods.set("**"_s);
s_optimized_methods.set("<=>"_s);
s_optimized_methods.set("=="_s);
s_optimized_methods.set("==="_s);
s_optimized_methods.set("<"_s);
s_optimized_methods.set("<="_s);
s_optimized_methods.set(">"_s);
s_optimized_methods.set(">="_s);
s_optimized_methods.set("==="_s);
s_optimized_methods.set("succ"_s);
s_optimized_methods.set("chr"_s);
s_optimized_methods.set("~"_s);
}
return !!s_optimized_methods.get(method_name);
}
Value IntegerObject::negate(Env *env) {
return create(-m_integer);
}
Value IntegerObject::numerator() {
return this;
}
Value IntegerObject::complement(Env *env) const {
return create(~m_integer);
}
Value IntegerObject::sqrt(Env *env, Value arg) {
Integer argument;
if (arg.is_fast_integer()) {
argument = arg.get_fast_integer();
} else {
arg.unguard();
argument = arg->to_int(env)->integer();
}
if (argument < 0) {
auto domain_error = find_nested_const(env, { "Math"_s, "DomainError"_s });
auto message = new StringObject { "Numerical argument is out of domain - \"isqrt\"" };
auto exception = new ExceptionObject { domain_error->as_class(), message };
env->raise_exception(exception);
}
return create(Natalie::sqrt(argument));
}
Value IntegerObject::round(Env *env, Value ndigits, Value kwargs) {
if (!ndigits)
return this;
int digits = IntegerObject::convert_to_int(env, ndigits);
RoundingMode rounding_mode = rounding_mode_from_kwargs(env, kwargs);
if (digits >= 0)
return this;
auto result = m_integer;
auto dividend = Natalie::pow(Integer(10), -digits);
auto half = dividend / 2;
auto remainder = result.modulo_c(dividend);
auto remainder_abs = Natalie::abs(remainder);
if (remainder_abs < half) {
result -= remainder;
} else if (remainder_abs > half) {
result += dividend - remainder;
} else {
switch (rounding_mode) {
case RoundingMode::Up:
result += remainder;
break;
case RoundingMode::Down:
result -= remainder;
break;
case RoundingMode::Even:
auto digit = result.modulo_c(dividend * 10).div_c(dividend);
if (digit % 2 == 0) {
result -= remainder;
} else {
result += remainder;
}
break;
}
}
return create(result);
}
Value IntegerObject::truncate(Env *env, Value ndigits) {
if (!ndigits)
return this;
int digits = IntegerObject::convert_to_int(env, ndigits);
if (digits >= 0)
return this;
auto result = m_integer;
auto dividend = Natalie::pow(Integer(10), -digits);
auto remainder = result.modulo_c(dividend);
return create(result - remainder);
}
Value IntegerObject::ref(Env *env, Value offset_obj, Value size_obj) {
auto from_offset_and_size = [this, env](Optional<nat_int_t> offset_or_empty, Optional<nat_int_t> size_or_empty = {}) -> Value {
auto offset = offset_or_empty.value_or(0);
if (!size_or_empty.present() && offset < 0)
return Value::integer(0);
auto size = size_or_empty.value_or(1);
Integer result;
if (offset < 0)
result = m_integer << -offset;
else
result = m_integer >> offset;
if (size >= 0)
result = result & ((1 << size) - 1);
if (result != 0 && !offset_or_empty.present())
env->raise("ArgumentError", "The beginless range for Integer#[] results in infinity");
return create(result);
};
if (!size_obj && !offset_obj.is_fast_integer() && offset_obj->is_range()) {
auto range = offset_obj->as_range();
Optional<nat_int_t> begin;
if (range->begin().is_fast_integer()) {
begin = range->begin().get_fast_integer();
} else if (!range->begin()->is_nil()) {
auto begin_obj = range->begin()->to_int(env);
begin = begin_obj->integer().to_nat_int_t();
}
Optional<nat_int_t> end;
if (range->end().is_fast_integer()) {
end = range->end().get_fast_integer();
} else if (!range->end()->is_nil()) {
auto end_obj = range->end()->to_int(env);
end = end_obj->integer().to_nat_int_t();
}
Optional<nat_int_t> size;
if (!end || (begin && end.value() < begin.value()))
size = -1;
else if (end)
size = end.value() - begin.value_or(0) + 1;
return from_offset_and_size(begin, size);
} else {
nat_int_t offset;
if (offset_obj.is_fast_integer()) {
offset = offset_obj.get_fast_integer();
} else {
auto *offset_integer = offset_obj->to_int(env);
if (offset_integer->is_bignum())
return Value::integer(0);
offset = offset_integer->integer().to_nat_int_t();
}
Optional<nat_int_t> size;
if (size_obj) {
if (size_obj.is_fast_integer()) {
size = size_obj.get_fast_integer();
} else {
IntegerObject *size_integer = size_obj->to_int(env);
if (size_integer->is_bignum())
env->raise("RangeError", "shift width too big");
size = size_integer->integer().to_nat_int_t();
}
}
return from_offset_and_size(offset, size);
}
}
nat_int_t IntegerObject::convert_to_nat_int_t(Env *env, Value arg) {
if (arg.is_fast_integer())
return arg.get_fast_integer();
auto integer = arg->to_int(env);
integer->assert_fixnum(env);
return integer->integer().to_nat_int_t();
}
int IntegerObject::convert_to_int(Env *env, Value arg) {
auto result = convert_to_nat_int_t(env, arg);
if (result < std::numeric_limits<int>::min())
env->raise("RangeError", "integer {} too small to convert to `int'");
else if (result > std::numeric_limits<int>::max())
env->raise("RangeError", "integer {} too big to convert to `int'");
return (int)result;
}
}
| 30.963724
| 144
| 0.60171
|
natalie-lang
|
a300f8530681b7011e461d6a2778e77172497a22
| 151
|
cpp
|
C++
|
PanGuEngine/PanGuEngine/Renderer/Component.cpp
|
Litmin/PanGuEngine
|
777286f811c925b489b9d13c0d174e050e284450
|
[
"MIT"
] | 41
|
2020-10-20T06:13:47.000Z
|
2022-03-23T16:12:22.000Z
|
PanGuEngine/PanGuEngine/Renderer/Component.cpp
|
Litmin/PanGuEngine
|
777286f811c925b489b9d13c0d174e050e284450
|
[
"MIT"
] | null | null | null |
PanGuEngine/PanGuEngine/Renderer/Component.cpp
|
Litmin/PanGuEngine
|
777286f811c925b489b9d13c0d174e050e284450
|
[
"MIT"
] | 3
|
2021-04-17T06:34:11.000Z
|
2021-04-27T04:58:43.000Z
|
#include "pch.h"
#include "Component.h"
#include "GameObject.h"
void Component::SetGameObject(GameObject* gameObject)
{
m_GameObject = gameObject;
}
| 16.777778
| 53
| 0.754967
|
Litmin
|
a3030862fe75ca67d8685d7ea97b33824c871e61
| 1,243
|
cpp
|
C++
|
Source/src/Modules/ModuleSceneManager.cpp
|
Erick9Thor/Engine3D
|
32d78f79723fb7c319f79d5e26cdc26481d5cb35
|
[
"MIT"
] | 1
|
2021-11-17T19:20:07.000Z
|
2021-11-17T19:20:07.000Z
|
Source/src/Modules/ModuleSceneManager.cpp
|
Erick9Thor/Engine3D
|
32d78f79723fb7c319f79d5e26cdc26481d5cb35
|
[
"MIT"
] | null | null | null |
Source/src/Modules/ModuleSceneManager.cpp
|
Erick9Thor/Engine3D
|
32d78f79723fb7c319f79d5e26cdc26481d5cb35
|
[
"MIT"
] | null | null | null |
#include "ModuleSceneManager.h"
#include "../Importers/SceneImporter.h"
#include "../Utils/Logger.h"
ModuleSceneManager::ModuleSceneManager() {}
ModuleSceneManager::~ModuleSceneManager() {}
bool ModuleSceneManager::Init()
{
LOG("Creating Empty scene");
// main_scene = new Scene();
main_scene = SceneImporter::LoadScene(ASSETS_FOLDER "/Scenes/lights_delivery.scene");
//LoadModel(ASSETS_FOLDER "\\Models\\BakerHouse.fbx"); //TODO: Remove this when importen will be created
// CreateEmptyScene();
// LoadScene(LIBRARY_SCENE_FOLDER "/survival_shooter.scene");
return true;
}
update_status ModuleSceneManager::Update(const float delta)
{
main_scene->Update();
return UPDATE_CONTINUE;
}
bool ModuleSceneManager::CleanUp()
{
RELEASE(main_scene);
return true;
}
void ModuleSceneManager::LoadModel(const char* model_path)
{
// delete scene_model;
main_scene->LoadFBX(model_path);
}
void ModuleSceneManager::CreateEmptyScene()
{
delete main_scene;
main_scene = new Scene();
}
void ModuleSceneManager::LoadScene(const char* file_path)
{
delete main_scene;
main_scene = SceneImporter::LoadScene(file_path);
}
void ModuleSceneManager::SaveScene(const char* file_path)
{
SceneImporter::SaveScene(main_scene, file_path);
}
| 21.067797
| 105
| 0.761062
|
Erick9Thor
|
a3088a5f88b3b215782720df2b4b9fb8543027f0
| 33,287
|
cpp
|
C++
|
app/bin/miner/xmr-stak/xmrstak/misc/executor.cpp
|
chrisknepper/electron-gui-crypto-miner
|
e154b1f1ea6ce8285c7a682a8dcef90f17a5c8a2
|
[
"MIT"
] | 2
|
2018-01-25T04:29:57.000Z
|
2020-02-13T15:30:55.000Z
|
app/bin/miner/xmr-stak/xmrstak/misc/executor.cpp
|
chrisknepper/electron-gui-crypto-miner
|
e154b1f1ea6ce8285c7a682a8dcef90f17a5c8a2
|
[
"MIT"
] | 1
|
2019-05-26T17:51:57.000Z
|
2019-05-26T17:51:57.000Z
|
app/bin/miner/xmr-stak/xmrstak/misc/executor.cpp
|
chrisknepper/electron-gui-crypto-miner
|
e154b1f1ea6ce8285c7a682a8dcef90f17a5c8a2
|
[
"MIT"
] | 5
|
2018-02-17T11:32:37.000Z
|
2021-02-26T22:26:07.000Z
|
/*
* 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
* 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/>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with OpenSSL (or a modified version of that library), containing parts
* covered by the terms of OpenSSL License and SSLeay License, the licensors
* of this Program grant you additional permission to convey the resulting work.
*
*/
#include "xmrstak/jconf.hpp"
#include "executor.hpp"
#include "xmrstak/net/jpsock.hpp"
#include "telemetry.hpp"
#include "xmrstak/backend/miner_work.hpp"
#include "xmrstak/backend/globalStates.hpp"
#include "xmrstak/backend/backendConnector.hpp"
#include "xmrstak/backend/iBackend.hpp"
#include "xmrstak/jconf.hpp"
#include "xmrstak/misc/console.hpp"
#include "xmrstak/donate-level.hpp"
#include "xmrstak/version.hpp"
#include "xmrstak/http/webdesign.hpp"
#include <thread>
#include <string>
#include <cmath>
#include <algorithm>
#include <functional>
#include <assert.h>
#include <time.h>
#ifdef _WIN32
#define strncasecmp _strnicmp
#endif // _WIN32
executor::executor()
{
}
void executor::push_timed_event(ex_event&& ev, size_t sec)
{
std::unique_lock<std::mutex> lck(timed_event_mutex);
lTimedEvents.emplace_back(std::move(ev), sec_to_ticks(sec));
}
void executor::ex_clock_thd()
{
size_t tick = 0;
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(size_t(iTickTime)));
push_event(ex_event(EV_PERF_TICK));
//Eval pool choice every fourth tick
if((tick++ & 0x03) == 0)
push_event(ex_event(EV_EVAL_POOL_CHOICE));
// Service timed events
std::unique_lock<std::mutex> lck(timed_event_mutex);
std::list<timed_event>::iterator ev = lTimedEvents.begin();
while (ev != lTimedEvents.end())
{
ev->ticks_left--;
if(ev->ticks_left == 0)
{
push_event(std::move(ev->event));
ev = lTimedEvents.erase(ev);
}
else
ev++;
}
lck.unlock();
}
}
bool executor::get_live_pools(std::vector<jpsock*>& eval_pools, bool is_dev)
{
size_t limit = jconf::inst()->GetGiveUpLimit();
size_t wait = jconf::inst()->GetNetRetry();
if(limit == 0 || is_dev) limit = (-1); //No limit = limit of 2^64-1
size_t pool_count = 0;
size_t over_limit = 0;
for(jpsock& pool : pools)
{
if(pool.is_dev_pool() != is_dev)
continue;
// Only eval live pools
size_t num, dtime;
if(pool.get_disconnects(num, dtime))
set_timestamp();
if(dtime == 0 || (dtime >= wait && num <= limit))
eval_pools.emplace_back(&pool);
pool_count++;
if(num > limit)
over_limit++;
}
if(eval_pools.size() == 0)
{
if(!is_dev)
{
if(xmrstak::globalStates::inst().pool_id != invalid_pool_id)
{
printer::inst()->print_msg(L0, "All pools are dead. Idling...");
auto work = xmrstak::miner_work();
xmrstak::pool_data dat;
xmrstak::globalStates::inst().switch_work(work, dat);
}
if(over_limit == pool_count)
{
printer::inst()->print_msg(L0, "All pools are over give up limit. Exitting.");
exit(0);
}
return false;
}
else
return get_live_pools(eval_pools, false);
}
return true;
}
/*
* This event is called by the timer and whenever something relevant happens.
* The job here is to decide if we want to connect, disconnect, or switch jobs (or do nothing)
*/
void executor::eval_pool_choice()
{
std::vector<jpsock*> eval_pools;
eval_pools.reserve(pools.size());
bool dev_time = is_dev_time();
if(!get_live_pools(eval_pools, dev_time))
return;
size_t running = 0;
for(jpsock* pool : eval_pools)
{
if(pool->is_running())
running++;
}
// Special case - if we are without a pool, connect to all find a live pool asap
if(running == 0)
{
if(dev_time)
printer::inst()->print_msg(L1, "Fast-connecting to dev pool ...");
for(jpsock* pool : eval_pools)
{
if(pool->can_connect())
{
if(!dev_time)
printer::inst()->print_msg(L1, "Fast-connecting to %s pool ...", pool->get_pool_addr());
std::string error;
if(!pool->connect(error))
log_socket_error(pool, std::move(error));
}
}
return;
}
std::sort(eval_pools.begin(), eval_pools.end(), [](jpsock* a, jpsock* b) { return b->get_pool_weight(true) < a->get_pool_weight(true); });
jpsock* goal = eval_pools[0];
if(goal->get_pool_id() != xmrstak::globalStates::inst().pool_id)
{
if(!goal->is_running() && goal->can_connect())
{
if(dev_time)
printer::inst()->print_msg(L1, "Connecting to dev pool ...");
else
printer::inst()->print_msg(L1, "Connecting to %s pool ...", goal->get_pool_addr());
std::string error;
if(!goal->connect(error))
log_socket_error(goal, std::move(error));
return;
}
if(goal->is_logged_in())
{
pool_job oPoolJob;
if(!goal->get_current_job(oPoolJob))
{
goal->disconnect();
return;
}
size_t prev_pool_id = current_pool_id;
current_pool_id = goal->get_pool_id();
on_pool_have_job(current_pool_id, oPoolJob);
jpsock* prev_pool = pick_pool_by_id(prev_pool_id);
if(prev_pool == nullptr || (!prev_pool->is_dev_pool() && !goal->is_dev_pool()))
reset_stats();
if(goal->is_dev_pool() && (prev_pool != nullptr && !prev_pool->is_dev_pool()))
last_usr_pool_id = prev_pool_id;
else
last_usr_pool_id = invalid_pool_id;
return;
}
}
else
{
/* All is good - but check if we can do better */
std::sort(eval_pools.begin(), eval_pools.end(), [](jpsock* a, jpsock* b) { return b->get_pool_weight(false) < a->get_pool_weight(false); });
jpsock* goal2 = eval_pools[0];
if(goal->get_pool_id() != goal2->get_pool_id())
{
if(!goal2->is_running() && goal2->can_connect())
{
printer::inst()->print_msg(L1, "Background-connect to %s pool ...", goal2->get_pool_addr());
std::string error;
if(!goal2->connect(error))
log_socket_error(goal2, std::move(error));
return;
}
}
}
if(!dev_time)
{
for(jpsock& pool : pools)
{
if(goal->is_logged_in() && pool.is_logged_in() && pool.get_pool_id() != goal->get_pool_id())
pool.disconnect(true);
if(pool.is_dev_pool() && pool.is_logged_in())
pool.disconnect(true);
}
}
}
void executor::log_socket_error(jpsock* pool, std::string&& sError)
{
std::string pool_name;
pool_name.reserve(128);
pool_name.append("[").append(pool->get_pool_addr()).append("] ");
sError.insert(0, pool_name);
vSocketLog.emplace_back(std::move(sError));
printer::inst()->print_msg(L1, "SOCKET ERROR - %s", vSocketLog.back().msg.c_str());
push_event(ex_event(EV_EVAL_POOL_CHOICE));
}
void executor::log_result_error(std::string&& sError)
{
size_t i = 1, ln = vMineResults.size();
for(; i < ln; i++)
{
if(vMineResults[i].compare(sError))
{
vMineResults[i].increment();
break;
}
}
if(i == ln) //Not found
vMineResults.emplace_back(std::move(sError));
else
sError.clear();
}
void executor::log_result_ok(uint64_t iActualDiff)
{
iPoolHashes += iPoolDiff;
size_t ln = iTopDiff.size() - 1;
if(iActualDiff > iTopDiff[ln])
{
iTopDiff[ln] = iActualDiff;
std::sort(iTopDiff.rbegin(), iTopDiff.rend());
}
vMineResults[0].increment();
}
jpsock* executor::pick_pool_by_id(size_t pool_id)
{
if(pool_id == invalid_pool_id)
return nullptr;
for(jpsock& pool : pools)
if(pool.get_pool_id() == pool_id)
return &pool;
return nullptr;
}
void executor::on_sock_ready(size_t pool_id)
{
jpsock* pool = pick_pool_by_id(pool_id);
if(pool->is_dev_pool())
printer::inst()->print_msg(L1, "Dev pool connected. Logging in...");
else
printer::inst()->print_msg(L1, "Pool %s connected. Logging in...", pool->get_pool_addr());
if(!pool->cmd_login())
{
if(!pool->have_sock_error())
{
log_socket_error(pool, pool->get_call_error());
pool->disconnect();
}
}
}
void executor::on_sock_error(size_t pool_id, std::string&& sError, bool silent)
{
jpsock* pool = pick_pool_by_id(pool_id);
pool->disconnect();
if(pool_id == current_pool_id)
current_pool_id = invalid_pool_id;
if(silent)
return;
if(!pool->is_dev_pool())
log_socket_error(pool, std::move(sError));
else
printer::inst()->print_msg(L1, "Dev pool socket error - mining on user pool...");
}
void executor::on_pool_have_job(size_t pool_id, pool_job& oPoolJob)
{
if(pool_id != current_pool_id)
return;
jpsock* pool = pick_pool_by_id(pool_id);
xmrstak::miner_work oWork(oPoolJob.sJobID, oPoolJob.bWorkBlob, oPoolJob.iWorkLen, oPoolJob.iTarget, pool->is_nicehash(), pool_id);
xmrstak::pool_data dat;
dat.iSavedNonce = oPoolJob.iSavedNonce;
dat.pool_id = pool_id;
xmrstak::globalStates::inst().switch_work(oWork, dat);
if(dat.pool_id != pool_id)
{
jpsock* prev_pool;
if((prev_pool = pick_pool_by_id(dat.pool_id)) != nullptr)
prev_pool->save_nonce(dat.iSavedNonce);
}
if(pool->is_dev_pool())
return;
if(iPoolDiff != pool->get_current_diff())
{
iPoolDiff = pool->get_current_diff();
printer::inst()->print_msg(L2, "Difficulty changed. Now: %llu.", int_port(iPoolDiff));
}
if(dat.pool_id != pool_id)
{
jpsock* prev_pool;
if(dat.pool_id != invalid_pool_id && (prev_pool = pick_pool_by_id(dat.pool_id)) != nullptr)
{
if(prev_pool->is_dev_pool())
printer::inst()->print_msg(L2, "Switching back to user pool.");
else
printer::inst()->print_msg(L2, "Pool switched.");
}
else
printer::inst()->print_msg(L2, "Pool logged in.");
}
else
printer::inst()->print_msg(L3, "New block detected.");
}
void executor::on_miner_result(size_t pool_id, job_result& oResult)
{
jpsock* pool = pick_pool_by_id(pool_id);
bool is_monero = jconf::inst()->IsCurrencyMonero();
if(pool->is_dev_pool())
{
//Ignore errors silently
if(pool->is_running() && pool->is_logged_in())
pool->cmd_submit(oResult.sJobID, oResult.iNonce, oResult.bResult, pvThreads->at(oResult.iThreadId), is_monero);
return;
}
if (!pool->is_running() || !pool->is_logged_in())
{
log_result_error("[NETWORK ERROR]");
return;
}
size_t t_start = get_timestamp_ms();
bool bResult = pool->cmd_submit(oResult.sJobID, oResult.iNonce, oResult.bResult, pvThreads->at(oResult.iThreadId), is_monero);
size_t t_len = get_timestamp_ms() - t_start;
if(t_len > 0xFFFF)
t_len = 0xFFFF;
iPoolCallTimes.push_back((uint16_t)t_len);
if(bResult)
{
uint64_t* targets = (uint64_t*)oResult.bResult;
log_result_ok(jpsock::t64_to_diff(targets[3]));
printer::inst()->print_msg(L3, "Result accepted by the pool.");
}
else
{
if(!pool->have_sock_error())
{
printer::inst()->print_msg(L3, "Result rejected by the pool.");
std::string error = pool->get_call_error();
if(strncasecmp(error.c_str(), "Unauthenticated", 15) == 0)
{
printer::inst()->print_msg(L2, "Your miner was unable to find a share in time. Either the pool difficulty is too high, or the pool timeout is too low.");
pool->disconnect();
}
log_result_error(std::move(error));
}
else
log_result_error("[NETWORK ERROR]");
}
}
#ifndef _WIN32
#include <signal.h>
void disable_sigpipe()
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
if (sigaction(SIGPIPE, &sa, 0) == -1)
printer::inst()->print_msg(L1, "ERROR: Call to sigaction failed!");
}
#else
inline void disable_sigpipe() {}
#endif
void executor::ex_main()
{
disable_sigpipe();
assert(1000 % iTickTime == 0);
xmrstak::miner_work oWork = xmrstak::miner_work();
// \todo collect all backend threads
pvThreads = xmrstak::BackendConnector::thread_starter(oWork);
if(pvThreads->size()==0)
{
printer::inst()->print_msg(L1, "ERROR: No miner backend enabled.");
win_exit();
}
telem = new xmrstak::telemetry(pvThreads->size());
set_timestamp();
size_t pc = jconf::inst()->GetPoolCount();
bool dev_tls = true;
bool already_have_cli_pool = false;
size_t i=0;
for(; i < pc; i++)
{
jconf::pool_cfg cfg;
jconf::inst()->GetPoolConfig(i, cfg);
#ifdef CONF_NO_TLS
if(cfg.tls)
{
printer::inst()->print_msg(L1, "ERROR: No miner was compiled without TLS support.");
win_exit();
}
#endif
if(!cfg.tls) dev_tls = false;
if(!xmrstak::params::inst().poolURL.empty() && xmrstak::params::inst().poolURL == cfg.sPoolAddr)
{
auto& params = xmrstak::params::inst();
already_have_cli_pool = true;
const char* wallet = params.poolUsername.empty() ? cfg.sWalletAddr : params.poolUsername.c_str();
const char* pwd = params.userSetPwd ? params.poolPasswd.c_str() : cfg.sPasswd;
bool nicehash = cfg.nicehash || params.nicehashMode;
pools.emplace_back(i+1, cfg.sPoolAddr, wallet, pwd, 9.9, false, params.poolUseTls, cfg.tls_fingerprint, nicehash);
}
else
pools.emplace_back(i+1, cfg.sPoolAddr, cfg.sWalletAddr, cfg.sPasswd, cfg.weight, false, cfg.tls, cfg.tls_fingerprint, cfg.nicehash);
}
if(!xmrstak::params::inst().poolURL.empty() && !already_have_cli_pool)
{
auto& params = xmrstak::params::inst();
if(params.poolUsername.empty())
{
printer::inst()->print_msg(L1, "ERROR: You didn't specify the username / wallet address for %s", xmrstak::params::inst().poolURL.c_str());
win_exit();
}
pools.emplace_back(i+1, params.poolURL.c_str(), params.poolUsername.c_str(), params.poolPasswd.c_str(), 9.9, false, params.poolUseTls, "", params.nicehashMode);
}
if(jconf::inst()->IsCurrencyMonero())
{
if(dev_tls)
pools.emplace_front(0, "donate.xmr-stak.net:6666", "", "", 0.0, true, true, "", false);
else
pools.emplace_front(0, "donate.xmr-stak.net:3333", "", "", 0.0, true, false, "", false);
}
else
{
if(dev_tls)
pools.emplace_front(0, "donate.xmr-stak.net:7777", "", "", 0.0, true, true, "", true);
else
pools.emplace_front(0, "donate.xmr-stak.net:4444", "", "", 0.0, true, false, "", true);
}
ex_event ev;
std::thread clock_thd(&executor::ex_clock_thd, this);
eval_pool_choice();
// Place the default success result at position 0, it needs to
// be here even if our first result is a failure
vMineResults.emplace_back();
// If the user requested it, start the autohash printer
if(jconf::inst()->GetVerboseLevel() >= 4)
push_timed_event(ex_event(EV_HASHRATE_LOOP), jconf::inst()->GetAutohashTime());
size_t cnt = 0;
while (true)
{
ev = oEventQ.pop();
switch (ev.iName)
{
case EV_SOCK_READY:
on_sock_ready(ev.iPoolId);
break;
case EV_SOCK_ERROR:
on_sock_error(ev.iPoolId, std::move(ev.oSocketError.sSocketError), ev.oSocketError.silent);
break;
case EV_POOL_HAVE_JOB:
on_pool_have_job(ev.iPoolId, ev.oPoolJob);
break;
case EV_MINER_HAVE_RESULT:
on_miner_result(ev.iPoolId, ev.oJobResult);
break;
case EV_EVAL_POOL_CHOICE:
eval_pool_choice();
break;
case EV_GPU_RES_ERROR:
log_result_error(std::string(ev.oGpuError.error_str));
break;
case EV_PERF_TICK:
for (i = 0; i < pvThreads->size(); i++)
telem->push_perf_value(i, pvThreads->at(i)->iHashCount.load(std::memory_order_relaxed),
pvThreads->at(i)->iTimestamp.load(std::memory_order_relaxed));
if((cnt++ & 0xF) == 0) //Every 16 ticks
{
double fHps = 0.0;
double fTelem;
bool normal = true;
for (i = 0; i < pvThreads->size(); i++)
{
fTelem = telem->calc_telemetry_data(10000, i);
if(std::isnormal(fTelem))
{
fHps += fTelem;
}
else
{
normal = false;
break;
}
}
if(normal && fHighestHps < fHps)
fHighestHps = fHps;
}
break;
case EV_USR_HASHRATE:
case EV_USR_RESULTS:
case EV_USR_CONNSTAT:
print_report(ev.iName);
break;
case EV_HTML_HASHRATE:
case EV_HTML_RESULTS:
case EV_HTML_CONNSTAT:
case EV_HTML_JSON:
http_report(ev.iName);
break;
case EV_HASHRATE_LOOP:
print_report(EV_USR_HASHRATE);
push_timed_event(ex_event(EV_HASHRATE_LOOP), jconf::inst()->GetAutohashTime());
break;
case EV_INVALID_VAL:
default:
assert(false);
break;
}
}
}
inline const char* hps_format(double h, char* buf, size_t l)
{
if(std::isnormal(h) || h == 0.0)
{
snprintf(buf, l, " %6.1f", h);
return buf;
}
else
return " (na)";
}
bool executor::motd_filter_console(std::string& motd)
{
if(motd.size() > motd_max_length)
return false;
motd.erase(std::remove_if(motd.begin(), motd.end(), [](int chr)->bool { return !((chr >= 0x20 && chr <= 0x7e) || chr == '\n');}), motd.end());
return motd.size() > 0;
}
bool executor::motd_filter_web(std::string& motd)
{
if(!motd_filter_console(motd))
return false;
std::string tmp;
tmp.reserve(motd.size() + 128);
for(size_t i=0; i < motd.size(); i++)
{
char c = motd[i];
switch(c)
{
case '&':
tmp.append("&");
break;
case '"':
tmp.append(""");
break;
case '\'':
tmp.append("'");
break;
case '<':
tmp.append("<");
break;
case '>':
tmp.append(">");
break;
case '\n':
tmp.append("<br>");
break;
default:
tmp.append(1, c);
break;
}
}
motd = std::move(tmp);
return true;
}
void executor::hashrate_report(std::string& out)
{
out.reserve(2048 + pvThreads->size() * 64);
if(jconf::inst()->PrintMotd())
{
std::string motd;
for(jpsock& pool : pools)
{
motd.empty();
if(pool.get_pool_motd(motd) && motd_filter_console(motd))
{
out.append("Message from ").append(pool.get_pool_addr()).append(":\n");
out.append(motd).append("\n");
out.append("-----------------------------------------------------\n");
}
}
}
char num[32];
double fTotal[3] = { 0.0, 0.0, 0.0};
for( uint32_t b = 0; b < 4u; ++b)
{
std::vector<xmrstak::iBackend*> backEnds;
std::copy_if(pvThreads->begin(), pvThreads->end(), std::back_inserter(backEnds),
[&](xmrstak::iBackend* backend)
{
return backend->backendType == b;
}
);
size_t nthd = backEnds.size();
if(nthd != 0)
{
size_t i;
auto bType = static_cast<xmrstak::iBackend::BackendType>(b);
std::string name(xmrstak::iBackend::getName(bType));
std::transform(name.begin(), name.end(), name.begin(), ::toupper);
out.append("HASHRATE REPORT - ").append(name).append("\n");
out.append("| ID | 10s | 60s | 15m |");
if(nthd != 1)
out.append(" ID | 10s | 60s | 15m |\n");
else
out.append(1, '\n');
for (i = 0; i < nthd; i++)
{
double fHps[3];
uint32_t tid = backEnds[i]->iThreadNo;
fHps[0] = telem->calc_telemetry_data(10000, tid);
fHps[1] = telem->calc_telemetry_data(60000, tid);
fHps[2] = telem->calc_telemetry_data(900000, tid);
snprintf(num, sizeof(num), "| %2u |", (unsigned int)i);
out.append(num);
out.append(hps_format(fHps[0], num, sizeof(num))).append(" |");
out.append(hps_format(fHps[1], num, sizeof(num))).append(" |");
out.append(hps_format(fHps[2], num, sizeof(num))).append(1, ' ');
fTotal[0] += fHps[0];
fTotal[1] += fHps[1];
fTotal[2] += fHps[2];
if((i & 0x1) == 1) //Odd i's
out.append("|\n");
}
if((i & 0x1) == 1) //We had odd number of threads
out.append("|\n");
if(nthd != 1)
out.append("-----------------------------------------------------\n");
else
out.append("---------------------------\n");
}
}
out.append("Totals: ");
out.append(hps_format(fTotal[0], num, sizeof(num)));
out.append(hps_format(fTotal[1], num, sizeof(num)));
out.append(hps_format(fTotal[2], num, sizeof(num)));
out.append(" H/s\nHighest: ");
out.append(hps_format(fHighestHps, num, sizeof(num)));
out.append(" H/s\n");
}
char* time_format(char* buf, size_t len, std::chrono::system_clock::time_point time)
{
time_t ctime = std::chrono::system_clock::to_time_t(time);
tm stime;
/*
* Oh for god's sake... this feels like we are back to the 90's...
* and don't get me started on lack strcpy_s because NIH - use non-standard strlcpy...
* And of course C++ implements unsafe version because... reasons
*/
#ifdef _WIN32
localtime_s(&stime, &ctime);
#else
localtime_r(&ctime, &stime);
#endif // __WIN32
strftime(buf, len, "%F %T", &stime);
return buf;
}
void executor::result_report(std::string& out)
{
char num[128];
char date[32];
out.reserve(1024);
size_t iGoodRes = vMineResults[0].count, iTotalRes = iGoodRes;
size_t ln = vMineResults.size();
for(size_t i=1; i < ln; i++)
iTotalRes += vMineResults[i].count;
out.append("RESULT REPORT\n");
if(iTotalRes == 0)
{
out.append("You haven't found any results yet.\n");
return;
}
double dConnSec;
{
using namespace std::chrono;
dConnSec = (double)duration_cast<seconds>(system_clock::now() - tPoolConnTime).count();
}
snprintf(num, sizeof(num), " (%.1f %%)\n", 100.0 * iGoodRes / iTotalRes);
out.append("Difficulty : ").append(std::to_string(iPoolDiff)).append(1, '\n');
out.append("Good results : ").append(std::to_string(iGoodRes)).append(" / ").
append(std::to_string(iTotalRes)).append(num);
if(iPoolCallTimes.size() != 0)
{
// Here we use iPoolCallTimes since it also gets reset when we disconnect
snprintf(num, sizeof(num), "%.1f sec\n", dConnSec / iPoolCallTimes.size());
out.append("Avg result time : ").append(num);
}
out.append("Pool-side hashes : ").append(std::to_string(iPoolHashes)).append(2, '\n');
out.append("Top 10 best results found:\n");
for(size_t i=0; i < 10; i += 2)
{
snprintf(num, sizeof(num), "| %2llu | %16llu | %2llu | %16llu |\n",
int_port(i), int_port(iTopDiff[i]), int_port(i+1), int_port(iTopDiff[i+1]));
out.append(num);
}
out.append("\nError details:\n");
if(ln > 1)
{
out.append("| Count | Error text | Last seen |\n");
for(size_t i=1; i < ln; i++)
{
snprintf(num, sizeof(num), "| %5llu | %-32.32s | %s |\n", int_port(vMineResults[i].count),
vMineResults[i].msg.c_str(), time_format(date, sizeof(date), vMineResults[i].time));
out.append(num);
}
}
else
out.append("Yay! No errors.\n");
}
void executor::connection_report(std::string& out)
{
char num[128];
char date[32];
out.reserve(512);
jpsock* pool = pick_pool_by_id(current_pool_id);
if(pool != nullptr && pool->is_dev_pool())
pool = pick_pool_by_id(last_usr_pool_id);
out.append("CONNECTION REPORT\n");
out.append("Pool address : ").append(pool != nullptr ? pool->get_pool_addr() : "<not connected>").append(1, '\n');
if(pool != nullptr && pool->is_running() && pool->is_logged_in())
out.append("Connected since : ").append(time_format(date, sizeof(date), tPoolConnTime)).append(1, '\n');
else
out.append("Connected since : <not connected>\n");
size_t n_calls = iPoolCallTimes.size();
if (n_calls > 1)
{
//Not-really-but-good-enough median
std::nth_element(iPoolCallTimes.begin(), iPoolCallTimes.begin() + n_calls/2, iPoolCallTimes.end());
out.append("Pool ping time : ").append(std::to_string(iPoolCallTimes[n_calls/2])).append(" ms\n");
}
else
out.append("Pool ping time : (n/a)\n");
out.append("\nNetwork error log:\n");
size_t ln = vSocketLog.size();
if(ln > 0)
{
out.append("| Date | Error text |\n");
for(size_t i=0; i < ln; i++)
{
snprintf(num, sizeof(num), "| %s | %-54.54s |\n",
time_format(date, sizeof(date), vSocketLog[i].time), vSocketLog[i].msg.c_str());
out.append(num);
}
}
else
out.append("Yay! No errors.\n");
}
void executor::print_report(ex_event_name ev)
{
std::string out;
switch(ev)
{
case EV_USR_HASHRATE:
hashrate_report(out);
break;
case EV_USR_RESULTS:
result_report(out);
break;
case EV_USR_CONNSTAT:
connection_report(out);
break;
default:
assert(false);
break;
}
printer::inst()->print_str(out.c_str());
}
void executor::http_hashrate_report(std::string& out)
{
char num_a[32], num_b[32], num_c[32], num_d[32];
char buffer[4096];
size_t nthd = pvThreads->size();
out.reserve(4096);
snprintf(buffer, sizeof(buffer), sHtmlCommonHeader, "Hashrate Report", ver_html, "Hashrate Report");
out.append(buffer);
bool have_motd = false;
if(jconf::inst()->PrintMotd())
{
std::string motd;
for(jpsock& pool : pools)
{
motd.empty();
if(pool.get_pool_motd(motd) && motd_filter_web(motd))
{
if(!have_motd)
{
out.append(sHtmlMotdBoxStart);
have_motd = true;
}
snprintf(buffer, sizeof(buffer), sHtmlMotdEntry, pool.get_pool_addr(), motd.c_str());
out.append(buffer);
}
}
}
if(have_motd)
out.append(sHtmlMotdBoxEnd);
snprintf(buffer, sizeof(buffer), sHtmlHashrateBodyHigh, (unsigned int)nthd + 3);
out.append(buffer);
double fTotal[3] = { 0.0, 0.0, 0.0};
for(size_t i=0; i < nthd; i++)
{
double fHps[3];
fHps[0] = telem->calc_telemetry_data(10000, i);
fHps[1] = telem->calc_telemetry_data(60000, i);
fHps[2] = telem->calc_telemetry_data(900000, i);
num_a[0] = num_b[0] = num_c[0] ='\0';
hps_format(fHps[0], num_a, sizeof(num_a));
hps_format(fHps[1], num_b, sizeof(num_b));
hps_format(fHps[2], num_c, sizeof(num_c));
fTotal[0] += fHps[0];
fTotal[1] += fHps[1];
fTotal[2] += fHps[2];
snprintf(buffer, sizeof(buffer), sHtmlHashrateTableRow, (unsigned int)i, num_a, num_b, num_c);
out.append(buffer);
}
num_a[0] = num_b[0] = num_c[0] = num_d[0] ='\0';
hps_format(fTotal[0], num_a, sizeof(num_a));
hps_format(fTotal[1], num_b, sizeof(num_b));
hps_format(fTotal[2], num_c, sizeof(num_c));
hps_format(fHighestHps, num_d, sizeof(num_d));
snprintf(buffer, sizeof(buffer), sHtmlHashrateBodyLow, num_a, num_b, num_c, num_d);
out.append(buffer);
}
void executor::http_result_report(std::string& out)
{
char date[128];
char buffer[4096];
out.reserve(4096);
snprintf(buffer, sizeof(buffer), sHtmlCommonHeader, "Result Report", ver_html, "Result Report");
out.append(buffer);
size_t iGoodRes = vMineResults[0].count, iTotalRes = iGoodRes;
size_t ln = vMineResults.size();
for(size_t i=1; i < ln; i++)
iTotalRes += vMineResults[i].count;
double fGoodResPrc = 0.0;
if(iTotalRes > 0)
fGoodResPrc = 100.0 * iGoodRes / iTotalRes;
double fAvgResTime = 0.0;
if(iPoolCallTimes.size() > 0)
{
using namespace std::chrono;
fAvgResTime = ((double)duration_cast<seconds>(system_clock::now() - tPoolConnTime).count())
/ iPoolCallTimes.size();
}
snprintf(buffer, sizeof(buffer), sHtmlResultBodyHigh,
iPoolDiff, iGoodRes, iTotalRes, fGoodResPrc, fAvgResTime, iPoolHashes,
int_port(iTopDiff[0]), int_port(iTopDiff[1]), int_port(iTopDiff[2]), int_port(iTopDiff[3]),
int_port(iTopDiff[4]), int_port(iTopDiff[5]), int_port(iTopDiff[6]), int_port(iTopDiff[7]),
int_port(iTopDiff[8]), int_port(iTopDiff[9]));
out.append(buffer);
for(size_t i=1; i < vMineResults.size(); i++)
{
snprintf(buffer, sizeof(buffer), sHtmlResultTableRow, vMineResults[i].msg.c_str(),
int_port(vMineResults[i].count), time_format(date, sizeof(date), vMineResults[i].time));
out.append(buffer);
}
out.append(sHtmlResultBodyLow);
}
void executor::http_connection_report(std::string& out)
{
char date[128];
char buffer[4096];
out.reserve(4096);
snprintf(buffer, sizeof(buffer), sHtmlCommonHeader, "Connection Report", ver_html, "Connection Report");
out.append(buffer);
jpsock* pool = pick_pool_by_id(current_pool_id);
if(pool != nullptr && pool->is_dev_pool())
pool = pick_pool_by_id(last_usr_pool_id);
const char* cdate = "not connected";
if (pool != nullptr && pool->is_running() && pool->is_logged_in())
cdate = time_format(date, sizeof(date), tPoolConnTime);
size_t n_calls = iPoolCallTimes.size();
unsigned int ping_time = 0;
if (n_calls > 1)
{
//Not-really-but-good-enough median
std::nth_element(iPoolCallTimes.begin(), iPoolCallTimes.begin() + n_calls/2, iPoolCallTimes.end());
ping_time = iPoolCallTimes[n_calls/2];
}
snprintf(buffer, sizeof(buffer), sHtmlConnectionBodyHigh,
pool != nullptr ? pool->get_pool_addr() : "not connected",
cdate, ping_time);
out.append(buffer);
for(size_t i=0; i < vSocketLog.size(); i++)
{
snprintf(buffer, sizeof(buffer), sHtmlConnectionTableRow,
time_format(date, sizeof(date), vSocketLog[i].time), vSocketLog[i].msg.c_str());
out.append(buffer);
}
out.append(sHtmlConnectionBodyLow);
}
inline const char* hps_format_json(double h, char* buf, size_t l)
{
if(std::isnormal(h) || h == 0.0)
{
snprintf(buf, l, "%.1f", h);
return buf;
}
else
return "null";
}
void executor::http_json_report(std::string& out)
{
const char *a, *b, *c;
char num_a[32], num_b[32], num_c[32];
char hr_buffer[64];
std::string hr_thds, res_error, cn_error;
size_t nthd = pvThreads->size();
double fTotal[3] = { 0.0, 0.0, 0.0};
hr_thds.reserve(nthd * 32);
for(size_t i=0; i < nthd; i++)
{
if(i != 0) hr_thds.append(1, ',');
double fHps[3];
fHps[0] = telem->calc_telemetry_data(10000, i);
fHps[1] = telem->calc_telemetry_data(60000, i);
fHps[2] = telem->calc_telemetry_data(900000, i);
fTotal[0] += fHps[0];
fTotal[1] += fHps[1];
fTotal[2] += fHps[2];
a = hps_format_json(fHps[0], num_a, sizeof(num_a));
b = hps_format_json(fHps[1], num_b, sizeof(num_b));
c = hps_format_json(fHps[2], num_c, sizeof(num_c));
snprintf(hr_buffer, sizeof(hr_buffer), sJsonApiThdHashrate, a, b, c);
hr_thds.append(hr_buffer);
}
a = hps_format_json(fTotal[0], num_a, sizeof(num_a));
b = hps_format_json(fTotal[1], num_b, sizeof(num_b));
c = hps_format_json(fTotal[2], num_c, sizeof(num_c));
snprintf(hr_buffer, sizeof(hr_buffer), sJsonApiThdHashrate, a, b, c);
a = hps_format_json(fHighestHps, num_a, sizeof(num_a));
size_t iGoodRes = vMineResults[0].count, iTotalRes = iGoodRes;
size_t ln = vMineResults.size();
for(size_t i=1; i < ln; i++)
iTotalRes += vMineResults[i].count;
jpsock* pool = pick_pool_by_id(current_pool_id);
if(pool != nullptr && pool->is_dev_pool())
pool = pick_pool_by_id(last_usr_pool_id);
size_t iConnSec = 0;
if(pool != nullptr && pool->is_running() && pool->is_logged_in())
{
using namespace std::chrono;
iConnSec = duration_cast<seconds>(system_clock::now() - tPoolConnTime).count();
}
double fAvgResTime = 0.0;
if(iPoolCallTimes.size() > 0)
fAvgResTime = double(iConnSec) / iPoolCallTimes.size();
char buffer[2048];
res_error.reserve((vMineResults.size() - 1) * 128);
for(size_t i=1; i < vMineResults.size(); i++)
{
using namespace std::chrono;
if(i != 1) res_error.append(1, ',');
snprintf(buffer, sizeof(buffer), sJsonApiResultError, int_port(vMineResults[i].count),
int_port(duration_cast<seconds>(vMineResults[i].time.time_since_epoch()).count()),
vMineResults[i].msg.c_str());
res_error.append(buffer);
}
size_t n_calls = iPoolCallTimes.size();
size_t iPoolPing = 0;
if (n_calls > 1)
{
//Not-really-but-good-enough median
std::nth_element(iPoolCallTimes.begin(), iPoolCallTimes.begin() + n_calls/2, iPoolCallTimes.end());
iPoolPing = iPoolCallTimes[n_calls/2];
}
cn_error.reserve(vSocketLog.size() * 256);
for(size_t i=0; i < vSocketLog.size(); i++)
{
using namespace std::chrono;
if(i != 0) cn_error.append(1, ',');
snprintf(buffer, sizeof(buffer), sJsonApiConnectionError,
int_port(duration_cast<seconds>(vMineResults[i].time.time_since_epoch()).count()),
vSocketLog[i].msg.c_str());
cn_error.append(buffer);
}
size_t bb_size = 2048 + hr_thds.size() + res_error.size() + cn_error.size();
std::unique_ptr<char[]> bigbuf( new char[ bb_size ] );
int bb_len = snprintf(bigbuf.get(), bb_size, sJsonApiFormat,
get_version_str().c_str(), hr_thds.c_str(), hr_buffer, a,
int_port(iPoolDiff), int_port(iGoodRes), int_port(iTotalRes), fAvgResTime, int_port(iPoolHashes),
int_port(iTopDiff[0]), int_port(iTopDiff[1]), int_port(iTopDiff[2]), int_port(iTopDiff[3]), int_port(iTopDiff[4]),
int_port(iTopDiff[5]), int_port(iTopDiff[6]), int_port(iTopDiff[7]), int_port(iTopDiff[8]), int_port(iTopDiff[9]),
res_error.c_str(), pool != nullptr ? pool->get_pool_addr() : "not connected", int_port(iConnSec), int_port(iPoolPing), cn_error.c_str());
out = std::string(bigbuf.get(), bigbuf.get() + bb_len);
}
void executor::http_report(ex_event_name ev)
{
assert(pHttpString != nullptr);
switch(ev)
{
case EV_HTML_HASHRATE:
http_hashrate_report(*pHttpString);
break;
case EV_HTML_RESULTS:
http_result_report(*pHttpString);
break;
case EV_HTML_CONNSTAT:
http_connection_report(*pHttpString);
break;
case EV_HTML_JSON:
http_json_report(*pHttpString);
break;
default:
assert(false);
break;
}
httpReady.set_value();
}
void executor::get_http_report(ex_event_name ev_id, std::string& data)
{
std::lock_guard<std::mutex> lck(httpMutex);
assert(pHttpString == nullptr);
assert(ev_id == EV_HTML_HASHRATE || ev_id == EV_HTML_RESULTS
|| ev_id == EV_HTML_CONNSTAT || ev_id == EV_HTML_JSON);
pHttpString = &data;
httpReady = std::promise<void>();
std::future<void> ready = httpReady.get_future();
push_event(ex_event(ev_id));
ready.wait();
pHttpString = nullptr;
}
| 25.985168
| 162
| 0.665245
|
chrisknepper
|
a30a9ce13359aa219e2aa5edf31339eda28e5ace
| 2,245
|
cpp
|
C++
|
Povox/src/Povox/Core/Application.cpp
|
PowerOfNames/PonX
|
cac2c67168857409b40f9f76e9570868668370fd
|
[
"Apache-2.0"
] | null | null | null |
Povox/src/Povox/Core/Application.cpp
|
PowerOfNames/PonX
|
cac2c67168857409b40f9f76e9570868668370fd
|
[
"Apache-2.0"
] | null | null | null |
Povox/src/Povox/Core/Application.cpp
|
PowerOfNames/PonX
|
cac2c67168857409b40f9f76e9570868668370fd
|
[
"Apache-2.0"
] | null | null | null |
#include "pxpch.h"
#include "Povox/Core/Application.h"
#include "Povox/Core/Log.h"
#include "Povox/Core/Input.h"
#include "Povox/Renderer/Renderer.h"
#include "Povox/Renderer/VoxelRenderer.h"
#include "Povox/Core/Time.h"
namespace Povox {
Application* Application::s_Instance = nullptr;
Application::Application()
{
PX_PROFILE_FUNCTION();
PX_CORE_ASSERT(!s_Instance, "Application already exists!");
s_Instance = this;
m_Window = Window::Create();
m_Window->SetEventCallback(PX_BIND_EVENT_FN(Application::OnEvent));
m_ImGuiLayer = new ImGuiLayer();
PushOverlay(m_ImGuiLayer);
}
Application::~Application()
{
}
void Application::PushLayer(Layer* layer)
{
PX_PROFILE_FUNCTION();
m_Layerstack.PushLayer(layer);
layer->OnAttach();
}
void Application::PushOverlay(Layer* overlay)
{
PX_PROFILE_FUNCTION();
m_Layerstack.PushOverlay(overlay);
overlay->OnAttach();
}
void Application::OnEvent(Event& e)
{
PX_PROFILE_FUNCTION();
EventDispatcher dispatcher(e);
dispatcher.Dispatch<WindowCloseEvent>(PX_BIND_EVENT_FN(Application::OnWindowClose));
dispatcher.Dispatch<WindowResizeEvent>(PX_BIND_EVENT_FN(Application::OnWindowResize));
for (auto it = m_Layerstack.rbegin(); it != m_Layerstack.rend(); ++it)
{
(*it)->OnEvent(e);
if (e.Handled)
break;
}
}
void Application::Run()
{
PX_PROFILE_FUNCTION();
while (m_Running)
{
MyTimestep time(&m_DeltaTime);
if (!m_Minimized)
{
for (Layer* layer : m_Layerstack)
{
layer->OnUpdate(m_DeltaTime);
}
}
// To be executed on the Render thread
m_ImGuiLayer->Begin();
for (Layer* layer : m_Layerstack)
{
layer->OnImGuiRender();
}
m_ImGuiLayer->End();
m_Window->OnUpdate(m_DeltaTime);
}
}
bool Application::OnWindowClose(WindowCloseEvent& e)
{
PX_PROFILE_FUNCTION();
m_Running = false;
return true;
}
bool Application::OnWindowResize(WindowResizeEvent& e)
{
PX_PROFILE_FUNCTION();
if (e.GetWidth() == 0 || e.GetHeight() == 0)
{
m_Minimized = true;
return false;
}
m_Minimized = false;
Renderer::OnWindowResize(e.GetWidth(), e.GetHeight());
VoxelRenderer::OnWindowResize(e.GetWidth(), e.GetHeight());
return false;
}
}
| 17.677165
| 88
| 0.688641
|
PowerOfNames
|
a30e12080f569961f7373a9c7fdb69677d5d122b
| 2,146
|
cpp
|
C++
|
libs/system/src/crc.cpp
|
skair39/mrpt
|
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
|
[
"BSD-3-Clause"
] | 2
|
2019-02-20T02:36:05.000Z
|
2019-02-20T02:46:51.000Z
|
libs/system/src/crc.cpp
|
skair39/mrpt
|
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
|
[
"BSD-3-Clause"
] | null | null | null |
libs/system/src/crc.cpp
|
skair39/mrpt
|
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
|
[
"BSD-3-Clause"
] | null | null | null |
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "system-precomp.h" // Precompiled headers
#include <mrpt/system/crc.h>
#include <mrpt/core/exceptions.h>
uint16_t mrpt::system::compute_CRC16(
const std::vector<uint8_t>& data, const uint16_t gen_pol)
{
ASSERT_(!data.empty());
return compute_CRC16(&data[0], data.size(), gen_pol);
}
uint32_t mrpt::system::compute_CRC32(
const std::vector<uint8_t>& data, const uint32_t gen_pol)
{
ASSERT_(!data.empty());
return compute_CRC32(&data[0], data.size(), gen_pol);
}
uint16_t mrpt::system::compute_CRC16(
const uint8_t* data, const size_t len_, const uint16_t gen_pol)
{
uint16_t uCrc16;
uint8_t abData[2];
size_t len = len_;
uCrc16 = 0;
abData[0] = 0;
while (len--)
{
abData[1] = abData[0];
abData[0] = *data++;
if (uCrc16 & 0x8000)
{
uCrc16 = (uCrc16 & 0x7fff) << 1;
uCrc16 ^= gen_pol;
}
else
{
uCrc16 <<= 1;
}
uCrc16 ^= (abData[0] | (abData[1] << 8));
}
return uCrc16;
}
unsigned long CRC32Value(int i, const uint32_t CRC32_POLYNOMIAL)
{
unsigned long ulCRC = i;
for (int j = 8; j > 0; j--)
{
if (ulCRC & 1)
ulCRC = (ulCRC >> 1) ^ CRC32_POLYNOMIAL;
else
ulCRC >>= 1;
}
return ulCRC;
}
uint32_t mrpt::system::compute_CRC32(
const uint8_t* data, const size_t len_, const uint32_t gen_pol)
{
size_t len = len_;
unsigned long ulCRC = 0;
while (len-- != 0)
{
unsigned long ulTemp1 = (ulCRC >> 8) & 0x00FFFFFFL;
unsigned long ulTemp2 =
CRC32Value(((int)ulCRC ^ *data++) & 0xff, gen_pol);
ulCRC = ulTemp1 ^ ulTemp2;
}
return ulCRC;
}
| 24.953488
| 80
| 0.553122
|
skair39
|
a30e7225628fd1e8a447dde0aede0a3487632dca
| 12,025
|
cpp
|
C++
|
src/filters/transform/Mpeg2DecFilter/mc_sse2.cpp
|
chinajeffery/MPC-BE--1.2.3
|
2229fde5535f565ba4a496a7f73267bd2c1ad338
|
[
"MIT"
] | null | null | null |
src/filters/transform/Mpeg2DecFilter/mc_sse2.cpp
|
chinajeffery/MPC-BE--1.2.3
|
2229fde5535f565ba4a496a7f73267bd2c1ad338
|
[
"MIT"
] | 1
|
2019-11-14T04:18:32.000Z
|
2019-11-14T04:18:32.000Z
|
src/filters/transform/Mpeg2DecFilter/mc_sse2.cpp
|
chinajeffery/MPC-BE--1.2.3
|
2229fde5535f565ba4a496a7f73267bd2c1ad338
|
[
"MIT"
] | null | null | null |
/*
* $Id: mc_sse2.cpp 1775 2013-01-05 14:19:34Z szl $
*
* (C) 2003-2006 Gabest
* (C) 2006-2013 see Authors.txt
*
* This file is part of MPC-BE.
*
* MPC-BE 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.
*
* MPC-BE 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/>.
*
*/
// Based on Intel's AP-942
#include "stdafx.h"
#include <inttypes.h>
#include "libmpeg2.h"
#include "attributes.h"
#include "../../../DSUtil/simd.h"
static const __m128i const_1_16_bytes=_mm_set1_epi16(1);
static void MC_put_o_16_sse2(uint8_t* ecx, const uint8_t* edx, const int eax, int esi)
{
const int edi= eax+eax;
const int ebx= edi+eax;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
__m128i xmm0,xmm1,xmm2,xmm3;
movdqu (xmm0, edx );
movdqu (xmm1, edx+eax);
movdqu (xmm2, edx+edi);
movdqu (xmm3, edx+ebx);
movdqa (ecx, xmm0 );
movdqa (ecx+eax, xmm1 );
movdqa (ecx+edi, xmm2 );
movdqa (ecx+ebx, xmm3 );
}
}
static void MC_put_o_8_sse2(uint8_t* ecx, const uint8_t* edx, const int eax, int esi)
{
const int edi= eax+eax;
const int ebx= edi+eax;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
__m128d xmm0,xmm1,xmm2,xmm3;
movlpd (xmm0, edx);
movlpd (xmm1, edx+eax);
movlpd (xmm2, edx+edi);
movlpd (xmm3, edx+ebx);
movlpd (ecx, xmm0);
movlpd (ecx+eax, xmm1 );
movlpd (ecx+edi, xmm2);
movlpd (ecx+ebx, xmm3 );
}
}
static void MC_put_x_16_sse2(uint8_t* ecx, const uint8_t* edx, const int eax, int esi)
{
const int edi= eax+eax;
const int ebx= edi+eax;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
__m128i xmm0,xmm1,xmm2,xmm3,xmm4,xmm5,xmm6,xmm7;
movdqu (xmm0, edx);
movdqu (xmm1, edx+1);
movdqu (xmm2, edx+eax);
movdqu (xmm3, edx+eax+1);
movdqu (xmm4, edx+edi);
movdqu( xmm5, edx+edi+1);
movdqu( xmm6, edx+ebx );
movdqu( xmm7, edx+ebx+1 );
pavgb (xmm0, xmm1);
pavgb (xmm2, xmm3);
pavgb (xmm4, xmm5);
pavgb (xmm6, xmm7);
movdqa (ecx, xmm0);
movdqa (ecx+eax, xmm2);
movdqa (ecx+edi, xmm4);
movdqa (ecx+ebx, xmm6);
}
}
static void MC_put_x_8_sse2(uint8_t* ecx, const uint8_t* edx, const int eax, int esi)
{
const int edi= eax+eax;
const int ebx= edi+eax;
__m128i xmm0,xmm1,xmm2,xmm3;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
movlpd (xmm0, edx);
movlpd (xmm1, edx+1);
movhpd (xmm0, edx+eax);
movhpd (xmm1, edx+eax+1);
movlpd (xmm2, edx+edi);
movlpd (xmm3, edx+edi+1);
movhpd (xmm2, edx+ebx);
movhpd (xmm3, edx+ebx+1);
pavgb (xmm0, xmm1);
pavgb (xmm2, xmm3);
movlpd (ecx, xmm0);
movhpd (ecx+eax, xmm0);
movlpd (ecx+edi, xmm2);
movhpd (ecx+ebx, xmm2);
}
}
static void MC_put_y_16_sse2(uint8_t* ecx, const uint8_t* edx, const int eax, int esi)
{
const int edi= eax+eax;
const int ebx= edi+eax;
__m128i xmm0;
movdqu (xmm0, edx);
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
__m128i xmm1,xmm2,xmm3,xmm4;
movdqu (xmm1, edx+eax);
movdqu (xmm2, edx+edi );
movdqu (xmm3, edx+ebx );
movdqu (xmm4, edx+edi*2 );
pavgb (xmm0, xmm1 );
pavgb (xmm1, xmm2 );
pavgb (xmm2, xmm3 );
pavgb (xmm3, xmm4 );
movdqa (ecx, xmm0 );
movdqa (ecx+eax, xmm1 );
movdqa (ecx+edi, xmm2 );
movdqa (ecx+ebx, xmm3 );
movdqa (xmm0, xmm4 );
}
}
static void MC_put_y_8_sse2(uint8_t* ecx, const uint8_t* edx, const int eax, int esi)
{
const int edi= eax+eax;
const int ebx= edi+eax;
__m128i xmm0;
movlpd (xmm0, edx);
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
__m128i xmm1,xmm2,xmm3,xmm4;
movlpd (xmm1, edx+eax );
movlpd (xmm2, edx+edi );
movlpd (xmm3, edx+ebx );
movlpd (xmm4, edx+edi*2 );
pavgb (xmm0, xmm1 );
pavgb (xmm1, xmm2);
pavgb (xmm2, xmm3 );
pavgb (xmm3, xmm4 );
movlpd (ecx, xmm0 );
movlpd (ecx+eax, xmm1 );
movlpd (ecx+edi, xmm2 );
movlpd (ecx+ebx, xmm3 );
movdqa (xmm0, xmm4 );
}
}
static void MC_put_xy_16_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref ;
uint8_t *ecx= dest;
int eax= stride;
int esi= height;
int edi= eax+eax;
__m128i xmm7,xmm0,xmm1,xmm4,xmm5,xmm2,xmm3;
movdqa (xmm7, const_1_16_bytes );
movdqu (xmm0, edx );
movdqu (xmm1, edx+1 );
for (; esi; edx+= edi,ecx+= edi,esi-= 2) {
movdqu (xmm2, edx+eax );
movdqu (xmm3, edx+eax+1 );
movdqu (xmm4, edx+edi );
movdqu (xmm5, edx+edi+1 );
pavgb (xmm0, xmm1 );
pavgb (xmm2, xmm3 );
movdqa( xmm1, xmm5 );
pavgb (xmm5, xmm4 );
psubusb( xmm2, xmm7 );
pavgb (xmm0, xmm2 );
pavgb (xmm2, xmm5);
movdqa (ecx, xmm0);
movdqa (xmm0, xmm4);
movdqa (ecx+eax, xmm2);
}
}
static void MC_put_xy_8_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int eax= stride;
int esi= height;
int edi= eax+eax;
__m128i xmm7,xmm0,xmm2,xmm1,xmm3,xmm4,xmm5;
movdqa (xmm7, const_1_16_bytes);
movlpd (xmm0, edx);
movlpd (xmm1, edx+1);
for (; esi; edx+= edi,ecx+= edi,esi-= 2) {
movlpd (xmm2, edx+eax);
movlpd (xmm3, edx+eax+1);
movlpd (xmm4, edx+edi);
movlpd (xmm5, edx+edi+1);
pavgb (xmm0, xmm1 );
pavgb (xmm2, xmm3 );
movdqa( xmm1, xmm5 );
pavgb (xmm5, xmm4 );
psubusb( xmm2, xmm7 );
pavgb (xmm0, xmm2 );
pavgb (xmm2, xmm5);
movlpd (ecx, xmm0);
movdqa (xmm0, xmm4);
movlpd (ecx+eax, xmm2);
}
}
static void MC_avg_o_16_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
int ebx= edi+eax;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
__m128i xmm0,xmm1,xmm2,xmm3;
movdqu (xmm0, edx);
movdqu (xmm1, edx+eax );
movdqu (xmm2, edx+edi);
movdqu (xmm3, edx+ebx );
pavgb (xmm0, ecx);
pavgb (xmm1, ecx+eax);
pavgb (xmm2, ecx+edi);
pavgb (xmm3, ecx+ebx);
movdqa (ecx, xmm0);
movdqa (ecx+eax, xmm1 );
movdqa (ecx+edi, xmm2);
movdqa (ecx+ebx, xmm3 );
}
}
static void MC_avg_o_8_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
int ebx= edi+eax;
__m128i xmm0,xmm1,xmm2,xmm3;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
movlpd (xmm0, edx);
movhpd (xmm0, edx+eax );
movlpd (xmm2, edx+edi);
movhpd (xmm2, edx+ebx );
movlpd (xmm1, ecx);
movhpd (xmm1, ecx+eax);
movlpd (xmm3, ecx+edi);
movhpd (xmm3, ecx+ebx);
pavgb (xmm0, xmm1);
pavgb (xmm2, xmm3);
movlpd (ecx, xmm0);
movhpd (ecx+eax, xmm0);
movlpd (ecx+edi, xmm2);
movhpd (ecx+ebx, xmm2);
}
}
static void MC_avg_x_16_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
int ebx= edi+eax;
__m128i xmm0,xmm1,xmm2,xmm3,xmm4,xmm5,xmm6,xmm7;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
movdqu (xmm0, edx);
movdqu (xmm1, edx+1);
movdqu (xmm2, edx+eax);
movdqu (xmm3, edx+eax+1);
movdqu (xmm4, edx+edi);
movdqu (xmm5, edx+edi+1);
movdqu (xmm6, edx+ebx);
movdqu (xmm7, edx+ebx+1);
pavgb (xmm0, xmm1);
pavgb (xmm2, xmm3);
pavgb (xmm4, xmm5);
pavgb (xmm6, xmm7);
pavgb (xmm0, ecx);
pavgb (xmm2, ecx+eax);
pavgb (xmm4, ecx+edi);
pavgb (xmm6, ecx+ebx);
movdqa (ecx, xmm0);
movdqa (ecx+eax, xmm2);
movdqa (ecx+edi, xmm4);
movdqa (ecx+ebx, xmm6);
}
}
static void MC_avg_x_8_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
int ebx= edi+eax;
__m128i xmm0,xmm1,xmm2,xmm3,xmm4,xmm5;
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
movlpd (xmm0, edx);
movlpd (xmm1, edx+1);
movhpd (xmm0, edx+eax);
movhpd (xmm1, edx+eax+1);
movlpd (xmm2, edx+edi);
movlpd (xmm3, edx+edi+1);
movhpd (xmm2, edx+ebx);
movhpd (xmm3, edx+ebx+1);
movlpd (xmm4, ecx);
movhpd (xmm4, ecx+eax);
movlpd (xmm5, ecx+edi);
movhpd (xmm5, ecx+ebx);
pavgb (xmm0, xmm1);
pavgb (xmm2, xmm3);
pavgb (xmm0, xmm4);
pavgb (xmm2, xmm5);
movlpd (ecx, xmm0);
movhpd (ecx+eax, xmm0);
movlpd (ecx+edi, xmm2);
movhpd (ecx+ebx, xmm2);
}
}
static void MC_avg_y_16_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
int ebx= edi+eax;
__m128i xmm0,xmm1,xmm2,xmm3,xmm4;
movdqu (xmm0,edx);
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
movdqu (xmm1, edx+eax );
movdqu (xmm2, edx+edi );
movdqu (xmm3, edx+ebx );
movdqu (xmm4, edx+edi*2 );
pavgb (xmm0, xmm1 );
pavgb (xmm1, xmm2 );
pavgb (xmm2, xmm3 );
pavgb (xmm3, xmm4 );
pavgb (xmm0, ecx);
pavgb (xmm1, ecx+eax );
pavgb (xmm2, ecx+edi);
pavgb (xmm3, ecx+ebx );
movdqa (ecx, xmm0 );
movdqa (ecx+eax, xmm1 );
movdqa (ecx+edi, xmm2 );
movdqa (ecx+ebx, xmm3 );
movdqa (xmm0, xmm4 );
}
}
static void MC_avg_y_8_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
int ebx= edi+eax;
__m128i xmm0,xmm1,xmm2,xmm3,xmm4,xmm5;
movhpd (xmm0, edx );
movlpd (xmm0, edx+eax );
for (; esi; edx+=edi*2,ecx+=edi*2,esi-=4) {
movlhps (xmm1, xmm0);
movlpd (xmm1, edx+edi );
movlhps (xmm2, xmm1);
movlpd (xmm2, edx+ebx );
movlhps (xmm3, xmm2);
movlpd (xmm3, edx+edi*2 );
movhpd (xmm4, ecx );
movlpd (xmm4, ecx+eax );
movhpd (xmm5, ecx+edi );
movlpd (xmm5, ecx+ebx );
pavgb (xmm0, xmm1 );
pavgb (xmm2, xmm3);
pavgb (xmm0, xmm4);
pavgb (xmm2, xmm5);
movhpd (ecx, xmm0 );
movlpd (ecx+eax, xmm0 );
movhpd (ecx+edi, xmm2 );
movlpd (ecx+ebx, xmm2);
movdqa (xmm0, xmm3 );
}
}
static void MC_avg_xy_16_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
__m128i xmm7,xmm0,xmm1,xmm2,xmm3,xmm4,xmm5;
movdqa (xmm7, const_1_16_bytes );
movdqu (xmm0, edx );
movdqu (xmm1, edx+1 );
for (; esi; edx+=edi,ecx+=edi,esi-=2) {
movdqu (xmm2, edx+eax );
movdqu (xmm3, edx+eax+1 );
movdqu (xmm4, edx+edi );
movdqu (xmm5, edx+edi+1 );
pavgb (xmm0, xmm1 );
pavgb (xmm2, xmm3 );
movdqa (xmm1, xmm5 );
pavgb (xmm5, xmm4 );
psubusb (xmm2, xmm7 );
pavgb (xmm0, xmm2 );
pavgb (xmm2, xmm5);
pavgb (xmm0, ecx );
pavgb (xmm2, ecx+eax);
movdqa (ecx, xmm0);
movdqa (xmm0, xmm4);
movdqa (ecx+eax, xmm2);
}
}
static void MC_avg_xy_8_sse2(uint8_t* dest, const uint8_t* ref, const int stride, int height)
{
const uint8_t *edx= ref;
uint8_t *ecx= dest;
int esi= height;
int eax= stride;
int edi= eax+eax;
__m128i xmm7,xmm0,xmm2,xmm1,xmm3,xmm4;
movdqa (xmm7, const_1_16_bytes );
movhpd (xmm0, edx );
movlpd (xmm0, edx+eax );
movhpd (xmm2, edx+1 );
movlpd (xmm2, edx+eax+1 );
for (; esi; edx+=edi,ecx+=edi,esi-=2) {
movhpd (xmm1, edx+eax );
movlpd (xmm1, edx+edi );
movhpd (xmm3, edx+eax+1 );
movlpd (xmm3, edx+edi+1 );
pavgb (xmm0, xmm1 );
pavgb (xmm2, xmm3 );
psubusb( xmm0, xmm7 );
pavgb (xmm0, xmm2 );
movhpd( xmm4, ecx);
movlpd( xmm4, ecx+eax);
pavgb (xmm0, xmm4 );
movhpd (ecx, xmm0 );
movlpd (ecx+eax, xmm0 );
movdqa (xmm0, xmm1 );
movdqa (xmm2, xmm3 );
}
}
mpeg2_mc_t mpeg2_mc_sse2 = {
{
MC_put_o_16_sse2, MC_put_x_16_sse2, MC_put_y_16_sse2, MC_put_xy_16_sse2,
MC_put_o_8_sse2, MC_put_x_8_sse2, MC_put_y_8_sse2, MC_put_xy_8_sse2
},
{
MC_avg_o_16_sse2, MC_avg_x_16_sse2, MC_avg_y_16_sse2, MC_avg_xy_16_sse2,
MC_avg_o_8_sse2, MC_avg_x_8_sse2, MC_avg_y_8_sse2, MC_avg_xy_8_sse2
}
};
| 24.793814
| 94
| 0.642412
|
chinajeffery
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.